_import

package
v0.1.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2022 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Cmd = &cobra.Command{
	Use:   "import",
	Short: "Import the image into PowerVS instances",
	Long: `Import the image into PowerVS instances
pvsadm image import --help for information

# Set the API key or feed the --api-key commandline argument
export IBMCLOUD_API_KEY=<IBM_CLOUD_API_KEY>

# To Import the imge across the two different IBM account use accesskey and secretkey options

# To Import the image from public bucket use public-bucket option

Examples:

# import image using default storage type (service credential will be autogenerated)
pvsadm image import -n upstream-core-lon04 -b <BUCKETNAME> --object rhel-83-10032020.ova.gz --pvs-image-name test-image -r <REGION>

# import image using default storage type with specifying the accesskey and secretkey explicitly
pvsadm image import -n upstream-core-lon04 -b <BUCKETNAME> --accesskey <ACCESSKEY> --secretkey <SECRETKEY> --object rhel-83-10032020.ova.gz --pvs-image-name test-image -r <REGION>

# with user provided storage type
pvsadm image import -n upstream-core-lon04 -b <BUCKETNAME> --pvs-storagetype <STORAGETYPE> --object rhel-83-10032020.ova.gz --pvs-image-name test-image -r <REGION>

# If user wants to specify the type of OS
pvsadm image import -n upstream-core-lon04 -b <BUCKETNAME> --object rhel-83-10032020.ova.gz --pvs-image-name test-image -r <REGION>

# import image from a public IBM Cloud Storage bucket
pvsadm image import -n upstream-core-lon04 -b <BUCKETNAME>  --object rhel-83-10032020.ova.gz --pvs-image-name test-image -r <REGION> --public-bucket
`,
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if pkg.ImageCMDOptions.InstanceID == "" && pkg.ImageCMDOptions.InstanceName == "" {
			return fmt.Errorf("--pvs-instance-name or --pvs-instance-id required")
		}

		case1 := pkg.ImageCMDOptions.AccessKey == "" && pkg.ImageCMDOptions.SecretKey != ""
		case2 := pkg.ImageCMDOptions.AccessKey != "" && pkg.ImageCMDOptions.SecretKey == ""

		if case1 || case2 {
			return fmt.Errorf("required both --accesskey and --secretkey values")
		}
		return nil
	},

	RunE: func(cmd *cobra.Command, args []string) error {
		opt := pkg.ImageCMDOptions
		apikey := pkg.Options.APIKey

		validStorageType := []string{"tier3", "tier1"}

		if !utils.Contains(validStorageType, strings.ToLower(opt.StorageType)) {
			klog.Errorf("Provide valid StorageType.. allowable values are [tier1, tier3]")
			os.Exit(1)
		}

		bxCli, err := client.NewClientWithEnv(apikey, pkg.Options.Environment, pkg.Options.Debug)
		if err != nil {
			return err
		}

		if (opt.AccessKey == "" || opt.SecretKey == "") && (!opt.Public) {
			//Find CosInstance of the bucket
			var svcs []models.ServiceInstanceV2
			svcs, err = bxCli.ResourceClientV2.ListInstances(controllerv2.ServiceInstanceQuery{
				Type: "service_instance",
			})
			if err != nil {
				return err
			}
			cosInstanceName, cosID, crn := findCOSInstanceDetails(svcs, bxCli)
			if cosInstanceName == "" {
				return fmt.Errorf("failed to find the COS instance for the bucket mentioned: %s", opt.BucketName)
			}

			keys, err := bxCli.GetResourceKeys(cosID)
			if err != nil {
				return fmt.Errorf("failed to list the service credentials: %v", err)
			}

			var cred map[string]interface{}
			var ok bool
			if len(keys) == 0 {
				if opt.ServiceCredName == "" {
					opt.ServiceCredName = serviceCredPrefix + "-" + cosInstanceName
				}

				klog.Infof("Auto Generating the COS Service credential for importing the image with name: %s", opt.ServiceCredName)
				CreateServiceKeyRequest := controller.CreateServiceKeyRequest{
					Name:       opt.ServiceCredName,
					SourceCRN:  crn,
					Parameters: map[string]interface{}{"HMAC": true},
				}
				newKey, err := bxCli.ResourceServiceKey.CreateKey(CreateServiceKeyRequest)
				if err != nil {
					return err
				}
				cred, ok = newKey.Credentials["cos_hmac_keys"].(map[string]interface{})
			} else {

				klog.Infof("Reading the existing service credential")
				cred, ok = keys[0].Credentials["cos_hmac_keys"].(map[string]interface{})
			}
			if !ok {
				return fmt.Errorf("failed to get the accessKey and secretKey from service credential")
			}

			opt.AccessKey = cred["access_key_id"].(string)
			opt.SecretKey = cred["secret_access_key"].(string)
		}

		pvmclient, err := client.NewPVMClientWithEnv(bxCli, opt.InstanceID, opt.InstanceName, pkg.Options.Environment)
		if err != nil {
			return err
		}

		bucketAccess := "private"

		if opt.Public {
			bucketAccess = "public"
		}
		jobRef, err := pvmclient.ImgClient.ImportImage(opt.ImageName, opt.ImageFilename, opt.Region,
			opt.AccessKey, opt.SecretKey, opt.BucketName, strings.ToLower(opt.StorageType), bucketAccess)
		if err != nil {
			return err
		}

		start := time.Now()
		pollErr := wait.PollImmediate(2*time.Minute, opt.WatchTimeout, func() (bool, error) {
			job, err := pvmclient.JobClient.Get(*jobRef.ID)
			if err != nil {
				return false, err
			}
			if *job.Status.State == "completed" {
				return true, nil
			}
			if *job.Status.State == "failed" {
				return false, fmt.Errorf("image import job failed to complete, err: %v", job.Status.Message)
			}
			klog.Infof("Image Import Job in-progress, current state: %s", *job.Status.State)
			return false, nil
		})
		if pollErr == wait.ErrWaitTimeout {
			pollErr = fmt.Errorf("timed out while waiting for image import job to complete")
		}

		if pollErr != nil {
			return fmt.Errorf("image import job failed to complete, err: %v", pollErr)
		}

		var image *pmodels.ImageReference = &pmodels.ImageReference{}
		for image.ImageID == nil {
			image, err = pvmclient.ImgClient.GetImageByName(opt.ImageName)
			if err != nil {
				return err
			}
			klog.Infof("Retriving image details")
		}

		if !opt.Watch {
			klog.Infof("Importing Image %s is currently in %s state, Please check the Progress in the IBM Cloud UI\n", *image.Name, *image.State)
			return nil
		}

		pollErr = wait.PollImmediate(2*time.Minute, opt.WatchTimeout, func() (bool, error) {
			img, err := pvmclient.ImgClient.Get(*image.ImageID)
			if err != nil {
				return false, err
			}
			if img.State == "active" {
				return true, nil
			}
			klog.Infof("Import in-progress, current state: %s", img.State)
			return false, nil
		})
		if pollErr == wait.ErrWaitTimeout {
			pollErr = fmt.Errorf("timed out while waiting for image to become ready state")
		}

		if pollErr != nil {
			return fmt.Errorf("failed to import the image, err: %v\n\nRun this command to get more information for the failure: pvsadm get events -i %s", pollErr, pvmclient.InstanceID)
		}

		klog.Infof("Successfully imported the image: %s with ID: %s within %s", *image.Name, *image.ImageID, time.Since(start))

		return nil
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL