file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
pkg/cmd/get/inventory/datastores.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListDatastoresWithInsecure queries the provider's datastore inventory with optional insecure TLS skip verification func ListDatastoresWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listDatastoresOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listDatastoresOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listDatastoresOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify datastore support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "vsphere": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "TYPE", JSONPath: "type"}, {DisplayName: "CAPACITY", JSONPath: "capacityFormatted"}, {DisplayName: "FREE", JSONPath: "freeSpaceFormatted"}, {DisplayName: "ACCESSIBLE", JSONPath: "accessible"}, {DisplayName: "REVISION", JSONPath: "revision"}, } default: return fmt.Errorf("provider type '%s' does not support datastore inventory", providerType) } // Fetch datastores inventory from the provider based on provider type var data interface{} switch providerType { case "vsphere": data, err = providerClient.GetDatastores(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support datastore inventory", providerType) } if err != nil { return fmt.Errorf("failed to fetch datastore inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for datastore inventory") } // Convert to expected format and add calculated fields datastores := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { datastore, ok := item.(map[string]interface{}) if !ok { continue } // Add human-readable capacity formatting if capacity, exists := datastore["capacity"]; exists { if capacityFloat, ok := capacity.(float64); ok { datastore["capacityFormatted"] = humanizeBytes(capacityFloat) } } // Add human-readable free space formatting if freeSpace, exists := datastore["freeSpace"]; exists { if freeSpaceFloat, ok := freeSpace.(float64); ok { datastore["freeSpaceFormatted"] = humanizeBytes(freeSpaceFloat) } } datastores = append(datastores, datastore) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter filteredData, err := querypkg.ApplyQueryInterface(datastores, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } // Convert back to []map[string]interface{} if convertedData, ok := filteredData.([]interface{}); ok { datastores = make([]map[string]interface{}, 0, len(convertedData)) for _, item := range convertedData { if datastoreMap, ok := item.(map[string]interface{}); ok { datastores = append(datastores, datastoreMap) } } } } // Generate output emptyMessage := fmt.Sprintf("No datastores found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(datastores, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(datastores, emptyMessage) default: return output.PrintTableWithQuery(datastores, defaultHeaders, queryOpts, emptyMessage) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/datavolumes.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListDataVolumesWithInsecure queries the provider's data volume inventory with optional insecure TLS skip verification func ListDataVolumesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listDataVolumesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listDataVolumesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listDataVolumesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify data volume support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "openshift": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "NAMESPACE", JSONPath: "namespace"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "PHASE", JSONPath: "object.status.phase"}, {DisplayName: "PROGRESS", JSONPath: "object.status.progress"}, {DisplayName: "STORAGE_CLASS", JSONPath: "object.spec.pvc.storageClassName"}, {DisplayName: "SIZE", JSONPath: "sizeFormatted"}, {DisplayName: "CREATED", JSONPath: "object.metadata.creationTimestamp"}, } default: return fmt.Errorf("provider type '%s' does not support data volume inventory", providerType) } // Fetch data volume inventory from the provider based on provider type var data interface{} switch providerType { case "openshift": data, err = providerClient.GetDataVolumes(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support data volume inventory", providerType) } if err != nil { return fmt.Errorf("failed to fetch data volume inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for data volume inventory") } // Convert to expected format and add calculated fields dataVolumes := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { dataVolume, ok := item.(map[string]interface{}) if !ok { continue } // Add human-readable size formatting using GetValueByPathString if storage, err := querypkg.GetValueByPathString(dataVolume, "object.spec.pvc.resources.requests.storage"); err == nil { if storageStr, ok := storage.(string); ok { dataVolume["sizeFormatted"] = storageStr } } dataVolumes = append(dataVolumes, dataVolume) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter filteredData, err := querypkg.ApplyQueryInterface(dataVolumes, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } // Convert back to []map[string]interface{} if convertedData, ok := filteredData.([]interface{}); ok { dataVolumes = make([]map[string]interface{}, 0, len(convertedData)) for _, item := range convertedData { if dataVolumeMap, ok := item.(map[string]interface{}); ok { dataVolumes = append(dataVolumes, dataVolumeMap) } } } } // Format and display the results emptyMessage := fmt.Sprintf("No data volumes found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(dataVolumes, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(dataVolumes, emptyMessage) case "table": return output.PrintTableWithQuery(dataVolumes, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/disks.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListDisksWithInsecure queries the provider's disk inventory with optional insecure TLS skip verification func ListDisksWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listDisksOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listDisksOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listDisksOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify disk support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "ova": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "PATH", JSONPath: "path"}, {DisplayName: "SIZE", JSONPath: "sizeHuman"}, {DisplayName: "VM-COUNT", JSONPath: "vmCount"}, } case "hyperv": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "SIZE", JSONPath: "provisionedSizeHuman"}, {DisplayName: "PATH", JSONPath: "filePath"}, } default: defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STORAGE-DOMAIN", JSONPath: "storageDomain.name"}, {DisplayName: "SIZE", JSONPath: "provisionedSizeHuman"}, {DisplayName: "ACTUAL-SIZE", JSONPath: "actualSizeHuman"}, {DisplayName: "TYPE", JSONPath: "storageType"}, {DisplayName: "STATUS", JSONPath: "status"}, } } // Fetch disks inventory from the provider based on provider type var data interface{} switch providerType { case "ovirt": data, err = providerClient.GetDisks(ctx, 4) case "openstack": data, err = providerClient.GetVolumes(ctx, 4) case "ova": data, err = providerClient.GetOVAFiles(ctx, 4) case "hyperv": data, err = providerClient.GetDisks(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support disk inventory", providerType) } if err != nil { return fmt.Errorf("failed to get disks from provider: %v", err) } // Process data to add human-readable sizes for oVirt and HyperV if providerType == "ovirt" || providerType == "hyperv" { data = addHumanReadableSizes(data) } // Process data to add human-readable sizes for oVirt if providerType == "ova" { data = addHumanReadableOVASizes(data) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No disks found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // addHumanReadableSizes adds human-readable size fields to disk data func addHumanReadableSizes(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if disk, ok := item.(map[string]interface{}); ok { if provisionedSize, exists := disk["provisionedSize"]; exists { if size, ok := provisionedSize.(float64); ok { disk["provisionedSizeHuman"] = humanizeBytes(size) } } if actualSize, exists := disk["actualSize"]; exists { if size, ok := actualSize.(float64); ok { disk["actualSizeHuman"] = humanizeBytes(size) } } } } case map[string]interface{}: if provisionedSize, exists := v["provisionedSize"]; exists { if size, ok := provisionedSize.(float64); ok { v["provisionedSizeHuman"] = humanizeBytes(size) } } if actualSize, exists := v["actualSize"]; exists { if size, ok := actualSize.(float64); ok { v["actualSizeHuman"] = humanizeBytes(size) } } } return data } // addHumanReadableOVASizes adds human-readable size fields to OVA data func addHumanReadableOVASizes(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if ova, ok := item.(map[string]interface{}); ok { if size, exists := ova["size"]; exists { if sizeVal, ok := size.(float64); ok { ova["sizeHuman"] = humanizeBytes(sizeVal) } } } } case map[string]interface{}: if size, exists := v["size"]; exists { if sizeVal, ok := size.(float64); ok { v["sizeHuman"] = humanizeBytes(sizeVal) } } } return data }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/ec2.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListEC2InstancesWithInsecure queries the provider's EC2 instance inventory with optional insecure TLS skip verification func ListEC2InstancesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listEC2InstancesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listEC2InstancesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listEC2InstancesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify EC2 support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Verify this is an EC2 provider if providerType != "ec2" { return fmt.Errorf("provider type '%s' is not an EC2 provider", providerType) } // Define default headers for EC2 instances // Note: AWS API returns PascalCase field names (object extracted) // NAME column shows Name tag if available, otherwise falls back to InstanceId defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "TYPE", JSONPath: "InstanceType"}, {DisplayName: "STATE", JSONPath: "State.Name"}, {DisplayName: "PLATFORM", JSONPath: "PlatformDetails"}, {DisplayName: "AZ", JSONPath: "Placement.AvailabilityZone"}, {DisplayName: "PUBLIC-IP", JSONPath: "PublicIpAddress"}, {DisplayName: "PRIVATE-IP", JSONPath: "PrivateIpAddress"}, } // Fetch EC2 instances from the provider data, err := providerClient.GetVMs(ctx, 4) if err != nil { return fmt.Errorf("failed to get EC2 instances from provider: %v", err) } // Extract objects from EC2 envelope data = ExtractEC2Objects(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No EC2 instances found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListEC2VolumesWithInsecure queries the provider's EC2 EBS volume inventory with optional insecure TLS skip verification func ListEC2VolumesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listEC2VolumesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listEC2VolumesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listEC2VolumesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify EC2 support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Verify this is an EC2 provider if providerType != "ec2" { return fmt.Errorf("provider type '%s' is not an EC2 provider", providerType) } // Define default headers for EC2 volumes // Note: AWS API returns PascalCase field names (object extracted) defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "SIZE", JSONPath: "sizeHuman"}, {DisplayName: "TYPE", JSONPath: "VolumeType"}, {DisplayName: "STATE", JSONPath: "State"}, {DisplayName: "IOPS", JSONPath: "Iops"}, {DisplayName: "THROUGHPUT", JSONPath: "Throughput"}, {DisplayName: "ATTACHED-TO", JSONPath: "attachedTo"}, } // Fetch EC2 volumes from the provider data, err := providerClient.GetVolumes(ctx, 4) if err != nil { return fmt.Errorf("failed to get EC2 volumes from provider: %v", err) } // Extract objects from EC2 envelope data = ExtractEC2Objects(data) // Process data to add human-readable fields data = addEC2VolumeFields(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No EC2 volumes found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListEC2VolumeTypesWithInsecure queries the provider's EC2 volume type inventory with optional insecure TLS skip verification func ListEC2VolumeTypesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listEC2VolumeTypesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listEC2VolumeTypesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listEC2VolumeTypesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify EC2 support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Verify this is an EC2 provider if providerType != "ec2" { return fmt.Errorf("provider type '%s' is not an EC2 provider", providerType) } // Define default headers for EC2 volume types defaultHeaders := []output.Header{ {DisplayName: "TYPE", JSONPath: "type"}, {DisplayName: "DESCRIPTION", JSONPath: "description"}, {DisplayName: "MAX-IOPS", JSONPath: "maxIOPS"}, {DisplayName: "MAX-THROUGHPUT", JSONPath: "maxThroughput"}, } // Fetch EC2 volume types (storage classes) from the provider data, err := providerClient.GetResourceCollection(ctx, "storages", 4) if err != nil { return fmt.Errorf("failed to get EC2 volume types from provider: %v", err) } // Extract objects from EC2 envelope data = ExtractEC2Objects(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No EC2 volume types found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListEC2NetworksWithInsecure queries the provider's EC2 network inventory (VPCs and Subnets) with optional insecure TLS skip verification func ListEC2NetworksWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listEC2NetworksOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listEC2NetworksOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listEC2NetworksOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify EC2 support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Verify this is an EC2 provider if providerType != "ec2" { return fmt.Errorf("provider type '%s' is not an EC2 provider", providerType) } // Define default headers for EC2 networks // Note: AWS API returns PascalCase field names (object extracted) defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "TYPE", JSONPath: "networkType"}, {DisplayName: "CIDR", JSONPath: "CidrBlock"}, {DisplayName: "STATE", JSONPath: "State"}, {DisplayName: "DEFAULT", JSONPath: "IsDefault"}, } // Fetch EC2 networks from the provider data, err := providerClient.GetNetworks(ctx, 4) if err != nil { return fmt.Errorf("failed to get EC2 networks from provider: %v", err) } // Extract objects from EC2 envelope data = ExtractEC2Objects(data) // Process data to extract names and normalize fields data = addEC2NetworkFields(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No EC2 networks found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // Helper functions for EC2 data processing // addEC2VolumeFields adds human-readable fields to volume data func addEC2VolumeFields(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if volume, ok := item.(map[string]interface{}); ok { processEC2Volume(volume) } } case map[string]interface{}: processEC2Volume(v) } return data } func processEC2Volume(volume map[string]interface{}) { // Add human-readable size (Size is in GiB) if size, exists := volume["Size"]; exists { if sizeVal, ok := size.(float64); ok { volume["sizeHuman"] = humanizeBytes(sizeVal * 1024 * 1024 * 1024) // Size is in GiB } } // Extract attached instance ID (Attachments, InstanceId) if attachments, exists := volume["Attachments"]; exists { if attachmentsArray, ok := attachments.([]interface{}); ok && len(attachmentsArray) > 0 { if attachment, ok := attachmentsArray[0].(map[string]interface{}); ok { if instanceID, ok := attachment["InstanceId"].(string); ok { volume["attachedTo"] = instanceID } } } } if _, hasAttached := volume["attachedTo"]; !hasAttached { volume["attachedTo"] = "-" } } // addEC2NetworkFields adds normalized fields to network data func addEC2NetworkFields(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if network, ok := item.(map[string]interface{}); ok { processEC2Network(network) } } case map[string]interface{}: processEC2Network(v) } return data } func processEC2Network(network map[string]interface{}) { // Determine network type based on which ID field is present (for display purposes) // Subnet takes precedence over VPC if _, hasType := network["networkType"]; !hasType { if _, ok := network["SubnetId"].(string); ok { network["networkType"] = "subnet" } else if _, ok := network["VpcId"].(string); ok { network["networkType"] = "vpc" } else { network["networkType"] = "unknown" } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/ec2_helpers.go
Go
package inventory // ExtractEC2Objects processes EC2 inventory data by extracting the "object" field // and discarding the envelope. This should be called immediately after fetching // EC2 inventory data from the API server. // // The EC2 inventory server returns data in this format: // // { // "id": "...", // "name": "...", // "object": { ... actual EC2 data ... }, // "provider": "ec2", // ... // } // // This function extracts the "object" content and merges it with id and name, // returning a flattened structure for easier processing. func ExtractEC2Objects(data interface{}) interface{} { switch v := data.(type) { case []interface{}: result := make([]interface{}, 0, len(v)) for _, item := range v { if itemMap, ok := item.(map[string]interface{}); ok { result = append(result, extractEC2Object(itemMap)) } } return result case map[string]interface{}: return extractEC2Object(v) default: return data } } // extractEC2Object extracts the object field from a single EC2 inventory item func extractEC2Object(item map[string]interface{}) map[string]interface{} { // If there's no object field, return the item as-is (backward compatibility) obj, hasObject := item["object"].(map[string]interface{}) if !hasObject { return item } // Add top-level id and name fields from the envelope to the object if id, ok := item["id"]; ok { obj["id"] = id } if name, ok := item["name"]; ok { obj["name"] = name } return obj }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/folders.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListFoldersWithInsecure queries the provider's folder inventory with optional insecure TLS skip verification func ListFoldersWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listFoldersOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listFoldersOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listFoldersOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify folder support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "vsphere": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "PARENT", JSONPath: "parent"}, {DisplayName: "PATH", JSONPath: "path"}, {DisplayName: "DATACENTER", JSONPath: "datacenter"}, {DisplayName: "REVISION", JSONPath: "revision"}, } default: return fmt.Errorf("provider type '%s' does not support folder inventory", providerType) } // Fetch folders inventory from the provider based on provider type var data interface{} switch providerType { case "vsphere": data, err = providerClient.GetFolders(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support folder inventory", providerType) } if err != nil { return fmt.Errorf("failed to fetch folder inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for folder inventory") } // Convert to expected format folders := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { folder, ok := item.(map[string]interface{}) if !ok { continue } folders = append(folders, folder) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter filteredData, err := querypkg.ApplyQueryInterface(folders, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } // Convert back to []map[string]interface{} if convertedData, ok := filteredData.([]interface{}); ok { folders = make([]map[string]interface{}, 0, len(convertedData)) for _, item := range convertedData { if folderMap, ok := item.(map[string]interface{}); ok { folders = append(folders, folderMap) } } } } // Generate output // Format and display the results emptyMessage := fmt.Sprintf("No folders found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(folders, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(folders, emptyMessage) case "table": return output.PrintTableWithQuery(folders, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/hosts.go
Go
package inventory import ( "context" "fmt" "strings" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListHostsWithInsecure queries the provider's host inventory with optional insecure TLS skip verification func ListHostsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listHostsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listHostsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listHostsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify host support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Fetch hosts inventory from the provider based on provider type var data interface{} switch providerType { case "ovirt", "vsphere", "hyperv": data, err = providerClient.GetHosts(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support host inventory", providerType) } // Error handling if err != nil { return fmt.Errorf("failed to fetch host inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for host inventory") } // Convert to expected format hosts := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { if host, ok := item.(map[string]interface{}); ok { // Add provider name to each host host["provider"] = providerName hosts = append(hosts, host) } } // Parse and apply query options queryOpts, err := querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("invalid query string: %v", err) } // Apply query options (sorting, filtering, limiting) hosts, err = querypkg.ApplyQuery(hosts, queryOpts) if err != nil { return fmt.Errorf("error applying query: %v", err) } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } // Handle different output formats emptyMessage := fmt.Sprintf("No hosts found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(hosts, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(hosts, emptyMessage) default: // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STATUS", JSONPath: "status"}, {DisplayName: "VERSION", JSONPath: "productVersion"}, {DisplayName: "MGMT IP", JSONPath: "managementServerIp"}, {DisplayName: "CORES", JSONPath: "cpuCores"}, {DisplayName: "SOCKETS", JSONPath: "cpuSockets"}, {DisplayName: "MAINTENANCE", JSONPath: "inMaintenance"}, } return output.PrintTableWithQuery(hosts, defaultHeaders, queryOpts, emptyMessage) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/inventory.go
Go
package inventory import ( "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // GetProviderByName fetches a provider by name from the specified namespace func GetProviderByName(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string) (*unstructured.Unstructured, error) { c, err := client.GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get client: %v", err) } provider, err := c.Resource(client.ProvidersGVR).Namespace(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("failed to get provider '%s': %v", name, err) } return provider, nil } // humanizeBytes converts bytes to a human-readable string with appropriate unit suffix func humanizeBytes(bytes float64) string { const unit = 1024.0 if bytes < unit { return fmt.Sprintf("%.1f B", bytes) } div, exp := unit, 0 for n := bytes / unit; n >= unit; n /= unit { div *= unit exp++ } suffix := "KMGTPE"[exp : exp+1] return fmt.Sprintf("%.1f %sB", bytes/div, suffix) }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/namespaces.go
Go
package inventory import ( "context" "fmt" "strings" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListNamespacesWithInsecure queries the provider's namespace inventory with optional insecure TLS skip verification func ListNamespacesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listNamespacesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listNamespacesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listNamespacesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify namespace support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Fetch namespace inventory from the provider based on provider type var data interface{} switch providerType { case "openshift": data, err = providerClient.GetNamespaces(ctx, 4) case "openstack": data, err = providerClient.GetProjects(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support namespace inventory", providerType) } // Error handling if err != nil { return fmt.Errorf("failed to fetch namespace inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for namespace inventory") } // Convert to expected format namespaces := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { if ns, ok := item.(map[string]interface{}); ok { // Add provider name to each namespace ns["provider"] = providerName namespaces = append(namespaces, ns) } } // Parse and apply query options queryOpts, err := querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("invalid query string: %v", err) } // Apply query options (sorting, filtering, limiting) namespaces, err = querypkg.ApplyQuery(namespaces, queryOpts) if err != nil { return fmt.Errorf("error applying query: %v", err) } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } // Handle different output formats emptyMessage := fmt.Sprintf("No namespaces found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(namespaces, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(namespaces, emptyMessage) default: // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "PROVIDER", JSONPath: "provider"}, } return output.PrintTableWithQuery(namespaces, defaultHeaders, queryOpts, emptyMessage) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/networks.go
Go
package inventory import ( "context" "fmt" "strings" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // countNetworkHosts calculates the number of hosts connected to a network func countNetworkHosts(network map[string]interface{}) int { hosts, exists := network["host"] if !exists { return 0 } hostsArray, ok := hosts.([]interface{}) if !ok { return 0 } return len(hostsArray) } // countNetworkSubnets calculates the number of subnets in a network (for OpenStack) func countNetworkSubnets(network map[string]interface{}) int { subnets, exists := network["subnets"] if !exists { return 0 } subnetsArray, ok := subnets.([]interface{}) if !ok { return 0 } return len(subnetsArray) } // ListNetworksWithInsecure queries the provider's network inventory and displays the results with optional insecure TLS skip verification func ListNetworksWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listNetworksOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listNetworksOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listNetworksOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to determine resource path and headers providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "openshift": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "NAMESPACE", JSONPath: "namespace"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "CREATED", JSONPath: "object.metadata.creationTimestamp"}, } case "openstack": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STATUS", JSONPath: "status"}, {DisplayName: "SHARED", JSONPath: "shared"}, {DisplayName: "ADMIN-UP", JSONPath: "adminStateUp"}, {DisplayName: "SUBNETS", JSONPath: "subnetsCount"}, } case "ec2": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "TYPE", JSONPath: "networkType"}, {DisplayName: "CIDR", JSONPath: "CidrBlock"}, {DisplayName: "STATE", JSONPath: "State"}, {DisplayName: "DEFAULT", JSONPath: "IsDefault"}, } default: defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "VARIANT", JSONPath: "variant"}, {DisplayName: "HOSTS", JSONPath: "hostCount"}, {DisplayName: "VLAN", JSONPath: "vlanId"}, {DisplayName: "REVISION", JSONPath: "revision"}, } } // Fetch network inventory from the provider based on provider type var data interface{} switch providerType { case "openshift": // For OpenShift, get network attachment definitions data, err = providerClient.GetResourceCollection(ctx, "networkattachmentdefinitions", 4) default: // For other providers, get networks data, err = providerClient.GetNetworks(ctx, 4) } if err != nil { return fmt.Errorf("failed to fetch network inventory: %v", err) } // Extract objects from EC2 envelope if providerType == "ec2" { data = ExtractEC2Objects(data) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for network inventory") } // Convert to expected format networks := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { if network, ok := item.(map[string]interface{}); ok { // Add provider name to each network network["provider"] = providerName // Add host count (for ovirt, vsphere, etc.) network["hostCount"] = countNetworkHosts(network) // Add subnets count (for OpenStack) if providerType == "openstack" { network["subnetsCount"] = countNetworkSubnets(network) } // Process EC2 networks (extract name from tags, set ID and type) if providerType == "ec2" { processEC2Network(network) } networks = append(networks, network) } } // Parse and apply query options queryOpts, err := querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("invalid query string: %v", err) } // Apply query options (sorting, filtering, limiting) networks, err = querypkg.ApplyQuery(networks, queryOpts) if err != nil { return fmt.Errorf("error applying query: %v", err) } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } // Handle different output formats emptyMessage := fmt.Sprintf("No networks found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(networks, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(networks, emptyMessage) default: return output.PrintTableWithQuery(networks, defaultHeaders, queryOpts, emptyMessage) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/openstack.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListInstancesWithInsecure queries the provider's instance inventory with optional insecure TLS skip verification func ListInstancesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listInstancesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listInstancesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listInstancesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify instance support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STATUS", JSONPath: "status"}, {DisplayName: "FLAVOR", JSONPath: "flavor.name"}, {DisplayName: "IMAGE", JSONPath: "image.name"}, {DisplayName: "PROJECT", JSONPath: "project.name"}, } // Fetch instances inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetInstances(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support instance inventory", providerType) } if err != nil { return fmt.Errorf("failed to get instances from provider: %v", err) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No instances found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListImagesWithInsecure queries the provider's image inventory with optional insecure TLS skip verification func ListImagesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listImagesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listImagesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listImagesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify image support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STATUS", JSONPath: "status"}, {DisplayName: "SIZE", JSONPath: "sizeHuman"}, {DisplayName: "VISIBILITY", JSONPath: "visibility"}, } // Fetch images inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetImages(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support image inventory", providerType) } if err != nil { return fmt.Errorf("failed to get images from provider: %v", err) } // Process data to add human-readable sizes data = addHumanReadableImageSizes(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No images found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListFlavorsWithInsecure queries the provider's flavor inventory with optional insecure TLS skip verification func ListFlavorsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listFlavorsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listFlavorsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listFlavorsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify flavor support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "VCPUS", JSONPath: "vcpus"}, {DisplayName: "RAM", JSONPath: "ramHuman"}, {DisplayName: "DISK", JSONPath: "diskHuman"}, {DisplayName: "EPHEMERAL", JSONPath: "ephemeralHuman"}, } // Fetch flavors inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetFlavors(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support flavor inventory", providerType) } if err != nil { return fmt.Errorf("failed to get flavors from provider: %v", err) } // Process data to add human-readable sizes data = addHumanReadableFlavorSizes(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No flavors found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListProjects queries the provider's project inventory and displays the results // ListProjectsWithInsecure queries the provider's project inventory with optional insecure TLS skip verification func ListProjectsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listProjectsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listProjectsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listProjectsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify project support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "DESCRIPTION", JSONPath: "description"}, {DisplayName: "ENABLED", JSONPath: "enabled"}, } // Fetch projects inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetProjects(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support project inventory", providerType) } if err != nil { return fmt.Errorf("failed to get projects from provider: %v", err) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No projects found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListVolumesWithInsecure queries the provider's volume inventory with optional insecure TLS skip verification func ListVolumesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listVolumesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listVolumesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listVolumesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify volume support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STATUS", JSONPath: "status"}, {DisplayName: "SIZE", JSONPath: "sizeHuman"}, {DisplayName: "TYPE", JSONPath: "volumeType"}, {DisplayName: "BOOTABLE", JSONPath: "bootable"}, } // Fetch volumes inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetVolumes(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support volume inventory", providerType) } if err != nil { return fmt.Errorf("failed to get volumes from provider: %v", err) } // Process data to add human-readable sizes data = addHumanReadableVolumeSizes(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No volumes found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListVolumeTypesWithInsecure queries the provider's volume type inventory with optional insecure TLS skip verification func ListVolumeTypesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listVolumeTypesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listVolumeTypesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listVolumeTypesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify volume type support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "DESCRIPTION", JSONPath: "description"}, {DisplayName: "PUBLIC", JSONPath: "isPublic"}, } // Fetch volume types inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetVolumeTypes(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support volume type inventory", providerType) } if err != nil { return fmt.Errorf("failed to get volume types from provider: %v", err) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No volume types found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListSnapshotsWithInsecure queries the provider's snapshot inventory with optional insecure TLS skip verification func ListSnapshotsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listSnapshotsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listSnapshotsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listSnapshotsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify snapshot support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STATUS", JSONPath: "status"}, {DisplayName: "SIZE", JSONPath: "sizeHuman"}, {DisplayName: "VOLUME-ID", JSONPath: "volumeID"}, } // Fetch snapshots inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetSnapshots(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support snapshot inventory", providerType) } if err != nil { return fmt.Errorf("failed to get snapshots from provider: %v", err) } // Process data to add human-readable sizes data = addHumanReadableSnapshotSizes(data) // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No snapshots found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListSubnetsWithInsecure queries the provider's subnet inventory with optional insecure TLS skip verification func ListSubnetsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listSubnetsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listSubnetsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listSubnetsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify subnet support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "NETWORK-ID", JSONPath: "networkID"}, {DisplayName: "CIDR", JSONPath: "cidr"}, {DisplayName: "IP-VERSION", JSONPath: "ipVersion"}, {DisplayName: "GATEWAY", JSONPath: "gatewayIP"}, {DisplayName: "DHCP", JSONPath: "enableDHCP"}, } // Fetch subnets inventory from the provider var data interface{} switch providerType { case "openstack": data, err = providerClient.GetSubnets(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support subnet inventory", providerType) } if err != nil { return fmt.Errorf("failed to get subnets from provider: %v", err) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No subnets found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // Helper functions for adding human-readable sizes // addHumanReadableImageSizes adds human-readable size fields to image data func addHumanReadableImageSizes(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if image, ok := item.(map[string]interface{}); ok { if size, exists := image["size"]; exists { if sizeVal, ok := size.(float64); ok { image["sizeHuman"] = humanizeBytes(sizeVal) } } } } case map[string]interface{}: if size, exists := v["size"]; exists { if sizeVal, ok := size.(float64); ok { v["sizeHuman"] = humanizeBytes(sizeVal) } } } return data } // addHumanReadableFlavorSizes adds human-readable size fields to flavor data func addHumanReadableFlavorSizes(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if flavor, ok := item.(map[string]interface{}); ok { if ram, exists := flavor["ram"]; exists { if ramVal, ok := ram.(float64); ok { flavor["ramHuman"] = humanizeBytes(ramVal * 1024 * 1024) // RAM is in MB } } if disk, exists := flavor["disk"]; exists { if diskVal, ok := disk.(float64); ok { flavor["diskHuman"] = humanizeBytes(diskVal * 1024 * 1024 * 1024) // Disk is in GB } } if ephemeral, exists := flavor["ephemeral"]; exists { if ephemeralVal, ok := ephemeral.(float64); ok { flavor["ephemeralHuman"] = humanizeBytes(ephemeralVal * 1024 * 1024 * 1024) // Ephemeral is in GB } } } } case map[string]interface{}: if ram, exists := v["ram"]; exists { if ramVal, ok := ram.(float64); ok { v["ramHuman"] = humanizeBytes(ramVal * 1024 * 1024) // RAM is in MB } } if disk, exists := v["disk"]; exists { if diskVal, ok := disk.(float64); ok { v["diskHuman"] = humanizeBytes(diskVal * 1024 * 1024 * 1024) // Disk is in GB } } if ephemeral, exists := v["ephemeral"]; exists { if ephemeralVal, ok := ephemeral.(float64); ok { v["ephemeralHuman"] = humanizeBytes(ephemeralVal * 1024 * 1024 * 1024) // Ephemeral is in GB } } } return data } // addHumanReadableVolumeSizes adds human-readable size fields to volume data func addHumanReadableVolumeSizes(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if volume, ok := item.(map[string]interface{}); ok { if size, exists := volume["size"]; exists { if sizeVal, ok := size.(float64); ok { volume["sizeHuman"] = humanizeBytes(sizeVal * 1024 * 1024 * 1024) // Size is in GB } } } } case map[string]interface{}: if size, exists := v["size"]; exists { if sizeVal, ok := size.(float64); ok { v["sizeHuman"] = humanizeBytes(sizeVal * 1024 * 1024 * 1024) // Size is in GB } } } return data } // addHumanReadableSnapshotSizes adds human-readable size fields to snapshot data func addHumanReadableSnapshotSizes(data interface{}) interface{} { switch v := data.(type) { case []interface{}: for _, item := range v { if snapshot, ok := item.(map[string]interface{}); ok { if size, exists := snapshot["size"]; exists { if sizeVal, ok := size.(float64); ok { snapshot["sizeHuman"] = humanizeBytes(sizeVal * 1024 * 1024 * 1024) // Size is in GB } } } } case map[string]interface{}: if size, exists := v["size"]; exists { if sizeVal, ok := size.(float64); ok { v["sizeHuman"] = humanizeBytes(sizeVal * 1024 * 1024 * 1024) // Size is in GB } } } return data }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/profiles.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListDiskProfilesWithInsecure queries the provider's disk profile inventory with optional insecure TLS skip verification func ListDiskProfilesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listDiskProfilesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listDiskProfilesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listDiskProfilesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify disk profile support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STORAGE-DOMAIN", JSONPath: "storageDomain.name"}, {DisplayName: "QOS", JSONPath: "qos.name"}, } // Fetch disk profiles inventory from the provider based on provider type var data interface{} switch providerType { case "ovirt": data, err = providerClient.GetDiskProfiles(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support disk profile inventory", providerType) } if err != nil { return fmt.Errorf("failed to get disk profiles from provider: %v", err) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No disk profiles found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } } // ListNICProfilesWithInsecure queries the provider's NIC profile inventory with optional insecure TLS skip verification func ListNICProfilesWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listNICProfilesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listNICProfilesOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listNICProfilesOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify NIC profile support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "NETWORK", JSONPath: "network.name"}, {DisplayName: "PORT-MIRRORING", JSONPath: "portMirroring"}, {DisplayName: "PASS-THROUGH", JSONPath: "passThrough"}, {DisplayName: "QOS", JSONPath: "qos.name"}, } // Fetch NIC profiles inventory from the provider based on provider type var data interface{} switch providerType { case "ovirt": data, err = providerClient.GetNICProfiles(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support NIC profile inventory", providerType) } if err != nil { return fmt.Errorf("failed to get NIC profiles from provider: %v", err) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter data, err = querypkg.ApplyQueryInterface(data, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } } // Format and display the results emptyMessage := fmt.Sprintf("No NIC profiles found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(data, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(data, emptyMessage) case "table": return output.PrintTableWithQuery(data, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/providers.go
Go
package inventory import ( "context" "fmt" "strings" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListProvidersWithInsecure queries the providers and displays their inventory information with optional insecure TLS skip verification func ListProvidersWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listProvidersOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listProvidersOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listProvidersOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // If inventoryURL is empty, try to discover it from an OpenShift Route if inventoryURL == "" { inventoryURL = client.DiscoverInventoryURL(ctx, kubeConfigFlags, namespace) } if inventoryURL == "" { return fmt.Errorf("inventory URL not provided and could not be discovered") } // Fetch provider inventory data directly from inventory API with detail=4 var providersData interface{} var err error if providerName != "" { // Get specific provider by name with detail=4 providersData, err = client.FetchSpecificProviderWithDetailAndInsecure(ctx, kubeConfigFlags, inventoryURL, providerName, 4, insecureSkipTLS) if err != nil { return fmt.Errorf("failed to get provider inventory: %v", err) } } else { // Get all providers with detail=4 providersData, err = client.FetchProvidersWithDetailAndInsecure(ctx, kubeConfigFlags, inventoryURL, 4, insecureSkipTLS) if err != nil { return fmt.Errorf("failed to fetch providers inventory: %v", err) } } // Parse provider inventory data var items []map[string]interface{} if providersMap, ok := providersData.(map[string]interface{}); ok { // Iterate through all provider types (vsphere, ovirt, openstack, etc.) for providerType, providerList := range providersMap { if providerListSlice, ok := providerList.([]interface{}); ok { for _, p := range providerListSlice { if providerMap, ok := p.(map[string]interface{}); ok { // Create item directly from inventory data (no CRD needed) item := map[string]interface{}{ "type": providerType, } // Copy all fields from inventory data for key, value := range providerMap { item[key] = value } // Add some derived fields for compatibility if namespace != "" { item["namespace"] = namespace } items = append(items, item) } } } } } else { return fmt.Errorf("unexpected provider inventory data format") } // Parse and apply query options queryOpts, err := querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("invalid query string: %v", err) } // Apply query options (sorting, filtering, limiting) items, err = querypkg.ApplyQuery(items, queryOpts) if err != nil { return fmt.Errorf("error applying query: %v", err) } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } // Handle different output formats emptyMessage := "No providers found" if namespace != "" { emptyMessage = fmt.Sprintf("No providers found in namespace %s", namespace) } switch outputFormat { case "json": return output.PrintJSONWithEmpty(items, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(items, emptyMessage) default: // Define headers optimized for inventory information defaultHeaders := []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, } // Add NAMESPACE column when listing across all namespaces (only if namespace data is available) if namespace == "" { // Only add namespace column if any items have namespace info hasNamespace := false for _, item := range items { if _, exists := item["namespace"]; exists { hasNamespace = true break } } if hasNamespace { defaultHeaders = append(defaultHeaders, output.Header{DisplayName: "NAMESPACE", JSONPath: "namespace"}) } } // Add remaining columns focused on inventory defaultHeaders = append(defaultHeaders, output.Header{DisplayName: "TYPE", JSONPath: "type"}, output.Header{DisplayName: "VERSION", JSONPath: "apiVersion"}, output.Header{DisplayName: "PHASE", JSONPath: "object.status.phase"}, output.Header{DisplayName: "VMS", JSONPath: "vmCount"}, output.Header{DisplayName: "HOSTS", JSONPath: "hostCount"}, ) return output.PrintTableWithQuery(items, defaultHeaders, queryOpts, emptyMessage) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/pvcs.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListPersistentVolumeClaimsWithInsecure queries the provider's persistent volume claim inventory with optional insecure TLS skip verification func ListPersistentVolumeClaimsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listPersistentVolumeClaimsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listPersistentVolumeClaimsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listPersistentVolumeClaimsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify PVC support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "openshift": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "NAMESPACE", JSONPath: "namespace"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "STATUS", JSONPath: "object.status.phase"}, {DisplayName: "CAPACITY", JSONPath: "object.status.capacity.storage"}, {DisplayName: "STORAGE_CLASS", JSONPath: "object.spec.storageClassName"}, {DisplayName: "ACCESS_MODES", JSONPath: "object.spec.accessModes"}, {DisplayName: "CREATED", JSONPath: "object.metadata.creationTimestamp"}, } default: return fmt.Errorf("provider type '%s' does not support persistent volume claim inventory", providerType) } // Fetch PVC inventory from the provider based on provider type var data interface{} switch providerType { case "openshift": data, err = providerClient.GetPersistentVolumeClaims(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support persistent volume claim inventory", providerType) } if err != nil { return fmt.Errorf("failed to fetch persistent volume claim inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for persistent volume claim inventory") } // Convert to expected format and add calculated fields pvcs := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { pvc, ok := item.(map[string]interface{}) if !ok { continue } // Add human-readable capacity formatting using GetValueByPathString if storage, err := querypkg.GetValueByPathString(pvc, "object.status.capacity.storage"); err == nil { if storageStr, ok := storage.(string); ok { pvc["capacityFormatted"] = storageStr } } // Format access modes using GetValueByPathString if accessModes, err := querypkg.GetValueByPathString(pvc, "object.spec.accessModes"); err == nil { if accessModesArray, ok := accessModes.([]interface{}); ok { var modes []string for _, mode := range accessModesArray { if modeStr, ok := mode.(string); ok { modes = append(modes, modeStr) } } pvc["accessModes"] = modes } } pvcs = append(pvcs, pvc) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter filteredData, err := querypkg.ApplyQueryInterface(pvcs, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } // Convert back to []map[string]interface{} if convertedData, ok := filteredData.([]interface{}); ok { pvcs = make([]map[string]interface{}, 0, len(convertedData)) for _, item := range convertedData { if pvcMap, ok := item.(map[string]interface{}); ok { pvcs = append(pvcs, pvcMap) } } } } // Format and display the results emptyMessage := fmt.Sprintf("No persistent volume claims found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(pvcs, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(pvcs, emptyMessage) case "table": return output.PrintTableWithQuery(pvcs, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/resource_pools.go
Go
package inventory import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListResourcePoolsWithInsecure queries the provider's resource pool inventory with optional insecure TLS skip verification func ListResourcePoolsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listResourcePoolsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listResourcePoolsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listResourcePoolsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify resource pool support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "vsphere": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "CPU_LIMIT", JSONPath: "cpuLimit"}, {DisplayName: "CPU_SHARES", JSONPath: "cpuShares"}, {DisplayName: "MEM_LIMIT", JSONPath: "memoryLimitFormatted"}, {DisplayName: "MEM_SHARES", JSONPath: "memoryShares"}, {DisplayName: "REVISION", JSONPath: "revision"}, } default: return fmt.Errorf("provider type '%s' does not support resource pool inventory", providerType) } // Fetch resource pools inventory from the provider based on provider type var data interface{} switch providerType { case "vsphere": data, err = providerClient.GetResourcePools(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support resource pool inventory", providerType) } if err != nil { return fmt.Errorf("failed to fetch resource pool inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for resource pool inventory") } // Convert to expected format and add calculated fields resourcePools := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { resourcePool, ok := item.(map[string]interface{}) if !ok { continue } // Add human-readable memory limit formatting if memoryLimit, exists := resourcePool["memoryLimit"]; exists { if memoryLimitFloat, ok := memoryLimit.(float64); ok { resourcePool["memoryLimitFormatted"] = humanizeBytes(memoryLimitFloat) } } resourcePools = append(resourcePools, resourcePool) } // Parse query options for advanced query features var queryOpts *querypkg.QueryOptions if query != "" { queryOpts, err = querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("failed to parse query: %v", err) } // Apply query filter filteredData, err := querypkg.ApplyQueryInterface(resourcePools, query) if err != nil { return fmt.Errorf("failed to apply query: %v", err) } // Convert back to []map[string]interface{} if convertedData, ok := filteredData.([]interface{}); ok { resourcePools = make([]map[string]interface{}, 0, len(convertedData)) for _, item := range convertedData { if resourcePoolMap, ok := item.(map[string]interface{}); ok { resourcePools = append(resourcePools, resourcePoolMap) } } } } // Format and display the results emptyMessage := fmt.Sprintf("No resource pools found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(resourcePools, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(resourcePools, emptyMessage) case "table": return output.PrintTableWithQuery(resourcePools, defaultHeaders, queryOpts, emptyMessage) default: return fmt.Errorf("unsupported output format: %s", outputFormat) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/storage.go
Go
package inventory import ( "context" "fmt" "strings" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // ListStorageWithInsecure queries the provider's storage inventory and displays the results with optional insecure TLS skip verification func ListStorageWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listStorageOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) }, watch.DefaultInterval) } return listStorageOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, query, insecureSkipTLS) } func listStorageOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to determine which storage resource to fetch providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Define default headers based on provider type var defaultHeaders []output.Header switch providerType { case "openshift": defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "DEFAULT", JSONPath: "object.metadata.annotations[storageclass.kubernetes.io/is-default-class]"}, {DisplayName: "VIRT-DEFAULT", JSONPath: "object.metadata.annotations[storageclass.kubevirt.io/is-default-virt-class]"}, } case "ec2": defaultHeaders = []output.Header{ {DisplayName: "TYPE", JSONPath: "type"}, {DisplayName: "DESCRIPTION", JSONPath: "description"}, {DisplayName: "MAX-IOPS", JSONPath: "maxIOPS"}, {DisplayName: "MAX-THROUGHPUT", JSONPath: "maxThroughput"}, } default: defaultHeaders = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "TYPE", JSONPath: "type"}, {DisplayName: "CAPACITY", JSONPath: "capacityHuman"}, {DisplayName: "FREE", JSONPath: "freeHuman"}, {DisplayName: "MAINTENANCE", JSONPath: "maintenance"}, } } // Fetch storage inventory based on provider type var data interface{} switch providerType { case "ovirt": data, err = providerClient.GetStorageDomains(ctx, 4) case "vsphere": data, err = providerClient.GetDatastores(ctx, 4) case "ova": data, err = providerClient.GetResourceCollection(ctx, "storages", 4) case "openstack": data, err = providerClient.GetVolumeTypes(ctx, 4) case "openshift": data, err = providerClient.GetStorageClasses(ctx, 4) case "ec2": data, err = providerClient.GetResourceCollection(ctx, "storages", 4) default: // For other providers, use generic storage resource data, err = providerClient.GetResourceCollection(ctx, "storages", 4) } if err != nil { return fmt.Errorf("failed to fetch storage inventory: %v", err) } // Extract objects from EC2 envelope if providerType == "ec2" { data = ExtractEC2Objects(data) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for storage inventory") } // Convert to expected format storages := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { if storage, ok := item.(map[string]interface{}); ok { // Add provider name to each storage storage["provider"] = providerName // Humanize capacity and free space if capacity, exists := storage["capacity"]; exists { if capacityFloat, ok := capacity.(float64); ok { storage["capacityHuman"] = humanizeBytes(capacityFloat) } else if capacityNum, ok := capacity.(int64); ok { storage["capacityHuman"] = humanizeBytes(float64(capacityNum)) } } if free, exists := storage["free"]; exists { if freeFloat, ok := free.(float64); ok { storage["freeHuman"] = humanizeBytes(freeFloat) } else if freeNum, ok := free.(int64); ok { storage["freeHuman"] = humanizeBytes(float64(freeNum)) } } storages = append(storages, storage) } } // Parse and apply query options queryOpts, err := querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("invalid query string: %v", err) } // Apply query options (sorting, filtering, limiting) storages, err = querypkg.ApplyQuery(storages, queryOpts) if err != nil { return fmt.Errorf("error applying query: %v", err) } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } // Handle different output formats emptyMessage := fmt.Sprintf("No storage resources found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(storages, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(storages, emptyMessage) default: return output.PrintTableWithQuery(storages, defaultHeaders, queryOpts, emptyMessage) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/inventory/vms.go
Go
package inventory import ( "context" "fmt" "strings" "gopkg.in/yaml.v3" "k8s.io/cli-runtime/pkg/genericclioptions" planv1beta1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan" "github.com/yaacov/kubectl-mtv/pkg/util/output" querypkg "github.com/yaacov/kubectl-mtv/pkg/util/query" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // countConcernsByCategory counts VM concerns by their category func countConcernsByCategory(vm map[string]interface{}) map[string]int { counts := map[string]int{ "Critical": 0, "Warning": 0, "Information": 0, } concerns, exists := vm["concerns"] if !exists { return counts } concernsArray, ok := concerns.([]interface{}) if !ok { return counts } for _, c := range concernsArray { concern, ok := c.(map[string]interface{}) if !ok { continue } category, ok := concern["category"].(string) if ok { counts[category]++ } } return counts } // formatVMConcerns formats all concerns for a VM into a displayable string func formatVMConcerns(vm map[string]interface{}) string { concerns, exists := vm["concerns"] if !exists { return "No concerns found" } concernsArray, ok := concerns.([]interface{}) if !ok || len(concernsArray) == 0 { return "No concerns found" } var result strings.Builder for i, c := range concernsArray { concern, ok := c.(map[string]interface{}) if !ok { continue } if i > 0 { result.WriteString("\n") } // Get category and use short form using GetValueByPathString categoryShort := "[?]" // Default if category unknown if categoryVal, err := querypkg.GetValueByPathString(concern, "category"); err == nil { if category, ok := categoryVal.(string); ok { switch category { case "Critical": categoryShort = "[C]" case "Warning": categoryShort = "[W]" case "Information": categoryShort = "[I]" default: categoryShort = "[" + string(category[0]) + "]" } } } result.WriteString(categoryShort + " ") // Add assessment using GetValueByPathString if assessmentVal, err := querypkg.GetValueByPathString(concern, "assessment"); err == nil { if assessment, ok := assessmentVal.(string); ok { result.WriteString(assessment) } else { result.WriteString("No details available") } } else { result.WriteString("No details available") } } return result.String() } // calculateTotalDiskCapacity returns the total disk capacity in GB func calculateTotalDiskCapacity(vm map[string]interface{}) float64 { disks, exists := vm["disks"] if !exists { return 0 } disksArray, ok := disks.([]interface{}) if !ok { return 0 } var totalCapacity float64 for _, d := range disksArray { disk, ok := d.(map[string]interface{}) if !ok { continue } if capacity, ok := disk["capacity"].(float64); ok { totalCapacity += capacity } } // Convert to GB (from bytes) return totalCapacity / (1024 * 1024 * 1024) } // augmentVMInfo adds computed fields to VM data for display purposes // Returns the expanded data string if the VM has concerns (for extended output) func augmentVMInfo(vm map[string]interface{}, extendedOutput bool) string { var expandedText string // Add concern counts by category concernCounts := countConcernsByCategory(vm) vm["criticalConcerns"] = concernCounts["Critical"] vm["warningConcerns"] = concernCounts["Warning"] vm["infoConcerns"] = concernCounts["Information"] // Create a combined concerns string (Critical/Warning/Info) vm["concernsHuman"] = fmt.Sprintf("%d/%d/%d", concernCounts["Critical"], concernCounts["Warning"], concernCounts["Information"]) // Add (*) indicator if critical concerns exist if concernCounts["Critical"] > 0 { vm["concernsHuman"] = vm["concernsHuman"].(string) + " (*)" } // If VM has concerns, create expanded data if extendedOutput && (concernCounts["Critical"] > 0 || concernCounts["Warning"] > 0 || concernCounts["Information"] > 0) { // Format concerns for expanded view expandedText = formatVMConcerns(vm) } // Format memory in GB for display if memoryMB, exists := vm["memoryMB"]; exists { if memVal, ok := memoryMB.(float64); ok { vm["memoryGB"] = fmt.Sprintf("%.1f GB", memVal/1024) } } // Calculate and format disk capacity totalDiskCapacityGB := calculateTotalDiskCapacity(vm) vm["diskCapacity"] = fmt.Sprintf("%.1f GB", totalDiskCapacityGB) // Format storage used if storageUsed, exists := vm["storageUsed"]; exists { if storageVal, ok := storageUsed.(float64); ok { storageUsedGB := storageVal / (1024 * 1024 * 1024) vm["storageUsedGB"] = fmt.Sprintf("%.1f GB", storageUsedGB) } } // Humanize power state if powerState, exists := vm["powerState"]; exists { if ps, ok := powerState.(string); ok { if strings.Contains(strings.ToLower(ps), "on") { vm["powerStateHuman"] = "On" } else { vm["powerStateHuman"] = "Off" } } } return expandedText } // FetchVMsByQuery fetches VMs from inventory based on a query string and returns them as plan VM structs func FetchVMsByQuery(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace, inventoryURL, query string) ([]planv1beta1.VM, error) { return FetchVMsByQueryWithInsecure(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, query, false) } // FetchVMsByQueryWithInsecure fetches VMs from inventory based on a query string and returns them as plan VM structs with optional insecure TLS skip verification func FetchVMsByQueryWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace, inventoryURL, query string, insecureSkipTLS bool) ([]planv1beta1.VM, error) { // Validate inputs early if providerName == "" { return nil, fmt.Errorf("provider name cannot be empty") } if query == "" { return nil, fmt.Errorf("query string cannot be empty") } // Parse and validate query syntax BEFORE fetching inventory (fail fast) queryOpts, err := querypkg.ParseQueryString(query) if err != nil { return nil, fmt.Errorf("invalid query string: %v", err) } // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return nil, err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify VM support providerType, err := providerClient.GetProviderType() if err != nil { return nil, fmt.Errorf("failed to get provider type: %v", err) } // Verify provider supports VM inventory before fetching switch providerType { case "ovirt", "vsphere", "openstack", "ova", "openshift", "ec2", "hyperv": // Provider supports VMs, continue default: return nil, fmt.Errorf("provider type '%s' does not support VM inventory", providerType) } // Fetch VM inventory from the provider (expensive operation) data, err := providerClient.GetVMs(ctx, 4) if err != nil { return nil, fmt.Errorf("failed to fetch VM inventory: %v", err) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return nil, fmt.Errorf("unexpected data format: expected array for VM inventory") } // Convert to expected format vms := make([]map[string]interface{}, 0, len(dataArray)) for _, item := range dataArray { if vm, ok := item.(map[string]interface{}); ok { // Add provider name to each VM vm["provider"] = providerName vms = append(vms, vm) } } // Apply query options (sorting, filtering, limiting) vms, err = querypkg.ApplyQuery(vms, queryOpts) if err != nil { return nil, fmt.Errorf("error applying query: %v", err) } // Convert inventory VMs to plan VM structs planVMs := make([]planv1beta1.VM, 0, len(vms)) for _, vm := range vms { vmName, ok := vm["name"].(string) if !ok { continue } planVM := planv1beta1.VM{} planVM.Name = vmName // Add ID if available if vmID, ok := vm["id"].(string); ok { planVM.ID = vmID } planVMs = append(planVMs, planVM) } return planVMs, nil } // ListVMs queries the provider's VM inventory and displays the results // ListVMsWithInsecure queries the provider's VM inventory and displays the results with optional insecure TLS skip verification func ListVMsWithInsecure(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, extendedOutput bool, query string, watchMode bool, insecureSkipTLS bool) error { if watchMode { return watch.Watch(func() error { return listVMsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, extendedOutput, query, insecureSkipTLS) }, watch.DefaultInterval) } return listVMsOnce(ctx, kubeConfigFlags, providerName, namespace, inventoryURL, outputFormat, extendedOutput, query, insecureSkipTLS) } func listVMsOnce(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags, providerName, namespace string, inventoryURL string, outputFormat string, extendedOutput bool, query string, insecureSkipTLS bool) error { // Get the provider object provider, err := GetProviderByName(ctx, kubeConfigFlags, providerName, namespace) if err != nil { return err } // Create a new provider client providerClient := NewProviderClientWithInsecure(kubeConfigFlags, provider, inventoryURL, insecureSkipTLS) // Get provider type to verify VM support providerType, err := providerClient.GetProviderType() if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } // Fetch VM inventory from the provider based on provider type var data interface{} switch providerType { case "ovirt", "vsphere", "openstack", "ova", "openshift", "ec2", "hyperv": data, err = providerClient.GetVMs(ctx, 4) default: return fmt.Errorf("provider type '%s' does not support VM inventory", providerType) } // Error handling if err != nil { return fmt.Errorf("failed to fetch VM inventory: %v", err) } // Extract objects from EC2 envelope if providerType == "ec2" { data = ExtractEC2Objects(data) } // Verify data is an array dataArray, ok := data.([]interface{}) if !ok { return fmt.Errorf("unexpected data format: expected array for VM inventory") } // Convert to expected format vms := make([]map[string]interface{}, 0, len(dataArray)) expandedData := make(map[string]string) // Map for expanded VM concerns for _, item := range dataArray { if vm, ok := item.(map[string]interface{}); ok { // Add provider name to each VM vm["provider"] = providerName // Provider-specific handling if providerType == "ec2" { // For EC2, skip augmentVMInfo as it doesn't have concern/memory/disk/power fields // The inventory server already provides name and id fields vms = append(vms, vm) continue } // Augment VM info for non-EC2 providers (adds concern counts, memory, disk, power formatting) if expandedText := augmentVMInfo(vm, extendedOutput); expandedText != "" { if vmName, ok := vm["name"].(string); ok { expandedData[vmName] = expandedText } } vms = append(vms, vm) } } // Parse and apply query options queryOpts, err := querypkg.ParseQueryString(query) if err != nil { return fmt.Errorf("invalid query string: %v", err) } // Apply query options (sorting, filtering, limiting) vms, err = querypkg.ApplyQuery(vms, queryOpts) if err != nil { return fmt.Errorf("error applying query: %v", err) } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "planvms" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml, planvms", outputFormat) } // Handle different output formats emptyMessage := fmt.Sprintf("No VMs found for provider %s", providerName) switch outputFormat { case "json": return output.PrintJSONWithEmpty(vms, emptyMessage) case "yaml": return output.PrintYAMLWithEmpty(vms, emptyMessage) case "planvms": // Convert inventory VMs to plan VM structs planVMs := make([]planv1beta1.VM, 0, len(vms)) for _, vm := range vms { vmName, ok := vm["name"].(string) if !ok { continue } planVM := planv1beta1.VM{} planVM.Name = vmName // Add ID if available if vmID, ok := vm["id"].(string); ok { planVM.ID = vmID } planVMs = append(planVMs, planVM) } // Marshal to YAML yamlData, err := yaml.Marshal(planVMs) if err != nil { return fmt.Errorf("failed to marshal plan VMs to YAML: %v", err) } // Print the YAML to stdout fmt.Println(string(yamlData)) return nil default: var tablePrinter *output.TablePrinter // Check if we should use custom headers from SELECT clause if queryOpts.HasSelect { headers := make([]output.Header, 0, len(queryOpts.Select)) for _, sel := range queryOpts.Select { headers = append(headers, output.Header{ DisplayName: sel.Alias, JSONPath: sel.Alias, }) } tablePrinter = output.NewTablePrinter(). WithHeaders(headers...). WithSelectOptions(queryOpts.Select) } else { // Use provider-specific table headers var headers []output.Header switch providerType { case "ec2": headers = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "TYPE", JSONPath: "InstanceType"}, {DisplayName: "STATE", JSONPath: "State.Name"}, {DisplayName: "PLATFORM", JSONPath: "PlatformDetails"}, {DisplayName: "AZ", JSONPath: "Placement.AvailabilityZone"}, {DisplayName: "PUBLIC-IP", JSONPath: "PublicIpAddress"}, {DisplayName: "PRIVATE-IP", JSONPath: "PrivateIpAddress"}, } default: headers = []output.Header{ {DisplayName: "NAME", JSONPath: "name"}, {DisplayName: "ID", JSONPath: "id"}, {DisplayName: "POWER", JSONPath: "powerStateHuman"}, {DisplayName: "CPU", JSONPath: "cpuCount"}, {DisplayName: "MEMORY", JSONPath: "memoryGB"}, {DisplayName: "DISK USAGE", JSONPath: "storageUsedGB"}, {DisplayName: "GUEST OS", JSONPath: "guestId"}, {DisplayName: "CONCERNS (C/W/I)", JSONPath: "concernsHuman"}, } } tablePrinter = output.NewTablePrinter().WithHeaders(headers...) } // Add items with expanded concern data for _, vm := range vms { vmName, _ := vm["name"].(string) expandedText, hasExpanded := expandedData[vmName] if hasExpanded { tablePrinter.AddItemWithExpanded(vm, expandedText) } else { tablePrinter.AddItem(vm) } } if len(vms) == 0 { return tablePrinter.PrintEmpty(emptyMessage) } return tablePrinter.Print() } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/mapping/list.go
Go
package mapping import ( "context" "fmt" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/dynamic" "github.com/yaacov/kubectl-mtv/pkg/util/client" "github.com/yaacov/kubectl-mtv/pkg/util/output" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // extractProviderName gets a provider name from the mapping spec func extractProviderName(mapping unstructured.Unstructured, providerType string) string { provider, found, _ := unstructured.NestedMap(mapping.Object, "spec", "provider", providerType) if !found || provider == nil { return "" } if name, ok := provider["name"].(string); ok { return name } return "" } // extractMappingStatus extracts the Ready status from a mapping's status.conditions. func extractMappingStatus(mapping unstructured.Unstructured) string { conditions, found, _ := unstructured.NestedSlice(mapping.Object, "status", "conditions") if !found || len(conditions) == 0 { return "" } for _, condition := range conditions { condMap, ok := condition.(map[string]interface{}) if !ok { continue } condType, _ := condMap["type"].(string) if condType == "Ready" { if status, ok := condMap["status"].(string); ok { if status == "True" { return "Ready" } return "Not Ready" } } } return "" } // createMappingItem creates a standardized mapping item for output func createMappingItem(mapping unstructured.Unstructured, mappingType string, useUTC bool) map[string]interface{} { item := map[string]interface{}{ "name": mapping.GetName(), "namespace": mapping.GetNamespace(), "type": mappingType, "source": extractProviderName(mapping, "source"), "target": extractProviderName(mapping, "destination"), "status": extractMappingStatus(mapping), "created": output.FormatTimestamp(mapping.GetCreationTimestamp().Time, useUTC), "object": mapping.Object, // Include the original object } // Add owner information if available if len(mapping.GetOwnerReferences()) > 0 { ownerRef := mapping.GetOwnerReferences()[0] item["owner"] = ownerRef.Name item["ownerKind"] = ownerRef.Kind } return item } // ListMappings lists network and storage mappings without watch functionality func ListMappings(ctx context.Context, configFlags *genericclioptions.ConfigFlags, mappingType, namespace, outputFormat string, mappingName string, useUTC bool) error { return listMappings(ctx, configFlags, mappingType, namespace, outputFormat, mappingName, useUTC) } // getNetworkMappings retrieves all network mappings from the given namespace func getNetworkMappings(ctx context.Context, dynamicClient dynamic.Interface, namespace string, useUTC bool) ([]map[string]interface{}, error) { var networks *unstructured.UnstructuredList var err error if namespace != "" { networks, err = dynamicClient.Resource(client.NetworkMapGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { networks, err = dynamicClient.Resource(client.NetworkMapGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list network mappings: %v", err) } var items []map[string]interface{} for _, mappingItem := range networks.Items { item := createMappingItem(mappingItem, "NetworkMap", useUTC) items = append(items, item) } return items, nil } // getStorageMappings retrieves all storage mappings from the given namespace func getStorageMappings(ctx context.Context, dynamicClient dynamic.Interface, namespace string, useUTC bool) ([]map[string]interface{}, error) { var storage *unstructured.UnstructuredList var err error if namespace != "" { storage, err = dynamicClient.Resource(client.StorageMapGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { storage, err = dynamicClient.Resource(client.StorageMapGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list storage mappings: %v", err) } var items []map[string]interface{} for _, mappingItem := range storage.Items { item := createMappingItem(mappingItem, "StorageMap", useUTC) items = append(items, item) } return items, nil } // getSpecificNetworkMapping retrieves a specific network mapping by name func getSpecificNetworkMapping(ctx context.Context, dynamicClient dynamic.Interface, namespace, mappingName string, useUTC bool) ([]map[string]interface{}, error) { if namespace != "" { // If namespace is specified, get the specific resource networkMap, err := dynamicClient.Resource(client.NetworkMapGVR).Namespace(namespace).Get(ctx, mappingName, metav1.GetOptions{}) if err != nil { return nil, err } item := createMappingItem(*networkMap, "NetworkMap", useUTC) return []map[string]interface{}{item}, nil } else { // If no namespace specified, list all and filter by name networks, err := dynamicClient.Resource(client.NetworkMapGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) if err != nil { return nil, fmt.Errorf("failed to list network mappings: %v", err) } var items []map[string]interface{} for _, mapping := range networks.Items { if mapping.GetName() == mappingName { item := createMappingItem(mapping, "NetworkMap", useUTC) items = append(items, item) } } if len(items) == 0 { return nil, fmt.Errorf("network mapping '%s' not found", mappingName) } return items, nil } } // getSpecificStorageMapping retrieves a specific storage mapping by name func getSpecificStorageMapping(ctx context.Context, dynamicClient dynamic.Interface, namespace, mappingName string, useUTC bool) ([]map[string]interface{}, error) { if namespace != "" { // If namespace is specified, get the specific resource storageMap, err := dynamicClient.Resource(client.StorageMapGVR).Namespace(namespace).Get(ctx, mappingName, metav1.GetOptions{}) if err != nil { return nil, err } item := createMappingItem(*storageMap, "StorageMap", useUTC) return []map[string]interface{}{item}, nil } else { // If no namespace specified, list all and filter by name storage, err := dynamicClient.Resource(client.StorageMapGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) if err != nil { return nil, fmt.Errorf("failed to list storage mappings: %v", err) } var items []map[string]interface{} for _, mapping := range storage.Items { if mapping.GetName() == mappingName { item := createMappingItem(mapping, "StorageMap", useUTC) items = append(items, item) } } if len(items) == 0 { return nil, fmt.Errorf("storage mapping '%s' not found", mappingName) } return items, nil } } // getSpecificAllMappings retrieves a specific mapping by name from both network and storage mappings func getSpecificAllMappings(ctx context.Context, dynamicClient dynamic.Interface, namespace, mappingName string, useUTC bool) ([]map[string]interface{}, error) { var allItems []map[string]interface{} // Try both types if no specific type is specified // First try network mapping networkItems, err := getSpecificNetworkMapping(ctx, dynamicClient, namespace, mappingName, useUTC) if err == nil && len(networkItems) > 0 { allItems = append(allItems, networkItems...) } // Then try storage mapping storageItems, err := getSpecificStorageMapping(ctx, dynamicClient, namespace, mappingName, useUTC) if err == nil && len(storageItems) > 0 { allItems = append(allItems, storageItems...) } // If no mappings found, return error if len(allItems) == 0 { return nil, fmt.Errorf("mapping '%s' not found", mappingName) } return allItems, nil } // getAllMappings retrieves all mappings (network and storage) from the given namespace func getAllMappings(ctx context.Context, dynamicClient dynamic.Interface, namespace string, useUTC bool) ([]map[string]interface{}, error) { var allItems []map[string]interface{} networkItems, err := getNetworkMappings(ctx, dynamicClient, namespace, useUTC) if err != nil { return nil, err } allItems = append(allItems, networkItems...) storageItems, err := getStorageMappings(ctx, dynamicClient, namespace, useUTC) if err != nil { return nil, err } allItems = append(allItems, storageItems...) return allItems, nil } // listMappings lists network and storage mappings func listMappings(ctx context.Context, configFlags *genericclioptions.ConfigFlags, mappingType, namespace, outputFormat string, mappingName string, useUTC bool) error { dynamicClient, err := client.GetDynamicClient(configFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } var allItems []map[string]interface{} // If mappingName is specified, get that specific mapping if mappingName != "" { // Get specific mapping based on type switch mappingType { case "", "all": allItems, err = getSpecificAllMappings(ctx, dynamicClient, namespace, mappingName, useUTC) case "network": allItems, err = getSpecificNetworkMapping(ctx, dynamicClient, namespace, mappingName, useUTC) case "storage": allItems, err = getSpecificStorageMapping(ctx, dynamicClient, namespace, mappingName, useUTC) default: return fmt.Errorf("unsupported mapping type: %s. Supported types: network, storage, all", mappingType) } } else { // Get mappings based on the requested type switch mappingType { case "network": allItems, err = getNetworkMappings(ctx, dynamicClient, namespace, useUTC) case "storage": allItems, err = getStorageMappings(ctx, dynamicClient, namespace, useUTC) case "", "all": allItems, err = getAllMappings(ctx, dynamicClient, namespace, useUTC) default: return fmt.Errorf("unsupported mapping type: %s. Supported types: network, storage, all", mappingType) } } // Handle error if no items found if err != nil { return err } // Handle output based on format switch outputFormat { case "json": jsonPrinter := output.NewJSONPrinter(). WithPrettyPrint(true). AddItems(allItems) if len(allItems) == 0 { return jsonPrinter.PrintEmpty("No mappings found in namespace " + namespace) } return jsonPrinter.Print() case "yaml": yamlPrinter := output.NewYAMLPrinter(). AddItems(allItems) if len(allItems) == 0 { return yamlPrinter.PrintEmpty("No mappings found in namespace " + namespace) } return yamlPrinter.Print() default: // Table output (default) var headers []output.Header // Add NAME column first headers = append(headers, output.Header{DisplayName: "NAME", JSONPath: "name"}) // Add NAMESPACE column after NAME when listing across all namespaces if namespace == "" { headers = append(headers, output.Header{DisplayName: "NAMESPACE", JSONPath: "namespace"}) } // Add remaining columns headers = append(headers, output.Header{DisplayName: "TYPE", JSONPath: "type"}, output.Header{DisplayName: "SOURCE", JSONPath: "source"}, output.Header{DisplayName: "TARGET", JSONPath: "target"}, output.Header{DisplayName: "STATUS", JSONPath: "status"}, output.Header{DisplayName: "OWNER", JSONPath: "owner"}, output.Header{DisplayName: "CREATED", JSONPath: "created"}, ) tablePrinter := output.NewTablePrinter().WithHeaders(headers...).AddItems(allItems) if len(allItems) == 0 { return tablePrinter.PrintEmpty("No mappings found in namespace " + namespace) } return tablePrinter.Print() } } // List lists network and storage mappings with optional watch mode func List(ctx context.Context, configFlags *genericclioptions.ConfigFlags, mappingType, namespace string, watchMode bool, outputFormat string, mappingName string, useUTC bool) error { return watch.WrapWithWatch(watchMode, outputFormat, func() error { return ListMappings(ctx, configFlags, mappingType, namespace, outputFormat, mappingName, useUTC) }, watch.DefaultInterval) }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/plan/helpers.go
Go
package plan import ( "fmt" "strings" "time" "unicode/utf8" ) // FormatTime formats a timestamp string with optional UTC conversion func FormatTime(timestamp string, useUTC bool) string { if timestamp == "" { return "N/A" } // Parse the timestamp t, err := time.Parse(time.RFC3339, timestamp) if err != nil { return timestamp } // Convert to UTC or local time as requested if useUTC { t = t.UTC() } else { t = t.Local() } // Format as "2006-01-02 15:04:05" return t.Format("2006-01-02 15:04:05") } // PrintTable prints a table with headers and rows func PrintTable(headers []string, rows [][]string, colWidths []int) { if len(headers) == 0 { return } // Calculate optimal column widths widths := calculateColumnWidths(headers, rows, colWidths) // Print headers printTableRow(headers, widths, 2) // Print separator line printTableSeparator(widths, 2) // Print data rows for _, row := range rows { printTableRow(row, widths, 2) } } // calculateColumnWidths determines optimal width for each column func calculateColumnWidths(headers []string, rows [][]string, colWidths []int) []int { widths := make([]int, len(headers)) // If specific column widths are provided, use them directly if len(colWidths) == len(headers) { copy(widths, colWidths) return widths } // Initialize with minimum widths minWidth := 8 for i := range widths { widths[i] = minWidth } // Check header widths for i, header := range headers { headerLen := utf8.RuneCountInString(stripAnsiCodes(header)) if headerLen > widths[i] { widths[i] = headerLen } } // Check data cell widths for _, row := range rows { for i, cell := range row { if i < len(widths) { cellLen := utf8.RuneCountInString(stripAnsiCodes(cell)) if cellLen > widths[i] { widths[i] = cellLen } } } } return widths } // printTableRow prints a single row with proper alignment func printTableRow(row []string, widths []int, padding int) { for i := 0; i < len(widths); i++ { var cell string if i < len(row) { cell = row[i] } // If row has fewer cells than headers, cell will be empty string // Truncate cell if it exceeds the column width displayCell := truncateCell(cell, widths[i]) // Print cell with proper alignment considering ANSI color codes printCellWithAlignment(displayCell, widths[i]) // Add padding between columns (except for last column) if i < len(widths)-1 { fmt.Print(strings.Repeat(" ", padding)) } } fmt.Println() } // printCellWithAlignment prints a cell with correct alignment accounting for ANSI escape codes func printCellWithAlignment(cell string, width int) { // Calculate visual length (without ANSI codes) for proper spacing stripped := stripAnsiCodes(cell) visualLen := utf8.RuneCountInString(stripped) // Print the cell content with ANSI colors preserved fmt.Print(cell) // Pad with spaces to reach the target column width if visualLen < width { spacesNeeded := width - visualLen fmt.Print(strings.Repeat(" ", spacesNeeded)) } } // printTableSeparator prints the separator line between headers and data func printTableSeparator(widths []int, padding int) { for i, width := range widths { fmt.Print(strings.Repeat("-", width)) // Add padding between columns (except for last column) if i < len(widths)-1 { fmt.Print(strings.Repeat(" ", padding)) } } fmt.Println() } // truncateCell truncates a cell to fit within the specified width func truncateCell(cell string, maxWidth int) string { // Strip ANSI codes for length calculation, but preserve them in output stripped := stripAnsiCodes(cell) if utf8.RuneCountInString(stripped) <= maxWidth { return cell } // Handle text containing ANSI color codes if len(cell) != len(stripped) { // Preserve ANSI codes while truncating text content if maxWidth > 3 { // Conservative truncation for colored text return cell[:min(len(cell), maxWidth*2)] } return cell[:min(len(cell), maxWidth)] } // Plain text - safe to truncate if maxWidth > 3 { runes := []rune(cell) return string(runes[:maxWidth-3]) + "..." } runes := []rune(cell) return string(runes[:maxWidth]) } // stripAnsiCodes removes ANSI escape sequences for length calculation func stripAnsiCodes(s string) string { result := strings.Builder{} inEscape := false for _, r := range s { if r == '\033' { // Start of ANSI escape sequence inEscape = true continue } if inEscape { if r == 'm' { // End of color code inEscape = false } continue } result.WriteRune(r) } return result.String() } // min returns the minimum of two integers func min(a, b int) int { if a < b { return a } return b }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/plan/list.go
Go
package plan import ( "context" "fmt" "strings" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/dynamic" "github.com/yaacov/kubectl-mtv/pkg/cmd/get/plan/status" "github.com/yaacov/kubectl-mtv/pkg/util/client" "github.com/yaacov/kubectl-mtv/pkg/util/output" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // getPlans retrieves all plans from the given namespace func getPlans(ctx context.Context, dynamicClient dynamic.Interface, namespace string) (*unstructured.UnstructuredList, error) { if namespace != "" { return dynamicClient.Resource(client.PlansGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { return dynamicClient.Resource(client.PlansGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } } // getSpecificPlan retrieves a specific plan by name func getSpecificPlan(ctx context.Context, dynamicClient dynamic.Interface, namespace, planName string) (*unstructured.UnstructuredList, error) { if namespace != "" { // If namespace is specified, get the specific resource plan, err := dynamicClient.Resource(client.PlansGVR).Namespace(namespace).Get(ctx, planName, metav1.GetOptions{}) if err != nil { return nil, err } // Create a list with just this plan return &unstructured.UnstructuredList{ Items: []unstructured.Unstructured{*plan}, }, nil } else { // If no namespace specified, list all and filter by name plans, err := dynamicClient.Resource(client.PlansGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) if err != nil { return nil, fmt.Errorf("failed to list plans: %v", err) } var filteredItems []unstructured.Unstructured for _, plan := range plans.Items { if plan.GetName() == planName { filteredItems = append(filteredItems, plan) } } if len(filteredItems) == 0 { return nil, fmt.Errorf("plan '%s' not found", planName) } return &unstructured.UnstructuredList{ Items: filteredItems, }, nil } } // ListPlans lists migration plans without watch functionality func ListPlans(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string, outputFormat string, planName string, useUTC bool) error { c, err := client.GetDynamicClient(configFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } var plans *unstructured.UnstructuredList if planName != "" { // Get specific plan by name plans, err = getSpecificPlan(ctx, c, namespace, planName) if err != nil { return fmt.Errorf("failed to get plan: %v", err) } } else { // Get all plans plans, err = getPlans(ctx, c, namespace) if err != nil { return fmt.Errorf("failed to list plans: %v", err) } } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } // Create printer items items := []map[string]interface{}{} for _, p := range plans.Items { source, _, _ := unstructured.NestedString(p.Object, "spec", "provider", "source", "name") target, _, _ := unstructured.NestedString(p.Object, "spec", "provider", "destination", "name") vms, _, _ := unstructured.NestedSlice(p.Object, "spec", "vms") creationTime := p.GetCreationTimestamp() // Get archived status archived, exists, _ := unstructured.NestedBool(p.Object, "spec", "archived") if !exists { archived = false } // Get plan details (ready, running migration, status) planDetails, _ := status.GetPlanDetails(c, namespace, &p, client.MigrationsGVR) // Format the VM migration status var vmStatus string if planDetails.RunningMigration != nil && planDetails.VMStats.Total > 0 { vmStatus = fmt.Sprintf("%d/%d (S:%d/F:%d/C:%d)", planDetails.VMStats.Completed, planDetails.VMStats.Total, planDetails.VMStats.Succeeded, planDetails.VMStats.Failed, planDetails.VMStats.Canceled) } else { vmStatus = fmt.Sprintf("%d", len(vms)) } // Format the disk transfer progress progressStatus := "-" if planDetails.RunningMigration != nil && planDetails.DiskProgress.Total > 0 { percentage := float64(planDetails.DiskProgress.Completed) / float64(planDetails.DiskProgress.Total) * 100 progressStatus = fmt.Sprintf("%.1f%% (%d/%d GB)", percentage, planDetails.DiskProgress.Completed/(1024), // Convert to GB planDetails.DiskProgress.Total/(1024)) // Convert to GB } // Determine migration type and cutover information cutoverInfo := "cold" // Default for cold migration // First check the new 'type' field migrationType, exists, _ := unstructured.NestedString(p.Object, "spec", "type") if exists && migrationType != "" { cutoverInfo = migrationType } else { // Fall back to legacy 'warm' boolean field warm, exists, _ := unstructured.NestedBool(p.Object, "spec", "warm") if exists && warm { cutoverInfo = "warm" } } // For warm migrations, check if there's a specific cutover time if cutoverInfo == "warm" && planDetails.RunningMigration != nil { // Extract cutover time from running migration cutoverTimeStr, exists, _ := unstructured.NestedString(planDetails.RunningMigration.Object, "spec", "cutover") if exists && cutoverTimeStr != "" { // Parse the cutover time string cutoverTime, err := time.Parse(time.RFC3339, cutoverTimeStr) if err == nil { cutoverInfo = output.FormatTimestamp(cutoverTime, useUTC) } } } // Create a new printer item item := map[string]interface{}{ "metadata": map[string]interface{}{ "name": p.GetName(), "namespace": p.GetNamespace(), }, "source": source, "target": target, "created": output.FormatTimestamp(creationTime.Time, useUTC), "vms": vmStatus, "ready": fmt.Sprintf("%t", planDetails.IsReady), "running": fmt.Sprintf("%t", planDetails.RunningMigration != nil), "status": planDetails.Status, "progress": progressStatus, "cutover": cutoverInfo, "archived": fmt.Sprintf("%t", archived), "object": p.Object, // Include the original object } // Add the item to the list items = append(items, item) } // Handle different output formats switch outputFormat { case "json": // Use JSON printer jsonPrinter := output.NewJSONPrinter(). WithPrettyPrint(true). AddItems(items) if len(plans.Items) == 0 { return jsonPrinter.PrintEmpty("No plans found in namespace " + namespace) } return jsonPrinter.Print() case "yaml": // Use YAML printer yamlPrinter := output.NewYAMLPrinter(). AddItems(items) if len(plans.Items) == 0 { return yamlPrinter.PrintEmpty("No plans found in namespace " + namespace) } return yamlPrinter.Print() } // Use Table printer (default) var headers []output.Header // Add NAME column first headers = append(headers, output.Header{DisplayName: "NAME", JSONPath: "metadata.name"}) // Add NAMESPACE column after NAME when listing across all namespaces if namespace == "" { headers = append(headers, output.Header{DisplayName: "NAMESPACE", JSONPath: "metadata.namespace"}) } // Add remaining columns headers = append(headers, output.Header{DisplayName: "SOURCE", JSONPath: "source"}, output.Header{DisplayName: "TARGET", JSONPath: "target"}, output.Header{DisplayName: "VMS", JSONPath: "vms"}, output.Header{DisplayName: "READY", JSONPath: "ready"}, output.Header{DisplayName: "STATUS", JSONPath: "status"}, output.Header{DisplayName: "PROGRESS", JSONPath: "progress"}, output.Header{DisplayName: "CUTOVER", JSONPath: "cutover"}, output.Header{DisplayName: "ARCHIVED", JSONPath: "archived"}, output.Header{DisplayName: "CREATED", JSONPath: "created"}, ) tablePrinter := output.NewTablePrinter().WithHeaders(headers...).AddItems(items) if len(plans.Items) == 0 { if err := tablePrinter.PrintEmpty("No plans found in namespace " + namespace); err != nil { return fmt.Errorf("error printing empty table: %v", err) } } else { if err := tablePrinter.Print(); err != nil { return fmt.Errorf("error printing table: %v", err) } } return nil } // List lists migration plans with optional watch mode func List(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string, watchMode bool, outputFormat string, planName string, useUTC bool) error { return watch.WrapWithWatch(watchMode, outputFormat, func() error { return ListPlans(ctx, configFlags, namespace, outputFormat, planName, useUTC) }, watch.DefaultInterval) }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/plan/status/status.go
Go
package status import ( "context" "fmt" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" ) // Migration status constants const ( StatusRunning = "Running" StatusFailed = "Failed" StatusSucceeded = "Succeeded" StatusCanceled = "Canceled" StatusUnknown = "-" StatusExecuting = "Executing" StatusCompleted = "Completed" ) // IsPlanReady checks if a migration plan is ready func IsPlanReady(plan *unstructured.Unstructured) (bool, error) { conditions, exists, err := unstructured.NestedSlice(plan.Object, "status", "conditions") if err != nil { return false, fmt.Errorf("failed to get plan conditions: %v", err) } if !exists { return false, fmt.Errorf("migration plan status conditions not found") } for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") if condType == "Ready" && condStatus == "True" { return true, nil } } return false, nil } // GetRunningMigration checks for migrations associated with the given plan and returns // the currently running migration if one exists, along with the most recent migration. func GetRunningMigration( client dynamic.Interface, namespace string, plan *unstructured.Unstructured, migrationsGVR schema.GroupVersionResource, ) (*unstructured.Unstructured, *unstructured.Unstructured, error) { // Get the plan UID planUID, found, err := unstructured.NestedString(plan.Object, "metadata", "uid") if !found || err != nil { return nil, nil, fmt.Errorf("failed to get plan UID: %v", err) } // Get all migrations in the namespace migrationList, err := client.Resource(migrationsGVR). Namespace(namespace). List(context.TODO(), metav1.ListOptions{}) if err != nil { return nil, nil, fmt.Errorf("failed to list migrations: %v", err) } var latestMigration *unstructured.Unstructured var latestTimestamp metav1.Time // Check each migration for i := range migrationList.Items { migration := &migrationList.Items[i] // Check if this migration references our plan planRef, found, _ := unstructured.NestedMap(migration.Object, "spec", "plan") if !found { continue } refUID, found, _ := unstructured.NestedString(planRef, "uid") if !found || refUID != planUID { continue } // Update latest migration if this one is newer creationTime := migration.GetCreationTimestamp() if latestMigration == nil || creationTime.After(latestTimestamp.Time) { latestMigration = migration latestTimestamp = creationTime } // Check if the migration is running conditions, exists, err := unstructured.NestedSlice(migration.Object, "status", "conditions") if err != nil || !exists { continue } for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") if condType == "Running" && condStatus == "True" { return migration, nil, nil } } } return nil, latestMigration, nil } // GetPlanStatus returns the status of a plan func GetPlanStatus(plan *unstructured.Unstructured) (string, error) { conditions, exists, err := unstructured.NestedSlice(plan.Object, "status", "conditions") if err != nil { return StatusUnknown, fmt.Errorf("failed to get plan conditions: %v", err) } if !exists { return StatusUnknown, fmt.Errorf("plan status conditions not found") } // Check all conditions with correct precedence for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") if condStatus != "True" { continue } // Return first condition that matches the current status switch condType { case StatusFailed: return StatusFailed, nil case StatusSucceeded: return StatusSucceeded, nil case StatusCanceled: return StatusCanceled, nil case StatusRunning: return StatusRunning, nil case StatusExecuting: return StatusExecuting, nil } } return StatusUnknown, nil } // VMStats contains statistics about VMs in a migration type VMStats struct { Total int Completed int Succeeded int Failed int Canceled int } // GetVMStats extracts VM migration statistics from a migration object func GetVMStats(migration *unstructured.Unstructured) (VMStats, error) { stats := VMStats{} // Get the list of VMs from the migration status vms, exists, err := unstructured.NestedSlice(migration.Object, "status", "vms") if err != nil { return stats, fmt.Errorf("failed to get VM list: %v", err) } if !exists || len(vms) == 0 { return stats, nil } // Update total VM count stats.Total = len(vms) // Check each VM's status for _, v := range vms { vm, ok := v.(map[string]interface{}) if !ok { continue } // Check if the VM migration phase is completed phase, _, _ := unstructured.NestedString(vm, "phase") if phase == "Completed" { stats.Completed++ // Check conditions to determine success/failure/canceled conditions, exists, _ := unstructured.NestedSlice(vm, "conditions") if !exists { continue } for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") if condStatus == "True" { switch condType { case StatusSucceeded: stats.Succeeded++ case StatusFailed: stats.Failed++ case StatusCanceled: stats.Canceled++ } } } } } return stats, nil } // ProgressStats contains progress information for disk transfers type ProgressStats struct { Completed int64 Total int64 } // GetDiskTransferProgress extracts disk transfer progress from a migration object func GetDiskTransferProgress(migration *unstructured.Unstructured) (ProgressStats, error) { stats := ProgressStats{} // Get the list of VMs from the migration status vms, exists, err := unstructured.NestedSlice(migration.Object, "status", "vms") if err != nil { return stats, fmt.Errorf("failed to get VM list: %v", err) } if !exists || len(vms) == 0 { return stats, nil } // Check each VM's pipeline for disk transfer progress for _, v := range vms { vm, ok := v.(map[string]interface{}) if !ok { continue } // Get the pipeline pipeline, exists, _ := unstructured.NestedSlice(vm, "pipeline") if !exists { continue } // Look for disk transfer phases for _, p := range pipeline { phase, ok := p.(map[string]interface{}) if !ok { continue } // Check if this is a disk transfer phase name, _, _ := unstructured.NestedString(phase, "name") if name == "" || !strings.HasPrefix(name, "DiskTransfer") { continue } // Extract progress information completed, found, _ := unstructured.NestedInt64(phase, "progress", "completed") if found { stats.Completed += completed } total, found, _ := unstructured.NestedInt64(phase, "progress", "total") if found { stats.Total += total } } } return stats, nil } // PlanDetails contains all relevant status information for a plan type PlanDetails struct { IsReady bool RunningMigration *unstructured.Unstructured LatestMigration *unstructured.Unstructured Status string VMStats VMStats DiskProgress ProgressStats } // GetPlanDetails returns all details about a plan's status in a single call func GetPlanDetails( client dynamic.Interface, namespace string, plan *unstructured.Unstructured, migrationsGVR schema.GroupVersionResource, ) (PlanDetails, error) { details := PlanDetails{} // Get if plan is ready ready, err := IsPlanReady(plan) if err != nil { return details, err } details.IsReady = ready // Get if plan has running migration runningMigration, latestMigration, err := GetRunningMigration(client, namespace, plan, migrationsGVR) if err != nil { return details, err } details.RunningMigration = runningMigration // Get plan status status, err := GetPlanStatus(plan) if err != nil { return details, err } details.Status = status // If there's a running migration, get VM stats if runningMigration != nil { details.RunningMigration = runningMigration // Found the migration for this plan, get VM stats vmStats, _ := GetVMStats(runningMigration) details.VMStats = vmStats // Get disk transfer progress diskProgress, _ := GetDiskTransferProgress(runningMigration) details.DiskProgress = diskProgress } if latestMigration != nil { details.LatestMigration = latestMigration // Found the migration for this plan, get VM stats vmStats, _ := GetVMStats(latestMigration) details.VMStats = vmStats // Get disk transfer progress diskProgress, _ := GetDiskTransferProgress(latestMigration) details.DiskProgress = diskProgress } return details, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/plan/vms.go
Go
package plan import ( "context" "fmt" "strings" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/cmd/get/plan/status" "github.com/yaacov/kubectl-mtv/pkg/util/client" "github.com/yaacov/kubectl-mtv/pkg/util/output" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // formatDuration calculates and formats the duration between two ISO timestamps func formatDuration(startedStr, completedStr string) string { if startedStr == "" || startedStr == "-" || completedStr == "" || completedStr == "-" { return "-" } started, err := time.Parse(time.RFC3339, startedStr) if err != nil { started, err = time.Parse(time.RFC3339Nano, startedStr) if err != nil { return "-" } } completed, err := time.Parse(time.RFC3339, completedStr) if err != nil { completed, err = time.Parse(time.RFC3339Nano, completedStr) if err != nil { return "-" } } duration := completed.Sub(started) if duration < 0 { return "-" } if duration < time.Minute { return fmt.Sprintf("%ds", int(duration.Seconds())) } else if duration < time.Hour { minutes := int(duration.Minutes()) seconds := int(duration.Seconds()) % 60 return fmt.Sprintf("%dm%ds", minutes, seconds) } hours := int(duration.Hours()) minutes := int(duration.Minutes()) % 60 return fmt.Sprintf("%dh%dm", hours, minutes) } // formatDiskSize formats size as human-readable based on unit func formatDiskSize(size int64, unit string) string { if size <= 0 { return "-" } switch unit { case "MB": return fmt.Sprintf("%.1f GB", float64(size)/1024.0) case "GB": return fmt.Sprintf("%.1f GB", float64(size)) case "KB": return fmt.Sprintf("%.1f GB", float64(size)/(1024.0*1024.0)) default: const gb = 1024 * 1024 * 1024 return fmt.Sprintf("%.1f GB", float64(size)/float64(gb)) } } // getVMCompletionStatus determines if a completed VM succeeded, failed, or was canceled func getVMCompletionStatus(vm map[string]interface{}) string { conditions, exists, _ := unstructured.NestedSlice(vm, "conditions") if !exists { return status.StatusUnknown } for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") if condStatus == "True" { switch condType { case status.StatusSucceeded: return status.StatusSucceeded case status.StatusFailed: return status.StatusFailed case status.StatusCanceled: return status.StatusCanceled case status.StatusCompleted: return status.StatusCompleted } } } return status.StatusUnknown } // printHeader prints the migration plan header func printHeader(planName, migrationName, title string) { fmt.Print("\n", output.ColorizedSeparator(105, output.YellowColor)) fmt.Printf("\n%s\n", output.Bold(title)) fmt.Printf("%s %s\n", output.Bold("Plan:"), output.Yellow(planName)) fmt.Printf("%s %s\n", output.Bold("Migration:"), output.Yellow(migrationName)) } // printNoMigrationMessage prints message when no migration is found func printNoMigrationMessage(planName string, plan *unstructured.Unstructured) { fmt.Printf("%s %s\n\n", output.Bold("Plan:"), output.Yellow(planName)) fmt.Println("No migration information found. Details will be available after the plan starts running.") specVMs, exists, err := unstructured.NestedSlice(plan.Object, "spec", "vms") if err == nil && exists && len(specVMs) > 0 { fmt.Printf("\n%s\n", output.Bold("Plan VM Specifications:")) headers := []string{"NAME", "ID"} colWidths := []int{40, 20} rows := make([][]string, 0, len(specVMs)) for _, v := range specVMs { vm, ok := v.(map[string]interface{}) if !ok { continue } vmName, _, _ := unstructured.NestedString(vm, "name") vmID, _, _ := unstructured.NestedString(vm, "id") rows = append(rows, []string{output.Yellow(vmName), output.Cyan(vmID)}) } PrintTable(headers, rows, colWidths) } } // printVMInfo prints the VM basic information header func printVMInfo(vm map[string]interface{}, showOS bool) string { vmName, _, _ := unstructured.NestedString(vm, "name") vmID, _, _ := unstructured.NestedString(vm, "id") vmPhase, _, _ := unstructured.NestedString(vm, "phase") vmOS, _, _ := unstructured.NestedString(vm, "operatingSystem") started, _, _ := unstructured.NestedString(vm, "started") completed, _, _ := unstructured.NestedString(vm, "completed") vmCompletionStatus := getVMCompletionStatus(vm) fmt.Print("\n", output.ColorizedSeparator(105, output.CyanColor)) fmt.Printf("\n%s %s (%s %s)\n", output.Bold("VM:"), output.Yellow(vmName), output.Bold("vmID="), output.Cyan(vmID)) fmt.Printf("%s %s %s %s\n", output.Bold("Phase:"), output.ColorizeStatus(vmPhase), output.Bold("Status:"), output.ColorizeStatus(vmCompletionStatus)) if showOS && vmOS != "" { fmt.Printf("%s %s\n", output.Bold("OS:"), output.Blue(vmOS)) } if started != "" { fmt.Printf("%s %s", output.Bold("Started:"), output.Blue(started)) if completed != "" { fmt.Printf(" %s %s", output.Bold("Completed:"), output.Green(completed)) } fmt.Println() } return vmCompletionStatus } // printPipelineTable prints the pipeline table for a VM func printPipelineTable(vm map[string]interface{}, vmCompletionStatus string) { pipeline, exists, _ := unstructured.NestedSlice(vm, "pipeline") if !exists || len(pipeline) == 0 { fmt.Println("No pipeline information available.") return } fmt.Printf("\n%s\n", output.Bold("Pipeline:")) headers := []string{"PHASE", "NAME", "STARTED", "COMPLETED", "PROGRESS"} colWidths := []int{15, 25, 25, 25, 15} rows := make([][]string, 0, len(pipeline)) for _, p := range pipeline { phase, ok := p.(map[string]interface{}) if !ok { continue } phaseName, _, _ := unstructured.NestedString(phase, "name") phaseStatus, _, _ := unstructured.NestedString(phase, "phase") phaseStarted, _, _ := unstructured.NestedString(phase, "started") phaseCompleted, _, _ := unstructured.NestedString(phase, "completed") progress := "-" progressMap, progressExists, _ := unstructured.NestedMap(phase, "progress") percentage := -1.0 if phaseStatus == status.StatusCompleted { percentage = 100.0 } else if progressExists { progCompleted, _, _ := unstructured.NestedInt64(progressMap, "completed") progTotal, _, _ := unstructured.NestedInt64(progressMap, "total") if progTotal > 0 { percentage = float64(progCompleted) / float64(progTotal) * 100 if percentage > 100.0 { percentage = 100.0 } } } if percentage >= 0 { progressText := fmt.Sprintf("%14.1f%%", percentage) switch vmCompletionStatus { case status.StatusFailed: progress = output.Red(progressText) case status.StatusCanceled: progress = output.Yellow(progressText) case status.StatusSucceeded, status.StatusCompleted: progress = output.Green(progressText) default: progress = output.Cyan(progressText) } } rows = append(rows, []string{ output.ColorizeStatus(phaseStatus), output.Bold(phaseName), phaseStarted, phaseCompleted, progress, }) } PrintTable(headers, rows, colWidths) } // printDisksTable prints the disk transfer table for a VM func printDisksTable(vm map[string]interface{}, vmCompletionStatus string) { pipeline, exists, _ := unstructured.NestedSlice(vm, "pipeline") if !exists || len(pipeline) == 0 { return } for _, p := range pipeline { phase, ok := p.(map[string]interface{}) if !ok { continue } phaseName, _, _ := unstructured.NestedString(phase, "name") if !strings.HasPrefix(phaseName, "DiskTransfer") { continue } phaseStatus, _, _ := unstructured.NestedString(phase, "phase") phaseStarted, _, _ := unstructured.NestedString(phase, "started") phaseCompleted, _, _ := unstructured.NestedString(phase, "completed") tasks, tasksExist, _ := unstructured.NestedSlice(phase, "tasks") if !tasksExist || len(tasks) == 0 { continue } fmt.Printf("\n%s %s\n", output.Bold("Disk Transfers:"), output.Yellow(phaseName)) headers := []string{"NAME", "PHASE", "PROGRESS", "SIZE", "DURATION", "STARTED", "COMPLETED"} colWidths := []int{35, 12, 12, 12, 10, 22, 22} rows := make([][]string, 0, len(tasks)) phaseAnnotations, _, _ := unstructured.NestedStringMap(phase, "annotations") phaseUnit := phaseAnnotations["unit"] for _, t := range tasks { task, ok := t.(map[string]interface{}) if !ok { continue } taskName, _, _ := unstructured.NestedString(task, "name") taskPhase, _, _ := unstructured.NestedString(task, "phase") taskStartedStr, _, _ := unstructured.NestedString(task, "started") taskCompletedStr, _, _ := unstructured.NestedString(task, "completed") if taskPhase == "" { taskPhase = phaseStatus } if len(taskName) > colWidths[0] { taskName = taskName[:colWidths[0]-3] + "..." } taskAnnotations, _, _ := unstructured.NestedStringMap(task, "annotations") taskUnit := taskAnnotations["unit"] if taskUnit == "" { taskUnit = phaseUnit } progress := "-" size := "-" taskProgressMap, taskProgressExists, _ := unstructured.NestedMap(task, "progress") if taskProgressExists { taskProgCompleted, _, _ := unstructured.NestedInt64(taskProgressMap, "completed") taskTotal, _, _ := unstructured.NestedInt64(taskProgressMap, "total") if taskTotal > 0 { percentage := float64(taskProgCompleted) / float64(taskTotal) * 100 if percentage > 100.0 { percentage = 100.0 } progressText := fmt.Sprintf("%.1f%%", percentage) switch vmCompletionStatus { case status.StatusFailed: progress = output.Red(progressText) case status.StatusCanceled: progress = output.Yellow(progressText) case status.StatusSucceeded, status.StatusCompleted: progress = output.Green(progressText) default: if percentage >= 100 { progress = output.Green(progressText) } else { progress = output.Cyan(progressText) } } size = formatDiskSize(taskTotal, taskUnit) } } else if taskPhase == status.StatusCompleted { progress = output.Green("100.0%") } startedStr := taskStartedStr if startedStr == "" { startedStr = phaseStarted } if startedStr == "" { startedStr = "-" } completedStr := taskCompletedStr if completedStr == "" && taskPhase == status.StatusCompleted { completedStr = phaseCompleted } if completedStr == "" { completedStr = "-" } duration := formatDuration(startedStr, completedStr) rows = append(rows, []string{ taskName, output.ColorizeStatus(taskPhase), progress, size, duration, startedStr, completedStr, }) } PrintTable(headers, rows, colWidths) } } // getMigrationData retrieves and validates plan and migration data func getMigrationData(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string) (*unstructured.Unstructured, *unstructured.Unstructured, []interface{}, error) { c, err := client.GetDynamicClient(configFlags) if err != nil { return nil, nil, nil, fmt.Errorf("failed to get client: %v", err) } plan, err := c.Resource(client.PlansGVR).Namespace(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, nil, nil, fmt.Errorf("failed to get plan: %v", err) } planDetails, _ := status.GetPlanDetails(c, namespace, plan, client.MigrationsGVR) migration := planDetails.RunningMigration if migration == nil { migration = planDetails.LatestMigration } if migration == nil { return plan, nil, nil, nil } vms, exists, err := unstructured.NestedSlice(migration.Object, "status", "vms") if err != nil { return plan, migration, nil, fmt.Errorf("failed to get VM list: %v", err) } if !exists { return plan, migration, nil, fmt.Errorf("no VMs found in migration status") } return plan, migration, vms, nil } // ListVMs lists all VMs in a migration plan func ListVMs(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string, watchMode bool) error { if watchMode { return watch.Watch(func() error { return listVMsOnce(ctx, configFlags, name, namespace) }, watch.DefaultInterval) } return listVMsOnce(ctx, configFlags, name, namespace) } func listVMsOnce(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string) error { plan, migration, vms, err := getMigrationData(ctx, configFlags, name, namespace) if err != nil { return err } if migration == nil { printNoMigrationMessage(name, plan) return nil } printHeader(name, migration.GetName(), "MIGRATION PLAN") for _, v := range vms { vm, ok := v.(map[string]interface{}) if !ok { continue } vmCompletionStatus := printVMInfo(vm, true) printPipelineTable(vm, vmCompletionStatus) } return nil } // ListDisks lists all disk transfers in a migration plan func ListDisks(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string, watchMode bool) error { if watchMode { return watch.Watch(func() error { return listDisksOnce(ctx, configFlags, name, namespace) }, watch.DefaultInterval) } return listDisksOnce(ctx, configFlags, name, namespace) } func listDisksOnce(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string) error { plan, migration, vms, err := getMigrationData(ctx, configFlags, name, namespace) if err != nil { return err } if migration == nil { printNoMigrationMessage(name, plan) return nil } printHeader(name, migration.GetName(), "MIGRATION PLAN - DISK TRANSFERS") for _, v := range vms { vm, ok := v.(map[string]interface{}) if !ok { continue } vmCompletionStatus := printVMInfo(vm, false) printDisksTable(vm, vmCompletionStatus) } return nil } // ListVMsWithDisks lists all VMs with disk transfer details func ListVMsWithDisks(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string, watchMode bool) error { if watchMode { return watch.Watch(func() error { return listVMsWithDisksOnce(ctx, configFlags, name, namespace) }, watch.DefaultInterval) } return listVMsWithDisksOnce(ctx, configFlags, name, namespace) } func listVMsWithDisksOnce(ctx context.Context, configFlags *genericclioptions.ConfigFlags, name, namespace string) error { plan, migration, vms, err := getMigrationData(ctx, configFlags, name, namespace) if err != nil { return err } if migration == nil { printNoMigrationMessage(name, plan) return nil } printHeader(name, migration.GetName(), "MIGRATION PLAN - VMS WITH DISK DETAILS") for _, v := range vms { vm, ok := v.(map[string]interface{}) if !ok { continue } vmCompletionStatus := printVMInfo(vm, true) printPipelineTable(vm, vmCompletionStatus) printDisksTable(vm, vmCompletionStatus) } return nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/get/provider/list.go
Go
package provider import ( "context" "fmt" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/dynamic" "k8s.io/klog/v2" "github.com/yaacov/kubectl-mtv/pkg/cmd/create/provider/providerutil" "github.com/yaacov/kubectl-mtv/pkg/util/client" "github.com/yaacov/kubectl-mtv/pkg/util/output" "github.com/yaacov/kubectl-mtv/pkg/util/watch" ) // getProviderRelevantFields returns the fields that are relevant for display func getProviderRelevantFields(providerType string) map[string]string { // Map field names to their inventory resource types for counting // All providers show VMS and NETWORKS columns return map[string]string{ "vmCount": "vms", "networkCount": "networks", } } // normalizeProviderInventory ensures all relevant fields exist for a provider // and attempts to count missing fields from inventory if possible func normalizeProviderInventory(ctx context.Context, configFlags *genericclioptions.ConfigFlags, baseURL string, provider *unstructured.Unstructured, item map[string]interface{}, insecureSkipTLS bool) { providerType, _, _ := unstructured.NestedString(provider.Object, "spec", "type") providerName := provider.GetName() // Get relevant fields for this provider type relevantFields := getProviderRelevantFields(providerType) // Process each relevant field for fieldName, resourceType := range relevantFields { // Skip if field already has a value if _, exists := item[fieldName]; exists { continue } // If we have inventory URL and resource type, try to count if baseURL != "" && resourceType != "" { count := countProviderResources(ctx, configFlags, baseURL, provider, resourceType, insecureSkipTLS) if count >= 0 { item[fieldName] = count klog.V(4).Infof("Counted %d %s for %s provider %s", count, resourceType, providerType, providerName) } else { // Counting failed, but this is a relevant field - set to 0 item[fieldName] = 0 klog.V(4).Infof("Failed to count %s for %s provider %s, defaulting to 0", resourceType, providerType, providerName) } } else { // No inventory URL or cannot count this resource type - set to 0 item[fieldName] = 0 } } // For fields that are NOT relevant to this provider, don't add them (leave undefined) // The table printer will show empty cells for undefined fields } // getDynamicInventoryColumns returns consistent inventory columns for all provider types func getDynamicInventoryColumns(providerTypes map[string]bool) []output.Header { // Always return the same essential columns for all providers // This ensures consistent table headers return []output.Header{ {DisplayName: "VMS", JSONPath: "vmCount"}, {DisplayName: "NETWORKS", JSONPath: "networkCount"}, } } // countProviderResources counts resources (vms or networks) for any provider type // Returns -1 if counting fails func countProviderResources(ctx context.Context, configFlags *genericclioptions.ConfigFlags, baseURL string, provider *unstructured.Unstructured, resourceType string, insecureSkipTLS bool) int { // Fetch the resource collection from the provider data, err := client.FetchProviderInventoryWithInsecure(ctx, configFlags, baseURL, provider, resourceType, insecureSkipTLS) if err != nil { klog.V(4).Infof("Failed to fetch %s for provider: %v", resourceType, err) return -1 } // Count the items in the response if dataSlice, ok := data.([]interface{}); ok { return len(dataSlice) } klog.V(4).Infof("Unexpected data format when counting %s for provider", resourceType) return -1 } // getProviders retrieves all providers from the given namespace func getProviders(ctx context.Context, dynamicClient dynamic.Interface, namespace string) (*unstructured.UnstructuredList, error) { if namespace != "" { return dynamicClient.Resource(client.ProvidersGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { return dynamicClient.Resource(client.ProvidersGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } } // getSpecificProvider retrieves a specific provider by name func getSpecificProvider(ctx context.Context, dynamicClient dynamic.Interface, namespace, providerName string) (*unstructured.UnstructuredList, error) { if namespace != "" { // If namespace is specified, get the specific resource provider, err := dynamicClient.Resource(client.ProvidersGVR).Namespace(namespace).Get(ctx, providerName, metav1.GetOptions{}) if err != nil { return nil, err } // Create a list with just this provider return &unstructured.UnstructuredList{ Items: []unstructured.Unstructured{*provider}, }, nil } else { // If no namespace specified, list all and filter by name providers, err := dynamicClient.Resource(client.ProvidersGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) if err != nil { return nil, fmt.Errorf("failed to list providers: %v", err) } var filteredItems []unstructured.Unstructured for _, provider := range providers.Items { if provider.GetName() == providerName { filteredItems = append(filteredItems, provider) } } if len(filteredItems) == 0 { return nil, fmt.Errorf("provider '%s' not found", providerName) } return &unstructured.UnstructuredList{ Items: filteredItems, }, nil } } // ListProviders lists providers without watch functionality func ListProviders(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string, baseURL string, outputFormat string, providerName string, insecureSkipTLS bool) error { c, err := client.GetDynamicClient(configFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } var providers *unstructured.UnstructuredList if providerName != "" { // Get specific provider by name providers, err = getSpecificProvider(ctx, c, namespace, providerName) if err != nil { return fmt.Errorf("failed to get provider: %v", err) } } else { // Get all providers providers, err = getProviders(ctx, c, namespace) if err != nil { return fmt.Errorf("failed to list providers: %v", err) } } // Format validation outputFormat = strings.ToLower(outputFormat) if outputFormat != "table" && outputFormat != "json" && outputFormat != "yaml" { return fmt.Errorf("unsupported output format: %s. Supported formats: table, json, yaml", outputFormat) } // If baseURL is empty, try to discover it from an OpenShift Route if baseURL == "" { route, err := client.GetForkliftInventoryRoute(ctx, configFlags, namespace) if err == nil && route != nil { host, found, _ := unstructured.NestedString(route.Object, "spec", "host") if found && host != "" { baseURL = fmt.Sprintf("https://%s", host) } } } // Fetch bulk provider inventory data var bulkProviderData map[string][]map[string]interface{} if baseURL != "" { // Detail level 1: includes basic inventory counts (vmCount, hostCount, etc.) without full resource lists if bulk, err := client.FetchProvidersWithDetailAndInsecure(ctx, configFlags, baseURL, 1, insecureSkipTLS); err == nil && bulk != nil { if bulkMap, ok := bulk.(map[string]interface{}); ok { bulkProviderData = make(map[string][]map[string]interface{}) // Parse bulk data for each provider type for providerType, providerList := range bulkMap { if providerListSlice, ok := providerList.([]interface{}); ok { var typedProviders []map[string]interface{} for _, p := range providerListSlice { if providerMap, ok := p.(map[string]interface{}); ok { typedProviders = append(typedProviders, providerMap) } } bulkProviderData[providerType] = typedProviders } } } else { klog.V(4).Infof("Failed to parse bulk provider response: expected map, got %T", bulk) } } else { klog.V(4).Infof("Failed to fetch bulk provider data: %v", err) } } // Create printer items with condition statuses incorporated items := []map[string]interface{}{} for i := range providers.Items { provider := &providers.Items[i] // Extract condition statuses conditionStatuses := providerutil.ExtractProviderConditionStatuses(provider.Object) // Create a new printer item with needed fields item := map[string]interface{}{ "metadata": map[string]interface{}{ "name": provider.GetName(), "namespace": provider.GetNamespace(), }, "spec": provider.Object["spec"], "status": provider.Object["status"], "conditionStatuses": map[string]interface{}{ "ConnectionStatus": conditionStatuses.ConnectionStatus, "ValidationStatus": conditionStatuses.ValidationStatus, "InventoryStatus": conditionStatuses.InventoryStatus, "ReadyStatus": conditionStatuses.ReadyStatus, }, "object": provider.Object, // Include the original object } // Extract inventory counts from bulk data if bulkProviderData != nil { providerType, found, _ := unstructured.NestedString(provider.Object, "spec", "type") providerUID := string(provider.GetUID()) providerName := provider.GetName() if found && providerType != "" { if providersList, exists := bulkProviderData[providerType]; exists { // Find matching provider by UID in bulk data providerFound := false for _, bulkProvider := range providersList { if bulkUID, ok := bulkProvider["uid"].(string); ok && bulkUID == providerUID { providerFound = true // Extract inventory counts from bulk data if vmCount, ok := bulkProvider["vmCount"]; ok { item["vmCount"] = vmCount } if hostCount, ok := bulkProvider["hostCount"]; ok { item["hostCount"] = hostCount } if datacenterCount, ok := bulkProvider["datacenterCount"]; ok { item["datacenterCount"] = datacenterCount } if clusterCount, ok := bulkProvider["clusterCount"]; ok { item["clusterCount"] = clusterCount } if networkCount, ok := bulkProvider["networkCount"]; ok { item["networkCount"] = networkCount } if datastoreCount, ok := bulkProvider["datastoreCount"]; ok { item["datastoreCount"] = datastoreCount } if storageClassCount, ok := bulkProvider["storageClassCount"]; ok { item["storageClassCount"] = storageClassCount } if product, ok := bulkProvider["product"]; ok { item["product"] = product } // Add other provider-type specific counts if regionCount, ok := bulkProvider["regionCount"]; ok { item["regionCount"] = regionCount } if projectCount, ok := bulkProvider["projectCount"]; ok { item["projectCount"] = projectCount } if imageCount, ok := bulkProvider["imageCount"]; ok { item["imageCount"] = imageCount } if volumeCount, ok := bulkProvider["volumeCount"]; ok { item["volumeCount"] = volumeCount } if volumeTypeCount, ok := bulkProvider["volumeTypeCount"]; ok { item["volumeTypeCount"] = volumeTypeCount } if diskCount, ok := bulkProvider["diskCount"]; ok { item["diskCount"] = diskCount } if storageCount, ok := bulkProvider["storageCount"]; ok { item["storageCount"] = storageCount } if storageDomainCount, ok := bulkProvider["storageDomainCount"]; ok { item["storageDomainCount"] = storageDomainCount } break } } if !providerFound { klog.V(4).Infof("Provider %s (%s) not found in bulk data", providerName, providerUID) } } else { klog.V(4).Infof("No bulk data available for provider type %s", providerType) } } } // Normalize inventory data: ensure all relevant fields exist for this provider type // and try to count missing fields from inventory if possible normalizeProviderInventory(ctx, configFlags, baseURL, provider, item, insecureSkipTLS) // Add the item to the list items = append(items, item) } // Handle different output formats switch outputFormat { case "json": // Use JSON printer jsonPrinter := output.NewJSONPrinter(). WithPrettyPrint(true). AddItems(items) if len(providers.Items) == 0 { return jsonPrinter.PrintEmpty("No providers found in namespace " + namespace) } return jsonPrinter.Print() case "yaml": // Use YAML printer yamlPrinter := output.NewYAMLPrinter(). AddItems(items) if len(providers.Items) == 0 { return yamlPrinter.PrintEmpty("No providers found in namespace " + namespace) } return yamlPrinter.Print() default: // Use Table printer (default) var headers []output.Header // Add NAME column first headers = append(headers, output.Header{DisplayName: "NAME", JSONPath: "metadata.name"}) // Add NAMESPACE column after NAME when listing across all namespaces if namespace == "" { headers = append(headers, output.Header{DisplayName: "NAMESPACE", JSONPath: "metadata.namespace"}) } // Add common columns headers = append(headers, output.Header{DisplayName: "TYPE", JSONPath: "spec.type"}, output.Header{DisplayName: "URL", JSONPath: "spec.url"}, output.Header{DisplayName: "STATUS", JSONPath: "status.phase"}, output.Header{DisplayName: "CONNECTED", JSONPath: "conditionStatuses.ConnectionStatus"}, output.Header{DisplayName: "INVENTORY", JSONPath: "conditionStatuses.InventoryStatus"}, output.Header{DisplayName: "READY", JSONPath: "conditionStatuses.ReadyStatus"}, ) // Determine which provider types are present providerTypes := make(map[string]bool) for _, item := range items { if spec, ok := item["spec"].(map[string]interface{}); ok { if providerType, ok := spec["type"].(string); ok { providerTypes[providerType] = true } } } // Add dynamic columns based on provider types present headers = append(headers, getDynamicInventoryColumns(providerTypes)...) tablePrinter := output.NewTablePrinter().WithHeaders(headers...).AddItems(items) if len(providers.Items) == 0 { if err := tablePrinter.PrintEmpty("No providers found in namespace " + namespace); err != nil { return fmt.Errorf("error printing empty table: %v", err) } } else { if err := tablePrinter.Print(); err != nil { return fmt.Errorf("error printing table: %v", err) } } } return nil } // List lists providers with optional watch mode func List(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string, baseURL string, watchMode bool, outputFormat string, providerName string, insecureSkipTLS bool) error { return watch.WrapWithWatch(watchMode, outputFormat, func() error { return ListProviders(ctx, configFlags, namespace, baseURL, outputFormat, providerName, insecureSkipTLS) }, watch.DefaultInterval) }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/controller.go
Go
package health import ( "context" "strconv" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // Known FQIN fields in ForkliftController spec var knownFQINFields = []string{ "controller_image_fqin", "api_image_fqin", "validation_image_fqin", "ui_plugin_image_fqin", "must_gather_image_fqin", "virt_v2v_image_fqin", "cli_download_image_fqin", "populator_controller_image_fqin", "populator_ovirt_image_fqin", "populator_openstack_image_fqin", "populator_vsphere_xcopy_volume_image_fqin", "ova_provider_server_fqin", "ova_proxy_fqin", "hyperv_provider_server_fqin", } // CheckControllerHealth checks the health of the ForkliftController CR. // // IMPORTANT: The ForkliftController custom resource ALWAYS exists in the operator // namespace. The caller (health.go) should pass the auto-detected operator // namespace here, NOT a user-specified namespace. func CheckControllerHealth(ctx context.Context, configFlags *genericclioptions.ConfigFlags, operatorNamespace string, hasVSphereProvider bool, hasRemoteOpenShiftProvider bool) (ControllerHealth, error) { health := ControllerHealth{ Found: false, HasVSphereProvider: hasVSphereProvider, HasRemoteOpenShiftProvider: hasRemoteOpenShiftProvider, CustomImages: []ImageOverride{}, } dynamicClient, err := client.GetDynamicClient(configFlags) if err != nil { health.Error = err.Error() return health, err } // Use provided operator namespace or fall back to default ns := operatorNamespace if ns == "" { ns = client.OpenShiftMTVNamespace } // List ForkliftControllers in the namespace controllers, err := dynamicClient.Resource(client.ForkliftControllersGVR).Namespace(ns).List(ctx, metav1.ListOptions{}) if err != nil { health.Error = err.Error() return health, err } if len(controllers.Items) == 0 { return health, nil } // Use the first controller (typically there's only one) controller := &controllers.Items[0] health.Found = true health.Name = controller.GetName() health.Namespace = controller.GetNamespace() // Extract spec fields extractControllerSpec(controller, &health) // Extract status conditions extractControllerStatus(controller, &health) return health, nil } // extractControllerSpec extracts spec fields from ForkliftController func extractControllerSpec(controller *unstructured.Unstructured, health *ControllerHealth) { spec, found, err := unstructured.NestedMap(controller.Object, "spec") if err != nil { // Spec exists but is malformed - could log this in verbose mode return } if !found { return } // Extract feature flags health.FeatureFlags = extractFeatureFlags(spec) // Extract VDDK image if vddkImage, ok := spec["vddk_image"].(string); ok && vddkImage != "" { health.VDDKImage = vddkImage } // Extract controller log level if logLevel, found, err := unstructured.NestedInt64(spec, "controller_log_level"); err == nil && found { health.LogLevel = int(logLevel) } else if logLevelStr, ok := spec["controller_log_level"].(string); ok { if level, err := strconv.Atoi(logLevelStr); err == nil { health.LogLevel = level } } // Extract custom FQIN images for _, field := range knownFQINFields { if image, ok := spec[field].(string); ok && image != "" { health.CustomImages = append(health.CustomImages, ImageOverride{ Field: field, Image: image, }) } } } // extractFeatureFlags extracts feature flag settings from spec func extractFeatureFlags(spec map[string]interface{}) FeatureFlags { flags := FeatureFlags{} // Helper function to parse boolean from string or bool parseBool := func(value interface{}) *bool { if value == nil { return nil } var result bool switch v := value.(type) { case bool: result = v return &result case string: if v == "true" { result = true return &result } else if v == "false" { result = false return &result } } return nil } flags.UIPlugin = parseBool(spec["feature_ui_plugin"]) flags.Validation = parseBool(spec["feature_validation"]) flags.VolumePopulator = parseBool(spec["feature_volume_populator"]) flags.AuthRequired = parseBool(spec["feature_auth_required"]) flags.OCPLiveMigration = parseBool(spec["feature_ocp_live_migration"]) return flags } // extractControllerStatus extracts status conditions from ForkliftController func extractControllerStatus(controller *unstructured.Unstructured, health *ControllerHealth) { conditions, found, _ := unstructured.NestedSlice(controller.Object, "status", "conditions") if !found { return } for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") message, _, _ := unstructured.NestedString(condition, "message") switch condType { case "Running": health.Status.Running = condStatus == "True" case "Successful": health.Status.Successful = condStatus == "True" case "Failure": health.Status.Failed = condStatus == "True" if condStatus == "True" && message != "" { health.Status.Message = message } } } } // AnalyzeControllerHealth analyzes the controller health and returns issues func AnalyzeControllerHealth(health *ControllerHealth, report *HealthReport) { // If there was an API error, don't report "not found" since we couldn't actually check if health.Error != "" { // Error was already reported by the caller, skip further analysis return } if !health.Found { report.AddIssue( SeverityCritical, "Controller", "ForkliftController", "ForkliftController not found", "Create a ForkliftController resource in the MTV namespace", ) return } // Check for vSphere providers without VDDK image if health.HasVSphereProvider && health.VDDKImage == "" { report.AddIssue( SeverityCritical, "Controller", health.Name, "vSphere providers detected but vddk_image not configured - VMware migrations will fail", "Set vddk_image in ForkliftController spec or run: kubectl mtv create vddk-image --help", ) } // Check for controller failure if health.Status.Failed { message := "ForkliftController is in Failed state" if health.Status.Message != "" { message += ": " + health.Status.Message } report.AddIssue( SeverityCritical, "Controller", health.Name, message, "Check the forklift-operator logs for details", ) } // Check for custom images (informational) if len(health.CustomImages) > 0 { report.AddIssue( SeverityInfo, "Controller", health.Name, "Custom container images configured - ensure registries are accessible", "Verify custom images are available: "+health.CustomImages[0].Image, ) } // Check for high log level (informational) if health.LogLevel > 3 { report.AddIssue( SeverityInfo, "Controller", health.Name, "High controller log level configured ("+strconv.Itoa(health.LogLevel)+") - may impact performance", "Consider reducing controller_log_level for production use", ) } // Check for remote OpenShift provider without OCP live migration enabled if health.HasRemoteOpenShiftProvider { liveMigrationEnabled := health.FeatureFlags.OCPLiveMigration != nil && *health.FeatureFlags.OCPLiveMigration if !liveMigrationEnabled { report.AddIssue( SeverityWarning, "Controller", health.Name, "Remote OpenShift provider detected but feature_ocp_live_migration not enabled - live migrations will not be available", "Set feature_ocp_live_migration: true in ForkliftController spec to enable cross-cluster live migration", ) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/health.go
Go
package health import ( "context" "fmt" "k8s.io/cli-runtime/pkg/genericclioptions" ) // RunHealthCheck performs all health checks and returns a complete health report func RunHealthCheck(ctx context.Context, configFlags *genericclioptions.ConfigFlags, opts HealthCheckOptions) (*HealthReport, error) { report := NewHealthReport() // 1. Check operator health report.Operator = CheckOperatorHealth(ctx, configFlags) // ========================================================================== // IMPORTANT: Two different namespace concepts are used in health checks: // // 1. operatorNamespace - ALWAYS auto-detected, where Forklift operator runs. // Used for: ForkliftController, Forklift component pods, Forklift logs. // These components ONLY exist in the operator namespace. // // 2. userNamespace (opts.Namespace) + opts.AllNamespaces - user-specified. // Used for: Providers, Plans (and their related conversion pods). // These user resources can exist in any namespace. // ========================================================================== // Auto-detect operator namespace from the operator health check // If detection failed (error or not found), fall back to default and warn operatorNamespace := report.Operator.Namespace if operatorNamespace == "" { operatorNamespace = "openshift-mtv" // Default fallback if report.Operator.Error != "" { report.AddIssue( SeverityInfo, "Operator", "", fmt.Sprintf("Could not auto-detect operator namespace (%s), using default 'openshift-mtv'", report.Operator.Error), "Ensure you have permissions to read CRDs or specify namespace with --namespace", ) } } // User-specified namespace for providers/plans (empty means use operatorNamespace as default) userNamespace := opts.Namespace // If operator is not installed and no error (genuinely not found), we can't do much more if !report.Operator.Installed && report.Operator.Error == "" { report.AddIssue( SeverityCritical, "Operator", "MTV Operator", "MTV Operator is not installed", "Install the MTV/Forklift operator first", ) report.CalculateOverallStatus() report.CalculateSummary() return report, nil } // If there was an error checking operator, continue with best effort using default namespace if report.Operator.Error != "" && !report.Operator.Installed { report.AddIssue( SeverityWarning, "Operator", "", fmt.Sprintf("Could not verify operator installation: %s", report.Operator.Error), "Check cluster connectivity and RBAC permissions", ) // Continue with best effort - operator might be installed but we couldn't verify } // 2. Check providers (user resources - can be in any namespace) // Uses userNamespace if specified, or operatorNamespace as default, or all namespaces if requested // // NOTE: hasVSphereProvider and hasRemoteOpenShiftProvider are derived from the // providers in the checked namespace(s). Warnings about VDDK or live migration // configuration will only appear if such providers exist in the scoped namespace(s). // Use --all-namespaces to check all namespaces if you want cluster-wide provider detection. var hasVSphereProvider, hasRemoteOpenShiftProvider bool providerNS := userNamespace if providerNS == "" { providerNS = operatorNamespace } providerResult, err := CheckProvidersHealth(ctx, configFlags, providerNS, opts.AllNamespaces) if err != nil { // If all-namespaces query failed, try falling back to operator namespace only if opts.AllNamespaces { report.AddIssue( SeverityInfo, "Providers", "", "Cannot list providers across all namespaces (RBAC?), falling back to operator namespace", "Request cluster-wide read permissions for providers.forklift.konveyor.io", ) // Fallback: try operator namespace only providerResult, err = CheckProvidersHealth(ctx, configFlags, operatorNamespace, false) } if err != nil { report.AddIssue( SeverityWarning, "Providers", "", fmt.Sprintf("Failed to check providers: %v", err), "", ) // Use safe defaults when provider check fails hasVSphereProvider = false hasRemoteOpenShiftProvider = false } else { report.Providers = providerResult.Providers AnalyzeProvidersHealth(providerResult.Providers, report) hasVSphereProvider = providerResult.HasVSphereProvider hasRemoteOpenShiftProvider = providerResult.HasRemoteOpenShiftProvider } } else { report.Providers = providerResult.Providers AnalyzeProvidersHealth(providerResult.Providers, report) hasVSphereProvider = providerResult.HasVSphereProvider hasRemoteOpenShiftProvider = providerResult.HasRemoteOpenShiftProvider } // 3. Check controller health (operator component - ALWAYS in operatorNamespace) controller, err := CheckControllerHealth(ctx, configFlags, operatorNamespace, hasVSphereProvider, hasRemoteOpenShiftProvider) if err != nil { report.AddIssue( SeverityWarning, "Controller", "", fmt.Sprintf("Failed to check controller: %v", err), "Check cluster connectivity and RBAC permissions", ) } report.Controller = controller AnalyzeControllerHealth(&report.Controller, report) // 4. Check pods health (operator components - ALWAYS in operatorNamespace) pods, err := CheckPodsHealth(ctx, configFlags, operatorNamespace) if err != nil { report.AddIssue( SeverityWarning, "Pods", "", fmt.Sprintf("Failed to check pods: %v", err), "", ) } else { report.Pods = pods AnalyzePodsHealth(pods, report) } // 5. Check logs (operator components - ALWAYS in operatorNamespace) if opts.CheckLogs { logLines := opts.LogLines if logLines <= 0 { logLines = 100 } analyses, err := CheckLogsHealth(ctx, configFlags, operatorNamespace, logLines) if err != nil { if opts.Verbose { report.AddIssue( SeverityInfo, "Logs", "", fmt.Sprintf("Failed to analyze logs: %v", err), "", ) } } else { report.LogAnalysis = analyses AnalyzeLogsHealth(analyses, report) } } // 6. Check plans (user resources - can be in any namespace) // Uses userNamespace if specified, or operatorNamespace as default, or all namespaces if requested planNS := userNamespace if planNS == "" { planNS = operatorNamespace } plans, err := CheckPlansHealth(ctx, configFlags, planNS, opts.AllNamespaces) if err != nil { // If all-namespaces query failed, try falling back to operator namespace only if opts.AllNamespaces { report.AddIssue( SeverityInfo, "Plans", "", "Cannot list plans across all namespaces (RBAC?), falling back to operator namespace", "Request cluster-wide read permissions for plans.forklift.konveyor.io", ) // Fallback: try operator namespace only plans, err = CheckPlansHealth(ctx, configFlags, operatorNamespace, false) } if err != nil { report.AddIssue( SeverityWarning, "Plans", "", fmt.Sprintf("Failed to check plans: %v", err), "", ) } else { report.Plans = plans AnalyzePlansHealth(plans, report) } } else { report.Plans = plans AnalyzePlansHealth(plans, report) } // Calculate overall status and summary report.CalculateOverallStatus() report.CalculateSummary() report.GenerateRecommendations() return report, nil } // PrintHealthReport formats and prints the health report func PrintHealthReport(report *HealthReport, outputFormat string) error { output, err := FormatReport(report, outputFormat) if err != nil { return fmt.Errorf("failed to format report: %v", err) } fmt.Print(output) return nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/logs.go
Go
package health import ( "bufio" "context" "fmt" "regexp" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/kubernetes" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // Log analysis patterns (pre-compiled for performance) var ( errorPatterns = []*regexp.Regexp{ regexp.MustCompile(`(?i)\berror\b`), regexp.MustCompile(`(?i)\bfailed\b`), regexp.MustCompile(`(?i)\bfatal\b`), regexp.MustCompile(`(?i)\bpanic\b`), } warningPatterns = []*regexp.Regexp{ regexp.MustCompile(`(?i)\bwarn(ing)?\b`), } // Patterns to ignore (false positives) ignorePatterns = []*regexp.Regexp{ regexp.MustCompile(`(?i)error.*nil`), regexp.MustCompile(`(?i)no error`), regexp.MustCompile(`(?i)error count.*0`), } ) // DeploymentLogs maps deployment names for log analysis var forkliftDeployments = []string{ "forklift-controller", "forklift-api", "forklift-validation", "forklift-ui-plugin", "forklift-volume-populator-controller", } // CheckLogsHealth analyzes logs from Forklift operator component deployments. // // IMPORTANT: This function checks logs from Forklift OPERATOR pods (forklift-controller, // forklift-api, forklift-validation, etc.) which ALWAYS run in the operator // namespace. The caller (health.go) should pass the auto-detected operator // namespace here, NOT a user-specified namespace. func CheckLogsHealth(ctx context.Context, configFlags *genericclioptions.ConfigFlags, operatorNamespace string, logLines int) ([]LogAnalysis, error) { clientset, err := client.GetKubernetesClientset(configFlags) if err != nil { return nil, fmt.Errorf("failed to get kubernetes clientset: %v", err) } // Use provided operator namespace or fall back to default ns := operatorNamespace if ns == "" { ns = client.OpenShiftMTVNamespace } var analyses []LogAnalysis for _, deployment := range forkliftDeployments { // Get pods for this deployment pods, err := clientset.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{ LabelSelector: fmt.Sprintf("app.kubernetes.io/name=%s", deployment), }) if err != nil { continue } // If no pods found with specific label, try by name prefix if len(pods.Items) == 0 { allPods, err := clientset.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{}) if err != nil { continue } for _, pod := range allPods.Items { if strings.HasPrefix(pod.Name, deployment) { pods.Items = append(pods.Items, pod) break // Just take the first matching pod } } } if len(pods.Items) == 0 { continue } // Analyze logs from the first pod pod := &pods.Items[0] analysis := analyzePodsLogs(ctx, clientset, pod, deployment, logLines) analyses = append(analyses, analysis) } return analyses, nil } // analyzePodsLogs analyzes logs from a single pod func analyzePodsLogs(ctx context.Context, clientset *kubernetes.Clientset, pod *corev1.Pod, name string, logLines int) LogAnalysis { analysis := LogAnalysis{ Name: name, Errors: 0, Warnings: 0, ErrorLines: []string{}, WarnLines: []string{}, } // Get logs for all containers in the pod for _, container := range pod.Spec.Containers { tailLines := int64(logLines) req := clientset.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &corev1.PodLogOptions{ Container: container.Name, TailLines: &tailLines, }) logStream, err := req.Stream(ctx) if err != nil { continue } // Use anonymous function to ensure logStream.Close() is called via defer func() { defer logStream.Close() scanner := bufio.NewScanner(logStream) for scanner.Scan() { line := scanner.Text() analyzeLogLine(line, &analysis) } // Note: Scanner errors are intentionally ignored as partial // log analysis is acceptable for health checks }() } return analysis } // analyzeLogLine analyzes a single log line for errors and warnings func analyzeLogLine(line string, analysis *LogAnalysis) { // Check if line should be ignored for _, pattern := range ignorePatterns { if pattern.MatchString(line) { return } } // Check for errors for _, pattern := range errorPatterns { if pattern.MatchString(line) { analysis.Errors++ if len(analysis.ErrorLines) < 5 { // Keep only first 5 error lines analysis.ErrorLines = append(analysis.ErrorLines, truncateLine(line, 200)) } return // Count as error only once } } // Check for warnings for _, pattern := range warningPatterns { if pattern.MatchString(line) { analysis.Warnings++ if len(analysis.WarnLines) < 5 { // Keep only first 5 warning lines analysis.WarnLines = append(analysis.WarnLines, truncateLine(line, 200)) } return // Count as warning only once } } } // truncateLine truncates a line to the specified length func truncateLine(line string, maxLen int) string { if len(line) <= maxLen { return line } return line[:maxLen-3] + "..." } // AnalyzeLogsHealth adds log-related issues to the report func AnalyzeLogsHealth(analyses []LogAnalysis, report *HealthReport) { for _, analysis := range analyses { if analysis.Errors > 10 { report.AddIssue( SeverityWarning, "Logs", analysis.Name, fmt.Sprintf("High error count in logs: %d errors", analysis.Errors), fmt.Sprintf("Check %s logs for details", analysis.Name), ) } else if analysis.Errors > 0 { report.AddIssue( SeverityInfo, "Logs", analysis.Name, fmt.Sprintf("%d errors found in recent logs", analysis.Errors), "", ) } if analysis.Warnings > 20 { report.AddIssue( SeverityInfo, "Logs", analysis.Name, fmt.Sprintf("High warning count in logs: %d warnings", analysis.Warnings), fmt.Sprintf("Review %s logs for potential issues", analysis.Name), ) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/operator.go
Go
package health import ( "context" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // CheckOperatorHealth checks the health of the MTV operator func CheckOperatorHealth(ctx context.Context, configFlags *genericclioptions.ConfigFlags) OperatorHealth { health := OperatorHealth{ Installed: false, Status: "Not Installed", } // Get operator info using existing utility operatorInfo := client.GetMTVOperatorInfo(ctx, configFlags) // Check for API/auth/network errors first if operatorInfo.Error != "" { health.Status = "Unknown" health.Error = operatorInfo.Error return health } if !operatorInfo.Found { return health } health.Installed = true health.Version = operatorInfo.Version health.Namespace = operatorInfo.Namespace if health.Namespace == "" { health.Namespace = client.OpenShiftMTVNamespace } health.Status = "Installed" return health } // GetOperatorNamespace returns the MTV operator namespace func GetOperatorNamespace(ctx context.Context, configFlags *genericclioptions.ConfigFlags) string { return client.GetMTVOperatorNamespace(ctx, configFlags) }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/plans.go
Go
package health import ( "context" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // CheckPlansHealth checks the health of all migration plans func CheckPlansHealth(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string, allNamespaces bool) ([]PlanHealth, error) { dynamicClient, err := client.GetDynamicClient(configFlags) if err != nil { return nil, err } var plans *unstructured.UnstructuredList if allNamespaces { plans, err = dynamicClient.Resource(client.PlansGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } else { ns := namespace if ns == "" { ns = client.OpenShiftMTVNamespace } plans, err = dynamicClient.Resource(client.PlansGVR).Namespace(ns).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, err } var planHealths []PlanHealth for _, plan := range plans.Items { health := analyzePlan(&plan) planHealths = append(planHealths, health) } return planHealths, nil } // analyzePlan analyzes a single plan and returns its health status func analyzePlan(plan *unstructured.Unstructured) PlanHealth { health := PlanHealth{ Name: plan.GetName(), Namespace: plan.GetNamespace(), } // Get VM count vms, exists, _ := unstructured.NestedSlice(plan.Object, "spec", "vms") if exists { health.VMCount = len(vms) } // Extract conditions conditions, exists, _ := unstructured.NestedSlice(plan.Object, "status", "conditions") if exists { for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") message, _, _ := unstructured.NestedString(condition, "message") isTrue := condStatus == "True" switch condType { case "Ready": health.Ready = isTrue if !isTrue && message != "" { health.Message = message } case "Failed": if isTrue { health.Status = "Failed" if message != "" { health.Message = message } } case "Succeeded": if isTrue && health.Status != "Failed" { health.Status = "Succeeded" } case "Running": if isTrue && health.Status == "" { health.Status = "Running" } case "Executing": if isTrue && health.Status == "" { health.Status = "Executing" } case "Canceled": if isTrue && health.Status != "Failed" { health.Status = "Canceled" } } } } // Default status if not set if health.Status == "" { if health.Ready { health.Status = "Ready" } else { health.Status = "NotReady" } } // Get migration statistics if available migration, exists, _ := unstructured.NestedMap(plan.Object, "status", "migration") if exists { if vms, vmExists, _ := unstructured.NestedSlice(migration, "vms"); vmExists { for _, v := range vms { vm, ok := v.(map[string]interface{}) if !ok { continue } // Check VM conditions for success/failure vmConditions, exists, _ := unstructured.NestedSlice(vm, "conditions") if !exists { continue } for _, c := range vmConditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") if condStatus == "True" { switch condType { case "Succeeded": health.Succeeded++ case "Failed": health.Failed++ } } } } } } return health } // AnalyzePlansHealth analyzes plan health and adds issues to the report func AnalyzePlansHealth(plans []PlanHealth, report *HealthReport) { for _, plan := range plans { // Check for failed plans if plan.Status == "Failed" { message := "Migration plan failed" if plan.Message != "" { message += ": " + plan.Message } report.AddIssue( SeverityCritical, "Plan", plan.Name, message, "Check plan status and VM logs for details", ) } // Check for not ready plans if !plan.Ready && plan.Status != "Failed" && plan.Status != "Succeeded" && plan.Status != "Canceled" { message := "Migration plan is not ready" if plan.Message != "" { message += ": " + plan.Message } report.AddIssue( SeverityWarning, "Plan", plan.Name, message, "Verify plan configuration, mappings, and provider status", ) } // Check for VM failures in running/executing plans if plan.Failed > 0 && (plan.Status == "Running" || plan.Status == "Executing") { report.AddIssue( SeverityWarning, "Plan", plan.Name, "Plan has failed VM migrations", "Check individual VM status and logs", ) } // Check for plans stuck in executing if plan.Status == "Executing" && plan.VMCount > 0 && plan.Succeeded+plan.Failed == 0 { report.AddIssue( SeverityInfo, "Plan", plan.Name, "Plan is executing but no VMs have completed", "Monitor migration progress", ) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/pods.go
Go
package health import ( "context" "fmt" "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // ForkliftPodLabelSelector is the label selector used to identify Forklift pods const ForkliftPodLabelSelector = "app=forklift" // CheckPodsHealth checks the health of Forklift operator component pods. // // IMPORTANT: This function checks Forklift OPERATOR pods (forklift-controller, // forklift-api, forklift-validation, etc.) which ALWAYS run in the operator // namespace. The caller (health.go) should pass the auto-detected operator // namespace here, NOT a user-specified namespace. // // User workload pods (like conversion pods) are NOT checked here - they are // associated with Plans and Providers which can be in any namespace. func CheckPodsHealth(ctx context.Context, configFlags *genericclioptions.ConfigFlags, operatorNamespace string) ([]PodHealth, error) { clientset, err := client.GetKubernetesClientset(configFlags) if err != nil { return nil, fmt.Errorf("failed to get kubernetes clientset: %v", err) } // Use provided operator namespace or fall back to default ns := operatorNamespace if ns == "" { ns = client.OpenShiftMTVNamespace } // List pods with forklift labels pods, err := clientset.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{ LabelSelector: ForkliftPodLabelSelector, }) var forkliftPods []corev1.Pod if err == nil { // Label selector query succeeded, use these pods directly (no filtering needed) forkliftPods = pods.Items } else { // Fallback: try without label selector and filter manually pods, err = clientset.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{}) if err != nil { return nil, fmt.Errorf("failed to list pods: %v", err) } // Filter to only forklift-related pods for _, pod := range pods.Items { if isForkliftPod(&pod) { forkliftPods = append(forkliftPods, pod) } } } var podHealths []PodHealth for _, pod := range forkliftPods { podHealth := analyzePod(&pod) podHealths = append(podHealths, podHealth) } return podHealths, nil } // isForkliftPod checks if a pod is a Forklift-related pod func isForkliftPod(pod *corev1.Pod) bool { name := pod.Name // Check by name prefix forkliftPrefixes := []string{ "forklift-", } for _, prefix := range forkliftPrefixes { if len(name) >= len(prefix) && name[:len(prefix)] == prefix { return true } } // Check by labels if labels := pod.Labels; labels != nil { if labels["app.kubernetes.io/part-of"] == "forklift" { return true } if labels["app"] == "forklift" { return true } } return false } // analyzePod analyzes a single pod and returns its health status func analyzePod(pod *corev1.Pod) PodHealth { health := PodHealth{ Name: pod.Name, Namespace: pod.Namespace, Status: string(pod.Status.Phase), Ready: isPodReady(pod), Restarts: getTotalRestarts(pod), Age: formatAge(pod.CreationTimestamp.Time), Issues: []string{}, } // Check for terminated containers for _, cs := range pod.Status.ContainerStatuses { if cs.LastTerminationState.Terminated != nil { health.TerminatedReason = cs.LastTerminationState.Terminated.Reason if health.TerminatedReason == "OOMKilled" { health.Issues = append(health.Issues, "Container was OOMKilled") } } } // Check for high restart count if health.Restarts > 5 { health.Issues = append(health.Issues, fmt.Sprintf("High restart count: %d", health.Restarts)) } // Check for pending state if pod.Status.Phase == corev1.PodPending { health.Issues = append(health.Issues, "Pod is in Pending state") // Check for scheduling issues for _, condition := range pod.Status.Conditions { if condition.Type == corev1.PodScheduled && condition.Status == corev1.ConditionFalse { health.Issues = append(health.Issues, "Scheduling failed: "+condition.Reason) } } } // Check for failed state if pod.Status.Phase == corev1.PodFailed { health.Issues = append(health.Issues, "Pod is in Failed state") } // Check for not ready if !health.Ready && pod.Status.Phase == corev1.PodRunning { health.Issues = append(health.Issues, "Pod is running but not ready") } return health } // isPodReady checks if all containers in a pod are ready func isPodReady(pod *corev1.Pod) bool { for _, condition := range pod.Status.Conditions { if condition.Type == corev1.PodReady { return condition.Status == corev1.ConditionTrue } } return false } // getTotalRestarts returns the total restart count across all containers func getTotalRestarts(pod *corev1.Pod) int { total := 0 for _, cs := range pod.Status.ContainerStatuses { total += int(cs.RestartCount) } return total } // formatAge formats the age of a pod func formatAge(creationTime time.Time) string { duration := time.Since(creationTime) if duration.Hours() >= 24 { days := int(duration.Hours() / 24) return fmt.Sprintf("%dd", days) } else if duration.Hours() >= 1 { return fmt.Sprintf("%dh", int(duration.Hours())) } else if duration.Minutes() >= 1 { return fmt.Sprintf("%dm", int(duration.Minutes())) } return fmt.Sprintf("%ds", int(duration.Seconds())) } // AnalyzePodsHealth analyzes pod health and adds issues to the report func AnalyzePodsHealth(pods []PodHealth, report *HealthReport) { for _, pod := range pods { // Check for critical issues if pod.Status == "Failed" { report.AddIssue( SeverityCritical, "Pod", pod.Name, "Pod is in Failed state", "Check pod logs and events: kubectl describe pod "+pod.Name, ) } // Check for OOMKilled if pod.TerminatedReason == "OOMKilled" { report.AddIssue( SeverityCritical, "Pod", pod.Name, "Container was OOMKilled - memory limit too low", "Increase memory limits for the pod", ) } // Check for high restarts if pod.Restarts > 5 { report.AddIssue( SeverityWarning, "Pod", pod.Name, fmt.Sprintf("High restart count (%d) - indicates instability", pod.Restarts), "Check pod logs for crash reasons", ) } // Check for pending pods if pod.Status == "Pending" { report.AddIssue( SeverityWarning, "Pod", pod.Name, "Pod is stuck in Pending state", "Check node resources and scheduling constraints", ) } // Check for not ready pods if !pod.Ready && pod.Status == "Running" { report.AddIssue( SeverityWarning, "Pod", pod.Name, "Pod is running but not ready", "Check readiness probe failures", ) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/providers.go
Go
package health import ( "context" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // ProviderCheckResult contains the results of provider health checks type ProviderCheckResult struct { Providers []ProviderHealth HasVSphereProvider bool HasRemoteOpenShiftProvider bool } // CheckProvidersHealth checks the health of all providers func CheckProvidersHealth(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string, allNamespaces bool) (ProviderCheckResult, error) { result := ProviderCheckResult{ Providers: []ProviderHealth{}, } dynamicClient, err := client.GetDynamicClient(configFlags) if err != nil { return result, err } var providers *unstructured.UnstructuredList if allNamespaces { providers, err = dynamicClient.Resource(client.ProvidersGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } else { ns := namespace if ns == "" { ns = client.OpenShiftMTVNamespace } providers, err = dynamicClient.Resource(client.ProvidersGVR).Namespace(ns).List(ctx, metav1.ListOptions{}) } if err != nil { return result, err } for _, provider := range providers.Items { health := analyzeProvider(&provider) result.Providers = append(result.Providers, health) // Check if this is a vSphere provider if health.Type == "vsphere" { result.HasVSphereProvider = true } // Check if this is a remote OpenShift provider (has URL set) if health.Type == "openshift" { url, _, _ := unstructured.NestedString(provider.Object, "spec", "url") if url != "" { result.HasRemoteOpenShiftProvider = true } } } return result, nil } // analyzeProvider analyzes a single provider and returns its health status func analyzeProvider(provider *unstructured.Unstructured) ProviderHealth { health := ProviderHealth{ Name: provider.GetName(), Namespace: provider.GetNamespace(), } // Get provider type providerType, _, _ := unstructured.NestedString(provider.Object, "spec", "type") health.Type = providerType // Get phase phase, _, _ := unstructured.NestedString(provider.Object, "status", "phase") health.Phase = phase // Extract conditions conditions, exists, _ := unstructured.NestedSlice(provider.Object, "status", "conditions") if exists { for _, c := range conditions { condition, ok := c.(map[string]interface{}) if !ok { continue } condType, _, _ := unstructured.NestedString(condition, "type") condStatus, _, _ := unstructured.NestedString(condition, "status") message, _, _ := unstructured.NestedString(condition, "message") isTrue := condStatus == "True" switch condType { case "Ready": health.Ready = isTrue if !isTrue && message != "" { health.Message = message } case "ConnectionTestSucceeded": health.Connected = isTrue if !isTrue && message != "" && health.Message == "" { health.Message = message } case "Validated": health.Validated = isTrue case "InventoryCreated": health.InventoryCreated = isTrue } } } return health } // AnalyzeProvidersHealth analyzes provider health and adds issues to the report func AnalyzeProvidersHealth(providers []ProviderHealth, report *HealthReport) { for _, provider := range providers { // Skip the "host" provider (local OpenShift) if provider.Name == "host" && provider.Type == "openshift" { continue } // Check for not ready if !provider.Ready { severity := SeverityWarning message := "Provider is not ready" suggestion := "Check provider configuration and credentials" if !provider.Connected { severity = SeverityCritical message = "Provider connection failed" suggestion = "Verify provider URL and network connectivity" } if provider.Message != "" { message += ": " + provider.Message } report.AddIssue( severity, "Provider", provider.Name, message, suggestion, ) } // Check for connection issues if !provider.Connected && provider.Ready { report.AddIssue( SeverityWarning, "Provider", provider.Name, "Provider connection test not succeeded", "Check provider credentials and network access", ) } // Check for validation issues if !provider.Validated && provider.Ready { report.AddIssue( SeverityWarning, "Provider", provider.Name, "Provider validation not completed", "Review provider configuration", ) } // Check for inventory issues if !provider.InventoryCreated && provider.Ready && provider.Connected { report.AddIssue( SeverityWarning, "Provider", provider.Name, "Provider inventory not created", "Wait for inventory sync or check for inventory service issues", ) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/report.go
Go
package health import ( "encoding/json" "fmt" "strings" "gopkg.in/yaml.v3" "github.com/yaacov/kubectl-mtv/pkg/util/output" ) // FormatReport formats the health report in the specified output format func FormatReport(report *HealthReport, outputFormat string) (string, error) { switch strings.ToLower(outputFormat) { case "json": return formatJSON(report) case "yaml": return formatYAML(report) default: return formatTable(report), nil } } // formatJSON formats the report as JSON func formatJSON(report *HealthReport) (string, error) { data, err := json.MarshalIndent(report, "", " ") if err != nil { return "", err } return string(data), nil } // formatYAML formats the report as YAML func formatYAML(report *HealthReport) (string, error) { data, err := yaml.Marshal(report) if err != nil { return "", err } return string(data), nil } // formatTable formats the report as a colored table func formatTable(report *HealthReport) string { var sb strings.Builder // Header sb.WriteString(output.ColorizedSeparator(80, output.YellowColor)) sb.WriteString("\n") sb.WriteString(output.Bold(output.Cyan("MTV HEALTH REPORT"))) sb.WriteString("\n") sb.WriteString(output.ColorizedSeparator(80, output.YellowColor)) sb.WriteString("\n\n") // Operator Status sb.WriteString(formatOperatorSection(report)) // Controller Status sb.WriteString(formatControllerSection(report)) // Pods Status sb.WriteString(formatPodsSection(report)) // Log Analysis if len(report.LogAnalysis) > 0 { sb.WriteString(formatLogAnalysisSection(report)) } // Providers sb.WriteString(formatProvidersSection(report)) // Plans sb.WriteString(formatPlansSection(report)) // Summary sb.WriteString(formatSummarySection(report)) return sb.String() } func formatOperatorSection(report *HealthReport) string { var sb strings.Builder sb.WriteString(output.Bold(output.Cyan("OPERATOR STATUS"))) sb.WriteString("\n") op := report.Operator if op.Installed { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("MTV Operator:"), output.Green("Installed"))) if op.Version != "" && op.Version != "unknown" { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("Version:"), output.Yellow(op.Version))) } sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("Namespace:"), output.Yellow(op.Namespace))) } else { // Check for error or unknown status before falling back to generic "Not Installed" if op.Error != "" { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("MTV Operator:"), output.Red(op.Error))) } else if op.Status == "Unknown" { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("MTV Operator:"), output.Yellow(op.Status))) } else { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("MTV Operator:"), output.Red("Not Installed"))) } } sb.WriteString("\n") return sb.String() } func formatControllerSection(report *HealthReport) string { var sb strings.Builder sb.WriteString(output.Bold(output.Cyan("FORKLIFT CONTROLLER"))) sb.WriteString("\n") ctrl := report.Controller if !ctrl.Found { // Prefer displaying the error if present (e.g., API/auth failures) if ctrl.Error != "" { sb.WriteString(fmt.Sprintf(" %s\n", output.Red(ctrl.Error))) } else { sb.WriteString(fmt.Sprintf(" %s\n", output.Red("ForkliftController not found"))) } sb.WriteString("\n") return sb.String() } sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("Name:"), output.Yellow(ctrl.Name))) // Feature Flags sb.WriteString(fmt.Sprintf(" %s\n", output.Bold("Feature Flags:"))) sb.WriteString(fmt.Sprintf(" UI Plugin: %s\n", formatBoolPtr(ctrl.FeatureFlags.UIPlugin))) sb.WriteString(fmt.Sprintf(" Validation: %s\n", formatBoolPtr(ctrl.FeatureFlags.Validation))) sb.WriteString(fmt.Sprintf(" Volume Pop: %s\n", formatBoolPtr(ctrl.FeatureFlags.VolumePopulator))) sb.WriteString(fmt.Sprintf(" Auth Required: %s\n", formatBoolPtr(ctrl.FeatureFlags.AuthRequired))) // Show OCP Live Migration if there's a remote OpenShift provider or if it's explicitly set if ctrl.HasRemoteOpenShiftProvider || ctrl.FeatureFlags.OCPLiveMigration != nil { liveMigStatus := formatBoolPtr(ctrl.FeatureFlags.OCPLiveMigration) if ctrl.HasRemoteOpenShiftProvider && (ctrl.FeatureFlags.OCPLiveMigration == nil || !*ctrl.FeatureFlags.OCPLiveMigration) { liveMigStatus = output.Red("[not set] *** Remote OpenShift provider exists!") } sb.WriteString(fmt.Sprintf(" OCP Live Mig: %s\n", liveMigStatus)) } // Custom Images if len(ctrl.CustomImages) > 0 { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("Custom Images:"), output.Yellow(fmt.Sprintf("%d overrides", len(ctrl.CustomImages))))) for _, img := range ctrl.CustomImages { sb.WriteString(fmt.Sprintf(" - %s: %s\n", img.Field, output.Blue(img.Image))) } } else { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("Custom Images:"), "None")) } // VDDK Image if ctrl.VDDKImage != "" { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("VDDK Image:"), output.Green(ctrl.VDDKImage))) } else if ctrl.HasVSphereProvider { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("VDDK Image:"), output.Red("[NOT SET] *** WARNING: vSphere providers exist!"))) } else { sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("VDDK Image:"), "[not set]")) } // Log Level if ctrl.LogLevel > 0 { sb.WriteString(fmt.Sprintf(" %s %d\n", output.Bold("Log Level:"), ctrl.LogLevel)) } sb.WriteString("\n") return sb.String() } func formatPodsSection(report *HealthReport) string { var sb strings.Builder unhealthy := 0 for _, pod := range report.Pods { if !pod.Ready || pod.Status != "Running" || len(pod.Issues) > 0 { unhealthy++ } } sb.WriteString(output.Bold(output.Cyan(fmt.Sprintf("FORKLIFT PODS (%d total, %d unhealthy)", len(report.Pods), unhealthy)))) sb.WriteString("\n") if len(report.Pods) == 0 { sb.WriteString(" No Forklift pods found\n") sb.WriteString("\n") return sb.String() } // Table header sb.WriteString(fmt.Sprintf(" %-45s %-10s %-10s %s\n", output.Bold("NAME"), output.Bold("STATUS"), output.Bold("RESTARTS"), output.Bold("ISSUES"))) for _, pod := range report.Pods { status := pod.Status if pod.Ready && pod.Status == "Running" { status = output.Green(status) } else if pod.Status == "Failed" { status = output.Red(status) } else if pod.Status == "Pending" { status = output.Yellow(status) } restarts := fmt.Sprintf("%d", pod.Restarts) if pod.Restarts > 5 { restarts = output.Red(restarts) } else if pod.Restarts > 0 { restarts = output.Yellow(restarts) } issues := "None" if len(pod.Issues) > 0 { issues = output.Red(strings.Join(pod.Issues, ", ")) } // Truncate name if too long name := pod.Name if len(name) > 43 { name = name[:40] + "..." } sb.WriteString(fmt.Sprintf(" %-45s %-10s %-10s %s\n", name, status, restarts, issues)) } sb.WriteString("\n") return sb.String() } func formatLogAnalysisSection(report *HealthReport) string { var sb strings.Builder sb.WriteString(output.Bold(output.Cyan("POD LOG ANALYSIS"))) sb.WriteString("\n") for _, analysis := range report.LogAnalysis { errStr := fmt.Sprintf("%d errors", analysis.Errors) warnStr := fmt.Sprintf("%d warnings", analysis.Warnings) if analysis.Errors > 0 { errStr = output.Red(errStr) } else { errStr = output.Green(errStr) } if analysis.Warnings > 5 { warnStr = output.Yellow(warnStr) } sb.WriteString(fmt.Sprintf(" %-25s %s, %s\n", analysis.Name+":", errStr, warnStr)) } sb.WriteString("\n") return sb.String() } func formatProvidersSection(report *HealthReport) string { var sb strings.Builder unhealthy := 0 for _, provider := range report.Providers { if !provider.Ready { unhealthy++ } } sb.WriteString(output.Bold(output.Cyan(fmt.Sprintf("PROVIDERS (%d total, %d unhealthy)", len(report.Providers), unhealthy)))) sb.WriteString("\n") if len(report.Providers) == 0 { sb.WriteString(" No providers found\n") sb.WriteString("\n") return sb.String() } // Table header sb.WriteString(fmt.Sprintf(" %-20s %-15s %-12s %-10s %-10s %-10s\n", output.Bold("NAME"), output.Bold("NAMESPACE"), output.Bold("TYPE"), output.Bold("CONNECTED"), output.Bold("INVENTORY"), output.Bold("READY"))) for _, provider := range report.Providers { connected := formatBool(provider.Connected) inventory := formatBool(provider.InventoryCreated) ready := formatBool(provider.Ready) name := provider.Name if len(name) > 18 { name = name[:15] + "..." } ns := provider.Namespace if len(ns) > 13 { ns = ns[:10] + "..." } sb.WriteString(fmt.Sprintf(" %-20s %-15s %-12s %-10s %-10s %-10s\n", name, ns, provider.Type, connected, inventory, ready)) } sb.WriteString("\n") return sb.String() } func formatPlansSection(report *HealthReport) string { var sb strings.Builder unhealthy := 0 for _, plan := range report.Plans { if !plan.Ready || plan.Status == "Failed" { unhealthy++ } } sb.WriteString(output.Bold(output.Cyan(fmt.Sprintf("PLANS (%d total, %d with issues)", len(report.Plans), unhealthy)))) sb.WriteString("\n") if len(report.Plans) == 0 { sb.WriteString(" No migration plans found\n") sb.WriteString("\n") return sb.String() } // Table header sb.WriteString(fmt.Sprintf(" %-25s %-15s %-12s %-8s %s\n", output.Bold("NAME"), output.Bold("NAMESPACE"), output.Bold("STATUS"), output.Bold("READY"), output.Bold("VMS"))) for _, plan := range report.Plans { status := plan.Status switch status { case "Failed": status = output.Red(status) case "Succeeded": status = output.Green(status) case "Running", "Executing": status = output.Blue(status) } ready := formatBool(plan.Ready) vmInfo := fmt.Sprintf("%d", plan.VMCount) if plan.Failed > 0 { vmInfo = fmt.Sprintf("%d (F:%d)", plan.VMCount, plan.Failed) vmInfo = output.Red(vmInfo) } else if plan.Succeeded > 0 { vmInfo = fmt.Sprintf("%d (S:%d)", plan.VMCount, plan.Succeeded) } name := plan.Name if len(name) > 23 { name = name[:20] + "..." } ns := plan.Namespace if len(ns) > 13 { ns = ns[:10] + "..." } sb.WriteString(fmt.Sprintf(" %-25s %-15s %-12s %-8s %s\n", name, ns, status, ready, vmInfo)) } sb.WriteString("\n") return sb.String() } func formatSummarySection(report *HealthReport) string { var sb strings.Builder sb.WriteString(output.Bold(output.Cyan("SUMMARY"))) sb.WriteString("\n") // Overall Health healthStr := string(report.OverallStatus) switch report.OverallStatus { case HealthStatusHealthy: healthStr = output.Green(healthStr) case HealthStatusWarning: healthStr = output.Yellow(healthStr) case HealthStatusCritical: healthStr = output.Red(healthStr) } sb.WriteString(fmt.Sprintf(" %s %s\n", output.Bold("Overall Health:"), healthStr)) // Issue counts sb.WriteString(fmt.Sprintf(" %s %d\n", output.Bold("Issues Found:"), report.Summary.TotalIssues)) if report.Summary.CriticalIssues > 0 { sb.WriteString(fmt.Sprintf(" Critical: %s\n", output.Red(fmt.Sprintf("%d", report.Summary.CriticalIssues)))) } if report.Summary.WarningIssues > 0 { sb.WriteString(fmt.Sprintf(" Warning: %s\n", output.Yellow(fmt.Sprintf("%d", report.Summary.WarningIssues)))) } // Recommendations if len(report.Issues) > 0 { sb.WriteString(fmt.Sprintf(" %s\n", output.Bold("Recommendations:"))) for _, issue := range report.Issues { prefix := " " switch issue.Severity { case SeverityCritical: prefix = output.Red("[CRITICAL]") case SeverityWarning: prefix = output.Yellow("[WARNING]") case SeverityInfo: prefix = output.Blue("[INFO]") } resource := "" if issue.Resource != "" { resource = issue.Resource + ": " } sb.WriteString(fmt.Sprintf(" %s %s%s\n", prefix, resource, issue.Message)) if issue.Suggestion != "" { sb.WriteString(fmt.Sprintf(" %s\n", output.Cyan(issue.Suggestion))) } } } sb.WriteString("\n") return sb.String() } // Helper functions func formatBool(b bool) string { if b { return output.Green("True") } return output.Red("False") } func formatBoolPtr(b *bool) string { if b == nil { return "[not set]" } if *b { return output.Green("True") } return output.Yellow("False") }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/health/types.go
Go
package health import ( "time" ) // HealthStatus represents the overall health status type HealthStatus string const ( HealthStatusHealthy HealthStatus = "Healthy" HealthStatusWarning HealthStatus = "Warning" HealthStatusCritical HealthStatus = "Critical" HealthStatusUnknown HealthStatus = "Unknown" ) // IssueSeverity represents the severity of a health issue type IssueSeverity string const ( SeverityCritical IssueSeverity = "Critical" SeverityWarning IssueSeverity = "Warning" SeverityInfo IssueSeverity = "Info" ) // HealthReport contains the complete health check results type HealthReport struct { Timestamp time.Time `json:"timestamp" yaml:"timestamp"` OverallStatus HealthStatus `json:"overallStatus" yaml:"overallStatus"` Operator OperatorHealth `json:"operator" yaml:"operator"` Controller ControllerHealth `json:"controller" yaml:"controller"` Pods []PodHealth `json:"pods" yaml:"pods"` LogAnalysis []LogAnalysis `json:"logAnalysis,omitempty" yaml:"logAnalysis,omitempty"` Providers []ProviderHealth `json:"providers" yaml:"providers"` Plans []PlanHealth `json:"plans" yaml:"plans"` Issues []HealthIssue `json:"issues" yaml:"issues"` Recommendations []string `json:"recommendations" yaml:"recommendations"` Summary HealthSummary `json:"summary" yaml:"summary"` } // HealthSummary provides a quick overview of the health report type HealthSummary struct { TotalPods int `json:"totalPods" yaml:"totalPods"` HealthyPods int `json:"healthyPods" yaml:"healthyPods"` TotalProviders int `json:"totalProviders" yaml:"totalProviders"` HealthyProviders int `json:"healthyProviders" yaml:"healthyProviders"` TotalPlans int `json:"totalPlans" yaml:"totalPlans"` HealthyPlans int `json:"healthyPlans" yaml:"healthyPlans"` TotalIssues int `json:"totalIssues" yaml:"totalIssues"` CriticalIssues int `json:"criticalIssues" yaml:"criticalIssues"` WarningIssues int `json:"warningIssues" yaml:"warningIssues"` } // OperatorHealth contains operator health information type OperatorHealth struct { Installed bool `json:"installed" yaml:"installed"` Version string `json:"version,omitempty" yaml:"version,omitempty"` Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"` Status string `json:"status" yaml:"status"` Error string `json:"error,omitempty" yaml:"error,omitempty"` } // ControllerHealth contains ForkliftController spec analysis type ControllerHealth struct { Name string `json:"name" yaml:"name"` Namespace string `json:"namespace" yaml:"namespace"` Found bool `json:"found" yaml:"found"` Error string `json:"error,omitempty" yaml:"error,omitempty"` FeatureFlags FeatureFlags `json:"featureFlags" yaml:"featureFlags"` CustomImages []ImageOverride `json:"customImages,omitempty" yaml:"customImages,omitempty"` VDDKImage string `json:"vddkImage,omitempty" yaml:"vddkImage,omitempty"` LogLevel int `json:"logLevel,omitempty" yaml:"logLevel,omitempty"` HasVSphereProvider bool `json:"hasVSphereProvider" yaml:"hasVSphereProvider"` HasRemoteOpenShiftProvider bool `json:"hasRemoteOpenShiftProvider" yaml:"hasRemoteOpenShiftProvider"` Status ControllerStatus `json:"status" yaml:"status"` } // ControllerStatus contains ForkliftController status conditions type ControllerStatus struct { Running bool `json:"running" yaml:"running"` Successful bool `json:"successful" yaml:"successful"` Failed bool `json:"failed" yaml:"failed"` Message string `json:"message,omitempty" yaml:"message,omitempty"` } // FeatureFlags contains ForkliftController feature flag settings type FeatureFlags struct { UIPlugin *bool `json:"uiPlugin,omitempty" yaml:"uiPlugin,omitempty"` Validation *bool `json:"validation,omitempty" yaml:"validation,omitempty"` VolumePopulator *bool `json:"volumePopulator,omitempty" yaml:"volumePopulator,omitempty"` AuthRequired *bool `json:"authRequired,omitempty" yaml:"authRequired,omitempty"` OCPLiveMigration *bool `json:"ocpLiveMigration,omitempty" yaml:"ocpLiveMigration,omitempty"` } // ImageOverride represents a custom FQIN image override type ImageOverride struct { Field string `json:"field" yaml:"field"` Image string `json:"image" yaml:"image"` } // PodHealth contains health information for a single pod type PodHealth struct { Name string `json:"name" yaml:"name"` Namespace string `json:"namespace" yaml:"namespace"` Status string `json:"status" yaml:"status"` Ready bool `json:"ready" yaml:"ready"` Restarts int `json:"restarts" yaml:"restarts"` Age string `json:"age" yaml:"age"` Issues []string `json:"issues,omitempty" yaml:"issues,omitempty"` TerminatedReason string `json:"terminatedReason,omitempty" yaml:"terminatedReason,omitempty"` } // LogAnalysis contains log analysis results for a pod/deployment type LogAnalysis struct { Name string `json:"name" yaml:"name"` Errors int `json:"errors" yaml:"errors"` Warnings int `json:"warnings" yaml:"warnings"` ErrorLines []string `json:"errorLines,omitempty" yaml:"errorLines,omitempty"` WarnLines []string `json:"warnLines,omitempty" yaml:"warnLines,omitempty"` } // ProviderHealth contains health information for a provider type ProviderHealth struct { Name string `json:"name" yaml:"name"` Namespace string `json:"namespace" yaml:"namespace"` Type string `json:"type" yaml:"type"` Phase string `json:"phase" yaml:"phase"` Ready bool `json:"ready" yaml:"ready"` Connected bool `json:"connected" yaml:"connected"` Validated bool `json:"validated" yaml:"validated"` InventoryCreated bool `json:"inventoryCreated" yaml:"inventoryCreated"` Message string `json:"message,omitempty" yaml:"message,omitempty"` } // PlanHealth contains health information for a migration plan type PlanHealth struct { Name string `json:"name" yaml:"name"` Namespace string `json:"namespace" yaml:"namespace"` Ready bool `json:"ready" yaml:"ready"` Status string `json:"status" yaml:"status"` VMCount int `json:"vmCount" yaml:"vmCount"` Failed int `json:"failed,omitempty" yaml:"failed,omitempty"` Succeeded int `json:"succeeded,omitempty" yaml:"succeeded,omitempty"` Message string `json:"message,omitempty" yaml:"message,omitempty"` } // HealthIssue represents a detected health issue type HealthIssue struct { Severity IssueSeverity `json:"severity" yaml:"severity"` Component string `json:"component" yaml:"component"` Resource string `json:"resource,omitempty" yaml:"resource,omitempty"` Message string `json:"message" yaml:"message"` Suggestion string `json:"suggestion,omitempty" yaml:"suggestion,omitempty"` } // HealthCheckOptions contains options for running health checks type HealthCheckOptions struct { Namespace string AllNamespaces bool CheckLogs bool LogLines int Verbose bool } // NewHealthReport creates a new health report with initial values func NewHealthReport() *HealthReport { return &HealthReport{ Timestamp: time.Now(), OverallStatus: HealthStatusUnknown, Pods: []PodHealth{}, LogAnalysis: []LogAnalysis{}, Providers: []ProviderHealth{}, Plans: []PlanHealth{}, Issues: []HealthIssue{}, Recommendations: []string{}, } } // AddIssue adds a health issue to the report func (r *HealthReport) AddIssue(severity IssueSeverity, component, resource, message, suggestion string) { r.Issues = append(r.Issues, HealthIssue{ Severity: severity, Component: component, Resource: resource, Message: message, Suggestion: suggestion, }) } // CalculateOverallStatus determines the overall health status based on issues func (r *HealthReport) CalculateOverallStatus() { hasCritical := false hasWarning := false for _, issue := range r.Issues { switch issue.Severity { case SeverityCritical: hasCritical = true case SeverityWarning: hasWarning = true } } if hasCritical { r.OverallStatus = HealthStatusCritical } else if hasWarning { r.OverallStatus = HealthStatusWarning } else { r.OverallStatus = HealthStatusHealthy } } // CalculateSummary calculates the summary statistics func (r *HealthReport) CalculateSummary() { // Reset totals (assigned directly from slice lengths) r.Summary.TotalPods = len(r.Pods) r.Summary.TotalProviders = len(r.Providers) r.Summary.TotalPlans = len(r.Plans) r.Summary.TotalIssues = len(r.Issues) // Reset derived counters to zero before recomputing r.Summary.HealthyPods = 0 r.Summary.HealthyProviders = 0 r.Summary.HealthyPlans = 0 r.Summary.CriticalIssues = 0 r.Summary.WarningIssues = 0 for _, pod := range r.Pods { if pod.Ready && pod.Status == "Running" { r.Summary.HealthyPods++ } } for _, provider := range r.Providers { if provider.Ready { r.Summary.HealthyProviders++ } } for _, plan := range r.Plans { if plan.Ready && plan.Status != "Failed" { r.Summary.HealthyPlans++ } } for _, issue := range r.Issues { switch issue.Severity { case SeverityCritical: r.Summary.CriticalIssues++ case SeverityWarning: r.Summary.WarningIssues++ } } } // GenerateRecommendations generates recommendations based on issues func (r *HealthReport) GenerateRecommendations() { for _, issue := range r.Issues { if issue.Suggestion != "" { recommendation := issue.Message if issue.Resource != "" { recommendation = issue.Resource + ": " + recommendation } recommendation += " - " + issue.Suggestion r.Recommendations = append(r.Recommendations, recommendation) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/help/generator.go
Go
package help import ( "regexp" "strconv" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" ) // SchemaVersion is the current version of the help schema format. // Version 1.2 removes positional args, provider hints, migration hints, and LLM annotations. const SchemaVersion = "1.2" // EnumValuer is an interface for flags that provide valid values. // Custom flag types can implement this to expose their allowed values. type EnumValuer interface { GetValidValues() []string } // Generate creates a HelpSchema from a Cobra command tree. func Generate(rootCmd *cobra.Command, cliVersion string, opts Options) *HelpSchema { schema := &HelpSchema{ Version: SchemaVersion, CLIVersion: cliVersion, Name: rootCmd.Name(), Description: rootCmd.Short, LongDescription: rootCmd.Long, Commands: []Command{}, GlobalFlags: []Flag{}, } // Walk command tree - automatically discovers all commands walkCommands(rootCmd, []string{}, func(cmd *cobra.Command, path []string) { // Skip hidden commands unless requested if cmd.Hidden && !opts.IncludeHidden { return } runnable := cmd.Runnable() // Include non-runnable commands only if they are at depth ≥ 2 // (e.g., "get inventory") and have 3+ runnable children. // This provides description metadata for sibling-group compaction // without including top-level structural parents like "get" or "create". if !runnable { if len(path) < 2 { return } runnableChildren := 0 for _, child := range cmd.Commands() { if child.Runnable() { runnableChildren++ } } if runnableChildren < 3 { return } } // Apply category filter category := getCategory(path) if opts.ReadOnly && category != "read" { return } if opts.Write && category != "write" { return } c := commandToSchema(cmd, path, opts) c.Runnable = runnable schema.Commands = append(schema.Commands, c) }) // Extract global flags from persistent flags if opts.IncludeGlobalFlags { rootCmd.PersistentFlags().VisitAll(func(f *pflag.Flag) { if f.Hidden && !opts.IncludeHidden { return } schema.GlobalFlags = append(schema.GlobalFlags, flagToSchema(f)) }) } return schema } // FilterByPath filters a schema to only include commands whose path starts with // the given prefix. For example, FilterByPath(schema, ["get"]) keeps all "get *" // commands, and FilterByPath(schema, ["get", "plan"]) keeps only "get plan". // Returns the number of commands remaining after filtering. func FilterByPath(schema *HelpSchema, prefix []string) int { if len(prefix) == 0 { return len(schema.Commands) } filtered := make([]Command, 0, len(schema.Commands)) for _, cmd := range schema.Commands { if len(cmd.Path) < len(prefix) { continue } match := true for i, seg := range prefix { if cmd.Path[i] != seg { match = false break } } if match { filtered = append(filtered, cmd) } } schema.Commands = filtered return len(filtered) } // walkCommands recursively visits all commands in the tree. func walkCommands(cmd *cobra.Command, path []string, visitor func(*cobra.Command, []string)) { visitor(cmd, path) for _, child := range cmd.Commands() { walkCommands(child, append(append([]string{}, path...), child.Name()), visitor) } } // commandToSchema converts a Cobra command to our schema format. func commandToSchema(cmd *cobra.Command, path []string, opts Options) Command { c := Command{ Name: cmd.Name(), Path: path, PathString: strings.Join(path, " "), Description: cmd.Short, Usage: cmd.UseLine(), Category: getCategory(path), Flags: []Flag{}, } // Include verbose fields only when not in short mode if !opts.Short { c.LongDescription = cmd.Long c.Examples = parseExamples(cmd.Example) } // Copy aliases if len(cmd.Aliases) > 0 { c.Aliases = append([]string{}, cmd.Aliases...) } // Extract local flags (not inherited) cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { if f.Hidden && !opts.IncludeHidden { return } schema := flagToSchema(f) // Check if flag is required (MarkFlagRequired annotates the flag, not the command) if ann := f.Annotations; ann != nil { if _, ok := ann[cobra.BashCompOneRequiredFlag]; ok { schema.Required = true } } // Try to get enum values from the flag value if enumValuer, ok := f.Value.(EnumValuer); ok { schema.Enum = enumValuer.GetValidValues() } c.Flags = append(c.Flags, schema) }) return c } // flagToSchema converts a pflag.Flag to our schema format. func flagToSchema(f *pflag.Flag) Flag { flag := Flag{ Name: f.Name, Shorthand: f.Shorthand, Type: f.Value.Type(), Description: f.Usage, Hidden: f.Hidden, } // Set default value with proper typing based on flag type if f.DefValue != "" { flagType := f.Value.Type() switch { case flagType == "bool": // Convert boolean strings to actual booleans if f.DefValue == "true" { flag.Default = true } else if f.DefValue == "false" { flag.Default = false } case flagType == "int" || flagType == "int8" || flagType == "int16" || flagType == "int32" || flagType == "int64": // Convert integer strings to numbers if v, err := strconv.ParseInt(f.DefValue, 10, 64); err == nil { flag.Default = v } else { flag.Default = f.DefValue } case flagType == "uint" || flagType == "uint8" || flagType == "uint16" || flagType == "uint32" || flagType == "uint64": // Convert unsigned integer strings to numbers if v, err := strconv.ParseUint(f.DefValue, 10, 64); err == nil { flag.Default = v } else { flag.Default = f.DefValue } case flagType == "float32" || flagType == "float64": // Convert float strings to numbers if v, err := strconv.ParseFloat(f.DefValue, 64); err == nil { flag.Default = v } else { flag.Default = f.DefValue } case strings.HasSuffix(flagType, "Slice") || strings.HasSuffix(flagType, "Array"): // Convert slice/array defaults to empty array or preserve value if f.DefValue == "[]" { flag.Default = []string{} } else { flag.Default = f.DefValue } default: // For all other types, preserve as string flag.Default = f.DefValue } } // Try to get enum values from the flag value if enumValuer, ok := f.Value.(EnumValuer); ok { flag.Enum = enumValuer.GetValidValues() } return flag } // getCategory determines the command category based on its path. func getCategory(path []string) string { if len(path) == 0 { return "admin" } // Handle settings command specially - settings set/unset is write, settings get is read if path[0] == "settings" { if len(path) >= 2 && (path[1] == "set" || path[1] == "unset") { return "write" } return "read" } switch path[0] { case "get", "describe", "health": return "read" case "create", "delete", "patch", "start", "cancel", "archive", "unarchive", "cutover": return "write" default: return "admin" } } // parseExamples parses Cobra-style examples into our format. // Cobra examples are typically formatted as: // // # Comment describing the example // command args // // Multi-line examples using backslash continuations are joined into a single // command string so that downstream consumers (e.g. MCP example conversion) // see the full command with all flags: // // kubectl-mtv create provider --name vsphere-prod \ // --type vsphere \ // --url https://vcenter/sdk // // becomes: "kubectl-mtv create provider --name vsphere-prod --type vsphere --url https://vcenter/sdk" func parseExamples(exampleText string) []Example { if exampleText == "" { return nil } var examples []Example lines := strings.Split(exampleText, "\n") var currentDesc string var pendingCmd string // accumulates backslash-continued lines for _, line := range lines { line = strings.TrimSpace(line) if line == "" { continue } if strings.HasPrefix(line, "#") { // Flush any pending command before starting a new description if pendingCmd != "" { examples = append(examples, Example{ Description: currentDesc, Command: pendingCmd, }) pendingCmd = "" } // This is a description comment (overwrites any previous unused description) currentDesc = strings.TrimSpace(strings.TrimPrefix(line, "#")) } else if strings.HasSuffix(line, "\\") { // Backslash continuation: strip the trailing '\' and accumulate part := strings.TrimSpace(strings.TrimSuffix(line, "\\")) if pendingCmd == "" { pendingCmd = part } else { pendingCmd += " " + part } } else { // Final line of a command (no trailing backslash) if pendingCmd != "" { // Join with accumulated continuation lines pendingCmd += " " + line examples = append(examples, Example{ Description: currentDesc, Command: pendingCmd, }) pendingCmd = "" } else { // Single-line command examples = append(examples, Example{ Description: currentDesc, Command: line, }) } currentDesc = "" } } // Flush any trailing continued command (edge case: example ends with '\') if pendingCmd != "" { examples = append(examples, Example{ Description: currentDesc, Command: pendingCmd, }) } return examples } // RequiredFlagAnnotation is the annotation key Cobra uses to mark required flags. // This is used when checking if a flag is required via MarkFlagRequired. var requiredFlagRegex = regexp.MustCompile(`required`) // IsRequiredFlag checks if a flag is marked as required on a command. func IsRequiredFlag(cmd *cobra.Command, flagName string) bool { f := cmd.Flag(flagName) if f == nil { return false } if f.Annotations == nil { return false } for key := range f.Annotations { if requiredFlagRegex.MatchString(key) { return true } } return false }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/help/generator_test.go
Go
package help import ( "testing" "github.com/spf13/cobra" ) // --- helpers --- // testEnumFlag implements EnumValuer for testing enum detection. type testEnumFlag struct { val string validValues []string } func (f *testEnumFlag) String() string { return f.val } func (f *testEnumFlag) Set(v string) error { f.val = v; return nil } func (f *testEnumFlag) Type() string { return "string" } func (f *testEnumFlag) GetValidValues() []string { return f.validValues } // buildTree creates a tiny command tree for testing: // // root // ├── get // │ ├── plan (runnable, read) // │ └── provider (runnable, read) // ├── create // │ └── plan (runnable, write) // ├── delete // │ └── plan (runnable, write) // └── health (runnable, read) func buildTree() *cobra.Command { root := &cobra.Command{ Use: "kubectl-mtv", Short: "Migrate virtual machines", Long: "Long description of kubectl-mtv", } root.PersistentFlags().IntP("verbose", "v", 0, "Verbosity level") root.PersistentFlags().BoolP("all-namespaces", "A", false, "All namespaces") // --- get --- getCmd := &cobra.Command{Use: "get", Short: "Get resources"} getPlanCmd := &cobra.Command{ Use: "plan", Short: "Get migration plans", Long: "Get migration plans with optional filters.", Aliases: []string{"plans"}, Example: ` # List all plans kubectl-mtv get plan # Get a specific plan kubectl-mtv get plan --name my-plan`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } getPlanCmd.Flags().StringP("name", "", "", "Plan name") getPlanCmd.Flags().StringP("output", "o", "table", "Output format") getProviderCmd := &cobra.Command{ Use: "provider", Short: "Get providers", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } getProviderCmd.Flags().StringP("name", "", "", "Provider name") getCmd.AddCommand(getPlanCmd, getProviderCmd) // --- create --- createCmd := &cobra.Command{Use: "create", Short: "Create resources"} createPlanCmd := &cobra.Command{ Use: "plan", Short: "Create a migration plan", Args: cobra.NoArgs, Example: ` # Create a plan kubectl-mtv create plan --name my-plan \ --source vsphere-prod \ --target host`, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } createPlanCmd.Flags().String("name", "", "Plan name") _ = createPlanCmd.MarkFlagRequired("name") createPlanCmd.Flags().String("source", "", "Source provider") createPlanCmd.Flags().String("target", "", "Target") createCmd.AddCommand(createPlanCmd) // --- delete --- deleteCmd := &cobra.Command{Use: "delete", Short: "Delete resources"} deletePlanCmd := &cobra.Command{ Use: "plan", Short: "Delete migration plans", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } deletePlanCmd.Flags().StringSlice("name", nil, "Plan names (comma-separated)") deletePlanCmd.Flags().Bool("all", false, "Delete all plans") deleteCmd.AddCommand(deletePlanCmd) // --- health --- healthCmd := &cobra.Command{ Use: "health", Short: "Check MTV health", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } root.AddCommand(getCmd, createCmd, deleteCmd, healthCmd) return root } // --- Generate tests --- func TestGenerate_BasicSchema(t *testing.T) { root := buildTree() schema := Generate(root, "v0.1.0", DefaultOptions()) if schema.Version != SchemaVersion { t.Errorf("expected version %s, got %s", SchemaVersion, schema.Version) } if schema.CLIVersion != "v0.1.0" { t.Errorf("expected cli version v0.1.0, got %s", schema.CLIVersion) } if schema.Name != "kubectl-mtv" { t.Errorf("expected name kubectl-mtv, got %s", schema.Name) } if schema.Description != "Migrate virtual machines" { t.Errorf("expected short description, got %s", schema.Description) } if schema.LongDescription != "Long description of kubectl-mtv" { t.Errorf("expected long description, got %s", schema.LongDescription) } } func TestGenerate_CommandCount(t *testing.T) { root := buildTree() schema := Generate(root, "v0.1.0", DefaultOptions()) // We expect: get plan, get provider, create plan, delete plan, health = 5 if len(schema.Commands) != 5 { t.Errorf("expected 5 commands, got %d", len(schema.Commands)) for _, c := range schema.Commands { t.Logf(" command: %s", c.PathString) } } } func TestGenerate_ReadOnlyFilter(t *testing.T) { root := buildTree() opts := DefaultOptions() opts.ReadOnly = true schema := Generate(root, "v0.1.0", opts) // Read-only: get plan, get provider, health = 3 if len(schema.Commands) != 3 { t.Errorf("expected 3 read-only commands, got %d", len(schema.Commands)) for _, c := range schema.Commands { t.Logf(" command: %s (category=%s)", c.PathString, c.Category) } } for _, c := range schema.Commands { if c.Category != "read" { t.Errorf("expected category read, got %s for %s", c.Category, c.PathString) } } } func TestGenerate_WriteFilter(t *testing.T) { root := buildTree() opts := DefaultOptions() opts.Write = true schema := Generate(root, "v0.1.0", opts) // Write: create plan, delete plan = 2 if len(schema.Commands) != 2 { t.Errorf("expected 2 write commands, got %d", len(schema.Commands)) for _, c := range schema.Commands { t.Logf(" command: %s (category=%s)", c.PathString, c.Category) } } for _, c := range schema.Commands { if c.Category != "write" { t.Errorf("expected category write, got %s for %s", c.Category, c.PathString) } } } func TestGenerate_ShortMode(t *testing.T) { root := buildTree() opts := DefaultOptions() opts.Short = true schema := Generate(root, "v0.1.0", opts) for _, c := range schema.Commands { if c.LongDescription != "" { t.Errorf("expected empty long description in short mode for %s, got %q", c.PathString, c.LongDescription) } if len(c.Examples) > 0 { t.Errorf("expected no examples in short mode for %s, got %d", c.PathString, len(c.Examples)) } } } func TestGenerate_GlobalFlags(t *testing.T) { root := buildTree() opts := DefaultOptions() opts.IncludeGlobalFlags = true schema := Generate(root, "v0.1.0", opts) if len(schema.GlobalFlags) == 0 { t.Error("expected global flags to be populated") } flagNames := map[string]bool{} for _, f := range schema.GlobalFlags { flagNames[f.Name] = true } if !flagNames["verbose"] { t.Error("expected global flag 'verbose'") } if !flagNames["all-namespaces"] { t.Error("expected global flag 'all-namespaces'") } } func TestGenerate_NoGlobalFlags(t *testing.T) { root := buildTree() opts := DefaultOptions() opts.IncludeGlobalFlags = false schema := Generate(root, "v0.1.0", opts) if len(schema.GlobalFlags) != 0 { t.Errorf("expected no global flags, got %d", len(schema.GlobalFlags)) } } func TestGenerate_HiddenCommandsExcluded(t *testing.T) { root := buildTree() hiddenCmd := &cobra.Command{ Use: "secret", Short: "Hidden command", Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } root.AddCommand(hiddenCmd) schema := Generate(root, "v0.1.0", DefaultOptions()) for _, c := range schema.Commands { if c.Name == "secret" { t.Error("hidden command should not appear without IncludeHidden") } } } func TestGenerate_HiddenCommandsIncluded(t *testing.T) { root := buildTree() hiddenCmd := &cobra.Command{ Use: "secret", Short: "Hidden command", Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } root.AddCommand(hiddenCmd) opts := DefaultOptions() opts.IncludeHidden = true schema := Generate(root, "v0.1.0", opts) found := false for _, c := range schema.Commands { if c.Name == "secret" { found = true break } } if !found { t.Error("hidden command should appear with IncludeHidden") } } // --- commandToSchema tests --- func TestCommandToSchema_BasicFields(t *testing.T) { root := buildTree() // Find "get plan" getCmd, _, _ := root.Find([]string{"get", "plan"}) path := []string{"get", "plan"} c := commandToSchema(getCmd, path, DefaultOptions()) if c.Name != "plan" { t.Errorf("expected name 'plan', got %q", c.Name) } if c.PathString != "get plan" { t.Errorf("expected path_string 'get plan', got %q", c.PathString) } if c.Category != "read" { t.Errorf("expected category read, got %q", c.Category) } if c.Description != "Get migration plans" { t.Errorf("expected description, got %q", c.Description) } if c.LongDescription != "Get migration plans with optional filters." { t.Errorf("expected long description, got %q", c.LongDescription) } if len(c.Aliases) != 1 || c.Aliases[0] != "plans" { t.Errorf("expected aliases [plans], got %v", c.Aliases) } } func TestCommandToSchema_Flags(t *testing.T) { root := buildTree() getCmd, _, _ := root.Find([]string{"get", "plan"}) path := []string{"get", "plan"} c := commandToSchema(getCmd, path, DefaultOptions()) flagNames := map[string]bool{} for _, f := range c.Flags { flagNames[f.Name] = true } if !flagNames["name"] { t.Error("expected flag 'name'") } if !flagNames["output"] { t.Error("expected flag 'output'") } } func TestCommandToSchema_RequiredFlag(t *testing.T) { root := buildTree() createPlan, _, _ := root.Find([]string{"create", "plan"}) path := []string{"create", "plan"} c := commandToSchema(createPlan, path, DefaultOptions()) for _, f := range c.Flags { if f.Name == "name" && !f.Required { t.Error("expected 'name' flag to be marked as required") } } } func TestCommandToSchema_Examples(t *testing.T) { root := buildTree() getCmd, _, _ := root.Find([]string{"get", "plan"}) path := []string{"get", "plan"} c := commandToSchema(getCmd, path, DefaultOptions()) if len(c.Examples) != 2 { t.Fatalf("expected 2 examples, got %d", len(c.Examples)) } if c.Examples[0].Description != "List all plans" { t.Errorf("expected first example description, got %q", c.Examples[0].Description) } if c.Examples[0].Command != "kubectl-mtv get plan" { t.Errorf("expected first example command, got %q", c.Examples[0].Command) } } // --- flagToSchema tests --- func TestFlagToSchema_String(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().StringP("name", "n", "default-val", "The name") f := cmd.Flags().Lookup("name") schema := flagToSchema(f) if schema.Name != "name" { t.Errorf("expected name 'name', got %q", schema.Name) } if schema.Shorthand != "n" { t.Errorf("expected shorthand 'n', got %q", schema.Shorthand) } if schema.Type != "string" { t.Errorf("expected type 'string', got %q", schema.Type) } if schema.Default != "default-val" { t.Errorf("expected default 'default-val', got %v", schema.Default) } if schema.Description != "The name" { t.Errorf("expected description, got %q", schema.Description) } } func TestFlagToSchema_Bool(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().Bool("verbose", false, "Verbose output") f := cmd.Flags().Lookup("verbose") schema := flagToSchema(f) if schema.Type != "bool" { t.Errorf("expected type 'bool', got %q", schema.Type) } if def, ok := schema.Default.(bool); !ok || def != false { t.Errorf("expected default false, got %v", schema.Default) } } func TestFlagToSchema_BoolTrue(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().Bool("enabled", true, "Enable feature") f := cmd.Flags().Lookup("enabled") schema := flagToSchema(f) if def, ok := schema.Default.(bool); !ok || def != true { t.Errorf("expected default true, got %v", schema.Default) } } func TestFlagToSchema_Int(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().Int("count", 42, "Number of items") f := cmd.Flags().Lookup("count") schema := flagToSchema(f) if schema.Type != "int" { t.Errorf("expected type 'int', got %q", schema.Type) } if def, ok := schema.Default.(int64); !ok || def != 42 { t.Errorf("expected default 42, got %v (type %T)", schema.Default, schema.Default) } } func TestFlagToSchema_Float(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().Float64("ratio", 3.14, "Ratio") f := cmd.Flags().Lookup("ratio") schema := flagToSchema(f) if schema.Type != "float64" { t.Errorf("expected type 'float64', got %q", schema.Type) } if def, ok := schema.Default.(float64); !ok || def != 3.14 { t.Errorf("expected default 3.14, got %v", schema.Default) } } func TestFlagToSchema_StringSlice(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().StringSlice("names", nil, "Names") f := cmd.Flags().Lookup("names") schema := flagToSchema(f) if schema.Type != "stringSlice" { t.Errorf("expected type 'stringSlice', got %q", schema.Type) } // Default for nil StringSlice is "[]" if def, ok := schema.Default.([]string); !ok || len(def) != 0 { t.Errorf("expected default empty slice, got %v (type %T)", schema.Default, schema.Default) } } func TestFlagToSchema_Hidden(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().String("secret", "", "Secret flag") _ = cmd.Flags().MarkHidden("secret") f := cmd.Flags().Lookup("secret") schema := flagToSchema(f) if !schema.Hidden { t.Error("expected flag to be marked hidden") } } func TestFlagToSchema_Enum(t *testing.T) { cmd := &cobra.Command{Use: "test"} ef := &testEnumFlag{val: "json", validValues: []string{"json", "yaml", "table"}} cmd.Flags().Var(ef, "output", "Output format") f := cmd.Flags().Lookup("output") schema := flagToSchema(f) if len(schema.Enum) != 3 { t.Fatalf("expected 3 enum values, got %d", len(schema.Enum)) } if schema.Enum[0] != "json" || schema.Enum[1] != "yaml" || schema.Enum[2] != "table" { t.Errorf("unexpected enum values: %v", schema.Enum) } } // --- getCategory tests --- func TestGetCategory(t *testing.T) { tests := []struct { path []string expected string }{ {[]string{}, "admin"}, {[]string{"get"}, "read"}, {[]string{"get", "plan"}, "read"}, {[]string{"describe"}, "read"}, {[]string{"describe", "plan"}, "read"}, {[]string{"health"}, "read"}, {[]string{"create"}, "write"}, {[]string{"create", "plan"}, "write"}, {[]string{"delete"}, "write"}, {[]string{"delete", "plan"}, "write"}, {[]string{"patch"}, "write"}, {[]string{"patch", "plan"}, "write"}, {[]string{"start"}, "write"}, {[]string{"start", "plan"}, "write"}, {[]string{"cancel"}, "write"}, {[]string{"archive"}, "write"}, {[]string{"unarchive"}, "write"}, {[]string{"cutover"}, "write"}, {[]string{"settings"}, "read"}, {[]string{"settings", "get"}, "read"}, {[]string{"settings", "set"}, "write"}, {[]string{"settings", "unset"}, "write"}, {[]string{"unknown"}, "admin"}, {[]string{"help"}, "admin"}, } for _, tt := range tests { t.Run(joinPath(tt.path), func(t *testing.T) { result := getCategory(tt.path) if result != tt.expected { t.Errorf("getCategory(%v) = %q, want %q", tt.path, result, tt.expected) } }) } } func joinPath(path []string) string { if len(path) == 0 { return "<empty>" } result := path[0] for _, p := range path[1:] { result += "/" + p } return result } // --- parseExamples tests --- func TestParseExamples_Empty(t *testing.T) { examples := parseExamples("") if examples != nil { t.Errorf("expected nil for empty input, got %v", examples) } } func TestParseExamples_SingleLine(t *testing.T) { input := ` # List plans kubectl-mtv get plan` examples := parseExamples(input) if len(examples) != 1 { t.Fatalf("expected 1 example, got %d", len(examples)) } if examples[0].Description != "List plans" { t.Errorf("expected description 'List plans', got %q", examples[0].Description) } if examples[0].Command != "kubectl-mtv get plan" { t.Errorf("expected command 'kubectl-mtv get plan', got %q", examples[0].Command) } } func TestParseExamples_MultipleExamples(t *testing.T) { input := ` # List all plans kubectl-mtv get plan # Get a specific plan kubectl-mtv get plan --name my-plan` examples := parseExamples(input) if len(examples) != 2 { t.Fatalf("expected 2 examples, got %d", len(examples)) } if examples[0].Description != "List all plans" { t.Errorf("example[0] desc = %q", examples[0].Description) } if examples[1].Description != "Get a specific plan" { t.Errorf("example[1] desc = %q", examples[1].Description) } if examples[1].Command != "kubectl-mtv get plan --name my-plan" { t.Errorf("example[1] cmd = %q", examples[1].Command) } } func TestParseExamples_BackslashContinuation(t *testing.T) { input := ` # Create a plan with multiple flags kubectl-mtv create plan --name my-plan \ --source vsphere-prod \ --target host` examples := parseExamples(input) if len(examples) != 1 { t.Fatalf("expected 1 example, got %d", len(examples)) } expected := "kubectl-mtv create plan --name my-plan --source vsphere-prod --target host" if examples[0].Command != expected { t.Errorf("expected command %q, got %q", expected, examples[0].Command) } } func TestParseExamples_NoDescription(t *testing.T) { input := ` kubectl-mtv get plan` examples := parseExamples(input) if len(examples) != 1 { t.Fatalf("expected 1 example, got %d", len(examples)) } if examples[0].Description != "" { t.Errorf("expected empty description, got %q", examples[0].Description) } } func TestParseExamples_TrailingBackslash(t *testing.T) { // Edge case: example ends with backslash but no continuation input := ` # Trailing backslash edge case kubectl-mtv get plan \` examples := parseExamples(input) if len(examples) != 1 { t.Fatalf("expected 1 example, got %d", len(examples)) } if examples[0].Command != "kubectl-mtv get plan" { t.Errorf("expected 'kubectl-mtv get plan', got %q", examples[0].Command) } } func TestParseExamples_ConsecutiveDescriptions(t *testing.T) { // When two # comments appear in a row, the second one overwrites the first input := ` # First comment # Actual description kubectl-mtv get plan` examples := parseExamples(input) if len(examples) != 1 { t.Fatalf("expected 1 example, got %d", len(examples)) } if examples[0].Description != "Actual description" { t.Errorf("expected 'Actual description', got %q", examples[0].Description) } } func TestParseExamples_DescriptionThenNewExample(t *testing.T) { // A pending command should be flushed when a new description appears input := ` # First example kubectl-mtv get plan \ --name foo # Second example kubectl-mtv delete plan --name bar` examples := parseExamples(input) if len(examples) != 2 { t.Fatalf("expected 2 examples, got %d", len(examples)) } if examples[0].Command != "kubectl-mtv get plan --name foo" { t.Errorf("example[0] cmd = %q", examples[0].Command) } if examples[1].Command != "kubectl-mtv delete plan --name bar" { t.Errorf("example[1] cmd = %q", examples[1].Command) } } // --- FilterByPath tests --- func TestFilterByPath_NoFilter(t *testing.T) { root := buildTree() schema := Generate(root, "v0.1.0", DefaultOptions()) total := len(schema.Commands) n := FilterByPath(schema, nil) if n != total { t.Errorf("expected %d commands with nil prefix, got %d", total, n) } } func TestFilterByPath_GetCommands(t *testing.T) { root := buildTree() schema := Generate(root, "v0.1.0", DefaultOptions()) n := FilterByPath(schema, []string{"get"}) if n != 2 { t.Errorf("expected 2 'get' commands, got %d", n) for _, c := range schema.Commands { t.Logf(" command: %s", c.PathString) } } } func TestFilterByPath_SpecificCommand(t *testing.T) { root := buildTree() schema := Generate(root, "v0.1.0", DefaultOptions()) n := FilterByPath(schema, []string{"get", "plan"}) if n != 1 { t.Errorf("expected 1 'get plan' command, got %d", n) } if len(schema.Commands) != 1 { t.Fatalf("expected exactly 1 command after filter") } if schema.Commands[0].PathString != "get plan" { t.Errorf("expected 'get plan', got %q", schema.Commands[0].PathString) } } func TestFilterByPath_NoMatch(t *testing.T) { root := buildTree() schema := Generate(root, "v0.1.0", DefaultOptions()) n := FilterByPath(schema, []string{"nonexistent"}) if n != 0 { t.Errorf("expected 0 commands for nonexistent prefix, got %d", n) } } // --- walkCommands tests --- func TestWalkCommands_CountsAllNodes(t *testing.T) { root := buildTree() var visited []string walkCommands(root, []string{}, func(cmd *cobra.Command, path []string) { if len(path) > 0 { visited = append(visited, joinPath(path)) } }) // Expect: get, get/plan, get/provider, create, create/plan, delete, delete/plan, health // Plus cobra auto-added commands (completion, help) might appear too if len(visited) < 8 { t.Errorf("expected at least 8 visited nodes, got %d: %v", len(visited), visited) } } // --- IsRequiredFlag tests --- func TestIsRequiredFlag_Required(t *testing.T) { cmd := &cobra.Command{Use: "test", RunE: func(cmd *cobra.Command, args []string) error { return nil }} cmd.Flags().String("name", "", "Name") _ = cmd.MarkFlagRequired("name") if !IsRequiredFlag(cmd, "name") { t.Error("expected 'name' to be required") } } func TestIsRequiredFlag_NotRequired(t *testing.T) { cmd := &cobra.Command{Use: "test", RunE: func(cmd *cobra.Command, args []string) error { return nil }} cmd.Flags().String("name", "", "Name") if IsRequiredFlag(cmd, "name") { t.Error("expected 'name' to not be required") } } func TestIsRequiredFlag_NonExistentFlag(t *testing.T) { cmd := &cobra.Command{Use: "test", RunE: func(cmd *cobra.Command, args []string) error { return nil }} if IsRequiredFlag(cmd, "nonexistent") { t.Error("expected false for non-existent flag") } } // --- DefaultOptions tests --- func TestDefaultOptions(t *testing.T) { opts := DefaultOptions() if opts.ReadOnly { t.Error("expected ReadOnly to be false") } if opts.Write { t.Error("expected Write to be false") } if !opts.IncludeGlobalFlags { t.Error("expected IncludeGlobalFlags to be true") } if opts.IncludeHidden { t.Error("expected IncludeHidden to be false") } if opts.Short { t.Error("expected Short to be false") } } // --- Non-runnable command tests --- func TestGenerate_NonRunnableParentExcluded(t *testing.T) { root := buildTree() schema := Generate(root, "v0.1.0", DefaultOptions()) for _, c := range schema.Commands { // "get", "create", "delete" are non-runnable parents with < 3 runnable children each // They should NOT appear in the schema if c.PathString == "get" || c.PathString == "create" || c.PathString == "delete" { t.Errorf("non-runnable parent %q should not appear in schema", c.PathString) } } } func TestGenerate_NonRunnableParentIncludedWith3PlusChildren(t *testing.T) { // Create a command tree where a depth-2 non-runnable parent has 3+ runnable children root := &cobra.Command{Use: "kubectl-mtv", Short: "CLI"} getCmd := &cobra.Command{Use: "get", Short: "Get resources"} inventoryCmd := &cobra.Command{Use: "inventory", Short: "Get inventory resources"} for _, name := range []string{"vm", "network", "storage"} { child := &cobra.Command{ Use: name, Short: "Get " + name, RunE: func(cmd *cobra.Command, args []string) error { return nil }, } inventoryCmd.AddCommand(child) } getCmd.AddCommand(inventoryCmd) root.AddCommand(getCmd) schema := Generate(root, "v0.1.0", DefaultOptions()) found := false for _, c := range schema.Commands { if c.PathString == "get inventory" { found = true if c.Runnable { t.Error("expected 'get inventory' to be non-runnable") } break } } if !found { t.Error("expected 'get inventory' to appear (non-runnable parent with 3+ children)") } } // --- Shorthand detection via schema --- func TestFlagToSchema_Shorthand(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().StringP("provider", "p", "", "Provider name") f := cmd.Flags().Lookup("provider") schema := flagToSchema(f) if schema.Shorthand != "p" { t.Errorf("expected shorthand 'p', got %q", schema.Shorthand) } } func TestFlagToSchema_NoShorthand(t *testing.T) { cmd := &cobra.Command{Use: "test"} cmd.Flags().String("name", "", "Name") f := cmd.Flags().Lookup("name") schema := flagToSchema(f) if schema.Shorthand != "" { t.Errorf("expected empty shorthand, got %q", schema.Shorthand) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/help/topics.go
Go
package help import "strings" // Topic represents a built-in help topic that provides reference documentation // for a domain-specific language or concept used across multiple commands. type Topic struct { // Name is the topic identifier (e.g., "tsl", "karl") Name string `json:"name" yaml:"name"` // Short is a one-line description of the topic Short string `json:"short" yaml:"short"` // Content is the full reference text Content string `json:"content" yaml:"content"` } // topicRegistry holds all registered help topics. var topicRegistry = []Topic{ { Name: "tsl", Short: "Tree Search Language (TSL) query syntax reference", Content: `Query Language (TSL) Syntax ========================== TSL is used to filter inventory results with --query "where ..." and to select VMs for migration plans with --vms "where ...". Query Structure: [SELECT fields] WHERE condition [ORDER BY field [ASC|DESC]] [LIMIT n] For --vms flag: where <condition> Operators: Comparison: = != <> < <= > >= Arithmetic: + - * / % String match: like (% wildcard), ilike (case-insensitive) ~= (regex match), ~! (regex not match) Logical: and, or, not Set/range: in ['a','b'], not in ['a','b'], between X and Y Null checks: is null, is not null Array and Aggregate Functions: len(field) length of an array field sum(field[*].sub) sum of numeric values in an array any(field[*].sub = 'value') true if any element matches all(field[*].sub >= N) true if all elements match Array Access and SI Units: field[0] index access (zero-based) field[*].sub wildcard access across all elements field.sub implicit traversal (same as field[*].sub) 4Gi, 512Mi, 1Ti SI unit suffixes (Ki, Mi, Gi, Ti, Pi) Field Access: Dot notation for nested fields: parent.id, guest.distribution To discover all available fields for your provider, run: kubectl-mtv get inventory vm --provider <provider> --output json VM Fields by Provider --------------------- vSphere: Identity: name, id, uuid, path, parent.id, parent.kind State: powerState, connectionState Compute: cpuCount, coresPerSocket, memoryMB Guest: guestId, guestName, firmware, isTemplate Network: ipAddress, hostName, host Storage: storageUsed Security: secureBoot, tpmEnabled, changeTrackingEnabled Disks: len(disks), disks[*].capacity, disks[*].datastore.id, disks[*].datastore.name, disks[*].file, disks[*].shared NICs: len(nics), nics[*].mac, nics[*].network.id Networks: len(networks), networks[*].id, networks[*].kind Concerns: len(concerns), concerns[*].category, concerns[*].assessment, concerns[*].label oVirt / RHV: Identity: name, id, path, cluster, host State: status (up, down, ...) Compute: cpuSockets, cpuCores, cpuThreads, memory (bytes) Guest: osType, guestName, guest.distribution, guest.fullVersion Config: haEnabled, stateless, placementPolicyAffinity, display Disks: len(diskAttachments), diskAttachments[*].disk, diskAttachments[*].interface NICs: len(nics), nics[*].name, nics[*].mac, nics[*].interface, nics[*].ipAddress, nics[*].profile Concerns: len(concerns), concerns[*].category, concerns[*].assessment, concerns[*].label OpenStack: Identity: name, id, status Resources: flavor.name, image.name, project.name Volumes: len(attachedVolumes), attachedVolumes[*].ID EC2 (PascalCase): Identity: name, InstanceType, State.Name, PlatformDetails Placement: Placement.AvailabilityZone Network: PublicIpAddress, PrivateIpAddress, VpcId, SubnetId Computed Fields (added by kubectl-mtv, available for all providers): criticalConcerns count of critical migration concerns warningConcerns count of warning migration concerns infoConcerns count of informational migration concerns concernsHuman human-readable concern summary memoryGB memory in GB (converted from MB or bytes) storageUsedGB storage used in GB diskCapacity total disk capacity powerStateHuman human-readable power state provider provider name Examples -------- Basic filtering: where name ~= 'prod-.*' where name like '%web%' where name in ['vm-01','vm-02','vm-03'] By compute resources (vSphere): where powerState = 'poweredOn' and memoryMB > 4096 where cpuCount > 4 and memoryMB > 8192 where memoryMB between 2048 and 16384 By compute resources (oVirt, memory in bytes): where status = 'up' and memory > 4Gi By guest OS: where guestId ~= 'rhel.*' (vSphere) where guest.distribution ~= 'Red Hat.*' (oVirt) By firmware and security: where firmware = 'efi' where isTemplate = false and secureBoot = true By disk and network configuration: where len(disks) > 1 where len(disks) > 1 and cpuCount <= 8 where len(nics) >= 2 where any(disks[*].shared = true) Using the in operator (square brackets required): where guestId in ['rhel8_64Guest','rhel9_64Guest'] where firmware in ['efi','bios'] where guestId not in ['rhel8_64Guest',''] Array element matching with any() (parentheses required for strings): where any(concerns[*].category = 'Critical') where any(concerns[*].category = 'Warning') where any(disks[*].datastore.id = 'datastore-12') By migration concerns: where criticalConcerns > 0 where len(concerns) = 0 By folder path: where path ~= '/Production/.*' where path like '/Datacenter/vm/Linux/%' Sorting and limiting: where memoryMB > 1024 order by memoryMB desc limit 10 where powerState = 'poweredOn' order by name limit 50 OpenStack: where status = 'ACTIVE' and flavor.name = 'm1.large' EC2: where State.Name = 'running' and InstanceType = 'm5.xlarge' where Placement.AvailabilityZone = 'us-east-1a'`, }, { Name: "karl", Short: "Kubernetes Affinity Rule Language (KARL) syntax reference", Content: `Affinity Syntax (KARL) ===================== KARL is used by --target-affinity and --convertor-affinity flags in create plan and patch plan to define Kubernetes pod affinity rules. Syntax: RULE_TYPE pods(selector[,selector...]) on TOPOLOGY [weight=N] Rule Types: REQUIRE hard affinity - pod MUST be placed with matching pods PREFER soft affinity - pod SHOULD be placed with matching pods (weight=1-100) AVOID hard anti-affinity - pod MUST NOT be placed with matching pods REPEL soft anti-affinity - pod SHOULD NOT be placed with matching pods (weight=1-100) REQUIRE and AVOID are strict: the scheduler will not place the pod if the rule cannot be satisfied. PREFER and REPEL are best-effort: the scheduler will try to honor them, with higher weight values taking priority. Topology Keys: node specific node (kubernetes.io/hostname) zone availability zone (topology.kubernetes.io/zone) region cloud region (topology.kubernetes.io/region) rack rack location (topology.kubernetes.io/rack) Label Selectors: Inside pods(...), use comma-separated selectors. All selectors are AND-ed. key=value equality match key in [v1,v2,v3] value in set key not in [v1,v2] value not in set has key label exists (any value) not has key label does not exist Examples -------- Basic co-location and anti-affinity: REQUIRE pods(app=database) on node AVOID pods(app=web) on node Soft affinity with weight: PREFER pods(app=cache) on zone weight=80 REPEL pods(tier in [batch,worker]) on zone weight=50 Multiple label selectors (AND-ed): REQUIRE pods(app=web,tier=frontend,has monitoring) on node Zone-aware placement: PREFER pods(app=api) on zone weight=100 REPEL pods(app=api) on zone weight=50 Using label sets: AVOID pods(env in [staging,dev]) on node REQUIRE pods(storage not in [ephemeral]) on node Convertor pod optimization (place near storage): --convertor-affinity "PREFER pods(app=storage-controller) on node weight=80" Target VM placement (co-locate with database): --target-affinity "REQUIRE pods(app=database) on node" Spread VMs across zones: --target-affinity "REPEL pods(app=myapp) on zone weight=50"`, }, } // GetTopic returns a copy of the topic with the given name, or nil if not found. // The lookup is case-insensitive. func GetTopic(name string) *Topic { lower := strings.ToLower(name) for _, t := range topicRegistry { if t.Name == lower { copy := t return &copy } } return nil } // ListTopics returns a copy of all available help topics. func ListTopics() []Topic { result := make([]Topic, len(topicRegistry)) copy(result, topicRegistry) return result }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/help/topics_test.go
Go
package help import "testing" func TestGetTopic_TSL(t *testing.T) { topic := GetTopic("tsl") if topic == nil { t.Fatal("expected TSL topic, got nil") return } if topic.Name != "tsl" { t.Errorf("expected name 'tsl', got %q", topic.Name) } if topic.Short == "" { t.Error("expected non-empty short description") } if topic.Content == "" { t.Error("expected non-empty content") } } func TestGetTopic_KARL(t *testing.T) { topic := GetTopic("karl") if topic == nil { t.Fatal("expected KARL topic, got nil") return } if topic.Name != "karl" { t.Errorf("expected name 'karl', got %q", topic.Name) } if topic.Short == "" { t.Error("expected non-empty short description") } if topic.Content == "" { t.Error("expected non-empty content") } } func TestGetTopic_CaseInsensitive(t *testing.T) { tests := []string{"TSL", "Tsl", "tSl", "tsl"} for _, name := range tests { topic := GetTopic(name) if topic == nil { t.Errorf("GetTopic(%q) returned nil", name) } } } func TestGetTopic_NotFound(t *testing.T) { topic := GetTopic("nonexistent") if topic != nil { t.Errorf("expected nil for nonexistent topic, got %+v", topic) } } func TestGetTopic_ReturnsCopy(t *testing.T) { topic1 := GetTopic("tsl") topic2 := GetTopic("tsl") if topic1 == topic2 { t.Error("GetTopic should return a copy, not the same pointer") } // Modify one and verify the other is unchanged topic1.Short = "modified" topic2Again := GetTopic("tsl") if topic2Again.Short == "modified" { t.Error("modifying returned topic should not affect the registry") } } func TestListTopics(t *testing.T) { topics := ListTopics() if len(topics) < 2 { t.Fatalf("expected at least 2 topics, got %d", len(topics)) } names := map[string]bool{} for _, topic := range topics { names[topic.Name] = true if topic.Short == "" { t.Errorf("topic %q has empty short description", topic.Name) } if topic.Content == "" { t.Errorf("topic %q has empty content", topic.Name) } } if !names["tsl"] { t.Error("expected 'tsl' topic in list") } if !names["karl"] { t.Error("expected 'karl' topic in list") } } func TestListTopics_ReturnsCopy(t *testing.T) { topics1 := ListTopics() topics2 := ListTopics() // Modify the first copy and verify the second is unaffected topics1[0].Name = "modified" if topics2[0].Name == "modified" { t.Error("ListTopics should return a copy of the registry") } } func TestTopicContent_TSL_HasExpectedSections(t *testing.T) { topic := GetTopic("tsl") if topic == nil { t.Fatal("expected TSL topic") } sections := []string{ "Query Structure:", "Operators:", "VM Fields by Provider", "vSphere:", "oVirt / RHV:", "OpenStack:", "EC2 (PascalCase):", "Examples", } for _, section := range sections { if !containsString(topic.Content, section) { t.Errorf("TSL content missing section: %q", section) } } } func TestTopicContent_KARL_HasExpectedSections(t *testing.T) { topic := GetTopic("karl") if topic == nil { t.Fatal("expected KARL topic") } sections := []string{ "Rule Types:", "Topology Keys:", "Label Selectors:", "Examples", } for _, section := range sections { if !containsString(topic.Content, section) { t.Errorf("KARL content missing section: %q", section) } } } func containsString(s, substr string) bool { return len(s) > 0 && len(substr) > 0 && contains(s, substr) } func contains(s, substr string) bool { for i := 0; i <= len(s)-len(substr); i++ { if s[i:i+len(substr)] == substr { return true } } return false }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/help/types.go
Go
// Package help provides machine-readable help output for kubectl-mtv commands. package help // HelpSchema represents the complete CLI help information in a machine-readable format. type HelpSchema struct { // Version is the schema version (e.g., "1.0") Version string `json:"version" yaml:"version"` // CLIVersion is the kubectl-mtv version (e.g., "v0.1.59") CLIVersion string `json:"cli_version" yaml:"cli_version"` // Name is the CLI name ("kubectl-mtv") Name string `json:"name" yaml:"name"` // Description is the CLI short description Description string `json:"description" yaml:"description"` // LongDescription is the extended CLI description with domain context // (e.g., "Migrate virtual machines from VMware vSphere, oVirt...") LongDescription string `json:"long_description,omitempty" yaml:"long_description,omitempty"` // Commands contains all leaf commands Commands []Command `json:"commands" yaml:"commands"` // GlobalFlags contains flags available to all commands GlobalFlags []Flag `json:"global_flags" yaml:"global_flags"` } // Command represents a single CLI command. type Command struct { // Name is the command name (last segment of path) Name string `json:"name" yaml:"name"` // Path is the full command path as array (e.g., ["get", "plan"]) Path []string `json:"path" yaml:"path"` // PathString is the full command path as space-separated string (e.g., "get plan") PathString string `json:"path_string" yaml:"path_string"` // Description is the short one-line description Description string `json:"description" yaml:"description"` // LongDescription is the extended description with details LongDescription string `json:"long_description,omitempty" yaml:"long_description,omitempty"` // Usage is the usage pattern string Usage string `json:"usage" yaml:"usage"` // Aliases are alternative command names Aliases []string `json:"aliases,omitempty" yaml:"aliases,omitempty"` // Category is one of: "read", "write", "admin" Category string `json:"category" yaml:"category"` // Flags are command-specific flags Flags []Flag `json:"flags" yaml:"flags"` // Examples are usage examples Examples []Example `json:"examples,omitempty" yaml:"examples,omitempty"` // Runnable indicates whether the command can be executed directly. // Non-runnable commands are structural parents (e.g., "get inventory") // included for their description metadata. Runnable bool `json:"runnable" yaml:"runnable"` } // Flag represents a command-line flag. type Flag struct { // Name is the long flag name (without --) Name string `json:"name" yaml:"name"` // Shorthand is the single-char shorthand (without -) Shorthand string `json:"shorthand,omitempty" yaml:"shorthand,omitempty"` // Type is one of: "bool", "string", "int", "stringArray", "duration" Type string `json:"type" yaml:"type"` // Default is the default value Default interface{} `json:"default,omitempty" yaml:"default,omitempty"` // Description is the flag description Description string `json:"description" yaml:"description"` // Required indicates whether the flag is required Required bool `json:"required" yaml:"required"` // Enum contains allowed values (for string flags with choices) Enum []string `json:"enum,omitempty" yaml:"enum,omitempty"` // Hidden indicates whether the flag is hidden from normal help Hidden bool `json:"hidden,omitempty" yaml:"hidden,omitempty"` } // Example represents a usage example. type Example struct { // Description explains what the example does Description string `json:"description" yaml:"description"` // Command is the example command Command string `json:"command" yaml:"command"` } // Options configures the help generation. type Options struct { // ReadOnly includes only read-only commands when true ReadOnly bool // Write includes only write commands when true Write bool // IncludeGlobalFlags includes global flags in output (default: true) IncludeGlobalFlags bool // IncludeHidden includes hidden flags and commands IncludeHidden bool // Short omits long_description and examples from command output Short bool } // DefaultOptions returns the default generation options. func DefaultOptions() Options { return Options{ IncludeGlobalFlags: true, IncludeHidden: false, } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/patch/mapping/network.go
Go
package mapping import ( "context" "fmt" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/klog/v2" "github.com/yaacov/kubectl-mtv/pkg/cmd/create/mapping" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // patchNetworkMapping patches an existing network mapping func patchNetworkMapping(configFlags *genericclioptions.ConfigFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL string) error { klog.V(2).Infof("Patching network mapping '%s' in namespace '%s'", name, namespace) dynamicClient, err := client.GetDynamicClient(configFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } // Get the existing mapping existingMapping, err := dynamicClient.Resource(client.NetworkMapGVR).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { return fmt.Errorf("failed to get network mapping '%s': %v", name, err) } // Extract source provider for pair resolution sourceProviderName, sourceProviderNamespace, err := getSourceProviderFromMapping(existingMapping) if err != nil { return fmt.Errorf("failed to get source provider from mapping: %v", err) } if sourceProviderNamespace != "" { klog.V(2).Infof("Using source provider '%s/%s' for network pair resolution", sourceProviderNamespace, sourceProviderName) } else { klog.V(2).Infof("Using source provider '%s' for network pair resolution", sourceProviderName) } // Extract the existing network pairs from the unstructured mapping // Work with unstructured data throughout to avoid reflection issues currentPairs, found, err := unstructured.NestedSlice(existingMapping.Object, "spec", "map") if err != nil { return fmt.Errorf("failed to extract existing mapping pairs: %v", err) } if !found { currentPairs = []interface{}{} } // Work with unstructured pairs to avoid conversion issues workingPairs := make([]interface{}, len(currentPairs)) copy(workingPairs, currentPairs) klog.V(3).Infof("Current mapping has %d network pairs", len(workingPairs)) // Process removals first if removePairs != "" { sourcesToRemove := parseSourcesToRemove(removePairs) klog.V(2).Infof("Removing %d network pairs from mapping", len(sourcesToRemove)) workingPairs = removeSourceFromUnstructuredPairs(workingPairs, sourcesToRemove) klog.V(2).Infof("Successfully removed network pairs from mapping '%s'", name) } // Process additions if addPairs != "" { klog.V(2).Infof("Adding network pairs to mapping: %s", addPairs) newPairs, err := mapping.ParseNetworkPairs(addPairs, sourceProviderNamespace, configFlags, sourceProviderName, inventoryURL) if err != nil { return fmt.Errorf("failed to parse add-pairs: %v", err) } // Convert new pairs to unstructured format var newUnstructuredPairs []interface{} for _, pair := range newPairs { pairMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&pair) if err != nil { klog.V(2).Infof("Warning: Failed to convert new pair to unstructured, skipping: %v", err) continue } newUnstructuredPairs = append(newUnstructuredPairs, pairMap) } // Check for duplicate sources duplicates := checkUnstructuredSourceDuplicates(workingPairs, newUnstructuredPairs) if len(duplicates) > 0 { klog.V(1).Infof("Warning: Found duplicate sources in add-pairs, skipping: %v", duplicates) fmt.Printf("Warning: Skipping duplicate sources: %s\n", strings.Join(duplicates, ", ")) newUnstructuredPairs = filterOutDuplicateUnstructuredPairs(workingPairs, newUnstructuredPairs) } if len(newUnstructuredPairs) > 0 { workingPairs = append(workingPairs, newUnstructuredPairs...) klog.V(2).Infof("Added %d network pairs to mapping '%s'", len(newUnstructuredPairs), name) } else { klog.V(2).Infof("No new network pairs to add after filtering duplicates") } } // Process updates if updatePairs != "" { klog.V(2).Infof("Updating network pairs in mapping: %s", updatePairs) updatePairsList, err := mapping.ParseNetworkPairs(updatePairs, sourceProviderNamespace, configFlags, sourceProviderName, inventoryURL) if err != nil { return fmt.Errorf("failed to parse update-pairs: %v", err) } // Convert update pairs to unstructured format var updateUnstructuredPairs []interface{} for _, pair := range updatePairsList { pairMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&pair) if err != nil { klog.V(2).Infof("Warning: Failed to convert update pair to unstructured, skipping: %v", err) continue } updateUnstructuredPairs = append(updateUnstructuredPairs, pairMap) } workingPairs = updateUnstructuredPairsBySource(workingPairs, updateUnstructuredPairs) klog.V(2).Infof("Updated %d network pairs in mapping '%s'", len(updateUnstructuredPairs), name) } klog.V(3).Infof("Final working pairs count: %d", len(workingPairs)) // Patch the spec.map field (workingPairs is already unstructured) patchData := map[string]interface{}{ "spec": map[string]interface{}{ "map": workingPairs, }, } patchBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, &unstructured.Unstructured{Object: patchData}) if err != nil { return fmt.Errorf("failed to encode patch data: %v", err) } // Apply the patch _, err = dynamicClient.Resource(client.NetworkMapGVR).Namespace(namespace).Patch( context.TODO(), name, types.MergePatchType, patchBytes, metav1.PatchOptions{}, ) if err != nil { return fmt.Errorf("failed to patch network mapping: %v", err) } fmt.Printf("networkmap/%s patched\n", name) return nil } // removeSourceFromUnstructuredPairs removes pairs with matching source names/IDs from unstructured pairs func removeSourceFromUnstructuredPairs(pairs []interface{}, sourcesToRemove []string) []interface{} { var filteredPairs []interface{} for _, pairInterface := range pairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } // Extract source information sourceInterface, found := pairMap["source"] if !found { filteredPairs = append(filteredPairs, pairInterface) continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { filteredPairs = append(filteredPairs, pairInterface) continue } sourceName, _ := sourceMap["name"].(string) sourceID, _ := sourceMap["id"].(string) shouldRemove := false for _, sourceToRemove := range sourcesToRemove { if sourceName == sourceToRemove || sourceID == sourceToRemove { shouldRemove = true break } } if !shouldRemove { filteredPairs = append(filteredPairs, pairInterface) } } return filteredPairs } // checkUnstructuredSourceDuplicates checks if any of the new pairs have sources that already exist in current pairs func checkUnstructuredSourceDuplicates(currentPairs []interface{}, newPairs []interface{}) []string { var duplicates []string // Create a map of existing sources for quick lookup existingSourceMap := make(map[string]bool) for _, pairInterface := range currentPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { continue } if sourceName, ok := sourceMap["name"].(string); ok && sourceName != "" { existingSourceMap[sourceName] = true } if sourceID, ok := sourceMap["id"].(string); ok && sourceID != "" { existingSourceMap[sourceID] = true } } // Check new pairs against existing sources for _, pairInterface := range newPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { continue } sourceName, _ := sourceMap["name"].(string) sourceID, _ := sourceMap["id"].(string) if sourceName != "" && existingSourceMap[sourceName] { duplicates = append(duplicates, sourceName) } else if sourceID != "" && existingSourceMap[sourceID] { duplicates = append(duplicates, sourceID) } } return duplicates } // filterOutDuplicateUnstructuredPairs removes pairs that have duplicate sources, keeping only unique ones func filterOutDuplicateUnstructuredPairs(currentPairs []interface{}, newPairs []interface{}) []interface{} { // Create a map of existing sources for quick lookup existingSourceMap := make(map[string]bool) for _, pairInterface := range currentPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { continue } if sourceName, ok := sourceMap["name"].(string); ok && sourceName != "" { existingSourceMap[sourceName] = true } if sourceID, ok := sourceMap["id"].(string); ok && sourceID != "" { existingSourceMap[sourceID] = true } } // Filter new pairs to exclude duplicates var filteredPairs []interface{} for _, pairInterface := range newPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { filteredPairs = append(filteredPairs, pairInterface) continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { filteredPairs = append(filteredPairs, pairInterface) continue } sourceName, _ := sourceMap["name"].(string) sourceID, _ := sourceMap["id"].(string) isDuplicate := false if sourceName != "" && existingSourceMap[sourceName] { isDuplicate = true } else if sourceID != "" && existingSourceMap[sourceID] { isDuplicate = true } if !isDuplicate { filteredPairs = append(filteredPairs, pairInterface) } } return filteredPairs } // updateUnstructuredPairsBySource updates or adds pairs based on source name/ID matching func updateUnstructuredPairsBySource(existingPairs []interface{}, newPairs []interface{}) []interface{} { updatedPairs := make([]interface{}, len(existingPairs)) copy(updatedPairs, existingPairs) for _, newPairInterface := range newPairs { newPairMap, ok := newPairInterface.(map[string]interface{}) if !ok { continue } newSourceInterface, found := newPairMap["source"] if !found { // Add new pair if no source info updatedPairs = append(updatedPairs, newPairInterface) continue } newSourceMap, ok := newSourceInterface.(map[string]interface{}) if !ok { updatedPairs = append(updatedPairs, newPairInterface) continue } newSourceName, _ := newSourceMap["name"].(string) newSourceID, _ := newSourceMap["id"].(string) found = false for i, existingPairInterface := range updatedPairs { existingPairMap, ok := existingPairInterface.(map[string]interface{}) if !ok { continue } existingSourceInterface, hasSource := existingPairMap["source"] if !hasSource { continue } existingSourceMap, ok := existingSourceInterface.(map[string]interface{}) if !ok { continue } existingSourceName, _ := existingSourceMap["name"].(string) existingSourceID, _ := existingSourceMap["id"].(string) if (existingSourceName != "" && existingSourceName == newSourceName) || (existingSourceID != "" && existingSourceID == newSourceID) { // Update existing pair updatedPairs[i] = newPairInterface found = true break } } if !found { // Add new pair updatedPairs = append(updatedPairs, newPairInterface) } } return updatedPairs }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/patch/mapping/patch.go
Go
package mapping import ( "fmt" "strings" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" ) // PatchNetwork patches a network mapping func PatchNetwork(configFlags *genericclioptions.ConfigFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL string) error { return patchNetworkMapping(configFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL) } // PatchStorage patches a storage mapping (wrapper for backward compatibility) func PatchStorage(configFlags *genericclioptions.ConfigFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL string) error { return PatchStorageWithOptions(configFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL, false, "", "", "", "", "") } // PatchStorageWithOptions patches a storage mapping with additional options for VolumeMode, AccessMode, and OffloadPlugin func PatchStorageWithOptions(configFlags *genericclioptions.ConfigFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL string, inventoryInsecureSkipTLS bool, defaultVolumeMode, defaultAccessMode, defaultOffloadPlugin, defaultOffloadSecret, defaultOffloadVendor string) error { return patchStorageMappingWithOptions(configFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL, inventoryInsecureSkipTLS, defaultVolumeMode, defaultAccessMode, defaultOffloadPlugin, defaultOffloadSecret, defaultOffloadVendor) } // getSourceProviderFromMapping extracts the source provider name and namespace from a mapping func getSourceProviderFromMapping(mapping *unstructured.Unstructured) (string, string, error) { provider, found, err := unstructured.NestedMap(mapping.Object, "spec", "provider", "source") if err != nil { return "", "", fmt.Errorf("failed to get source provider: %v", err) } if !found || provider == nil { return "", "", fmt.Errorf("source provider not found in mapping") } name, nameOk := provider["name"].(string) namespace, namespaceOk := provider["namespace"].(string) if !nameOk { return "", "", fmt.Errorf("source provider name not found") } // namespace is optional, so we don't error if it's not found if !namespaceOk { namespace = "" } return name, namespace, nil } // parseSourcesToRemove parses a comma-separated list of source names to remove func parseSourcesToRemove(removeStr string) []string { if removeStr == "" { return nil } var sources []string sourceList := strings.Split(removeStr, ",") for _, source := range sourceList { source = strings.TrimSpace(source) if source != "" { sources = append(sources, source) } } return sources }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/patch/mapping/storage.go
Go
package mapping import ( "context" "fmt" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/klog/v2" "github.com/yaacov/kubectl-mtv/pkg/cmd/create/mapping" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // removeSourceFromUnstructuredStoragePairs removes pairs with matching source names/IDs from unstructured pairs func removeSourceFromUnstructuredStoragePairs(pairs []interface{}, sourcesToRemove []string) []interface{} { var filteredPairs []interface{} for _, pairInterface := range pairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } // Extract source information sourceInterface, found := pairMap["source"] if !found { filteredPairs = append(filteredPairs, pairInterface) continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { filteredPairs = append(filteredPairs, pairInterface) continue } sourceName, _ := sourceMap["name"].(string) sourceID, _ := sourceMap["id"].(string) shouldRemove := false for _, sourceToRemove := range sourcesToRemove { if sourceName == sourceToRemove || sourceID == sourceToRemove { shouldRemove = true break } } if !shouldRemove { filteredPairs = append(filteredPairs, pairInterface) } } return filteredPairs } // checkUnstructuredStorageSourceDuplicates checks if any of the new pairs have sources that already exist in current pairs func checkUnstructuredStorageSourceDuplicates(currentPairs []interface{}, newPairs []interface{}) []string { var duplicates []string // Create a map of existing sources for quick lookup existingSourceMap := make(map[string]bool) for _, pairInterface := range currentPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { continue } if sourceName, ok := sourceMap["name"].(string); ok && sourceName != "" { existingSourceMap[sourceName] = true } if sourceID, ok := sourceMap["id"].(string); ok && sourceID != "" { existingSourceMap[sourceID] = true } } // Check new pairs against existing sources for _, pairInterface := range newPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { continue } sourceName, _ := sourceMap["name"].(string) sourceID, _ := sourceMap["id"].(string) if sourceName != "" && existingSourceMap[sourceName] { duplicates = append(duplicates, sourceName) } else if sourceID != "" && existingSourceMap[sourceID] { duplicates = append(duplicates, sourceID) } } return duplicates } // filterOutDuplicateUnstructuredStoragePairs removes pairs that have duplicate sources, keeping only unique ones func filterOutDuplicateUnstructuredStoragePairs(currentPairs []interface{}, newPairs []interface{}) []interface{} { // Create a map of existing sources for quick lookup existingSourceMap := make(map[string]bool) for _, pairInterface := range currentPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { continue } if sourceName, ok := sourceMap["name"].(string); ok && sourceName != "" { existingSourceMap[sourceName] = true } if sourceID, ok := sourceMap["id"].(string); ok && sourceID != "" { existingSourceMap[sourceID] = true } } // Filter new pairs to exclude duplicates var filteredPairs []interface{} for _, pairInterface := range newPairs { pairMap, ok := pairInterface.(map[string]interface{}) if !ok { continue } sourceInterface, found := pairMap["source"] if !found { filteredPairs = append(filteredPairs, pairInterface) continue } sourceMap, ok := sourceInterface.(map[string]interface{}) if !ok { filteredPairs = append(filteredPairs, pairInterface) continue } sourceName, _ := sourceMap["name"].(string) sourceID, _ := sourceMap["id"].(string) isDuplicate := false if sourceName != "" && existingSourceMap[sourceName] { isDuplicate = true } else if sourceID != "" && existingSourceMap[sourceID] { isDuplicate = true } if !isDuplicate { filteredPairs = append(filteredPairs, pairInterface) } } return filteredPairs } // updateUnstructuredStoragePairsBySource updates or adds pairs based on source name/ID matching func updateUnstructuredStoragePairsBySource(existingPairs []interface{}, newPairs []interface{}) []interface{} { updatedPairs := make([]interface{}, len(existingPairs)) copy(updatedPairs, existingPairs) for _, newPairInterface := range newPairs { newPairMap, ok := newPairInterface.(map[string]interface{}) if !ok { continue } newSourceInterface, found := newPairMap["source"] if !found { // Add new pair if no source info updatedPairs = append(updatedPairs, newPairInterface) continue } newSourceMap, ok := newSourceInterface.(map[string]interface{}) if !ok { updatedPairs = append(updatedPairs, newPairInterface) continue } newSourceName, _ := newSourceMap["name"].(string) newSourceID, _ := newSourceMap["id"].(string) found = false for i, existingPairInterface := range updatedPairs { existingPairMap, ok := existingPairInterface.(map[string]interface{}) if !ok { continue } existingSourceInterface, hasSource := existingPairMap["source"] if !hasSource { continue } existingSourceMap, ok := existingSourceInterface.(map[string]interface{}) if !ok { continue } existingSourceName, _ := existingSourceMap["name"].(string) existingSourceID, _ := existingSourceMap["id"].(string) if (existingSourceName != "" && existingSourceName == newSourceName) || (existingSourceID != "" && existingSourceID == newSourceID) { // Update existing pair updatedPairs[i] = newPairInterface found = true break } } if !found { // Add new pair updatedPairs = append(updatedPairs, newPairInterface) } } return updatedPairs } // patchStorageMappingWithOptions patches an existing storage mapping with additional options for VolumeMode, AccessMode, and OffloadPlugin func patchStorageMappingWithOptions(configFlags *genericclioptions.ConfigFlags, name, namespace, addPairs, updatePairs, removePairs, inventoryURL string, inventoryInsecureSkipTLS bool, defaultVolumeMode, defaultAccessMode, defaultOffloadPlugin, defaultOffloadSecret, defaultOffloadVendor string) error { klog.V(2).Infof("Patching storage mapping '%s' in namespace '%s' with enhanced options", name, namespace) dynamicClient, err := client.GetDynamicClient(configFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } // Get the existing mapping existingMapping, err := dynamicClient.Resource(client.StorageMapGVR).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { return fmt.Errorf("failed to get storage mapping '%s': %v", name, err) } // Extract source provider for pair resolution sourceProviderName, sourceProviderNamespace, err := getSourceProviderFromMapping(existingMapping) if err != nil { return fmt.Errorf("failed to get source provider from mapping: %v", err) } if sourceProviderNamespace != "" { klog.V(2).Infof("Using source provider '%s/%s' for storage pair resolution", sourceProviderNamespace, sourceProviderName) } else { klog.V(2).Infof("Using source provider '%s' for storage pair resolution", sourceProviderName) } // Extract the existing storage pairs from the unstructured mapping // Work with unstructured data throughout to avoid reflection issues with Referenced field currentPairs, found, err := unstructured.NestedSlice(existingMapping.Object, "spec", "map") if err != nil { return fmt.Errorf("failed to extract existing mapping pairs: %v", err) } if !found { currentPairs = []interface{}{} } // Work with unstructured pairs to avoid conversion issues workingPairs := make([]interface{}, len(currentPairs)) copy(workingPairs, currentPairs) klog.V(3).Infof("Current mapping has %d storage pairs", len(workingPairs)) // Process removals first if removePairs != "" { sourcesToRemove := parseSourcesToRemove(removePairs) klog.V(2).Infof("Removing %d storage pairs from mapping", len(sourcesToRemove)) workingPairs = removeSourceFromUnstructuredStoragePairs(workingPairs, sourcesToRemove) klog.V(2).Infof("Successfully removed storage pairs from mapping '%s'", name) } // Process additions if addPairs != "" { klog.V(2).Infof("Adding storage pairs to mapping: %s", addPairs) newPairs, err := mapping.ParseStoragePairsWithOptions(mapping.StorageParseOptions{ PairStr: addPairs, DefaultNamespace: sourceProviderNamespace, ConfigFlags: configFlags, SourceProvider: sourceProviderName, InventoryURL: inventoryURL, InventoryInsecureSkipTLS: inventoryInsecureSkipTLS, DefaultVolumeMode: defaultVolumeMode, DefaultAccessMode: defaultAccessMode, DefaultOffloadPlugin: defaultOffloadPlugin, DefaultOffloadSecret: defaultOffloadSecret, DefaultOffloadVendor: defaultOffloadVendor, }) if err != nil { return fmt.Errorf("failed to parse add-pairs: %v", err) } // Convert new pairs to unstructured format var newUnstructuredPairs []interface{} for _, pair := range newPairs { pairMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&pair) if err != nil { klog.V(2).Infof("Warning: Failed to convert new pair to unstructured, skipping: %v", err) continue } newUnstructuredPairs = append(newUnstructuredPairs, pairMap) } // Check for duplicate sources duplicates := checkUnstructuredStorageSourceDuplicates(workingPairs, newUnstructuredPairs) if len(duplicates) > 0 { klog.V(1).Infof("Warning: Found duplicate sources in add-pairs, skipping: %v", duplicates) fmt.Printf("Warning: Skipping duplicate sources: %s\n", strings.Join(duplicates, ", ")) newUnstructuredPairs = filterOutDuplicateUnstructuredStoragePairs(workingPairs, newUnstructuredPairs) } if len(newUnstructuredPairs) > 0 { workingPairs = append(workingPairs, newUnstructuredPairs...) klog.V(2).Infof("Added %d storage pairs to mapping '%s'", len(newUnstructuredPairs), name) } else { klog.V(2).Infof("No new storage pairs to add after filtering duplicates") } } // Process updates if updatePairs != "" { klog.V(2).Infof("Updating storage pairs in mapping: %s", updatePairs) updatePairsList, err := mapping.ParseStoragePairsWithOptions(mapping.StorageParseOptions{ PairStr: updatePairs, DefaultNamespace: sourceProviderNamespace, ConfigFlags: configFlags, SourceProvider: sourceProviderName, InventoryURL: inventoryURL, InventoryInsecureSkipTLS: inventoryInsecureSkipTLS, DefaultVolumeMode: defaultVolumeMode, DefaultAccessMode: defaultAccessMode, DefaultOffloadPlugin: defaultOffloadPlugin, DefaultOffloadSecret: defaultOffloadSecret, DefaultOffloadVendor: defaultOffloadVendor, }) if err != nil { return fmt.Errorf("failed to parse update-pairs: %v", err) } // Convert update pairs to unstructured format var updateUnstructuredPairs []interface{} for _, pair := range updatePairsList { pairMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&pair) if err != nil { klog.V(2).Infof("Warning: Failed to convert update pair to unstructured, skipping: %v", err) continue } updateUnstructuredPairs = append(updateUnstructuredPairs, pairMap) } workingPairs = updateUnstructuredStoragePairsBySource(workingPairs, updateUnstructuredPairs) klog.V(2).Infof("Updated %d storage pairs in mapping '%s'", len(updateUnstructuredPairs), name) } klog.V(3).Infof("Final working pairs count: %d", len(workingPairs)) // Patch the spec.map field (workingPairs is already unstructured) patchData := map[string]interface{}{ "spec": map[string]interface{}{ "map": workingPairs, }, } patchBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, &unstructured.Unstructured{Object: patchData}) if err != nil { return fmt.Errorf("failed to encode patch data: %v", err) } // Apply the patch _, err = dynamicClient.Resource(client.StorageMapGVR).Namespace(namespace).Patch( context.TODO(), name, types.MergePatchType, patchBytes, metav1.PatchOptions{}, ) if err != nil { return fmt.Errorf("failed to patch storage mapping: %v", err) } fmt.Printf("storagemap/%s patched\n", name) return nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/patch/plan/patch.go
Go
package plan import ( "context" "encoding/json" "fmt" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/klog/v2" "github.com/yaacov/karl-interpreter/pkg/karl" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // PatchPlanOptions contains all the options for patching a plan type PatchPlanOptions struct { ConfigFlags *genericclioptions.ConfigFlags Name string Namespace string // Core plan fields TransferNetwork string InstallLegacyDrivers string MigrationType string TargetLabels []string TargetNodeSelector []string UseCompatibilityMode bool TargetAffinity string TargetNamespace string TargetPowerState string // Convertor-related fields ConvertorLabels []string ConvertorNodeSelector []string ConvertorAffinity string // Additional plan fields Description string PreserveClusterCPUModel bool PreserveStaticIPs bool PVCNameTemplate string VolumeNameTemplate string NetworkNameTemplate string MigrateSharedDisks bool Archived bool PVCNameTemplateUseGenerateName bool DeleteGuestConversionPod bool DeleteVmOnFailMigration bool SkipGuestConversion bool Warm bool RunPreflightInspection bool // Flag change tracking UseCompatibilityModeChanged bool PreserveClusterCPUModelChanged bool PreserveStaticIPsChanged bool MigrateSharedDisksChanged bool ArchivedChanged bool PVCNameTemplateUseGenerateNameChanged bool DeleteGuestConversionPodChanged bool DeleteVmOnFailMigrationChanged bool SkipGuestConversionChanged bool WarmChanged bool RunPreflightInspectionChanged bool } // PatchPlan patches an existing migration plan func PatchPlan(opts PatchPlanOptions) error { klog.V(2).Infof("Patching plan '%s' in namespace '%s'", opts.Name, opts.Namespace) dynamicClient, err := client.GetDynamicClient(opts.ConfigFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } // Create a working copy of the spec to build the patch // Work with unstructured data to avoid reflection issues with Referenced field patchSpec := make(map[string]interface{}) planUpdated := false // Update transfer network if provided if opts.TransferNetwork != "" { klog.V(2).Infof("Updating transfer network to '%s'", opts.TransferNetwork) // Parse network name and namespace (supports "namespace/name" or "name" format) var networkName, networkNamespace string if strings.Contains(opts.TransferNetwork, "/") { parts := strings.SplitN(opts.TransferNetwork, "/", 2) networkNamespace = strings.TrimSpace(parts[0]) networkName = strings.TrimSpace(parts[1]) } else { networkName = strings.TrimSpace(opts.TransferNetwork) networkNamespace = opts.Namespace // Use plan namespace as default } patchSpec["transferNetwork"] = map[string]interface{}{ "kind": "NetworkAttachmentDefinition", "apiVersion": "k8s.cni.cncf.io/v1", "name": networkName, "namespace": networkNamespace, } planUpdated = true } // Update install legacy drivers if provided if opts.InstallLegacyDrivers != "" { switch strings.ToLower(opts.InstallLegacyDrivers) { case "true": patchSpec["installLegacyDrivers"] = true klog.V(2).Infof("Updated install legacy drivers to true") planUpdated = true case "false": patchSpec["installLegacyDrivers"] = false klog.V(2).Infof("Updated install legacy drivers to false") planUpdated = true default: return fmt.Errorf("invalid value for install-legacy-drivers: %s (must be 'true' or 'false')", opts.InstallLegacyDrivers) } } // Update migration type if provided if opts.MigrationType != "" { patchSpec["type"] = opts.MigrationType klog.V(2).Infof("Updated migration type to '%s'", opts.MigrationType) // Also set the legacy warm field for backward compatibility if opts.MigrationType == "warm" { patchSpec["warm"] = true } else { patchSpec["warm"] = false } planUpdated = true } // Update target labels if provided if len(opts.TargetLabels) > 0 { labelMap, err := parseKeyValuePairs(opts.TargetLabels, "target-labels") if err != nil { return fmt.Errorf("failed to parse target labels: %v", err) } patchSpec["targetLabels"] = labelMap klog.V(2).Infof("Updated target labels: %v", labelMap) planUpdated = true } // Update target node selector if provided if len(opts.TargetNodeSelector) > 0 { nodeSelectorMap, err := parseKeyValuePairs(opts.TargetNodeSelector, "target-node-selector") if err != nil { return fmt.Errorf("failed to parse target node selector: %v", err) } patchSpec["targetNodeSelector"] = nodeSelectorMap klog.V(2).Infof("Updated target node selector: %v", nodeSelectorMap) planUpdated = true } // Update use compatibility mode if flag was changed if opts.UseCompatibilityModeChanged { patchSpec["useCompatibilityMode"] = opts.UseCompatibilityMode klog.V(2).Infof("Updated use compatibility mode to %t", opts.UseCompatibilityMode) planUpdated = true } // Update target affinity if provided (using karl-interpreter) if opts.TargetAffinity != "" { interpreter := karl.NewKARLInterpreter() err := interpreter.Parse(opts.TargetAffinity) if err != nil { return fmt.Errorf("failed to parse target affinity KARL rule: %v", err) } affinity, err := interpreter.ToAffinity() if err != nil { return fmt.Errorf("failed to convert KARL rule to affinity: %v", err) } // Convert affinity to unstructured format for patch affinityObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(affinity) if err != nil { return fmt.Errorf("failed to convert affinity to unstructured: %v", err) } // JSON Patch: upsert spec.targetAffinity without merging subfields patchOps := []map[string]interface{}{ { "op": "add", // On objects, "add" replaces the key if it already exists "path": "/spec/targetAffinity", "value": affinityObj, }, } patchBytes, err := json.Marshal(patchOps) if err != nil { return fmt.Errorf("failed to marshal JSON patch: %v", err) } _, err = dynamicClient.Resource(client.PlansGVR).Namespace(opts.Namespace).Patch( context.TODO(), opts.Name, types.JSONPatchType, patchBytes, metav1.PatchOptions{}, ) if err != nil { return fmt.Errorf("failed to set target affinity: %v", err) } klog.V(2).Infof("Updated target affinity configuration") planUpdated = true // Mark plan as updated since we've applied a patch } // Update convertor labels if provided if len(opts.ConvertorLabels) > 0 { labelMap, err := parseKeyValuePairs(opts.ConvertorLabels, "convertor-labels") if err != nil { return fmt.Errorf("failed to parse convertor labels: %v", err) } patchSpec["convertorLabels"] = labelMap klog.V(2).Infof("Updated convertor labels: %v", labelMap) planUpdated = true } // Update convertor node selector if provided if len(opts.ConvertorNodeSelector) > 0 { nodeSelectorMap, err := parseKeyValuePairs(opts.ConvertorNodeSelector, "convertor-node-selector") if err != nil { return fmt.Errorf("failed to parse convertor node selector: %v", err) } patchSpec["convertorNodeSelector"] = nodeSelectorMap klog.V(2).Infof("Updated convertor node selector: %v", nodeSelectorMap) planUpdated = true } // Update convertor affinity if provided (using karl-interpreter) if opts.ConvertorAffinity != "" { interpreter := karl.NewKARLInterpreter() err := interpreter.Parse(opts.ConvertorAffinity) if err != nil { return fmt.Errorf("failed to parse convertor affinity KARL rule: %v", err) } affinity, err := interpreter.ToAffinity() if err != nil { return fmt.Errorf("failed to convert KARL rule to affinity: %v", err) } // Convert affinity to unstructured format for patch affinityObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(affinity) if err != nil { return fmt.Errorf("failed to convert affinity to unstructured: %v", err) } // JSON Patch: upsert spec.convertorAffinity without merging subfields patchOps := []map[string]interface{}{ { "op": "add", // On objects, "add" replaces the key if it already exists "path": "/spec/convertorAffinity", "value": affinityObj, }, } patchBytes, err := json.Marshal(patchOps) if err != nil { return fmt.Errorf("failed to marshal JSON patch: %v", err) } _, err = dynamicClient.Resource(client.PlansGVR).Namespace(opts.Namespace).Patch( context.TODO(), opts.Name, types.JSONPatchType, patchBytes, metav1.PatchOptions{}, ) if err != nil { return fmt.Errorf("failed to set convertor affinity: %v", err) } klog.V(2).Infof("Updated convertor affinity configuration") planUpdated = true // Mark plan as updated since we've applied a patch } // Update target namespace if provided if opts.TargetNamespace != "" { patchSpec["targetNamespace"] = opts.TargetNamespace klog.V(2).Infof("Updated target namespace to '%s'", opts.TargetNamespace) planUpdated = true } // Update target power state if provided if opts.TargetPowerState != "" { patchSpec["targetPowerState"] = opts.TargetPowerState klog.V(2).Infof("Updated target power state to '%s'", opts.TargetPowerState) planUpdated = true } // Update description if provided if opts.Description != "" { patchSpec["description"] = opts.Description klog.V(2).Infof("Updated description to '%s'", opts.Description) planUpdated = true } // Update preserve cluster CPU model if flag was changed if opts.PreserveClusterCPUModelChanged { patchSpec["preserveClusterCPUModel"] = opts.PreserveClusterCPUModel klog.V(2).Infof("Updated preserve cluster CPU model to %t", opts.PreserveClusterCPUModel) planUpdated = true } // Update preserve static IPs if flag was changed if opts.PreserveStaticIPsChanged { patchSpec["preserveStaticIPs"] = opts.PreserveStaticIPs klog.V(2).Infof("Updated preserve static IPs to %t", opts.PreserveStaticIPs) planUpdated = true } // Update PVC name template if provided if opts.PVCNameTemplate != "" { patchSpec["pvcNameTemplate"] = opts.PVCNameTemplate klog.V(2).Infof("Updated PVC name template to '%s'", opts.PVCNameTemplate) planUpdated = true } // Update volume name template if provided if opts.VolumeNameTemplate != "" { patchSpec["volumeNameTemplate"] = opts.VolumeNameTemplate klog.V(2).Infof("Updated volume name template to '%s'", opts.VolumeNameTemplate) planUpdated = true } // Update network name template if provided if opts.NetworkNameTemplate != "" { patchSpec["networkNameTemplate"] = opts.NetworkNameTemplate klog.V(2).Infof("Updated network name template to '%s'", opts.NetworkNameTemplate) planUpdated = true } // Update migrate shared disks if flag was changed if opts.MigrateSharedDisksChanged { patchSpec["migrateSharedDisks"] = opts.MigrateSharedDisks klog.V(2).Infof("Updated migrate shared disks to %t", opts.MigrateSharedDisks) planUpdated = true } // Update archived if flag was changed if opts.ArchivedChanged { patchSpec["archived"] = opts.Archived klog.V(2).Infof("Updated archived to %t", opts.Archived) planUpdated = true } // Update PVC name template use generate name if flag was changed if opts.PVCNameTemplateUseGenerateNameChanged { patchSpec["pvcNameTemplateUseGenerateName"] = opts.PVCNameTemplateUseGenerateName klog.V(2).Infof("Updated PVC name template use generate name to %t", opts.PVCNameTemplateUseGenerateName) planUpdated = true } // Update delete guest conversion pod if flag was changed if opts.DeleteGuestConversionPodChanged { patchSpec["deleteGuestConversionPod"] = opts.DeleteGuestConversionPod klog.V(2).Infof("Updated delete guest conversion pod to %t", opts.DeleteGuestConversionPod) planUpdated = true } // Update delete VM on fail migration if flag was changed if opts.DeleteVmOnFailMigrationChanged { patchSpec["deleteVmOnFailMigration"] = opts.DeleteVmOnFailMigration klog.V(2).Infof("Updated delete VM on fail migration to %t", opts.DeleteVmOnFailMigration) planUpdated = true } // Update skip guest conversion if flag was changed if opts.SkipGuestConversionChanged { patchSpec["skipGuestConversion"] = opts.SkipGuestConversion klog.V(2).Infof("Updated skip guest conversion to %t", opts.SkipGuestConversion) planUpdated = true } // Update warm migration if flag was changed if opts.WarmChanged { patchSpec["warm"] = opts.Warm klog.V(2).Infof("Updated warm migration to %t", opts.Warm) planUpdated = true } // Update run preflight inspection if flag was changed if opts.RunPreflightInspectionChanged { patchSpec["runPreflightInspection"] = opts.RunPreflightInspection klog.V(2).Infof("Updated run preflight inspection to %t", opts.RunPreflightInspection) planUpdated = true } // Early return if no changes were made if !planUpdated { fmt.Printf("plan/%s unchanged (no updates specified)\n", opts.Name) return nil } // Apply merge patch if there are spec fields to patch if len(patchSpec) > 0 { // Patch the changed spec fields patchData := map[string]interface{}{ "spec": patchSpec, } patchBytes, err := json.Marshal(patchData) if err != nil { return fmt.Errorf("failed to encode patch data: %v", err) } // Apply the patch _, err = dynamicClient.Resource(client.PlansGVR).Namespace(opts.Namespace).Patch( context.TODO(), opts.Name, types.MergePatchType, patchBytes, metav1.PatchOptions{}, ) if err != nil { return fmt.Errorf("failed to patch plan: %v", err) } } // Print success message since we know planUpdated is true fmt.Printf("plan/%s patched\n", opts.Name) return nil } // PatchPlanVM patches a specific VM within a plan's VM list func PatchPlanVM(configFlags *genericclioptions.ConfigFlags, planName, vmName, namespace string, targetName, rootDisk, instanceType, pvcNameTemplate, volumeNameTemplate, networkNameTemplate, luksSecret, targetPowerState string, addPreHook, addPostHook, removeHook string, clearHooks bool, deleteVmOnFailMigration bool, deleteVmOnFailMigrationChanged bool) error { klog.V(2).Infof("Patching VM '%s' in plan '%s'", vmName, planName) dynamicClient, err := client.GetDynamicClient(configFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } // Get the existing plan existingPlan, err := dynamicClient.Resource(client.PlansGVR).Namespace(namespace).Get(context.TODO(), planName, metav1.GetOptions{}) if err != nil { return fmt.Errorf("failed to get plan '%s': %v", planName, err) } // Get the VMs slice from spec.vms specVMs, exists, err := unstructured.NestedSlice(existingPlan.Object, "spec", "vms") if err != nil { return fmt.Errorf("failed to get VMs from plan spec: %v", err) } if !exists { return fmt.Errorf("no VMs found in plan '%s'", planName) } // Make a copy of the VMs slice to work with workingVMs := make([]interface{}, len(specVMs)) copy(workingVMs, specVMs) // Find the VM in the plan's VMs list vmIndex := -1 for i, v := range workingVMs { vm, ok := v.(map[string]interface{}) if !ok { continue } currentVMName, _, _ := unstructured.NestedString(vm, "name") if currentVMName == vmName { vmIndex = i break } } if vmIndex == -1 { return fmt.Errorf("VM '%s' not found in plan '%s'", vmName, planName) } // Get the VM object to modify vm, ok := workingVMs[vmIndex].(map[string]interface{}) if !ok { return fmt.Errorf("invalid VM data structure for VM '%s'", vmName) } // Create a copy of the VM to work with vmCopy := make(map[string]interface{}) for k, v := range vm { vmCopy[k] = v } // Track if updates were made vmUpdated := false // Update target name if provided if targetName != "" { err = unstructured.SetNestedField(vmCopy, targetName, "targetName") if err != nil { return fmt.Errorf("failed to set target name: %v", err) } klog.V(2).Infof("Updated VM target name to '%s'", targetName) vmUpdated = true } // Update root disk if provided if rootDisk != "" { err = unstructured.SetNestedField(vmCopy, rootDisk, "rootDisk") if err != nil { return fmt.Errorf("failed to set root disk: %v", err) } klog.V(2).Infof("Updated VM root disk to '%s'", rootDisk) vmUpdated = true } // Update instance type if provided if instanceType != "" { err = unstructured.SetNestedField(vmCopy, instanceType, "instanceType") if err != nil { return fmt.Errorf("failed to set instance type: %v", err) } klog.V(2).Infof("Updated VM instance type to '%s'", instanceType) vmUpdated = true } // Update PVC name template if provided if pvcNameTemplate != "" { err = unstructured.SetNestedField(vmCopy, pvcNameTemplate, "pvcNameTemplate") if err != nil { return fmt.Errorf("failed to set PVC name template: %v", err) } klog.V(2).Infof("Updated VM PVC name template to '%s'", pvcNameTemplate) vmUpdated = true } // Update volume name template if provided if volumeNameTemplate != "" { err = unstructured.SetNestedField(vmCopy, volumeNameTemplate, "volumeNameTemplate") if err != nil { return fmt.Errorf("failed to set volume name template: %v", err) } klog.V(2).Infof("Updated VM volume name template to '%s'", volumeNameTemplate) vmUpdated = true } // Update network name template if provided if networkNameTemplate != "" { err = unstructured.SetNestedField(vmCopy, networkNameTemplate, "networkNameTemplate") if err != nil { return fmt.Errorf("failed to set network name template: %v", err) } klog.V(2).Infof("Updated VM network name template to '%s'", networkNameTemplate) vmUpdated = true } // Update LUKS secret if provided if luksSecret != "" { luksRef := map[string]interface{}{ "kind": "Secret", "name": luksSecret, "namespace": namespace, } err = unstructured.SetNestedMap(vmCopy, luksRef, "luks") if err != nil { return fmt.Errorf("failed to set LUKS secret: %v", err) } klog.V(2).Infof("Updated VM LUKS secret to '%s'", luksSecret) vmUpdated = true } // Update target power state if provided if targetPowerState != "" { err = unstructured.SetNestedField(vmCopy, targetPowerState, "targetPowerState") if err != nil { return fmt.Errorf("failed to set target power state: %v", err) } klog.V(2).Infof("Updated VM target power state to '%s'", targetPowerState) vmUpdated = true } // Update delete VM on fail migration if flag was changed if deleteVmOnFailMigrationChanged { err = unstructured.SetNestedField(vmCopy, deleteVmOnFailMigration, "deleteVmOnFailMigration") if err != nil { return fmt.Errorf("failed to set delete VM on fail migration: %v", err) } klog.V(2).Infof("Updated VM delete on fail migration to %t", deleteVmOnFailMigration) vmUpdated = true } // Handle hook operations hooksUpdated, err := updateVMHooksUnstructured(vmCopy, namespace, addPreHook, addPostHook, removeHook, clearHooks) if err != nil { return fmt.Errorf("failed to update VM hooks: %v", err) } if hooksUpdated { vmUpdated = true } // Apply the patch if any changes were made if vmUpdated { // Update the working copy with the modified VM workingVMs[vmIndex] = vmCopy // Patch the VMs array patchData := map[string]interface{}{ "spec": map[string]interface{}{ "vms": workingVMs, }, } patchBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, &unstructured.Unstructured{Object: patchData}) if err != nil { return fmt.Errorf("failed to encode patch data: %v", err) } // Apply the patch _, err = dynamicClient.Resource(client.PlansGVR).Namespace(namespace).Patch( context.TODO(), planName, types.MergePatchType, patchBytes, metav1.PatchOptions{}, ) if err != nil { return fmt.Errorf("failed to patch plan: %v", err) } fmt.Printf("plan/%s vm/%s patched\n", planName, vmName) } else { fmt.Printf("plan/%s vm/%s unchanged (no updates specified)\n", planName, vmName) } return nil } // parseKeyValuePairs parses key=value pairs from string slice func parseKeyValuePairs(pairs []string, fieldName string) (map[string]string, error) { result := make(map[string]string) for _, pairGroup := range pairs { // Split by comma to handle multiple pairs in one flag value keyValuePairs := strings.Split(pairGroup, ",") for _, pair := range keyValuePairs { pair = strings.TrimSpace(pair) if pair == "" { continue } parts := strings.SplitN(pair, "=", 2) if len(parts) == 2 { key := strings.TrimSpace(parts[0]) value := strings.TrimSpace(parts[1]) result[key] = value } else { return nil, fmt.Errorf("invalid %s: %s (expected key=value format)", fieldName, pair) } } } return result, nil } // updateVMHooksUnstructured handles hook operations for a VM func updateVMHooksUnstructured(vm map[string]interface{}, namespace, addPreHook, addPostHook, removeHook string, clearHooks bool) (bool, error) { updated := false // Get existing hooks or create empty slice hooks, _, _ := unstructured.NestedSlice(vm, "hooks") if hooks == nil { hooks = []interface{}{} } // Clear all hooks if requested if clearHooks { if len(hooks) > 0 { err := unstructured.SetNestedSlice(vm, []interface{}{}, "hooks") if err != nil { return false, fmt.Errorf("failed to clear hooks: %v", err) } klog.V(2).Infof("Cleared all hooks from VM") updated = true } return updated, nil } // Remove specific hook if requested if removeHook != "" { originalLen := len(hooks) var filteredHooks []interface{} for _, h := range hooks { hook, ok := h.(map[string]interface{}) if !ok { filteredHooks = append(filteredHooks, h) continue } hookName, _, _ := unstructured.NestedString(hook, "hook", "name") if hookName != strings.TrimSpace(removeHook) { filteredHooks = append(filteredHooks, h) } } if len(filteredHooks) < originalLen { err := unstructured.SetNestedSlice(vm, filteredHooks, "hooks") if err != nil { return false, fmt.Errorf("failed to remove hook: %v", err) } klog.V(2).Infof("Removed hook '%s' from VM", removeHook) updated = true hooks = filteredHooks } } // Add pre-hook if requested if addPreHook != "" { hookName := strings.TrimSpace(addPreHook) // Check if this pre-hook already exists hookExists := false for _, h := range hooks { hook, ok := h.(map[string]interface{}) if !ok { continue } existingHookName, _, _ := unstructured.NestedString(hook, "hook", "name") step, _, _ := unstructured.NestedString(hook, "step") if existingHookName == hookName && step == "PreHook" { hookExists = true break } } if !hookExists { preHookRef := map[string]interface{}{ "step": "PreHook", "hook": map[string]interface{}{ "kind": "Hook", "apiVersion": "forklift.konveyor.io/v1beta1", "name": hookName, "namespace": namespace, }, } hooks = append(hooks, preHookRef) err := unstructured.SetNestedSlice(vm, hooks, "hooks") if err != nil { return false, fmt.Errorf("failed to add pre-hook: %v", err) } klog.V(2).Infof("Added pre-hook '%s' to VM", hookName) updated = true } else { klog.V(1).Infof("Pre-hook '%s' already exists for VM, skipping", hookName) } } // Add post-hook if requested if addPostHook != "" { hookName := strings.TrimSpace(addPostHook) // Check if this post-hook already exists hookExists := false for _, h := range hooks { hook, ok := h.(map[string]interface{}) if !ok { continue } existingHookName, _, _ := unstructured.NestedString(hook, "hook", "name") step, _, _ := unstructured.NestedString(hook, "step") if existingHookName == hookName && step == "PostHook" { hookExists = true break } } if !hookExists { postHookRef := map[string]interface{}{ "step": "PostHook", "hook": map[string]interface{}{ "kind": "Hook", "apiVersion": "forklift.konveyor.io/v1beta1", "name": hookName, "namespace": namespace, }, } hooks = append(hooks, postHookRef) err := unstructured.SetNestedSlice(vm, hooks, "hooks") if err != nil { return false, fmt.Errorf("failed to add post-hook: %v", err) } klog.V(2).Infof("Added post-hook '%s' to VM", hookName) updated = true } else { klog.V(1).Infof("Post-hook '%s' already exists for VM, skipping", hookName) } } return updated, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/patch/provider/patch.go
Go
package provider import ( "context" "fmt" "strconv" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/klog/v2" "github.com/yaacov/kubectl-mtv/pkg/cmd/create/provider/ec2" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // PatchProviderOptions contains the options for patching a provider type PatchProviderOptions struct { ConfigFlags *genericclioptions.ConfigFlags Name string Namespace string // Credentials URL string Username string Password string CACert string Token string // Flags InsecureSkipTLS bool InsecureSkipTLSChanged bool // vSphere VDDK settings VddkInitImage string UseVddkAioOptimization bool UseVddkAioOptimizationChanged bool VddkBufSizeIn64K int VddkBufCount int // OpenStack settings DomainName string ProjectName string RegionName string // EC2 settings EC2Region string EC2TargetRegion string EC2TargetAZ string EC2TargetAccessKeyID string EC2TargetSecretKey string AutoTargetCredentials bool // HyperV settings SMBUrl string SMBUser string SMBPassword string } // PatchProvider patches an existing provider func PatchProvider(opts PatchProviderOptions) error { klog.V(2).Infof("Patching provider '%s' in namespace '%s'", opts.Name, opts.Namespace) dynamicClient, err := client.GetDynamicClient(opts.ConfigFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } // Get the existing provider existingProvider, err := dynamicClient.Resource(client.ProvidersGVR).Namespace(opts.Namespace).Get(context.TODO(), opts.Name, metav1.GetOptions{}) if err != nil { return fmt.Errorf("failed to get provider '%s': %v", opts.Name, err) } // Get provider type using unstructured operations providerType, found, err := unstructured.NestedString(existingProvider.Object, "spec", "type") if err != nil { return fmt.Errorf("failed to get provider type: %v", err) } if !found { return fmt.Errorf("provider type not found in spec") } klog.V(3).Infof("Current provider type: %s", providerType) // For EC2 provider, use regionName (from --provider-region-name) if ec2Region is empty // This allows using --provider-region-name for EC2 regions as shown in documentation if providerType == "ec2" && opts.EC2Region == "" && opts.RegionName != "" { opts.EC2Region = opts.RegionName } // Auto-fetch target credentials and target-az from cluster if requested (EC2 only) if providerType == "ec2" && opts.AutoTargetCredentials { if err := ec2.AutoPopulateTargetOptions(opts.ConfigFlags, &opts.EC2TargetAccessKeyID, &opts.EC2TargetSecretKey, &opts.EC2TargetAZ, &opts.EC2TargetRegion); err != nil { return err } } // Track if we need to update credentials // Note: AutoTargetCredentials for EC2 providers will populate EC2TargetAccessKeyID and EC2TargetSecretKey above needsCredentialUpdate := opts.Username != "" || opts.Password != "" || opts.Token != "" || opts.CACert != "" || opts.DomainName != "" || opts.ProjectName != "" || opts.RegionName != "" || opts.EC2Region != "" || opts.EC2TargetAccessKeyID != "" || opts.EC2TargetSecretKey != "" || opts.InsecureSkipTLSChanged || opts.SMBUrl != "" || opts.SMBUser != "" || opts.SMBPassword != "" // Get and validate secret ownership if credentials need updating var secret *corev1.Secret if needsCredentialUpdate { secret, err = getAndValidateSecret(opts.ConfigFlags, existingProvider) if err != nil { return err } } // Create a working copy of the spec to build the patch patchSpec := make(map[string]interface{}) providerUpdated := false // Update URL if provided if opts.URL != "" { currentURL, _, _ := unstructured.NestedString(existingProvider.Object, "spec", "url") klog.V(2).Infof("Updating provider URL from '%s' to '%s'", currentURL, opts.URL) patchSpec["url"] = opts.URL providerUpdated = true } // Get current settings or create empty map for patch currentSettings := make(map[string]string) existingSettings, found, err := unstructured.NestedStringMap(existingProvider.Object, "spec", "settings") if err != nil { return fmt.Errorf("failed to get provider settings: %v", err) } if found && existingSettings != nil { for k, v := range existingSettings { currentSettings[k] = v } } // Update VDDK settings for vSphere providers if providerType == "vsphere" { if opts.VddkInitImage != "" { klog.V(2).Infof("Updating VDDK init image to '%s'", opts.VddkInitImage) currentSettings["vddkInitImage"] = opts.VddkInitImage providerUpdated = true } if opts.UseVddkAioOptimizationChanged { currentSettings["useVddkAioOptimization"] = fmt.Sprintf("%t", opts.UseVddkAioOptimization) klog.V(2).Infof("Updated VDDK AIO optimization to %t", opts.UseVddkAioOptimization) providerUpdated = true } // Update VDDK configuration if buffer settings are provided if opts.VddkBufSizeIn64K > 0 || opts.VddkBufCount > 0 { // Get existing vddkConfig or create new one existingConfig := currentSettings["vddkConfig"] updatedConfig := updateVddkConfig(existingConfig, opts.VddkBufSizeIn64K, opts.VddkBufCount) currentSettings["vddkConfig"] = updatedConfig klog.V(2).Infof("Updated VDDK configuration: %s", updatedConfig) providerUpdated = true } } // Update EC2 settings for EC2 providers if providerType == "ec2" { if opts.EC2TargetRegion != "" { klog.V(2).Infof("Updating EC2 target-region to '%s'", opts.EC2TargetRegion) currentSettings["target-region"] = opts.EC2TargetRegion providerUpdated = true // If no explicit target AZ is provided in this patch, apply the documented default "<target-region>a" if opts.EC2TargetAZ == "" { defaultAZ := opts.EC2TargetRegion + "a" klog.V(2).Infof("No EC2 target-az provided, defaulting to '%s'", defaultAZ) currentSettings["target-az"] = defaultAZ providerUpdated = true } } if opts.EC2TargetAZ != "" { klog.V(2).Infof("Updating EC2 target-az to '%s'", opts.EC2TargetAZ) currentSettings["target-az"] = opts.EC2TargetAZ providerUpdated = true } } // Add settings to patch if any were modified if providerUpdated && len(currentSettings) > 0 { patchSpec["settings"] = currentSettings } // Update credentials if provided and secret is owned by provider secretUpdated := false if needsCredentialUpdate && secret != nil { secretUpdated, err = updateSecretCredentials(opts.ConfigFlags, secret, providerType, opts) if err != nil { return fmt.Errorf("failed to update credentials: %v", err) } } // Apply the patch if any changes were made if providerUpdated { // Patch the changed spec fields patchData := map[string]interface{}{ "spec": patchSpec, } patchBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, &unstructured.Unstructured{Object: patchData}) if err != nil { return fmt.Errorf("failed to encode patch data: %v", err) } // Apply the patch _, err = dynamicClient.Resource(client.ProvidersGVR).Namespace(opts.Namespace).Patch( context.TODO(), opts.Name, types.MergePatchType, patchBytes, metav1.PatchOptions{}, ) if err != nil { return fmt.Errorf("failed to patch provider: %v", err) } } // Provide user feedback if providerUpdated || secretUpdated { fmt.Printf("provider/%s patched\n", opts.Name) if secretUpdated { klog.V(2).Infof("Updated credentials for provider '%s'", opts.Name) } } else { fmt.Printf("provider/%s unchanged (no updates specified)\n", opts.Name) } return nil } // getAndValidateSecret retrieves the secret and validates that it's owned by the provider func getAndValidateSecret(configFlags *genericclioptions.ConfigFlags, provider *unstructured.Unstructured) (*corev1.Secret, error) { // Get secret reference using unstructured operations secretRef, found, err := unstructured.NestedMap(provider.Object, "spec", "secret") if err != nil { return nil, fmt.Errorf("failed to get secret reference: %v", err) } if !found || secretRef == nil { return nil, fmt.Errorf("provider has no associated secret") } secretName, nameOk := secretRef["name"].(string) secretNamespace, namespaceOk := secretRef["namespace"].(string) if !nameOk || secretName == "" { return nil, fmt.Errorf("provider has no associated secret") } if !namespaceOk || secretNamespace == "" { // Use provider namespace if secret namespace is not specified secretNamespace = provider.GetNamespace() } k8sClient, err := client.GetKubernetesClientset(configFlags) if err != nil { return nil, fmt.Errorf("failed to get kubernetes client: %v", err) } // Get the secret secret, err := k8sClient.CoreV1().Secrets(secretNamespace).Get( context.TODO(), secretName, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("failed to get secret '%s': %v", secretName, err) } // Check if the secret is owned by this provider isOwned := false for _, ownerRef := range secret.GetOwnerReferences() { if ownerRef.Kind == "Provider" && ownerRef.Name == provider.GetName() && ownerRef.UID == provider.GetUID() { isOwned = true break } } if !isOwned { return nil, fmt.Errorf("cannot update credentials: the secret '%s' is not owned by provider '%s'. "+ "This usually means the secret was created independently and is shared by multiple providers. "+ "To update credentials, either:\n"+ "1. Update the secret directly: kubectl patch secret %s -p '{...}'\n"+ "2. Create a new secret and update the provider to use it: kubectl patch provider %s --secret new-secret-name", secret.Name, provider.GetName(), secret.Name, provider.GetName()) } klog.V(2).Infof("Secret '%s' is owned by provider '%s', credentials can be updated", secret.Name, provider.GetName()) return secret, nil } // updateSecretCredentials updates the secret with new credential values func updateSecretCredentials(configFlags *genericclioptions.ConfigFlags, secret *corev1.Secret, providerType string, opts PatchProviderOptions) (bool, error) { updated := false if secret.Data == nil { secret.Data = make(map[string][]byte) } // Update credentials based on provider type switch providerType { case "openshift": if opts.Token != "" { secret.Data["token"] = []byte(opts.Token) klog.V(2).Infof("Updated OpenShift token") updated = true } case "vsphere", "ovirt", "ova": if opts.Username != "" { secret.Data["user"] = []byte(opts.Username) klog.V(2).Infof("Updated username") updated = true } if opts.Password != "" { secret.Data["password"] = []byte(opts.Password) klog.V(2).Infof("Updated password") updated = true } case "openstack": if opts.Username != "" { secret.Data["username"] = []byte(opts.Username) klog.V(2).Infof("Updated OpenStack username") updated = true } if opts.Password != "" { secret.Data["password"] = []byte(opts.Password) klog.V(2).Infof("Updated OpenStack password") updated = true } if opts.DomainName != "" { secret.Data["domainName"] = []byte(opts.DomainName) klog.V(2).Infof("Updated OpenStack domain name") updated = true } if opts.ProjectName != "" { secret.Data["projectName"] = []byte(opts.ProjectName) klog.V(2).Infof("Updated OpenStack project name") updated = true } if opts.RegionName != "" { secret.Data["regionName"] = []byte(opts.RegionName) klog.V(2).Infof("Updated OpenStack region name") updated = true } case "ec2": if opts.Username != "" { secret.Data["accessKeyId"] = []byte(opts.Username) klog.V(2).Infof("Updated EC2 access key ID") updated = true } if opts.Password != "" { secret.Data["secretAccessKey"] = []byte(opts.Password) klog.V(2).Infof("Updated EC2 secret access key") updated = true } if opts.EC2Region != "" { secret.Data["region"] = []byte(opts.EC2Region) klog.V(2).Infof("Updated EC2 region") updated = true } if opts.EC2TargetAccessKeyID != "" { secret.Data["targetAccessKeyId"] = []byte(opts.EC2TargetAccessKeyID) klog.V(2).Infof("Updated EC2 target account access key ID (cross-account)") updated = true } if opts.EC2TargetSecretKey != "" { secret.Data["targetSecretAccessKey"] = []byte(opts.EC2TargetSecretKey) klog.V(2).Infof("Updated EC2 target account secret access key (cross-account)") updated = true } case "hyperv": if opts.Username != "" { secret.Data["username"] = []byte(opts.Username) klog.V(2).Infof("Updated HyperV username") updated = true } if opts.Password != "" { secret.Data["password"] = []byte(opts.Password) klog.V(2).Infof("Updated HyperV password") updated = true } if opts.SMBUrl != "" { secret.Data["smbUrl"] = []byte(opts.SMBUrl) klog.V(2).Infof("Updated HyperV SMB URL") updated = true } if opts.SMBUser != "" { secret.Data["smbUser"] = []byte(opts.SMBUser) klog.V(2).Infof("Updated HyperV SMB username") updated = true } if opts.SMBPassword != "" { secret.Data["smbPassword"] = []byte(opts.SMBPassword) klog.V(2).Infof("Updated HyperV SMB password") updated = true } } // Update CA certificate for all types (if applicable) if opts.CACert != "" { secret.Data["cacert"] = []byte(opts.CACert) klog.V(2).Infof("Updated CA certificate") updated = true } // Update insecureSkipVerify for all types (if changed) if opts.InsecureSkipTLSChanged { if opts.InsecureSkipTLS { secret.Data["insecureSkipVerify"] = []byte("true") } else { // Remove the key if insecureSkipTLS is false delete(secret.Data, "insecureSkipVerify") } klog.V(2).Infof("Updated insecureSkipVerify to %t", opts.InsecureSkipTLS) updated = true } // Update the secret if any changes were made if updated { k8sClient, err := client.GetKubernetesClientset(configFlags) if err != nil { return false, fmt.Errorf("failed to get kubernetes client: %v", err) } _, err = k8sClient.CoreV1().Secrets(secret.Namespace).Update(context.TODO(), secret, metav1.UpdateOptions{}) if err != nil { return false, fmt.Errorf("failed to update secret: %v", err) } } return updated, nil } // updateVddkConfig updates the VDDK configuration block with new buffer settings func updateVddkConfig(existingConfig string, bufSizeIn64K, bufCount int) string { var configBuilder strings.Builder // Start with YAML literal block scalar format configBuilder.WriteString("|") // Parse existing config to preserve other settings existingLines := make(map[string]string) if existingConfig != "" { // Remove the "|" prefix and split by lines configContent := strings.TrimPrefix(existingConfig, "|") lines := strings.Split(configContent, "\n") for _, line := range lines { line = strings.TrimSpace(line) if line == "" { continue } // Parse key=value pairs if parts := strings.SplitN(line, "=", 2); len(parts) == 2 { existingLines[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } } } // Update buffer size if provided if bufSizeIn64K > 0 { existingLines["VixDiskLib.nfcAio.Session.BufSizeIn64K"] = strconv.Itoa(bufSizeIn64K) } // Update buffer count if provided if bufCount > 0 { existingLines["VixDiskLib.nfcAio.Session.BufCount"] = strconv.Itoa(bufCount) } // Build the config string for key, value := range existingLines { configBuilder.WriteString("\n") configBuilder.WriteString(key) configBuilder.WriteString("=") configBuilder.WriteString(value) } return configBuilder.String() }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/settings/settings.go
Go
// Package settings provides functionality for managing ForkliftController settings. package settings import ( "context" "encoding/json" "fmt" "sort" "strconv" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // GetSettingsOptions contains options for getting settings. type GetSettingsOptions struct { ConfigFlags *genericclioptions.ConfigFlags SettingName string // optional: get a specific setting AllSettings bool // if true, return all settings (supported + extended) } // SetSettingOptions contains options for setting a value. type SetSettingOptions struct { ConfigFlags *genericclioptions.ConfigFlags Name string Value string Verbosity int } // UnsetSettingOptions contains options for unsetting a value. type UnsetSettingOptions struct { ConfigFlags *genericclioptions.ConfigFlags Name string Verbosity int } // wrapClusterError wraps cluster connection errors with user-friendly messages. func wrapClusterError(err error, operation string) error { errStr := err.Error() // Connection refused - cluster not accessible if strings.Contains(errStr, "connection refused") { return fmt.Errorf("cannot connect to Kubernetes cluster: %w\n\nMake sure:\n - Your kubeconfig is correctly configured\n - The cluster is running and accessible\n - Run 'kubectl cluster-info' to verify connectivity", err) } // Unauthorized - authentication issues if strings.Contains(errStr, "Unauthorized") || strings.Contains(errStr, "unauthorized") { return fmt.Errorf("authentication failed: %w\n\nMake sure:\n - Your kubeconfig credentials are valid\n - Run 'kubectl auth can-i get forkliftcontrollers --namespace openshift-mtv' to check permissions", err) } // Forbidden - permission issues if strings.Contains(errStr, "forbidden") || strings.Contains(errStr, "Forbidden") { return fmt.Errorf("permission denied: %w\n\nMake sure you have permissions to access ForkliftController resources", err) } // Resource not found - MTV not installed if strings.Contains(errStr, "the server could not find the requested resource") || strings.Contains(errStr, "no matches for kind") { return fmt.Errorf("MTV (Migration Toolkit for Virtualization) is not installed on this cluster\n\nThe ForkliftController CRD was not found. Please install MTV first.") } // Default: return original error with operation context return fmt.Errorf("%s: %w", operation, err) } // GetSettings retrieves the current ForkliftController settings. // If settingName is empty, settings are returned based on AllSettings flag. // If settingName is specified, only that setting is returned. // If AllSettings is true, all settings (supported + extended) are returned. func GetSettings(ctx context.Context, opts GetSettingsOptions) ([]SettingValue, error) { // Get the MTV operator namespace operatorNamespace := client.GetMTVOperatorNamespace(ctx, opts.ConfigFlags) // Get dynamic client dynamicClient, err := client.GetDynamicClient(opts.ConfigFlags) if err != nil { return nil, wrapClusterError(err, "failed to create Kubernetes client") } // List ForkliftController resources in the operator namespace controllerList, err := dynamicClient.Resource(client.ForkliftControllersGVR).Namespace(operatorNamespace).List(ctx, metav1.ListOptions{}) if err != nil { return nil, wrapClusterError(err, "failed to access ForkliftController") } if len(controllerList.Items) == 0 { return nil, fmt.Errorf("no ForkliftController found in namespace '%s'\n\nMake sure MTV is properly installed and the ForkliftController CR exists", operatorNamespace) } // Use the first ForkliftController (typically there's only one) controller := &controllerList.Items[0] // Extract spec spec, _, err := unstructured.NestedMap(controller.Object, "spec") if err != nil { return nil, fmt.Errorf("failed to get ForkliftController spec: %w", err) } // Determine which settings map to use settingsMap := SupportedSettings if opts.AllSettings { settingsMap = GetAllSettings() } // Build the result var result []SettingValue // If a specific setting is requested, only return that one if opts.SettingName != "" { // For specific setting lookups, check all settings (not just the filtered set) allSettings := GetAllSettings() def, ok := allSettings[opts.SettingName] if !ok { return nil, fmt.Errorf("unknown setting: %s\nUse 'kubectl mtv settings --all' to see all available settings", opts.SettingName) } sv := extractSettingValue(spec, def) return []SettingValue{sv}, nil } // Return all settings in category order with deterministic ordering within each category for _, category := range CategoryOrder { // Collect names for this category var categoryNames []string for name, def := range settingsMap { if def.Category == category { categoryNames = append(categoryNames, name) } } // Sort names within category for deterministic ordering sort.Strings(categoryNames) // Iterate sorted names and build result for _, name := range categoryNames { def := settingsMap[name] sv := extractSettingValue(spec, def) sv.Name = name result = append(result, sv) } } return result, nil } // extractSettingValue extracts a setting value from the ForkliftController spec. func extractSettingValue(spec map[string]interface{}, def SettingDefinition) SettingValue { sv := SettingValue{ Name: def.Name, Default: def.Default, Definition: def, IsSet: false, } if spec == nil { return sv } rawValue, exists := spec[def.Name] if !exists { return sv } sv.IsSet = true // Convert the value based on type switch def.Type { case TypeBool: switch v := rawValue.(type) { case bool: sv.Value = v case string: if v == "true" { sv.Value = true } else if v == "false" { sv.Value = false } } case TypeInt: switch v := rawValue.(type) { case int64: sv.Value = int(v) case float64: sv.Value = int(v) case int: sv.Value = v case string: if i, err := strconv.Atoi(v); err == nil { sv.Value = i } } case TypeString: if v, ok := rawValue.(string); ok { sv.Value = v } } return sv } // SetSetting updates a ForkliftController setting. func SetSetting(ctx context.Context, opts SetSettingOptions) error { // Validate setting name against all known settings allSettings := GetAllSettings() def, ok := allSettings[opts.Name] if !ok { return fmt.Errorf("unknown setting: %s\nUse 'kubectl mtv settings --all' to see available settings", opts.Name) } // Validate and convert the value patchValue, err := validateAndConvertValue(opts.Value, def) if err != nil { return fmt.Errorf("invalid value for %s: %w", opts.Name, err) } // Get the MTV operator namespace operatorNamespace := client.GetMTVOperatorNamespace(ctx, opts.ConfigFlags) if opts.Verbosity > 0 { fmt.Printf("Using MTV operator namespace: %s\n", operatorNamespace) } // Get dynamic client dynamicClient, err := client.GetDynamicClient(opts.ConfigFlags) if err != nil { return wrapClusterError(err, "failed to create Kubernetes client") } // List ForkliftController resources in the operator namespace controllerList, err := dynamicClient.Resource(client.ForkliftControllersGVR).Namespace(operatorNamespace).List(ctx, metav1.ListOptions{}) if err != nil { return wrapClusterError(err, "failed to access ForkliftController") } if len(controllerList.Items) == 0 { return fmt.Errorf("no ForkliftController found in namespace '%s'\n\nMake sure MTV is properly installed and the ForkliftController CR exists", operatorNamespace) } // Use the first ForkliftController (typically there's only one) controller := controllerList.Items[0] controllerName := controller.GetName() // Create the patch data patchMap := map[string]interface{}{ "spec": map[string]interface{}{ opts.Name: patchValue, }, } patchData, err := json.Marshal(patchMap) if err != nil { return fmt.Errorf("failed to create patch: %w", err) } if opts.Verbosity > 0 { fmt.Printf("Patching ForkliftController '%s': %s\n", controllerName, string(patchData)) } // Apply the patch _, err = dynamicClient.Resource(client.ForkliftControllersGVR).Namespace(operatorNamespace).Patch( ctx, controllerName, types.MergePatchType, patchData, metav1.PatchOptions{}, ) if err != nil { return wrapClusterError(err, "failed to update setting") } return nil } // UnsetSetting removes a ForkliftController setting (reverts to default). func UnsetSetting(ctx context.Context, opts UnsetSettingOptions) error { // Validate setting name against all known settings allSettings := GetAllSettings() _, ok := allSettings[opts.Name] if !ok { return fmt.Errorf("unknown setting: %s\nUse 'kubectl mtv settings --all' to see available settings", opts.Name) } // Get the MTV operator namespace operatorNamespace := client.GetMTVOperatorNamespace(ctx, opts.ConfigFlags) if opts.Verbosity > 0 { fmt.Printf("Using MTV operator namespace: %s\n", operatorNamespace) } // Get dynamic client dynamicClient, err := client.GetDynamicClient(opts.ConfigFlags) if err != nil { return wrapClusterError(err, "failed to create Kubernetes client") } // List ForkliftController resources in the operator namespace controllerList, err := dynamicClient.Resource(client.ForkliftControllersGVR).Namespace(operatorNamespace).List(ctx, metav1.ListOptions{}) if err != nil { return wrapClusterError(err, "failed to access ForkliftController") } if len(controllerList.Items) == 0 { return fmt.Errorf("no ForkliftController found in namespace '%s'\n\nMake sure MTV is properly installed and the ForkliftController CR exists", operatorNamespace) } // Use the first ForkliftController (typically there's only one) controller := controllerList.Items[0] controllerName := controller.GetName() // Create the patch data to remove the field (set to null in JSON merge patch) // Using a raw JSON string to properly set null value patchData := []byte(fmt.Sprintf(`{"spec":{"%s":null}}`, opts.Name)) if opts.Verbosity > 0 { fmt.Printf("Patching ForkliftController '%s': %s\n", controllerName, string(patchData)) } // Apply the patch _, err = dynamicClient.Resource(client.ForkliftControllersGVR).Namespace(operatorNamespace).Patch( ctx, controllerName, types.MergePatchType, patchData, metav1.PatchOptions{}, ) if err != nil { return wrapClusterError(err, "failed to remove setting") } return nil } // validateAndConvertValue validates and converts a string value to the appropriate type. func validateAndConvertValue(value string, def SettingDefinition) (interface{}, error) { switch def.Type { case TypeBool: switch value { case "true", "True", "TRUE", "1", "yes", "Yes", "YES": return true, nil case "false", "False", "FALSE", "0", "no", "No", "NO": return false, nil default: return nil, fmt.Errorf("expected boolean value (true/false), got: %s", value) } case TypeInt: i, err := strconv.Atoi(value) if err != nil { return nil, fmt.Errorf("expected integer value, got: %s", value) } return i, nil case TypeString: return value, nil default: return value, nil } } // FormatValue formats a setting value for display. func FormatValue(sv SettingValue) string { if !sv.IsSet || sv.Value == nil { return "(not set)" } switch v := sv.Value.(type) { case bool: return strconv.FormatBool(v) case int: return strconv.Itoa(v) case string: if v == "" { return "(empty)" } return v default: return fmt.Sprintf("%v", v) } } // FormatDefault formats a default value for display. func FormatDefault(def SettingDefinition) string { switch v := def.Default.(type) { case bool: return strconv.FormatBool(v) case int: return strconv.Itoa(v) case string: if v == "" { return "-" } return v default: return fmt.Sprintf("%v", v) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/settings/settings_test.go
Go
package settings import ( "errors" "strings" "testing" ) // --- FormatValue --- func TestFormatValue_NotSet(t *testing.T) { sv := SettingValue{IsSet: false} if got := FormatValue(sv); got != "(not set)" { t.Errorf("FormatValue(not set) = %q, want %q", got, "(not set)") } } func TestFormatValue_NilValue(t *testing.T) { sv := SettingValue{IsSet: true, Value: nil} if got := FormatValue(sv); got != "(not set)" { t.Errorf("FormatValue(nil) = %q, want %q", got, "(not set)") } } func TestFormatValue_Bool(t *testing.T) { tests := []struct { value bool expected string }{ {true, "true"}, {false, "false"}, } for _, tt := range tests { sv := SettingValue{IsSet: true, Value: tt.value} if got := FormatValue(sv); got != tt.expected { t.Errorf("FormatValue(%v) = %q, want %q", tt.value, got, tt.expected) } } } func TestFormatValue_Int(t *testing.T) { sv := SettingValue{IsSet: true, Value: 42} if got := FormatValue(sv); got != "42" { t.Errorf("FormatValue(42) = %q, want %q", got, "42") } } func TestFormatValue_String(t *testing.T) { sv := SettingValue{IsSet: true, Value: "quay.io/test:latest"} if got := FormatValue(sv); got != "quay.io/test:latest" { t.Errorf("FormatValue(string) = %q", got) } } func TestFormatValue_EmptyString(t *testing.T) { sv := SettingValue{IsSet: true, Value: ""} if got := FormatValue(sv); got != "(empty)" { t.Errorf("FormatValue(empty string) = %q, want %q", got, "(empty)") } } // --- FormatDefault --- func TestFormatDefault_Bool(t *testing.T) { def := SettingDefinition{Default: true} if got := FormatDefault(def); got != "true" { t.Errorf("FormatDefault(true) = %q", got) } def.Default = false if got := FormatDefault(def); got != "false" { t.Errorf("FormatDefault(false) = %q", got) } } func TestFormatDefault_Int(t *testing.T) { def := SettingDefinition{Default: 20} if got := FormatDefault(def); got != "20" { t.Errorf("FormatDefault(20) = %q", got) } } func TestFormatDefault_String(t *testing.T) { def := SettingDefinition{Default: "4000m"} if got := FormatDefault(def); got != "4000m" { t.Errorf("FormatDefault(string) = %q", got) } } func TestFormatDefault_EmptyString(t *testing.T) { def := SettingDefinition{Default: ""} if got := FormatDefault(def); got != "-" { t.Errorf("FormatDefault(empty) = %q, want %q", got, "-") } } // --- wrapClusterError --- func TestWrapClusterError_ConnectionRefused(t *testing.T) { err := wrapClusterError(errors.New("dial tcp: connection refused"), "test") if !strings.Contains(err.Error(), "cannot connect to Kubernetes cluster") { t.Errorf("expected connection refused message, got: %s", err.Error()) } } func TestWrapClusterError_Unauthorized(t *testing.T) { err := wrapClusterError(errors.New("Unauthorized"), "test") if !strings.Contains(err.Error(), "authentication failed") { t.Errorf("expected auth failed message, got: %s", err.Error()) } err = wrapClusterError(errors.New("unauthorized access"), "test") if !strings.Contains(err.Error(), "authentication failed") { t.Errorf("expected auth failed message for lowercase, got: %s", err.Error()) } } func TestWrapClusterError_Forbidden(t *testing.T) { err := wrapClusterError(errors.New("forbidden"), "test") if !strings.Contains(err.Error(), "permission denied") { t.Errorf("expected permission denied message, got: %s", err.Error()) } err = wrapClusterError(errors.New("Forbidden: user cannot get"), "test") if !strings.Contains(err.Error(), "permission denied") { t.Errorf("expected permission denied for capitalized, got: %s", err.Error()) } } func TestWrapClusterError_ResourceNotFound(t *testing.T) { err := wrapClusterError(errors.New("the server could not find the requested resource"), "test") if !strings.Contains(err.Error(), "MTV") { t.Errorf("expected MTV not installed message, got: %s", err.Error()) } err = wrapClusterError(errors.New("no matches for kind \"ForkliftController\""), "test") if !strings.Contains(err.Error(), "MTV") { t.Errorf("expected MTV not installed for no matches, got: %s", err.Error()) } } func TestWrapClusterError_GenericError(t *testing.T) { err := wrapClusterError(errors.New("some random error"), "do something") if !strings.HasPrefix(err.Error(), "do something:") { t.Errorf("expected operation prefix, got: %s", err.Error()) } } // --- extractSettingValue --- func TestExtractSettingValue_NilSpec(t *testing.T) { def := SettingDefinition{Name: "test", Type: TypeString, Default: "default"} sv := extractSettingValue(nil, def) if sv.IsSet { t.Error("expected IsSet=false for nil spec") } if sv.Default != "default" { t.Errorf("expected Default=%q, got %v", "default", sv.Default) } } func TestExtractSettingValue_MissingKey(t *testing.T) { spec := map[string]interface{}{} def := SettingDefinition{Name: "missing_key", Type: TypeString, Default: "def"} sv := extractSettingValue(spec, def) if sv.IsSet { t.Error("expected IsSet=false for missing key") } } func TestExtractSettingValue_String(t *testing.T) { spec := map[string]interface{}{"vddk_image": "quay.io/test:v1"} def := SettingDefinition{Name: "vddk_image", Type: TypeString, Default: ""} sv := extractSettingValue(spec, def) if !sv.IsSet { t.Error("expected IsSet=true") } if sv.Value != "quay.io/test:v1" { t.Errorf("expected Value=%q, got %v", "quay.io/test:v1", sv.Value) } } func TestExtractSettingValue_BoolNative(t *testing.T) { spec := map[string]interface{}{"feature": true} def := SettingDefinition{Name: "feature", Type: TypeBool, Default: false} sv := extractSettingValue(spec, def) if !sv.IsSet { t.Error("expected IsSet=true") } if sv.Value != true { t.Errorf("expected Value=true, got %v", sv.Value) } } func TestExtractSettingValue_BoolFromString(t *testing.T) { spec := map[string]interface{}{"feature": "true"} def := SettingDefinition{Name: "feature", Type: TypeBool, Default: false} sv := extractSettingValue(spec, def) if !sv.IsSet { t.Error("expected IsSet=true") } if sv.Value != true { t.Errorf("expected Value=true from string, got %v", sv.Value) } } func TestExtractSettingValue_IntFromFloat64(t *testing.T) { // JSON unmarshalling produces float64 for numbers spec := map[string]interface{}{"max_vm": float64(30)} def := SettingDefinition{Name: "max_vm", Type: TypeInt, Default: 20} sv := extractSettingValue(spec, def) if !sv.IsSet { t.Error("expected IsSet=true") } if sv.Value != 30 { t.Errorf("expected Value=30 from float64, got %v", sv.Value) } } func TestExtractSettingValue_IntFromInt64(t *testing.T) { spec := map[string]interface{}{"max_vm": int64(25)} def := SettingDefinition{Name: "max_vm", Type: TypeInt, Default: 20} sv := extractSettingValue(spec, def) if sv.Value != 25 { t.Errorf("expected Value=25 from int64, got %v", sv.Value) } } func TestExtractSettingValue_IntFromString(t *testing.T) { spec := map[string]interface{}{"max_vm": "42"} def := SettingDefinition{Name: "max_vm", Type: TypeInt, Default: 20} sv := extractSettingValue(spec, def) if sv.Value != 42 { t.Errorf("expected Value=42 from string, got %v", sv.Value) } } // --- validateAndConvertValue --- func TestValidateAndConvertValue_BoolTrue(t *testing.T) { def := SettingDefinition{Type: TypeBool} trueValues := []string{"true", "True", "TRUE", "1", "yes", "Yes", "YES"} for _, v := range trueValues { result, err := validateAndConvertValue(v, def) if err != nil { t.Errorf("validateAndConvertValue(%q) error: %v", v, err) } if result != true { t.Errorf("validateAndConvertValue(%q) = %v, want true", v, result) } } } func TestValidateAndConvertValue_BoolFalse(t *testing.T) { def := SettingDefinition{Type: TypeBool} falseValues := []string{"false", "False", "FALSE", "0", "no", "No", "NO"} for _, v := range falseValues { result, err := validateAndConvertValue(v, def) if err != nil { t.Errorf("validateAndConvertValue(%q) error: %v", v, err) } if result != false { t.Errorf("validateAndConvertValue(%q) = %v, want false", v, result) } } } func TestValidateAndConvertValue_BoolInvalid(t *testing.T) { def := SettingDefinition{Type: TypeBool} _, err := validateAndConvertValue("maybe", def) if err == nil { t.Error("expected error for invalid bool value") } if !strings.Contains(err.Error(), "expected boolean") { t.Errorf("expected bool error message, got: %s", err.Error()) } } func TestValidateAndConvertValue_Int(t *testing.T) { def := SettingDefinition{Type: TypeInt} result, err := validateAndConvertValue("42", def) if err != nil { t.Fatalf("unexpected error: %v", err) } if result != 42 { t.Errorf("expected 42, got %v", result) } } func TestValidateAndConvertValue_IntInvalid(t *testing.T) { def := SettingDefinition{Type: TypeInt} _, err := validateAndConvertValue("not-a-number", def) if err == nil { t.Error("expected error for invalid int value") } if !strings.Contains(err.Error(), "expected integer") { t.Errorf("expected int error message, got: %s", err.Error()) } } func TestValidateAndConvertValue_String(t *testing.T) { def := SettingDefinition{Type: TypeString} result, err := validateAndConvertValue("any-value", def) if err != nil { t.Fatalf("unexpected error: %v", err) } if result != "any-value" { t.Errorf("expected 'any-value', got %v", result) } } func TestValidateAndConvertValue_EmptyString(t *testing.T) { def := SettingDefinition{Type: TypeString} result, err := validateAndConvertValue("", def) if err != nil { t.Fatalf("unexpected error: %v", err) } if result != "" { t.Errorf("expected empty string, got %v", result) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/settings/types.go
Go
// Package settings provides types and utilities for managing ForkliftController settings. package settings import "sort" // SettingType represents the data type of a setting. type SettingType string const ( // TypeString represents a string setting. TypeString SettingType = "string" // TypeBool represents a boolean setting. TypeBool SettingType = "bool" // TypeInt represents an integer setting. TypeInt SettingType = "int" ) // SettingCategory represents the category of a setting. type SettingCategory string const ( // CategoryImage represents container image settings. CategoryImage SettingCategory = "image" // CategoryFeature represents feature flag settings. CategoryFeature SettingCategory = "feature" // CategoryPerformance represents performance tuning settings. CategoryPerformance SettingCategory = "performance" // CategoryDebug represents debugging settings. CategoryDebug SettingCategory = "debug" // CategoryVirtV2V represents virt-v2v container settings. CategoryVirtV2V SettingCategory = "virt-v2v" // CategoryPopulator represents volume populator container settings. CategoryPopulator SettingCategory = "populator" // CategoryHook represents hook container settings. CategoryHook SettingCategory = "hook" // CategoryOVA represents OVA provider server container settings. CategoryOVA SettingCategory = "ova" // CategoryHyperV represents HyperV provider server container settings. CategoryHyperV SettingCategory = "hyperv" // CategoryController represents controller deployment resource settings. CategoryController SettingCategory = "controller" // CategoryInventory represents inventory container resource settings. CategoryInventory SettingCategory = "inventory" // CategoryAPI represents API service resource settings. CategoryAPI SettingCategory = "api" // CategoryUIPlugin represents UI plugin resource settings. CategoryUIPlugin SettingCategory = "ui-plugin" // CategoryValidation represents validation service resource settings. CategoryValidation SettingCategory = "validation" // CategoryCLIDownload represents CLI download service resource settings. CategoryCLIDownload SettingCategory = "cli-download" // CategoryOVAProxy represents OVA proxy resource settings. CategoryOVAProxy SettingCategory = "ova-proxy" // CategoryConfigMaps represents ConfigMap name settings. CategoryConfigMaps SettingCategory = "configmaps" // CategoryAdvanced represents advanced/misc settings. CategoryAdvanced SettingCategory = "advanced" ) // SettingDefinition defines metadata for a ForkliftController setting. type SettingDefinition struct { // Name is the setting key in the ForkliftController spec (snake_case). Name string // Type is the data type of the setting. Type SettingType // Default is the default value if not set. Default interface{} // Description is a human-readable description of the setting. Description string // Category groups related settings together. Category SettingCategory } // SettingValue represents a setting with its current and default values. type SettingValue struct { // Name is the setting key. Name string // Value is the current value (nil if not set). Value interface{} // Default is the default value. Default interface{} // IsSet indicates whether the value is explicitly set. IsSet bool // Definition contains the setting metadata. Definition SettingDefinition } // CategoryOrder defines the display order for categories. var CategoryOrder = []SettingCategory{ CategoryImage, CategoryFeature, CategoryPerformance, CategoryDebug, CategoryVirtV2V, CategoryPopulator, CategoryHook, CategoryOVA, CategoryHyperV, CategoryController, CategoryInventory, CategoryAPI, CategoryUIPlugin, CategoryValidation, CategoryCLIDownload, CategoryOVAProxy, CategoryConfigMaps, CategoryAdvanced, } // SupportedSettings contains all supported ForkliftController settings. // This is a curated subset of settings that users commonly need to configure. var SupportedSettings = map[string]SettingDefinition{ // Container Images "vddk_image": { Name: "vddk_image", Type: TypeString, Default: "", Description: "VDDK container image for vSphere migrations", Category: CategoryImage, }, "virt_v2v_image_fqin": { Name: "virt_v2v_image_fqin", Type: TypeString, Default: "", Description: "Custom virt-v2v container image", Category: CategoryImage, }, // Feature Flags "controller_vsphere_incremental_backup": { Name: "controller_vsphere_incremental_backup", Type: TypeBool, Default: true, Description: "Enable CBT-based warm migration for vSphere", Category: CategoryFeature, }, "controller_ovirt_warm_migration": { Name: "controller_ovirt_warm_migration", Type: TypeBool, Default: true, Description: "Enable warm migration from oVirt", Category: CategoryFeature, }, "feature_copy_offload": { Name: "feature_copy_offload", Type: TypeBool, Default: true, Description: "Enable storage array offload (XCOPY)", Category: CategoryFeature, }, "feature_ocp_live_migration": { Name: "feature_ocp_live_migration", Type: TypeBool, Default: false, Description: "Enable cross-cluster OpenShift live migration", Category: CategoryFeature, }, "feature_vmware_system_serial_number": { Name: "feature_vmware_system_serial_number", Type: TypeBool, Default: true, Description: "Use VMware system serial number for migrated VMs", Category: CategoryFeature, }, "controller_static_udn_ip_addresses": { Name: "controller_static_udn_ip_addresses", Type: TypeBool, Default: true, Description: "Enable static IP addresses with User Defined Networks", Category: CategoryFeature, }, "controller_retain_precopy_importer_pods": { Name: "controller_retain_precopy_importer_pods", Type: TypeBool, Default: false, Description: "Retain importer pods during warm migration (debugging)", Category: CategoryFeature, }, "feature_ova_appliance_management": { Name: "feature_ova_appliance_management", Type: TypeBool, Default: false, Description: "Enable appliance management for OVF-based providers", Category: CategoryFeature, }, // Performance Tuning "controller_max_vm_inflight": { Name: "controller_max_vm_inflight", Type: TypeInt, Default: 20, Description: "Maximum concurrent VM migrations", Category: CategoryPerformance, }, "controller_precopy_interval": { Name: "controller_precopy_interval", Type: TypeInt, Default: 60, Description: "Minutes between warm migration precopies", Category: CategoryPerformance, }, "controller_max_concurrent_reconciles": { Name: "controller_max_concurrent_reconciles", Type: TypeInt, Default: 10, Description: "Maximum concurrent controller reconciles", Category: CategoryPerformance, }, "controller_snapshot_removal_timeout_minuts": { Name: "controller_snapshot_removal_timeout_minuts", Type: TypeInt, Default: 120, Description: "Timeout for snapshot removal (minutes)", Category: CategoryPerformance, }, "controller_vddk_job_active_deadline_sec": { Name: "controller_vddk_job_active_deadline_sec", Type: TypeInt, Default: 300, Description: "VDDK validation job deadline (seconds)", Category: CategoryPerformance, }, "controller_filesystem_overhead": { Name: "controller_filesystem_overhead", Type: TypeInt, Default: 10, Description: "Filesystem overhead percentage", Category: CategoryPerformance, }, "controller_block_overhead": { Name: "controller_block_overhead", Type: TypeInt, Default: 0, Description: "Block storage fixed overhead (bytes)", Category: CategoryPerformance, }, "controller_cleanup_retries": { Name: "controller_cleanup_retries", Type: TypeInt, Default: 10, Description: "Maximum cleanup retry attempts", Category: CategoryPerformance, }, "controller_snapshot_removal_check_retries": { Name: "controller_snapshot_removal_check_retries", Type: TypeInt, Default: 20, Description: "Maximum snapshot removal check retries", Category: CategoryPerformance, }, "controller_host_lease_namespace": { Name: "controller_host_lease_namespace", Type: TypeString, Default: "openshift-mtv", Description: "Namespace for host lease objects (copy offload)", Category: CategoryPerformance, }, "controller_host_lease_duration_seconds": { Name: "controller_host_lease_duration_seconds", Type: TypeInt, Default: 10, Description: "Host lease duration in seconds (copy offload)", Category: CategoryPerformance, }, // Debugging "controller_log_level": { Name: "controller_log_level", Type: TypeInt, Default: 3, Description: "Controller log verbosity (0-9)", Category: CategoryDebug, }, // virt-v2v Container Settings "virt_v2v_extra_args": { Name: "virt_v2v_extra_args", Type: TypeString, Default: "", Description: "Additional virt-v2v command-line arguments", Category: CategoryVirtV2V, }, "virt_v2v_dont_request_kvm": { Name: "virt_v2v_dont_request_kvm", Type: TypeBool, Default: false, Description: "Don't request KVM device (use for nested virtualization)", Category: CategoryVirtV2V, }, "virt_v2v_extra_conf_config_map": { Name: "virt_v2v_extra_conf_config_map", Type: TypeString, Default: "", Description: "ConfigMap with extra virt-v2v configuration files", Category: CategoryVirtV2V, }, "virt_v2v_container_limits_cpu": { Name: "virt_v2v_container_limits_cpu", Type: TypeString, Default: "4000m", Description: "virt-v2v container CPU limit", Category: CategoryVirtV2V, }, "virt_v2v_container_limits_memory": { Name: "virt_v2v_container_limits_memory", Type: TypeString, Default: "8Gi", Description: "virt-v2v container memory limit", Category: CategoryVirtV2V, }, "virt_v2v_container_requests_cpu": { Name: "virt_v2v_container_requests_cpu", Type: TypeString, Default: "1000m", Description: "virt-v2v container CPU request", Category: CategoryVirtV2V, }, "virt_v2v_container_requests_memory": { Name: "virt_v2v_container_requests_memory", Type: TypeString, Default: "1Gi", Description: "virt-v2v container memory request", Category: CategoryVirtV2V, }, // Volume Populator Container Settings "populator_container_limits_cpu": { Name: "populator_container_limits_cpu", Type: TypeString, Default: "1000m", Description: "Volume populator container CPU limit", Category: CategoryPopulator, }, "populator_container_limits_memory": { Name: "populator_container_limits_memory", Type: TypeString, Default: "1Gi", Description: "Volume populator container memory limit", Category: CategoryPopulator, }, "populator_container_requests_cpu": { Name: "populator_container_requests_cpu", Type: TypeString, Default: "100m", Description: "Volume populator container CPU request", Category: CategoryPopulator, }, "populator_container_requests_memory": { Name: "populator_container_requests_memory", Type: TypeString, Default: "512Mi", Description: "Volume populator container memory request", Category: CategoryPopulator, }, // Hook Container Settings "hooks_container_limits_cpu": { Name: "hooks_container_limits_cpu", Type: TypeString, Default: "1000m", Description: "Hook container CPU limit", Category: CategoryHook, }, "hooks_container_limits_memory": { Name: "hooks_container_limits_memory", Type: TypeString, Default: "1Gi", Description: "Hook container memory limit", Category: CategoryHook, }, "hooks_container_requests_cpu": { Name: "hooks_container_requests_cpu", Type: TypeString, Default: "100m", Description: "Hook container CPU request", Category: CategoryHook, }, "hooks_container_requests_memory": { Name: "hooks_container_requests_memory", Type: TypeString, Default: "150Mi", Description: "Hook container memory request", Category: CategoryHook, }, // OVA Provider Server Container Settings "ova_container_limits_cpu": { Name: "ova_container_limits_cpu", Type: TypeString, Default: "1000m", Description: "OVA provider server CPU limit", Category: CategoryOVA, }, "ova_container_limits_memory": { Name: "ova_container_limits_memory", Type: TypeString, Default: "1Gi", Description: "OVA provider server memory limit", Category: CategoryOVA, }, "ova_container_requests_cpu": { Name: "ova_container_requests_cpu", Type: TypeString, Default: "100m", Description: "OVA provider server CPU request", Category: CategoryOVA, }, "ova_container_requests_memory": { Name: "ova_container_requests_memory", Type: TypeString, Default: "512Mi", Description: "OVA provider server memory request", Category: CategoryOVA, }, // HyperV Provider Server Container Settings "hyperv_container_limits_cpu": { Name: "hyperv_container_limits_cpu", Type: TypeString, Default: "1000m", Description: "HyperV provider server CPU limit", Category: CategoryHyperV, }, "hyperv_container_limits_memory": { Name: "hyperv_container_limits_memory", Type: TypeString, Default: "1Gi", Description: "HyperV provider server memory limit", Category: CategoryHyperV, }, "hyperv_container_requests_cpu": { Name: "hyperv_container_requests_cpu", Type: TypeString, Default: "100m", Description: "HyperV provider server CPU request", Category: CategoryHyperV, }, "hyperv_container_requests_memory": { Name: "hyperv_container_requests_memory", Type: TypeString, Default: "512Mi", Description: "HyperV provider server memory request", Category: CategoryHyperV, }, } // ExtendedSettings contains additional ForkliftController settings not in the curated SupportedSettings. // These are less commonly used settings that are available via the --all flag. var ExtendedSettings = map[string]SettingDefinition{ // Additional Feature Gates "feature_ui_plugin": { Name: "feature_ui_plugin", Type: TypeBool, Default: true, Description: "Enable OpenShift Console UI plugin", Category: CategoryFeature, }, "feature_validation": { Name: "feature_validation", Type: TypeBool, Default: true, Description: "Enable VM validation with OPA policies", Category: CategoryFeature, }, "feature_volume_populator": { Name: "feature_volume_populator", Type: TypeBool, Default: true, Description: "Enable volume populator for oVirt/OpenStack", Category: CategoryFeature, }, "feature_auth_required": { Name: "feature_auth_required", Type: TypeBool, Default: true, Description: "Require authentication for inventory API", Category: CategoryFeature, }, "feature_cli_download": { Name: "feature_cli_download", Type: TypeBool, Default: true, Description: "Enable kubectl-mtv CLI download service", Category: CategoryFeature, }, // Controller Deployment Resources "controller_container_limits_cpu": { Name: "controller_container_limits_cpu", Type: TypeString, Default: "2", Description: "Controller container CPU limit", Category: CategoryController, }, "controller_container_limits_memory": { Name: "controller_container_limits_memory", Type: TypeString, Default: "800Mi", Description: "Controller container memory limit", Category: CategoryController, }, "controller_container_requests_cpu": { Name: "controller_container_requests_cpu", Type: TypeString, Default: "100m", Description: "Controller container CPU request", Category: CategoryController, }, "controller_container_requests_memory": { Name: "controller_container_requests_memory", Type: TypeString, Default: "350Mi", Description: "Controller container memory request", Category: CategoryController, }, "controller_transfer_network": { Name: "controller_transfer_network", Type: TypeString, Default: "", Description: "Optional NAD name for controller pod transfer network (format: namespace/network-name)", Category: CategoryController, }, // Inventory Container Resources "inventory_container_limits_cpu": { Name: "inventory_container_limits_cpu", Type: TypeString, Default: "2", Description: "Inventory container CPU limit", Category: CategoryInventory, }, "inventory_container_limits_memory": { Name: "inventory_container_limits_memory", Type: TypeString, Default: "1Gi", Description: "Inventory container memory limit", Category: CategoryInventory, }, "inventory_container_requests_cpu": { Name: "inventory_container_requests_cpu", Type: TypeString, Default: "500m", Description: "Inventory container CPU request", Category: CategoryInventory, }, "inventory_container_requests_memory": { Name: "inventory_container_requests_memory", Type: TypeString, Default: "500Mi", Description: "Inventory container memory request", Category: CategoryInventory, }, "inventory_route_timeout": { Name: "inventory_route_timeout", Type: TypeString, Default: "360s", Description: "Inventory route timeout", Category: CategoryInventory, }, // API Service Resources "api_container_limits_cpu": { Name: "api_container_limits_cpu", Type: TypeString, Default: "1000m", Description: "API service CPU limit", Category: CategoryAPI, }, "api_container_limits_memory": { Name: "api_container_limits_memory", Type: TypeString, Default: "1Gi", Description: "API service memory limit", Category: CategoryAPI, }, "api_container_requests_cpu": { Name: "api_container_requests_cpu", Type: TypeString, Default: "100m", Description: "API service CPU request", Category: CategoryAPI, }, "api_container_requests_memory": { Name: "api_container_requests_memory", Type: TypeString, Default: "150Mi", Description: "API service memory request", Category: CategoryAPI, }, // UI Plugin Resources "ui_plugin_container_limits_cpu": { Name: "ui_plugin_container_limits_cpu", Type: TypeString, Default: "100m", Description: "UI plugin CPU limit", Category: CategoryUIPlugin, }, "ui_plugin_container_limits_memory": { Name: "ui_plugin_container_limits_memory", Type: TypeString, Default: "800Mi", Description: "UI plugin memory limit", Category: CategoryUIPlugin, }, "ui_plugin_container_requests_cpu": { Name: "ui_plugin_container_requests_cpu", Type: TypeString, Default: "100m", Description: "UI plugin CPU request", Category: CategoryUIPlugin, }, "ui_plugin_container_requests_memory": { Name: "ui_plugin_container_requests_memory", Type: TypeString, Default: "150Mi", Description: "UI plugin memory request", Category: CategoryUIPlugin, }, // Validation Service Resources "validation_container_limits_cpu": { Name: "validation_container_limits_cpu", Type: TypeString, Default: "1000m", Description: "Validation service CPU limit", Category: CategoryValidation, }, "validation_container_limits_memory": { Name: "validation_container_limits_memory", Type: TypeString, Default: "300Mi", Description: "Validation service memory limit", Category: CategoryValidation, }, "validation_container_requests_cpu": { Name: "validation_container_requests_cpu", Type: TypeString, Default: "400m", Description: "Validation service CPU request", Category: CategoryValidation, }, "validation_container_requests_memory": { Name: "validation_container_requests_memory", Type: TypeString, Default: "50Mi", Description: "Validation service memory request", Category: CategoryValidation, }, "validation_policy_agent_search_interval": { Name: "validation_policy_agent_search_interval", Type: TypeInt, Default: 120, Description: "Policy agent search interval in seconds", Category: CategoryValidation, }, "validation_extra_volume_name": { Name: "validation_extra_volume_name", Type: TypeString, Default: "validation-extra-rules", Description: "Volume name for extra validation rules", Category: CategoryValidation, }, "validation_extra_volume_mountpath": { Name: "validation_extra_volume_mountpath", Type: TypeString, Default: "/usr/share/opa/policies/extra", Description: "Mount path for extra validation rules", Category: CategoryValidation, }, // CLI Download Service Resources "cli_download_container_limits_cpu": { Name: "cli_download_container_limits_cpu", Type: TypeString, Default: "100m", Description: "CLI download service CPU limit", Category: CategoryCLIDownload, }, "cli_download_container_limits_memory": { Name: "cli_download_container_limits_memory", Type: TypeString, Default: "128Mi", Description: "CLI download service memory limit", Category: CategoryCLIDownload, }, "cli_download_container_requests_cpu": { Name: "cli_download_container_requests_cpu", Type: TypeString, Default: "50m", Description: "CLI download service CPU request", Category: CategoryCLIDownload, }, "cli_download_container_requests_memory": { Name: "cli_download_container_requests_memory", Type: TypeString, Default: "64Mi", Description: "CLI download service memory request", Category: CategoryCLIDownload, }, // OVA Proxy Resources "ova_proxy_container_limits_cpu": { Name: "ova_proxy_container_limits_cpu", Type: TypeString, Default: "1000m", Description: "OVA proxy CPU limit", Category: CategoryOVAProxy, }, "ova_proxy_container_limits_memory": { Name: "ova_proxy_container_limits_memory", Type: TypeString, Default: "1Gi", Description: "OVA proxy memory limit", Category: CategoryOVAProxy, }, "ova_proxy_container_requests_cpu": { Name: "ova_proxy_container_requests_cpu", Type: TypeString, Default: "250m", Description: "OVA proxy CPU request", Category: CategoryOVAProxy, }, "ova_proxy_container_requests_memory": { Name: "ova_proxy_container_requests_memory", Type: TypeString, Default: "512Mi", Description: "OVA proxy memory request", Category: CategoryOVAProxy, }, "ova_proxy_route_timeout": { Name: "ova_proxy_route_timeout", Type: TypeString, Default: "360s", Description: "OVA proxy route timeout", Category: CategoryOVAProxy, }, // Additional Container Images (FQINs) "controller_image_fqin": { Name: "controller_image_fqin", Type: TypeString, Default: "", Description: "Controller pod image", Category: CategoryImage, }, "api_image_fqin": { Name: "api_image_fqin", Type: TypeString, Default: "", Description: "API service image", Category: CategoryImage, }, "validation_image_fqin": { Name: "validation_image_fqin", Type: TypeString, Default: "", Description: "Validation service image", Category: CategoryImage, }, "ui_plugin_image_fqin": { Name: "ui_plugin_image_fqin", Type: TypeString, Default: "", Description: "UI plugin image", Category: CategoryImage, }, "cli_download_image_fqin": { Name: "cli_download_image_fqin", Type: TypeString, Default: "", Description: "CLI download service image", Category: CategoryImage, }, "populator_controller_image_fqin": { Name: "populator_controller_image_fqin", Type: TypeString, Default: "", Description: "Volume populator controller image", Category: CategoryImage, }, "populator_ovirt_image_fqin": { Name: "populator_ovirt_image_fqin", Type: TypeString, Default: "", Description: "oVirt populator image", Category: CategoryImage, }, "populator_openstack_image_fqin": { Name: "populator_openstack_image_fqin", Type: TypeString, Default: "", Description: "OpenStack populator image", Category: CategoryImage, }, "populator_vsphere_xcopy_volume_image_fqin": { Name: "populator_vsphere_xcopy_volume_image_fqin", Type: TypeString, Default: "", Description: "vSphere xcopy populator image", Category: CategoryImage, }, "ova_provider_server_fqin": { Name: "ova_provider_server_fqin", Type: TypeString, Default: "", Description: "OVA provider server image", Category: CategoryImage, }, "hyperv_provider_server_fqin": { Name: "hyperv_provider_server_fqin", Type: TypeString, Default: "", Description: "HyperV provider server image", Category: CategoryImage, }, "must_gather_image_fqin": { Name: "must_gather_image_fqin", Type: TypeString, Default: "", Description: "Must-gather debugging image", Category: CategoryImage, }, "ova_proxy_fqin": { Name: "ova_proxy_fqin", Type: TypeString, Default: "", Description: "OVA inventory proxy image", Category: CategoryImage, }, // ConfigMap Names "ovirt_osmap_configmap_name": { Name: "ovirt_osmap_configmap_name", Type: TypeString, Default: "forklift-ovirt-osmap", Description: "ConfigMap name for oVirt OS mappings", Category: CategoryConfigMaps, }, "vsphere_osmap_configmap_name": { Name: "vsphere_osmap_configmap_name", Type: TypeString, Default: "forklift-vsphere-osmap", Description: "ConfigMap name for vSphere OS mappings", Category: CategoryConfigMaps, }, "virt_customize_configmap_name": { Name: "virt_customize_configmap_name", Type: TypeString, Default: "forklift-virt-customize", Description: "ConfigMap name for virt-customize configuration", Category: CategoryConfigMaps, }, // Advanced Settings "controller_snapshot_status_check_rate_seconds": { Name: "controller_snapshot_status_check_rate_seconds", Type: TypeInt, Default: 10, Description: "Rate for checking snapshot status (seconds)", Category: CategoryAdvanced, }, "controller_tls_connection_timeout_sec": { Name: "controller_tls_connection_timeout_sec", Type: TypeInt, Default: 5, Description: "TLS connection timeout (seconds)", Category: CategoryAdvanced, }, "controller_max_parent_backing_retries": { Name: "controller_max_parent_backing_retries", Type: TypeInt, Default: 10, Description: "Maximum retries for parent backing lookup", Category: CategoryAdvanced, }, "controller_cdi_export_token_ttl": { Name: "controller_cdi_export_token_ttl", Type: TypeInt, Default: 720, Description: "CDI export token TTL (minutes)", Category: CategoryAdvanced, }, "image_pull_policy": { Name: "image_pull_policy", Type: TypeString, Default: "Always", Description: "Image pull policy (Always, IfNotPresent, Never)", Category: CategoryAdvanced, }, "k8s_cluster": { Name: "k8s_cluster", Type: TypeBool, Default: false, Description: "Whether running on Kubernetes (vs OpenShift)", Category: CategoryAdvanced, }, "metric_interval": { Name: "metric_interval", Type: TypeString, Default: "30s", Description: "Metrics scrape interval", Category: CategoryAdvanced, }, } // GetAllSettings returns a merged map of SupportedSettings + ExtendedSettings. // This provides access to all known ForkliftController settings. func GetAllSettings() map[string]SettingDefinition { all := make(map[string]SettingDefinition, len(SupportedSettings)+len(ExtendedSettings)) for k, v := range SupportedSettings { all[k] = v } for k, v := range ExtendedSettings { all[k] = v } return all } // GetAllSettingNames returns all setting names (supported + extended) in a consistent order. func GetAllSettingNames() []string { allSettings := GetAllSettings() var names []string for _, category := range CategoryOrder { var categoryNames []string for name, def := range allSettings { if def.Category == category { categoryNames = append(categoryNames, name) } } sort.Strings(categoryNames) names = append(names, categoryNames...) } return names } // GetSettingNames returns all supported setting names in a consistent order. func GetSettingNames() []string { var names []string for _, category := range CategoryOrder { // Collect names for this category var categoryNames []string for name, def := range SupportedSettings { if def.Category == category { categoryNames = append(categoryNames, name) } } // Sort names within category for deterministic ordering sort.Strings(categoryNames) names = append(names, categoryNames...) } return names } // GetSettingsByCategory returns settings grouped by category. func GetSettingsByCategory() map[SettingCategory][]SettingDefinition { result := make(map[SettingCategory][]SettingDefinition) for _, def := range SupportedSettings { result[def.Category] = append(result[def.Category], def) } return result } // IsValidSetting checks if a setting name is in the curated SupportedSettings. func IsValidSetting(name string) bool { _, ok := SupportedSettings[name] return ok } // IsValidAnySetting checks if a setting name is valid (in either SupportedSettings or ExtendedSettings). func IsValidAnySetting(name string) bool { if _, ok := SupportedSettings[name]; ok { return true } _, ok := ExtendedSettings[name] return ok } // GetSettingDefinition returns the definition for a setting from SupportedSettings, or nil if not found. func GetSettingDefinition(name string) *SettingDefinition { if def, ok := SupportedSettings[name]; ok { return &def } return nil } // GetAnySettingDefinition returns the definition for a setting from all settings, or nil if not found. func GetAnySettingDefinition(name string) *SettingDefinition { if def, ok := SupportedSettings[name]; ok { return &def } if def, ok := ExtendedSettings[name]; ok { return &def } return nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/settings/types_test.go
Go
package settings import ( "sort" "testing" ) // --- GetAllSettings --- func TestGetAllSettings_MergesMaps(t *testing.T) { all := GetAllSettings() // Must include entries from both SupportedSettings and ExtendedSettings for name := range SupportedSettings { if _, ok := all[name]; !ok { t.Errorf("GetAllSettings() missing supported setting %q", name) } } for name := range ExtendedSettings { if _, ok := all[name]; !ok { t.Errorf("GetAllSettings() missing extended setting %q", name) } } expected := len(SupportedSettings) + len(ExtendedSettings) if len(all) != expected { t.Errorf("GetAllSettings() returned %d entries, expected %d", len(all), expected) } } func TestGetAllSettings_ReturnsCopy(t *testing.T) { all1 := GetAllSettings() all2 := GetAllSettings() // Mutating one should not affect the other all1["__test_key__"] = SettingDefinition{Name: "test"} if _, ok := all2["__test_key__"]; ok { t.Error("GetAllSettings() should return a new map each time") } } // --- GetAllSettingNames --- func TestGetAllSettingNames_ContainsAll(t *testing.T) { names := GetAllSettingNames() all := GetAllSettings() if len(names) != len(all) { t.Errorf("GetAllSettingNames() returned %d names, expected %d", len(names), len(all)) } nameSet := map[string]bool{} for _, n := range names { nameSet[n] = true } for name := range all { if !nameSet[name] { t.Errorf("GetAllSettingNames() missing %q", name) } } } func TestGetAllSettingNames_NoDuplicates(t *testing.T) { names := GetAllSettingNames() seen := map[string]bool{} for _, n := range names { if seen[n] { t.Errorf("GetAllSettingNames() has duplicate %q", n) } seen[n] = true } } // --- GetSettingNames --- func TestGetSettingNames_ContainsSupportedOnly(t *testing.T) { names := GetSettingNames() if len(names) != len(SupportedSettings) { t.Errorf("GetSettingNames() returned %d names, expected %d", len(names), len(SupportedSettings)) } for _, n := range names { if _, ok := SupportedSettings[n]; !ok { t.Errorf("GetSettingNames() returned non-supported setting %q", n) } } } func TestGetSettingNames_SortedWithinCategory(t *testing.T) { names := GetSettingNames() // Group names by category and check sorting within each group byCategory := map[SettingCategory][]string{} for _, n := range names { def := SupportedSettings[n] byCategory[def.Category] = append(byCategory[def.Category], n) } for cat, catNames := range byCategory { if !sort.StringsAreSorted(catNames) { t.Errorf("GetSettingNames() not sorted within category %q: %v", cat, catNames) } } } // --- GetSettingsByCategory --- func TestGetSettingsByCategory_GroupsCorrectly(t *testing.T) { grouped := GetSettingsByCategory() totalCount := 0 for _, defs := range grouped { totalCount += len(defs) } if totalCount != len(SupportedSettings) { t.Errorf("GetSettingsByCategory() total %d, expected %d", totalCount, len(SupportedSettings)) } // Verify each setting is in the correct category for cat, defs := range grouped { for _, def := range defs { if def.Category != cat { t.Errorf("setting %q has category %q but grouped under %q", def.Name, def.Category, cat) } } } } func TestGetSettingsByCategory_HasExpectedCategories(t *testing.T) { grouped := GetSettingsByCategory() // SupportedSettings should have at least image, feature, performance, debug categories expected := []SettingCategory{CategoryImage, CategoryFeature, CategoryPerformance, CategoryDebug} for _, cat := range expected { if _, ok := grouped[cat]; !ok { t.Errorf("GetSettingsByCategory() missing category %q", cat) } } } // --- IsValidSetting --- func TestIsValidSetting_KnownSettings(t *testing.T) { for name := range SupportedSettings { if !IsValidSetting(name) { t.Errorf("IsValidSetting(%q) = false, want true", name) } } } func TestIsValidSetting_ExtendedSettingsReturnFalse(t *testing.T) { for name := range ExtendedSettings { // Extended settings that are NOT in SupportedSettings should return false if _, ok := SupportedSettings[name]; ok { continue // Skip overlapping entries } if IsValidSetting(name) { t.Errorf("IsValidSetting(%q) = true for extended-only setting, want false", name) } } } func TestIsValidSetting_InvalidName(t *testing.T) { if IsValidSetting("nonexistent_setting_xyzzy") { t.Error("IsValidSetting(nonexistent) = true, want false") } } // --- IsValidAnySetting --- func TestIsValidAnySetting_SupportedSettings(t *testing.T) { for name := range SupportedSettings { if !IsValidAnySetting(name) { t.Errorf("IsValidAnySetting(%q) = false for supported setting", name) } } } func TestIsValidAnySetting_ExtendedSettings(t *testing.T) { for name := range ExtendedSettings { if !IsValidAnySetting(name) { t.Errorf("IsValidAnySetting(%q) = false for extended setting", name) } } } func TestIsValidAnySetting_InvalidName(t *testing.T) { if IsValidAnySetting("nonexistent_setting_xyzzy") { t.Error("IsValidAnySetting(nonexistent) = true, want false") } } // --- GetSettingDefinition --- func TestGetSettingDefinition_Found(t *testing.T) { def := GetSettingDefinition("vddk_image") if def == nil { t.Fatal("GetSettingDefinition(vddk_image) = nil, want non-nil") return } if def.Name != "vddk_image" { t.Errorf("def.Name = %q, want %q", def.Name, "vddk_image") } if def.Type != TypeString { t.Errorf("def.Type = %q, want %q", def.Type, TypeString) } if def.Category != CategoryImage { t.Errorf("def.Category = %q, want %q", def.Category, CategoryImage) } } func TestGetSettingDefinition_NotFoundExtended(t *testing.T) { // "feature_ui_plugin" is only in ExtendedSettings def := GetSettingDefinition("feature_ui_plugin") if def != nil { t.Error("GetSettingDefinition(extended-only) should return nil") } } func TestGetSettingDefinition_NotFoundInvalid(t *testing.T) { def := GetSettingDefinition("nonexistent_setting") if def != nil { t.Error("GetSettingDefinition(nonexistent) should return nil") } } // --- GetAnySettingDefinition --- func TestGetAnySettingDefinition_Supported(t *testing.T) { def := GetAnySettingDefinition("vddk_image") if def == nil { t.Fatal("GetAnySettingDefinition(supported) = nil") } if def.Name != "vddk_image" { t.Errorf("def.Name = %q, want %q", def.Name, "vddk_image") } } func TestGetAnySettingDefinition_Extended(t *testing.T) { def := GetAnySettingDefinition("feature_ui_plugin") if def == nil { t.Fatal("GetAnySettingDefinition(extended) = nil") } if def.Name != "feature_ui_plugin" { t.Errorf("def.Name = %q, want %q", def.Name, "feature_ui_plugin") } } func TestGetAnySettingDefinition_NotFound(t *testing.T) { def := GetAnySettingDefinition("nonexistent_setting") if def != nil { t.Error("GetAnySettingDefinition(nonexistent) should return nil") } } // --- CategoryOrder --- func TestCategoryOrder_ContainsExpectedCategories(t *testing.T) { expected := map[SettingCategory]bool{ CategoryImage: true, CategoryFeature: true, CategoryPerformance: true, CategoryDebug: true, CategoryVirtV2V: true, CategoryPopulator: true, CategoryHook: true, CategoryOVA: true, CategoryHyperV: true, CategoryController: true, CategoryInventory: true, CategoryAPI: true, CategoryUIPlugin: true, CategoryValidation: true, CategoryCLIDownload: true, CategoryOVAProxy: true, CategoryConfigMaps: true, CategoryAdvanced: true, } for _, cat := range CategoryOrder { if !expected[cat] { t.Errorf("unexpected category %q in CategoryOrder", cat) } delete(expected, cat) } for cat := range expected { t.Errorf("missing category %q in CategoryOrder", cat) } } // --- Setting definitions consistency --- func TestSupportedSettings_NameFieldConsistency(t *testing.T) { for key, def := range SupportedSettings { if key != def.Name { t.Errorf("SupportedSettings key %q != def.Name %q", key, def.Name) } if def.Description == "" { t.Errorf("SupportedSettings[%q] has empty Description", key) } if def.Type != TypeString && def.Type != TypeBool && def.Type != TypeInt { t.Errorf("SupportedSettings[%q] has invalid Type %q", key, def.Type) } } } func TestExtendedSettings_NameFieldConsistency(t *testing.T) { for key, def := range ExtendedSettings { if key != def.Name { t.Errorf("ExtendedSettings key %q != def.Name %q", key, def.Name) } if def.Description == "" { t.Errorf("ExtendedSettings[%q] has empty Description", key) } if def.Type != TypeString && def.Type != TypeBool && def.Type != TypeInt { t.Errorf("ExtendedSettings[%q] has invalid Type %q", key, def.Type) } } } func TestNoOverlapBetweenSupportedAndExtended(t *testing.T) { for name := range SupportedSettings { if _, ok := ExtendedSettings[name]; ok { t.Errorf("setting %q exists in both SupportedSettings and ExtendedSettings", name) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/start/plan/start.go
Go
package plan import ( "context" "encoding/json" "fmt" "os" "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/cli-runtime/pkg/genericclioptions" "sigs.k8s.io/yaml" forkliftv1beta1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/yaacov/kubectl-mtv/pkg/cmd/get/plan/status" "github.com/yaacov/kubectl-mtv/pkg/util/client" "github.com/yaacov/kubectl-mtv/pkg/util/output" ) // Start starts a migration plan or outputs the Migration CR if dry-run is enabled func Start(configFlags *genericclioptions.ConfigFlags, name, namespace string, cutoverTime *time.Time, useUTC bool, dryRun bool, outputFormat string) error { c, err := client.GetDynamicClient(configFlags) if err != nil { return fmt.Errorf("failed to get client: %v", err) } // Get the plan plan, err := c.Resource(client.PlansGVR).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { return fmt.Errorf("failed to get plan: %v", err) } // Check if the plan is ready planReady, err := status.IsPlanReady(plan) if err != nil { return err } if !planReady { return fmt.Errorf("migration plan '%s' is not ready", name) } // Check if the plan has running migrations runningMigration, _, err := status.GetRunningMigration(c, namespace, plan, client.MigrationsGVR) if err != nil { return err } if runningMigration != nil { return fmt.Errorf("migration plan '%s' already has a running migration", name) } // Check if the plan has already succeeded planStatus, err := status.GetPlanStatus(plan) if err != nil { return err } if planStatus == status.StatusSucceeded { return fmt.Errorf("migration plan '%s' has already succeeded", name) } // Check if the plan is a warm migration warm, _, err := unstructured.NestedBool(plan.Object, "spec", "warm") if err != nil { return fmt.Errorf("failed to check if plan is warm: %v", err) } // Handle cutover time based on plan type if !warm && cutoverTime != nil { fmt.Fprintf(os.Stderr, "Warning: Cutover time is specified but plan '%s' is not a warm migration. Ignoring cutover time.\n", name) cutoverTime = nil } else if warm && cutoverTime == nil { // For warm migrations without specified cutover, default to now + 1 hour defaultTime := time.Now().Add(1 * time.Hour) cutoverTime = &defaultTime fmt.Fprintf(os.Stderr, "Warning: No cutover time specified for warm migration. Setting default cutover time to %s (1 hour from now).\n", output.FormatTimestamp(*cutoverTime, useUTC)) } // Extract the plan's UID planUID := string(plan.GetUID()) // Create a migration object using structured type migration := &forkliftv1beta1.Migration{ ObjectMeta: metav1.ObjectMeta{ GenerateName: fmt.Sprintf("%s-", name), Namespace: namespace, OwnerReferences: []metav1.OwnerReference{ { APIVersion: forkliftv1beta1.SchemeGroupVersion.String(), Kind: "Plan", Name: name, UID: types.UID(planUID), }, }, }, Spec: forkliftv1beta1.MigrationSpec{ Plan: corev1.ObjectReference{ Name: name, Namespace: namespace, UID: types.UID(planUID), }, }, } migration.Kind = "Migration" migration.APIVersion = forkliftv1beta1.SchemeGroupVersion.String() // Set cutover time if applicable (for warm migrations) if warm && cutoverTime != nil { // Convert time.Time to *metav1.Time metaTime := metav1.NewTime(*cutoverTime) migration.Spec.Cutover = &metaTime } // Handle dry-run mode if dryRun { return OutputMigrationCR(migration, outputFormat) } // Convert Migration object to Unstructured unstructuredMigration, err := runtime.DefaultUnstructuredConverter.ToUnstructured(migration) if err != nil { return fmt.Errorf("failed to convert Migration to Unstructured: %v", err) } migrationUnstructured := &unstructured.Unstructured{Object: unstructuredMigration} // Create the migration in the specified namespace _, err = c.Resource(client.MigrationsGVR).Namespace(namespace).Create(context.TODO(), migrationUnstructured, metav1.CreateOptions{}) if err != nil { return fmt.Errorf("failed to create migration: %v", err) } fmt.Fprintf(os.Stderr, "Migration started for plan '%s' in namespace '%s'\n", name, namespace) if warm && cutoverTime != nil { fmt.Fprintf(os.Stderr, "Cutover scheduled for: %s\n", output.FormatTimestamp(*cutoverTime, useUTC)) } return nil } // OutputMigrationCR serializes a Migration CR to the specified format and outputs it to stdout func OutputMigrationCR(migration *forkliftv1beta1.Migration, outputFormat string) error { if migration == nil { return fmt.Errorf("migration CR is nil") } var output []byte var err error switch outputFormat { case "yaml": output, err = yaml.Marshal(migration) if err != nil { return fmt.Errorf("failed to marshal Migration to YAML: %v", err) } // Always prefix YAML with document separator for proper multi-document format fmt.Print("---\n") fmt.Print(string(output)) return nil case "json": output, err = json.MarshalIndent(migration, "", " ") if err != nil { return fmt.Errorf("failed to marshal Migration to JSON: %v", err) } default: return fmt.Errorf("unsupported output format: %s", outputFormat) } fmt.Print(string(output)) return nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/version/format.go
Go
package version import ( "encoding/json" "fmt" "gopkg.in/yaml.v3" ) // FormatOutput formats the version information according to the specified format func (info Info) FormatOutput(format string) (string, error) { switch format { case "json": return info.formatJSON() case "yaml": return info.formatYAML() default: return info.formatTable(), nil } } // formatJSON returns JSON formatted version information func (info Info) formatJSON() (string, error) { jsonBytes, err := json.MarshalIndent(info, "", " ") if err != nil { return "", fmt.Errorf("error marshaling JSON: %w", err) } return string(jsonBytes), nil } // formatYAML returns YAML formatted version information func (info Info) formatYAML() (string, error) { yamlBytes, err := yaml.Marshal(info) if err != nil { return "", fmt.Errorf("error marshaling YAML: %w", err) } return string(yamlBytes), nil } // formatTable returns table/text formatted version information func (info Info) formatTable() string { output := fmt.Sprintf("kubectl-mtv version: %s\n", info.ClientVersion) // Operator information - only print if we have status if info.OperatorStatus != "" { if info.OperatorStatus == "installed" { output += fmt.Sprintf("MTV Operator: %s\n", info.OperatorVersion) output += fmt.Sprintf("MTV Namespace: %s\n", info.OperatorNamespace) } else { output += fmt.Sprintf("MTV Operator: %s\n", info.OperatorStatus) } } // Inventory information - only print if we have status if info.InventoryStatus != "" { if info.InventoryStatus == "available" { if info.InventoryInsecure { output += fmt.Sprintf("MTV Inventory: %s (insecure)\n", info.InventoryURL) } else { output += fmt.Sprintf("MTV Inventory: %s\n", info.InventoryURL) } } else { output += fmt.Sprintf("MTV Inventory: %s\n", info.InventoryStatus) } } return output }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/cmd/version/version.go
Go
package version import ( "context" "github.com/yaacov/kubectl-mtv/pkg/util/client" "github.com/yaacov/kubectl-mtv/pkg/util/config" "k8s.io/cli-runtime/pkg/genericclioptions" ) // Info holds all version-related information type Info struct { ClientVersion string `json:"clientVersion" yaml:"clientVersion"` OperatorVersion string `json:"operatorVersion,omitempty" yaml:"operatorVersion,omitempty"` OperatorStatus string `json:"operatorStatus,omitempty" yaml:"operatorStatus,omitempty"` OperatorNamespace string `json:"operatorNamespace,omitempty" yaml:"operatorNamespace,omitempty"` InventoryURL string `json:"inventoryURL,omitempty" yaml:"inventoryURL,omitempty"` InventoryStatus string `json:"inventoryStatus,omitempty" yaml:"inventoryStatus,omitempty"` InventoryInsecure bool `json:"inventoryInsecure,omitempty" yaml:"inventoryInsecure,omitempty"` } // GetInventoryInfo returns information about the MTV inventory service // Uses the global config which already handles: // - Checking MTV_INVENTORY_URL env var // - Auto-discovering from OpenShift routes // - Caching the result func GetInventoryInfo(globalConfig config.InventoryConfigGetter) (string, string, bool) { inventoryURL := globalConfig.GetInventoryURL() insecureSkipTLS := globalConfig.GetInventoryInsecureSkipTLS() if inventoryURL != "" { return inventoryURL, "available", insecureSkipTLS } return "not found", "not available", false } // GetMTVControllerInfo returns information about the MTV Operator func GetMTVControllerInfo(ctx context.Context, kubeConfigFlags *genericclioptions.ConfigFlags) (string, string, string) { operatorInfo := client.GetMTVOperatorInfo(ctx, kubeConfigFlags) // Check for API/auth/network errors first if operatorInfo.Error != "" { return "unknown", "error: " + operatorInfo.Error, "" } if !operatorInfo.Found { return "not found", "not available", "" } status := "installed" version := operatorInfo.Version namespace := operatorInfo.Namespace if namespace == "" { namespace = "unknown" } return version, status, namespace } // GetVersionInfo gathers all version information func GetVersionInfo(ctx context.Context, clientVersion string, kubeConfigFlags *genericclioptions.ConfigFlags, globalConfig config.InventoryConfigGetter) Info { // Get MTV Operator information controllerVersion, controllerStatus, controllerNamespace := GetMTVControllerInfo(ctx, kubeConfigFlags) // Get inventory information from global config inventoryURL, inventoryStatus, inventoryInsecure := GetInventoryInfo(globalConfig) return Info{ ClientVersion: clientVersion, OperatorVersion: controllerVersion, OperatorStatus: controllerStatus, OperatorNamespace: controllerNamespace, InventoryURL: inventoryURL, InventoryStatus: inventoryStatus, InventoryInsecure: inventoryInsecure, } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/discovery/registry.go
Go
package discovery import ( "context" "encoding/json" "fmt" "os" "os/exec" "sort" "strings" "time" ) // Registry holds discovered kubectl-mtv commands organized by read/write access. type Registry struct { // ReadOnly contains commands that don't modify cluster state ReadOnly map[string]*Command // ReadOnlyOrder preserves the original registration order of read-only // commands from help --machine. This is used for example selection so // the first command per group matches the developer's intended ordering. ReadOnlyOrder []string // ReadWrite contains commands that modify cluster state ReadWrite map[string]*Command // ReadWriteOrder preserves the original registration order of read-write commands. ReadWriteOrder []string // Parents contains non-runnable structural parent commands // (e.g., "get/inventory") for description lookup during group compaction. Parents map[string]*Command // GlobalFlags are flags available to all commands GlobalFlags []Flag // RootDescription is the main kubectl-mtv short description RootDescription string // LongDescription is the extended CLI description with domain context // (e.g., "Migrate virtual machines from VMware vSphere, oVirt...") LongDescription string } // NewRegistry creates a new registry by calling kubectl-mtv help --machine. // This single call returns the complete command schema as JSON. // It uses os.Executable() to call the same binary that is running the MCP server, // ensuring the help schema always matches the server's code (avoids version mismatch // when a different kubectl-mtv version is installed in PATH). func NewRegistry(ctx context.Context) (*Registry, error) { // Create command with timeout cmdCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() // Use the current executable to ensure help matches the running server self, err := os.Executable() if err != nil { // Fall back to PATH lookup if os.Executable fails self = "kubectl-mtv" } cmd := exec.CommandContext(cmdCtx, self, "help", "--machine") output, err := cmd.Output() if err != nil { return nil, fmt.Errorf("failed to get machine help: %w", err) } var schema HelpSchema if err := json.Unmarshal(output, &schema); err != nil { return nil, fmt.Errorf("failed to parse help schema: %w", err) } registry := &Registry{ ReadOnly: make(map[string]*Command), ReadWrite: make(map[string]*Command), Parents: make(map[string]*Command), GlobalFlags: schema.GlobalFlags, RootDescription: schema.Description, LongDescription: schema.LongDescription, } // Categorize commands by read/write based on category field. // Admin commands (completions, help, mcp-server, version) are skipped // entirely — they are irrelevant to LLM tool use. // Non-runnable parent commands are stored separately for description lookup. // // Backward compatibility: older CLI versions may not emit the "runnable" field. // We detect this by checking if ANY command has Runnable=true. If none do, // the schema predates the field and all commands are leaf commands. schemaHasRunnable := false for i := range schema.Commands { if schema.Commands[i].Runnable { schemaHasRunnable = true break } } for i := range schema.Commands { cmd := &schema.Commands[i] pathKey := cmd.PathKey() // Determine if this command is runnable: // - If the schema has the field: trust cmd.Runnable // - If the schema lacks the field: all commands are leaf (runnable) isRunnable := cmd.Runnable || !schemaHasRunnable // Store non-runnable parents separately for group description lookup if !isRunnable { registry.Parents[pathKey] = cmd continue } switch cmd.Category { case "read": registry.ReadOnly[pathKey] = cmd registry.ReadOnlyOrder = append(registry.ReadOnlyOrder, pathKey) case "admin": // Skip admin commands (shell completions, help, version, etc.) continue default: // "write" category registry.ReadWrite[pathKey] = cmd registry.ReadWriteOrder = append(registry.ReadWriteOrder, pathKey) } } return registry, nil } // GetCommand returns a command by its path key (e.g., "get/plan"). func (r *Registry) GetCommand(pathKey string) *Command { if cmd, ok := r.ReadOnly[pathKey]; ok { return cmd } if cmd, ok := r.ReadWrite[pathKey]; ok { return cmd } return nil } // GetCommandByPath returns a command by its path slice. func (r *Registry) GetCommandByPath(path []string) *Command { key := strings.Join(path, "/") return r.GetCommand(key) } // ListReadOnlyCommands returns sorted list of read-only command paths. func (r *Registry) ListReadOnlyCommands() []string { var commands []string for key := range r.ReadOnly { commands = append(commands, key) } sort.Strings(commands) return commands } // ListReadWriteCommands returns sorted list of read-write command paths. func (r *Registry) ListReadWriteCommands() []string { var commands []string for key := range r.ReadWrite { commands = append(commands, key) } sort.Strings(commands) return commands } // IsReadOnly checks if a command path is read-only. func (r *Registry) IsReadOnly(pathKey string) bool { _, ok := r.ReadOnly[pathKey] return ok } // IsReadWrite checks if a command path is read-write. func (r *Registry) IsReadWrite(pathKey string) bool { _, ok := r.ReadWrite[pathKey] return ok } // GenerateReadOnlyDescription generates a description for the read-only tool. func (r *Registry) GenerateReadOnlyDescription() string { roots := uniqueRootVerbs(r.ReadOnly) var sb strings.Builder sb.WriteString("MTV (Migration Toolkit for Virtualization) migrates VMs from VMware vSphere, oVirt, OpenStack, and Amazon EC2 into OpenShift Virtualization (KubeVirt).\n\n") sb.WriteString("Execute read-only kubectl-mtv commands to query MTV resources.\n\n") sb.WriteString(fmt.Sprintf("Commands: %s\n\n", strings.Join(roots, ", "))) sb.WriteString("Available commands:\n") commands := r.ListReadOnlyCommands() for _, key := range commands { cmd := r.ReadOnly[key] // Format: "get plan [NAME]" -> "get plan [NAME] - Get migration plans" usage := formatUsageShort(cmd) sb.WriteString(fmt.Sprintf("- %s - %s\n", usage, cmd.Description)) } sb.WriteString(r.formatGlobalFlags()) // Include extended notes from commands that have substantial LongDescription sb.WriteString(r.generateReadOnlyCommandNotes()) sb.WriteString("\nEnvironment Variable References:\n") sb.WriteString("- Use ${ENV_VAR_NAME} syntax to pass environment variable references as flag values\n") return sb.String() } // GenerateReadWriteDescription generates a description for the read-write tool. func (r *Registry) GenerateReadWriteDescription() string { var sb strings.Builder sb.WriteString("Execute kubectl-mtv commands that modify cluster state.\n\n") sb.WriteString("WARNING: These commands create, modify, or delete resources.\n\n") sb.WriteString("Typical migration workflow:\n") sb.WriteString("1. Set namespace for the migration\n") sb.WriteString("2. Check existing providers with mtv_read \"get provider\"; create via mtv_write \"create provider\" only if needed\n") sb.WriteString("3. Browse VMs with mtv_read \"get inventory vm\" + TSL queries\n") sb.WriteString("4. Create a migration plan (network/storage mappings are auto-generated; use --network-pairs/--storage-pairs to override)\n") sb.WriteString("5. Start the plan\n") sb.WriteString("6. Monitor with mtv_read \"get plan\", debug with kubectl_logs\n\n") readRoots := uniqueRootVerbs(r.ReadOnly) sb.WriteString(fmt.Sprintf("NOTE: For read-only operations (%s), use the mtv_read tool instead.\n\n", strings.Join(readRoots, ", "))) sb.WriteString("Available commands:\n") commands := r.ListReadWriteCommands() for _, key := range commands { cmd := r.ReadWrite[key] usage := formatUsageShort(cmd) sb.WriteString(fmt.Sprintf("- %s - %s\n", usage, cmd.Description)) } sb.WriteString(r.formatGlobalFlags()) // Append per-command flag reference for complex write commands sb.WriteString(r.generateFlagReference()) sb.WriteString("\nEnvironment Variable References:\n") sb.WriteString("You can pass environment variable references instead of literal values for any flag:\n") sb.WriteString("- Use ${ENV_VAR_NAME} syntax with curly braces (e.g., url: \"${GOVC_URL}\", password: \"${VCENTER_PASSWORD}\")\n") sb.WriteString("- Env vars can be embedded in strings (e.g., url: \"${GOVC_URL}/sdk\", endpoint: \"https://${HOST}:${PORT}/api\")\n") sb.WriteString("- IMPORTANT: Only ${VAR} format is recognized as env var reference. Bare $VAR is treated as literal value.\n") sb.WriteString("- The MCP server resolves the env var at execution time\n") sb.WriteString("- Sensitive values (passwords, tokens) are masked in command output for security\n") return sb.String() } // GenerateMinimalReadOnlyDescription generates a minimal description for the read-only tool. // It puts the command list first (most critical for the LM), followed by examples // and a hint to use mtv_help. Domain context and conventions are omitted to stay // within client description limits and avoid noise for smaller models. func (r *Registry) GenerateMinimalReadOnlyDescription() string { var sb strings.Builder sb.WriteString("MTV (Migration Toolkit for Virtualization) migrates VMs from VMware vSphere, oVirt, OpenStack, and Amazon EC2 into OpenShift Virtualization (KubeVirt).\n") sb.WriteString("\nQuery MTV resources (read-only).\n") sb.WriteString("\nCommands:\n") // Detect deep sibling groups (depth >= 3) for compaction groups, groupedKeys := detectDeepSiblingGroups(r.ReadOnly, r.Parents) // List non-grouped commands normally commands := r.ListReadOnlyCommands() for _, key := range commands { if groupedKeys[key] { continue } cmd := r.ReadOnly[key] sb.WriteString(fmt.Sprintf(" %s - %s\n", cmd.CommandPath(), cmd.Description)) } // Write compacted sibling groups for _, group := range groups { parentDisplay := strings.ReplaceAll(group.parentPath, "/", " ") sb.WriteString(fmt.Sprintf(" %s RESOURCE - %s\n", parentDisplay, group.description)) sb.WriteString(fmt.Sprintf(" Resources: %s\n", strings.Join(group.children, ", "))) } // Examples: first example from each command in order, capped at N examples := r.collectOrderedExamples(r.ReadOnly, r.ReadOnlyOrder, 6) if len(examples) > 0 { sb.WriteString("\nExamples:\n") for _, ex := range examples { sb.WriteString(fmt.Sprintf(" %s\n", ex)) } } sb.WriteString(r.formatGlobalFlags()) sb.WriteString("\nDefault output is table. For structured data, use flags: {output: \"json\"} and fields: [\"name\", \"status\"] to limit response size.\n") sb.WriteString("IMPORTANT: 'fields' is a TOP-LEVEL parameter, NOT inside flags. Example: {command: \"get plan\", flags: {output: \"json\"}, fields: [\"name\", \"status\"]}\n") sb.WriteString("Use mtv_help for flags, TSL query syntax, and examples.\n") sb.WriteString("IMPORTANT: Before writing inventory queries, call mtv_help(\"tsl\") to learn available fields per provider and query syntax.\n") return sb.String() } // GenerateMinimalReadWriteDescription generates a minimal description for the read-write tool. // It puts the command list first (most critical for the LM), followed by examples // and a hint to use mtv_help. Domain context and conventions are omitted to stay // within client description limits and avoid noise for smaller models. func (r *Registry) GenerateMinimalReadWriteDescription() string { // Detect bare parent commands to skip them from the listing. // Admin commands are already filtered out by NewRegistry. bareParents := detectBareParents(r.ReadWrite) var sb strings.Builder sb.WriteString("Create, modify, or delete MTV resources (write operations).\n") sb.WriteString("\nTypical migration workflow:\n") sb.WriteString("1. Set namespace for the migration\n") sb.WriteString("2. Check existing providers with mtv_read \"get provider\"; create via mtv_write \"create provider\" only if needed\n") sb.WriteString("3. Browse VMs with mtv_read \"get inventory vm\" + TSL queries\n") sb.WriteString("4. Create a migration plan (network/storage mappings are auto-generated; use --network-pairs/--storage-pairs to override)\n") sb.WriteString("5. Start the plan\n") sb.WriteString("6. Monitor with mtv_read \"get plan\", debug with kubectl_logs\n") sb.WriteString("\nCommands:\n") commands := r.ListReadWriteCommands() for _, key := range commands { if bareParents[key] { continue } cmd := r.ReadWrite[key] usage := formatUsageShort(cmd) sb.WriteString(fmt.Sprintf(" %s - %s\n", usage, cmd.Description)) } examples := r.collectOrderedExamples(r.ReadWrite, r.ReadWriteOrder, 8) if len(examples) > 0 { sb.WriteString("\nExamples:\n") for _, ex := range examples { sb.WriteString(fmt.Sprintf(" %s\n", ex)) } } sb.WriteString(r.formatGlobalFlags()) sb.WriteString("\nCall mtv_help before create/patch to learn required flags, TSL (Tree Search Language) query syntax, and KARL (affinity/anti-affinity rule) syntax.\n") return sb.String() } // ultraMinimalReadCommands lists the most commonly used read commands for the // ultra-minimal description. Only these are shown to very small models. var ultraMinimalReadCommands = map[string]bool{ "get/plan": true, "get/provider": true, "describe/plan": true, "get/inventory/vm": true, "get/mapping": true, "health": true, "settings/get": true, "get/inventory/network": true, "get/inventory/datastore": true, } // ultraMinimalWriteCommands lists the most commonly used write commands. var ultraMinimalWriteCommands = map[string]bool{ "create/provider": true, "create/plan": true, "start/plan": true, "delete/plan": true, "delete/provider": true, "patch/plan": true, "create/mapping/network": true, "create/mapping/storage": true, } // GenerateUltraMinimalReadOnlyDescription generates the shortest possible description // for the read-only tool, optimized for very small models (< 8B parameters). // It lists only the most common commands, 2 examples, and omits flags/workflow/notes. func (r *Registry) GenerateUltraMinimalReadOnlyDescription() string { var sb strings.Builder sb.WriteString("Query MTV migration resources (read-only).\n") sb.WriteString("\nCommands:\n") // List only ultra-minimal commands that exist in the registry commands := r.ListReadOnlyCommands() for _, key := range commands { if !ultraMinimalReadCommands[key] { continue } cmd := r.ReadOnly[key] sb.WriteString(fmt.Sprintf(" %s - %s\n", cmd.CommandPath(), cmd.Description)) } // If we have inventory commands not in the explicit list, mention them as a group hasInventory := false for key := range r.ReadOnly { if strings.HasPrefix(key, "get/inventory/") && !ultraMinimalReadCommands[key] { hasInventory = true break } } if hasInventory { sb.WriteString(" get inventory RESOURCE - Get other inventory resources (disk, host, cluster, ...)\n") } sb.WriteString("\nExamples:\n") sb.WriteString(" {command: \"get plan\", flags: {namespace: \"demo\"}}\n") sb.WriteString(" {command: \"get inventory vm\", flags: {provider: \"vsphere-prod\", namespace: \"demo\"}}\n") sb.WriteString("\nUse mtv_help for flags and query syntax.\n") return sb.String() } // GenerateUltraMinimalReadWriteDescription generates the shortest possible description // for the read-write tool, optimized for very small models (< 8B parameters). func (r *Registry) GenerateUltraMinimalReadWriteDescription() string { var sb strings.Builder sb.WriteString("Create, modify, or delete MTV migration resources.\n") sb.WriteString("\nCommands:\n") commands := r.ListReadWriteCommands() for _, key := range commands { if !ultraMinimalWriteCommands[key] { continue } cmd := r.ReadWrite[key] sb.WriteString(fmt.Sprintf(" %s - %s\n", cmd.CommandPath(), cmd.Description)) } sb.WriteString("\nExamples:\n") sb.WriteString(" {command: \"create plan\", flags: {name: \"my-plan\", source: \"vsphere-prod\", target: \"host\", vms: \"web-server\", namespace: \"demo\"}}\n") sb.WriteString(" {command: \"start plan\", flags: {name: \"my-plan\", namespace: \"demo\"}}\n") sb.WriteString("\nCall mtv_help before create/patch to learn required flags.\n") return sb.String() } // generateFlagReference builds a concise per-command flag reference for write commands. // It includes all flags for commands that have required flags or many flags (complex commands), // so the LLM can construct valid calls without guessing flag names. func (r *Registry) generateFlagReference() string { var sb strings.Builder // Collect commands that need flag documentation: // 1. Commands with any required flags (these fail 100% without flag knowledge) // 2. Key complex commands (create/patch provider, create plan, create mapping) type commandEntry struct { pathKey string cmd *Command } // Get sorted list of write commands keys := r.ListReadWriteCommands() // First pass: identify commands with required flags or many flags var flaggedCommands []commandEntry for _, key := range keys { cmd := r.ReadWrite[key] if cmd == nil || len(cmd.Flags) == 0 { continue } hasRequired := false for _, f := range cmd.Flags { if f.Required { hasRequired = true break } } // Include if: has required flags, or is a complex command (>5 flags) if hasRequired || len(cmd.Flags) > 5 { flaggedCommands = append(flaggedCommands, commandEntry{key, cmd}) } } if len(flaggedCommands) == 0 { return "" } sb.WriteString("\nFlag reference for complex commands:\n") for _, entry := range flaggedCommands { cmd := entry.cmd cmdPath := strings.ReplaceAll(entry.pathKey, "/", " ") // Include the command's LongDescription when available, as it may contain // syntax references (e.g., KARL affinity syntax, TSL query language) if cmd.LongDescription != "" { sb.WriteString(fmt.Sprintf("\n%s notes:\n%s\n", cmdPath, cmd.LongDescription)) } sb.WriteString(fmt.Sprintf("\n%s flags:\n", cmdPath)) for _, f := range cmd.Flags { if f.Hidden { continue } // Format: " --name (type) - description [REQUIRED] [enum: a|b|c]" line := fmt.Sprintf(" --%s", f.Name) // Add type for non-bool flags if f.Type != "bool" { line += fmt.Sprintf(" (%s)", f.Type) } line += fmt.Sprintf(" - %s", f.Description) if f.Required { line += " [REQUIRED]" } if len(f.Enum) > 0 { line += fmt.Sprintf(" [enum: %s]", strings.Join(f.Enum, "|")) } sb.WriteString(line + "\n") } } return sb.String() } // generateReadOnlyCommandNotes includes LongDescription from read-only commands // that have substantial documentation (e.g., query language syntax references). // This surfaces documentation that was added to Cobra Long descriptions into the // MCP tool description, so AI clients can discover syntax without external docs. func (r *Registry) generateReadOnlyCommandNotes() string { var sb strings.Builder // Minimum length threshold to avoid including trivial one-liner descriptions const minLongDescLength = 200 commands := r.ListReadOnlyCommands() var hasNotes bool for _, key := range commands { cmd := r.ReadOnly[key] if cmd == nil || len(cmd.LongDescription) < minLongDescLength { continue } if !hasNotes { sb.WriteString("\nCommand notes:\n") hasNotes = true } cmdPath := strings.ReplaceAll(key, "/", " ") sb.WriteString(fmt.Sprintf("\n%s:\n%s\n", cmdPath, cmd.LongDescription)) } return sb.String() } // collectOrderedExamples collects MCP-style examples by iterating commands in // their help registration order and taking the first example from each command. // No heuristics — the help output order is the source of truth. func (r *Registry) collectOrderedExamples(commands map[string]*Command, orderedKeys []string, maxExamples int) []string { var examples []string for _, key := range orderedKeys { if len(examples) >= maxExamples { break } cmd := commands[key] if cmd == nil || len(cmd.Examples) == 0 { continue } mcpExamples := convertCLIToMCPExamples(cmd, 1) examples = append(examples, mcpExamples...) } return examples } // sensitiveFlags lists flag names whose values should not appear in MCP examples. // These are replaced with a placeholder to avoid leaking credentials. var sensitiveFlags = map[string]bool{ "password": true, "token": true, "provider-token": true, "secret": true, "secret-name": true, } // convertCLIToMCPExamples converts up to n CLI examples of a command into // MCP-style call format strings. CLI commands should define their most // instructive examples first — this is the source of truth for MCP descriptions. // Duplicate MCP call strings (e.g., examples that differ only in description) // are deduplicated. func convertCLIToMCPExamples(cmd *Command, n int) []string { if len(cmd.Examples) == 0 || n <= 0 { return nil } pathString := cmd.CommandPath() seen := make(map[string]bool) var results []string for _, ex := range cmd.Examples { if len(results) >= n { break } mcpCall := formatCLIAsMCP(ex.Command, pathString) if mcpCall != "" && !seen[mcpCall] { results = append(results, mcpCall) seen[mcpCall] = true } } return results } // formatCLIAsMCP parses a single CLI command string and converts it to // MCP-style call format: {command: "...", flags: {...}}. // It strips the CLI prefix and collects --flag value pairs. // // Examples: // // "kubectl-mtv get plan" → {command: "get plan"} // "kubectl-mtv get inventory vm --provider vsphere-prod --query \"where len(nics) >= 2\"" → // {command: "get inventory vm", flags: {provider: "vsphere-prod", query: "where len(nics) >= 2"}} func formatCLIAsMCP(cliCmd string, pathString string) string { cliCmd = strings.TrimSpace(cliCmd) if cliCmd == "" { return "" } cliCmd = strings.TrimPrefix(cliCmd, "kubectl-mtv ") cliCmd = strings.TrimPrefix(cliCmd, "kubectl mtv ") // Strip the command path from the front to get flags rest := cliCmd pathParts := strings.Fields(pathString) for _, part := range pathParts { rest = strings.TrimSpace(rest) if strings.HasPrefix(rest, part+" ") { rest = rest[len(part)+1:] } else if rest == part { rest = "" } } rest = strings.TrimSpace(rest) if rest == "" { return fmt.Sprintf("{command: \"%s\"}", pathString) } tokens := shellTokenize(rest) flagMap := make(map[string]string) // Extract --flag value pairs (no positional args to handle) for i := 0; i < len(tokens); i++ { tok := tokens[i] if !strings.HasPrefix(tok, "-") { continue // skip stray tokens } // Strip leading dashes and handle --flag=value syntax flagName := strings.TrimLeft(tok, "-") var flagValue string if eqIdx := strings.Index(flagName, "="); eqIdx >= 0 { flagValue = flagName[eqIdx+1:] flagName = flagName[:eqIdx] } else if i+1 < len(tokens) && !strings.HasPrefix(tokens[i+1], "-") { i++ flagValue = tokens[i] } else { // Boolean flag (no value) flagValue = "true" } // Skip sensitive flags if sensitiveFlags[flagName] { continue } // Strip surrounding quotes flagValue = strings.Trim(flagValue, "'\"") // Use underscores for MCP JSON convention displayName := strings.ReplaceAll(flagName, "-", "_") flagMap[displayName] = flagValue } if len(flagMap) == 0 { return fmt.Sprintf("{command: \"%s\"}", pathString) } var flagParts []string for k, v := range flagMap { if v == "true" { flagParts = append(flagParts, fmt.Sprintf("%s: true", k)) } else { flagParts = append(flagParts, fmt.Sprintf("%s: \"%s\"", k, v)) } } // Sort for deterministic output sort.Strings(flagParts) return fmt.Sprintf("{command: \"%s\", flags: {%s}}", pathString, strings.Join(flagParts, ", ")) } // shellTokenize splits a string into tokens, respecting double-quoted and // single-quoted substrings so that values like "VM Network:default" remain // a single token. Quotes are stripped from the returned tokens. func shellTokenize(s string) []string { var tokens []string var current strings.Builder inDouble := false inSingle := false for i := 0; i < len(s); i++ { ch := s[i] switch { case ch == '"' && !inSingle: inDouble = !inDouble case ch == '\'' && !inDouble: inSingle = !inSingle case ch == ' ' && !inDouble && !inSingle: if current.Len() > 0 { tokens = append(tokens, current.String()) current.Reset() } default: current.WriteByte(ch) } } if current.Len() > 0 { tokens = append(tokens, current.String()) } return tokens } // uniqueRootVerbs extracts the unique first path element from a set of commands // and returns them sorted. For example, commands "get/plan", "get/provider", // "describe/plan", "health" produce ["describe", "get", "health"]. func uniqueRootVerbs(commands map[string]*Command) []string { seen := make(map[string]bool) for key := range commands { parts := strings.SplitN(key, "/", 2) seen[parts[0]] = true } roots := make([]string, 0, len(seen)) for root := range seen { roots = append(roots, root) } sort.Strings(roots) return roots } // importantGlobalFlags lists the global flags that are relevant for MCP tool descriptions. var importantGlobalFlags = map[string]bool{ "namespace": true, "all-namespaces": true, "inventory-url": true, "verbose": true, } func (r *Registry) formatGlobalFlags(extraNames ...string) string { extras := make(map[string]bool, len(extraNames)) for _, name := range extraNames { extras[name] = true } var sb strings.Builder sb.WriteString("\nCommon flags:\n") found := false for _, f := range r.GlobalFlags { if !importantGlobalFlags[f.Name] && !extras[f.Name] { continue } found = true displayName := strings.ReplaceAll(f.Name, "-", "_") sb.WriteString(fmt.Sprintf("- %s: %s\n", displayName, f.Description)) } if !found { return "" } return sb.String() } // deepSiblingGroup represents a group of commands at depth >= 3 that share a common parent path. type deepSiblingGroup struct { parentPath string children []string description string } // detectDeepSiblingGroups finds groups of commands at depth >= 3 that share a common // parent path with at least 3 siblings (e.g., get/inventory/*). This is used to // compact many inventory-style subcommands into a single summary line. func detectDeepSiblingGroups(commands map[string]*Command, parents map[string]*Command) ([]deepSiblingGroup, map[string]bool) { const minGroupSize = 3 parentChildren := make(map[string][]string) parentChildKeys := make(map[string][]string) for key := range commands { parts := strings.Split(key, "/") if len(parts) < 3 { continue } parentPath := strings.Join(parts[:len(parts)-1], "/") childName := parts[len(parts)-1] parentChildren[parentPath] = append(parentChildren[parentPath], childName) parentChildKeys[parentPath] = append(parentChildKeys[parentPath], key) } var groups []deepSiblingGroup groupedKeys := make(map[string]bool) var parentPaths []string for p := range parentChildren { parentPaths = append(parentPaths, p) } sort.Strings(parentPaths) for _, parentPath := range parentPaths { children := parentChildren[parentPath] if len(children) < minGroupSize { continue } sort.Strings(children) // Use parent's description if available desc := "" if parents != nil { if parent, ok := parents[parentPath]; ok && parent.Description != "" { desc = parent.Description } } if desc == "" { desc = "Get " + strings.ReplaceAll(parentPath, "/", " ") + " resources" } groups = append(groups, deepSiblingGroup{ parentPath: parentPath, children: children, description: desc, }) for _, key := range parentChildKeys[parentPath] { groupedKeys[key] = true } } return groups, groupedKeys } // detectBareParents finds commands that are structural grouping nodes rather than // real commands. A bare parent is a command whose path is a proper prefix of another // command's path AND that has no command-specific flags. func detectBareParents(commands map[string]*Command) map[string]bool { bareParents := make(map[string]bool) keys := make([]string, 0, len(commands)) for k := range commands { keys = append(keys, k) } for _, key := range keys { cmd := commands[key] // Must have no command-specific flags if len(cmd.Flags) > 0 { continue } // Check if this path is a proper prefix of any other command's path prefix := key + "/" for _, otherKey := range keys { if strings.HasPrefix(otherKey, prefix) { bareParents[key] = true break } } } return bareParents } // formatUsageShort returns a short usage string for a command. func formatUsageShort(cmd *Command) string { return cmd.CommandPath() } // BuildCommandArgs builds command-line arguments from command path and flags. func BuildCommandArgs(cmdPath string, flags map[string]string, namespace string, allNamespaces bool) []string { var args []string // Add command path parts := strings.Split(cmdPath, "/") args = append(args, parts...) // Add namespace flags if allNamespaces { args = append(args, "--all-namespaces") } else if namespace != "" { args = append(args, "--namespace", namespace) } // Add other flags for name, value := range flags { if name == "namespace" || name == "all_namespaces" { continue // Already handled } if value == "true" { // Boolean flag args = append(args, "--"+name) } else if value == "false" { // Skip false boolean flags continue } else if value != "" { // String/int flag with value args = append(args, "--"+name, value) } } return args }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/discovery/registry_test.go
Go
package discovery import ( "encoding/json" "os" "path/filepath" "runtime" "strings" "testing" ) // testdataPath returns the path to the help_machine_output.json fixture // located in the testdata/ directory alongside this test file. func testdataPath() string { _, thisFile, _, _ := runtime.Caller(0) return filepath.Join(filepath.Dir(thisFile), "testdata", "help_machine_output.json") } // loadRealRegistry loads a Registry from the real help_machine_output.json file. // It skips the test if the file is not available. func loadRealRegistry(t *testing.T) *Registry { t.Helper() data, err := os.ReadFile(testdataPath()) if err != nil { t.Skipf("Skipping: could not read help_machine_output.json: %v", err) } var schema HelpSchema if err := json.Unmarshal(data, &schema); err != nil { t.Fatalf("Failed to parse help_machine_output.json: %v", err) } registry := &Registry{ ReadOnly: make(map[string]*Command), ReadWrite: make(map[string]*Command), Parents: make(map[string]*Command), GlobalFlags: schema.GlobalFlags, RootDescription: schema.Description, LongDescription: schema.LongDescription, } for i := range schema.Commands { cmd := &schema.Commands[i] pathKey := cmd.PathKey() // Store non-runnable parents separately, matching NewRegistry behavior if !cmd.Runnable { registry.Parents[pathKey] = cmd continue } switch cmd.Category { case "read": registry.ReadOnly[pathKey] = cmd registry.ReadOnlyOrder = append(registry.ReadOnlyOrder, pathKey) case "admin": // Skip admin commands, matching NewRegistry behavior continue default: registry.ReadWrite[pathKey] = cmd registry.ReadWriteOrder = append(registry.ReadWriteOrder, pathKey) } } return registry } func TestCommand_PathKey(t *testing.T) { tests := []struct { name string cmd Command expected string }{ { name: "single level path", cmd: Command{ Path: []string{"get"}, }, expected: "get", }, { name: "two level path", cmd: Command{ Path: []string{"get", "plan"}, }, expected: "get/plan", }, { name: "three level path", cmd: Command{ Path: []string{"get", "inventory", "vm"}, }, expected: "get/inventory/vm", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.cmd.PathKey() if result != tt.expected { t.Errorf("PathKey() = %q, want %q", result, tt.expected) } }) } } func TestCommand_CommandPath(t *testing.T) { tests := []struct { name string cmd Command expected string }{ { name: "uses PathString if available", cmd: Command{ Path: []string{"get", "plan"}, PathString: "get plan", }, expected: "get plan", }, { name: "falls back to joining Path", cmd: Command{ Path: []string{"get", "inventory", "vm"}, }, expected: "get inventory vm", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.cmd.CommandPath() if result != tt.expected { t.Errorf("CommandPath() = %q, want %q", result, tt.expected) } }) } } func TestRegistry_IsReadOnly(t *testing.T) { registry := &Registry{ ReadOnly: map[string]*Command{ "get/plan": {Path: []string{"get", "plan"}}, "describe/vm": {Path: []string{"describe", "vm"}}, }, ReadWrite: map[string]*Command{ "create/plan": {Path: []string{"create", "plan"}}, "delete/plan": {Path: []string{"delete", "plan"}}, }, } tests := []struct { pathKey string expected bool }{ {"get/plan", true}, {"describe/vm", true}, {"create/plan", false}, {"delete/plan", false}, {"unknown/cmd", false}, } for _, tt := range tests { t.Run(tt.pathKey, func(t *testing.T) { result := registry.IsReadOnly(tt.pathKey) if result != tt.expected { t.Errorf("IsReadOnly(%q) = %v, want %v", tt.pathKey, result, tt.expected) } }) } } func TestRegistry_IsReadWrite(t *testing.T) { registry := &Registry{ ReadOnly: map[string]*Command{ "get/plan": {Path: []string{"get", "plan"}}, }, ReadWrite: map[string]*Command{ "create/plan": {Path: []string{"create", "plan"}}, "delete/plan": {Path: []string{"delete", "plan"}}, }, } tests := []struct { pathKey string expected bool }{ {"get/plan", false}, {"create/plan", true}, {"delete/plan", true}, {"unknown/cmd", false}, } for _, tt := range tests { t.Run(tt.pathKey, func(t *testing.T) { result := registry.IsReadWrite(tt.pathKey) if result != tt.expected { t.Errorf("IsReadWrite(%q) = %v, want %v", tt.pathKey, result, tt.expected) } }) } } func TestRegistry_GetCommand(t *testing.T) { readCmd := &Command{Path: []string{"get", "plan"}, Description: "Get plans"} writeCmd := &Command{Path: []string{"create", "plan"}, Description: "Create plan"} registry := &Registry{ ReadOnly: map[string]*Command{ "get/plan": readCmd, }, ReadWrite: map[string]*Command{ "create/plan": writeCmd, }, } tests := []struct { pathKey string expected *Command }{ {"get/plan", readCmd}, {"create/plan", writeCmd}, {"unknown/cmd", nil}, } for _, tt := range tests { t.Run(tt.pathKey, func(t *testing.T) { result := registry.GetCommand(tt.pathKey) if result != tt.expected { t.Errorf("GetCommand(%q) = %v, want %v", tt.pathKey, result, tt.expected) } }) } } func TestRegistry_ListReadOnlyCommands(t *testing.T) { registry := &Registry{ ReadOnly: map[string]*Command{ "get/plan": {Path: []string{"get", "plan"}}, "describe/vm": {Path: []string{"describe", "vm"}}, "get/inventory/vm": {Path: []string{"get", "inventory", "vm"}}, }, ReadWrite: map[string]*Command{ "create/plan": {Path: []string{"create", "plan"}}, }, } result := registry.ListReadOnlyCommands() // Should be sorted expected := []string{"describe/vm", "get/inventory/vm", "get/plan"} if len(result) != len(expected) { t.Fatalf("ListReadOnlyCommands() returned %d items, want %d", len(result), len(expected)) } for i, v := range expected { if result[i] != v { t.Errorf("ListReadOnlyCommands()[%d] = %q, want %q", i, result[i], v) } } } func TestRegistry_ListReadWriteCommands(t *testing.T) { registry := &Registry{ ReadOnly: map[string]*Command{ "get/plan": {Path: []string{"get", "plan"}}, }, ReadWrite: map[string]*Command{ "create/plan": {Path: []string{"create", "plan"}}, "delete/plan": {Path: []string{"delete", "plan"}}, "start/plan": {Path: []string{"start", "plan"}}, }, } result := registry.ListReadWriteCommands() // Should be sorted expected := []string{"create/plan", "delete/plan", "start/plan"} if len(result) != len(expected) { t.Fatalf("ListReadWriteCommands() returned %d items, want %d", len(result), len(expected)) } for i, v := range expected { if result[i] != v { t.Errorf("ListReadWriteCommands()[%d] = %q, want %q", i, result[i], v) } } } func TestBuildCommandArgs(t *testing.T) { tests := []struct { name string cmdPath string flags map[string]string namespace string allNamespaces bool expected []string }{ { name: "simple command", cmdPath: "get/plan", expected: []string{"get", "plan"}, }, { name: "with flag", cmdPath: "get/plan", flags: map[string]string{"name": "my-plan"}, expected: []string{"get", "plan", "--name", "my-plan"}, }, { name: "with namespace", cmdPath: "get/plan", namespace: "test-ns", expected: []string{"get", "plan", "--namespace", "test-ns"}, }, { name: "with all namespaces", cmdPath: "get/plan", allNamespaces: true, expected: []string{"get", "plan", "--all-namespaces"}, }, { name: "with string flag", cmdPath: "get/plan", flags: map[string]string{"output": "json"}, expected: []string{"get", "plan", "--output", "json"}, }, { name: "with boolean true flag", cmdPath: "get/plan", flags: map[string]string{"watch": "true"}, expected: []string{"get", "plan", "--watch"}, }, { name: "with boolean false flag - skipped", cmdPath: "get/plan", flags: map[string]string{"watch": "false"}, expected: []string{"get", "plan"}, }, { name: "namespace flag in map is ignored", cmdPath: "get/plan", namespace: "test-ns", flags: map[string]string{"namespace": "other-ns"}, expected: []string{"get", "plan", "--namespace", "test-ns"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := BuildCommandArgs(tt.cmdPath, tt.flags, tt.namespace, tt.allNamespaces) if len(result) != len(tt.expected) { t.Fatalf("BuildCommandArgs() returned %v, want %v", result, tt.expected) } for i, v := range tt.expected { if result[i] != v { t.Errorf("BuildCommandArgs()[%d] = %q, want %q", i, result[i], v) } } }) } } func TestFormatUsageShort(t *testing.T) { tests := []struct { name string cmd *Command expected string }{ { name: "command path", cmd: &Command{ PathString: "get plan", }, expected: "get plan", }, { name: "multi-segment path", cmd: &Command{ PathString: "create provider", }, expected: "create provider", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := formatUsageShort(tt.cmd) if result != tt.expected { t.Errorf("formatUsageShort() = %q, want %q", result, tt.expected) } }) } } func TestRegistry_GenerateReadOnlyDescription_Synthetic(t *testing.T) { registry := &Registry{ ReadOnly: map[string]*Command{ "get/plan": { PathString: "get plan", Description: "Get migration plans", }, }, ReadWrite: map[string]*Command{}, GlobalFlags: []Flag{ {Name: "namespace", Description: "Target namespace"}, }, } result := registry.GenerateReadOnlyDescription() if !strings.Contains(result, "read-only") { t.Error("Description should mention read-only") } if !strings.Contains(result, "get plan") { t.Error("Description should include command") } if !strings.Contains(result, "Get migration plans") { t.Error("Description should include command description") } // Root verbs should be derived from the command map if !strings.Contains(result, "Commands: get") { t.Error("Description should contain data-derived root verbs") } // Global flags should be derived from GlobalFlags data (important flags) if !strings.Contains(result, "namespace: Target namespace") { t.Error("Description should contain global flag descriptions from data") } } func TestRegistry_GenerateReadWriteDescription_Synthetic(t *testing.T) { registry := &Registry{ ReadOnly: map[string]*Command{ "get/plan": {PathString: "get plan", Description: "Get plans"}, }, ReadWrite: map[string]*Command{ "create/plan": { PathString: "create plan", Description: "Create a migration plan", }, }, GlobalFlags: []Flag{ {Name: "namespace", Description: "Target namespace"}, }, } result := registry.GenerateReadWriteDescription() if !strings.Contains(result, "WARNING") { t.Error("Description should include WARNING") } if !strings.Contains(result, "create plan") { t.Error("Description should include command") } if !strings.Contains(result, "Create a migration plan") { t.Error("Description should include command description") } // Should derive read-only root verbs for the NOTE line if !strings.Contains(result, "For read-only operations (get)") { t.Errorf("Description should derive read-only root verbs: %s", result) } } // --- Tests using real help --machine output --- func TestRegistry_RealHelpMachine_ReadOnlyDescription(t *testing.T) { registry := loadRealRegistry(t) result := registry.GenerateReadOnlyDescription() // Should contain key read-only commands for _, expected := range []string{ "health", "get plan", "get provider", "get inventory vm", "describe plan", "settings get", } { if !strings.Contains(result, expected) { t.Errorf("Read-only description should contain %q", expected) } } // Should NOT contain write commands for _, notExpected := range []string{ "create provider", "delete plan", "start plan", } { if strings.Contains(result, notExpected) { t.Errorf("Read-only description should NOT contain write command %q", notExpected) } } } func TestRegistry_RealHelpMachine_ReadWriteDescription(t *testing.T) { registry := loadRealRegistry(t) result := registry.GenerateReadWriteDescription() // Should contain key write commands for _, expected := range []string{ "create provider", "create plan", "delete plan", "start plan", "patch provider", "cancel plan", } { if !strings.Contains(result, expected) { t.Errorf("Read-write description should contain %q", expected) } } // Should contain env var documentation with embedded support if !strings.Contains(result, "${ENV_VAR_NAME}") { t.Error("Description should document env var syntax") } if !strings.Contains(result, "${GOVC_URL}/sdk") { t.Error("Description should document embedded env var references") } } func TestRegistry_RealHelpMachine_FlagReference(t *testing.T) { registry := loadRealRegistry(t) result := registry.GenerateReadWriteDescription() // Should contain the flag reference section if !strings.Contains(result, "Flag reference for complex commands:") { t.Fatal("Description should contain flag reference section") } // Should surface required flags that previously caused 100% failure requiredFlags := []struct { command string flag string }{ {"create provider", "--type"}, {"create provider", "[REQUIRED]"}, {"create provider", "[enum:"}, {"cancel plan", "--vms"}, {"cancel plan", "[REQUIRED]"}, {"create host", "--provider"}, {"create host", "[REQUIRED]"}, {"create vddk-image", "--tag"}, {"create vddk-image", "--tar"}, } for _, rf := range requiredFlags { if !strings.Contains(result, rf.flag) { t.Errorf("Flag reference should contain %q (for %s)", rf.flag, rf.command) } } // Should surface key flags that the LLM needs for common operations keyFlags := []string{ "--provider-insecure-skip-tls", "--url", "--username", "--password", "--sdk-endpoint", "--vddk-init-image", "--source", "--target", "--migration-type", } for _, flag := range keyFlags { if !strings.Contains(result, flag) { t.Errorf("Flag reference should contain key flag %q", flag) } } // Should surface enum values for constrained flags enumValues := []string{ "openshift", "vsphere", "ovirt", "openstack", "cold", "warm", } for _, val := range enumValues { if !strings.Contains(result, val) { t.Errorf("Flag reference should contain enum value %q", val) } } } func TestRegistry_RealHelpMachine_CommandCounts(t *testing.T) { registry := loadRealRegistry(t) readCount := len(registry.ReadOnly) writeCount := len(registry.ReadWrite) // Sanity check: the real data should have a reasonable number of commands. // Admin commands are filtered out by NewRegistry, so write count is lower. if readCount < 30 { t.Errorf("Expected at least 30 read-only commands, got %d", readCount) } if writeCount < 15 { t.Errorf("Expected at least 15 write commands (admin excluded), got %d", writeCount) } // Verify key commands exist keyReadCommands := []string{"health", "get/plan", "get/provider", "get/inventory/vm", "describe/plan"} for _, cmd := range keyReadCommands { if registry.ReadOnly[cmd] == nil { t.Errorf("Expected read-only command %q to exist", cmd) } } keyWriteCommands := []string{"create/provider", "create/plan", "delete/plan", "start/plan", "patch/provider", "cancel/plan"} for _, cmd := range keyWriteCommands { if registry.ReadWrite[cmd] == nil { t.Errorf("Expected read-write command %q to exist", cmd) } } } func TestRegistry_RealHelpMachine_KARLReference(t *testing.T) { registry := loadRealRegistry(t) result := registry.GenerateReadWriteDescription() // KARL syntax reference should be surfaced via LongDescription of create plan and patch plan. // Detailed KARL syntax is available via 'help karl'; command descriptions contain a summary. karlKeywords := []string{ "Affinity Syntax (KARL)", "REQUIRE", "PREFER", "AVOID", "REPEL", "pods(", "weight=", "Topology:", "help karl", } for _, keyword := range karlKeywords { if !strings.Contains(result, keyword) { t.Errorf("Read-write description should contain KARL keyword %q", keyword) } } } func TestRegistry_RealHelpMachine_QueryLanguageReference(t *testing.T) { registry := loadRealRegistry(t) // Query language reference should appear in the write description (via create plan LongDescription). // Detailed TSL syntax and field lists are available via 'help tsl'; command descriptions contain a summary. writeResult := registry.GenerateReadWriteDescription() tslKeywords := []string{ "Query Language (TSL)", "where", "~=", "cpuCount", "memoryMB", "powerState", "len(disks)", "help tsl", } for _, keyword := range tslKeywords { if !strings.Contains(writeResult, keyword) { t.Errorf("Read-write description should contain TSL keyword %q", keyword) } } // Query language reference should also appear in the read-only description // (via get inventory vm LongDescription) readResult := registry.GenerateReadOnlyDescription() readTSLKeywords := []string{ "Query Language (TSL)", "where", "like", "~=", "ORDER BY", "--output json", "cpuCount", "help tsl", } for _, keyword := range readTSLKeywords { if !strings.Contains(readResult, keyword) { t.Errorf("Read-only description should contain TSL keyword %q", keyword) } } } // --- Tests for generic helper functions --- func TestUniqueRootVerbs(t *testing.T) { commands := map[string]*Command{ "get/plan": {}, "get/provider": {}, "get/inventory/vm": {}, "describe/plan": {}, "health": {}, "settings/get": {}, } roots := uniqueRootVerbs(commands) expected := []string{"describe", "get", "health", "settings"} if len(roots) != len(expected) { t.Fatalf("uniqueRootVerbs() = %v, want %v", roots, expected) } for i, v := range expected { if roots[i] != v { t.Errorf("uniqueRootVerbs()[%d] = %q, want %q", i, roots[i], v) } } } func TestDetectBareParents(t *testing.T) { commands := map[string]*Command{ // "patch" is a bare parent: no flags, prefix of patch/plan "patch": {Path: []string{"patch"}}, "patch/plan": { Path: []string{"patch", "plan"}, Flags: []Flag{{Name: "query", Type: "string"}}, }, "patch/mapping": { // Also a bare parent: prefix of patch/mapping/network, no flags Path: []string{"patch", "mapping"}, }, "patch/mapping/network": { Path: []string{"patch", "mapping", "network"}, }, // "delete/mapping" has flags, so NOT a bare parent even though it's a prefix "delete/mapping": { Path: []string{"delete", "mapping"}, Flags: []Flag{{Name: "all", Type: "bool"}}, }, "delete/mapping/network": { Path: []string{"delete", "mapping", "network"}, }, // "create/plan" is NOT a prefix of anything, so not bare "create/plan": { Path: []string{"create", "plan"}, }, } bareParents := detectBareParents(commands) if !bareParents["patch"] { t.Error("Expected 'patch' to be detected as bare parent") } if !bareParents["patch/mapping"] { t.Error("Expected 'patch/mapping' to be detected as bare parent") } if bareParents["delete/mapping"] { t.Error("'delete/mapping' has flags, should NOT be detected as bare parent") } if bareParents["create/plan"] { t.Error("'create/plan' is not a prefix of anything, should NOT be bare parent") } if bareParents["patch/plan"] { t.Error("'patch/plan' has flags, should NOT be bare parent") } } func TestDetectDeepSiblingGroups(t *testing.T) { commands := map[string]*Command{ "get/inventory/vm": { Name: "vm", Path: []string{"get", "inventory", "vm"}, Description: "Get VMs from provider", }, "get/inventory/network": { Name: "network", Path: []string{"get", "inventory", "network"}, Description: "Get networks from provider", }, "get/inventory/cluster": { Name: "cluster", Path: []string{"get", "inventory", "cluster"}, Description: "Get clusters from provider", }, "get/plan": { Name: "plan", Path: []string{"get", "plan"}, Description: "Get plans", }, } groups, groupedKeys := detectDeepSiblingGroups(commands, nil) if len(groups) != 1 { t.Fatalf("Expected 1 sibling group, got %d", len(groups)) } group := groups[0] if group.parentPath != "get/inventory" { t.Errorf("Expected parent path 'get/inventory', got %q", group.parentPath) } if len(group.children) != 3 { t.Errorf("Expected 3 children, got %d: %v", len(group.children), group.children) } for _, key := range []string{"get/inventory/vm", "get/inventory/network", "get/inventory/cluster"} { if !groupedKeys[key] { t.Errorf("Expected %q to be in grouped keys", key) } } if groupedKeys["get/plan"] { t.Error("get/plan should not be in a sibling group") } } func TestDetectDeepSiblingGroups_BelowThreshold(t *testing.T) { // Only 2 siblings — below the threshold of 3 commands := map[string]*Command{ "get/inventory/vm": {Name: "vm", Path: []string{"get", "inventory", "vm"}, Description: "VMs"}, "get/inventory/network": {Name: "network", Path: []string{"get", "inventory", "network"}, Description: "Networks"}, } groups, groupedKeys := detectDeepSiblingGroups(commands, nil) if len(groups) != 0 { t.Errorf("Expected 0 groups below threshold, got %d", len(groups)) } if len(groupedKeys) != 0 { t.Errorf("Expected no grouped keys below threshold, got %d", len(groupedKeys)) } } func TestDetectDeepSiblingGroups_TopLevelNotCompacted(t *testing.T) { // Top-level groups (depth 2) should NOT be compacted — they are heterogeneous commands := map[string]*Command{ "get/plan": {Name: "plan", Path: []string{"get", "plan"}, Description: "Get plans"}, "get/provider": {Name: "provider", Path: []string{"get", "provider"}, Description: "Get providers"}, "get/hook": {Name: "hook", Path: []string{"get", "hook"}, Description: "Get hooks"}, "get/host": {Name: "host", Path: []string{"get", "host"}, Description: "Get hosts"}, } groups, groupedKeys := detectDeepSiblingGroups(commands, nil) if len(groups) != 0 { t.Errorf("Top-level groups (depth 2) should not be compacted, got %d groups", len(groups)) } if len(groupedKeys) != 0 { t.Errorf("No keys should be grouped for top-level commands, got %d", len(groupedKeys)) } } func TestFormatGlobalFlags(t *testing.T) { registry := &Registry{ GlobalFlags: []Flag{ {Name: "namespace", Description: "Target Kubernetes namespace"}, {Name: "all-namespaces", Description: "Query all namespaces"}, {Name: "output", Description: "Output format"}, {Name: "kubeconfig", Description: "Path to kubeconfig"}, {Name: "verbose", Description: "Enable verbose output"}, }, } result := registry.formatGlobalFlags() // Should include the important global flags if !strings.Contains(result, "namespace: Target Kubernetes namespace") { t.Error("Should include namespace flag from data") } if !strings.Contains(result, "all_namespaces: Query all namespaces") { t.Error("Should include all_namespaces flag from data (hyphens converted to underscores for MCP JSON)") } if !strings.Contains(result, "verbose: Enable verbose output") { t.Error("Should include verbose flag from data") } // Should NOT include kubeconfig or output (not in importantGlobalFlags) if strings.Contains(result, "kubeconfig") { t.Error("Should NOT include kubeconfig flag (not LLM-relevant)") } } func TestFormatGlobalFlags_Empty(t *testing.T) { registry := &Registry{ GlobalFlags: []Flag{ {Name: "kubeconfig", Description: "Path to kubeconfig"}, }, } // No relevant flags → should return empty string result := registry.formatGlobalFlags() if result != "" { t.Errorf("Expected empty string when no relevant flags, got %q", result) } } func TestRegistry_RealHelpMachine_NoAdminCommands(t *testing.T) { registry := loadRealRegistry(t) // Admin commands should NOT be present in either map adminCommands := []string{ "completion/bash", "completion/fish", "completion/powershell", "completion/zsh", "help", "mcp-server", "version", } for _, cmd := range adminCommands { if registry.ReadOnly[cmd] != nil { t.Errorf("Admin command %q should not be in ReadOnly", cmd) } if registry.ReadWrite[cmd] != nil { t.Errorf("Admin command %q should not be in ReadWrite", cmd) } } } func TestRegistry_RealHelpMachine_MinimalReadOnlyGroupsInventory(t *testing.T) { registry := loadRealRegistry(t) result := registry.GenerateMinimalReadOnlyDescription() // Should have a compacted inventory line with "RESOURCE" if !strings.Contains(result, "get inventory RESOURCE") { t.Errorf("Minimal read-only description should compact inventory commands into 'get inventory RESOURCE', got:\n%s", result) } // Should list resource names if !strings.Contains(result, "vm") { t.Error("Compacted inventory should list 'vm' as a resource") } if !strings.Contains(result, "network") { t.Error("Compacted inventory should list 'network' as a resource") } // Should have examples section if !strings.Contains(result, "Examples:") { t.Error("Description should include examples section") } if !strings.Contains(result, "get inventory") { t.Error("Examples should include an inventory command") } if !strings.Contains(result, "query") { t.Error("Inventory example should include a query flag to demonstrate TSL filtering") } if !strings.Contains(result, "TSL") { t.Error("Description should include TSL syntax hint") } if !strings.Contains(result, "mtv_help") { t.Error("Description should reference mtv_help for detailed flags") } // Should NOT list individual inventory commands separately (they should be compacted) if strings.Contains(result, " get inventory vm -") { t.Error("Individual inventory commands should be compacted, not listed separately") } // Should list non-grouped commands like get plan if !strings.Contains(result, "get plan") { t.Error("Description should list non-grouped commands like 'get plan'") } // Should include short MTV context preamble if !strings.Contains(result, "Migration Toolkit for Virtualization") { t.Error("Minimal description should include MTV context preamble") } // Should NOT include orphaned convention notes (removed) if strings.Contains(result, "Args: <required>, [optional]") { t.Error("Minimal description should NOT include the orphaned args convention note") } } func TestRegistry_RealHelpMachine_MinimalReadWriteNoBareParents(t *testing.T) { registry := loadRealRegistry(t) result := registry.GenerateMinimalReadWriteDescription() // Real write commands should be present if !strings.Contains(result, "create plan") { t.Error("Minimal write description should contain 'create plan'") } if !strings.Contains(result, "patch plan") { t.Error("Minimal write description should contain 'patch plan'") } // Should have examples derived from source if !strings.Contains(result, "Examples:") { t.Error("Minimal write description should contain examples section") } // Should include KARL hint if !strings.Contains(result, "KARL") { t.Error("Minimal write description should include KARL hint") } // Should include mtv_help reference if !strings.Contains(result, "mtv_help") { t.Error("Minimal write description should reference mtv_help") } // Should NOT include LongDescription (removed to save space) if strings.Contains(result, "Migration Toolkit for Virtualization") { t.Error("Minimal description should NOT include LongDescription domain context") } // Bare parent "patch" (if it exists as a structural node) should be excluded. // We check by ensuring "patch -" does not appear as a standalone command line. for _, line := range strings.Split(result, "\n") { trimmed := strings.TrimSpace(line) if trimmed == "patch - Patch mappings" || trimmed == "patch -" { t.Errorf("Bare parent 'patch' should not appear as standalone command: %q", line) } } } func TestRegistry_RealHelpMachine_CreateProviderFlags(t *testing.T) { registry := loadRealRegistry(t) cmd := registry.ReadWrite["create/provider"] if cmd == nil { t.Fatal("create/provider command not found in registry") } // Should have a reasonable number of flags if len(cmd.Flags) < 10 { t.Errorf("create provider should have at least 10 flags, got %d", len(cmd.Flags)) } // --type should be required with enum values var typeFlag *Flag for i := range cmd.Flags { if cmd.Flags[i].Name == "type" { typeFlag = &cmd.Flags[i] break } } if typeFlag == nil { t.Fatal("create provider should have a --type flag") } if !typeFlag.Required { t.Error("--type flag should be marked as required") } if len(typeFlag.Enum) == 0 { t.Error("--type flag should have enum values") } // --provider-insecure-skip-tls should exist found := false for _, f := range cmd.Flags { if f.Name == "provider-insecure-skip-tls" { found = true break } } if !found { t.Error("create provider should have --provider-insecure-skip-tls flag") } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/discovery/types.go
Go
// Package discovery provides dynamic command discovery from kubectl-mtv help output. package discovery import "strings" // HelpSchema matches kubectl-mtv help --machine output type HelpSchema struct { Version string `json:"version"` CLIVersion string `json:"cli_version"` Name string `json:"name"` Description string `json:"description"` LongDescription string `json:"long_description,omitempty"` Commands []Command `json:"commands"` GlobalFlags []Flag `json:"global_flags"` } // Command represents a kubectl-mtv command discovered from help --machine output. type Command struct { // Name is the command name (e.g., "plan", "provider") Name string `json:"name"` // Path is the complete command path as array (e.g., ["get", "inventory", "vm"]) Path []string `json:"path"` // PathString is the full command path as space-separated string PathString string `json:"path_string"` // Description is the command's short description Description string `json:"description"` // LongDescription is the extended description with details LongDescription string `json:"long_description,omitempty"` // Usage is the usage pattern (e.g., "kubectl-mtv get inventory vm [flags]") Usage string `json:"usage"` // Aliases are alternative names for the command Aliases []string `json:"aliases,omitempty"` // Category is one of: "read", "write", "admin" Category string `json:"category"` // Flags are the command-specific flags Flags []Flag `json:"flags"` // Examples are usage examples from the CLI help Examples []Example `json:"examples,omitempty"` // Runnable indicates whether the command can be executed directly. // Non-runnable commands are structural parents (e.g., "get inventory") // included for their description metadata. Runnable bool `json:"runnable"` } // Example represents a usage example from CLI help. type Example struct { // Description explains what the example does Description string `json:"description"` // Command is the example command Command string `json:"command"` } // Flag represents a command-line flag discovered from help --machine output. type Flag struct { // Name is the long flag name without dashes (e.g., "output") Name string `json:"name"` // Shorthand is the single-character shorthand without dash (e.g., "o") Shorthand string `json:"shorthand,omitempty"` // Type is the flag type: "bool", "string", "int", "stringArray", "duration" Type string `json:"type"` // Default is the default value if specified Default any `json:"default,omitempty"` // Description is the flag's help text Description string `json:"description"` // Required indicates if the flag is required Required bool `json:"required"` // Enum contains allowed values for string flags Enum []string `json:"enum,omitempty"` // Hidden indicates if the flag is hidden from normal help Hidden bool `json:"hidden,omitempty"` } // CommandPath returns the full command path as a string (e.g., "get inventory vm") func (c *Command) CommandPath() string { if c.PathString != "" { return c.PathString } return strings.Join(c.Path, " ") } // PathKey returns a key suitable for map lookups (e.g., "get/inventory/vm") func (c *Command) PathKey() string { return strings.Join(c.Path, "/") }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/coerce.go
Go
package tools import ( "context" "encoding/json" "fmt" "reflect" "strings" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // extractKubeCredsFromRequest extracts Kubernetes credentials from the request's // Extra.Header field and adds them to the context. The wrapper in mcpserver.go // ensures that Extra.Header is populated for SSE mode. func extractKubeCredsFromRequest(ctx context.Context, req *mcp.CallToolRequest) context.Context { if req.Extra != nil && req.Extra.Header != nil { return util.WithKubeCredsFromHeaders(ctx, req.Extra.Header) } return ctx } // AddToolWithCoercion registers a tool with the server using the low-level // s.AddTool API, adding a boolean coercion layer that converts string boolean // values ("true", "True", "TRUE", "false", "False", "FALSE") to actual JSON // booleans before unmarshaling into the typed input struct. // // This is needed because some AI models send boolean parameters as strings // (e.g., Python-style "True" instead of JSON true), which the MCP SDK's // strict schema validation rejects. // // The function: // 1. Generates the input schema from the In type using jsonschema.For[In] // 2. Creates a raw ToolHandler that coerces string booleans before unmarshal // 3. Registers via s.AddTool (bypassing the SDK's strict validation) func AddToolWithCoercion[In, Out any](s *mcp.Server, t *mcp.Tool, h mcp.ToolHandlerFor[In, Out]) { // Generate input schema from the In type if not already set if t.InputSchema == nil { schema, err := jsonschema.For[In](nil) if err != nil { panic(fmt.Sprintf("AddToolWithCoercion: tool %q: failed to generate input schema: %v", t.Name, err)) } t.InputSchema = schema } rawHandler := func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) { var input json.RawMessage if req.Params.Arguments != nil { input = req.Params.Arguments } // Coerce string booleans to actual booleans based on the In struct's bool fields input = CoerceBooleans[In](input) // Unmarshal into typed input var in In if input != nil { if err := json.Unmarshal(input, &in); err != nil { return nil, fmt.Errorf("invalid params: %v", err) } } // Call the typed handler res, out, err := h(ctx, req, in) // Handle errors: wrap as tool errors (IsError=true), not protocol errors. // This matches the SDK's ToolHandlerFor behavior (server.go lines 283-291). if err != nil { var errRes mcp.CallToolResult errRes.Content = []mcp.Content{&mcp.TextContent{Text: err.Error()}} errRes.IsError = true return &errRes, nil } if res == nil { res = &mcp.CallToolResult{} } // Marshal the output and populate StructuredContent + Content. // This replicates the SDK's output serialization (server.go lines 298-332). var outval any = out if outval != nil { outBytes, err := json.Marshal(outval) if err != nil { return nil, fmt.Errorf("marshaling output: %w", err) } outJSON := json.RawMessage(outBytes) res.StructuredContent = outJSON if res.Content == nil { res.Content = []mcp.Content{&mcp.TextContent{ Text: string(outJSON), }} } } return res, nil } s.AddTool(t, rawHandler) } // CoerceBooleans examines the In type's struct fields via reflection, finds // all bool fields, and coerces any corresponding string values in the JSON // data to actual JSON booleans. This allows clients that send "True"/"true" // as strings to work correctly. // // If the data is not valid JSON or the In type is not a struct, the original // data is returned unchanged. func CoerceBooleans[In any](data json.RawMessage) json.RawMessage { if len(data) == 0 { return data } var m map[string]any if err := json.Unmarshal(data, &m); err != nil { return data } rt := reflect.TypeFor[In]() // Follow pointers to the underlying type for rt.Kind() == reflect.Pointer { rt = rt.Elem() } if rt.Kind() != reflect.Struct { return data } changed := false for i := 0; i < rt.NumField(); i++ { field := rt.Field(i) if field.Type.Kind() != reflect.Bool { continue } // Extract the JSON key from the struct tag jsonTag := field.Tag.Get("json") if jsonTag == "" || jsonTag == "-" { continue } jsonKey := strings.Split(jsonTag, ",")[0] if jsonKey == "" { continue } // Check if the value is a string that should be coerced to bool if v, ok := m[jsonKey]; ok { if s, ok := v.(string); ok { switch strings.ToLower(s) { case "true": m[jsonKey] = true changed = true case "false": m[jsonKey] = false changed = true } } } } if !changed { return data } result, err := json.Marshal(m) if err != nil { return data } return result }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/coerce_test.go
Go
package tools import ( "context" "encoding/json" "testing" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // --- CoerceBooleans tests --- // testInput is a struct used for testing CoerceBooleans. type testInput struct { Command string `json:"command" jsonschema:"test command"` AllNamespaces bool `json:"all_namespaces,omitempty" jsonschema:"Query all namespaces"` DryRun bool `json:"dry_run,omitempty" jsonschema:"Dry run mode"` Previous bool `json:"previous,omitempty" jsonschema:"Previous container"` Name string `json:"name,omitempty" jsonschema:"Resource name"` Flags map[string]any `json:"flags,omitempty" jsonschema:"Additional flags"` } func TestCoerceBooleans_ProperBooleans(t *testing.T) { // Proper JSON booleans should pass through unchanged data := json.RawMessage(`{"command":"get plan","all_namespaces":true,"dry_run":false}`) result := CoerceBooleans[testInput](data) var m map[string]any if err := json.Unmarshal(result, &m); err != nil { t.Fatalf("Failed to unmarshal result: %v", err) } if m["all_namespaces"] != true { t.Errorf("all_namespaces = %v, want true", m["all_namespaces"]) } if m["dry_run"] != false { t.Errorf("dry_run = %v, want false", m["dry_run"]) } } func TestCoerceBooleans_StringTrue(t *testing.T) { tests := []struct { name string value string }{ {"lowercase true", `"true"`}, {"capitalized True", `"True"`}, {"uppercase TRUE", `"TRUE"`}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { data := json.RawMessage(`{"command":"get plan","all_namespaces":` + tt.value + `}`) result := CoerceBooleans[testInput](data) var m map[string]any if err := json.Unmarshal(result, &m); err != nil { t.Fatalf("Failed to unmarshal result: %v", err) } if m["all_namespaces"] != true { t.Errorf("all_namespaces = %v (%T), want true (bool)", m["all_namespaces"], m["all_namespaces"]) } }) } } func TestCoerceBooleans_StringFalse(t *testing.T) { tests := []struct { name string value string }{ {"lowercase false", `"false"`}, {"capitalized False", `"False"`}, {"uppercase FALSE", `"FALSE"`}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { data := json.RawMessage(`{"command":"get plan","dry_run":` + tt.value + `}`) result := CoerceBooleans[testInput](data) var m map[string]any if err := json.Unmarshal(result, &m); err != nil { t.Fatalf("Failed to unmarshal result: %v", err) } if m["dry_run"] != false { t.Errorf("dry_run = %v (%T), want false (bool)", m["dry_run"], m["dry_run"]) } }) } } func TestCoerceBooleans_MixedCorrectAndString(t *testing.T) { // Mix of proper booleans and string booleans data := json.RawMessage(`{"command":"get plan","all_namespaces":true,"dry_run":"True","previous":"false"}`) result := CoerceBooleans[testInput](data) var m map[string]any if err := json.Unmarshal(result, &m); err != nil { t.Fatalf("Failed to unmarshal result: %v", err) } if m["all_namespaces"] != true { t.Errorf("all_namespaces = %v, want true", m["all_namespaces"]) } if m["dry_run"] != true { t.Errorf("dry_run = %v, want true (coerced from \"True\")", m["dry_run"]) } if m["previous"] != false { t.Errorf("previous = %v, want false (coerced from \"false\")", m["previous"]) } } func TestCoerceBooleans_NoBooleanFields(t *testing.T) { // Struct with no boolean fields should return data unchanged type noBools struct { Name string `json:"name"` } data := json.RawMessage(`{"name":"test"}`) result := CoerceBooleans[noBools](data) if string(result) != string(data) { t.Errorf("CoerceBooleans changed data when no bool fields exist: got %s, want %s", result, data) } } func TestCoerceBooleans_NonBoolStringNotCoerced(t *testing.T) { // String values that aren't "true"/"false" should not be coerced data := json.RawMessage(`{"command":"get plan","all_namespaces":"yes","name":"test"}`) result := CoerceBooleans[testInput](data) var m map[string]any if err := json.Unmarshal(result, &m); err != nil { t.Fatalf("Failed to unmarshal result: %v", err) } // "yes" is not a recognized boolean string, so it should remain a string if _, ok := m["all_namespaces"].(string); !ok { t.Errorf("all_namespaces should remain a string for unrecognized value 'yes', got %T", m["all_namespaces"]) } } func TestCoerceBooleans_EmptyData(t *testing.T) { result := CoerceBooleans[testInput](nil) if result != nil { t.Errorf("Expected nil for nil input, got %s", result) } result = CoerceBooleans[testInput](json.RawMessage{}) if len(result) != 0 { t.Errorf("Expected empty for empty input, got %s", result) } } func TestCoerceBooleans_MalformedJSON(t *testing.T) { data := json.RawMessage(`{invalid json}`) result := CoerceBooleans[testInput](data) // Malformed JSON should be returned unchanged if string(result) != string(data) { t.Errorf("CoerceBooleans changed malformed JSON: got %s, want %s", result, data) } } func TestCoerceBooleans_NonStructField(t *testing.T) { // String fields should not be affected even if their values look like booleans data := json.RawMessage(`{"command":"true","name":"false"}`) result := CoerceBooleans[testInput](data) var m map[string]any if err := json.Unmarshal(result, &m); err != nil { t.Fatalf("Failed to unmarshal result: %v", err) } if m["command"] != "true" { t.Errorf("command = %v, should remain string \"true\"", m["command"]) } if m["name"] != "false" { t.Errorf("name = %v, should remain string \"false\"", m["name"]) } } func TestCoerceBooleans_UnmarshalAfterCoerce(t *testing.T) { // Verify that coerced data can be successfully unmarshaled into the typed struct data := json.RawMessage(`{"command":"get plan","all_namespaces":"True","dry_run":"false"}`) result := CoerceBooleans[testInput](data) var input testInput if err := json.Unmarshal(result, &input); err != nil { t.Fatalf("Failed to unmarshal coerced data into struct: %v", err) } if input.Command != "get plan" { t.Errorf("Command = %q, want %q", input.Command, "get plan") } if !input.AllNamespaces { t.Error("AllNamespaces should be true after coercion from \"True\"") } if input.DryRun { t.Error("DryRun should be false after coercion from \"false\"") } } // --- CoerceBooleans with real tool input types --- func TestCoerceBooleans_MTVReadInput(t *testing.T) { data := json.RawMessage(`{"command":"get plan","dry_run":"FALSE"}`) result := CoerceBooleans[MTVReadInput](data) var input MTVReadInput if err := json.Unmarshal(result, &input); err != nil { t.Fatalf("Failed to unmarshal: %v", err) } if input.DryRun { t.Error("DryRun should be false") } } func TestCoerceBooleans_MTVWriteInput(t *testing.T) { data := json.RawMessage(`{"command":"create plan","dry_run":"True"}`) result := CoerceBooleans[MTVWriteInput](data) var input MTVWriteInput if err := json.Unmarshal(result, &input); err != nil { t.Fatalf("Failed to unmarshal: %v", err) } if !input.DryRun { t.Error("DryRun should be true") } } func TestCoerceBooleans_KubectlLogsInput(t *testing.T) { // KubectlLogsInput has flags and dry_run at top level. // Boolean params like previous etc. are inside the flags map. data := json.RawMessage(`{"dry_run":"True"}`) result := CoerceBooleans[KubectlLogsInput](data) var input KubectlLogsInput if err := json.Unmarshal(result, &input); err != nil { t.Fatalf("Failed to unmarshal: %v", err) } if !input.DryRun { t.Error("DryRun should be true") } } func TestCoerceBooleans_KubectlInput(t *testing.T) { // KubectlInput has action, flags, and dry_run at top level. data := json.RawMessage(`{"action":"get","dry_run":"True"}`) result := CoerceBooleans[KubectlInput](data) var input KubectlInput if err := json.Unmarshal(result, &input); err != nil { t.Fatalf("Failed to unmarshal: %v", err) } if !input.DryRun { t.Error("DryRun should be true") } } // --- parseBoolValue tests --- func TestParseBoolValue(t *testing.T) { tests := []struct { name string value any expected bool }{ {"bool true", true, true}, {"bool false", false, false}, {"string true lowercase", "true", true}, {"string True capitalized", "True", true}, {"string TRUE uppercase", "TRUE", true}, {"string false lowercase", "false", false}, {"string False capitalized", "False", false}, {"string FALSE uppercase", "FALSE", false}, {"string 1", "1", true}, {"string 0", "0", false}, {"string other", "yes", false}, {"string empty", "", false}, {"float64 1", float64(1), true}, {"float64 0", float64(0), false}, {"float64 nonzero", float64(42), true}, {"nil", nil, false}, {"int (unexpected type)", 1, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := parseBoolValue(tt.value) if result != tt.expected { t.Errorf("parseBoolValue(%v) = %v, want %v", tt.value, result, tt.expected) } }) } } // --- AddToolWithCoercion tests --- // testToolInput is a simple input struct for testing AddToolWithCoercion. type testToolInput struct { Name string `json:"name" jsonschema:"Resource name"` Verbose bool `json:"verbose,omitempty" jsonschema:"Enable verbose output"` } func TestAddToolWithCoercion_SchemaSet(t *testing.T) { server := mcp.NewServer(&mcp.Implementation{ Name: "test", Version: "1.0", }, nil) handler := func(_ context.Context, _ *mcp.CallToolRequest, _ testToolInput) (*mcp.CallToolResult, any, error) { return nil, map[string]any{"status": "ok"}, nil } tool := &mcp.Tool{ Name: "test_tool", Description: "A test tool", OutputSchema: map[string]any{ "type": "object", "properties": map[string]any{}, }, } // Register with coercion wrapper AddToolWithCoercion(server, tool, handler) // Verify that the tool's InputSchema was set if tool.InputSchema == nil { t.Fatal("Tool InputSchema should be set after AddToolWithCoercion") } } func TestAddToolWithCoercion_EndToEnd(t *testing.T) { // Verify the full coercion path: string booleans are coerced before // reaching the handler, so the handler receives proper bool values. // This tests the same CoerceBooleans + unmarshal + handler call that // AddToolWithCoercion's raw handler performs internally. var receivedVerbose bool var receivedName string handler := func(_ context.Context, _ *mcp.CallToolRequest, input testToolInput) (*mcp.CallToolResult, any, error) { receivedVerbose = input.Verbose receivedName = input.Name return nil, map[string]any{"name": input.Name, "verbose": input.Verbose}, nil } // Simulate a tool call with string boolean "True" (what a broken model sends) rawArgs := json.RawMessage(`{"name":"test","verbose":"True"}`) // This is the same code path that AddToolWithCoercion's wrapper executes: // 1. Coerce string booleans coerced := CoerceBooleans[testToolInput](rawArgs) // 2. Unmarshal into typed input var input testToolInput if err := json.Unmarshal(coerced, &input); err != nil { t.Fatalf("Failed to unmarshal coerced data: %v", err) } // 3. Call handler with the coerced input ctx := context.Background() _, _, err := handler(ctx, nil, input) if err != nil { t.Fatalf("Handler returned error: %v", err) } if !receivedVerbose { t.Error("Handler should have received Verbose=true after coercion from \"True\"") } if receivedName != "test" { t.Errorf("Handler received Name=%q, want %q", receivedName, "test") } } // --- buildArgs flags extraction tests --- func TestBuildArgs_FlagsAllNamespaces(t *testing.T) { tests := []struct { name string flags map[string]any wantA bool // whether -A should be in the result }{ { name: "flags all_namespaces bool true", flags: map[string]any{"all_namespaces": true}, wantA: true, }, { name: "flags all_namespaces string True", flags: map[string]any{"all_namespaces": "True"}, wantA: true, }, { name: "flags all_namespaces string true", flags: map[string]any{"all_namespaces": "true"}, wantA: true, }, { name: "flags A bool true", flags: map[string]any{"A": true}, wantA: true, }, { name: "flags A string true", flags: map[string]any{"A": "true"}, wantA: true, }, { name: "flags all_namespaces false", flags: map[string]any{"all_namespaces": false}, wantA: false, }, { name: "flags all_namespaces string false", flags: map[string]any{"all_namespaces": "false"}, wantA: false, }, { name: "no flags", flags: nil, wantA: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Use text format to avoid --output json in the result (simplifies assertions) origFormat := util.GetOutputFormat() util.SetOutputFormat("text") defer util.SetOutputFormat(origFormat) result := buildArgs("get/plan", tt.flags) // Use exact element match to avoid false positives from substrings hasA := false for _, arg := range result { if arg == "--all-namespaces" { hasA = true break } } if hasA != tt.wantA { t.Errorf("buildArgs() = %v, contains --all-namespaces = %v, want %v", result, hasA, tt.wantA) } }) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/kubectl.go
Go
package tools import ( "context" "encoding/json" "fmt" "regexp" "strconv" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // KubectlLogsInput represents the input for the kubectl_logs tool. // All parameters are passed via flags, consistent with mtv_read/mtv_write tools. type KubectlLogsInput struct { Flags map[string]any `json:"flags,omitempty" jsonschema:"All parameters as key-value pairs (e.g. name: \"deployments/forklift-controller\", namespace: \"openshift-mtv\", filter_plan: \"my-plan\")"` DryRun bool `json:"dry_run,omitempty" jsonschema:"If true, does not execute. Returns the equivalent CLI command in the output field instead"` } // KubectlInput represents the input for the kubectl tool (get, describe, events). // All parameters (except action and dry_run) are passed via flags. type KubectlInput struct { Action string `json:"action" jsonschema:"get | describe | events"` Flags map[string]any `json:"flags,omitempty" jsonschema:"All parameters as key-value pairs (e.g. resource_type: \"pods\", namespace: \"openshift-mtv\", labels: \"plan=my-plan\")"` DryRun bool `json:"dry_run,omitempty" jsonschema:"If true, does not execute. Returns the equivalent CLI command in the output field instead"` } // kubectlDebugParams holds the resolved parameters for kubectl debug operations. // This internal struct is populated from the Flags map. type kubectlDebugParams struct { Name string ResourceType string Namespace string AllNamespaces bool Labels string Container string Previous bool TailLines int Since string Output string FieldSelector string SortBy string ForResource string Grep string IgnoreCase bool NoTimestamps bool LogFormat string FilterPlan string FilterProvider string FilterVM string FilterMigration string FilterLevel string FilterLogger string } // resolveDebugParams extracts all parameters from the flags map into a typed struct. func resolveDebugParams(flags map[string]any) kubectlDebugParams { p := kubectlDebugParams{} if flags == nil { return p } p.Name = flagStr(flags, "name") p.ResourceType = flagStr(flags, "resource_type") p.Namespace = flagStr(flags, "namespace") p.AllNamespaces = flagBool(flags, "all_namespaces") p.Labels = flagStr(flags, "labels") p.Container = flagStr(flags, "container") p.Previous = flagBool(flags, "previous") p.TailLines = flagInt(flags, "tail_lines") p.Since = flagStr(flags, "since") p.Output = flagStr(flags, "output") p.FieldSelector = flagStr(flags, "field_selector") p.SortBy = flagStr(flags, "sort_by") p.ForResource = flagStr(flags, "for_resource") p.Grep = flagStr(flags, "grep") p.IgnoreCase = flagBool(flags, "ignore_case") p.NoTimestamps = flagBool(flags, "no_timestamps") p.LogFormat = flagStr(flags, "log_format") p.FilterPlan = flagStr(flags, "filter_plan") p.FilterProvider = flagStr(flags, "filter_provider") p.FilterVM = flagStr(flags, "filter_vm") p.FilterMigration = flagStr(flags, "filter_migration") p.FilterLevel = flagStr(flags, "filter_level") p.FilterLogger = flagStr(flags, "filter_logger") return p } // flagStr extracts a string from the flags map. func flagStr(flags map[string]any, key string) string { if v, ok := flags[key]; ok { return fmt.Sprintf("%v", v) } return "" } // flagBool extracts a boolean from the flags map. func flagBool(flags map[string]any, key string) bool { if v, ok := flags[key]; ok { return parseBoolValue(v) } return false } // flagInt extracts an integer from the flags map. func flagInt(flags map[string]any, key string) int { if v, ok := flags[key]; ok { switch n := v.(type) { case float64: return int(n) case int: return n case string: if i, err := strconv.Atoi(n); err == nil { return i } } } return 0 } // GetMinimalKubectlLogsTool returns the minimal tool definition for kubectl log retrieval. // This tool is focused on forklift-controller logs with JSON parsing and filtering. func GetMinimalKubectlLogsTool() *mcp.Tool { return &mcp.Tool{ Name: "kubectl_logs", Description: `Get logs from any Kubernetes pod or deployment, with extra structured JSON filters for forklift-controller logs. Use this for debugging migration execution: filter by plan, VM, or error level. All parameters go in flags. Required: name (resource-type/name format, e.g. "deployments/forklift-controller" or "pod/my-pod") Default: last 500 lines. Set tail_lines: -1 for all logs. Common flags: namespace, container, previous, tail_lines, since, grep, ignore_case. Log format: log_format (json|text|pretty), no_timestamps. JSON filters (forklift-controller only): filter_plan, filter_provider, filter_vm, filter_migration, filter_level (info|debug|error|warn), filter_logger (plan|provider|migration|networkMap|storageMap). Examples: {flags: {name: "deployments/forklift-controller", namespace: "openshift-mtv"}} {flags: {name: "deployments/forklift-controller", namespace: "openshift-mtv", filter_plan: "my-plan", filter_level: "error"}} {flags: {name: "pod/virt-v2v-cold-xyz", namespace: "target-ns", tail_lines: 100}}`, OutputSchema: mtvOutputSchema, } } // GetMinimalKubectlTool returns the minimal tool definition for kubectl resource inspection. // This tool handles get, describe, and events actions for Kubernetes resources. func GetMinimalKubectlTool() *mcp.Tool { return &mcp.Tool{ Name: "kubectl", Description: `Inspect standard Kubernetes resources (pods, PVCs, services, deployments, events). Use ONLY for standard K8s objects. All MTV/Forklift custom resources (plans, providers, mappings, hooks, hosts) go through mtv_read and mtv_write. For MTV source-provider inventory (VMs, datastores, networks from vSphere/oVirt/OpenStack), use mtv_read "get inventory" commands. Actions: get, describe, events. All parameters (except action) go in flags. Flag names use underscores (e.g. resource_type, all_namespaces, for_resource). get/describe: resource_type (required), name, labels, output. events: for_resource, field_selector, sort_by. Common: namespace, all_namespaces. Examples: {action: "get", flags: {resource_type: "pods", namespace: "openshift-mtv", labels: "plan=my-plan"}} {action: "describe", flags: {resource_type: "pvc", name: "my-pvc", namespace: "target-ns"}} {action: "events", flags: {for_resource: "pod/virt-v2v-xxx", namespace: "target-ns"}}`, OutputSchema: mtvOutputSchema, } } // HandleKubectlLogs handles the kubectl_logs tool invocation. func HandleKubectlLogs(ctx context.Context, req *mcp.CallToolRequest, input KubectlLogsInput) (*mcp.CallToolResult, any, error) { // Extract K8s credentials from HTTP headers (populated by wrapper in SSE mode) ctx = extractKubeCredsFromRequest(ctx, req) // Enable dry run mode if requested if input.DryRun { ctx = util.WithDryRun(ctx, true) } // Resolve all parameters from the flags map p := resolveDebugParams(input.Flags) if p.Name == "" { return nil, nil, fmt.Errorf("'name' is required in flags (e.g. flags: {name: \"deployments/forklift-controller\"})") } args := buildLogsArgs(p) // Execute kubectl command result, err := util.RunKubectlCommand(ctx, args) if err != nil { return nil, nil, fmt.Errorf("kubectl command failed: %w", err) } // Parse and return result data, err := util.UnmarshalJSONResponse(result) if err != nil { return nil, nil, err } // Check for CLI errors and surface as MCP IsError response if errResult := buildCLIErrorResult(data); errResult != nil { return errResult, nil, nil } // Process logs with filtering and formatting if output, ok := data["output"].(string); ok { processLogsOutput(data, output, p) } return nil, data, nil } // HandleKubectl handles the kubectl tool invocation (get, describe, events). func HandleKubectl(ctx context.Context, req *mcp.CallToolRequest, input KubectlInput) (*mcp.CallToolResult, any, error) { // Extract K8s credentials from HTTP headers (populated by wrapper in SSE mode) ctx = extractKubeCredsFromRequest(ctx, req) // Enable dry run mode if requested if input.DryRun { ctx = util.WithDryRun(ctx, true) } // Resolve all parameters from the flags map p := resolveDebugParams(input.Flags) var args []string switch input.Action { case "get": if p.ResourceType == "" { return nil, nil, fmt.Errorf("get action requires 'resource_type' in flags (e.g. flags: {resource_type: \"pods\"})") } args = buildGetArgs(p) case "describe": if p.ResourceType == "" { return nil, nil, fmt.Errorf("describe action requires 'resource_type' in flags (e.g. flags: {resource_type: \"pods\"})") } args = buildDescribeArgs(p) case "events": args = buildEventsArgs(p) default: return nil, nil, fmt.Errorf("unknown action '%s'. Valid actions: get, describe, events", input.Action) } // Execute kubectl command result, err := util.RunKubectlCommand(ctx, args) if err != nil { return nil, nil, fmt.Errorf("kubectl command failed: %w", err) } // Parse and return result data, err := util.UnmarshalJSONResponse(result) if err != nil { return nil, nil, err } // Check for CLI errors and surface as MCP IsError response if errResult := buildCLIErrorResult(data); errResult != nil { return errResult, nil, nil } return nil, data, nil } // processLogsOutput applies grep, JSON detection, filtering, and formatting to log output. // It modifies the data map in place with the processed results. func processLogsOutput(data map[string]interface{}, output string, p kubectlDebugParams) { // Apply grep filter first (regex pattern matching) if p.Grep != "" { filtered, err := filterLogsByPattern(output, p.Grep, p.IgnoreCase) if err != nil { data["warning"] = fmt.Sprintf("grep filter error: %v", err) data["output"] = output return } output = filtered } // Check if logs appear to be JSON formatted by inspecting the first line isJSONLogs := looksLikeJSONLogs(output) hasFilters := hasJSONParamFilters(p) // Warn if JSON filters are requested but logs don't appear to be JSON if hasFilters && !isJSONLogs { data["warning"] = "JSON filters were specified but logs do not appear to be in JSON format. Filters will be ignored." } if isJSONLogs { // Normalize LogFormat to a valid value before processing // Valid formats: "json", "text", "pretty" format := p.LogFormat switch format { case "json", "text", "pretty": // Valid format, use as-is case "": format = "json" default: // Invalid format specified, default to "json" and warn data["warning"] = fmt.Sprintf("Invalid log_format '%s' specified, defaulting to 'json'. Valid formats: json, text, pretty", format) format = "json" } // Apply JSON filtering and formatting for JSON-formatted logs normalizedParams := p normalizedParams.LogFormat = format formatted, err := filterAndFormatJSONLogs(output, normalizedParams) if err != nil { data["warning"] = fmt.Sprintf("JSON log processing error: %v", err) data["output"] = output return } // Set the appropriate output field based on format if format == "json" { // For JSON format, put parsed entries in "logs" field delete(data, "output") data["logs"] = formatted } else { // For text/pretty formats, keep as "output" string if str, ok := formatted.(string); ok { data["output"] = str } else { jsonBytes, _ := json.Marshal(formatted) data["output"] = string(jsonBytes) } } } else { // Non-JSON logs: return as raw text, skip JSON parsing entirely data["output"] = output } } // buildLogsArgs builds arguments for kubectl logs command. func buildLogsArgs(p kubectlDebugParams) []string { args := []string{"logs"} if p.Name != "" { args = append(args, p.Name) } if p.Namespace != "" { args = append(args, "-n", p.Namespace) } if p.Container != "" { args = append(args, "-c", p.Container) } if p.Previous { args = append(args, "--previous") } // Tail lines - default to 500 if not specified; -1 gets all logs if p.TailLines == 0 { args = append(args, "--tail", "500") } else if p.TailLines > 0 { args = append(args, "--tail", strconv.Itoa(p.TailLines)) } if p.Since != "" { args = append(args, "--since", p.Since) } // Timestamps enabled by default; use no_timestamps=true to disable if !p.NoTimestamps { args = append(args, "--timestamps") } return args } // buildGetArgs builds arguments for kubectl get command. func buildGetArgs(p kubectlDebugParams) []string { args := []string{"get"} if p.ResourceType != "" { args = append(args, p.ResourceType) } if p.Name != "" { args = append(args, p.Name) } if p.AllNamespaces { args = append(args, "-A") } else if p.Namespace != "" { args = append(args, "-n", p.Namespace) } if p.Labels != "" { args = append(args, "-l", p.Labels) } output := p.Output if output == "" { output = util.GetOutputFormat() } if output != "text" { args = append(args, "-o", output) } return args } // buildDescribeArgs builds arguments for kubectl describe command. func buildDescribeArgs(p kubectlDebugParams) []string { args := []string{"describe"} if p.ResourceType != "" { args = append(args, p.ResourceType) } if p.Name != "" { args = append(args, p.Name) } if p.AllNamespaces { args = append(args, "-A") } else if p.Namespace != "" { args = append(args, "-n", p.Namespace) } if p.Labels != "" { args = append(args, "-l", p.Labels) } return args } // buildEventsArgs builds arguments for kubectl get events command with specialized filtering. func buildEventsArgs(p kubectlDebugParams) []string { args := []string{"get", "events"} if p.AllNamespaces { args = append(args, "-A") } else if p.Namespace != "" { args = append(args, "-n", p.Namespace) } if p.ForResource != "" { args = append(args, "--for", p.ForResource) } if p.FieldSelector != "" { args = append(args, "--field-selector", p.FieldSelector) } if p.SortBy != "" { args = append(args, "--sort-by", p.SortBy) } output := p.Output if output == "" { output = util.GetOutputFormat() } if output != "text" { args = append(args, "-o", output) } return args } // filterLogsByPattern filters log lines by a regex pattern. // If pattern is empty, returns the original logs unchanged. // If ignoreCase is true, the pattern matching is case-insensitive. func filterLogsByPattern(logs string, pattern string, ignoreCase bool) (string, error) { if pattern == "" { return logs, nil } flags := "" if ignoreCase { flags = "(?i)" } re, err := regexp.Compile(flags + pattern) if err != nil { return "", fmt.Errorf("invalid grep pattern: %w", err) } var filtered []string lines := strings.Split(logs, "\n") for _, line := range lines { if re.MatchString(line) { filtered = append(filtered, line) } } return strings.Join(filtered, "\n"), nil } // JSONLogEntry represents a structured log entry from forklift controller. // The forklift controller outputs JSON logs with fields like: // {"level":"info","ts":"2026-02-05 10:45:52","logger":"plan|zw4bt","msg":"Reconcile started.","plan":{"name":"my-plan","namespace":"demo"}} type JSONLogEntry struct { Level string `json:"level"` Ts string `json:"ts"` Logger string `json:"logger"` Msg string `json:"msg"` Plan map[string]string `json:"plan,omitempty"` Provider map[string]string `json:"provider,omitempty"` Map map[string]string `json:"map,omitempty"` Migration map[string]string `json:"migration,omitempty"` VM string `json:"vm,omitempty"` VMName string `json:"vmName,omitempty"` VMID string `json:"vmID,omitempty"` ReQ int `json:"reQ,omitempty"` } // RawLogLine represents a log line that could not be parsed as JSON. // Used to preserve malformed or non-JSON log lines in the output. type RawLogLine struct { Raw string `json:"raw"` } // hasJSONParamFilters returns true if any JSON-specific filters are set. func hasJSONParamFilters(p kubectlDebugParams) bool { return p.FilterPlan != "" || p.FilterProvider != "" || p.FilterVM != "" || p.FilterMigration != "" || p.FilterLevel != "" || p.FilterLogger != "" } // looksLikeJSONLogs checks if the logs appear to be in JSON format by examining up to 5 non-empty lines. // It handles the kubectl --timestamps prefix (e.g., "2026-02-05T10:45:52.123Z {\"level\":...}") // Returns true as soon as any scanned line contains valid JSON with expected log fields (level, msg). // Returns false if none of the scanned lines yield a valid JSON entry. func looksLikeJSONLogs(logs string) bool { lines := strings.Split(logs, "\n") // Check up to 5 non-empty lines for JSON format const maxLinesToCheck = 5 checkedLines := 0 for _, line := range lines { trimmed := strings.TrimSpace(line) if trimmed == "" { continue } checkedLines++ if checkedLines > maxLinesToCheck { break } // Extract JSON part (skip timestamp prefix if present) idx := strings.Index(trimmed, "{") if idx < 0 { // No JSON object found in this line, try next continue } jsonPart := trimmed[idx:] // Try to parse as JSON var entry map[string]interface{} if err := json.Unmarshal([]byte(jsonPart), &entry); err != nil { // Not valid JSON, try next line continue } // Check for expected JSON log fields (forklift controller format) // A valid JSON log should have at least "level" and "msg" fields _, hasLevel := entry["level"] _, hasMsg := entry["msg"] if hasLevel && hasMsg { return true } } return false } // matchesParamFilters checks if a log entry matches all specified filters. func matchesParamFilters(entry JSONLogEntry, p kubectlDebugParams) bool { if p.FilterLevel != "" && !strings.EqualFold(entry.Level, p.FilterLevel) { return false } if p.FilterLogger != "" { loggerType := strings.Split(entry.Logger, "|")[0] if !strings.EqualFold(loggerType, p.FilterLogger) { return false } } if p.FilterPlan != "" { planName := "" if entry.Plan != nil { planName = entry.Plan["name"] } if !strings.EqualFold(planName, p.FilterPlan) { return false } } if p.FilterProvider != "" { providerName := "" if entry.Provider != nil { providerName = entry.Provider["name"] } if !strings.EqualFold(providerName, p.FilterProvider) { return false } } if p.FilterVM != "" { vmMatch := strings.EqualFold(entry.VM, p.FilterVM) || strings.EqualFold(entry.VMName, p.FilterVM) || strings.EqualFold(entry.VMID, p.FilterVM) if !vmMatch { return false } } if p.FilterMigration != "" { loggerParts := strings.Split(entry.Logger, "|") loggerType := loggerParts[0] if loggerType != "migration" { return false } migrationName := "" if entry.Migration != nil { migrationName = entry.Migration["name"] } if migrationName == "" && len(loggerParts) > 1 { migrationName = loggerParts[1] } if !strings.EqualFold(migrationName, p.FilterMigration) { return false } } return true } // filterAndFormatJSONLogs parses JSON logs, applies filters, and formats output. // It returns the processed logs based on the specified format: // - "json": Array of mixed JSONLogEntry and RawLogLine (for malformed lines) // - "text": Original raw JSONL lines (filtered) // - "pretty": Human-readable formatted output func filterAndFormatJSONLogs(logs string, p kubectlDebugParams) (interface{}, error) { lines := strings.Split(strings.TrimSpace(logs), "\n") if len(lines) == 0 || (len(lines) == 1 && lines[0] == "") { return []interface{}{}, nil } var logLines []interface{} var filteredLines []string hasFilters := hasJSONParamFilters(p) for _, line := range lines { line = strings.TrimSpace(line) if line == "" { continue } // Handle timestamp prefix from kubectl --timestamps flag // Format: "2026-02-05T10:45:52.123456789Z {"level":"info",...}" jsonPart := line timestampPrefix := "" if idx := strings.Index(line, "{"); idx > 0 { timestampPrefix = line[:idx] jsonPart = line[idx:] } var entry JSONLogEntry if err := json.Unmarshal([]byte(jsonPart), &entry); err != nil { if !hasFilters { logLines = append(logLines, RawLogLine{Raw: line}) filteredLines = append(filteredLines, line) } continue } if hasFilters && !matchesParamFilters(entry, p) { continue } logLines = append(logLines, entry) filteredLines = append(filteredLines, timestampPrefix+jsonPart) } format := p.LogFormat if format == "" { format = "json" } switch format { case "json": return logLines, nil case "text": return strings.Join(filteredLines, "\n"), nil case "pretty": return formatPrettyLogs(logLines), nil default: return logLines, nil } } // formatPrettyLogs formats log entries in a human-readable format. // It handles both JSONLogEntry (parsed) and RawLogLine (malformed) types. func formatPrettyLogs(logLines []interface{}) string { var lines []string for _, item := range logLines { switch v := item.(type) { case RawLogLine: // Include raw malformed lines as-is lines = append(lines, v.Raw) case JSONLogEntry: // Format: [LEVEL] timestamp logger: message (context) levelUpper := strings.ToUpper(v.Level) context := "" // Add context info if v.Plan != nil && v.Plan["name"] != "" { context = fmt.Sprintf(" plan=%s", v.Plan["name"]) if ns := v.Plan["namespace"]; ns != "" { context += fmt.Sprintf("/%s", ns) } } else if v.Provider != nil && v.Provider["name"] != "" { context = fmt.Sprintf(" provider=%s", v.Provider["name"]) if ns := v.Provider["namespace"]; ns != "" { context += fmt.Sprintf("/%s", ns) } } else if v.Map != nil && v.Map["name"] != "" { context = fmt.Sprintf(" map=%s", v.Map["name"]) if ns := v.Map["namespace"]; ns != "" { context += fmt.Sprintf("/%s", ns) } } if v.VM != "" { context += fmt.Sprintf(" vm=%s", v.VM) } else if v.VMName != "" { context += fmt.Sprintf(" vm=%s", v.VMName) } line := fmt.Sprintf("[%s] %s %s: %s%s", levelUpper, v.Ts, v.Logger, v.Msg, context) lines = append(lines, line) } } return strings.Join(lines, "\n") }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/kubectl_test.go
Go
package tools import ( "context" "strings" "testing" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // --- Tool definition tests --- func TestGetMinimalKubectlLogsTool(t *testing.T) { tool := GetMinimalKubectlLogsTool() if tool.Name != "kubectl_logs" { t.Errorf("Name = %q, want %q", tool.Name, "kubectl_logs") } if tool.Description == "" { t.Error("Description should not be empty") } // Should contain key log-specific keywords for _, keyword := range []string{ "forklift-controller", "filter_plan", "log_format", "filter_level", "deployments/forklift-controller", "tail_lines", } { if !strings.Contains(tool.Description, keyword) { t.Errorf("Description should contain %q", keyword) } } // OutputSchema should have expected properties schema, ok := tool.OutputSchema.(map[string]any) if !ok { t.Fatal("OutputSchema should be a map") } props, ok := schema["properties"].(map[string]any) if !ok { t.Fatal("OutputSchema should have properties") } for _, key := range []string{"return_value", "data", "output", "stderr"} { if _, exists := props[key]; !exists { t.Errorf("OutputSchema.properties should contain %q", key) } } // "command" should NOT be in the output schema (stripped to prevent CLI mimicry) if _, exists := props["command"]; exists { t.Error("OutputSchema.properties should NOT contain 'command' (stripped to help small LLMs)") } } func TestGetMinimalKubectlTool(t *testing.T) { tool := GetMinimalKubectlTool() if tool.Name != "kubectl" { t.Errorf("Name = %q, want %q", tool.Name, "kubectl") } if tool.Description == "" { t.Error("Description should not be empty") } // Should mention the three actions for _, action := range []string{"get", "describe", "events"} { if !strings.Contains(tool.Description, action) { t.Errorf("Description should contain action %q", action) } } // Should contain key resource-inspection keywords for _, keyword := range []string{ "resource_type", "namespace", "mtv_read", } { if !strings.Contains(tool.Description, keyword) { t.Errorf("Description should contain %q", keyword) } } // OutputSchema should have expected properties schema, ok := tool.OutputSchema.(map[string]any) if !ok { t.Fatal("OutputSchema should be a map") } props, ok := schema["properties"].(map[string]any) if !ok { t.Fatal("OutputSchema should have properties") } for _, key := range []string{"return_value", "data", "output", "stderr"} { if _, exists := props[key]; !exists { t.Errorf("OutputSchema.properties should contain %q", key) } } // "command" should NOT be in the output schema (stripped to prevent CLI mimicry) if _, exists := props["command"]; exists { t.Error("OutputSchema.properties should NOT contain 'command' (stripped to help small LLMs)") } } // --- buildLogsArgs tests --- func TestBuildLogsArgs(t *testing.T) { tests := []struct { name string params kubectlDebugParams wantContains []string wantMissing []string }{ { name: "basic logs with default tail", params: kubectlDebugParams{Name: "deployments/forklift-controller", Namespace: "openshift-mtv"}, wantContains: []string{"logs", "deployments/forklift-controller", "-n", "openshift-mtv", "--tail", "500", "--timestamps"}, }, { name: "custom tail lines", params: kubectlDebugParams{Name: "my-pod", TailLines: 100}, wantContains: []string{"--tail", "100"}, wantMissing: []string{"--tail 500"}, }, { name: "tail -1 gets all logs", params: kubectlDebugParams{Name: "my-pod", TailLines: -1}, wantMissing: []string{"--tail"}, }, { name: "with previous", params: kubectlDebugParams{Name: "crashed-pod", Previous: true}, wantContains: []string{"--previous"}, }, { name: "with container", params: kubectlDebugParams{Name: "multi-container-pod", Container: "main"}, wantContains: []string{"-c", "main"}, }, { name: "with since", params: kubectlDebugParams{Name: "my-pod", Since: "1h"}, wantContains: []string{"--since", "1h"}, }, { name: "no timestamps when disabled", params: kubectlDebugParams{Name: "my-pod", NoTimestamps: true}, wantMissing: []string{"--timestamps"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := buildLogsArgs(tt.params) joined := strings.Join(result, " ") for _, want := range tt.wantContains { if !strings.Contains(joined, want) { t.Errorf("buildLogsArgs() = %v, should contain %q", result, want) } } for _, notWant := range tt.wantMissing { if strings.Contains(joined, notWant) { t.Errorf("buildLogsArgs() = %v, should NOT contain %q", result, notWant) } } }) } } // --- buildGetArgs tests --- func TestBuildGetArgs(t *testing.T) { origFormat := util.GetOutputFormat() defer util.SetOutputFormat(origFormat) util.SetOutputFormat("json") tests := []struct { name string params kubectlDebugParams wantContains []string wantMissing []string }{ { name: "basic get pods", params: kubectlDebugParams{ResourceType: "pods", Namespace: "openshift-mtv"}, wantContains: []string{"get", "pods", "-n", "openshift-mtv", "-o", "json"}, }, { name: "get with labels", params: kubectlDebugParams{ResourceType: "pods", Labels: "plan=my-plan"}, wantContains: []string{"get", "pods", "-l", "plan=my-plan"}, }, { name: "get with name", params: kubectlDebugParams{ResourceType: "pvc", Name: "my-pvc"}, wantContains: []string{"get", "pvc", "my-pvc"}, }, { name: "get all namespaces", params: kubectlDebugParams{ResourceType: "pods", AllNamespaces: true}, wantContains: []string{"get", "pods", "-A"}, wantMissing: []string{"-n"}, }, { name: "get with custom output", params: kubectlDebugParams{ResourceType: "pods", Output: "wide"}, wantContains: []string{"-o", "wide"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := buildGetArgs(tt.params) joined := strings.Join(result, " ") for _, want := range tt.wantContains { if !strings.Contains(joined, want) { t.Errorf("buildGetArgs() = %v, should contain %q", result, want) } } for _, notWant := range tt.wantMissing { if strings.Contains(joined, notWant) { t.Errorf("buildGetArgs() = %v, should NOT contain %q", result, notWant) } } }) } } // --- buildDescribeArgs tests --- func TestBuildDescribeArgs(t *testing.T) { tests := []struct { name string params kubectlDebugParams wantContains []string }{ { name: "describe pod", params: kubectlDebugParams{ResourceType: "pods", Name: "my-pod", Namespace: "demo"}, wantContains: []string{"describe", "pods", "my-pod", "-n", "demo"}, }, { name: "describe with labels", params: kubectlDebugParams{ResourceType: "pods", Labels: "app=test"}, wantContains: []string{"describe", "pods", "-l", "app=test"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := buildDescribeArgs(tt.params) joined := strings.Join(result, " ") for _, want := range tt.wantContains { if !strings.Contains(joined, want) { t.Errorf("buildDescribeArgs() = %v, should contain %q", result, want) } } }) } } // --- buildEventsArgs tests --- func TestBuildEventsArgs(t *testing.T) { origFormat := util.GetOutputFormat() defer util.SetOutputFormat(origFormat) util.SetOutputFormat("json") tests := []struct { name string params kubectlDebugParams wantContains []string }{ { name: "events with namespace", params: kubectlDebugParams{Namespace: "demo"}, wantContains: []string{"get", "events", "-n", "demo"}, }, { name: "events with for_resource", params: kubectlDebugParams{ForResource: "pod/my-pod", Namespace: "demo"}, wantContains: []string{"--for", "pod/my-pod"}, }, { name: "events with field selector", params: kubectlDebugParams{FieldSelector: "type=Warning", Namespace: "demo"}, wantContains: []string{"--field-selector", "type=Warning"}, }, { name: "events with sort by", params: kubectlDebugParams{SortBy: ".lastTimestamp", Namespace: "demo"}, wantContains: []string{"--sort-by", ".lastTimestamp"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := buildEventsArgs(tt.params) joined := strings.Join(result, " ") for _, want := range tt.wantContains { if !strings.Contains(joined, want) { t.Errorf("buildEventsArgs() = %v, should contain %q", result, want) } } }) } } // --- Handler validation error tests --- func TestHandleKubectlLogs_ValidationErrors(t *testing.T) { ctx := context.Background() req := &mcp.CallToolRequest{} tests := []struct { name string input KubectlLogsInput wantError string }{ { name: "logs without name", input: KubectlLogsInput{}, wantError: "'name' is required", }, { name: "logs with name in flags works", input: KubectlLogsInput{ Flags: map[string]any{"name": "my-pod"}, DryRun: true, }, wantError: "", // no error expected }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, _, err := HandleKubectlLogs(ctx, req, tt.input) if tt.wantError == "" { if err != nil { t.Fatalf("unexpected error: %v", err) } return } if err == nil { t.Fatal("expected error, got nil") } if !strings.Contains(err.Error(), tt.wantError) { t.Errorf("error = %q, should contain %q", err.Error(), tt.wantError) } }) } } func TestHandleKubectl_ValidationErrors(t *testing.T) { ctx := context.Background() req := &mcp.CallToolRequest{} tests := []struct { name string input KubectlInput wantError string }{ { name: "unknown action", input: KubectlInput{Action: "invalid"}, wantError: "unknown action", }, { name: "get without resource_type", input: KubectlInput{Action: "get"}, wantError: "requires 'resource_type'", }, { name: "describe without resource_type", input: KubectlInput{Action: "describe"}, wantError: "requires 'resource_type'", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, _, err := HandleKubectl(ctx, req, tt.input) if tt.wantError == "" { if err != nil { t.Fatalf("unexpected error: %v", err) } return } if err == nil { t.Fatal("expected error, got nil") } if !strings.Contains(err.Error(), tt.wantError) { t.Errorf("error = %q, should contain %q", err.Error(), tt.wantError) } }) } } // --- Handler DryRun tests --- func TestHandleKubectlLogs_DryRun(t *testing.T) { ctx := context.Background() req := &mcp.CallToolRequest{} tests := []struct { name string input KubectlLogsInput wantContains []string }{ { name: "basic logs", input: KubectlLogsInput{ Flags: map[string]any{"name": "deployments/forklift-controller", "namespace": "openshift-mtv"}, DryRun: true, }, wantContains: []string{"kubectl", "logs", "deployments/forklift-controller", "-n", "openshift-mtv", "--tail", "500", "--timestamps"}, }, { name: "logs with previous and container", input: KubectlLogsInput{ Flags: map[string]any{"name": "crashed-pod", "container": "main", "previous": true, "tail_lines": 200}, DryRun: true, }, wantContains: []string{"kubectl", "logs", "crashed-pod", "-c", "main", "--previous", "--tail", "200"}, }, { name: "logs with since", input: KubectlLogsInput{ Flags: map[string]any{"name": "my-pod", "since": "30m"}, DryRun: true, }, wantContains: []string{"--since", "30m"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, data, err := HandleKubectlLogs(ctx, req, tt.input) if err != nil { t.Fatalf("unexpected error: %v", err) } dataMap, ok := data.(map[string]interface{}) if !ok { t.Fatalf("expected map[string]interface{}, got %T", data) } // In dry-run mode, the CLI command is in "output" (command field is stripped) output, ok := dataMap["output"].(string) if !ok { t.Fatal("response should have 'output' string field in dry-run mode") } for _, want := range tt.wantContains { if !strings.Contains(output, want) { t.Errorf("output = %q, should contain %q", output, want) } } }) } } func TestHandleKubectl_DryRun(t *testing.T) { ctx := context.Background() req := &mcp.CallToolRequest{} origFormat := util.GetOutputFormat() defer util.SetOutputFormat(origFormat) util.SetOutputFormat("json") tests := []struct { name string input KubectlInput wantContains []string }{ { name: "get action", input: KubectlInput{ Action: "get", Flags: map[string]any{"resource_type": "pods", "labels": "plan=my-plan", "namespace": "demo"}, DryRun: true, }, wantContains: []string{"kubectl", "get", "pods", "-n", "demo", "-l", "plan=my-plan", "-o", "json"}, }, { name: "describe action", input: KubectlInput{ Action: "describe", Flags: map[string]any{"resource_type": "pods", "name": "virt-v2v-cold-123", "namespace": "demo"}, DryRun: true, }, wantContains: []string{"kubectl", "describe", "pods", "virt-v2v-cold-123", "-n", "demo"}, }, { name: "events action", input: KubectlInput{ Action: "events", Flags: map[string]any{"field_selector": "type=Warning", "namespace": "demo"}, DryRun: true, }, wantContains: []string{"kubectl", "get", "events", "-n", "demo", "--field-selector", "type=Warning"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, data, err := HandleKubectl(ctx, req, tt.input) if err != nil { t.Fatalf("unexpected error: %v", err) } dataMap, ok := data.(map[string]interface{}) if !ok { t.Fatalf("expected map[string]interface{}, got %T", data) } // In dry-run mode, the CLI command is in "output" (command field is stripped) output, ok := dataMap["output"].(string) if !ok { t.Fatal("response should have 'output' string field in dry-run mode") } for _, want := range tt.wantContains { if !strings.Contains(output, want) { t.Errorf("output = %q, should contain %q", output, want) } } }) } } // --- filterLogsByPattern tests --- func TestFilterLogsByPattern(t *testing.T) { logs := "line 1 error found\nline 2 all good\nline 3 ERROR uppercase\nline 4 warning here" tests := []struct { name string pattern string ignoreCase bool wantErr bool wantLines int wantMatch string }{ { name: "empty pattern returns all", pattern: "", wantLines: 4, }, { name: "case-sensitive match", pattern: "error", wantLines: 1, wantMatch: "line 1", }, { name: "case-insensitive match", pattern: "error", ignoreCase: true, wantLines: 2, }, { name: "regex or pattern", pattern: "error|warning", wantLines: 2, }, { name: "invalid regex returns error", pattern: "[invalid", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := filterLogsByPattern(logs, tt.pattern, tt.ignoreCase) if tt.wantErr { if err == nil { t.Fatal("expected error, got nil") } return } if err != nil { t.Fatalf("unexpected error: %v", err) } lines := strings.Split(result, "\n") // Count non-empty lines for the empty pattern case nonEmpty := 0 for _, l := range lines { if l != "" { nonEmpty++ } } if tt.pattern == "" { // Empty pattern returns original string unchanged if result != logs { t.Error("empty pattern should return original logs") } } else if nonEmpty != tt.wantLines { t.Errorf("got %d non-empty lines, want %d", nonEmpty, tt.wantLines) } if tt.wantMatch != "" && !strings.Contains(result, tt.wantMatch) { t.Errorf("result should contain %q", tt.wantMatch) } }) } } // --- looksLikeJSONLogs tests --- func TestLooksLikeJSONLogs(t *testing.T) { tests := []struct { name string logs string expect bool }{ { name: "valid JSON with level and msg", logs: `{"level":"info","ts":"2026-02-05","logger":"plan","msg":"Reconcile started."}`, expect: true, }, { name: "timestamp-prefixed JSON", logs: `2026-02-05T10:45:52.123Z {"level":"info","ts":"2026-02-05","logger":"plan","msg":"Started."}`, expect: true, }, { name: "plain text logs", logs: "Starting virt-v2v conversion\nDisk 1/1 copied\nConversion complete", expect: false, }, { name: "empty string", logs: "", expect: false, }, { name: "JSON without level field", logs: `{"ts":"2026-02-05","msg":"no level"}`, expect: false, }, { name: "JSON without msg field", logs: `{"level":"info","ts":"2026-02-05"}`, expect: false, }, { name: "mixed - JSON line among non-JSON", logs: "some text\n{\"level\":\"info\",\"msg\":\"test\"}\nmore text", expect: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := looksLikeJSONLogs(tt.logs) if result != tt.expect { t.Errorf("looksLikeJSONLogs() = %v, want %v", result, tt.expect) } }) } } // --- matchesParamFilters tests --- func TestMatchesParamFilters(t *testing.T) { entry := JSONLogEntry{ Level: "info", Logger: "plan|abc123", Msg: "Reconcile started", Plan: map[string]string{"name": "my-plan", "namespace": "demo"}, Provider: map[string]string{"name": "my-provider", "namespace": "demo"}, VM: "vm-001", VMName: "web-server", VMID: "id-123", Migration: map[string]string{"name": "migration-xyz"}, } tests := []struct { name string params kubectlDebugParams expect bool }{ { name: "no filters matches all", params: kubectlDebugParams{}, expect: true, }, { name: "filter level matches", params: kubectlDebugParams{FilterLevel: "info"}, expect: true, }, { name: "filter level mismatch", params: kubectlDebugParams{FilterLevel: "error"}, expect: false, }, { name: "filter logger matches prefix", params: kubectlDebugParams{FilterLogger: "plan"}, expect: true, }, { name: "filter logger mismatch", params: kubectlDebugParams{FilterLogger: "provider"}, expect: false, }, { name: "filter plan matches", params: kubectlDebugParams{FilterPlan: "my-plan"}, expect: true, }, { name: "filter plan mismatch", params: kubectlDebugParams{FilterPlan: "other-plan"}, expect: false, }, { name: "filter provider matches", params: kubectlDebugParams{FilterProvider: "my-provider"}, expect: true, }, { name: "filter provider mismatch", params: kubectlDebugParams{FilterProvider: "other"}, expect: false, }, { name: "filter VM by VM field", params: kubectlDebugParams{FilterVM: "vm-001"}, expect: true, }, { name: "filter VM by VMName field", params: kubectlDebugParams{FilterVM: "web-server"}, expect: true, }, { name: "filter VM by VMID field", params: kubectlDebugParams{FilterVM: "id-123"}, expect: true, }, { name: "filter VM mismatch", params: kubectlDebugParams{FilterVM: "nonexistent"}, expect: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := matchesParamFilters(entry, tt.params) if result != tt.expect { t.Errorf("matchesParamFilters() = %v, want %v", result, tt.expect) } }) } } func TestMatchesParamFilters_Migration(t *testing.T) { entry := JSONLogEntry{ Level: "info", Logger: "migration|migration-xyz", Msg: "Migration started", Migration: map[string]string{"name": "migration-xyz"}, } tests := []struct { name string params kubectlDebugParams expect bool }{ { name: "migration filter matches from field", params: kubectlDebugParams{FilterMigration: "migration-xyz"}, expect: true, }, { name: "migration filter mismatch", params: kubectlDebugParams{FilterMigration: "other-migration"}, expect: false, }, { name: "migration filter requires migration logger", params: kubectlDebugParams{FilterMigration: "migration-xyz"}, expect: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := matchesParamFilters(entry, tt.params) if result != tt.expect { t.Errorf("matchesParamFilters() = %v, want %v", result, tt.expect) } }) } // Non-migration logger should not match migration filter nonMigrationEntry := JSONLogEntry{ Level: "info", Logger: "plan|abc", Msg: "test", } if matchesParamFilters(nonMigrationEntry, kubectlDebugParams{FilterMigration: "any"}) { t.Error("non-migration logger should not match migration filter") } } // --- filterAndFormatJSONLogs tests --- func TestFilterAndFormatJSONLogs(t *testing.T) { jsonLogs := `{"level":"info","ts":"2026-02-05 10:00:00","logger":"plan|abc","msg":"Started","plan":{"name":"my-plan","namespace":"demo"}} {"level":"error","ts":"2026-02-05 10:01:00","logger":"plan|abc","msg":"Failed","plan":{"name":"my-plan","namespace":"demo"}} {"level":"info","ts":"2026-02-05 10:02:00","logger":"provider|xyz","msg":"Refreshed","provider":{"name":"my-provider","namespace":"demo"}}` t.Run("json format returns array", func(t *testing.T) { result, err := filterAndFormatJSONLogs(jsonLogs, kubectlDebugParams{LogFormat: "json"}) if err != nil { t.Fatalf("unexpected error: %v", err) } entries, ok := result.([]interface{}) if !ok { t.Fatalf("expected []interface{}, got %T", result) } if len(entries) != 3 { t.Errorf("got %d entries, want 3", len(entries)) } }) t.Run("text format returns string", func(t *testing.T) { result, err := filterAndFormatJSONLogs(jsonLogs, kubectlDebugParams{LogFormat: "text"}) if err != nil { t.Fatalf("unexpected error: %v", err) } str, ok := result.(string) if !ok { t.Fatalf("expected string, got %T", result) } if !strings.Contains(str, "Started") { t.Error("text output should contain log messages") } }) t.Run("pretty format returns formatted string", func(t *testing.T) { result, err := filterAndFormatJSONLogs(jsonLogs, kubectlDebugParams{LogFormat: "pretty"}) if err != nil { t.Fatalf("unexpected error: %v", err) } str, ok := result.(string) if !ok { t.Fatalf("expected string, got %T", result) } if !strings.Contains(str, "[INFO]") { t.Error("pretty output should contain [INFO] prefix") } if !strings.Contains(str, "[ERROR]") { t.Error("pretty output should contain [ERROR] prefix") } }) t.Run("filter by level", func(t *testing.T) { result, err := filterAndFormatJSONLogs(jsonLogs, kubectlDebugParams{ LogFormat: "json", FilterLevel: "error", }) if err != nil { t.Fatalf("unexpected error: %v", err) } entries, ok := result.([]interface{}) if !ok { t.Fatalf("expected []interface{}, got %T", result) } if len(entries) != 1 { t.Errorf("got %d entries, want 1 (only error)", len(entries)) } }) t.Run("filter by plan name", func(t *testing.T) { result, err := filterAndFormatJSONLogs(jsonLogs, kubectlDebugParams{ LogFormat: "json", FilterPlan: "my-plan", }) if err != nil { t.Fatalf("unexpected error: %v", err) } entries, ok := result.([]interface{}) if !ok { t.Fatalf("expected []interface{}, got %T", result) } if len(entries) != 2 { t.Errorf("got %d entries, want 2 (plan entries only)", len(entries)) } }) t.Run("malformed line preserved as raw", func(t *testing.T) { mixedLogs := `{"level":"info","ts":"2026-02-05","logger":"plan","msg":"OK"} not a json line {"level":"error","ts":"2026-02-05","logger":"plan","msg":"fail"}` result, err := filterAndFormatJSONLogs(mixedLogs, kubectlDebugParams{LogFormat: "json"}) if err != nil { t.Fatalf("unexpected error: %v", err) } entries, ok := result.([]interface{}) if !ok { t.Fatalf("expected []interface{}, got %T", result) } if len(entries) != 3 { t.Errorf("got %d entries, want 3 (2 JSON + 1 raw)", len(entries)) } if raw, ok := entries[1].(RawLogLine); ok { if !strings.Contains(raw.Raw, "not a json line") { t.Error("raw line should preserve original text") } } else { t.Errorf("entry[1] should be RawLogLine, got %T", entries[1]) } }) t.Run("empty logs returns empty array", func(t *testing.T) { result, err := filterAndFormatJSONLogs("", kubectlDebugParams{LogFormat: "json"}) if err != nil { t.Fatalf("unexpected error: %v", err) } entries, ok := result.([]interface{}) if !ok { t.Fatalf("expected []interface{}, got %T", result) } if len(entries) != 0 { t.Errorf("got %d entries, want 0", len(entries)) } }) t.Run("default format is json", func(t *testing.T) { result, err := filterAndFormatJSONLogs(jsonLogs, kubectlDebugParams{}) if err != nil { t.Fatalf("unexpected error: %v", err) } if _, ok := result.([]interface{}); !ok { t.Fatalf("default format should return []interface{}, got %T", result) } }) } // --- formatPrettyLogs tests --- func TestFormatPrettyLogs(t *testing.T) { logLines := []interface{}{ JSONLogEntry{ Level: "info", Ts: "2026-02-05 10:00:00", Logger: "plan|abc", Msg: "Reconcile started", Plan: map[string]string{"name": "my-plan", "namespace": "demo"}, }, JSONLogEntry{ Level: "error", Ts: "2026-02-05 10:01:00", Logger: "provider|xyz", Msg: "Connection failed", Provider: map[string]string{"name": "my-vsphere", "namespace": "demo"}, }, JSONLogEntry{ Level: "info", Ts: "2026-02-05 10:02:00", Logger: "plan|abc", Msg: "VM migrating", VMName: "web-server-01", }, RawLogLine{Raw: "unparseable line"}, } result := formatPrettyLogs(logLines) // Check level prefixes if !strings.Contains(result, "[INFO]") { t.Error("should contain [INFO] prefix") } if !strings.Contains(result, "[ERROR]") { t.Error("should contain [ERROR] prefix") } // Check context annotations if !strings.Contains(result, "plan=my-plan") { t.Error("should contain plan context") } if !strings.Contains(result, "provider=my-vsphere") { t.Error("should contain provider context") } if !strings.Contains(result, "vm=web-server-01") { t.Error("should contain VM context") } // Check raw line preserved if !strings.Contains(result, "unparseable line") { t.Error("should preserve raw lines") } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/mtv_help.go
Go
package tools import ( "context" "fmt" "regexp" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // MTVHelpInput represents the input for the mtv_help tool. type MTVHelpInput struct { // Command is the kubectl-mtv command or topic to get help for. // Examples: "create plan", "get inventory vm", "tsl", "karl" Command string `json:"command" jsonschema:"Command or topic (e.g. create plan, get inventory vm, tsl, karl)"` } // GetMTVHelpTool returns the tool definition for on-demand help. func GetMTVHelpTool() *mcp.Tool { return &mcp.Tool{ Name: "mtv_help", Description: `Get help: flags, usage, examples for any command, or syntax refs for topics. Commands: any from mtv_read/mtv_write, e.g.: "get plan", "get provider", "get inventory vm" "describe plan", "create provider", "create plan" "start plan", "patch plan", "delete plan" Topics: "tsl" - VM query language with field list per provider (vSphere, oVirt, OpenStack, EC2) "karl" - VM placement affinity/anti-affinity rules (e.g. "REQUIRE tag:zone=us-east") IMPORTANT: Call mtv_help("tsl") before writing inventory queries to learn available fields and syntax. Output: Returns command flags, usage, and examples as structured data.`, OutputSchema: mtvOutputSchema, } } // HandleMTVHelp handles the mtv_help tool invocation. func HandleMTVHelp(ctx context.Context, req *mcp.CallToolRequest, input MTVHelpInput) (*mcp.CallToolResult, any, error) { // Extract K8s credentials from HTTP headers (populated by wrapper in SSE mode) ctx = extractKubeCredsFromRequest(ctx, req) command := strings.TrimSpace(input.Command) if command == "" { return nil, nil, fmt.Errorf("command is required (e.g. \"create plan\", \"tsl\", \"karl\")") } // Build args: help --machine [command parts...] args := []string{"help", "--machine"} parts := strings.Fields(command) args = append(args, parts...) // Execute kubectl-mtv help --machine [command] result, err := util.RunKubectlMTVCommand(ctx, args) if err != nil { return nil, nil, fmt.Errorf("help command failed: %w", err) } // Parse and return result data, err := util.UnmarshalJSONResponse(result) if err != nil { return nil, nil, err } // Post-process: convert CLI-style help to MCP-style for LLM consumption. // This handles both single-command responses and multi-command (array) responses. convertHelpToMCPStyle(data) return nil, data, nil } // convertHelpToMCPStyle transforms CLI-style help data into MCP-style. // It modifies the data map in place, converting: // - "usage" field from CLI format to MCP call pattern // - "examples" from CLI commands to MCP JSON-style calls // Works for both single command (data.commands is a single object) and // multi-command responses (data.commands is an array). func convertHelpToMCPStyle(data map[string]interface{}) { // Handle the "data" envelope — help --machine returns {command, return_value, data} rawData, ok := data["data"] if !ok { return } switch d := rawData.(type) { case map[string]interface{}: // Single command or topic response — check if it has "commands" (array of commands) if commands, ok := d["commands"].([]interface{}); ok { for _, cmdRaw := range commands { if cmd, ok := cmdRaw.(map[string]interface{}); ok { convertCommandToMCPStyle(cmd) } } } else { // Single command response (e.g., help --machine get plan) convertCommandToMCPStyle(d) } case []interface{}: // Array of commands for _, cmdRaw := range d { if cmd, ok := cmdRaw.(map[string]interface{}); ok { convertCommandToMCPStyle(cmd) } } } } // convertCommandToMCPStyle transforms a single command's help data to MCP-style. // It replaces the "usage" field with an MCP call pattern and converts CLI examples // to MCP-style JSON calls. func convertCommandToMCPStyle(cmd map[string]interface{}) { pathString, _ := cmd["path_string"].(string) if pathString == "" { return } // Build flag shorthand -> long name mapping shortToLong := make(map[string]string) if rawFlags, ok := cmd["flags"].([]interface{}); ok { for _, rawFlag := range rawFlags { if flag, ok := rawFlag.(map[string]interface{}); ok { name, _ := flag["name"].(string) shorthand, _ := flag["shorthand"].(string) if shorthand != "" && name != "" { shortToLong[shorthand] = name } } } } // Replace "usage" with MCP-style call pattern cmd["usage"] = fmt.Sprintf("{command: \"%s\", flags: {...}}", pathString) // Convert examples from CLI to MCP style if rawExamples, ok := cmd["examples"].([]interface{}); ok { for i, rawEx := range rawExamples { ex, ok := rawEx.(map[string]interface{}) if !ok { continue } cliCmd, _ := ex["command"].(string) if cliCmd == "" { continue } mcpCall := convertCLIExampleToMCP(cliCmd, pathString, shortToLong) if mcpCall != "" { ex["command"] = mcpCall rawExamples[i] = ex } } } } // cliContinuationRegex matches backslash-newline-comment patterns from multi-line CLI examples. // Cobra examples use "\" followed by "# " comment lines for readability. var cliContinuationRegex = regexp.MustCompile(`\s*\\\s*(?:#[^\n]*)?\n\s*(?:#\s*)?`) // convertCLIExampleToMCP converts a CLI example string to an MCP-style JSON call. // Example: "kubectl-mtv get inventory vm --provider vsphere-prod --query \"where name ~= 'web-.*'\"" // becomes: {command: "get inventory vm", flags: {provider: "vsphere-prod", query: "where name ~= 'web-.*'"}} func convertCLIExampleToMCP(cliCmd string, pathString string, shortToLong map[string]string) string { // Clean up multi-line examples (backslash continuations with # comments) cliCmd = cliContinuationRegex.ReplaceAllString(cliCmd, " ") cliCmd = strings.TrimSpace(cliCmd) // Strip "kubectl-mtv " or "kubectl mtv " prefix cliCmd = strings.TrimPrefix(cliCmd, "kubectl-mtv ") cliCmd = strings.TrimPrefix(cliCmd, "kubectl mtv ") // Strip the command path from the front rest := cliCmd pathParts := strings.Fields(pathString) for _, part := range pathParts { rest = strings.TrimSpace(rest) if strings.HasPrefix(rest, part+" ") { rest = rest[len(part)+1:] } else if rest == part { rest = "" } } rest = strings.TrimSpace(rest) // Tokenize the remaining string, respecting quotes tokens := tokenizeCLIArgs(rest) // Parse tokens as flags (no positional args — all args are flags now) flags := make(map[string]string) for i := 0; i < len(tokens); i++ { tok := tokens[i] if !strings.HasPrefix(tok, "-") { continue // skip stray tokens } // Handle --flag=value if strings.Contains(tok, "=") { parts := strings.SplitN(tok, "=", 2) name := strings.TrimLeft(parts[0], "-") // Resolve shorthand if long, ok := shortToLong[name]; ok { name = long } flags[name] = parts[1] continue } // Handle --flag value or -f value name := strings.TrimLeft(tok, "-") // Resolve shorthand if long, ok := shortToLong[name]; ok { name = long } // Check if next token is a value (not another flag) if i+1 < len(tokens) && !strings.HasPrefix(tokens[i+1], "-") { flags[name] = tokens[i+1] i++ // skip value } else { // Boolean flag flags[name] = "true" } } // Build MCP-style call string if len(flags) == 0 { return fmt.Sprintf("{command: \"%s\"}", pathString) } var flagParts []string for k, v := range flags { if v == "true" { flagParts = append(flagParts, fmt.Sprintf("%s: true", k)) } else { flagParts = append(flagParts, fmt.Sprintf("%s: \"%s\"", k, v)) } } return fmt.Sprintf("{command: \"%s\", flags: {%s}}", pathString, strings.Join(flagParts, ", ")) } // tokenizeCLIArgs splits a CLI argument string into tokens, respecting single and double quotes. // Examples: // // "hello world" -> ["hello", "world"] // "--name 'my plan'" -> ["--name", "my plan"] // "--query \"where name ~= 'test'\"" -> ["--query", "where name ~= 'test'"] func tokenizeCLIArgs(s string) []string { var tokens []string var current strings.Builder inSingleQuote := false inDoubleQuote := false for i := 0; i < len(s); i++ { ch := s[i] switch { case ch == '\'' && !inDoubleQuote: inSingleQuote = !inSingleQuote case ch == '"' && !inSingleQuote: inDoubleQuote = !inDoubleQuote case ch == ' ' && !inSingleQuote && !inDoubleQuote: if current.Len() > 0 { tokens = append(tokens, current.String()) current.Reset() } default: current.WriteByte(ch) } } if current.Len() > 0 { tokens = append(tokens, current.String()) } return tokens }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/mtv_help_test.go
Go
package tools import ( "context" "strings" "testing" "github.com/modelcontextprotocol/go-sdk/mcp" ) // --- Tool definition tests --- func TestGetMTVHelpTool(t *testing.T) { tool := GetMTVHelpTool() if tool.Name != "mtv_help" { t.Errorf("Name = %q, want %q", tool.Name, "mtv_help") } if tool.Description == "" { t.Error("Description should not be empty") } // Description should reference key capabilities for _, keyword := range []string{"help", "flags", "tsl", "karl"} { if !strings.Contains(strings.ToLower(tool.Description), keyword) { t.Errorf("Description should contain %q", keyword) } } // OutputSchema should have expected properties schema, ok := tool.OutputSchema.(map[string]any) if !ok { t.Fatal("OutputSchema should be a map") } props, ok := schema["properties"].(map[string]any) if !ok { t.Fatal("OutputSchema should have properties") } for _, key := range []string{"return_value", "data", "output", "stderr"} { if _, exists := props[key]; !exists { t.Errorf("OutputSchema.properties should contain %q", key) } } // "command" should NOT be in the output schema (stripped to prevent CLI mimicry) if _, exists := props["command"]; exists { t.Error("OutputSchema.properties should NOT contain 'command' (stripped to help small LLMs)") } } // --- Handler validation error tests --- func TestHandleMTVHelp_EmptyCommand(t *testing.T) { ctx := context.Background() req := &mcp.CallToolRequest{} _, _, err := HandleMTVHelp(ctx, req, MTVHelpInput{Command: ""}) if err == nil { t.Fatal("expected error for empty command, got nil") } if !strings.Contains(err.Error(), "command is required") { t.Errorf("error = %q, should contain 'command is required'", err.Error()) } } func TestHandleMTVHelp_WhitespaceCommand(t *testing.T) { ctx := context.Background() req := &mcp.CallToolRequest{} _, _, err := HandleMTVHelp(ctx, req, MTVHelpInput{Command: " "}) if err == nil { t.Fatal("expected error for whitespace command, got nil") } if !strings.Contains(err.Error(), "command is required") { t.Errorf("error = %q, should contain 'command is required'", err.Error()) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/mtv_read.go
Go
package tools import ( "context" "fmt" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/discovery" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // MTVReadInput represents the input for the mtv_read tool. type MTVReadInput struct { Command string `json:"command" jsonschema:"Command path (e.g. get plan, get inventory vm, describe mapping)"` Flags map[string]any `json:"flags,omitempty" jsonschema:"All parameters including positional args and options (e.g. name: \"my-plan\", provider: \"my-vsphere\", output: \"json\", namespace: \"ns\", query: \"where cpuCount > 4\")"` DryRun bool `json:"dry_run,omitempty" jsonschema:"If true, does not execute. Returns the equivalent CLI command in the output field instead"` Fields []string `json:"fields,omitempty" jsonschema:"Limit JSON to these top-level keys only (e.g. [name, id, concerns])"` } // mtvOutputSchema is the shared output schema for mtv_read and mtv_write tools. // The "command" field is intentionally omitted to prevent small LLMs from // mimicking CLI command syntax (e.g., generating "kubectl-mtv get plan ...") // instead of structured {command, flags} tool calls. var mtvOutputSchema = map[string]any{ "type": "object", "properties": map[string]any{ "return_value": map[string]any{"type": "integer", "description": "Exit code (0=success)"}, "data": map[string]any{ "description": "Response data (object or array)", "oneOf": []map[string]any{ {"type": "object"}, {"type": "array"}, }, }, "output": map[string]any{"type": "string", "description": "Text output"}, "stderr": map[string]any{"type": "string", "description": "Error output"}, }, } // GetMTVReadTool returns the tool definition for read-only MTV commands. func GetMTVReadTool(registry *discovery.Registry) *mcp.Tool { description := registry.GenerateReadOnlyDescription() return &mcp.Tool{ Name: "mtv_read", Description: description, OutputSchema: mtvOutputSchema, } } // GetMinimalMTVReadTool returns a minimal tool definition for read-only MTV commands. // The input schema (jsonschema tags on MTVReadInput) already describes parameters. // The description only lists available commands and a hint to use mtv_help. func GetMinimalMTVReadTool(registry *discovery.Registry) *mcp.Tool { description := registry.GenerateMinimalReadOnlyDescription() return &mcp.Tool{ Name: "mtv_read", Description: description, OutputSchema: mtvOutputSchema, } } // GetUltraMinimalMTVReadTool returns the smallest possible tool definition for read-only // MTV commands, optimized for very small models (< 8B parameters). // Lists only the most common commands, 2 examples, and omits flags/workflow/notes. func GetUltraMinimalMTVReadTool(registry *discovery.Registry) *mcp.Tool { description := registry.GenerateUltraMinimalReadOnlyDescription() return &mcp.Tool{ Name: "mtv_read", Description: description, OutputSchema: mtvOutputSchema, } } // validateCommandInput checks for common malformed input patterns from small LLMs. // When a model sends garbled input (CLI commands, embedded tool results, etc.), // this returns a corrective error message that teaches the model the right format, // rather than letting it spiral into a degenerate loop. func validateCommandInput(command string) error { command = strings.TrimSpace(command) // Detect full CLI commands pasted as the command field lower := strings.ToLower(command) if strings.HasPrefix(lower, "kubectl-mtv ") || strings.HasPrefix(lower, "kubectl ") { return fmt.Errorf( "the 'command' field should be a subcommand path like 'get plan' or 'get inventory vm', " + "not a full CLI command. Remove the 'kubectl-mtv' or 'kubectl' prefix") } // Detect embedded JSON/output (hallucinated tool responses mixed into input) if strings.Contains(command, "\"output\"") || strings.Contains(command, "\"return_value\"") || strings.Contains(command, "\"stdout\"") || strings.Contains(command, "[TOOL_CALLS]") { return fmt.Errorf( "the 'command' field contains what looks like a previous tool response. " + "It should only contain a command path like 'get inventory datastore'") } // Detect overly long command strings (almost certainly malformed) if len(command) > 200 { return fmt.Errorf( "the 'command' field is too long (%d chars). "+ "It should be a short command path like 'get plan' or 'get inventory vm'", len(command)) } return nil } // HandleMTVRead returns a handler function for the mtv_read tool. func HandleMTVRead(registry *discovery.Registry) func(context.Context, *mcp.CallToolRequest, MTVReadInput) (*mcp.CallToolResult, any, error) { return func(ctx context.Context, req *mcp.CallToolRequest, input MTVReadInput) (*mcp.CallToolResult, any, error) { // Extract K8s credentials from HTTP headers (populated by wrapper in SSE mode) ctx = extractKubeCredsFromRequest(ctx, req) // Validate input to catch common small-LLM mistakes early if err := validateCommandInput(input.Command); err != nil { return nil, nil, err } // Normalize command path cmdPath := normalizeCommandPath(input.Command) // Validate command exists and is read-only if !registry.IsReadOnly(cmdPath) { if registry.IsReadWrite(cmdPath) { return nil, nil, fmt.Errorf("command '%s' is a write operation, use mtv_write tool instead", input.Command) } // List available commands in error, converting path keys to user-friendly format available := registry.ListReadOnlyCommands() for i, cmd := range available { available[i] = strings.ReplaceAll(cmd, "/", " ") } return nil, nil, fmt.Errorf("unknown command '%s'. Available read commands: %s", input.Command, strings.Join(available, ", ")) } // Enable dry run mode if requested if input.DryRun { ctx = util.WithDryRun(ctx, true) } // Build command arguments (all params passed via flags) args := buildArgs(cmdPath, input.Flags) // Execute command result, err := util.RunKubectlMTVCommand(ctx, args) if err != nil { return nil, nil, fmt.Errorf("command failed: %w", err) } // Parse and return result data, err := util.UnmarshalJSONResponse(result) if err != nil { return nil, nil, err } // Check for CLI errors and surface as MCP IsError response if errResult := buildCLIErrorResult(data); errResult != nil { return errResult, nil, nil } // Apply field filtering if requested if len(input.Fields) > 0 { data = filterResponseFields(data, input.Fields) } return nil, data, nil } } // filterResponseFields filters the "data" field of a response to include only the specified fields. // It handles both array responses ([]interface{}) and single object responses (map[string]interface{}). // Envelope fields (return_value, stderr, output) are always preserved. func filterResponseFields(data map[string]interface{}, fields []string) map[string]interface{} { if len(fields) == 0 { return data } // Build a set of allowed field names for fast lookup allowed := make(map[string]bool, len(fields)) for _, f := range fields { allowed[f] = true } // Filter the "data" field only, preserving envelope fields rawData, ok := data["data"] if !ok { return data } switch items := rawData.(type) { case []interface{}: // Array of items: filter each item filtered := make([]interface{}, 0, len(items)) for _, item := range items { if m, ok := item.(map[string]interface{}); ok { filtered = append(filtered, filterMapFields(m, allowed)) } else { // Non-object items are kept as-is filtered = append(filtered, item) } } data["data"] = filtered case map[string]interface{}: // Single object: filter its fields data["data"] = filterMapFields(items, allowed) } return data } // filterMapFields returns a new map containing only keys present in the allowed set. func filterMapFields(m map[string]interface{}, allowed map[string]bool) map[string]interface{} { result := make(map[string]interface{}, len(allowed)) for key, val := range m { if allowed[key] { result[key] = val } } return result } // normalizeCommandPath converts a command string to a path key. // "get plan" -> "get/plan" // "get inventory vm" -> "get/inventory/vm" func normalizeCommandPath(cmd string) string { // Trim and normalize whitespace cmd = strings.TrimSpace(cmd) parts := strings.Fields(cmd) return strings.Join(parts, "/") } // buildArgs builds the command-line arguments for kubectl-mtv. // All parameters (namespace, all_namespaces, inventory_url, output, name, provider, etc.) // are extracted from the flags map — there are no separate top-level fields. func buildArgs(cmdPath string, flags map[string]any) []string { var args []string // Add command path parts parts := strings.Split(cmdPath, "/") args = append(args, parts...) // Extract namespace / all_namespaces from flags var namespace string var allNamespaces bool if flags != nil { if v, ok := flags["namespace"]; ok { namespace = fmt.Sprintf("%v", v) } else if v, ok := flags["n"]; ok { namespace = fmt.Sprintf("%v", v) } if v, ok := flags["all_namespaces"]; ok { allNamespaces = parseBoolValue(v) } else if v, ok := flags["A"]; ok { allNamespaces = parseBoolValue(v) } } // Add namespace flags if allNamespaces { args = append(args, "--all-namespaces") } else if namespace != "" { args = append(args, "--namespace", namespace) } // Extract inventory URL from flags var inventoryURL string if flags != nil { if v, ok := flags["inventory_url"]; ok { inventoryURL = fmt.Sprintf("%v", v) } else if v, ok := flags["inventory-url"]; ok { inventoryURL = fmt.Sprintf("%v", v) } else if v, ok := flags["i"]; ok { inventoryURL = fmt.Sprintf("%v", v) } } if inventoryURL != "" { args = append(args, "--inventory-url", inventoryURL) } // Add output format - prefer user-specified, then configured default var userOutput string if flags != nil { if v, ok := flags["output"]; ok { userOutput = fmt.Sprintf("%v", v) } else if v, ok := flags["o"]; ok { userOutput = fmt.Sprintf("%v", v) } } if userOutput != "" { // User explicitly requested an output format args = append(args, "--output", userOutput) } else { // Use configured default from MCP server format := util.GetOutputFormat() // For "text" format, don't add --output flag to use default table output if format != "text" { args = append(args, "--output", format) } } // Skip set for already handled flags (namespace, output, inventory-url variants) skipFlags := map[string]bool{ "namespace": true, "n": true, "all_namespaces": true, "A": true, "inventory_url": true, "inventory-url": true, "i": true, "output": true, "o": true, } // Add other flags using the normalizer args = appendNormalizedFlags(args, flags, skipFlags) return args } // appendNormalizedFlags appends flags from a map[string]any to the args slice. // It handles different value types: // - bool true: includes the flag with no value (presence flag) // - bool false: explicitly passes --flag=false (needed for flags that default to true) // - string "true"/"false": treated as boolean // - string/number: converted to string form // // Flag prefix is determined by key length: single char uses "-x", multi-char uses "--long" func appendNormalizedFlags(args []string, flags map[string]any, skipFlags map[string]bool) []string { for name, value := range flags { // Skip flags in the skip set if skipFlags != nil && skipFlags[name] { continue } // Determine flag prefix: single dash for single-char flags, double dash for multi-char prefix := "--" if len(name) == 1 { prefix = "-" } // Handle different value types switch v := value.(type) { case bool: if v { // Boolean true: include flag with no value args = append(args, prefix+name) } else { // Boolean false: explicitly pass --flag=false // This is needed for flags that default to true (e.g., --migrate-shared-disks) args = append(args, prefix+name+"=false") } case string: // Handle string "true"/"false" as boolean for backwards compatibility if v == "true" { args = append(args, prefix+name) } else if v == "false" { // Explicitly pass --flag=false for flags that default to true args = append(args, prefix+name+"=false") } else if v != "" { args = append(args, prefix+name, v) } case float64: // JSON numbers are decoded as float64 // Check if it's a whole number to avoid unnecessary decimals if v == float64(int64(v)) { args = append(args, prefix+name, fmt.Sprintf("%d", int64(v))) } else { args = append(args, prefix+name, fmt.Sprintf("%g", v)) } case int, int64, int32: args = append(args, prefix+name, fmt.Sprintf("%d", v)) default: // For any other type, convert to string if v != nil { args = append(args, prefix+name, fmt.Sprintf("%v", v)) } } } return args } // buildCLIErrorResult checks if a CLI response indicates failure (non-zero return_value) // and returns an MCP CallToolResult with IsError=true if so. // This gives the LLM immediate, unambiguous error feedback instead of embedding // errors in a "successful" response where they may be overlooked. // Returns nil if the command succeeded (return_value == 0). func buildCLIErrorResult(data map[string]interface{}) *mcp.CallToolResult { rv, ok := data["return_value"].(float64) if !ok || rv == 0 { return nil } errMsg := fmt.Sprintf("Command failed (exit %d)", int(rv)) if stderr, ok := data["stderr"].(string); ok && stderr != "" { errMsg += ": " + strings.TrimSpace(stderr) } return &mcp.CallToolResult{ Content: []mcp.Content{&mcp.TextContent{Text: errMsg}}, IsError: true, } } // parseBoolValue interprets a value from the flags map as a boolean. // It handles bool, string ("true"/"True"/"TRUE"/"1"/"false"/"False"/"FALSE"/"0"), // and float64 (JSON numbers: 1 = true, 0 = false). func parseBoolValue(v any) bool { switch val := v.(type) { case bool: return val case string: if strings.EqualFold(val, "true") || val == "1" { return true } return false case float64: return val != 0 default: return false } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/mtv_read_test.go
Go
package tools import ( "context" "encoding/json" "os/exec" "strings" "testing" "time" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/discovery" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // testRegistry builds a minimal registry for testing. func testRegistry() *discovery.Registry { return &discovery.Registry{ ReadOnly: map[string]*discovery.Command{ "get/plan": { Path: []string{"get", "plan"}, PathString: "get plan", Description: "Get migration plans", }, "get/provider": { Path: []string{"get", "provider"}, PathString: "get provider", Description: "Get providers", }, "get/inventory/vm": { Path: []string{"get", "inventory", "vm"}, PathString: "get inventory vm", Description: "Get VMs", }, "describe/plan": { Path: []string{"describe", "plan"}, PathString: "describe plan", Description: "Describe plan", }, "health": {Path: []string{"health"}, PathString: "health", Description: "Health check"}, }, ReadWrite: map[string]*discovery.Command{ "create/provider": { Path: []string{"create", "provider"}, PathString: "create provider", Description: "Create provider", }, "create/plan": { Path: []string{"create", "plan"}, PathString: "create plan", Description: "Create plan", }, "delete/plan": { Path: []string{"delete", "plan"}, PathString: "delete plan", Description: "Delete plan", }, "start/plan": { Path: []string{"start", "plan"}, PathString: "start plan", Description: "Start plan", }, }, } } // --- Tool definition tests --- func TestGetMTVReadTool(t *testing.T) { registry := testRegistry() tool := GetMTVReadTool(registry) if tool.Name != "mtv_read" { t.Errorf("Name = %q, want %q", tool.Name, "mtv_read") } if tool.Description == "" { t.Error("Description should not be empty") } // Description should reference read-only commands for _, keyword := range []string{"get plan", "health"} { if !strings.Contains(tool.Description, keyword) { t.Errorf("Description should contain %q", keyword) } } // OutputSchema should have expected properties schema, ok := tool.OutputSchema.(map[string]any) if !ok { t.Fatal("OutputSchema should be a map") } props, ok := schema["properties"].(map[string]any) if !ok { t.Fatal("OutputSchema should have properties") } for _, key := range []string{"return_value", "data", "output", "stderr"} { if _, exists := props[key]; !exists { t.Errorf("OutputSchema.properties should contain %q", key) } } // "command" should NOT be in the output schema (stripped to prevent CLI mimicry) if _, exists := props["command"]; exists { t.Error("OutputSchema.properties should NOT contain 'command' (stripped to help small LLMs)") } } // --- normalizeCommandPath tests --- func TestNormalizeCommandPath(t *testing.T) { tests := []struct { name string input string expected string }{ {"simple two words", "get plan", "get/plan"}, {"three words", "get inventory vm", "get/inventory/vm"}, {"single word", "health", "health"}, {"extra whitespace", " get plan ", "get/plan"}, {"tabs and spaces", "\tget\tplan\t", "get/plan"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := normalizeCommandPath(tt.input) if result != tt.expected { t.Errorf("normalizeCommandPath(%q) = %q, want %q", tt.input, result, tt.expected) } }) } } // --- buildArgs tests --- func TestBuildArgs(t *testing.T) { // Save and restore the output format origFormat := util.GetOutputFormat() defer util.SetOutputFormat(origFormat) tests := []struct { name string cmdPath string flags map[string]any outputFormat string // configured default output format wantContains []string wantMissing []string }{ { name: "simple command with default json output", cmdPath: "get/plan", outputFormat: "json", wantContains: []string{"get", "plan", "--output", "json"}, }, { name: "with namespace in flags", cmdPath: "get/plan", flags: map[string]any{"namespace": "demo"}, outputFormat: "json", wantContains: []string{"get", "plan", "--namespace", "demo"}, }, { name: "with all_namespaces in flags", cmdPath: "get/plan", flags: map[string]any{"all_namespaces": true}, outputFormat: "json", wantContains: []string{"get", "plan", "--all-namespaces"}, }, { name: "with provider in flags", cmdPath: "get/inventory/vm", flags: map[string]any{"provider": "my-provider"}, outputFormat: "json", wantContains: []string{"get", "inventory", "vm", "--provider", "my-provider"}, }, { name: "with inventory_url in flags", cmdPath: "get/inventory/vm", flags: map[string]any{"provider": "my-provider", "inventory_url": "http://localhost:9090"}, outputFormat: "json", wantContains: []string{"--inventory-url", "http://localhost:9090"}, }, { name: "user output overrides default", cmdPath: "get/plan", flags: map[string]any{"output": "yaml"}, outputFormat: "json", wantContains: []string{"--output", "yaml"}, wantMissing: []string{"--output json"}, }, { name: "text output format omits --output flag", cmdPath: "get/plan", outputFormat: "text", wantContains: []string{"get", "plan"}, wantMissing: []string{"--output"}, }, { name: "custom flags are passed through", cmdPath: "get/inventory/vm", flags: map[string]any{"provider": "my-provider", "query": "where name ~= 'prod-.*'", "extended": true}, outputFormat: "json", wantContains: []string{"--query", "--extended"}, }, { name: "namespace extracted from flags not duplicated", cmdPath: "get/plan", flags: map[string]any{"namespace": "real-ns"}, outputFormat: "json", wantContains: []string{"--namespace", "real-ns"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { util.SetOutputFormat(tt.outputFormat) result := buildArgs(tt.cmdPath, tt.flags) joined := strings.Join(result, " ") for _, want := range tt.wantContains { if !strings.Contains(joined, want) { t.Errorf("buildArgs() = %v, should contain %q", result, want) } } for _, notWant := range tt.wantMissing { if strings.Contains(joined, notWant) { t.Errorf("buildArgs() = %v, should NOT contain %q", result, notWant) } } }) } } // --- appendNormalizedFlags tests --- func TestAppendNormalizedFlags(t *testing.T) { tests := []struct { name string flags map[string]any skipFlags map[string]bool wantContains []string wantMissing []string }{ { name: "bool true becomes presence flag", flags: map[string]any{"extended": true}, wantContains: []string{"--extended"}, }, { name: "bool false becomes explicit false", flags: map[string]any{"migrate-shared-disks": false}, wantContains: []string{"--migrate-shared-disks=false"}, }, { name: "string true treated as bool", flags: map[string]any{"watch": "true"}, wantContains: []string{"--watch"}, }, { name: "string false treated as bool", flags: map[string]any{"watch": "false"}, wantContains: []string{"--watch=false"}, }, { name: "string value", flags: map[string]any{"query": "where name = 'test'"}, wantContains: []string{"--query", "where name = 'test'"}, }, { name: "empty string is skipped", flags: map[string]any{"query": ""}, wantMissing: []string{"--query"}, }, { name: "float64 whole number no decimals", flags: map[string]any{"tail-lines": float64(500)}, wantContains: []string{"--tail-lines", "500"}, wantMissing: []string{"500."}, }, { name: "float64 fractional", flags: map[string]any{"ratio": float64(0.75)}, wantContains: []string{"--ratio", "0.75"}, }, { name: "single char key uses single dash", flags: map[string]any{"n": "demo"}, wantContains: []string{"-n", "demo"}, wantMissing: []string{"--n"}, }, { name: "nil value is skipped", flags: map[string]any{"something": nil}, wantMissing: []string{"--something"}, }, { name: "skip set respected", flags: map[string]any{"namespace": "should-skip", "query": "keep-me"}, skipFlags: map[string]bool{"namespace": true}, wantContains: []string{"--query", "keep-me"}, wantMissing: []string{"--namespace"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := appendNormalizedFlags(nil, tt.flags, tt.skipFlags) joined := strings.Join(result, " ") for _, want := range tt.wantContains { if !strings.Contains(joined, want) { t.Errorf("appendNormalizedFlags() = %v, should contain %q", result, want) } } for _, notWant := range tt.wantMissing { if strings.Contains(joined, notWant) { t.Errorf("appendNormalizedFlags() = %v, should NOT contain %q", result, notWant) } } }) } } // --- validateCommandInput tests --- func TestValidateCommandInput(t *testing.T) { tests := []struct { name string input string wantError string }{ { name: "valid simple command", input: "get plan", }, { name: "valid inventory command", input: "get inventory vm", }, { name: "valid single word", input: "health", }, { name: "full CLI command with kubectl-mtv prefix", input: "kubectl-mtv get plan --namespace demo", wantError: "subcommand path", }, { name: "full CLI command with kubectl prefix", input: "kubectl get pods", wantError: "subcommand path", }, { name: "embedded tool output with return_value", input: `get plan {"return_value": 0, "output": "..."}`, wantError: "previous tool response", }, { name: "embedded tool output with stdout", input: `{"stdout": "some output"}`, wantError: "previous tool response", }, { name: "embedded TOOL_CALLS marker", input: `get plan[TOOL_CALLS]more stuff`, wantError: "previous tool response", }, { name: "overly long command string", input: strings.Repeat("a", 201), wantError: "too long", }, { name: "command at exactly 200 chars is ok", input: strings.Repeat("a", 200), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validateCommandInput(tt.input) if tt.wantError == "" { if err != nil { t.Errorf("unexpected error: %v", err) } } else { if err == nil { t.Fatal("expected error, got nil") } if !strings.Contains(err.Error(), tt.wantError) { t.Errorf("error = %q, should contain %q", err.Error(), tt.wantError) } } }) } } // --- Handler validation error tests --- func TestHandleMTVRead_ValidationErrors(t *testing.T) { registry := testRegistry() handler := HandleMTVRead(registry) ctx := context.Background() req := &mcp.CallToolRequest{} tests := []struct { name string input MTVReadInput wantError string }{ { name: "unknown command", input: MTVReadInput{Command: "nonexistent command"}, wantError: "unknown command", }, { name: "write command rejected", input: MTVReadInput{Command: "create plan"}, wantError: "write operation", }, { name: "full CLI command rejected", input: MTVReadInput{Command: "kubectl-mtv get plan --namespace demo"}, wantError: "subcommand path", }, { name: "embedded tool output rejected", input: MTVReadInput{Command: `get plan {"return_value": 0}`}, wantError: "previous tool response", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, _, err := handler(ctx, req, tt.input) if err == nil { t.Fatal("expected error, got nil") } if !strings.Contains(err.Error(), tt.wantError) { t.Errorf("error = %q, should contain %q", err.Error(), tt.wantError) } }) } } // --- Handler DryRun tests --- func TestHandleMTVRead_DryRun(t *testing.T) { registry := testRegistry() handler := HandleMTVRead(registry) ctx := context.Background() req := &mcp.CallToolRequest{} // Save and restore the output format origFormat := util.GetOutputFormat() defer util.SetOutputFormat(origFormat) util.SetOutputFormat("json") tests := []struct { name string input MTVReadInput wantContains []string }{ { name: "get plan with namespace", input: MTVReadInput{ Command: "get plan", Flags: map[string]any{"namespace": "demo"}, DryRun: true, }, wantContains: []string{"kubectl-mtv", "get", "plan", "--namespace", "demo", "--output", "json"}, }, { name: "get plan all namespaces", input: MTVReadInput{ Command: "get plan", Flags: map[string]any{"all_namespaces": true}, DryRun: true, }, wantContains: []string{"kubectl-mtv", "get", "plan", "--all-namespaces"}, }, { name: "get inventory vm with provider via flag", input: MTVReadInput{ Command: "get inventory vm", Flags: map[string]any{"provider": "my-vsphere"}, DryRun: true, }, wantContains: []string{"kubectl-mtv", "get", "inventory", "vm", "--provider", "my-vsphere"}, }, { name: "describe plan with name via flag", input: MTVReadInput{ Command: "describe plan", Flags: map[string]any{"name": "my-plan", "namespace": "test-ns"}, DryRun: true, }, wantContains: []string{"kubectl-mtv", "describe", "plan", "--name", "my-plan", "--namespace", "test-ns"}, }, { name: "health check", input: MTVReadInput{ Command: "health", DryRun: true, }, wantContains: []string{"kubectl-mtv", "health"}, }, { name: "with inventory URL", input: MTVReadInput{ Command: "get inventory vm", Flags: map[string]any{"provider": "my-provider", "inventory_url": "http://localhost:9090"}, DryRun: true, }, wantContains: []string{"--inventory-url", "http://localhost:9090"}, }, { name: "with custom flags", input: MTVReadInput{ Command: "get inventory vm", Flags: map[string]any{"provider": "my-provider", "extended": true}, DryRun: true, }, wantContains: []string{"--extended"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, data, err := handler(ctx, req, tt.input) if err != nil { t.Fatalf("unexpected error: %v", err) } dataMap, ok := data.(map[string]interface{}) if !ok { t.Fatalf("expected map[string]interface{}, got %T", data) } // In dry-run mode, the CLI command is in "output" (command field is stripped) output, ok := dataMap["output"].(string) if !ok { t.Fatal("response should have 'output' string field in dry-run mode") } // "command" field should NOT be present (stripped to prevent CLI mimicry) if _, exists := dataMap["command"]; exists { t.Error("response should NOT contain 'command' field (stripped to help small LLMs)") } for _, want := range tt.wantContains { if !strings.Contains(output, want) { t.Errorf("output = %q, should contain %q", output, want) } } }) } } // buildTestBinary builds the kubectl-mtv binary from source into a temp directory // and returns its path. The binary is cached for the duration of the test. func buildTestBinary(t *testing.T) string { t.Helper() binary := t.TempDir() + "/kubectl-mtv" ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "go", "build", "-o", binary, ".") cmd.Dir = findRepoRoot(t) out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Failed to build kubectl-mtv from source: %v\n%s", err, out) } return binary } // findRepoRoot walks up from the test file to find the repo root (where go.mod is). func findRepoRoot(t *testing.T) string { t.Helper() // We know the test is at pkg/mcp/tools/ so repo root is 4 levels up // Use go list instead for reliability cmd := exec.Command("go", "list", "-m", "-f", "{{.Dir}}") out, err := cmd.Output() if err != nil { t.Fatalf("Failed to find repo root: %v", err) } return strings.TrimSpace(string(out)) } // newRegistryFromBinary runs the given kubectl-mtv binary with help --machine // plus optional extra args and builds a Registry from the output. func newRegistryFromBinary(t *testing.T, binary string, extraArgs ...string) *discovery.Registry { t.Helper() args := append([]string{"help", "--machine"}, extraArgs...) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() cmd := exec.CommandContext(ctx, binary, args...) output, err := cmd.Output() if err != nil { t.Skipf("Skipping: binary %s not available: %v", binary, err) } var schema discovery.HelpSchema if err := json.Unmarshal(output, &schema); err != nil { t.Fatalf("Failed to parse help schema: %v", err) } registry := &discovery.Registry{ ReadOnly: make(map[string]*discovery.Command), ReadWrite: make(map[string]*discovery.Command), GlobalFlags: schema.GlobalFlags, RootDescription: schema.Description, } for i := range schema.Commands { cmd := &schema.Commands[i] pathKey := cmd.PathKey() switch cmd.Category { case "read": registry.ReadOnly[pathKey] = cmd default: registry.ReadWrite[pathKey] = cmd } } return registry } // toolSizes holds the size metrics for a single tool description. type toolSizes struct { name string chars int lines int } // TestLiveToolContextSize builds the kubectl-mtv binary from source, discovers // commands, and compares the OLD (full) vs NEW (minimal + mtv_help) tool // descriptions that would be sent to an AI agent. // // Run with: go test -v -run TestLiveToolContextSize ./pkg/mcp/tools/ func TestLiveToolContextSize(t *testing.T) { // Build kubectl-mtv from source to ensure latest code is tested binary := buildTestBinary(t) registry := newRegistryFromBinary(t, binary) // --- OLD mode: full descriptions (2 tools) --- oldRead := registry.GenerateReadOnlyDescription() oldWrite := registry.GenerateReadWriteDescription() oldTools := []toolSizes{ {name: "mtv_read", chars: len(oldRead), lines: strings.Count(oldRead, "\n") + 1}, {name: "mtv_write", chars: len(oldWrite), lines: strings.Count(oldWrite, "\n") + 1}, } // --- NEW mode: minimal descriptions (5 tools) --- newRead := registry.GenerateMinimalReadOnlyDescription() newWrite := registry.GenerateMinimalReadWriteDescription() newLogs := GetMinimalKubectlLogsTool().Description newKubectl := GetMinimalKubectlTool().Description newHelp := GetMTVHelpTool().Description newTools := []toolSizes{ {name: "mtv_read", chars: len(newRead), lines: strings.Count(newRead, "\n") + 1}, {name: "mtv_write", chars: len(newWrite), lines: strings.Count(newWrite, "\n") + 1}, {name: "kubectl_logs", chars: len(newLogs), lines: strings.Count(newLogs, "\n") + 1}, {name: "kubectl", chars: len(newKubectl), lines: strings.Count(newKubectl, "\n") + 1}, {name: "mtv_help", chars: len(newHelp), lines: strings.Count(newHelp, "\n") + 1}, } // --- Report --- t.Logf("=== MCP Tool Context Size Report (live kubectl-mtv) ===") t.Logf("") oldTotal := 0 t.Logf("--- OLD mode (full descriptions, 2 tools) ---") for _, ts := range oldTools { t.Logf(" %-20s %6d chars %4d lines ~%d tokens", ts.name, ts.chars, ts.lines, ts.chars/4) oldTotal += ts.chars } t.Logf(" %-20s %6d chars ~%d tokens", "TOTAL", oldTotal, oldTotal/4) t.Logf("") newTotal := 0 t.Logf("--- NEW mode (minimal + mtv_help, 5 tools) ---") for _, ts := range newTools { t.Logf(" %-20s %6d chars %4d lines ~%d tokens", ts.name, ts.chars, ts.lines, ts.chars/4) newTotal += ts.chars } t.Logf(" %-20s %6d chars ~%d tokens", "TOTAL", newTotal, newTotal/4) t.Logf("") saved := oldTotal - newTotal pct := float64(saved) / float64(oldTotal) * 100 t.Logf("--- SAVINGS ---") t.Logf(" Saved: %d chars / ~%d tokens (%.1f%% reduction)", saved, saved/4, pct) t.Logf(" Read commands: %d", len(registry.ReadOnly)) t.Logf(" Write commands: %d", len(registry.ReadWrite)) t.Logf("====================================================") // Dump new minimal descriptions for inspection t.Logf("") t.Logf("--- [NEW] mtv_read description ---") t.Logf("\n%s", newRead) t.Logf("--- [NEW] mtv_write description ---") t.Logf("\n%s", newWrite) t.Logf("--- [NEW] kubectl_logs description ---") t.Logf("\n%s", newLogs) t.Logf("--- [NEW] kubectl description ---") t.Logf("\n%s", newKubectl) t.Logf("--- [NEW] mtv_help description ---") t.Logf("\n%s", newHelp) } // --- filterResponseFields tests --- func TestFilterResponseFields_ArrayData(t *testing.T) { data := map[string]interface{}{ "return_value": float64(0), "data": []interface{}{ map[string]interface{}{ "name": "vm-1", "id": "vm-101", "powerState": "poweredOn", "concerns": []interface{}{"cbt-disabled"}, "memoryMB": 2048, "disks": []interface{}{"disk-1", "disk-2"}, }, map[string]interface{}{ "name": "vm-2", "id": "vm-102", "powerState": "poweredOff", "concerns": []interface{}{}, "memoryMB": 4096, "disks": []interface{}{"disk-3"}, }, }, } result := filterResponseFields(data, []string{"name", "id", "concerns"}) // Envelope fields should be preserved if result["return_value"] != float64(0) { t.Error("return_value envelope field should be preserved") } // Data should be filtered items, ok := result["data"].([]interface{}) if !ok { t.Fatal("data should be []interface{}") } if len(items) != 2 { t.Fatalf("expected 2 items, got %d", len(items)) } // First item: only name, id, concerns item0 := items[0].(map[string]interface{}) if item0["name"] != "vm-1" { t.Errorf("item[0].name = %v, want vm-1", item0["name"]) } if item0["id"] != "vm-101" { t.Errorf("item[0].id = %v, want vm-101", item0["id"]) } if _, exists := item0["concerns"]; !exists { t.Error("item[0].concerns should exist") } // Excluded fields should be absent if _, exists := item0["powerState"]; exists { t.Error("item[0].powerState should be filtered out") } if _, exists := item0["memoryMB"]; exists { t.Error("item[0].memoryMB should be filtered out") } if _, exists := item0["disks"]; exists { t.Error("item[0].disks should be filtered out") } } func TestFilterResponseFields_ObjectData(t *testing.T) { data := map[string]interface{}{ "return_value": float64(0), "data": map[string]interface{}{ "overallStatus": "Healthy", "pods": []interface{}{"pod-1", "pod-2"}, "providers": []interface{}{"prov-1"}, "operator": map[string]interface{}{"version": "2.10.4"}, }, } result := filterResponseFields(data, []string{"overallStatus", "providers"}) obj, ok := result["data"].(map[string]interface{}) if !ok { t.Fatal("data should be map[string]interface{}") } if obj["overallStatus"] != "Healthy" { t.Errorf("overallStatus = %v, want Healthy", obj["overallStatus"]) } if _, exists := obj["providers"]; !exists { t.Error("providers should exist") } if _, exists := obj["pods"]; exists { t.Error("pods should be filtered out") } if _, exists := obj["operator"]; exists { t.Error("operator should be filtered out") } } func TestFilterResponseFields_EmptyFields(t *testing.T) { data := map[string]interface{}{ "return_value": float64(0), "data": []interface{}{ map[string]interface{}{"name": "vm-1", "id": "vm-101"}, }, } result := filterResponseFields(data, []string{}) // With empty fields, data should be unchanged items := result["data"].([]interface{}) item0 := items[0].(map[string]interface{}) if item0["name"] != "vm-1" { t.Error("data should not be modified when fields is empty") } if item0["id"] != "vm-101" { t.Error("data should not be modified when fields is empty") } } func TestFilterResponseFields_NoDataKey(t *testing.T) { data := map[string]interface{}{ "return_value": float64(0), "output": "some plain text output", } result := filterResponseFields(data, []string{"name", "id"}) // When there's no "data" key, the response should be unchanged if result["output"] != "some plain text output" { t.Error("output should be preserved when no data key exists") } } func TestFilterResponseFields_NonObjectItems(t *testing.T) { data := map[string]interface{}{ "return_value": float64(0), "data": []interface{}{ "string-item", float64(42), map[string]interface{}{"name": "vm-1", "id": "vm-101", "extra": "value"}, }, } result := filterResponseFields(data, []string{"name"}) items := result["data"].([]interface{}) if len(items) != 3 { t.Fatalf("expected 3 items, got %d", len(items)) } // Non-object items kept as-is if items[0] != "string-item" { t.Errorf("string item should be preserved, got %v", items[0]) } if items[1] != float64(42) { t.Errorf("number item should be preserved, got %v", items[1]) } // Object item filtered obj := items[2].(map[string]interface{}) if obj["name"] != "vm-1" { t.Error("name should be kept") } if _, exists := obj["id"]; exists { t.Error("id should be filtered out") } if _, exists := obj["extra"]; exists { t.Error("extra should be filtered out") } } // --- buildCLIErrorResult tests --- func TestBuildCLIErrorResult_Success(t *testing.T) { // return_value == 0 should return nil (no error) data := map[string]interface{}{ "return_value": float64(0), "data": []interface{}{}, } result := buildCLIErrorResult(data) if result != nil { t.Error("return_value 0 should not produce an error result") } } func TestBuildCLIErrorResult_MissingReturnValue(t *testing.T) { // No return_value key should return nil (no error) data := map[string]interface{}{} result := buildCLIErrorResult(data) if result != nil { t.Error("missing return_value should not produce an error result") } } func TestBuildCLIErrorResult_NonZeroExit(t *testing.T) { data := map[string]interface{}{ "return_value": float64(1), "stderr": "Error: failed to get provider 'vsphere-provider': providers.forklift.konveyor.io \"vsphere-provider\" not found\n", "stdout": "", } result := buildCLIErrorResult(data) if result == nil { t.Fatal("non-zero return_value should produce an error result") } if !result.IsError { t.Error("result.IsError should be true") } if len(result.Content) == 0 { t.Fatal("result should have content") } text, ok := result.Content[0].(*mcp.TextContent) if !ok { t.Fatalf("content should be TextContent, got %T", result.Content[0]) } // Should contain exit code and stderr message if !strings.Contains(text.Text, "exit 1") { t.Errorf("error text should contain exit code, got: %s", text.Text) } if !strings.Contains(text.Text, "vsphere-provider") { t.Errorf("error text should contain stderr message, got: %s", text.Text) } } func TestBuildCLIErrorResult_NoStderr(t *testing.T) { data := map[string]interface{}{ "return_value": float64(2), "stderr": "", } result := buildCLIErrorResult(data) if result == nil { t.Fatal("non-zero return_value should produce an error result") } if !result.IsError { t.Error("result.IsError should be true") } text := result.Content[0].(*mcp.TextContent) if !strings.Contains(text.Text, "exit 2") { t.Errorf("error text should contain exit code, got: %s", text.Text) } } func TestBuildCLIErrorResult_StderrOnly(t *testing.T) { data := map[string]interface{}{ "return_value": float64(1), "stderr": "some error", } result := buildCLIErrorResult(data) if result == nil { t.Fatal("non-zero return_value should produce an error result") } text := result.Content[0].(*mcp.TextContent) if !strings.Contains(text.Text, "some error") { t.Errorf("error text should contain stderr, got: %s", text.Text) } if !strings.Contains(text.Text, "exit 1") { t.Errorf("error text should contain exit code, got: %s", text.Text) } } func TestFilterMapFields(t *testing.T) { m := map[string]interface{}{ "name": "test-vm", "id": "vm-123", "powerState": "poweredOn", "memoryMB": 2048, "concerns": []interface{}{"issue1"}, } allowed := map[string]bool{"name": true, "concerns": true} result := filterMapFields(m, allowed) if len(result) != 2 { t.Errorf("expected 2 fields, got %d", len(result)) } if result["name"] != "test-vm" { t.Errorf("name = %v, want test-vm", result["name"]) } if _, exists := result["concerns"]; !exists { t.Error("concerns should exist") } if _, exists := result["powerState"]; exists { t.Error("powerState should be filtered out") } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/mtv_write.go
Go
package tools import ( "context" "fmt" "strings" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/discovery" "github.com/yaacov/kubectl-mtv/pkg/mcp/util" ) // MTVWriteInput represents the input for the mtv_write tool. type MTVWriteInput struct { Command string `json:"command" jsonschema:"Command path (e.g. create provider, delete plan, patch mapping)"` Flags map[string]any `json:"flags,omitempty" jsonschema:"All parameters including positional args and options (e.g. name: \"my-provider\", type: \"vsphere\", url: \"https://vcenter/sdk\", namespace: \"ns\")"` DryRun bool `json:"dry_run,omitempty" jsonschema:"If true, does not execute. Returns the equivalent CLI command in the output field instead"` } // GetUltraMinimalMTVWriteTool returns the smallest possible tool definition for read-write // MTV commands, optimized for very small models (< 8B parameters). func GetUltraMinimalMTVWriteTool(registry *discovery.Registry) *mcp.Tool { description := registry.GenerateUltraMinimalReadWriteDescription() return &mcp.Tool{ Name: "mtv_write", Description: description, OutputSchema: mtvOutputSchema, } } // GetMTVWriteTool returns the tool definition for read-write MTV commands. func GetMTVWriteTool(registry *discovery.Registry) *mcp.Tool { description := registry.GenerateReadWriteDescription() return &mcp.Tool{ Name: "mtv_write", Description: description, OutputSchema: mtvOutputSchema, } } // GetMinimalMTVWriteTool returns a minimal tool definition for read-write MTV commands. // The input schema (jsonschema tags on MTVWriteInput) already describes parameters. // The description only lists available commands and hints to use mtv_help. func GetMinimalMTVWriteTool(registry *discovery.Registry) *mcp.Tool { description := registry.GenerateMinimalReadWriteDescription() return &mcp.Tool{ Name: "mtv_write", Description: description, OutputSchema: mtvOutputSchema, } } // HandleMTVWrite returns a handler function for the mtv_write tool. func HandleMTVWrite(registry *discovery.Registry) func(context.Context, *mcp.CallToolRequest, MTVWriteInput) (*mcp.CallToolResult, any, error) { return func(ctx context.Context, req *mcp.CallToolRequest, input MTVWriteInput) (*mcp.CallToolResult, any, error) { // Extract K8s credentials from HTTP headers (populated by wrapper in SSE mode) ctx = extractKubeCredsFromRequest(ctx, req) // Validate input to catch common small-LLM mistakes early if err := validateCommandInput(input.Command); err != nil { return nil, nil, err } // Normalize command path cmdPath := normalizeCommandPath(input.Command) // Validate command exists and is read-write if !registry.IsReadWrite(cmdPath) { if registry.IsReadOnly(cmdPath) { return nil, nil, fmt.Errorf("command '%s' is a read-only operation, use mtv_read tool instead", input.Command) } // List available commands in error, converting path keys to user-friendly format available := registry.ListReadWriteCommands() for i, cmd := range available { available[i] = strings.ReplaceAll(cmd, "/", " ") } return nil, nil, fmt.Errorf("unknown command '%s'. Available write commands: %s", input.Command, strings.Join(available, ", ")) } // Enable dry run mode if requested if input.DryRun { ctx = util.WithDryRun(ctx, true) } // Build command arguments (all params passed via flags) args := buildWriteArgs(cmdPath, input.Flags) // Execute command result, err := util.RunKubectlMTVCommand(ctx, args) if err != nil { return nil, nil, fmt.Errorf("command failed: %w", err) } // Parse and return result data, err := util.UnmarshalJSONResponse(result) if err != nil { return nil, nil, err } // Check for CLI errors and surface as MCP IsError response if errResult := buildCLIErrorResult(data); errResult != nil { return errResult, nil, nil } return nil, data, nil } } // buildWriteArgs builds the command-line arguments for kubectl-mtv write commands. // All parameters (namespace, name, etc.) are extracted from the flags map. func buildWriteArgs(cmdPath string, flags map[string]any) []string { var args []string // Add command path parts parts := strings.Split(cmdPath, "/") args = append(args, parts...) // Extract namespace from flags var namespace string if flags != nil { if v, ok := flags["namespace"]; ok { namespace = fmt.Sprintf("%v", v) } else if v, ok := flags["n"]; ok { namespace = fmt.Sprintf("%v", v) } } // Add namespace flag if namespace != "" { args = append(args, "--namespace", namespace) } // Note: Write commands typically don't support --output json output format // so we don't add it automatically like we do for read commands // Skip set for already handled flags skipFlags := map[string]bool{ "namespace": true, "n": true, } // Add other flags using the normalizer args = appendNormalizedFlags(args, flags, skipFlags) return args }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/tools/mtv_write_test.go
Go
package tools import ( "context" "strings" "testing" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/yaacov/kubectl-mtv/pkg/mcp/discovery" ) // --- Tool definition tests --- func TestGetMTVWriteTool(t *testing.T) { registry := testRegistry() tool := GetMTVWriteTool(registry) if tool.Name != "mtv_write" { t.Errorf("Name = %q, want %q", tool.Name, "mtv_write") } if tool.Description == "" { t.Error("Description should not be empty") } // Description should reference write commands for _, keyword := range []string{"create provider", "create plan"} { if !strings.Contains(tool.Description, keyword) { t.Errorf("Description should contain %q", keyword) } } // OutputSchema should have expected properties schema, ok := tool.OutputSchema.(map[string]any) if !ok { t.Fatal("OutputSchema should be a map") } props, ok := schema["properties"].(map[string]any) if !ok { t.Fatal("OutputSchema should have properties") } for _, key := range []string{"return_value", "data", "output", "stderr"} { if _, exists := props[key]; !exists { t.Errorf("OutputSchema.properties should contain %q", key) } } // "command" should NOT be in the output schema (stripped to prevent CLI mimicry) if _, exists := props["command"]; exists { t.Error("OutputSchema.properties should NOT contain 'command' (stripped to help small LLMs)") } } // --- buildWriteArgs tests --- func TestBuildWriteArgs(t *testing.T) { tests := []struct { name string cmdPath string flags map[string]any wantContains []string wantMissing []string }{ { name: "simple command", cmdPath: "create/provider", wantContains: []string{"create", "provider"}, }, { name: "with name in flags", cmdPath: "delete/plan", flags: map[string]any{"name": "my-plan"}, wantContains: []string{"delete", "plan", "--name", "my-plan"}, }, { name: "with namespace in flags", cmdPath: "start/plan", flags: map[string]any{"name": "my-plan", "namespace": "demo"}, wantContains: []string{"start", "plan", "--name", "my-plan", "--namespace", "demo"}, }, { name: "with flags", cmdPath: "create/provider", flags: map[string]any{ "name": "my-provider", "type": "vsphere", "url": "https://vcenter.example.com", "provider-insecure-skip-tls": true, }, wantContains: []string{"create", "provider", "--name", "my-provider", "--type", "vsphere", "--url", "--provider-insecure-skip-tls"}, }, { name: "does not auto-add output format", cmdPath: "create/plan", flags: map[string]any{"name": "test-plan"}, wantContains: []string{"create", "plan", "--name", "test-plan"}, wantMissing: []string{"--output"}, }, { name: "namespace extracted from flags not duplicated", cmdPath: "start/plan", flags: map[string]any{"name": "my-plan", "namespace": "real-ns"}, wantContains: []string{"--namespace", "real-ns"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := buildWriteArgs(tt.cmdPath, tt.flags) joined := strings.Join(result, " ") for _, want := range tt.wantContains { if !strings.Contains(joined, want) { t.Errorf("buildWriteArgs() = %v, should contain %q", result, want) } } for _, notWant := range tt.wantMissing { if strings.Contains(joined, notWant) { t.Errorf("buildWriteArgs() = %v, should NOT contain %q", result, notWant) } } }) } } // --- Handler validation error tests --- func TestHandleMTVWrite_ValidationErrors(t *testing.T) { registry := testRegistry() handler := HandleMTVWrite(registry) ctx := context.Background() req := &mcp.CallToolRequest{} tests := []struct { name string input MTVWriteInput wantError string }{ { name: "unknown command", input: MTVWriteInput{Command: "nonexistent command"}, wantError: "unknown command", }, { name: "read command rejected", input: MTVWriteInput{Command: "get plan"}, wantError: "read-only operation", }, { name: "full CLI command rejected", input: MTVWriteInput{Command: "kubectl-mtv create provider --name test"}, wantError: "subcommand path", }, { name: "embedded tool output rejected", input: MTVWriteInput{Command: `create plan {"output": "something"}`}, wantError: "previous tool response", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, _, err := handler(ctx, req, tt.input) if err == nil { t.Fatal("expected error, got nil") } if !strings.Contains(err.Error(), tt.wantError) { t.Errorf("error = %q, should contain %q", err.Error(), tt.wantError) } }) } } // --- Handler DryRun tests --- func TestHandleMTVWrite_DryRun(t *testing.T) { registry := &discovery.Registry{ ReadOnly: map[string]*discovery.Command{ "get/plan": {Path: []string{"get", "plan"}, PathString: "get plan", Description: "Get plans"}, }, ReadWrite: map[string]*discovery.Command{ "create/provider": { Path: []string{"create", "provider"}, PathString: "create provider", Description: "Create provider", }, "delete/plan": { Path: []string{"delete", "plan"}, PathString: "delete plan", Description: "Delete plan", }, "start/plan": { Path: []string{"start", "plan"}, PathString: "start plan", Description: "Start plan", }, }, } handler := HandleMTVWrite(registry) ctx := context.Background() req := &mcp.CallToolRequest{} tests := []struct { name string input MTVWriteInput wantContains []string }{ { name: "create provider with flags", input: MTVWriteInput{ Command: "create provider", Flags: map[string]any{ "name": "my-vsphere", "type": "vsphere", "url": "https://vcenter.example.com", }, DryRun: true, }, wantContains: []string{"kubectl-mtv", "create", "provider", "--name", "my-vsphere", "--type", "vsphere", "--url"}, }, { name: "delete plan with name and namespace", input: MTVWriteInput{ Command: "delete plan", Flags: map[string]any{"name": "old-plan", "namespace": "demo"}, DryRun: true, }, wantContains: []string{"kubectl-mtv", "delete", "plan", "old-plan", "--namespace", "demo"}, }, { name: "start plan with named arg", input: MTVWriteInput{ Command: "start plan", Flags: map[string]any{"name": "my-plan"}, DryRun: true, }, wantContains: []string{"kubectl-mtv", "start", "plan", "my-plan"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, data, err := handler(ctx, req, tt.input) if err != nil { t.Fatalf("unexpected error: %v", err) } dataMap, ok := data.(map[string]interface{}) if !ok { t.Fatalf("expected map[string]interface{}, got %T", data) } // In dry-run mode, the CLI command is in "output" (command field is stripped) output, ok := dataMap["output"].(string) if !ok { t.Fatal("response should have 'output' string field in dry-run mode") } for _, want := range tt.wantContains { if !strings.Contains(output, want) { t.Errorf("output = %q, should contain %q", output, want) } } }) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/util/util.go
Go
package util import ( "bytes" "context" "encoding/json" "fmt" "log" "net/http" "os" "os/exec" "regexp" "strings" "time" shellquote "github.com/kballard/go-shellquote" ) // contextKey is a custom type for context keys to avoid collisions type contextKey string const ( // kubeconfigTokenKey is the context key for Kubernetes token kubeconfigTokenKey contextKey = "kubeconfig_token" // kubeconfigServerKey is the context key for Kubernetes API server URL kubeconfigServerKey contextKey = "kubeconfig_server" // dryRunKey is the context key for dry run mode dryRunKey contextKey = "dry_run" ) // WithKubeToken adds a Kubernetes token to the context func WithKubeToken(ctx context.Context, token string) context.Context { return context.WithValue(ctx, kubeconfigTokenKey, token) } // GetKubeToken retrieves the Kubernetes token from the context func GetKubeToken(ctx context.Context) (string, bool) { if ctx == nil { return "", false } token, ok := ctx.Value(kubeconfigTokenKey).(string) return token, ok } // WithKubeServer adds a Kubernetes API server URL to the context func WithKubeServer(ctx context.Context, server string) context.Context { return context.WithValue(ctx, kubeconfigServerKey, server) } // GetKubeServer retrieves the Kubernetes API server URL from the context func GetKubeServer(ctx context.Context) (string, bool) { if ctx == nil { return "", false } server, ok := ctx.Value(kubeconfigServerKey).(string) return server, ok } // WithKubeCredsFromHeaders extracts Kubernetes credentials from HTTP headers // and adds them to the context. Supported headers: // - Authorization: Bearer <token> - extracted and added via WithKubeToken // - X-Kubernetes-Server: <url> - extracted and added via WithKubeServer // // If headers are nil or the specific headers are not present, the context // is returned unchanged (fallback to default kubeconfig behavior). func WithKubeCredsFromHeaders(ctx context.Context, headers http.Header) context.Context { if headers == nil { return ctx } // Extract Authorization Bearer token if auth := headers.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") { token := strings.TrimPrefix(auth, "Bearer ") if token != "" { ctx = WithKubeToken(ctx, token) } } // Extract Kubernetes API server URL if server := headers.Get("X-Kubernetes-Server"); server != "" { ctx = WithKubeServer(ctx, server) } return ctx } // WithDryRun adds a dry run flag to the context func WithDryRun(ctx context.Context, dryRun bool) context.Context { return context.WithValue(ctx, dryRunKey, dryRun) } // GetDryRun retrieves the dry run flag from the context func GetDryRun(ctx context.Context) bool { if ctx == nil { return false } dryRun, ok := ctx.Value(dryRunKey).(bool) return ok && dryRun } // outputFormat stores the configured output format for MCP responses var outputFormat = "text" // maxResponseChars limits the size of text output returned to the LLM. // Long responses fill the context window and increase the chance of small LLMs // losing track of the tool protocol. When > 0, the "output" field is truncated // to this many characters with a hint to use structured queries. // 0 means no truncation (default). var maxResponseChars int // SetMaxResponseChars sets the maximum number of characters for text output. // 0 disables truncation. func SetMaxResponseChars(n int) { maxResponseChars = n } // GetMaxResponseChars returns the configured max response chars limit. func GetMaxResponseChars() int { return maxResponseChars } // SetOutputFormat sets the output format for MCP responses. // Valid values are "text" (default, table output) or "json". func SetOutputFormat(format string) { if format == "" { outputFormat = "text" } else { outputFormat = format } } // GetOutputFormat returns the configured output format for MCP responses. func GetOutputFormat() string { return outputFormat } // defaultKubeServer stores the default Kubernetes API server URL set via CLI flags. // This is used as a fallback when no server URL is provided in the request context (HTTP headers). var defaultKubeServer string // SetDefaultKubeServer sets the default Kubernetes API server URL from CLI flags. func SetDefaultKubeServer(server string) { defaultKubeServer = server } // GetDefaultKubeServer returns the default Kubernetes API server URL set via CLI flags. func GetDefaultKubeServer() string { return defaultKubeServer } // defaultKubeToken stores the default Kubernetes authentication token set via CLI flags. // This is used as a fallback when no token is provided in the request context (HTTP headers). var defaultKubeToken string // SetDefaultKubeToken sets the default Kubernetes authentication token from CLI flags. func SetDefaultKubeToken(token string) { defaultKubeToken = token } // GetDefaultKubeToken returns the default Kubernetes authentication token set via CLI flags. func GetDefaultKubeToken() string { return defaultKubeToken } // defaultInsecureSkipTLS stores whether to skip TLS verification for Kubernetes API connections. // When true, --insecure-skip-tls-verify is prepended to every subprocess invocation. var defaultInsecureSkipTLS bool // SetDefaultInsecureSkipTLS sets the default TLS skip verification flag. func SetDefaultInsecureSkipTLS(skip bool) { defaultInsecureSkipTLS = skip } // GetDefaultInsecureSkipTLS returns whether TLS verification should be skipped. func GetDefaultInsecureSkipTLS() bool { return defaultInsecureSkipTLS } // CommandResponse represents the structured response from command execution type CommandResponse struct { Command string `json:"command"` ReturnValue int `json:"return_value"` Stdout string `json:"stdout"` Stderr string `json:"stderr"` } // selfExePath caches the path to the currently running executable. // This ensures the MCP server always calls its own binary rather than // whatever "kubectl-mtv" happens to be on PATH (which may be an older version). var selfExePath = func() string { exe, err := os.Executable() if err != nil { return "kubectl-mtv" // fallback to PATH lookup } return exe }() // RunKubectlMTVCommand executes a kubectl-mtv command and returns structured JSON // It accepts a context which may contain a Kubernetes token and/or server URL for authentication. // If a token is present in the context, it will be passed via the --token flag. // If a server URL is present in the context, it will be passed via the --server flag. // If neither is present, it falls back to CLI default values, then to the default kubeconfig behavior. // Precedence: context (HTTP headers) > CLI defaults > kubeconfig (implicit). // If dry run mode is enabled in the context, it returns a teaching response instead of executing. func RunKubectlMTVCommand(ctx context.Context, args []string) (string, error) { // Prepend --insecure-skip-tls-verify when configured (before server/token) if defaultInsecureSkipTLS { args = append([]string{"--insecure-skip-tls-verify"}, args...) } // Check context first (HTTP headers), then fall back to CLI defaults for --server flag // Server flag is prepended first so it appears before --token in the final command if server, ok := GetKubeServer(ctx); ok && server != "" { args = append([]string{"--server", server}, args...) } else if defaultKubeServer != "" { args = append([]string{"--server", defaultKubeServer}, args...) } // Check context first (HTTP headers), then fall back to CLI defaults for --token flag if token, ok := GetKubeToken(ctx); ok && token != "" { // Insert --token flag at the beginning of args (after subcommand if present) // This ensures it's processed before any other flags args = append([]string{"--token", token}, args...) } else if defaultKubeToken != "" { log.Println("[auth] RunKubectlMTVCommand: using token from CLI defaults") args = append([]string{"--token", defaultKubeToken}, args...) } else { log.Println("[auth] RunKubectlMTVCommand: NO token available (context or defaults)") } // Check if we're in dry run mode if GetDryRun(ctx) { // In dry run mode, just return the command that would be executed // The AI will explain it in context cmdStr := formatShellCommand("kubectl-mtv", args) response := CommandResponse{ Command: cmdStr, ReturnValue: 0, Stdout: cmdStr, Stderr: "", } jsonData, err := json.MarshalIndent(response, "", " ") if err != nil { return "", fmt.Errorf("failed to marshal response: %w", err) } return string(jsonData), nil } // Resolve environment variable references for sensitive flags (e.g., $VCENTER_PASSWORD) // This is done after dry run check so dry run shows $VAR syntax, not resolved values resolvedArgs, err := ResolveEnvVars(args) if err != nil { return "", fmt.Errorf("failed to resolve environment variables: %w", err) } cmd := exec.Command(selfExePath, resolvedArgs...) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr // Set timeout of 120 seconds timer := time.AfterFunc(120*time.Second, func() { _ = cmd.Process.Kill() }) defer timer.Stop() err = cmd.Run() response := CommandResponse{ Command: formatShellCommand("kubectl-mtv", args), Stdout: stdout.String(), Stderr: stderr.String(), } if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { response.ReturnValue = exitErr.ExitCode() } else { response.ReturnValue = -1 if response.Stderr == "" { response.Stderr = err.Error() } } } else { response.ReturnValue = 0 } jsonData, err := json.MarshalIndent(response, "", " ") if err != nil { return "", fmt.Errorf("failed to marshal response: %w", err) } return string(jsonData), nil } // RunKubectlCommand executes a kubectl command and returns structured JSON // It accepts a context which may contain a Kubernetes token and/or server URL for authentication. // If a token is present in the context, it will be passed via the --token flag. // If a server URL is present in the context, it will be passed via the --server flag. // If neither is present, it falls back to CLI default values, then to the default kubeconfig behavior. // Precedence: context (HTTP headers) > CLI defaults > kubeconfig (implicit). // If dry run mode is enabled in the context, it returns a teaching response instead of executing. func RunKubectlCommand(ctx context.Context, args []string) (string, error) { // Prepend --insecure-skip-tls-verify when configured (before server/token) if defaultInsecureSkipTLS { args = append([]string{"--insecure-skip-tls-verify"}, args...) } // Check context first (HTTP headers), then fall back to CLI defaults for --server flag // Server flag is prepended first so it appears before --token in the final command if server, ok := GetKubeServer(ctx); ok && server != "" { args = append([]string{"--server", server}, args...) } else if defaultKubeServer != "" { args = append([]string{"--server", defaultKubeServer}, args...) } // Check context first (HTTP headers), then fall back to CLI defaults for --token flag if token, ok := GetKubeToken(ctx); ok && token != "" { // Insert --token flag at the beginning of args (after subcommand if present) // This ensures it's processed before any other flags args = append([]string{"--token", token}, args...) } else if defaultKubeToken != "" { log.Println("[auth] RunKubectlCommand: using token from CLI defaults") args = append([]string{"--token", defaultKubeToken}, args...) } else { log.Println("[auth] RunKubectlCommand: NO token available (context or defaults)") } // Check if we're in dry run mode if GetDryRun(ctx) { // In dry run mode, just return the command that would be executed // The AI will explain it in context cmdStr := formatShellCommand("kubectl", args) response := CommandResponse{ Command: cmdStr, ReturnValue: 0, Stdout: cmdStr, Stderr: "", } jsonData, err := json.MarshalIndent(response, "", " ") if err != nil { return "", fmt.Errorf("failed to marshal response: %w", err) } return string(jsonData), nil } cmd := exec.Command("kubectl", args...) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr // Set timeout of 120 seconds timer := time.AfterFunc(120*time.Second, func() { _ = cmd.Process.Kill() }) defer timer.Stop() err := cmd.Run() response := CommandResponse{ Command: formatShellCommand("kubectl", args), Stdout: stdout.String(), Stderr: stderr.String(), } if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { response.ReturnValue = exitErr.ExitCode() } else { response.ReturnValue = -1 if response.Stderr == "" { response.Stderr = err.Error() } } } else { response.ReturnValue = 0 } jsonData, err := json.MarshalIndent(response, "", " ") if err != nil { return "", fmt.Errorf("failed to marshal response: %w", err) } return string(jsonData), nil } // sensitiveFlags defines flags whose values should be redacted in logs/output. // These are security-sensitive flags like passwords and tokens. var sensitiveFlags = map[string]bool{ "--password": true, "-p": true, // shorthand for password "--token": true, "-T": true, // shorthand for token "--offload-vsphere-password": true, "--offload-storage-password": true, "--target-secret-access-key": true, // AWS secret key for EC2 } // envVarPattern matches ${VAR_NAME} references embedded anywhere in a string. // Only the ${VAR} syntax (with curly braces) is recognized as an env var reference. // This allows literal values starting with $ (e.g., "$ecureP@ss") to pass through unchanged. var envVarPattern = regexp.MustCompile(`\$\{([^}]+)\}`) // resolveEnvVar resolves environment variable references within a string value. // It supports both whole-value references (e.g., "${GOVC_URL}") and embedded references // (e.g., "${GOVC_URL}/sdk", "https://${HOST}:${PORT}/api"). // Only the ${VAR_NAME} syntax with curly braces is recognized, so bare $VAR or literal // values starting with $ (e.g., "$ecureP@ss") pass through unchanged. // Returns an error if any referenced env var is not set. func resolveEnvVar(value string) (string, error) { if !strings.Contains(value, "${") { return value, nil } var resolveErr error result := envVarPattern.ReplaceAllStringFunc(value, func(match string) string { if resolveErr != nil { return match } // Extract the variable name from ${VAR_NAME} envName := match[2 : len(match)-1] if envName == "" { resolveErr = fmt.Errorf("empty environment variable name in ${}") return match } resolved := os.Getenv(envName) if resolved == "" { resolveErr = fmt.Errorf("environment variable %s is not set", envName) return match } return resolved }) if resolveErr != nil { return "", resolveErr } return result, nil } // ResolveEnvVars resolves environment variable references for all argument values. // This allows users to pass ${ENV_VAR_NAME} instead of literal values for any flag or argument. // Environment variables are resolved for any value matching the ${VAR_NAME} pattern. func ResolveEnvVars(args []string) ([]string, error) { result := make([]string, len(args)) copy(result, args) for i := 0; i < len(result); i++ { // Skip flags themselves (only resolve values) if strings.HasPrefix(result[i], "-") { continue } resolved, err := resolveEnvVar(result[i]) if err != nil { return nil, err } result[i] = resolved } return result, nil } // formatShellCommand formats a command and args into a display string // It sanitizes sensitive parameters like passwords and tokens // Note: This is for display/logging only. Actual command execution uses exec.Command() // which handles arguments directly without shell interpretation. func formatShellCommand(cmd string, args []string) string { // Build the display command with sanitization sanitizedArgs := []string{} sanitizeNext := false for _, arg := range args { if sanitizeNext { // Replace sensitive value with **** sanitizedArgs = append(sanitizedArgs, "****") sanitizeNext = false } else if sensitiveFlags[arg] { // This is a sensitive flag, add it and mark next arg for sanitization sanitizedArgs = append(sanitizedArgs, arg) sanitizeNext = true } else { // Normal argument sanitizedArgs = append(sanitizedArgs, arg) } } // Use shellquote.Join to properly quote all arguments quotedArgs := shellquote.Join(sanitizedArgs...) return cmd + " " + quotedArgs } // UnmarshalJSONResponse unmarshals a JSON string response into a native object. // This is needed because the MCP SDK expects a native object, not a JSON string. // // The function also parses the stdout field if it contains JSON: // - If stdout is a JSON object or array, it's parsed and moved to a "data" field // - If stdout is plain text, it's renamed to "output" for clarity // // Post-processing to help small LLMs: // - The "command" field (full CLI command string) is stripped to prevent models // from mimicking CLI syntax instead of using structured MCP tool calls. // - Empty "stderr" is removed to reduce noise. // - The "output" field is truncated to maxResponseChars (if configured) to keep // responses within manageable context window sizes. // // This makes responses clearer for LLMs by avoiding double-encoded strings. func UnmarshalJSONResponse(responseJSON string) (map[string]interface{}, error) { var cmdResponse map[string]interface{} if err := json.Unmarshal([]byte(responseJSON), &cmdResponse); err != nil { return nil, fmt.Errorf("failed to unmarshal JSON response: %w", err) } // Try to parse stdout as JSON if stdout, ok := cmdResponse["stdout"].(string); ok && stdout != "" { stdout = strings.TrimSpace(stdout) // Try parsing as JSON object var jsonObj map[string]interface{} if err := json.Unmarshal([]byte(stdout), &jsonObj); err == nil { delete(cmdResponse, "stdout") cmdResponse["data"] = jsonObj cleanupResponse(cmdResponse) return cmdResponse, nil } // Try parsing as JSON array var jsonArr []interface{} if err := json.Unmarshal([]byte(stdout), &jsonArr); err == nil { delete(cmdResponse, "stdout") cmdResponse["data"] = jsonArr cleanupResponse(cmdResponse) return cmdResponse, nil } // Not JSON - rename to "output" for clarity (plain text) delete(cmdResponse, "stdout") cmdResponse["output"] = stdout } cleanupResponse(cmdResponse) return cmdResponse, nil } // cleanupResponse removes noise from tool responses to help small LLMs stay on track. // - Strips the "command" field (full CLI echo like "kubectl-mtv get plan --namespace demo") // which causes small models to mimic CLI syntax instead of using structured tool calls. // - Removes empty "stderr" to reduce noise. // - Truncates the "output" field if maxResponseChars is configured. func cleanupResponse(data map[string]interface{}) { // Strip CLI command echo — this is the #1 cause of small LLMs generating // raw CLI strings instead of structured {command, flags} tool calls. delete(data, "command") // Remove empty stderr to reduce noise if stderr, ok := data["stderr"].(string); ok && strings.TrimSpace(stderr) == "" { delete(data, "stderr") } // Truncate long text output if configured if maxResponseChars > 0 { if output, ok := data["output"].(string); ok && len(output) > maxResponseChars { truncated := output[:maxResponseChars] truncated += fmt.Sprintf("\n\n[truncated at %d chars. Use flags: {output: \"json\"} with fields: [\"name\", \"id\"] to get specific data]", maxResponseChars) data["output"] = truncated } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/mcp/util/util_test.go
Go
package util import ( "context" "net/http" "os" "strings" "testing" ) func TestResolveEnvVar(t *testing.T) { // Set test environment variables os.Setenv("TEST_HOST", "https://10.6.46.250") os.Setenv("TEST_PORT", "443") os.Setenv("TEST_USER", "admin") defer func() { os.Unsetenv("TEST_HOST") os.Unsetenv("TEST_PORT") os.Unsetenv("TEST_USER") }() tests := []struct { name string input string want string wantErr bool }{ { name: "whole value env var reference", input: "${TEST_HOST}", want: "https://10.6.46.250", }, { name: "embedded env var with path suffix", input: "${TEST_HOST}/sdk", want: "https://10.6.46.250/sdk", }, { name: "embedded env var with prefix and suffix", input: "https://${TEST_USER}@example.com", want: "https://admin@example.com", }, { name: "multiple env var references", input: "${TEST_HOST}:${TEST_PORT}/api", want: "https://10.6.46.250:443/api", }, { name: "literal string no env vars", input: "https://example.com/sdk", want: "https://example.com/sdk", }, { name: "literal dollar sign without braces", input: "$ecureP@ss", want: "$ecureP@ss", }, { name: "bare $VAR without braces passes through", input: "$TEST_HOST", want: "$TEST_HOST", }, { name: "empty string", input: "", want: "", }, { name: "unset env var returns error", input: "${NONEXISTENT_VAR_12345}", wantErr: true, }, { name: "empty env var name passes through (not a valid pattern)", input: "${}", want: "${}", }, { name: "unset env var embedded in string returns error", input: "${NONEXISTENT_VAR_12345}/sdk", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := resolveEnvVar(tt.input) if tt.wantErr { if err == nil { t.Errorf("resolveEnvVar(%q) expected error, got nil", tt.input) } return } if err != nil { t.Errorf("resolveEnvVar(%q) unexpected error: %v", tt.input, err) return } if got != tt.want { t.Errorf("resolveEnvVar(%q) = %q, want %q", tt.input, got, tt.want) } }) } } func TestResolveEnvVars(t *testing.T) { os.Setenv("TEST_URL", "https://vcenter.example.com") os.Setenv("TEST_PASS", "s3cret") defer func() { os.Unsetenv("TEST_URL") os.Unsetenv("TEST_PASS") }() tests := []struct { name string args []string want []string wantErr bool }{ { name: "flags are skipped, values are resolved", args: []string{"--url", "${TEST_URL}/sdk", "--password", "${TEST_PASS}"}, want: []string{"--url", "https://vcenter.example.com/sdk", "--password", "s3cret"}, }, { name: "non-env values pass through", args: []string{"--type", "vsphere", "--url", "https://literal.example.com"}, want: []string{"--type", "vsphere", "--url", "https://literal.example.com"}, }, { name: "positional args with env vars", args: []string{"create", "provider", "my-provider", "--url", "${TEST_URL}"}, want: []string{"create", "provider", "my-provider", "--url", "https://vcenter.example.com"}, }, { name: "error on unset env var", args: []string{"--url", "${DOES_NOT_EXIST_XYZ}"}, wantErr: true, }, { name: "short flags are skipped", args: []string{"-n", "demo", "-p", "${TEST_PASS}"}, want: []string{"-n", "demo", "-p", "s3cret"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := ResolveEnvVars(tt.args) if tt.wantErr { if err == nil { t.Errorf("ResolveEnvVars(%v) expected error, got nil", tt.args) } return } if err != nil { t.Errorf("ResolveEnvVars(%v) unexpected error: %v", tt.args, err) return } if len(got) != len(tt.want) { t.Errorf("ResolveEnvVars(%v) = %v (len %d), want %v (len %d)", tt.args, got, len(got), tt.want, len(tt.want)) return } for i := range got { if got[i] != tt.want[i] { t.Errorf("ResolveEnvVars(%v)[%d] = %q, want %q", tt.args, i, got[i], tt.want[i]) } } }) } } // --- UnmarshalJSONResponse tests --- func TestUnmarshalJSONResponse(t *testing.T) { tests := []struct { name string input string wantData bool // expect "data" key in result wantOutput bool // expect "output" key in result wantErr bool checkData func(t *testing.T, data interface{}) }{ { name: "stdout is JSON object", input: `{"command":"kubectl-mtv get plan","return_value":0,"stdout":"{\"items\":[],\"kind\":\"PlanList\"}","stderr":""}`, wantData: true, checkData: func(t *testing.T, data interface{}) { m, ok := data.(map[string]interface{}) if !ok { t.Fatalf("expected map, got %T", data) } if _, exists := m["kind"]; !exists { t.Error("parsed data should contain 'kind'") } }, }, { name: "stdout is JSON array", input: `{"command":"test","return_value":0,"stdout":"[{\"name\":\"plan1\"},{\"name\":\"plan2\"}]","stderr":""}`, wantData: true, checkData: func(t *testing.T, data interface{}) { arr, ok := data.([]interface{}) if !ok { t.Fatalf("expected array, got %T", data) } if len(arr) != 2 { t.Errorf("expected 2 items, got %d", len(arr)) } }, }, { name: "stdout is plain text", input: `{"command":"test","return_value":0,"stdout":"NAME STATUS\nplan1 Ready","stderr":""}`, wantOutput: true, }, { name: "empty stdout", input: `{"command":"test","return_value":0,"stdout":"","stderr":""}`, }, { name: "invalid JSON input", input: `not json at all`, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := UnmarshalJSONResponse(tt.input) if tt.wantErr { if err == nil { t.Fatal("expected error, got nil") } return } if err != nil { t.Fatalf("unexpected error: %v", err) } // "command" field should always be stripped (prevents CLI mimicry) if _, hasCommand := result["command"]; hasCommand { t.Error("'command' field should be stripped from response") } // Empty "stderr" should be stripped if stderr, hasSterr := result["stderr"]; hasSterr { if s, ok := stderr.(string); ok && strings.TrimSpace(s) == "" { t.Error("empty 'stderr' should be stripped from response") } } if tt.wantData { data, exists := result["data"] if !exists { t.Fatal("expected 'data' key in result") } if _, hasStdout := result["stdout"]; hasStdout { t.Error("'stdout' should be removed when 'data' is set") } if tt.checkData != nil { tt.checkData(t, data) } } if tt.wantOutput { output, exists := result["output"] if !exists { t.Fatal("expected 'output' key in result") } if _, ok := output.(string); !ok { t.Errorf("output should be a string, got %T", output) } if _, hasStdout := result["stdout"]; hasStdout { t.Error("'stdout' should be removed when 'output' is set") } } }) } } // TestUnmarshalJSONResponse_ResponseTruncation verifies that long output is truncated // when maxResponseChars is configured. func TestUnmarshalJSONResponse_ResponseTruncation(t *testing.T) { // Save and restore orig := GetMaxResponseChars() defer SetMaxResponseChars(orig) longOutput := strings.Repeat("A", 5000) input := `{"command":"test","return_value":0,"stdout":"` + longOutput + `","stderr":""}` // Without truncation SetMaxResponseChars(0) result, err := UnmarshalJSONResponse(input) if err != nil { t.Fatalf("unexpected error: %v", err) } output := result["output"].(string) if len(output) != 5000 { t.Errorf("without truncation, output should be 5000 chars, got %d", len(output)) } // With truncation at 100 chars SetMaxResponseChars(100) result, err = UnmarshalJSONResponse(input) if err != nil { t.Fatalf("unexpected error: %v", err) } output = result["output"].(string) if !strings.Contains(output, "[truncated at 100 chars") { t.Errorf("truncated output should contain truncation hint, got: %s", output[:min(200, len(output))]) } // The output should start with the original content if !strings.HasPrefix(output, strings.Repeat("A", 100)) { t.Error("truncated output should start with original content") } } // --- formatShellCommand tests --- func TestFormatShellCommand(t *testing.T) { tests := []struct { name string cmd string args []string wantContain string wantMissing string }{ { name: "simple command", cmd: "kubectl-mtv", args: []string{"get", "plan", "--namespace", "demo"}, wantContain: "kubectl-mtv get plan --namespace demo", }, { name: "password is sanitized", cmd: "kubectl-mtv", args: []string{"create", "provider", "--password", "s3cret"}, wantContain: "--password", wantMissing: "s3cret", }, { name: "token is sanitized", cmd: "kubectl", args: []string{"--token", "my-secret-token", "get", "pods"}, wantContain: "--token", wantMissing: "my-secret-token", }, { name: "offload password is sanitized", cmd: "kubectl-mtv", args: []string{"create", "mapping", "--offload-vsphere-password", "pass123"}, wantContain: "--offload-vsphere-password", wantMissing: "pass123", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := formatShellCommand(tt.cmd, tt.args) if tt.wantContain != "" && !strings.Contains(result, tt.wantContain) { t.Errorf("formatShellCommand() = %q, should contain %q", result, tt.wantContain) } if tt.wantMissing != "" && strings.Contains(result, tt.wantMissing) { t.Errorf("formatShellCommand() = %q, should NOT contain %q", result, tt.wantMissing) } }) } } // --- Context helpers tests --- func TestWithKubeToken(t *testing.T) { ctx := context.Background() // No token in fresh context token, ok := GetKubeToken(ctx) if ok || token != "" { t.Error("fresh context should not have a token") } // Add token ctx = WithKubeToken(ctx, "my-token") token, ok = GetKubeToken(ctx) if !ok || token != "my-token" { t.Errorf("expected token 'my-token', got %q (ok=%v)", token, ok) } } func TestWithKubeServer(t *testing.T) { ctx := context.Background() // No server in fresh context server, ok := GetKubeServer(ctx) if ok || server != "" { t.Error("fresh context should not have a server") } // Add server ctx = WithKubeServer(ctx, "https://api.example.com:6443") server, ok = GetKubeServer(ctx) if !ok || server != "https://api.example.com:6443" { t.Errorf("expected server URL, got %q (ok=%v)", server, ok) } } func TestWithDryRun(t *testing.T) { ctx := context.Background() // Default is false if GetDryRun(ctx) { t.Error("fresh context should not have dry run enabled") } // Enable dry run ctx = WithDryRun(ctx, true) if !GetDryRun(ctx) { t.Error("dry run should be enabled after setting true") } // Disable dry run ctx = WithDryRun(ctx, false) if GetDryRun(ctx) { t.Error("dry run should be disabled after setting false") } } func TestGetKubeToken_NilContext(t *testing.T) { token, ok := GetKubeToken(nil) //nolint:staticcheck // intentionally testing nil context behavior if ok || token != "" { t.Error("nil context should return empty token") } } func TestGetKubeServer_NilContext(t *testing.T) { server, ok := GetKubeServer(nil) //nolint:staticcheck // intentionally testing nil context behavior if ok || server != "" { t.Error("nil context should return empty server") } } func TestGetDryRun_NilContext(t *testing.T) { if GetDryRun(nil) { //nolint:staticcheck // intentionally testing nil context behavior t.Error("nil context should return false for dry run") } } // --- WithKubeCredsFromHeaders tests --- func TestWithKubeCredsFromHeaders(t *testing.T) { tests := []struct { name string headers http.Header wantToken string wantServer string }{ { name: "nil headers", headers: nil, }, { name: "empty headers", headers: http.Header{}, }, { name: "bearer token", headers: http.Header{ "Authorization": []string{"Bearer my-k8s-token"}, }, wantToken: "my-k8s-token", }, { name: "kubernetes server", headers: http.Header{ "X-Kubernetes-Server": []string{"https://api.cluster.local:6443"}, }, wantServer: "https://api.cluster.local:6443", }, { name: "both token and server", headers: http.Header{ "Authorization": []string{"Bearer both-token"}, "X-Kubernetes-Server": []string{"https://api.example.com"}, }, wantToken: "both-token", wantServer: "https://api.example.com", }, { name: "non-bearer auth header ignored", headers: http.Header{ "Authorization": []string{"Basic dXNlcjpwYXNz"}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx := context.Background() ctx = WithKubeCredsFromHeaders(ctx, tt.headers) token, _ := GetKubeToken(ctx) if token != tt.wantToken { t.Errorf("token = %q, want %q", token, tt.wantToken) } server, _ := GetKubeServer(ctx) if server != tt.wantServer { t.Errorf("server = %q, want %q", server, tt.wantServer) } }) } } // --- Default kube credentials tests --- func TestDefaultKubeServer(t *testing.T) { // Save and restore orig := GetDefaultKubeServer() defer SetDefaultKubeServer(orig) // Default is empty SetDefaultKubeServer("") if got := GetDefaultKubeServer(); got != "" { t.Errorf("GetDefaultKubeServer() should be empty, got %q", got) } // Set a server SetDefaultKubeServer("https://api.example.com:6443") if got := GetDefaultKubeServer(); got != "https://api.example.com:6443" { t.Errorf("GetDefaultKubeServer() = %q, want %q", got, "https://api.example.com:6443") } // Clear it SetDefaultKubeServer("") if got := GetDefaultKubeServer(); got != "" { t.Errorf("GetDefaultKubeServer() should be empty after clearing, got %q", got) } } func TestDefaultKubeToken(t *testing.T) { // Save and restore orig := GetDefaultKubeToken() defer SetDefaultKubeToken(orig) // Default is empty SetDefaultKubeToken("") if got := GetDefaultKubeToken(); got != "" { t.Errorf("GetDefaultKubeToken() should be empty, got %q", got) } // Set a token SetDefaultKubeToken("my-cli-token") if got := GetDefaultKubeToken(); got != "my-cli-token" { t.Errorf("GetDefaultKubeToken() = %q, want %q", got, "my-cli-token") } // Clear it SetDefaultKubeToken("") if got := GetDefaultKubeToken(); got != "" { t.Errorf("GetDefaultKubeToken() should be empty after clearing, got %q", got) } } func TestRunKubectlMTVCommand_DefaultCredsFallback(t *testing.T) { // Save and restore defaults origServer := GetDefaultKubeServer() origToken := GetDefaultKubeToken() defer func() { SetDefaultKubeServer(origServer) SetDefaultKubeToken(origToken) }() // Set CLI defaults SetDefaultKubeServer("https://cli-default.example.com:6443") SetDefaultKubeToken("cli-default-token") // Use dry run mode to capture the command without executing ctx := WithDryRun(context.Background(), true) result, err := RunKubectlMTVCommand(ctx, []string{"get", "plan"}) if err != nil { t.Fatalf("unexpected error: %v", err) } // Verify CLI defaults are used (token is sanitized in output) if !strings.Contains(result, "--server") { t.Errorf("expected --server flag in command, got: %s", result) } if !strings.Contains(result, "cli-default.example.com") { t.Errorf("expected CLI default server URL in command, got: %s", result) } if !strings.Contains(result, "--token") { t.Errorf("expected --token flag in command, got: %s", result) } } func TestRunKubectlMTVCommand_ContextOverridesDefaults(t *testing.T) { // Save and restore defaults origServer := GetDefaultKubeServer() origToken := GetDefaultKubeToken() defer func() { SetDefaultKubeServer(origServer) SetDefaultKubeToken(origToken) }() // Set CLI defaults SetDefaultKubeServer("https://cli-default.example.com:6443") SetDefaultKubeToken("cli-default-token") // Set context values (simulating HTTP headers) that should override CLI defaults ctx := context.Background() ctx = WithKubeServer(ctx, "https://header-override.example.com:6443") ctx = WithKubeToken(ctx, "header-override-token") ctx = WithDryRun(ctx, true) result, err := RunKubectlMTVCommand(ctx, []string{"get", "plan"}) if err != nil { t.Fatalf("unexpected error: %v", err) } // Context values should be used, not CLI defaults if !strings.Contains(result, "header-override.example.com") { t.Errorf("expected context server URL to override CLI default, got: %s", result) } if strings.Contains(result, "cli-default.example.com") { t.Errorf("CLI default server should NOT appear when context has server, got: %s", result) } } func TestRunKubectlMTVCommand_NoCredsWhenNoneSet(t *testing.T) { // Save and restore defaults origServer := GetDefaultKubeServer() origToken := GetDefaultKubeToken() defer func() { SetDefaultKubeServer(origServer) SetDefaultKubeToken(origToken) }() // Clear CLI defaults SetDefaultKubeServer("") SetDefaultKubeToken("") // Use dry run mode with no context credentials ctx := WithDryRun(context.Background(), true) result, err := RunKubectlMTVCommand(ctx, []string{"get", "plan"}) if err != nil { t.Fatalf("unexpected error: %v", err) } // No --server or --token should appear if strings.Contains(result, "--server") { t.Errorf("--server flag should NOT appear when no creds set, got: %s", result) } if strings.Contains(result, "--token") { t.Errorf("--token flag should NOT appear when no creds set, got: %s", result) } } func TestRunKubectlCommand_DefaultCredsFallback(t *testing.T) { // Save and restore defaults origServer := GetDefaultKubeServer() origToken := GetDefaultKubeToken() defer func() { SetDefaultKubeServer(origServer) SetDefaultKubeToken(origToken) }() // Set CLI defaults SetDefaultKubeServer("https://cli-default.example.com:6443") SetDefaultKubeToken("cli-default-token") // Use dry run mode to capture the command without executing ctx := WithDryRun(context.Background(), true) result, err := RunKubectlCommand(ctx, []string{"get", "pods"}) if err != nil { t.Fatalf("unexpected error: %v", err) } // Verify CLI defaults are used if !strings.Contains(result, "--server") { t.Errorf("expected --server flag in command, got: %s", result) } if !strings.Contains(result, "cli-default.example.com") { t.Errorf("expected CLI default server URL in command, got: %s", result) } if !strings.Contains(result, "--token") { t.Errorf("expected --token flag in command, got: %s", result) } } func TestRunKubectlCommand_ContextOverridesDefaults(t *testing.T) { // Save and restore defaults origServer := GetDefaultKubeServer() origToken := GetDefaultKubeToken() defer func() { SetDefaultKubeServer(origServer) SetDefaultKubeToken(origToken) }() // Set CLI defaults SetDefaultKubeServer("https://cli-default.example.com:6443") SetDefaultKubeToken("cli-default-token") // Set context values (simulating HTTP headers) that should override CLI defaults ctx := context.Background() ctx = WithKubeServer(ctx, "https://header-override.example.com:6443") ctx = WithKubeToken(ctx, "header-override-token") ctx = WithDryRun(ctx, true) result, err := RunKubectlCommand(ctx, []string{"get", "pods"}) if err != nil { t.Fatalf("unexpected error: %v", err) } // Context values should be used, not CLI defaults if !strings.Contains(result, "header-override.example.com") { t.Errorf("expected context server URL to override CLI default, got: %s", result) } if strings.Contains(result, "cli-default.example.com") { t.Errorf("CLI default server should NOT appear when context has server, got: %s", result) } } // --- Output format tests --- func TestOutputFormat(t *testing.T) { // Save and restore orig := GetOutputFormat() defer SetOutputFormat(orig) // Default is "text" SetOutputFormat("") if got := GetOutputFormat(); got != "text" { t.Errorf("SetOutputFormat(\"\") should default to \"text\", got %q", got) } // Set to json SetOutputFormat("json") if got := GetOutputFormat(); got != "json" { t.Errorf("SetOutputFormat(\"json\") = %q, want \"json\"", got) } // Set back to text SetOutputFormat("text") if got := GetOutputFormat(); got != "text" { t.Errorf("SetOutputFormat(\"text\") = %q, want \"text\"", got) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/client/access.go
Go
package client import ( "context" authorizationv1 "k8s.io/api/authorization/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/cli-runtime/pkg/genericclioptions" ) // CanAccessResource checks if the user has permissions to perform the specified verb on the given resource in the namespace func CanAccessResource(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string, gvr schema.GroupVersionResource, verb string) bool { // Get clientset clientset, err := GetKubernetesClientset(configFlags) if err != nil { return false } // Create a SelfSubjectAccessReview to check if the user can access the resource accessReview := &authorizationv1.SelfSubjectAccessReview{ Spec: authorizationv1.SelfSubjectAccessReviewSpec{ ResourceAttributes: &authorizationv1.ResourceAttributes{ Namespace: namespace, Verb: verb, Group: gvr.Group, Resource: gvr.Resource, }, }, } // Submit the access review result, err := clientset.AuthorizationV1().SelfSubjectAccessReviews().Create( ctx, accessReview, metav1.CreateOptions{}, ) if err != nil { return false } return result.Status.Allowed }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/client/client.go
Go
package client import ( "context" "fmt" "io" "net/http" "net/url" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/klog/v2" _ "k8s.io/client-go/plugin/pkg/client/auth" ) // Group is the API group for MTV CRDs const Group = "forklift.konveyor.io" // Version is the API version for MTV CRDs const Version = "v1beta1" // Resource GVRs for MTV CRDs var ( ProvidersGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "providers", } NetworkMapGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "networkmaps", } StorageMapGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "storagemaps", } PlansGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "plans", } MigrationsGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "migrations", } HostsGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "hosts", } HooksGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "hooks", } ForkliftControllersGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "forkliftcontrollers", } DynamicProvidersGVR = schema.GroupVersionResource{ Group: Group, Version: Version, Resource: "dynamicproviders", } // SecretGVR is used to access secrets in the cluster SecretsGVR = schema.GroupVersionResource{ Group: "", Version: "v1", Resource: "secrets", } // ConfigMapsGVR is used to access configmaps in the cluster ConfigMapsGVR = schema.GroupVersionResource{ Group: "", Version: "v1", Resource: "configmaps", } // RouteGVR is used to access routes in an Openshift cluster RouteGVR = schema.GroupVersionResource{ Group: "route.openshift.io", Version: "v1", Resource: "routes", } ) // GetDynamicClient returns a dynamic client for interacting with MTV CRDs func GetDynamicClient(configFlags *genericclioptions.ConfigFlags) (dynamic.Interface, error) { config, err := configFlags.ToRESTConfig() if err != nil { return nil, fmt.Errorf("failed to get REST config: %v", err) } client, err := dynamic.NewForConfig(config) if err != nil { return nil, fmt.Errorf("failed to create dynamic client: %v", err) } return client, nil } // GetKubernetesClientset returns a kubernetes clientset for interacting with the Kubernetes API func GetKubernetesClientset(configFlags *genericclioptions.ConfigFlags) (*kubernetes.Clientset, error) { config, err := configFlags.ToRESTConfig() if err != nil { return nil, fmt.Errorf("failed to get REST config: %v", err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, fmt.Errorf("failed to create kubernetes clientset: %v", err) } return clientset, nil } // GetAuthenticatedTransport returns an HTTP transport configured with Kubernetes authentication func GetAuthenticatedTransport(ctx context.Context, configFlags *genericclioptions.ConfigFlags) (http.RoundTripper, error) { return GetAuthenticatedTransportWithInsecure(ctx, configFlags, false) } // GetAuthenticatedTransportWithInsecure returns an HTTP transport configured with Kubernetes authentication // and optional insecure TLS skip verification func GetAuthenticatedTransportWithInsecure(ctx context.Context, configFlags *genericclioptions.ConfigFlags, insecureSkipTLS bool) (http.RoundTripper, error) { config, err := configFlags.ToRESTConfig() if err != nil { return nil, fmt.Errorf("failed to get REST config: %v", err) } // Handle client certificate authentication (common in Kind/minikube clusters) // The MTV inventory service expects bearer tokens, not client certificates if NeedsBearerTokenForInventory(config) { klog.V(5).Infof("Detected client certificate authentication without bearer token") if token, ok := GetServiceAccountTokenForInventory(ctx, configFlags, config); ok { config.BearerToken = token } else { klog.V(5).Infof("WARNING: Could not retrieve service account token, client certificate auth may not work with inventory service") } } // Debug logging for authentication if config.BearerToken != "" { klog.V(5).Infof("Using bearer token authentication (token length: %d)", len(config.BearerToken)) } else if config.BearerTokenFile != "" { klog.V(5).Infof("Using bearer token file: %s", config.BearerTokenFile) } else if config.CertData != nil || config.CertFile != "" { klog.V(5).Infof("Using client certificate authentication") } else if config.KeyData != nil || config.KeyFile != "" { klog.V(5).Infof("Using client key authentication") } else if config.Username != "" { klog.V(5).Infof("Using basic authentication with username: %s", config.Username) } else if config.ExecProvider != nil { klog.V(5).Infof("Using exec auth provider: %s", config.ExecProvider.Command) } else if config.AuthProvider != nil { klog.V(5).Infof("Using auth provider: %s", config.AuthProvider.Name) } else { klog.V(5).Infof("WARNING: No authentication credentials found in REST config!") klog.V(5).Infof(" BearerToken: %v, CertData: %v, CertFile: %s", config.BearerToken != "", config.CertData != nil, config.CertFile) klog.V(5).Infof(" Username: %s, ExecProvider: %v, AuthProvider: %v", config.Username, config.ExecProvider != nil, config.AuthProvider != nil) } // If insecure skip TLS is enabled, modify the REST config before creating transport if insecureSkipTLS { config.TLSClientConfig.Insecure = true config.TLSClientConfig.CAFile = "" config.TLSClientConfig.CAData = nil klog.V(5).Infof("TLS certificate verification disabled (insecure mode)") } // Create a transport wrapper that adds authentication // This must be done AFTER modifying the TLS config so the transport is created correctly transport, err := rest.TransportFor(config) if err != nil { return nil, fmt.Errorf("failed to create authenticated transport: %v", err) } return transport, nil } // GetAuthenticatedHTTPClientWithInsecure returns an HTTP client configured with Kubernetes authentication // and optional insecure TLS skip verification func GetAuthenticatedHTTPClientWithInsecure(ctx context.Context, configFlags *genericclioptions.ConfigFlags, baseURL string, insecureSkipTLS bool) (*HTTPClient, error) { transport, err := GetAuthenticatedTransportWithInsecure(ctx, configFlags, insecureSkipTLS) if err != nil { return nil, err } return NewHTTPClient(baseURL, transport), nil } // GetAllPlanNames retrieves all plan names from the given namespace func GetAllPlanNames(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) ([]string, error) { dynamicClient, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get dynamic client: %v", err) } var planList *unstructured.UnstructuredList if namespace != "" { planList, err = dynamicClient.Resource(PlansGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { planList, err = dynamicClient.Resource(PlansGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list plans: %v", err) } var planNames []string for _, plan := range planList.Items { planNames = append(planNames, plan.GetName()) } return planNames, nil } // GetAllHookNames retrieves all hook names from the given namespace func GetAllHookNames(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) ([]string, error) { dynamicClient, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get dynamic client: %v", err) } var hookList *unstructured.UnstructuredList if namespace != "" { hookList, err = dynamicClient.Resource(HooksGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { hookList, err = dynamicClient.Resource(HooksGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list hooks: %v", err) } var hookNames []string for _, hook := range hookList.Items { hookNames = append(hookNames, hook.GetName()) } return hookNames, nil } // GetAllHostNames retrieves all host names from the given namespace func GetAllHostNames(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) ([]string, error) { dynamicClient, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get dynamic client: %v", err) } var hostList *unstructured.UnstructuredList if namespace != "" { hostList, err = dynamicClient.Resource(HostsGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { hostList, err = dynamicClient.Resource(HostsGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list hosts: %v", err) } var hostNames []string for _, host := range hostList.Items { hostNames = append(hostNames, host.GetName()) } return hostNames, nil } // GetAllProviderNames retrieves all provider names from the given namespace func GetAllProviderNames(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) ([]string, error) { dynamicClient, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get dynamic client: %v", err) } var providerList *unstructured.UnstructuredList if namespace != "" { providerList, err = dynamicClient.Resource(ProvidersGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { providerList, err = dynamicClient.Resource(ProvidersGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list providers: %v", err) } var providerNames []string for _, provider := range providerList.Items { providerNames = append(providerNames, provider.GetName()) } return providerNames, nil } // GetAllNetworkMappingNames retrieves all network mapping names from the given namespace func GetAllNetworkMappingNames(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) ([]string, error) { dynamicClient, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get dynamic client: %v", err) } var mappingList *unstructured.UnstructuredList if namespace != "" { mappingList, err = dynamicClient.Resource(NetworkMapGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { mappingList, err = dynamicClient.Resource(NetworkMapGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list network mappings: %v", err) } var mappingNames []string for _, mapping := range mappingList.Items { mappingNames = append(mappingNames, mapping.GetName()) } return mappingNames, nil } // GetAllStorageMappingNames retrieves all storage mapping names from the given namespace func GetAllStorageMappingNames(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) ([]string, error) { dynamicClient, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get dynamic client: %v", err) } var mappingList *unstructured.UnstructuredList if namespace != "" { mappingList, err = dynamicClient.Resource(StorageMapGVR).Namespace(namespace).List(ctx, metav1.ListOptions{}) } else { mappingList, err = dynamicClient.Resource(StorageMapGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) } if err != nil { return nil, fmt.Errorf("failed to list storage mappings: %v", err) } var mappingNames []string for _, mapping := range mappingList.Items { mappingNames = append(mappingNames, mapping.GetName()) } return mappingNames, nil } // HTTPClient represents a client for making HTTP requests with authentication type HTTPClient struct { BaseURL string httpClient *http.Client } // NewHTTPClient creates a new HTTP client with the given base URL and authentication func NewHTTPClient(baseURL string, transport http.RoundTripper) *HTTPClient { if transport == nil { transport = http.DefaultTransport } client := &http.Client{ Transport: transport, } return &HTTPClient{ BaseURL: baseURL, httpClient: client, } } // GetWithContext performs a context-aware HTTP GET request to the specified path with credentials. // This method respects context cancellation and deadlines, making it suitable for long-running // requests or requests that need to be cancelled (e.g., on SIGINT). func (c *HTTPClient) GetWithContext(ctx context.Context, path string) ([]byte, error) { // Split the path into path part and query part parts := strings.SplitN(path, "?", 2) pathPart := parts[0] // Construct the base URL from baseURL and path part fullURL, err := url.JoinPath(c.BaseURL, pathPart) if err != nil { return nil, fmt.Errorf("failed to construct URL: %v", err) } // Append query string if it exists if len(parts) > 1 { fullURL = fullURL + "?" + parts[1] } // Create a context-aware request req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %v", err) } // Debug: Log request details (auth is injected by the Kubernetes transport) klog.V(5).Infof("Making HTTP request to: %s", fullURL) // Execute the request (transport will add auth headers) resp, err := c.httpClient.Do(req) // Debug: Log response details if err == nil { klog.V(5).Infof("Response status: %d %s", resp.StatusCode, resp.Status) } else { klog.V(5).Infof("Request failed: %v", err) } if err != nil { return nil, fmt.Errorf("failed to execute request: %v", err) } defer resp.Body.Close() // Check for non-success status codes if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status) } // Read the response body body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %v", err) } return body, nil } // GetDynamicProviderTypes fetches all DynamicProvider types from the cluster. // Returns an empty slice if the CRD is not available (fails gracefully). func GetDynamicProviderTypes(configFlags *genericclioptions.ConfigFlags) ([]string, error) { dynamicClient, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get dynamic client: %v", err) } ctx := context.Background() // Try to list DynamicProvider resources list, err := dynamicClient.Resource(DynamicProvidersGVR).List(ctx, metav1.ListOptions{}) if err != nil { // Check if it's a "not found" error (CRD doesn't exist) if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "the server could not find the requested resource") { // Fail gracefully - DynamicProvider CRD is not installed return []string{}, nil } return nil, fmt.Errorf("failed to list DynamicProviders: %v", err) } // Extract the types from each DynamicProvider types := make([]string, 0, len(list.Items)) for _, item := range list.Items { providerType, found, err := unstructured.NestedString(item.Object, "spec", "type") if err != nil { continue // Skip items with errors } if found && providerType != "" { types = append(types, providerType) } } return types, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/client/inventory.go
Go
package client import ( "context" "encoding/json" "fmt" "net/url" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/klog/v2" ) // parseJSONResponse parses a JSON response, treating empty or null responses as empty arrays. // For malformed JSON, it provides a helpful error message with a preview of the response. func parseJSONResponse(responseBytes []byte) (interface{}, error) { // Handle empty response as empty array (not an error) if len(responseBytes) == 0 { return []interface{}{}, nil } // Parse the response as JSON var result interface{} if err := json.Unmarshal(responseBytes, &result); err != nil { // Provide more context for debugging malformed responses preview := string(responseBytes) if len(preview) > 100 { preview = preview[:100] + "..." } return nil, fmt.Errorf("failed to parse inventory response as JSON: %v (response preview: %q)", err, preview) } // Handle JSON null as empty array if result == nil { return []interface{}{}, nil } return result, nil } // FetchProvidersWithDetailAndInsecure fetches lists of providers from the inventory server with specified detail level // and optional insecure TLS skip verification func FetchProvidersWithDetailAndInsecure(ctx context.Context, configFlags *genericclioptions.ConfigFlags, baseURL string, detail int, insecureSkipTLS bool) (interface{}, error) { httpClient, err := GetAuthenticatedHTTPClientWithInsecure(ctx, configFlags, baseURL, insecureSkipTLS) if err != nil { return nil, fmt.Errorf("failed to create authenticated HTTP client: %v", err) } // Construct the path for provider inventory with detail level path := fmt.Sprintf("/providers?detail=%d", detail) klog.V(4).Infof("Fetching provider inventory from: %s%s (insecure=%v)", baseURL, path, insecureSkipTLS) // Fetch the provider inventory responseBytes, err := httpClient.GetWithContext(ctx, path) if err != nil { return nil, err } return parseJSONResponse(responseBytes) } // FetchProviderInventoryWithInsecure fetches inventory for a specific provider with optional insecure TLS skip verification func FetchProviderInventoryWithInsecure(ctx context.Context, configFlags *genericclioptions.ConfigFlags, baseURL string, provider *unstructured.Unstructured, subPath string, insecureSkipTLS bool) (interface{}, error) { if provider == nil { return nil, fmt.Errorf("provider is nil") } httpClient, err := GetAuthenticatedHTTPClientWithInsecure(ctx, configFlags, baseURL, insecureSkipTLS) if err != nil { return nil, fmt.Errorf("failed to create authenticated HTTP client: %v", err) } providerType, found, err := unstructured.NestedString(provider.Object, "spec", "type") if err != nil || !found { return nil, fmt.Errorf("provider type not found or error retrieving it: %v", err) } providerUID, found, err := unstructured.NestedString(provider.Object, "metadata", "uid") if err != nil || !found { return nil, fmt.Errorf("provider UID not found or error retrieving it: %v", err) } // Construct the path for provider inventory: /providers/<spec.type>/<metadata.uid> path := fmt.Sprintf("/providers/%s/%s", url.PathEscape(providerType), url.PathEscape(providerUID)) // Add subPath if provided if subPath != "" { path = fmt.Sprintf("%s/%s", path, strings.TrimPrefix(subPath, "/")) } klog.V(4).Infof("Fetching provider inventory from path: %s (insecure=%v)", path, insecureSkipTLS) // Fetch the provider inventory responseBytes, err := httpClient.GetWithContext(ctx, path) if err != nil { return nil, err } return parseJSONResponse(responseBytes) } // FetchSpecificProviderWithDetailAndInsecure fetches inventory for a specific provider by name with specified detail level // and optional insecure TLS skip verification // This function uses direct URL access: /providers/<type>/<uid>?detail=N func FetchSpecificProviderWithDetailAndInsecure(ctx context.Context, configFlags *genericclioptions.ConfigFlags, baseURL string, providerName string, detail int, insecureSkipTLS bool) (interface{}, error) { // We need to determine the namespace to look for the provider CRD // Try to get it from configFlags or use empty string for all namespaces namespace := "" if configFlags.Namespace != nil && *configFlags.Namespace != "" { namespace = *configFlags.Namespace } // First get the provider CRD by name to extract type and UID c, err := GetDynamicClient(configFlags) if err != nil { return nil, fmt.Errorf("failed to get client: %v", err) } var provider *unstructured.Unstructured if namespace != "" { // Get from specific namespace provider, err = c.Resource(ProvidersGVR).Namespace(namespace).Get(ctx, providerName, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("failed to get provider '%s' in namespace '%s': %v", providerName, namespace, err) } } else { // Search all namespaces providersList, err := c.Resource(ProvidersGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) if err != nil { return nil, fmt.Errorf("failed to list providers: %v", err) } var foundProvider *unstructured.Unstructured for _, p := range providersList.Items { if p.GetName() == providerName { foundProvider = &p break } } if foundProvider == nil { return nil, fmt.Errorf("provider '%s' not found", providerName) } provider = foundProvider } // Extract provider type and UID from the CRD providerType, found, err := unstructured.NestedString(provider.Object, "spec", "type") if err != nil || !found { return nil, fmt.Errorf("provider type not found or error retrieving it: %v", err) } providerUID := string(provider.GetUID()) if providerUID == "" { return nil, fmt.Errorf("provider UID not found") } // Use direct URL to fetch provider inventory: /providers/<type>/<uid>?detail=N httpClient, err := GetAuthenticatedHTTPClientWithInsecure(ctx, configFlags, baseURL, insecureSkipTLS) if err != nil { return nil, fmt.Errorf("failed to create authenticated HTTP client: %v", err) } path := fmt.Sprintf("/providers/%s/%s?detail=%d", url.PathEscape(providerType), url.PathEscape(providerUID), detail) klog.V(4).Infof("Fetching specific provider inventory from path: %s (insecure=%v)", path, insecureSkipTLS) // Fetch the provider inventory responseBytes, err := httpClient.GetWithContext(ctx, path) if err != nil { return nil, fmt.Errorf("failed to fetch provider inventory: %v", err) } result, err := parseJSONResponse(responseBytes) if err != nil { return nil, err } // Wrap the result in the same structure as FetchProviders for consistency return map[string]interface{}{ providerType: []interface{}{result}, }, nil } // DiscoverInventoryURL tries to discover the inventory URL from an OpenShift Route func DiscoverInventoryURL(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) string { route, err := GetForkliftInventoryRoute(ctx, configFlags, namespace) if err == nil && route != nil { host, found, _ := unstructured.NestedString(route.Object, "spec", "host") if found && host != "" { return fmt.Sprintf("https://%s", host) } } return "" }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/client/namespace.go
Go
package client import ( "k8s.io/cli-runtime/pkg/genericclioptions" ) // ForkliftMTVNamespace is the default namespace where Forklift MTV CRDs are deployed const OpenShiftMTVNamespace = "openshift-mtv" // ResolveNamespace determines the effective namespace with fallback logic: // 1. Use namespace from command line flags if specified // 2. Use namespace from current kubeconfig context if available // 3. Fall back to "default" namespace if neither is available func ResolveNamespace(configFlags *genericclioptions.ConfigFlags) string { // Check if the namespace is set in the command line flags if configFlags.Namespace != nil && *configFlags.Namespace != "" { return *configFlags.Namespace } // Try to get the namespace from kubeconfig clientConfig := configFlags.ToRawKubeConfigLoader() if clientConfig != nil { namespace, _, err := clientConfig.Namespace() if err == nil && namespace != "" { return namespace } } // Fall back to default namespace if not found in kubeconfig return "default" } // ResolveNamespaceWithAllFlag determines the effective namespace considering the all-namespaces flag: // 1. If allNamespaces is true, return empty string (indicates all namespaces) // 2. Otherwise, use the standard ResolveNamespace logic func ResolveNamespaceWithAllFlag(configFlags *genericclioptions.ConfigFlags, allNamespaces bool) string { if allNamespaces { return "" // Empty string indicates all namespaces in Kubernetes APIs } return ResolveNamespace(configFlags) } // GetProviderNamespace returns the provider namespace, falling back to default if empty. // This is commonly used when provider namespaces may be unspecified and should default // to the same namespace as the resource being created. func GetProviderNamespace(providerNamespace, defaultNamespace string) string { if providerNamespace != "" { return providerNamespace } return defaultNamespace }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/client/operator.go
Go
package client import ( "context" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/cli-runtime/pkg/genericclioptions" ) // MTVOperatorInfo holds information about the MTV Operator installation type MTVOperatorInfo struct { Version string Namespace string Found bool Error string } // GetMTVOperatorInfo discovers information about the MTV Operator installation // by examining the providers.forklift.konveyor.io CRD annotations. // Returns operator version, namespace, whether the operator was found, and any error. func GetMTVOperatorInfo(ctx context.Context, configFlags *genericclioptions.ConfigFlags) MTVOperatorInfo { info := MTVOperatorInfo{ Version: "unknown", Namespace: "", Found: false, Error: "", } // Try to get dynamic client dynamicClient, err := GetDynamicClient(configFlags) if err != nil { info.Error = err.Error() return info } // Check if MTV is installed by looking for the providers CRD crdGVR := schema.GroupVersionResource{ Group: "apiextensions.k8s.io", Version: "v1", Resource: "customresourcedefinitions", } crd, err := dynamicClient.Resource(crdGVR).Get(ctx, "providers.forklift.konveyor.io", metav1.GetOptions{}) if err != nil { // Check if this is a "not found" error vs other errors if strings.Contains(err.Error(), "not found") { // CRD not found means operator is not installed - not an error return info } // Other errors (auth, network, etc.) should be reported info.Error = err.Error() return info } info.Found = true // Try to get version and namespace from operator annotation if annotations, found, _ := unstructured.NestedStringMap(crd.Object, "metadata", "annotations"); found { // Look for operatorframework.io/installed-alongside annotation for key, value := range annotations { if strings.HasPrefix(key, "operatorframework.io/installed-alongside-") { // Format: namespace/operator-name.version parts := strings.Split(value, "/") if len(parts) == 2 { info.Namespace = parts[0] info.Version = parts[1] } break } } } return info } // GetMTVOperatorNamespace returns the namespace where MTV operator is installed. // It first tries to discover it from CRD annotations, then falls back to the // hardcoded OpenShiftMTVNamespace constant if not found. func GetMTVOperatorNamespace(ctx context.Context, configFlags *genericclioptions.ConfigFlags) string { operatorInfo := GetMTVOperatorInfo(ctx, configFlags) if operatorInfo.Found && operatorInfo.Namespace != "" { return operatorInfo.Namespace } // Fall back to hardcoded default return OpenShiftMTVNamespace }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/client/routes.go
Go
package client import ( "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/cli-runtime/pkg/genericclioptions" ) // CanAccessRoutesInNamespace checks if the user has permissions to list routes in the given namespace func CanAccessRoutesInNamespace(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) bool { return CanAccessResource(ctx, configFlags, namespace, RouteGVR, "list") } // GetForkliftInventoryRoute attempts to find a route with the forklift inventory service labels func GetForkliftInventoryRoute(ctx context.Context, configFlags *genericclioptions.ConfigFlags, namespace string) (*unstructured.Unstructured, error) { // Get dynamic client c, err := GetDynamicClient(configFlags) if err != nil { return nil, err } // Create label selector for forklift inventory route labelSelector := "app=forklift,service=forklift-inventory" // Try to discover the MTV operator namespace from CRD annotations mtvNamespace := GetMTVOperatorNamespace(ctx, configFlags) // Check if we have access to the discovered MTV namespace if CanAccessRoutesInNamespace(ctx, configFlags, mtvNamespace) { // Try to find the route in the MTV operator namespace routes, err := c.Resource(RouteGVR).Namespace(mtvNamespace).List(ctx, metav1.ListOptions{ LabelSelector: labelSelector, }) // If we find a route in MTV operator namespace, return it if err == nil && len(routes.Items) > 0 { return &routes.Items[0], nil } } // If we couldn't find the route in MTV operator namespace or didn't have permissions, // try the provided namespace routes, err := c.Resource(RouteGVR).Namespace(namespace).List(ctx, metav1.ListOptions{ LabelSelector: labelSelector, }) if err != nil { return nil, err } // Return the first matching route if found if len(routes.Items) > 0 { return &routes.Items[0], nil } return nil, fmt.Errorf("no matching route found") }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/client/token.go
Go
package client import ( "context" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/klog/v2" ) // Fallback namespaces where Forklift/MTV controller may be deployed // Used only when auto-detection fails var fallbackForkliftNamespaces = []string{ "openshift-mtv", // OpenShift MTV (most common) "konveyor-forklift", // Community Forklift } // GetServiceAccountTokenForInventory attempts to retrieve a service account token // for use with the MTV inventory service when the kubeconfig uses client certificate authentication. // // This is needed for Kind and similar clusters where: // - The kubeconfig uses client certificates for authentication // - The MTV inventory service validates bearer tokens, not client certificates // // The function first tries to auto-detect the operator namespace from CRD annotations. // If that fails, it falls back to known namespace locations. // // RBAC Requirements: The service account running this code must have 'get' and 'list' // permissions on secrets in the forklift namespace. // // Returns: bearer token string (empty if not found), success boolean func GetServiceAccountTokenForInventory(ctx context.Context, configFlags *genericclioptions.ConfigFlags, config *rest.Config) (string, bool) { // Defensive check: ensure config is not nil if config == nil { klog.V(5).Infof("Cannot retrieve service account token: config is nil") return "", false } klog.V(5).Infof("Attempting to retrieve service account token for inventory service authentication") // Create a Kubernetes clientset using the existing config (with client certs) clientset, err := kubernetes.NewForConfig(config) if err != nil { klog.V(5).Infof("Failed to create Kubernetes clientset: %v", err) return "", false } serviceAccountName := "forklift-controller" // First, try to auto-detect the operator namespace from CRD annotations if configFlags != nil { operatorInfo := GetMTVOperatorInfo(ctx, configFlags) if operatorInfo.Found && operatorInfo.Namespace != "" { klog.V(5).Infof("Auto-detected operator namespace: %s", operatorInfo.Namespace) if token, ok := getServiceAccountTokenInNamespace(ctx, clientset, operatorInfo.Namespace, serviceAccountName); ok { return token, true } klog.V(5).Infof("No service account token found in auto-detected namespace %s, trying fallback namespaces", operatorInfo.Namespace) } else { klog.V(5).Infof("Could not auto-detect operator namespace (found=%v, error=%s), trying fallback namespaces", operatorInfo.Found, operatorInfo.Error) } } else { klog.V(5).Infof("configFlags is nil, skipping namespace auto-detection, trying fallback namespaces") } // Fallback: try known namespaces where forklift might be deployed for _, namespace := range fallbackForkliftNamespaces { klog.V(5).Infof("Trying fallback namespace: %s", namespace) if token, ok := getServiceAccountTokenInNamespace(ctx, clientset, namespace, serviceAccountName); ok { return token, true } } klog.V(5).Infof("No service account token found in any forklift namespace") return "", false } // getServiceAccountTokenInNamespace attempts to retrieve a service account token from a specific namespace func getServiceAccountTokenInNamespace(ctx context.Context, clientset *kubernetes.Clientset, namespace, serviceAccountName string) (string, bool) { // Try method 1: Get a secret named exactly "forklift-controller-token" // (older Kubernetes versions create this automatically) secret, err := clientset.CoreV1().Secrets(namespace).Get(ctx, serviceAccountName+"-token", metav1.GetOptions{}) if err == nil && secret.Type == corev1.SecretTypeServiceAccountToken { if token, ok := secret.Data["token"]; ok && len(token) > 0 { klog.V(5).Infof("Found service account token in secret %s/%s (length: %d)", namespace, secret.Name, len(token)) return string(token), true } } // Try method 2: List all secrets and find one associated with the service account // This handles: // - Auto-generated secrets with random suffixes (forklift-controller-token-xxxxx) // - Manually created secrets with service account annotations klog.V(5).Infof("Secret %s not found in %s, listing all secrets", serviceAccountName+"-token", namespace) secrets, err := clientset.CoreV1().Secrets(namespace).List(ctx, metav1.ListOptions{}) if err != nil { klog.V(5).Infof("Failed to list secrets in namespace %s: %v", namespace, err) return "", false } for _, s := range secrets.Items { // Check if this secret is associated with our service account and is the correct type // Match by name prefix or by annotation isServiceAccountToken := false if strings.HasPrefix(s.Name, serviceAccountName+"-token-") { isServiceAccountToken = true } else if s.Annotations != nil && s.Annotations[corev1.ServiceAccountNameKey] == serviceAccountName { isServiceAccountToken = true } // Only process secrets of the correct type if isServiceAccountToken && s.Type == corev1.SecretTypeServiceAccountToken { if token, ok := s.Data["token"]; ok && len(token) > 0 { klog.V(5).Infof("Found service account token in secret %s/%s (length: %d)", namespace, s.Name, len(token)) return string(token), true } } } klog.V(5).Infof("No service account token found for %s/%s", namespace, serviceAccountName) return "", false } // NeedsBearerTokenForInventory determines if we need to retrieve a bearer token // for inventory service authentication. // // Returns true when: // - Using client certificate authentication (CertData or CertFile is set) // - AND no bearer token is already configured // // This indicates a Kind/minikube-style cluster where the inventory service // needs a bearer token instead of client certificates. func NeedsBearerTokenForInventory(config *rest.Config) bool { // Defensive check: ensure config is not nil if config == nil { return false } usingClientCert := (config.CertData != nil || config.CertFile != "") hasBearerToken := (config.BearerToken != "" || config.BearerTokenFile != "") return usingClientCert && !hasBearerToken }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/completion/completion.go
Go
package completion import ( "context" "fmt" "strings" "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/cli-runtime/pkg/genericclioptions" "github.com/yaacov/kubectl-mtv/pkg/cmd/get/inventory" "github.com/yaacov/kubectl-mtv/pkg/util/client" ) // getResourceNames fetches resource names for completion func getResourceNames(ctx context.Context, configFlags *genericclioptions.ConfigFlags, gvr schema.GroupVersionResource, namespace string) ([]string, error) { c, err := client.GetDynamicClient(configFlags) if err != nil { return nil, err } var list []string // List resources if namespace != "" { resources, err := c.Resource(gvr).Namespace(namespace).List(ctx, metav1.ListOptions{}) if err != nil { return nil, err } for _, resource := range resources.Items { list = append(list, resource.GetName()) } } else { resources, err := c.Resource(gvr).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) if err != nil { return nil, err } for _, resource := range resources.Items { list = append(list, resource.GetName()) } } return list, nil } // PlanNameCompletion provides completion for plan names func PlanNameCompletion(configFlags *genericclioptions.ConfigFlags) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { namespace := client.ResolveNamespace(configFlags) names, err := getResourceNames(context.Background(), configFlags, client.PlansGVR, namespace) if err != nil { return []string{fmt.Sprintf("Error fetching plans: %v", err)}, cobra.ShellCompDirectiveError } if len(names) == 0 { namespaceMsg := "current namespace" if namespace != "" { namespaceMsg = fmt.Sprintf("namespace '%s'", namespace) } return []string{fmt.Sprintf("No migration plans found in %s", namespaceMsg)}, cobra.ShellCompDirectiveError } // Filter results based on what's already typed var filtered []string for _, name := range names { if strings.HasPrefix(name, toComplete) { filtered = append(filtered, name) } } if len(filtered) == 0 && toComplete != "" { return []string{fmt.Sprintf("No migration plans matching '%s'", toComplete)}, cobra.ShellCompDirectiveError } return filtered, cobra.ShellCompDirectiveNoFileComp } } // ProviderNameCompletion provides completion for provider names func ProviderNameCompletion(configFlags *genericclioptions.ConfigFlags) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return ProviderNameCompletionByType(configFlags, "") } // ProviderNameCompletionByType provides completion for provider names filtered by provider type // If providerType is empty, returns all providers func ProviderNameCompletionByType(configFlags *genericclioptions.ConfigFlags, providerType string) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { namespace := client.ResolveNamespace(configFlags) // Get all providers c, err := client.GetDynamicClient(configFlags) if err != nil { return []string{fmt.Sprintf("Error getting client: %v", err)}, cobra.ShellCompDirectiveError } resources, err := c.Resource(client.ProvidersGVR).Namespace(namespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return []string{fmt.Sprintf("Error fetching providers: %v", err)}, cobra.ShellCompDirectiveError } if len(resources.Items) == 0 { namespaceMsg := "current namespace" if namespace != "" { namespaceMsg = fmt.Sprintf("namespace '%s'", namespace) } return []string{fmt.Sprintf("No providers found in %s", namespaceMsg)}, cobra.ShellCompDirectiveError } // Filter providers by type if specified var filtered []string for _, resource := range resources.Items { resourceName := resource.GetName() // Skip if doesn't match what's being typed if !strings.HasPrefix(resourceName, toComplete) { continue } // If provider type filter is specified, check the provider type if providerType != "" { resourceType, found, err := unstructured.NestedString(resource.Object, "spec", "type") if err != nil || !found || resourceType != providerType { continue } } filtered = append(filtered, resourceName) } if len(filtered) == 0 { if providerType != "" { if toComplete != "" { return []string{fmt.Sprintf("No %s providers matching '%s'", providerType, toComplete)}, cobra.ShellCompDirectiveError } return []string{fmt.Sprintf("No %s providers found", providerType)}, cobra.ShellCompDirectiveError } else { if toComplete != "" { return []string{fmt.Sprintf("No providers matching '%s'", toComplete)}, cobra.ShellCompDirectiveError } return []string{"No providers found"}, cobra.ShellCompDirectiveError } } return filtered, cobra.ShellCompDirectiveNoFileComp } } // MappingNameCompletion provides completion for mapping names // mappingType should be "network" or "storage" func MappingNameCompletion(configFlags *genericclioptions.ConfigFlags, mappingType string) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { namespace := client.ResolveNamespace(configFlags) var gvr schema.GroupVersionResource var resourceType string if mappingType == "storage" { gvr = client.StorageMapGVR resourceType = "storage mappings" } else { gvr = client.NetworkMapGVR resourceType = "network mappings" } names, err := getResourceNames(context.Background(), configFlags, gvr, namespace) if err != nil { return []string{fmt.Sprintf("Error fetching %s: %v", resourceType, err)}, cobra.ShellCompDirectiveError } if len(names) == 0 { namespaceMsg := "current namespace" if namespace != "" { namespaceMsg = fmt.Sprintf("namespace '%s'", namespace) } return []string{fmt.Sprintf("No %s found in %s", resourceType, namespaceMsg)}, cobra.ShellCompDirectiveError } // Filter results based on what's already typed var filtered []string for _, name := range names { if strings.HasPrefix(name, toComplete) { filtered = append(filtered, name) } } if len(filtered) == 0 && toComplete != "" { return []string{fmt.Sprintf("No %s matching '%s'", resourceType, toComplete)}, cobra.ShellCompDirectiveError } return filtered, cobra.ShellCompDirectiveNoFileComp } } // HostIDCompletion provides completion for host inventory IDs from provider inventory. // These are vSphere managed object IDs (e.g. "host-8"), not display names or IP addresses. func HostIDCompletion(configFlags *genericclioptions.ConfigFlags, providerName, toComplete string) ([]string, cobra.ShellCompDirective) { if providerName == "" { return []string{"Provider not specified"}, cobra.ShellCompDirectiveError } namespace := client.ResolveNamespace(configFlags) inventoryURL := client.DiscoverInventoryURL(context.Background(), configFlags, namespace) // Validate provider is vSphere provider, err := inventory.GetProviderByName(context.Background(), configFlags, providerName, namespace) if err != nil { return []string{fmt.Sprintf("Error getting provider: %v", err)}, cobra.ShellCompDirectiveError } // Check if it's a vSphere provider providerType, found, err := unstructured.NestedString(provider.Object, "spec", "type") if err != nil || !found { return []string{fmt.Sprintf("Error getting provider type: %v", err)}, cobra.ShellCompDirectiveError } if providerType != "vsphere" { return []string{fmt.Sprintf("Only vSphere providers support hosts, got: %s", providerType)}, cobra.ShellCompDirectiveError } // Get available hosts // Note: Completion functions use insecure=false as a safe default providerClient := inventory.NewProviderClientWithInsecure(configFlags, provider, inventoryURL, false) data, err := providerClient.GetHosts(context.Background(), 4) if err != nil { return []string{fmt.Sprintf("Error fetching hosts: %v", err)}, cobra.ShellCompDirectiveError } // Convert to expected format dataArray, ok := data.([]interface{}) if !ok { return []string{"Error: unexpected data format for host inventory"}, cobra.ShellCompDirectiveError } // Extract host IDs var hostIDs []string for _, item := range dataArray { if host, ok := item.(map[string]interface{}); ok { if id, ok := host["id"].(string); ok { if strings.HasPrefix(id, toComplete) { hostIDs = append(hostIDs, id) } } } } if len(hostIDs) == 0 { if toComplete != "" { return []string{fmt.Sprintf("No host IDs matching '%s'", toComplete)}, cobra.ShellCompDirectiveError } return []string{"No host IDs found"}, cobra.ShellCompDirectiveError } return hostIDs, cobra.ShellCompDirectiveNoFileComp } // HostIPAddressCompletion provides completion for IP addresses from host network adapters func HostIPAddressCompletion(configFlags *genericclioptions.ConfigFlags, providerName string, hostNames []string, toComplete string) ([]string, cobra.ShellCompDirective) { if providerName == "" { return []string{"Provider not specified"}, cobra.ShellCompDirectiveError } if len(hostNames) == 0 { return []string{"No hosts specified"}, cobra.ShellCompDirectiveError } namespace := client.ResolveNamespace(configFlags) inventoryURL := client.DiscoverInventoryURL(context.Background(), configFlags, namespace) // Get provider provider, err := inventory.GetProviderByName(context.Background(), configFlags, providerName, namespace) if err != nil { return []string{fmt.Sprintf("Error getting provider: %v", err)}, cobra.ShellCompDirectiveError } // Get available hosts // Note: Completion functions use insecure=false as a safe default providerClient := inventory.NewProviderClientWithInsecure(configFlags, provider, inventoryURL, false) data, err := providerClient.GetHosts(context.Background(), 4) if err != nil { return []string{fmt.Sprintf("Error fetching hosts: %v", err)}, cobra.ShellCompDirectiveError } dataArray, ok := data.([]interface{}) if !ok { return []string{"Error: unexpected data format for host inventory"}, cobra.ShellCompDirectiveError } // Extract IP addresses from specified hosts' network adapters var ipAddresses []string seenIPs := make(map[string]bool) for _, item := range dataArray { if host, ok := item.(map[string]interface{}); ok { if hostID, ok := host["id"].(string); ok { // Check if this host is in our list hostInList := false for _, requestedHost := range hostNames { if hostID == requestedHost { hostInList = true break } } if !hostInList { continue } // Extract IP addresses from network adapters if networkAdapters, ok := host["networkAdapters"].([]interface{}); ok { for _, adapter := range networkAdapters { if adapterMap, ok := adapter.(map[string]interface{}); ok { if ipAddress, ok := adapterMap["ipAddress"].(string); ok && ipAddress != "" { if strings.HasPrefix(ipAddress, toComplete) && !seenIPs[ipAddress] { ipAddresses = append(ipAddresses, ipAddress) seenIPs[ipAddress] = true } } } } } } } } if len(ipAddresses) == 0 { if toComplete != "" { return []string{fmt.Sprintf("No IP addresses matching '%s' found for specified hosts", toComplete)}, cobra.ShellCompDirectiveError } return []string{"No IP addresses found for specified hosts"}, cobra.ShellCompDirectiveError } return ipAddresses, cobra.ShellCompDirectiveNoFileComp } // HostNetworkAdapterCompletion provides completion for network adapter names from host inventory func HostNetworkAdapterCompletion(configFlags *genericclioptions.ConfigFlags, providerName string, hostNames []string, toComplete string) ([]string, cobra.ShellCompDirective) { if providerName == "" { return []string{"Provider not specified"}, cobra.ShellCompDirectiveError } if len(hostNames) == 0 { return []string{"No hosts specified"}, cobra.ShellCompDirectiveError } namespace := client.ResolveNamespace(configFlags) inventoryURL := client.DiscoverInventoryURL(context.Background(), configFlags, namespace) // Get provider provider, err := inventory.GetProviderByName(context.Background(), configFlags, providerName, namespace) if err != nil { return []string{fmt.Sprintf("Error getting provider: %v", err)}, cobra.ShellCompDirectiveError } // Get available hosts // Note: Completion functions use insecure=false as a safe default providerClient := inventory.NewProviderClientWithInsecure(configFlags, provider, inventoryURL, false) data, err := providerClient.GetHosts(context.Background(), 4) if err != nil { return []string{fmt.Sprintf("Error fetching hosts: %v", err)}, cobra.ShellCompDirectiveError } dataArray, ok := data.([]interface{}) if !ok { return []string{"Error: unexpected data format for host inventory"}, cobra.ShellCompDirectiveError } // Extract network adapter names from specified hosts var adapterNames []string seenAdapters := make(map[string]bool) for _, item := range dataArray { if host, ok := item.(map[string]interface{}); ok { if hostID, ok := host["id"].(string); ok { // Check if this host is in our list hostInList := false for _, requestedHost := range hostNames { if hostID == requestedHost { hostInList = true break } } if !hostInList { continue } // Extract adapter names from network adapters if networkAdapters, ok := host["networkAdapters"].([]interface{}); ok { for _, adapter := range networkAdapters { if adapterMap, ok := adapter.(map[string]interface{}); ok { if adapterName, ok := adapterMap["name"].(string); ok && adapterName != "" { if strings.HasPrefix(adapterName, toComplete) && !seenAdapters[adapterName] { adapterNames = append(adapterNames, adapterName) seenAdapters[adapterName] = true } } } } } } } } if len(adapterNames) == 0 { if toComplete != "" { return []string{fmt.Sprintf("No network adapters matching '%s' found for specified hosts", toComplete)}, cobra.ShellCompDirectiveError } return []string{"No network adapters found for specified hosts"}, cobra.ShellCompDirectiveError } return adapterNames, cobra.ShellCompDirectiveNoFileComp } // MigrationNameCompletion provides completion for migration names func MigrationNameCompletion(configFlags *genericclioptions.ConfigFlags) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { namespace := client.ResolveNamespace(configFlags) names, err := getResourceNames(context.Background(), configFlags, client.MigrationsGVR, namespace) if err != nil { return []string{fmt.Sprintf("Error fetching migrations: %v", err)}, cobra.ShellCompDirectiveError } if len(names) == 0 { namespaceMsg := "current namespace" if namespace != "" { namespaceMsg = fmt.Sprintf("namespace '%s'", namespace) } return []string{fmt.Sprintf("No migrations found in %s", namespaceMsg)}, cobra.ShellCompDirectiveError } // Filter results based on what's already typed var filtered []string for _, name := range names { if strings.HasPrefix(name, toComplete) { filtered = append(filtered, name) } } if len(filtered) == 0 && toComplete != "" { return []string{fmt.Sprintf("No migrations matching '%s'", toComplete)}, cobra.ShellCompDirectiveError } return filtered, cobra.ShellCompDirectiveNoFileComp } } // HookResourceNameCompletion provides completion for hook resource names func HookResourceNameCompletion(configFlags *genericclioptions.ConfigFlags) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { namespace := client.ResolveNamespace(configFlags) names, err := getResourceNames(context.Background(), configFlags, client.HooksGVR, namespace) if err != nil { return []string{fmt.Sprintf("Error fetching hooks: %v", err)}, cobra.ShellCompDirectiveError } if len(names) == 0 { namespaceMsg := "current namespace" if namespace != "" { namespaceMsg = fmt.Sprintf("namespace '%s'", namespace) } return []string{fmt.Sprintf("No hook resources found in %s", namespaceMsg)}, cobra.ShellCompDirectiveError } // Filter results based on what's already typed var filtered []string for _, name := range names { if strings.HasPrefix(name, toComplete) { filtered = append(filtered, name) } } return filtered, cobra.ShellCompDirectiveNoFileComp } } // HostResourceNameCompletion provides completion for host resource names func HostResourceNameCompletion(configFlags *genericclioptions.ConfigFlags) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { namespace := client.ResolveNamespace(configFlags) names, err := getResourceNames(context.Background(), configFlags, client.HostsGVR, namespace) if err != nil { return []string{fmt.Sprintf("Error fetching hosts: %v", err)}, cobra.ShellCompDirectiveError } if len(names) == 0 { namespaceMsg := "current namespace" if namespace != "" { namespaceMsg = fmt.Sprintf("namespace '%s'", namespace) } return []string{fmt.Sprintf("No host resources found in %s", namespaceMsg)}, cobra.ShellCompDirectiveError } // Filter results based on what's already typed var filtered []string for _, name := range names { if strings.HasPrefix(name, toComplete) { filtered = append(filtered, name) } } if len(filtered) == 0 && toComplete != "" { return []string{fmt.Sprintf("No host resources matching '%s'", toComplete)}, cobra.ShellCompDirectiveError } return filtered, cobra.ShellCompDirectiveNoFileComp } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/config/interfaces.go
Go
package config import "k8s.io/cli-runtime/pkg/genericclioptions" // InventoryConfigGetter defines the interface for getting inventory service configuration. // This interface is shared across multiple commands that need to access the MTV inventory service. type InventoryConfigGetter interface { GetInventoryURL() string GetInventoryInsecureSkipTLS() bool } // InventoryConfigWithKubeFlags extends InventoryConfigGetter with KubeConfigFlags access. // This is useful for commands that need inventory configuration and Kubernetes client access. type InventoryConfigWithKubeFlags interface { InventoryConfigGetter GetKubeConfigFlags() *genericclioptions.ConfigFlags } // InventoryConfigWithVerbosity extends InventoryConfigGetter with verbosity control. // This is useful for commands that need inventory configuration and logging control. type InventoryConfigWithVerbosity interface { InventoryConfigGetter GetVerbosity() int } // GlobalConfigGetter defines the full interface for accessing global configuration. // This extends InventoryConfigGetter with additional configuration methods used by various commands. type GlobalConfigGetter interface { InventoryConfigGetter GetVerbosity() int GetAllNamespaces() bool GetUseUTC() bool GetKubeConfigFlags() *genericclioptions.ConfigFlags }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/flags/mapping_type.go
Go
package flags import ( "fmt" ) // MappingTypeFlag implements pflag.Value interface for mapping type validation type MappingTypeFlag struct { value string } func (m *MappingTypeFlag) String() string { return m.value } func (m *MappingTypeFlag) Set(value string) error { validTypes := []string{"network", "storage"} isValid := false for _, validType := range validTypes { if value == validType { isValid = true break } } if !isValid { return fmt.Errorf("invalid mapping type: %s. Valid types are: network, storage", value) } m.value = value return nil } func (m *MappingTypeFlag) Type() string { return "string" } // GetValue returns the mapping type value func (m *MappingTypeFlag) GetValue() string { return m.value } // GetValidValues returns all valid mapping type values for auto-completion func (m *MappingTypeFlag) GetValidValues() []string { return []string{"network", "storage"} } // NewMappingTypeFlag creates a new mapping type flag with default value "network" func NewMappingTypeFlag() *MappingTypeFlag { return &MappingTypeFlag{ value: "network", // Default value set here } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/flags/migration_type.go
Go
package flags import ( "fmt" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" ) // MigrationTypeFlag implements pflag.Value interface for migration type validation type MigrationTypeFlag struct { value v1beta1.MigrationType } func (m *MigrationTypeFlag) String() string { return string(m.value) } func (m *MigrationTypeFlag) Set(value string) error { validTypes := []v1beta1.MigrationType{v1beta1.MigrationCold, v1beta1.MigrationWarm, v1beta1.MigrationLive, v1beta1.MigrationOnlyConversion} isValid := false for _, validType := range validTypes { if v1beta1.MigrationType(value) == validType { isValid = true break } } if !isValid { return fmt.Errorf("invalid migration type: %s. Valid types are: cold, warm, live, conversion", value) } m.value = v1beta1.MigrationType(value) return nil } func (m *MigrationTypeFlag) Type() string { return "string" } // GetValue returns the migration type value func (m *MigrationTypeFlag) GetValue() v1beta1.MigrationType { return m.value } // GetValidValues returns all valid migration type values for auto-completion func (m *MigrationTypeFlag) GetValidValues() []string { return []string{"cold", "warm", "live", "conversion"} } // NewMigrationTypeFlag creates a new migration type flag func NewMigrationTypeFlag() *MigrationTypeFlag { return &MigrationTypeFlag{} }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/flags/output_format_type.go
Go
package flags import ( "fmt" ) // OutputFormatTypeFlag implements pflag.Value interface for output format type validation type OutputFormatTypeFlag struct { value string validFormats []string } func (o *OutputFormatTypeFlag) String() string { return o.value } func (o *OutputFormatTypeFlag) Set(value string) error { isValid := false for _, validType := range o.validFormats { if value == validType { isValid = true break } } if !isValid { return fmt.Errorf("invalid output format: %s. Valid formats are: %v", value, o.validFormats) } o.value = value return nil } func (o *OutputFormatTypeFlag) Type() string { return "string" } // GetValue returns the output format type value func (o *OutputFormatTypeFlag) GetValue() string { return o.value } // GetValidValues returns all valid output format type values for auto-completion func (o *OutputFormatTypeFlag) GetValidValues() []string { return o.validFormats } // NewOutputFormatTypeFlag creates a new output format type flag with standard formats func NewOutputFormatTypeFlag() *OutputFormatTypeFlag { return &OutputFormatTypeFlag{ validFormats: []string{"table", "json", "yaml"}, value: "table", // default value } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/flags/provider_type.go
Go
package flags import ( "fmt" "strings" forkliftv1beta1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" ) // staticProviderTypes is the single source of truth for built-in provider types. var staticProviderTypes = []forkliftv1beta1.ProviderType{ forkliftv1beta1.OpenShift, forkliftv1beta1.VSphere, forkliftv1beta1.OVirt, forkliftv1beta1.OpenStack, forkliftv1beta1.Ova, forkliftv1beta1.HyperV, forkliftv1beta1.EC2, } // staticProviderTypeStrings returns the string representations of static provider types. func staticProviderTypeStrings() []string { strs := make([]string, len(staticProviderTypes)) for i, t := range staticProviderTypes { strs[i] = string(t) } return strs } // ProviderTypeFlag implements pflag.Value interface for provider type validation type ProviderTypeFlag struct { value string dynamicTypes []string } func (p *ProviderTypeFlag) String() string { return p.value } func (p *ProviderTypeFlag) Set(value string) error { // Check static types isValid := false for _, validType := range staticProviderTypes { if forkliftv1beta1.ProviderType(value) == validType { isValid = true break } } // Check dynamic types if not found in static types if !isValid { for _, dynamicType := range p.dynamicTypes { if value == dynamicType { isValid = true break } } } if !isValid { validTypesStr := strings.Join(staticProviderTypeStrings(), ", ") if len(p.dynamicTypes) > 0 { validTypesStr = fmt.Sprintf("%s, %s", validTypesStr, strings.Join(p.dynamicTypes, ", ")) } return fmt.Errorf("invalid provider type: %s. Valid types are: %s", value, validTypesStr) } p.value = value return nil } func (p *ProviderTypeFlag) Type() string { return "string" } // GetValue returns the provider type value func (p *ProviderTypeFlag) GetValue() string { return p.value } // GetValidValues returns all valid provider type values for auto-completion func (p *ProviderTypeFlag) GetValidValues() []string { staticStrs := staticProviderTypeStrings() // Combine static and dynamic types allTypes := make([]string, 0, len(staticStrs)+len(p.dynamicTypes)) allTypes = append(allTypes, staticStrs...) allTypes = append(allTypes, p.dynamicTypes...) return allTypes } // SetDynamicTypes sets the list of dynamic provider types from the cluster func (p *ProviderTypeFlag) SetDynamicTypes(types []string) { p.dynamicTypes = types } // NewProviderTypeFlag creates a new provider type flag func NewProviderTypeFlag() *ProviderTypeFlag { return &ProviderTypeFlag{ dynamicTypes: []string{}, } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/flags/sdk_endpoint_type.go
Go
package flags import ( "fmt" ) // SdkEndpointTypeFlag implements pflag.Value interface for SDK endpoint type validation type SdkEndpointTypeFlag struct { value string } func (s *SdkEndpointTypeFlag) String() string { return s.value } func (s *SdkEndpointTypeFlag) Set(value string) error { validTypes := []string{"vcenter", "esxi"} isValid := false for _, validType := range validTypes { if value == validType { isValid = true break } } if !isValid { return fmt.Errorf("invalid SDK endpoint type: %s. Valid types are: vcenter, esxi", value) } s.value = value return nil } func (s *SdkEndpointTypeFlag) Type() string { return "string" } // GetValue returns the SDK endpoint type value func (s *SdkEndpointTypeFlag) GetValue() string { return s.value } // GetValidValues returns all valid SDK endpoint type values for auto-completion func (s *SdkEndpointTypeFlag) GetValidValues() []string { return []string{"vcenter", "esxi"} } // NewSdkEndpointTypeFlag creates a new SDK endpoint type flag func NewSdkEndpointTypeFlag() *SdkEndpointTypeFlag { return &SdkEndpointTypeFlag{} }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/flags/vm_inventory_output_type.go
Go
package flags import ( "fmt" ) // VMInventoryOutputTypeFlag implements pflag.Value interface for VM inventory output format validation type VMInventoryOutputTypeFlag struct { value string } func (v *VMInventoryOutputTypeFlag) String() string { return v.value } func (v *VMInventoryOutputTypeFlag) Set(value string) error { validTypes := []string{"table", "json", "yaml", "planvms"} isValid := false for _, validType := range validTypes { if value == validType { isValid = true break } } if !isValid { return fmt.Errorf("invalid VM inventory output format: %s. Valid formats are: table, json, yaml, planvms", value) } v.value = value return nil } func (v *VMInventoryOutputTypeFlag) Type() string { return "string" } // GetValue returns the VM inventory output format value func (v *VMInventoryOutputTypeFlag) GetValue() string { return v.value } // GetValidValues returns all valid VM inventory output format values for auto-completion func (v *VMInventoryOutputTypeFlag) GetValidValues() []string { return []string{"table", "json", "yaml", "planvms"} } // SetDefault sets the default value for the VM inventory output format func (v *VMInventoryOutputTypeFlag) SetDefault(defaultValue string) { v.value = defaultValue } // NewVMInventoryOutputTypeFlag creates a new VM inventory output format type flag func NewVMInventoryOutputTypeFlag() *VMInventoryOutputTypeFlag { return &VMInventoryOutputTypeFlag{ value: "table", // default value } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/output/color.go
Go
package output import ( "fmt" "regexp" "strings" ) // ANSI color codes const ( Reset = "\033[0m" BoldText = "\033[1m" RedColor = "\033[31m" GreenColor = "\033[32m" YellowColor = "\033[33m" BlueColor = "\033[34m" PurpleColor = "\033[35m" CyanColor = "\033[36m" White = "\033[37m" BoldRed = "\033[1;31m" BoldGreen = "\033[1;32m" BoldYellow = "\033[1;33m" BoldBlue = "\033[1;34m" ) // ansiRegex is a regular expression that matches ANSI color escape codes var ansiRegex = regexp.MustCompile("\033\\[[0-9;]*m") // Bold returns a bold-formatted string func Bold(text string) string { return ColorizedString(text, BoldText) } // ColorizedString returns a string with the specified color applied func ColorizedString(text string, color string) string { return color + text + Reset } // Yellow returns a yellow-colored string func Yellow(text string) string { return ColorizedString(text, YellowColor) } // Green returns a green-colored string func Green(text string) string { return ColorizedString(text, GreenColor) } // Red returns a red-colored string func Red(text string) string { return ColorizedString(text, RedColor) } // Blue returns a blue-colored string func Blue(text string) string { return ColorizedString(text, BlueColor) } // Cyan returns a cyan-colored string func Cyan(text string) string { return ColorizedString(text, CyanColor) } // StripANSI removes ANSI color codes from a string func StripANSI(text string) string { return ansiRegex.ReplaceAllString(text, "") } // VisibleLength returns the visible length of a string, excluding ANSI color codes func VisibleLength(text string) int { return len(StripANSI(text)) } // ColorizeStatus returns a colored string based on status value func ColorizeStatus(status string) string { status = strings.TrimSpace(status) switch strings.ToLower(status) { case "running": return Blue(status) case "executing": return Blue(status) case "completed": return Green(status) case "pending": return Yellow(status) case "failed": return Red(status) case "canceled": return Cyan(status) default: return status } } // ColorizeNumber returns a blue-colored number for migration progress func ColorizeNumber(number interface{}) string { return Blue(fmt.Sprintf("%v", number)) } // ColorizeBoolean returns a colored string based on boolean value func ColorizeBoolean(b bool) string { if b { return Green(fmt.Sprintf("%t", b)) } return fmt.Sprintf("%t", b) } // ColorizedSeparator returns a separator line with the specified color func ColorizedSeparator(length int, color string) string { return ColorizedString(strings.Repeat("=", length), color) }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/output/json.go
Go
package output // PrintJSON prints the given data as JSON using JSONPrinter import ( "encoding/json" "fmt" "io" "os" ) // PrintJSONWithEmpty prints the given data as JSON using JSONPrinter with empty handling func PrintJSONWithEmpty(data interface{}, emptyMessage string) error { // Convert data to []map[string]interface{} if possible items, ok := data.([]map[string]interface{}) printer := NewJSONPrinter().WithPrettyPrint(true) if ok { if len(items) == 0 && emptyMessage != "" { return printer.PrintEmpty(emptyMessage) } printer.AddItems(items) } else if item, ok := data.(map[string]interface{}); ok { printer.AddItem(item) } else { // Fallback: marshal any data b, err := json.MarshalIndent(data, "", " ") if err != nil { return err } _, err = fmt.Fprintln(os.Stdout, string(b)) return err } return printer.Print() } // JSONPrinter prints data as JSON type JSONPrinter struct { items []map[string]interface{} writer io.Writer prettyPrint bool } // NewJSONPrinter creates a new JSONPrinter func NewJSONPrinter() *JSONPrinter { return &JSONPrinter{ items: []map[string]interface{}{}, writer: os.Stdout, prettyPrint: false, } } // WithWriter sets the output writer func (j *JSONPrinter) WithWriter(writer io.Writer) *JSONPrinter { j.writer = writer return j } // WithPrettyPrint enables or disables pretty printing (indentation) func (j *JSONPrinter) WithPrettyPrint(pretty bool) *JSONPrinter { j.prettyPrint = pretty return j } // AddItem adds an item to the JSON output func (j *JSONPrinter) AddItem(item map[string]interface{}) *JSONPrinter { j.items = append(j.items, item) return j } // AddItems adds multiple items to the JSON output func (j *JSONPrinter) AddItems(items []map[string]interface{}) *JSONPrinter { j.items = append(j.items, items...) return j } // Print outputs the items as JSON func (j *JSONPrinter) Print() error { var data []byte var err error if j.prettyPrint { data, err = json.MarshalIndent(j.items, "", " ") } else { data, err = json.Marshal(j.items) } if err != nil { return fmt.Errorf("failed to marshal JSON: %v", err) } _, err = fmt.Fprintln(j.writer, string(data)) return err } // PrintEmpty outputs an empty JSON array or a message when there are no items func (j *JSONPrinter) PrintEmpty(message string) error { var data []byte var err error if message == "" { // If no message, just print an empty array if j.prettyPrint { data, err = json.MarshalIndent([]interface{}{}, "", " ") } else { data, err = json.Marshal([]interface{}{}) } } else { // If message provided, print only the message result := map[string]interface{}{ "message": message, } if j.prettyPrint { data, err = json.MarshalIndent(result, "", " ") } else { data, err = json.Marshal(result) } } if err != nil { return fmt.Errorf("failed to marshal JSON: %v", err) } _, err = fmt.Fprintln(j.writer, string(data)) return err }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/output/table.go
Go
package output // PrintTable prints the given data as a table using TablePrinter and headers import ( "fmt" "io" "os" "strings" "unicode/utf8" "github.com/yaacov/kubectl-mtv/pkg/util/query" ) // PrintTableWithQuery prints the given data as a table using TablePrinter, // supporting dynamic headers from query options and empty message handling. func PrintTableWithQuery(data interface{}, defaultHeaders []Header, queryOpts *query.QueryOptions, emptyMessage string) error { items, ok := data.([]map[string]interface{}) if !ok { if item, ok := data.(map[string]interface{}); ok { // Handle single item map items = []map[string]interface{}{item} } else if slice, ok := data.([]interface{}); ok { // Handle []interface{} from JSON unmarshaling items = make([]map[string]interface{}, len(slice)) for i, item := range slice { if mapItem, ok := item.(map[string]interface{}); ok { items[i] = mapItem } else { return fmt.Errorf("unsupported data type for table output: slice contains non-map elements") } } } else { return fmt.Errorf("unsupported data type for table output") } } var printer *TablePrinter // Check if we should use custom headers from SELECT clause if queryOpts != nil && queryOpts.HasSelect { headers := make([]Header, 0, len(queryOpts.Select)) for _, sel := range queryOpts.Select { headers = append(headers, Header{ DisplayName: sel.Alias, JSONPath: sel.Alias, }) } printer = NewTablePrinter(). WithHeaders(headers...). WithSelectOptions(queryOpts.Select) } else { // Use the provided default headers printer = NewTablePrinter().WithHeaders(defaultHeaders...) } if len(items) == 0 && emptyMessage != "" { return printer.PrintEmpty(emptyMessage) } printer.AddItems(items) return printer.Print() } // Header represents a table column header with display text and a JSON path type Header struct { DisplayName string JSONPath string } // TablePrinter prints tabular data with dynamically sized columns type TablePrinter struct { headers []Header items []map[string]interface{} padding int minWidth int writer io.Writer maxColWidth int expandedData map[int]string // Stores expanded data for each row by index selectOptions []query.SelectOption // Optional: select options for advanced extraction } // NewTablePrinter creates a new TablePrinter func NewTablePrinter() *TablePrinter { return &TablePrinter{ headers: []Header{}, items: []map[string]interface{}{}, padding: 2, minWidth: 10, writer: os.Stdout, maxColWidth: 50, // Prevent very wide columns expandedData: make(map[int]string), } } // WithHeaders sets the table headers with display names and JSON paths func (t *TablePrinter) WithHeaders(headers ...Header) *TablePrinter { t.headers = headers return t } // WithPadding sets the padding between columns func (t *TablePrinter) WithPadding(padding int) *TablePrinter { t.padding = padding return t } // WithMinWidth sets the minimum column width func (t *TablePrinter) WithMinWidth(minWidth int) *TablePrinter { t.minWidth = minWidth return t } // WithMaxWidth sets the maximum column width func (t *TablePrinter) WithMaxWidth(maxWidth int) *TablePrinter { t.maxColWidth = maxWidth return t } // WithWriter sets the output writer func (t *TablePrinter) WithWriter(writer io.Writer) *TablePrinter { t.writer = writer return t } // WithExpandedData sets expanded data for a specific row index func (t *TablePrinter) WithExpandedData(index int, data string) *TablePrinter { t.expandedData[index] = data return t } // WithSelectOptions sets the select options for the table printer func (t *TablePrinter) WithSelectOptions(selectOptions []query.SelectOption) *TablePrinter { t.selectOptions = selectOptions return t } // AddItem adds an item to the table func (t *TablePrinter) AddItem(item map[string]interface{}) *TablePrinter { t.items = append(t.items, item) return t } // AddItemWithExpanded adds an item to the table with expanded data func (t *TablePrinter) AddItemWithExpanded(item map[string]interface{}, expanded string) *TablePrinter { index := len(t.items) t.items = append(t.items, item) t.expandedData[index] = expanded return t } // AddItems adds multiple items to the table func (t *TablePrinter) AddItems(items []map[string]interface{}) *TablePrinter { t.items = append(t.items, items...) return t } // extractValue extracts a value from an item using a JSON path func (t *TablePrinter) extractValue(item map[string]interface{}, path string) string { if path == "" { // No path provided, return empty string return "" } // Use query.GetValue if selectOptions are set, otherwise fallback to GetValueByPathString if len(t.selectOptions) > 0 { val, err := query.GetValue(item, path, t.selectOptions) if err != nil { return "" } return valueToString(val) } value, err := query.GetValueByPathString(item, path) if err != nil { return "" } return valueToString(value) } // valueToString converts a value of any supported type to a string func valueToString(value interface{}) string { if value == nil { return "" } switch v := value.(type) { case string: return v case int: return fmt.Sprintf("%d", v) case int64: return fmt.Sprintf("%d", v) case int32: return fmt.Sprintf("%d", v) case float64: return fmt.Sprintf("%g", v) case float32: return fmt.Sprintf("%g", v) case bool: return fmt.Sprintf("%t", v) default: // For other types, use default string conversion return fmt.Sprintf("%v", v) } } // calculateColumnWidths determines the optimal width for each column func (t *TablePrinter) calculateColumnWidths() []int { numCols := len(t.headers) if numCols == 0 { return []int{} } // Initialize widths with minimum values widths := make([]int, numCols) for i := range widths { widths[i] = t.minWidth } // Check header widths for i, header := range t.headers { headerWidth := utf8.RuneCountInString(header.DisplayName) if headerWidth > widths[i] { widths[i] = min(headerWidth, t.maxColWidth) } } // Calculate row data for width determination for _, item := range t.items { for i, header := range t.headers { value := t.extractValue(item, header.JSONPath) cellWidth := utf8.RuneCountInString(value) if cellWidth > widths[i] { widths[i] = min(cellWidth, t.maxColWidth) } } } return widths } // Print prints the table with dynamic column widths func (t *TablePrinter) Print() error { widths := t.calculateColumnWidths() if len(widths) == 0 { return nil } // Print headers headerRow := make([]string, len(t.headers)) for i, header := range t.headers { headerRow[i] = header.DisplayName } t.printRow(headerRow, widths) // Print item rows and expanded data if available for i, item := range t.items { row := make([]string, len(t.headers)) for j, header := range t.headers { row[j] = t.extractValue(item, header.JSONPath) } t.printRow(row, widths) // Print expanded data if it exists for this row if expanded, exists := t.expandedData[i]; exists && expanded != "" { // Split expanded data into lines and add prefix lines := strings.Split(expanded, "\n") for _, line := range lines { fmt.Fprintf(t.writer, " │ %s\n", line) } } } return nil } // PrintEmpty prints a message when there are no items to display func (t *TablePrinter) PrintEmpty(message string) error { fmt.Fprintln(t.writer, message) return nil } // printRow prints a single row with the specified column widths func (t *TablePrinter) printRow(row []string, widths []int) { var sb strings.Builder for i, cell := range row { if i >= len(widths) { break } // Truncate if the cell is too long displayCell := cell if utf8.RuneCountInString(cell) > t.maxColWidth { displayCell = cell[:t.maxColWidth-3] + "..." } // Format with proper padding format := fmt.Sprintf("%%-%ds", widths[i]+t.padding) sb.WriteString(fmt.Sprintf(format, displayCell)) } fmt.Fprintln(t.writer, strings.TrimRight(sb.String(), " ")) } // min returns the minimum of two integers func min(a, b int) int { if a < b { return a } return b } // MappingEntryFormatter is a function type for formatting mapping entries type MappingEntryFormatter func(entryMap map[string]interface{}, entryType string) string // PrintMappingTable prints mapping entries in a custom table format func PrintMappingTable(mapEntries []interface{}, formatter MappingEntryFormatter) error { if len(mapEntries) == 0 { return nil } // Calculate the maximum width for both source and destination columns based on content maxSourceWidth := len("SOURCE") // minimum width (header width) maxDestWidth := len("DESTINATION") // minimum width (header width) for _, entry := range mapEntries { if entryMap, ok := entry.(map[string]interface{}); ok { // Calculate source width sourceText := formatter(entryMap, "source") sourceLines := strings.Split(sourceText, "\n") for _, line := range sourceLines { if len(line) > maxSourceWidth { maxSourceWidth = len(line) } } // Calculate destination width destText := formatter(entryMap, "destination") destLines := strings.Split(destText, "\n") for _, line := range destLines { if len(line) > maxDestWidth { maxDestWidth = len(line) } } } } // Cap the widths to prevent overly wide tables if maxSourceWidth > 50 { maxSourceWidth = 50 } if maxDestWidth > 50 { maxDestWidth = 50 } // Define column spacing columnSpacing := " " // 2 spaces // Print table header headerFormat := fmt.Sprintf("%%-%ds%s%%s\n", maxSourceWidth+8, columnSpacing) fmt.Printf(headerFormat, Bold("SOURCE"), Bold("DESTINATION")) // Print separator line using calculated widths separatorLine := strings.Repeat("─", maxSourceWidth) + columnSpacing + strings.Repeat("─", maxDestWidth) fmt.Println(separatorLine) // Process each mapping entry for i, entry := range mapEntries { if entryMap, ok := entry.(map[string]interface{}); ok { sourceText := formatter(entryMap, "source") destText := formatter(entryMap, "destination") printMappingTableRow(sourceText, destText, maxSourceWidth, maxDestWidth, columnSpacing) // Add separator between entries (except for the last one) if i < len(mapEntries)-1 { entrySeperatorLine := strings.Repeat("─", maxSourceWidth) + columnSpacing + strings.Repeat("─", maxDestWidth) fmt.Println(entrySeperatorLine) } } } return nil } // printMappingTableRow prints a single mapping row with proper alignment for multi-line content func printMappingTableRow(source, dest string, sourceWidth, destWidth int, columnSpacing string) { sourceLines := strings.Split(source, "\n") destLines := strings.Split(dest, "\n") // Determine the maximum number of lines maxLines := len(sourceLines) if len(destLines) > maxLines { maxLines = len(destLines) } // Print each line for i := 0; i < maxLines; i++ { var sourceLine, destLine string if i < len(sourceLines) { sourceLine = sourceLines[i] } if i < len(destLines) { destLine = destLines[i] } // Truncate lines if they're too long if len(sourceLine) > sourceWidth { sourceLine = sourceLine[:sourceWidth-3] + "..." } if len(destLine) > destWidth { destLine = destLine[:destWidth-3] + "..." } // Format and print the line with proper column widths rowFormat := fmt.Sprintf("%%-%ds%s%%-%ds\n", sourceWidth, columnSpacing, destWidth) fmt.Printf(rowFormat, sourceLine, destLine) } } // PrintConditions prints conditions information in a consistent format func PrintConditions(conditions []interface{}) { if len(conditions) == 0 { return } fmt.Printf("%s\n", Bold("Conditions:")) for _, condition := range conditions { if condMap, ok := condition.(map[string]interface{}); ok { condType, _ := condMap["type"].(string) condStatus, _ := condMap["status"].(string) reason, _ := condMap["reason"].(string) message, _ := condMap["message"].(string) lastTransitionTime, _ := condMap["lastTransitionTime"].(string) fmt.Printf(" %s: %s", Bold(condType), ColorizeStatus(condStatus)) if reason != "" { fmt.Printf(" (%s)", reason) } fmt.Println() if message != "" { fmt.Printf(" %s\n", message) } if lastTransitionTime != "" { fmt.Printf(" Last Transition: %s\n", lastTransitionTime) } } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/output/time.go
Go
package output import ( "time" ) // FormatTime formats a timestamp string with optional UTC conversion func FormatTime(timestamp string, useUTC bool) string { if timestamp == "" { return "N/A" } // Parse the timestamp t, err := time.Parse(time.RFC3339, timestamp) if err != nil { return timestamp } // Convert to UTC or local time as requested if useUTC { t = t.UTC() } else { t = t.Local() } // Format as "2006-01-02 15:04:05" return t.Format("2006-01-02 15:04:05") } // FormatTimestamp formats a time.Time object with optional UTC conversion func FormatTimestamp(timestamp time.Time, useUTC bool) string { // Convert to UTC or local time as requested if useUTC { timestamp = timestamp.UTC() } else { timestamp = timestamp.Local() } // Format as "2006-01-02 15:04:05" return timestamp.Format("2006-01-02 15:04:05") }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/output/yaml.go
Go
package output // PrintYAML prints the given data as YAML using YAMLPrinter import ( "fmt" "io" "os" "gopkg.in/yaml.v3" ) // PrintYAMLWithEmpty prints the given data as YAML using YAMLPrinter with empty handling func PrintYAMLWithEmpty(data interface{}, emptyMessage string) error { items, ok := data.([]map[string]interface{}) printer := NewYAMLPrinter() if ok { if len(items) == 0 && emptyMessage != "" { return printer.PrintEmpty(emptyMessage) } printer.AddItems(items) } else if item, ok := data.(map[string]interface{}); ok { printer.AddItem(item) } else { // Fallback: marshal any data b, err := yaml.Marshal(data) if err != nil { return err } _, err = fmt.Fprintln(os.Stdout, string(b)) return err } return printer.Print() } // YAMLPrinter prints data as YAML type YAMLPrinter struct { items []map[string]interface{} writer io.Writer prettyPrint bool } // NewYAMLPrinter creates a new YAMLPrinter func NewYAMLPrinter() *YAMLPrinter { return &YAMLPrinter{ items: []map[string]interface{}{}, writer: os.Stdout, prettyPrint: true, // YAML is inherently formatted, so default to true } } // WithWriter sets the output writer func (y *YAMLPrinter) WithWriter(writer io.Writer) *YAMLPrinter { y.writer = writer return y } // WithPrettyPrint enables or disables pretty printing (indentation) // Note: YAML is inherently formatted, so this mainly affects structure func (y *YAMLPrinter) WithPrettyPrint(pretty bool) *YAMLPrinter { y.prettyPrint = pretty return y } // AddItem adds an item to the YAML output func (y *YAMLPrinter) AddItem(item map[string]interface{}) *YAMLPrinter { y.items = append(y.items, item) return y } // AddItems adds multiple items to the YAML output func (y *YAMLPrinter) AddItems(items []map[string]interface{}) *YAMLPrinter { y.items = append(y.items, items...) return y } // Print outputs the items as YAML func (y *YAMLPrinter) Print() error { encoder := yaml.NewEncoder(y.writer) encoder.SetIndent(2) defer encoder.Close() err := encoder.Encode(y.items) if err != nil { return fmt.Errorf("failed to marshal YAML: %v", err) } return nil } // PrintEmpty outputs an empty YAML array or a message when there are no items func (y *YAMLPrinter) PrintEmpty(message string) error { encoder := yaml.NewEncoder(y.writer) encoder.SetIndent(2) defer encoder.Close() var data interface{} if message == "" { // If no message, just print an empty array data = []interface{}{} } else { // If message provided, print only the message data = map[string]interface{}{ "message": message, } } err := encoder.Encode(data) if err != nil { return fmt.Errorf("failed to marshal YAML: %v", err) } return nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/apply.go
Go
package query import ( "fmt" ) // ApplyQuery filters, sorts, and limits the given items based on QueryOptions func ApplyQuery(items []map[string]interface{}, queryOpts *QueryOptions) ([]map[string]interface{}, error) { result := items // Apply WHERE filtering if specified if queryOpts.Where != "" { var err error // Use parallel filtering, use sutomatic batch size (batch size = 0) result, err = FilterItemsParallel(result, queryOpts, 0) if err != nil { return nil, fmt.Errorf("where clause error: %v", err) } } // Apply sorting if specified if queryOpts.HasOrderBy { var err error result, err = SortItems(result, queryOpts) if err != nil { return nil, err } } // Apply limit if specified if queryOpts.HasLimit && queryOpts.Limit >= 0 && queryOpts.Limit < len(result) { result = result[:queryOpts.Limit] } return result, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/filter.go
Go
package query import ( "fmt" "github.com/yaacov/tree-search-language/v6/pkg/tsl" "github.com/yaacov/tree-search-language/v6/pkg/walkers/semantics" ) // ParseWhereClause parses a WHERE clause string into a TSL tree func ParseWhereClause(whereClause string) (*tsl.TSLNode, error) { tree, err := tsl.ParseTSL(whereClause) if err != nil { return nil, fmt.Errorf("failed to parse where clause: %v", err) } return tree, nil } // ApplyFilter filters items using a TSL tree func ApplyFilter(items []map[string]interface{}, tree *tsl.TSLNode, selectOpts []SelectOption) ([]map[string]interface{}, error) { var results []map[string]interface{} // Filter the items collection using the TSL tree for _, item := range items { eval := evalFactory(item, selectOpts) matchingFilter, err := semantics.Walk(tree, eval) if err != nil { return nil, fmt.Errorf("failed to evaluate where clause: %v", err) } // Convert interface{} to bool if match, ok := matchingFilter.(bool); ok && match { results = append(results, item) } } return results, nil } // evalFactory gets an item and returns a method that will get the field and return its value func evalFactory(item map[string]interface{}, selectOpts []SelectOption) semantics.EvalFunc { return func(k string) (interface{}, bool) { // Use GetValue to respect aliases and reducers if v, err := GetValue(item, k, selectOpts); err == nil { return v, true } return nil, true } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/filter_test.go
Go
package query import ( "reflect" "testing" "time" ) func TestApplyFilter(t *testing.T) { tests := []struct { name string items []map[string]interface{} where string selectOpts []SelectOption want []map[string]interface{} wantErr bool }{ { name: "numeric greater than", items: []map[string]interface{}{ {"foo": 1}, {"foo": 2}, {"foo": 3}, }, where: "foo>1", selectOpts: nil, want: []map[string]interface{}{ {"foo": 2}, {"foo": 3}, }, }, { name: "string equality", items: []map[string]interface{}{ {"bar": "a"}, {"bar": "b"}, {"bar": "a"}, }, where: `bar = "a"`, selectOpts: nil, want: []map[string]interface{}{ {"bar": "a"}, {"bar": "a"}, }, }, { name: "boolean truthy", items: []map[string]interface{}{ {"baz": true}, {"baz": false}, {"baz": true}, }, where: "baz", selectOpts: nil, want: []map[string]interface{}{ {"baz": true}, {"baz": true}, }, }, { name: "logical AND", items: []map[string]interface{}{ {"foo": 2, "bar": 3}, {"foo": 3, "bar": 5}, {"foo": 1, "bar": 2}, }, where: "foo > 1 and bar < 4", selectOpts: nil, want: []map[string]interface{}{ {"foo": 2, "bar": 3}, }, }, { name: "logical OR", items: []map[string]interface{}{ {"foo": 1}, {"foo": 3}, {"foo": 5}, }, where: "foo < 2 or foo > 4", selectOpts: nil, want: []map[string]interface{}{ {"foo": 1}, {"foo": 5}, }, }, { name: "nested field equality", items: []map[string]interface{}{ {"n": map[string]interface{}{"x": 1.0}}, {"n": map[string]interface{}{"x": 2.0}}, }, where: "n.x = 1.0", selectOpts: nil, want: []map[string]interface{}{ {"n": map[string]interface{}{"x": 1.0}}, }, }, { name: "parentheses grouping", items: []map[string]interface{}{ {"a": 1, "b": 2, "c": false}, {"a": 2, "b": 3, "c": false}, {"a": 3, "b": 1, "c": true}, }, where: "(a > 1 and b < 2) or c", selectOpts: nil, want: []map[string]interface{}{ {"a": 3, "b": 1, "c": true}, }, }, { name: "alias usage", items: []map[string]interface{}{ {"foo": 1}, {"foo": 3}, }, where: "f>2", selectOpts: []SelectOption{{Field: ".foo", Alias: "f"}}, want: []map[string]interface{}{ {"foo": 3}, }, }, { name: "reducer alias", items: []map[string]interface{}{ {"nums": []interface{}{1, 2}}, {"nums": []interface{}{3, 4}}, }, where: "s>5", selectOpts: []SelectOption{{Field: ".nums", Alias: "s", Reducer: "sum"}}, want: []map[string]interface{}{ {"nums": []interface{}{3, 4}}, }, }, { name: "int-float equality", items: []map[string]interface{}{ {"foo": 3}, {"foo": 3.0}, {"foo": 4}, }, where: "foo = 3.0", selectOpts: nil, want: []map[string]interface{}{ {"foo": 3}, {"foo": 3.0}, }, }, { name: "date-string equality", items: []map[string]interface{}{ {"date": time.Date(2020, time.January, 2, 15, 4, 5, 0, time.UTC)}, {"date": time.Date(2021, time.January, 2, 15, 4, 5, 0, time.UTC)}, }, where: `date = "2020-01-02T15:04:05Z"`, selectOpts: nil, want: []map[string]interface{}{ {"date": time.Date(2020, time.January, 2, 15, 4, 5, 0, time.UTC)}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tree, err := ParseWhereClause(tt.where) if (err != nil) != tt.wantErr { t.Fatalf("ParseWhereClause(%q) error = %v, wantErr %v", tt.where, err, tt.wantErr) } if err != nil { return } got, err := ApplyFilter(tt.items, tree, tt.selectOpts) if err != nil { t.Fatalf("ApplyFilter error: %v", err) } if !reflect.DeepEqual(got, tt.want) { t.Errorf("got = %v, want %v", got, tt.want) } }) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/helper.go
Go
package query // ApplyQueryInterface parses the query string and applies it to the data (interface{}). // Accepts data as []map[string]interface{} or map[string]interface{}. // Returns filtered data as interface{} and error. func ApplyQueryInterface(data interface{}, query string) (interface{}, error) { var items []map[string]interface{} switch v := data.(type) { case []map[string]interface{}: items = v case map[string]interface{}: items = []map[string]interface{}{v} default: return data, nil // If not a supported type, return as-is } queryOpts, err := ParseQueryString(query) if err != nil { return nil, err } filtered, err := ApplyQuery(items, queryOpts) if err != nil { return nil, err } return filtered, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/jsonpath.go
Go
package query import ( "fmt" "regexp" "strconv" "strings" ) // GetValueByPathString gets a value from an object using a string path // The path can use dot notation (e.g. "metadata.name") and array indexing (e.g. "spec.containers[0].name") func GetValueByPathString(obj interface{}, path string) (interface{}, error) { // Remove JSONPath notation if present path = strings.TrimPrefix(path, "{{") path = strings.TrimSuffix(path, "}}") path = strings.TrimSpace(path) // Remove leading dot if present path = strings.TrimPrefix(path, ".") // Split the path into parts, handling brackets and dots // e.g. "spec.containers[0].name" -> ["spec", "containers[0]", "name"] var parts []string var currentPart strings.Builder insideBrackets := false for _, char := range path { switch char { case '[': insideBrackets = true currentPart.WriteRune(char) case ']': insideBrackets = false currentPart.WriteRune(char) case '.': if insideBrackets { // If inside brackets, the dot is part of the current segment currentPart.WriteRune(char) } else { // If outside brackets, the dot is a separator parts = append(parts, currentPart.String()) currentPart.Reset() } default: currentPart.WriteRune(char) } } // Add the last part if there's anything left if currentPart.Len() > 0 { parts = append(parts, currentPart.String()) } return getValueByPath(obj, parts) } // getValueByPath recursively traverses an object following a path func getValueByPath(obj interface{}, pathParts []string) (interface{}, error) { if len(pathParts) == 0 { return obj, nil } if obj == nil { return nil, fmt.Errorf("cannot access %s on nil value", strings.Join(pathParts, ".")) } part := pathParts[0] remainingParts := pathParts[1:] // Check if part has array indexing notation [i], map key notation [key], or wildcard [*] arrayIndex := -1 mapKey := "" isWildcard := false // Run regex matchers wildcardMatch := regexp.MustCompile(`(.*)\[\*\]$`).FindStringSubmatch(part) arrayMatch := regexp.MustCompile(`(.*)\[(\d+)\]$`).FindStringSubmatch(part) mapMatch := regexp.MustCompile(`(.*)\[([^\]]+)\]$`).FindStringSubmatch(part) // Then use flat if conditions to process matches if len(wildcardMatch) == 2 { part = wildcardMatch[1] isWildcard = true } else if len(arrayMatch) == 3 { part = arrayMatch[1] index, err := strconv.Atoi(arrayMatch[2]) if err != nil { return nil, fmt.Errorf("invalid array index in path: %s", part) } arrayIndex = index } else if len(mapMatch) == 3 { part = mapMatch[1] mapKey = mapMatch[2] // Remove quotes if present mapKey = strings.Trim(mapKey, `"'`) } switch objTyped := obj.(type) { case map[string]interface{}: // Get value for current part value, exists := objTyped[part] if !exists { // Don't fail if the part is not found, just return nil return nil, nil } // Handle wildcard for arrays if isWildcard { // Check if the value is an array arr, ok := value.([]interface{}) if !ok { return nil, fmt.Errorf("cannot apply wildcard to non-array value: %s", part) } // For wildcard, collect results from all array elements var results []interface{} for _, item := range arr { result, err := getValueByPath(item, remainingParts) if err == nil && result != nil { // Check if result is an array itself and flatten if needed if resultArray, isArray := result.([]interface{}); isArray { // Flatten by appending individual elements results = append(results, resultArray...) } else { // Non-array result, append as is results = append(results, result) } } } return results, nil } // Handle array indexing if present if arrayIndex >= 0 { // Check if the value is an array if arr, ok := value.([]interface{}); ok { if arrayIndex >= len(arr) { return nil, fmt.Errorf("array index out of bounds: %d", arrayIndex) } value = arr[arrayIndex] } else { return nil, fmt.Errorf("cannot apply array index to non-array value: %s", part) } } // Handle map key access if present if mapKey != "" { // Check if the value is a map if m, ok := value.(map[string]interface{}); ok { mapValue, exists := m[mapKey] if !exists { return nil, nil } value = mapValue } else { return nil, fmt.Errorf("cannot apply map key to non-map value: %s", part) } } // If this is the last part, return the value if len(remainingParts) == 0 { return value, nil } // Implicit wildcard: when value is an array and we have remaining path parts, // iterate over all elements (equivalent to field[*].subfield) if arr, ok := value.([]interface{}); ok { var results []interface{} for _, item := range arr { result, err := getValueByPath(item, remainingParts) if err == nil && result != nil { if resultArray, isArray := result.([]interface{}); isArray { results = append(results, resultArray...) } else { results = append(results, result) } } } return results, nil } // Otherwise, continue recursing return getValueByPath(value, remainingParts) default: return nil, fmt.Errorf("cannot access property %s on non-object value", part) } } // GetValue retrieves a value by name (or alias) from obj using JSONPath, // then applies a reducer if one is specified in selectOpts. func GetValue(obj interface{}, name string, selectOpts []SelectOption) (interface{}, error) { path := name var reducer string // If name matches an alias, switch to its Field and capture reducer for _, opt := range selectOpts { if opt.Alias == name { path = opt.Field reducer = opt.Reducer break } } // Fetch the raw value val, err := GetValueByPathString(obj, path) if err != nil { return nil, err } // Apply reducer if specified if reducer != "" { reduced, err := applyReducer(val, reducer) if err != nil { return nil, fmt.Errorf("failed to apply reducer %q: %v", reducer, err) } return reduced, nil } return val, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/jsonpath_test.go
Go
package query import ( "reflect" "testing" "time" ) func TestGetValueByPathString(t *testing.T) { obj := map[string]interface{}{ "metadata": map[string]interface{}{ "name": "pod1", "labels": map[string]interface{}{ "env": "prod", }, }, "spec": map[string]interface{}{ "containers": []interface{}{ map[string]interface{}{"name": "c1"}, map[string]interface{}{"name": "c2"}, }, }, "intVal": 42, "floatVal": 3.14, "boolVal": true, "date": time.Date(2020, time.January, 2, 15, 4, 5, 0, time.UTC), } tests := []struct { name string path string want interface{} wantErr bool }{ {"simple dot", "metadata.name", "pod1", false}, {"leading dot", ".metadata.name", "pod1", false}, {"braces", "{{ metadata.name }}", "pod1", false}, {"map key", "metadata.labels[env]", "prod", false}, {"array index", "spec.containers[1].name", "c2", false}, {"wildcard", "spec.containers[*].name", []interface{}{"c1", "c2"}, false}, {"bool value", "boolVal", true, false}, {"int value", "intVal", 42, false}, {"float value", "floatVal", 3.14, false}, {"date value", "date", time.Date(2020, time.January, 2, 15, 4, 5, 0, time.UTC), false}, {"implicit wildcard", "spec.containers.name", []interface{}{"c1", "c2"}, false}, {"implicit equals explicit wildcard", "spec.containers[*].name", []interface{}{"c1", "c2"}, false}, {"missing field", "nonexistent.field", nil, false}, {"out of bounds", "spec.containers[10].name", nil, true}, {"bad index", "spec.containers[foo].name", nil, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetValueByPathString(obj, tt.path) if (err != nil) != tt.wantErr { t.Fatalf("err = %v, wantErr %v", err, tt.wantErr) } if !reflect.DeepEqual(got, tt.want) { t.Errorf("path %q = %#v, want %#v", tt.path, got, tt.want) } }) } } func TestGetValue(t *testing.T) { obj := map[string]interface{}{ "metadata": map[string]interface{}{ "name": "pod1", "labels": map[string]interface{}{ "env": "prod", }, }, "nums": []interface{}{1, 2, 3}, "flags": []interface{}{true, false}, } tests := []struct { name string field string opts []SelectOption want interface{} wantErr bool }{ {"direct", "metadata.name", nil, "pod1", false}, {"alias lookup", "aliasEnv", []SelectOption{ {Alias: "aliasEnv", Field: "metadata.labels[env]"}, }, "prod", false}, {"unknown name", "foo", nil, nil, false}, {"sum reducer", "sumNums", []SelectOption{ {Alias: "sumNums", Field: ".nums", Reducer: "sum"}, }, float64(6), false}, {"len reducer", "lenNums", []SelectOption{ {Alias: "lenNums", Field: ".nums", Reducer: "len"}, }, 3, false}, {"any reducer", "anyFlags", []SelectOption{ {Alias: "anyFlags", Field: ".flags", Reducer: "any"}, }, true, false}, {"all reducer", "allFlags", []SelectOption{ {Alias: "allFlags", Field: ".flags", Reducer: "all"}, }, false, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetValue(obj, tt.field, tt.opts) if (err != nil) != tt.wantErr { t.Fatalf("GetValue err = %v, wantErr %v", err, tt.wantErr) } if !reflect.DeepEqual(got, tt.want) { t.Errorf("GetValue(%q) = %#v, want %#v", tt.field, got, tt.want) } }) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/parallel_filter.go
Go
package query import ( "fmt" "runtime" "sync" ) // CalculateBatchSize determines an appropriate batch size based on the total items // and available CPU cores. If providedBatchSize > 0, it uses that instead. func CalculateBatchSize(totalItems int, providedBatchSize int) int { if providedBatchSize > 0 { return providedBatchSize } // Get number of available CPU cores numCPU := runtime.NumCPU() // Target 4 batches per core for good parallelism and load balancing targetBatches := numCPU * 4 batchSize := totalItems / targetBatches // Ensure reasonable minimum and maximum batch sizes if batchSize < 100 && totalItems > 100 { batchSize = 100 } else if batchSize < 1 { batchSize = 1 } return batchSize } // FilterItemsParallel filters items in parallel batches func FilterItemsParallel(items []map[string]interface{}, queryOpts *QueryOptions, batchSize int) ([]map[string]interface{}, error) { totalItems := len(items) if totalItems == 0 { return []map[string]interface{}{}, nil } tree, err := ParseWhereClause(queryOpts.Where) if err != nil { return nil, err } effectiveBatchSize := CalculateBatchSize(totalItems, batchSize) numBatches := (totalItems + effectiveBatchSize - 1) / effectiveBatchSize // Create channels for results and errors resultsChan := make(chan []map[string]interface{}, numBatches) errorsChan := make(chan error, numBatches) var wg sync.WaitGroup // Process each batch in a goroutine for i := 0; i < numBatches; i++ { wg.Add(1) go func(batchIndex int) { defer wg.Done() // Calculate start and end indices for this batch start := batchIndex * effectiveBatchSize end := start + effectiveBatchSize if end > totalItems { end = totalItems } // Process the batch using ApplyFilter filteredBatch, err := ApplyFilter(items[start:end], tree, queryOpts.Select) if err != nil { errorsChan <- fmt.Errorf("error filtering batch %d: %v", batchIndex, err) return } resultsChan <- filteredBatch }(i) } // Wait for all goroutines to complete wg.Wait() close(resultsChan) close(errorsChan) // Check for any errors for err := range errorsChan { if err != nil { return nil, err } } // Collect and combine all results var allResults []map[string]interface{} for batchResult := range resultsChan { allResults = append(allResults, batchResult...) } return allResults, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/parse.go
Go
package query import ( "fmt" "regexp" "strconv" "strings" ) var selectRegexp = regexp.MustCompile(`(?i)^(?:(sum|len|any|all)\s*\(?\s*([^)\s]+)\s*\)?|(.+?))\s*(?:as\s+(.+))?$`) // parseSelectClause splits and parses a select clause into SelectOptions entries. func parseSelectClause(selectClause string) []SelectOption { var opts []SelectOption for _, raw := range strings.Split(selectClause, ",") { field := strings.TrimSpace(raw) if field == "" { continue } if m := selectRegexp.FindStringSubmatch(field); m != nil { reducer := strings.ToLower(m[1]) expr := m[2] if expr == "" { expr = m[3] } alias := m[4] if alias == "" { alias = expr } if !strings.HasPrefix(expr, ".") && !strings.HasPrefix(expr, "{") { expr = "." + expr } opts = append(opts, SelectOption{ Field: expr, Alias: alias, Reducer: reducer, }) } } return opts } // parseOrderByClause splits an ORDER BY clause into OrderOption entries. func parseOrderByClause(orderByClause string, selectOpts []SelectOption) []OrderOption { var orderOpts []OrderOption for _, rawField := range strings.Split(orderByClause, ",") { fieldStr := strings.TrimSpace(rawField) if fieldStr == "" { continue } // determine direction parts := strings.Fields(fieldStr) descending := false last := parts[len(parts)-1] if strings.EqualFold(last, "desc") { descending = true parts = parts[:len(parts)-1] } else if strings.EqualFold(last, "asc") { parts = parts[:len(parts)-1] } // ensure JSONPath format name := strings.Join(parts, " ") if !strings.HasPrefix(name, ".") && !strings.HasPrefix(name, "{") { name = "." + name } // find matching select option or create default var selOpt SelectOption found := false for _, sel := range selectOpts { if sel.Field == name || sel.Alias == strings.TrimPrefix(name, ".") { selOpt = sel found = true break } } if !found { selOpt = SelectOption{ Field: name, Alias: strings.TrimPrefix(name, "."), Reducer: "", } } orderOpts = append(orderOpts, OrderOption{ Field: selOpt, Descending: descending, }) } return orderOpts } // validQueryPrefixes lists the keyword prefixes that start a valid TSL query clause. // Used by hasQueryKeywordPrefix to detect bare filter expressions. var validQueryPrefixes = []string{"select ", "where ", "order by ", "sort by ", "limit "} // hasQueryKeywordPrefix checks if the query starts with a recognized TSL keyword. // Case-insensitive check against select, where, order by, sort by, and limit. func hasQueryKeywordPrefix(query string) bool { lower := strings.ToLower(strings.TrimSpace(query)) for _, prefix := range validQueryPrefixes { if strings.HasPrefix(lower, prefix) { return true } } return false } // ParseQueryString parses a query string into its component parts func ParseQueryString(query string) (*QueryOptions, error) { options := &QueryOptions{ Limit: -1, // Default to no limit } if query == "" { return options, nil } // Heuristic: if the query doesn't start with a valid keyword prefix // (select, where, order by, sort by, limit), assume it's a bare filter // expression and prepend "where " to make it a valid query. // This helps LLMs and users who write "cpuCount > 4" instead of "where cpuCount > 4". if !hasQueryKeywordPrefix(query) { query = "where " + query } // Validate query syntax before parsing if err := ValidateQuerySyntax(query); err != nil { return nil, err } // Convert query to lowercase for case-insensitive matching but preserve original for extraction queryLower := strings.ToLower(query) // Check for SELECT clause selectIndex := strings.Index(queryLower, "select ") whereIndex := strings.Index(queryLower, "where ") limitIndex := strings.Index(queryLower, "limit ") // Look for ordering clause - first "order by", then "sort by" if not found orderByIndex := strings.Index(queryLower, "order by ") if orderByIndex == -1 { orderByIndex = strings.Index(queryLower, "sort by ") } // Extract SELECT clause if it exists if selectIndex >= 0 { selectEnd := len(query) if whereIndex > selectIndex { selectEnd = whereIndex } else if orderByIndex > selectIndex { selectEnd = orderByIndex } else if limitIndex > selectIndex { selectEnd = limitIndex } // Extract select clause (skip "select " prefix which is 7 chars) selectClause := strings.TrimSpace(query[selectIndex+7 : selectEnd]) options.Select = parseSelectClause(selectClause) options.HasSelect = len(options.Select) > 0 } // Extract WHERE clause if it exists if whereIndex >= 0 { whereEnd := len(query) if orderByIndex > whereIndex { whereEnd = orderByIndex } else if limitIndex > whereIndex { whereEnd = limitIndex } // Extract where clause (skip "where " prefix which is 6 chars) options.Where = strings.TrimSpace(query[whereIndex+6 : whereEnd]) } // Extract ORDER BY clause if it exists if orderByIndex >= 0 { orderByEnd := len(query) if limitIndex > orderByIndex { orderByEnd = limitIndex } // Extract order by clause (skip 8 chars for both "order by" and "sort by ") orderByClause := strings.TrimSpace(query[orderByIndex+8 : orderByEnd]) // use helper to build OrderOption slice options.OrderBy = parseOrderByClause(orderByClause, options.Select) options.HasOrderBy = len(options.OrderBy) > 0 } // Extract LIMIT clause using regex (for simplicity with number extraction) limitRegex := regexp.MustCompile(`(?i)limit\s+(\d+)`) limitMatches := limitRegex.FindStringSubmatch(query) if len(limitMatches) > 1 { limit, err := strconv.Atoi(limitMatches[1]) if err != nil { return nil, fmt.Errorf("invalid limit value: %v", err) } options.Limit = limit options.HasLimit = true } return options, nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/parse_test.go
Go
package query import ( "reflect" "testing" ) func TestParseQueryString(t *testing.T) { tests := []struct { name string query string expected *QueryOptions err bool }{ { name: "empty query", query: "", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "", OrderBy: nil, HasOrderBy: false, Limit: -1, HasLimit: false, }, }, { name: "simple select and alias", query: "SELECT foo, bar as baz", expected: &QueryOptions{ Select: []SelectOption{ {Field: ".foo", Alias: "foo", Reducer: ""}, {Field: ".bar", Alias: "baz", Reducer: ""}, }, HasSelect: true, Where: "", OrderBy: nil, HasOrderBy: false, Limit: -1, HasLimit: false, }, }, { name: "where and limit", query: "where count>0 limit 5", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "count>0", OrderBy: nil, HasOrderBy: false, Limit: 5, HasLimit: true, }, }, { name: "order by asc and desc", query: "order by foo desc, bar ASC", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".foo", Alias: "foo", Reducer: ""}, Descending: true, }, { Field: SelectOption{Field: ".bar", Alias: "bar", Reducer: ""}, Descending: false, }, }, HasOrderBy: true, Limit: -1, HasLimit: false, }, }, { name: "combined full query", query: "SELECT sum(x) as total, y WHERE y>1 ORDER BY x DESC, y LIMIT 10", expected: &QueryOptions{ Select: []SelectOption{ {Field: ".x", Alias: "total", Reducer: "sum"}, {Field: ".y", Alias: "y", Reducer: ""}, }, HasSelect: true, Where: "y>1", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".x", Alias: "total", Reducer: "sum"}, Descending: true, }, { Field: SelectOption{Field: ".y", Alias: "y", Reducer: ""}, Descending: false, }, }, HasOrderBy: true, Limit: 10, HasLimit: true, }, }, { name: "order by alias", query: "SELECT foo as f, bar as b ORDER BY f DESC, b", expected: &QueryOptions{ Select: []SelectOption{ {Field: ".foo", Alias: "f", Reducer: ""}, {Field: ".bar", Alias: "b", Reducer: ""}, }, HasSelect: true, Where: "", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".foo", Alias: "f", Reducer: ""}, Descending: true, }, { Field: SelectOption{Field: ".bar", Alias: "b", Reducer: ""}, Descending: false, }, }, HasOrderBy: true, Limit: -1, HasLimit: false, }, }, { name: "sort by asc and desc", query: "sort by foo desc, bar ASC", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".foo", Alias: "foo", Reducer: ""}, Descending: true, }, { Field: SelectOption{Field: ".bar", Alias: "bar", Reducer: ""}, Descending: false, }, }, HasOrderBy: true, Limit: -1, HasLimit: false, }, }, { name: "sort by alias", query: "SELECT foo as f, bar as b SORT BY f DESC, b", expected: &QueryOptions{ Select: []SelectOption{ {Field: ".foo", Alias: "f", Reducer: ""}, {Field: ".bar", Alias: "b", Reducer: ""}, }, HasSelect: true, Where: "", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".foo", Alias: "f", Reducer: ""}, Descending: true, }, { Field: SelectOption{Field: ".bar", Alias: "b", Reducer: ""}, Descending: false, }, }, HasOrderBy: true, Limit: -1, HasLimit: false, }, }, { name: "combined full query with sort by", query: "SELECT sum(x) as total, y WHERE y>1 SORT BY x DESC, y LIMIT 10", expected: &QueryOptions{ Select: []SelectOption{ {Field: ".x", Alias: "total", Reducer: "sum"}, {Field: ".y", Alias: "y", Reducer: ""}, }, HasSelect: true, Where: "y>1", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".x", Alias: "total", Reducer: "sum"}, Descending: true, }, { Field: SelectOption{Field: ".y", Alias: "y", Reducer: ""}, Descending: false, }, }, HasOrderBy: true, Limit: 10, HasLimit: true, }, }, { name: "case insensitive sort by", query: "select name where id > 1 Sort By name desc", expected: &QueryOptions{ Select: []SelectOption{ {Field: ".name", Alias: "name", Reducer: ""}, }, HasSelect: true, Where: "id > 1", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".name", Alias: "name", Reducer: ""}, Descending: true, }, }, HasOrderBy: true, Limit: -1, HasLimit: false, }, }, { name: "sort by with where and limit", query: "WHERE status = 'active' SORT BY created_date DESC, name LIMIT 5", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "status = 'active'", OrderBy: []OrderOption{ { Field: SelectOption{Field: ".created_date", Alias: "created_date", Reducer: ""}, Descending: true, }, { Field: SelectOption{Field: ".name", Alias: "name", Reducer: ""}, Descending: false, }, }, HasOrderBy: true, Limit: 5, HasLimit: true, }, }, // Bare expression heuristic tests: auto-prepend "where" { name: "bare filter expression", query: "cpuCount > 4", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "cpuCount > 4", OrderBy: nil, HasOrderBy: false, Limit: -1, HasLimit: false, }, }, { name: "bare compound filter", query: "name ~ 'web' and memoryMB > 8192", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "name ~ 'web' and memoryMB > 8192", OrderBy: nil, HasOrderBy: false, Limit: -1, HasLimit: false, }, }, { name: "bare filter with trailing limit", query: "name = 'test' limit 5", expected: &QueryOptions{ Select: nil, HasSelect: false, Where: "name = 'test'", OrderBy: nil, HasOrderBy: false, Limit: 5, HasLimit: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := ParseQueryString(tt.query) if (err != nil) != tt.err { t.Fatalf("unexpected error status: %v", err) } if !reflect.DeepEqual(got, tt.expected) { t.Errorf("ParseQueryString(%q) =\n %#v\nexpected\n %#v", tt.query, got, tt.expected) } }) } } func TestHasQueryKeywordPrefix(t *testing.T) { tests := []struct { query string expect bool }{ {"select name", true}, {"SELECT name", true}, {"where cpuCount > 4", true}, {"WHERE cpuCount > 4", true}, {"order by name", true}, {"ORDER BY name", true}, {"sort by name", true}, {"SORT BY name", true}, {"limit 10", true}, {"LIMIT 10", true}, {"cpuCount > 4", false}, {"name ~ 'web'", false}, {"status = 'active' limit 5", false}, {" where name = 'x'", true}, // leading whitespace {"", false}, } for _, tt := range tests { t.Run(tt.query, func(t *testing.T) { got := hasQueryKeywordPrefix(tt.query) if got != tt.expect { t.Errorf("hasQueryKeywordPrefix(%q) = %v, want %v", tt.query, got, tt.expect) } }) } } func TestParseSelectClauseFunctionOptionalParentheses(t *testing.T) { tests := []struct { input string want SelectOption }{ {"len hello", SelectOption{Field: ".hello", Reducer: "len", Alias: "hello"}}, {"len(hello)", SelectOption{Field: ".hello", Reducer: "len", Alias: "hello"}}, {"sum value as total", SelectOption{Field: ".value", Reducer: "sum", Alias: "total"}}, {"sum(value) as total", SelectOption{Field: ".value", Reducer: "sum", Alias: "total"}}, } for _, tc := range tests { got := parseSelectClause(tc.input) if len(got) != 1 { t.Errorf("parseSelectClause(%q) returned %d opts, want 1", tc.input, len(got)) continue } if !reflect.DeepEqual(got[0], tc.want) { t.Errorf("parseSelectClause(%q)[0] = %+v, want %+v", tc.input, got[0], tc.want) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/reducer.go
Go
package query import ( "fmt" ) // applyReducer runs sum/len/any/all on slice values. func applyReducer(value interface{}, reducer string) (interface{}, error) { arr, ok := value.([]interface{}) if !ok { // not an array – no reduction return value, nil } switch reducer { case "sum": var total float64 for _, v := range arr { switch n := v.(type) { case float64: total += n case int: total += float64(n) case int64: total += float64(n) default: // skip non‐numeric } } return total, nil case "len": return len(arr), nil case "any": for _, v := range arr { if b, ok := v.(bool); ok && b { return true, nil } } return false, nil case "all": if len(arr) == 0 { return false, nil } for _, v := range arr { if b, ok := v.(bool); !ok || !b { return false, nil } } return true, nil default: return value, fmt.Errorf("unknown reducer %q", reducer) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/sort.go
Go
package query import ( "fmt" "sort" "strconv" ) // SortItems sorts the items based on the provided ordering options func SortItems(items []map[string]interface{}, queryOpts *QueryOptions) ([]map[string]interface{}, error) { orderOpts := queryOpts.OrderBy selectOpts := queryOpts.Select if len(orderOpts) == 0 { return items, nil } // Create a copy of the items to avoid modifying the original result := make([]map[string]interface{}, len(items)) copy(result, items) // Sort the items sort.SliceStable(result, func(i, j int) bool { for _, orderOpt := range orderOpts { // Use GetValue to retrieve values respecting aliases and reducers name := orderOpt.Field.Alias valueI, err := GetValue(result[i], name, selectOpts) if err != nil { continue } valueJ, err := GetValue(result[j], name, selectOpts) if err != nil { continue } // Try to convert string values to numeric types if possible valueI = convertStringToNumeric(valueI) valueJ = convertStringToNumeric(valueJ) // Compare values cmp := compareValues(valueI, valueJ) if cmp == 0 { // equal on this field, try next continue } // If descending, reverse the comparison if orderOpt.Descending { return cmp > 0 } return cmp < 0 } // all equal return false }) return result, nil } // convertStringToNumeric attempts to convert string values to numeric types func convertStringToNumeric(value interface{}) interface{} { if strValue, ok := value.(string); ok { // Try to convert to numeric types if possible if i, err := strconv.ParseInt(strValue, 10, 64); err == nil { return int(i) } if f, err := strconv.ParseFloat(strValue, 64); err == nil { return f } } return value } // compareValues compares two values for sorting func compareValues(a, b interface{}) int { // Handle nil values if a == nil && b == nil { return 0 } if a == nil { return -1 } if b == nil { return 1 } // Convert to comparable types switch aVal := a.(type) { case string: if bVal, ok := b.(string); ok { if aVal < bVal { return -1 } if aVal > bVal { return 1 } return 0 } case int: if bVal, ok := b.(int); ok { return aVal - bVal } case float64: if bVal, ok := b.(float64); ok { if aVal < bVal { return -1 } if aVal > bVal { return 1 } return 0 } } // Default string comparison aStr := fmt.Sprintf("%v", a) bStr := fmt.Sprintf("%v", b) if aStr < bStr { return -1 } if aStr > bStr { return 1 } return 0 }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/sort_test.go
Go
package query import ( "reflect" "testing" ) func TestSortItems(t *testing.T) { tests := []struct { name string items []map[string]interface{} queryOpts *QueryOptions want []map[string]interface{} }{ { name: "simple ascending", items: []map[string]interface{}{ {"a": 2}, {"a": 1}, {"a": 3}, }, queryOpts: &QueryOptions{ OrderBy: []OrderOption{{Field: SelectOption{Field: ".a", Alias: "a"}, Descending: false}}, HasOrderBy: true, }, want: []map[string]interface{}{ {"a": 1}, {"a": 2}, {"a": 3}, }, }, { name: "with alias descending", items: []map[string]interface{}{ {"x": 5}, {"x": 3}, {"x": 4}, }, queryOpts: &QueryOptions{ Select: []SelectOption{{Field: ".x", Alias: "y"}}, OrderBy: []OrderOption{{Field: SelectOption{Field: ".x", Alias: "y"}, Descending: true}}, HasSelect: true, HasOrderBy: true, }, want: []map[string]interface{}{ {"x": 5}, {"x": 4}, {"x": 3}, }, }, { name: "with sum reducer ascending", items: []map[string]interface{}{ {"nums": []interface{}{1, 3}}, {"nums": []interface{}{2, 3}}, }, queryOpts: &QueryOptions{ Select: []SelectOption{{Field: ".nums", Alias: "nums", Reducer: "sum"}}, OrderBy: []OrderOption{{Field: SelectOption{Field: ".nums", Alias: "nums", Reducer: "sum"}, Descending: false}}, HasSelect: true, HasOrderBy: true, }, want: []map[string]interface{}{ {"nums": []interface{}{1, 3}}, {"nums": []interface{}{2, 3}}, }, }, { name: "with len reducer ascending", items: []map[string]interface{}{ {"arr": []interface{}{1, 2}}, {"arr": []interface{}{1}}, {"arr": []interface{}{1, 2, 3}}, }, queryOpts: &QueryOptions{ Select: []SelectOption{{Field: ".arr", Alias: "arr", Reducer: "len"}}, OrderBy: []OrderOption{{Field: SelectOption{Field: ".arr", Alias: "arr", Reducer: "len"}, Descending: false}}, HasSelect: true, HasOrderBy: true, }, want: []map[string]interface{}{ {"arr": []interface{}{1}}, {"arr": []interface{}{1, 2}}, {"arr": []interface{}{1, 2, 3}}, }, }, { name: "with any reducer descending", items: []map[string]interface{}{ {"flags": []interface{}{false, false, true}}, {"flags": []interface{}{false, false}}, {"flags": []interface{}{true, false}}, }, queryOpts: &QueryOptions{ Select: []SelectOption{{Field: ".flags", Alias: "flags", Reducer: "any"}}, OrderBy: []OrderOption{{Field: SelectOption{Field: ".flags", Alias: "flags", Reducer: "any"}, Descending: true}}, HasSelect: true, HasOrderBy: true, }, want: []map[string]interface{}{ {"flags": []interface{}{false, false, true}}, {"flags": []interface{}{true, false}}, {"flags": []interface{}{false, false}}, }, }, { name: "with all reducer ascending", items: []map[string]interface{}{ {"flags": []interface{}{true, true}}, {"flags": []interface{}{true, false}}, {"flags": []interface{}{}}, }, queryOpts: &QueryOptions{ Select: []SelectOption{{Field: ".flags", Alias: "flags", Reducer: "all"}}, OrderBy: []OrderOption{{Field: SelectOption{Field: ".flags", Alias: "flags", Reducer: "all"}, Descending: false}}, HasSelect: true, HasOrderBy: true, }, want: []map[string]interface{}{ {"flags": []interface{}{true, false}}, {"flags": []interface{}{}}, {"flags": []interface{}{true, true}}, }, }, { name: "compound sort", items: []map[string]interface{}{ {"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 0, "b": 3}, }, queryOpts: &QueryOptions{ OrderBy: []OrderOption{ {Field: SelectOption{Field: ".a", Alias: "a"}, Descending: false}, {Field: SelectOption{Field: ".b", Alias: "b"}, Descending: true}, }, HasOrderBy: true, }, want: []map[string]interface{}{ {"a": 0, "b": 3}, {"a": 1, "b": 2}, {"a": 1, "b": 1}, }, }, } for _, tc := range tests { got, err := SortItems(tc.items, tc.queryOpts) if err != nil { t.Errorf("%q: unexpected error: %v", tc.name, err) continue } if !reflect.DeepEqual(got, tc.want) { t.Errorf("%q: got %v, want %v", tc.name, got, tc.want) } } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/types.go
Go
package query // QueryOptions contains the parsed query string options type QueryOptions struct { Select []SelectOption Where string OrderBy []OrderOption Limit int HasSelect bool HasOrderBy bool HasLimit bool } // SelectOption represents a column to be selected and its optional alias type SelectOption struct { Field string Alias string Reducer string // one of "sum","len","any","all", or empty } // OrderOption represents a field to sort by and its direction type OrderOption struct { Field SelectOption Descending bool }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/validate.go
Go
package query import ( "fmt" "regexp" "strings" ) // QueryKeyword represents a SQL-like keyword in queries type QueryKeyword struct { Name string Pattern *regexp.Regexp Position int // Expected position order (1=SELECT, 2=WHERE, 3=ORDER BY, 4=LIMIT) } // Common query keywords with their expected positions var keywords = []QueryKeyword{ {"SELECT", regexp.MustCompile(`(?i)\bselect\b`), 1}, {"WHERE", regexp.MustCompile(`(?i)\bwhere\b`), 2}, {"ORDER BY", regexp.MustCompile(`(?i)\border\s+by\b`), 3}, {"SORT BY", regexp.MustCompile(`(?i)\bsort\s+by\b`), 3}, // Same position as ORDER BY {"LIMIT", regexp.MustCompile(`(?i)\blimit\b`), 4}, } // Common typos and their corrections var typoCorrections = map[string]string{ "selct": "SELECT", "slect": "SELECT", "select": "SELECT", // for case consistency "wher": "WHERE", "were": "WHERE", "whre": "WHERE", "limt": "LIMIT", "limit": "LIMIT", // for case consistency "lmit": "LIMIT", "oder": "ORDER", "order": "ORDER", // for case consistency "ordr": "ORDER", "srot": "SORT", "sort": "SORT", // for case consistency "sotr": "SORT", } // ValidationError represents a query syntax error with suggestions type ValidationError struct { Type string Message string Suggestion string Position int // Character position in query (if applicable) FoundText string } // Error implements the error interface func (e ValidationError) Error() string { if e.Suggestion != "" { return fmt.Sprintf("%s: %s. Suggestion: %s", e.Type, e.Message, e.Suggestion) } return fmt.Sprintf("%s: %s", e.Type, e.Message) } // KeywordOccurrence tracks where and how many times a keyword appears type KeywordOccurrence struct { Keyword QueryKeyword Count int Positions []int } // ValidateQuerySyntax performs comprehensive syntax validation on a query string func ValidateQuerySyntax(query string) error { if query == "" { return nil } // Check for typos first if err := checkTypos(query); err != nil { return err } // Count keyword occurrences occurrences := countKeywordOccurrences(query) // Check for duplicate keywords if err := checkDuplicateKeywords(occurrences); err != nil { return err } // Check clause ordering if err := checkClauseOrdering(occurrences); err != nil { return err } // Check for conflicting keywords (ORDER BY vs SORT BY) if err := checkConflictingKeywords(occurrences); err != nil { return err } // Check for empty clauses if err := checkEmptyClauses(query, occurrences); err != nil { return err } return nil } // checkTypos looks for common keyword typos and suggests corrections func checkTypos(query string) error { queryLower := strings.ToLower(query) words := regexp.MustCompile(`\b\w+\b`).FindAllString(queryLower, -1) for _, word := range words { if correction, found := typoCorrections[word]; found && word != strings.ToLower(correction) { // Make sure this isn't actually a valid keyword isValidKeyword := false for _, kw := range keywords { if kw.Pattern.MatchString(word) { isValidKeyword = true break } } if !isValidKeyword { return ValidationError{ Type: "Keyword Typo", Message: fmt.Sprintf("Unrecognized keyword '%s'", word), Suggestion: fmt.Sprintf("Did you mean '%s'?", correction), FoundText: word, } } } } return nil } // countKeywordOccurrences finds all occurrences of each keyword in the query func countKeywordOccurrences(query string) []KeywordOccurrence { var occurrences []KeywordOccurrence for _, keyword := range keywords { matches := keyword.Pattern.FindAllStringIndex(query, -1) if len(matches) > 0 { positions := make([]int, len(matches)) for i, match := range matches { positions[i] = match[0] } occurrences = append(occurrences, KeywordOccurrence{ Keyword: keyword, Count: len(matches), Positions: positions, }) } } return occurrences } // checkDuplicateKeywords validates that keywords don't appear multiple times func checkDuplicateKeywords(occurrences []KeywordOccurrence) error { for _, occ := range occurrences { if occ.Count > 1 { return ValidationError{ Type: "Duplicate Keyword", Message: fmt.Sprintf("Keyword '%s' appears %d times", occ.Keyword.Name, occ.Count), Suggestion: fmt.Sprintf("Use '%s' only once in your query", occ.Keyword.Name), } } } return nil } // checkClauseOrdering validates that clauses appear in the correct SQL-like order func checkClauseOrdering(occurrences []KeywordOccurrence) error { // Create a map of positions to keywords for easier sorting positionMap := make(map[int]QueryKeyword) for _, occ := range occurrences { if len(occ.Positions) > 0 { positionMap[occ.Positions[0]] = occ.Keyword } } // Get all positions and sort them var positions []int for pos := range positionMap { positions = append(positions, pos) } // Simple bubble sort for positions for i := 0; i < len(positions); i++ { for j := 0; j < len(positions)-1-i; j++ { if positions[j] > positions[j+1] { positions[j], positions[j+1] = positions[j+1], positions[j] } } } // Check if keywords appear in correct order lastPosition := 0 for _, pos := range positions { keyword := positionMap[pos] if keyword.Position < lastPosition { return ValidationError{ Type: "Invalid Clause Order", Message: fmt.Sprintf("'%s' appears after a clause that should come later", keyword.Name), Suggestion: "Use the order: SELECT → WHERE → ORDER BY/SORT BY → LIMIT", } } lastPosition = keyword.Position } return nil } // checkConflictingKeywords checks for mutually exclusive keywords func checkConflictingKeywords(occurrences []KeywordOccurrence) error { hasOrderBy := false hasSortBy := false for _, occ := range occurrences { switch occ.Keyword.Name { case "ORDER BY": hasOrderBy = true case "SORT BY": hasSortBy = true } } if hasOrderBy && hasSortBy { return ValidationError{ Type: "Conflicting Keywords", Message: "Cannot use both 'ORDER BY' and 'SORT BY' in the same query", Suggestion: "Choose either 'ORDER BY' or 'SORT BY', not both", } } return nil } // checkEmptyClauses validates that clauses have content after the keyword func checkEmptyClauses(query string, occurrences []KeywordOccurrence) error { queryLower := strings.ToLower(query) for _, occ := range occurrences { if len(occ.Positions) == 0 { continue } pos := occ.Positions[0] keywordName := strings.ToLower(occ.Keyword.Name) // Find the end of the keyword keywordEndPos := pos + len(keywordName) if strings.Contains(keywordName, " ") { // For multi-word keywords like "ORDER BY", we need to be more careful pattern := strings.ReplaceAll(keywordName, " ", `\s+`) regex := regexp.MustCompile(`(?i)` + pattern) match := regex.FindStringIndex(queryLower[pos:]) if match != nil { keywordEndPos = pos + match[1] } } // Extract everything after this keyword until the next keyword or end of query afterKeyword := query[keywordEndPos:] nextKeywordPos := len(afterKeyword) // Find the next keyword position for _, nextOcc := range occurrences { for _, nextPos := range nextOcc.Positions { if nextPos > keywordEndPos { relativePos := nextPos - keywordEndPos if relativePos < nextKeywordPos { nextKeywordPos = relativePos } } } } clauseContent := strings.TrimSpace(afterKeyword[:nextKeywordPos]) if clauseContent == "" { return ValidationError{ Type: "Empty Clause", Message: fmt.Sprintf("'%s' keyword found but no content follows", occ.Keyword.Name), Suggestion: fmt.Sprintf("Add content after '%s' or remove the keyword", occ.Keyword.Name), } } } return nil }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/query/validate_test.go
Go
package query import ( "strings" "testing" ) func TestValidateQuerySyntax(t *testing.T) { tests := []struct { name string query string expectError bool errorType string errorMsg string }{ // Valid queries { name: "empty query", query: "", expectError: false, }, { name: "simple valid query", query: "SELECT name WHERE id > 1 ORDER BY name LIMIT 10", expectError: false, }, { name: "valid query with sort by", query: "WHERE status = 'active' SORT BY created_date", expectError: false, }, // Typo detection tests { name: "typo in SELECT", query: "SELCT name FROM table", expectError: true, errorType: "Keyword Typo", errorMsg: "selct", }, { name: "typo in WHERE", query: "SELECT name WHER id > 1", expectError: true, errorType: "Keyword Typo", errorMsg: "wher", }, { name: "typo in LIMIT", query: "SELECT name LIMT 5", expectError: true, errorType: "Keyword Typo", errorMsg: "limt", }, { name: "typo in ORDER", query: "ODER BY name", expectError: true, errorType: "Keyword Typo", errorMsg: "oder", }, { name: "typo in SORT", query: "SROT BY name", expectError: true, errorType: "Keyword Typo", errorMsg: "srot", }, // Duplicate keyword tests { name: "duplicate SELECT", query: "SELECT name SELECT age WHERE id > 1", expectError: true, errorType: "Duplicate Keyword", errorMsg: "SELECT", }, { name: "duplicate WHERE", query: "SELECT name WHERE id > 1 WHERE status = 'active'", expectError: true, errorType: "Duplicate Keyword", errorMsg: "WHERE", }, { name: "duplicate LIMIT", query: "SELECT name LIMIT 5 LIMIT 10", expectError: true, errorType: "Duplicate Keyword", errorMsg: "LIMIT", }, { name: "duplicate ORDER BY", query: "SELECT name ORDER BY id ORDER BY name", expectError: true, errorType: "Duplicate Keyword", errorMsg: "ORDER BY", }, // Clause ordering tests { name: "WHERE before SELECT", query: "WHERE id > 1 SELECT name", expectError: true, errorType: "Invalid Clause Order", errorMsg: "SELECT", }, { name: "LIMIT before WHERE", query: "SELECT name LIMIT 5 WHERE id > 1", expectError: true, errorType: "Invalid Clause Order", errorMsg: "WHERE", }, { name: "ORDER BY before WHERE", query: "SELECT name ORDER BY name WHERE id > 1", expectError: true, errorType: "Invalid Clause Order", errorMsg: "WHERE", }, // Conflicting keywords tests { name: "ORDER BY and SORT BY together", query: "SELECT name ORDER BY id SORT BY name", expectError: true, errorType: "Conflicting Keywords", errorMsg: "ORDER BY", }, // Empty clause tests { name: "empty SELECT clause", query: "SELECT WHERE id > 1", expectError: true, errorType: "Empty Clause", errorMsg: "SELECT", }, { name: "empty WHERE clause", query: "SELECT name WHERE ORDER BY name", expectError: true, errorType: "Empty Clause", errorMsg: "WHERE", }, { name: "empty ORDER BY clause", query: "SELECT name WHERE id > 1 ORDER BY LIMIT 10", expectError: true, errorType: "Empty Clause", errorMsg: "ORDER BY", }, { name: "empty LIMIT clause", query: "SELECT name WHERE id > 1 LIMIT", expectError: true, errorType: "Empty Clause", errorMsg: "LIMIT", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := ValidateQuerySyntax(tt.query) if tt.expectError { if err == nil { t.Errorf("Expected error but got none for query: %s", tt.query) return } if !strings.Contains(err.Error(), tt.errorType) { t.Errorf("Expected error type '%s' but got: %s", tt.errorType, err.Error()) } if !strings.Contains(err.Error(), tt.errorMsg) { t.Errorf("Expected error message to contain '%s' but got: %s", tt.errorMsg, err.Error()) } } else { if err != nil { t.Errorf("Expected no error but got: %s", err.Error()) } } }) } } func TestCheckTypos(t *testing.T) { tests := []struct { name string query string expectError bool suggestion string }{ { name: "no typos", query: "SELECT name WHERE id > 1", expectError: false, }, { name: "selct typo", query: "SELCT name", expectError: true, suggestion: "SELECT", }, { name: "limt typo", query: "LIMT 5", expectError: true, suggestion: "LIMIT", }, { name: "wher typo", query: "WHER id = 1", expectError: true, suggestion: "WHERE", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := checkTypos(tt.query) if tt.expectError { if err == nil { t.Errorf("Expected error but got none") return } if !strings.Contains(err.Error(), tt.suggestion) { t.Errorf("Expected suggestion '%s' in error: %s", tt.suggestion, err.Error()) } } else { if err != nil { t.Errorf("Expected no error but got: %s", err.Error()) } } }) } } func TestCountKeywordOccurrences(t *testing.T) { tests := []struct { name string query string expected map[string]int }{ { name: "single keywords", query: "SELECT name WHERE id > 1 ORDER BY name LIMIT 10", expected: map[string]int{ "SELECT": 1, "WHERE": 1, "ORDER BY": 1, "LIMIT": 1, }, }, { name: "duplicate keywords", query: "SELECT name SELECT age WHERE id > 1", expected: map[string]int{ "SELECT": 2, "WHERE": 1, }, }, { name: "case insensitive", query: "select name where ID > 1 order by name", expected: map[string]int{ "SELECT": 1, "WHERE": 1, "ORDER BY": 1, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { occurrences := countKeywordOccurrences(tt.query) // Convert to map for easier comparison actual := make(map[string]int) for _, occ := range occurrences { actual[occ.Keyword.Name] = occ.Count } // Check each expected keyword for keyword, expectedCount := range tt.expected { if actualCount, found := actual[keyword]; !found { t.Errorf("Expected keyword '%s' not found", keyword) } else if actualCount != expectedCount { t.Errorf("Keyword '%s': expected count %d, got %d", keyword, expectedCount, actualCount) } } // Check no unexpected keywords for keyword := range actual { if _, expected := tt.expected[keyword]; !expected { t.Errorf("Unexpected keyword '%s' found with count %d", keyword, actual[keyword]) } } }) } } func TestParseQueryStringWithValidation(t *testing.T) { tests := []struct { name string query string expectError bool errorType string }{ { name: "valid query passes validation", query: "SELECT name WHERE id > 1 ORDER BY name LIMIT 10", expectError: false, }, { name: "typo fails validation", query: "SELCT name WHERE id > 1", expectError: true, errorType: "Keyword Typo", }, { name: "duplicate keyword fails validation", query: "SELECT name SELECT age WHERE id > 1", expectError: true, errorType: "Duplicate Keyword", }, { name: "wrong order fails validation", query: "WHERE id > 1 SELECT name", expectError: true, errorType: "Invalid Clause Order", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, err := ParseQueryString(tt.query) if tt.expectError { if err == nil { t.Errorf("Expected error but got none") return } if !strings.Contains(err.Error(), tt.errorType) { t.Errorf("Expected error type '%s' but got: %s", tt.errorType, err.Error()) } } else { if err != nil { t.Errorf("Expected no error but got: %s", err.Error()) } } }) } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat
pkg/util/tui/model.go
Go
package tui import ( "time" "github.com/charmbracelet/bubbles/help" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/spinner" "github.com/charmbracelet/bubbles/viewport" tea "github.com/charmbracelet/bubbletea" ) // DataFetcher is a function that fetches and returns data as a formatted string type DataFetcher func() (string, error) // Model represents the TUI state type Model struct { viewport viewport.Model spinner spinner.Model help help.Model keys keyMap dataFetcher DataFetcher content string lastUpdate time.Time lastError error refreshInterval time.Duration showHelp bool loading bool ready bool quitting bool width int height int } // keyMap defines the keybindings for the TUI type keyMap struct { Up key.Binding Down key.Binding PageUp key.Binding PageDown key.Binding Home key.Binding End key.Binding Quit key.Binding Refresh key.Binding Help key.Binding IncreaseInt key.Binding DecreaseInt key.Binding } // ShortHelp returns keybindings to be shown in the mini help view func (k keyMap) ShortHelp() []key.Binding { return []key.Binding{k.Help, k.Refresh, k.Quit} } // FullHelp returns keybindings for the expanded help view func (k keyMap) FullHelp() [][]key.Binding { return [][]key.Binding{ {k.Up, k.Down, k.PageUp, k.PageDown}, {k.Home, k.End}, {k.Refresh, k.IncreaseInt, k.DecreaseInt}, {k.Help, k.Quit}, } } // defaultKeys returns default key bindings func defaultKeys() keyMap { return keyMap{ Up: key.NewBinding( key.WithKeys("up", "k"), key.WithHelp("↑/k", "up"), ), Down: key.NewBinding( key.WithKeys("down", "j"), key.WithHelp("↓/j", "down"), ), PageUp: key.NewBinding( key.WithKeys("pgup", "b"), key.WithHelp("pgup/b", "page up"), ), PageDown: key.NewBinding( key.WithKeys("pgdown", "f", " "), key.WithHelp("pgdn/f/space", "page down"), ), Home: key.NewBinding( key.WithKeys("home", "g"), key.WithHelp("home/g", "go to start"), ), End: key.NewBinding( key.WithKeys("end", "G"), key.WithHelp("end/G", "go to end"), ), Quit: key.NewBinding( key.WithKeys("q", "ctrl+c"), key.WithHelp("q", "quit"), ), Refresh: key.NewBinding( key.WithKeys("r"), key.WithHelp("r", "refresh now"), ), Help: key.NewBinding( key.WithKeys("?"), key.WithHelp("?", "toggle help"), ), IncreaseInt: key.NewBinding( key.WithKeys("+", "="), key.WithHelp("+", "increase refresh interval"), ), DecreaseInt: key.NewBinding( key.WithKeys("-"), key.WithHelp("-", "decrease refresh interval"), ), } } // NewModel creates a new TUI model func NewModel(dataFetcher DataFetcher, refreshInterval time.Duration) Model { s := spinner.New() s.Spinner = spinner.Dot s.Style = spinnerStyle return Model{ spinner: s, help: help.New(), keys: defaultKeys(), dataFetcher: dataFetcher, refreshInterval: refreshInterval, lastUpdate: time.Now(), loading: false, showHelp: false, ready: false, quitting: false, } } // Init initializes the TUI model func (m Model) Init() tea.Cmd { return tea.Batch( m.spinner.Tick, fetchData(m.dataFetcher), tickCmd(m.refreshInterval), ) } // TickMsg is sent on each refresh interval type tickMsg time.Time // fetchDataMsg is sent when data fetching completes type fetchDataMsg struct { content string err error } // tickCmd returns a command that sends a tick message after the given duration func tickCmd(d time.Duration) tea.Cmd { return tea.Tick(d, func(t time.Time) tea.Msg { return tickMsg(t) }) } // fetchData returns a command that fetches data func fetchData(fetcher DataFetcher) tea.Cmd { return func() tea.Msg { content, err := fetcher() return fetchDataMsg{content: content, err: err} } }
yaacov/kubectl-mtv
11
A kubectl plugin that helps users of Forklift migrate virtualization workloads from oVirt, VMware, OpenStack, and OVA files to KubeVirt on Kubernetes.
Go
yaacov
Yaacov Zamir
Red Hat