// SnapshotCreate creates a read-only snapshot of a volume
543130
func (s *VolumeServer) SnapshotCreate(
	ctx context.Context,
	req *api.SdkVolumeSnapshotCreateRequest,
) (*api.SdkVolumeSnapshotCreateResponse, error) {
	if s.cluster() == nil || s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	if len(req.GetVolumeId()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must supply volume id")
	} else if len(req.GetName()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must supply a name")
	}

	// Get access rights
	if err := s.checkAccessForVolumeId(ctx, req.GetVolumeId(), api.Ownership_Read); err != nil {
		return nil, err
	}

	readonly := true
	snapshotID, err := s.driver(ctx).Snapshot(req.GetVolumeId(), readonly, &api.VolumeLocator{
		Name:         req.GetName(),
		VolumeLabels: req.GetLabels(),
	}, false)
	if err != nil {
		if err == kvdb.ErrNotFound {
			return nil, status.Errorf(
				codes.NotFound,
				"Id %s not found",
				req.GetVolumeId())
		}
		return nil, status.Errorf(codes.Internal, "Failed to create snapshot: %v", err.Error())
	}

	return &api.SdkVolumeSnapshotCreateResponse{
		SnapshotId: snapshotID,
	}, nil
}
18296
func (p *iscsiProvisioner) exportCreate(vol string, lun int32, pool string, initiator string) error {
	client, err := p.getConnection()
	defer client.Close()
	if err != nil {
		log.Warnln(err)
		return err
	}
	args := exportCreateArgs{
		Pool:         pool,
		Vol:          vol,
		InitiatorWwn: initiator,
		Lun:          lun,
	}
	err = client.Call("export_create", args, nil)
	return err
}
111432
func (d *driver) VolumeSnapshot(
	ctx types.Context,
	volumeID, snapshotName string,
	opts types.Store) (*types.Snapshot, error) {
	// TODO Snapshots are not implemented yet
	return nil, types.ErrNotImplemented
}
636567
func VolumeCreate(info *model.VolumeCreateInfo) error {
	return mgr.Do(func(ctx context.Context, cli *client.Client) (err error) {
		options := volume.VolumeCreateBody{
			Name:       info.Name,
			DriverOpts: info.Options.ToMap(),
			Labels:     info.Labels.ToMap(),
		}
		if info.Driver == "other" {
			options.Driver = info.CustomDriver
		} else {
			options.Driver = info.Driver
		}

		_, err = cli.VolumeCreate(ctx, options)
		return
	})
}
273148
func (c *Client) CreateVolume(p *CreateVolumeParameter) (*Volume, error) {
	obj, err := c.Request("createVolume", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Volume), err
}
562797
func (d *driver) VolumeCreate(
	ctx types.Context,
	name string,
	opts *types.VolumeCreateOpts) (*types.Volume, error) {

	// Token is limited to 64 ASCII characters so just create MD5 hash from full
	// tag/name identifier
	creationToken := fmt.Sprintf("%x", md5.Sum([]byte(d.getFullVolumeName(name))))
	request := &awsefs.CreateFileSystemInput{
		CreationToken:   aws.String(creationToken),
		PerformanceMode: aws.String(awsefs.PerformanceModeGeneralPurpose),
	}
	if opts.Type != nil && strings.ToLower(*opts.Type) == "maxio" {
		request.PerformanceMode = aws.String(awsefs.PerformanceModeMaxIo)
	}

	svc := mustSession(ctx)
	fileSystem, err := svc.CreateFileSystem(request)

	if err != nil {
		return nil, err
	}

	_, err = svc.CreateTags(&awsefs.CreateTagsInput{
		FileSystemId: fileSystem.FileSystemId,
		Tags: []*awsefs.Tag{
			{
				Key:   aws.String("Name"),
				Value: aws.String(d.getFullVolumeName(name)),
			},
		},
	})

	if err != nil {
		// To not leak the EFS instances remove the filesystem that couldn't
		// be tagged with correct name before returning error response.
		_, deleteErr := svc.DeleteFileSystem(
			&awsefs.DeleteFileSystemInput{
				FileSystemId: fileSystem.FileSystemId,
			})
		if deleteErr != nil {
			ctx.WithFields(log.Fields{
				"filesystemid": *fileSystem.FileSystemId,
			}).Error("failed to delete EFS")
		}

		return nil, err
	}

	f := func() (interface{}, error) {
		duration := d.statusDelay
		for i := 1; i <= d.maxAttempts; i++ {
			state, err := d.getFileSystemLifeCycleState(
				svc, *fileSystem.FileSystemId)
			if err != nil {
				return nil, goof.WithFieldE(
					"filesystemid",
					*fileSystem.FileSystemId,
					"failed to retreive EFS state",
					err)
			}
			if state == awsefs.LifeCycleStateAvailable {
				return nil, nil
			}
			ctx.WithFields(log.Fields{
				"state":        state,
				"filesystemid": *fileSystem.FileSystemId,
			}).Debug("EFS not ready")

			time.Sleep(time.Duration(duration) * time.Nanosecond)
			duration = int64(2) * duration
		}
		return nil, goof.WithField("maxAttempts", d.maxAttempts,
			"Status attempts exhausted")
	}

	// Wait until FS is in "available" state
	_, ok, err := apiUtils.WaitFor(f, d.statusTimeout)
	if !ok {
		return nil, goof.WithFields(goof.Fields{
			"filesystemid":  *fileSystem.FileSystemId,
			"statusTimeout": d.statusTimeout},
			"Timeout occured waiting for filesystem status")
	}
	if err != nil {
		return nil, goof.WithFieldE("filesystemid", *fileSystem.FileSystemId,
			"Error while waiting for storage action to finish", err)
	}

	return d.VolumeInspect(ctx, *fileSystem.FileSystemId,
		&types.VolumeInspectOpts{Attachments: 0})
}
197562
func (s *CloudBackupServer) Create(
	ctx context.Context,
	req *api.SdkCloudBackupCreateRequest,
) (*api.SdkCloudBackupCreateResponse, error) {

	if s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}
	credId := req.GetCredentialId()
	var err error
	if len(req.GetVolumeId()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must supply a volume id")
	}
	if len(req.GetCredentialId()) == 0 {
		credId, err = s.defaultCloudBackupCreds(ctx)
		if err != nil {
			return nil, err
		}
	}

	// Check ownership
	if err := checkAccessFromDriverForVolumeId(ctx, s.driver(ctx), req.GetVolumeId(), api.Ownership_Read); err != nil {
		return nil, err
	}

	if len(req.GetCredentialId()) != 0 {
		if err := s.checkAccessToCredential(ctx, credId); err != nil {
			return nil, err
		}
	}

	r, err := s.driver(ctx).CloudBackupCreate(&api.CloudBackupCreateRequest{
		VolumeID:       req.GetVolumeId(),
		CredentialUUID: credId,
		Full:           req.GetFull(),
		Name:           req.GetTaskId(),
		Labels:         req.GetLabels(),
	})
	if err != nil {
		if err == volume.ErrInvalidName {
			return nil, status.Errorf(codes.AlreadyExists, "Backup with this name already exists: %v", err)
		}
		return nil, status.Errorf(codes.Internal, "Failed to create backup: %v", err)
	}

	return &api.SdkCloudBackupCreateResponse{
		TaskId: r.Name,
	}, nil
}
782548
func (_m *APIClient) ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) {
	ret := _m.Called(ctx, parentReference, options)

	var r0 io.ReadCloser
	if rf, ok := ret.Get(0).(func(context.Context, string, types.ImageCreateOptions) io.ReadCloser); ok {
		r0 = rf(ctx, parentReference, options)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(io.ReadCloser)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, string, types.ImageCreateOptions) error); ok {
		r1 = rf(ctx, parentReference, options)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
293763
func createVolumeWithData(cli *client.Client, volumeName string, data map[string][]byte, image string) error {
	_, err := cli.VolumeCreate(context.Background(),
		volume.VolumeCreateBody{
			Driver: "local",
			Name:   volumeName,
		})
	if err != nil {
		return err
	}
	mnt := "/mnt"
	miniContainer, err := cli.ContainerCreate(context.Background(),
		&container.Config{
			Image: image,
		},
		&container.HostConfig{
			Mounts: []mount.Mount{
				{
					Type:   mount.TypeVolume,
					Source: volumeName,
					Target: mnt,
				},
			},
		}, nil, "")
	if err != nil {
		return err
	}
	tr, err := createTar(data)
	if err != nil {
		return err
	}
	if cli.CopyToContainer(context.Background(),
		miniContainer.ID, mnt, tr, types.CopyToContainerOptions{}); err != nil {
		return err
	}
	return cli.ContainerRemove(context.Background(),
		miniContainer.ID,
		types.ContainerRemoveOptions{})
}
514044
func (c *Client) CreateVolume(
	ctx context.Context, name string) (Volume, error) {

	_, err := apiv1.CreateIsiVolume(ctx, c.API, name)
	if err != nil {
		return nil, err
	}

	var isiVolume = &apiv1.IsiVolume{Name: name, AttributeMap: nil}
	return isiVolume, nil
}
6025
func (s *DBSnapshot) SetSnapshotCreateTime(v time.Time) *DBSnapshot {
	s.SnapshotCreateTime = &v
	return s
}
360737
func (d *driver) VolumeCreate(ctx types.Context, volumeName string,
	opts *types.VolumeCreateOpts) (*types.Volume, error) {

	vol, err := d.VolumeInspect(ctx, volumeName,
		&types.VolumeInspectOpts{Attachments: types.VolAttReqTrue})
	if err != nil {
		if _, ok := err.(*types.ErrNotFound); !ok {
			return nil, err
		}
	}

	if vol != nil {
		return nil, goof.New("volume name already exists")
	}

	_, err = d.client.CreateVolume(ctx, volumeName)
	if err != nil {
		return nil, goof.WithFieldE(
			"volumeName", volumeName, "Error creating volume", err)
	}

	// Set or update the quota for volume
	if d.quotas() {
		quota, err := d.client.GetQuota(ctx, volumeName)
		if quota == nil {
			// PAPI uses bytes for it's size units, but REX-Ray uses gigs
			err = d.client.SetQuotaSize(ctx, volumeName, *opts.Size*bytesPerGb)
			if err != nil {
				// TODO: not sure how to handle this situation. Delete created
				// volume and return an error?  Ignore and continue?
				return nil, goof.WithFieldE("volumeName", volumeName,
					"Error creating volume", err)
			}
		} else {
			// PAPI uses bytes for it's size units, but REX-Ray uses gigs
			err = d.client.UpdateQuotaSize(
				ctx, volumeName, *opts.Size*bytesPerGb)
			if err != nil {
				// TODO: not sure how to handle this situation. Delete created
				// volume and return an error?  Ignore and continue?
				return nil, goof.WithFieldE("volumeName", volumeName,
					"Error creating volume", err)
			}
		}
	}

	return d.VolumeInspect(ctx, volumeName,
		&types.VolumeInspectOpts{Attachments: 0})
}
376813
func (_m *API) VirtualizationCreate(ctx context.Context, opts *types.VirtualizationCreateOptions) (*types.VirtualizationCreated, error) {
	ret := _m.Called(ctx, opts)

	var r0 *types.VirtualizationCreated
	if rf, ok := ret.Get(0).(func(context.Context, *types.VirtualizationCreateOptions) *types.VirtualizationCreated); ok {
		r0 = rf(ctx, opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*types.VirtualizationCreated)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, *types.VirtualizationCreateOptions) error); ok {
		r1 = rf(ctx, opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
277067
func (c *Cloud) CreateSnapshot(snapshotOptions *SnapshotOptions) (snapshotID string, status string, err error) {
	request := &ec2.CreateSnapshotInput{}
	request.VolumeId = aws.String(snapshotOptions.VolumeID)
	request.DryRun = aws.Bool(false)
	descriptions := "Created by Kubernetes for volume " + snapshotOptions.VolumeID
	request.Description = aws.String(descriptions)
	res, err := c.ec2.CreateSnapshot(request)
	if err != nil {
		return "", "", err
	}
	if res == nil {
		return "", "", fmt.Errorf("nil CreateSnapshotResponse")
	}
	if snapshotOptions.Tags != nil {
		awsID := awsVolumeID(aws.StringValue(res.SnapshotId))
		// apply tags
		if err := c.tagging.createTags(c.ec2, string(awsID), ResourceLifecycleOwned, *snapshotOptions.Tags); err != nil {
			_, delerr := c.DeleteSnapshot(*res.SnapshotId)
			if delerr != nil {
				return "", "", fmt.Errorf("error tagging snapshot %s, could not delete the snapshot: %v", *res.SnapshotId, delerr)
			}
			return "", "", fmt.Errorf("error tagging snapshot %s: %v", *res.SnapshotId, err)
		}
	}
	return *res.SnapshotId, *res.State, nil

}
33644
func (vmdisk vmDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (canonicalDiskPath string, err error) {
	if vmdisk.volumeOptions.SCSIControllerType == "" {
		vmdisk.volumeOptions.SCSIControllerType = vclib.PVSCSIControllerType
	}
	pbmClient, err := vclib.NewPbmClient(ctx, datastore.Client())
	if err != nil {
		klog.Errorf("Error occurred while creating new pbmClient, err: %+v", err)
		return "", err
	}

	if vmdisk.volumeOptions.StoragePolicyID == "" && vmdisk.volumeOptions.StoragePolicyName != "" {
		vmdisk.volumeOptions.StoragePolicyID, err = pbmClient.ProfileIDByName(ctx, vmdisk.volumeOptions.StoragePolicyName)
		if err != nil {
			klog.Errorf("Error occurred while getting Profile Id from Profile Name: %s, err: %+v", vmdisk.volumeOptions.StoragePolicyName, err)
			return "", err
		}
	}
	if vmdisk.volumeOptions.StoragePolicyID != "" {
		compatible, faultMessage, err := datastore.IsCompatibleWithStoragePolicy(ctx, vmdisk.volumeOptions.StoragePolicyID)
		if err != nil {
			klog.Errorf("Error occurred while checking datastore compatibility with storage policy id: %s, err: %+v", vmdisk.volumeOptions.StoragePolicyID, err)
			return "", err
		}

		if !compatible {
			klog.Errorf("Datastore: %s is not compatible with Policy: %s", datastore.Name(), vmdisk.volumeOptions.StoragePolicyName)
			return "", fmt.Errorf("User specified datastore is not compatible with the storagePolicy: %q. Failed with faults: %+q", vmdisk.volumeOptions.StoragePolicyName, faultMessage)
		}
	}

	storageProfileSpec := &types.VirtualMachineDefinedProfileSpec{}
	// Is PBM storage policy ID is present, set the storage spec profile ID,
	// else, set raw the VSAN policy string.
	if vmdisk.volumeOptions.StoragePolicyID != "" {
		storageProfileSpec.ProfileId = vmdisk.volumeOptions.StoragePolicyID
	} else if vmdisk.volumeOptions.VSANStorageProfileData != "" {
		// Check Datastore type - VSANStorageProfileData is only applicable to vSAN Datastore
		dsType, err := datastore.GetType(ctx)
		if err != nil {
			return "", err
		}
		if dsType != vclib.VSANDatastoreType {
			klog.Errorf("The specified datastore: %q is not a VSAN datastore", datastore.Name())
			return "", fmt.Errorf("The specified datastore: %q is not a VSAN datastore."+
				" The policy parameters will work only with VSAN Datastore."+
				" So, please specify a valid VSAN datastore in Storage class definition.", datastore.Name())
		}
		storageProfileSpec.ProfileId = ""
		storageProfileSpec.ProfileData = &types.VirtualMachineProfileRawData{
			ExtensionKey: "com.vmware.vim.sps",
			ObjectData:   vmdisk.volumeOptions.VSANStorageProfileData,
		}
	} else {
		klog.Errorf("Both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set")
		return "", fmt.Errorf("Both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set")
	}
	var dummyVM *vclib.VirtualMachine
	// Check if VM already exist in the folder.
	// If VM is already present, use it, else create a new dummy VM.
	fnvHash := fnv.New32a()
	fnvHash.Write([]byte(vmdisk.volumeOptions.Name))
	dummyVMFullName := vclib.DummyVMPrefixName + "-" + fmt.Sprint(fnvHash.Sum32())
	dummyVM, err = datastore.Datacenter.GetVMByPath(ctx, vmdisk.vmOptions.VMFolder.InventoryPath+"/"+dummyVMFullName)
	if err != nil {
		// Create a dummy VM
		klog.V(1).Infof("Creating Dummy VM: %q", dummyVMFullName)
		dummyVM, err = vmdisk.createDummyVM(ctx, datastore.Datacenter, dummyVMFullName)
		if err != nil {
			klog.Errorf("Failed to create Dummy VM. err: %v", err)
			return "", err
		}
	}

	// Reconfigure the VM to attach the disk with the VSAN policy configured
	virtualMachineConfigSpec := types.VirtualMachineConfigSpec{}
	disk, _, err := dummyVM.CreateDiskSpec(ctx, vmdisk.diskPath, datastore, vmdisk.volumeOptions)
	if err != nil {
		klog.Errorf("Failed to create Disk Spec. err: %v", err)
		return "", err
	}
	deviceConfigSpec := &types.VirtualDeviceConfigSpec{
		Device:        disk,
		Operation:     types.VirtualDeviceConfigSpecOperationAdd,
		FileOperation: types.VirtualDeviceConfigSpecFileOperationCreate,
	}

	deviceConfigSpec.Profile = append(deviceConfigSpec.Profile, storageProfileSpec)
	virtualMachineConfigSpec.DeviceChange = append(virtualMachineConfigSpec.DeviceChange, deviceConfigSpec)
	fileAlreadyExist := false
	task, err := dummyVM.Reconfigure(ctx, virtualMachineConfigSpec)
	if err != nil {
		klog.Errorf("Failed to reconfig. err: %v", err)
		return "", err
	}
	err = task.Wait(ctx)
	if err != nil {
		fileAlreadyExist = isAlreadyExists(vmdisk.diskPath, err)
		if fileAlreadyExist {
			//Skip error and continue to detach the disk as the disk was already created on the datastore.
			klog.V(vclib.LogLevel).Infof("File: %v already exists", vmdisk.diskPath)
		} else {
			klog.Errorf("Failed to attach the disk to VM: %q with err: %+v", dummyVMFullName, err)
			return "", err
		}
	}
	// Detach the disk from the dummy VM.
	err = dummyVM.DetachDisk(ctx, vmdisk.diskPath)
	if err != nil {
		if vclib.DiskNotFoundErrMsg == err.Error() && fileAlreadyExist {
			// Skip error if disk was already detached from the dummy VM but still present on the datastore.
			klog.V(vclib.LogLevel).Infof("File: %v is already detached", vmdisk.diskPath)
		} else {
			klog.Errorf("Failed to detach the disk: %q from VM: %q with err: %+v", vmdisk.diskPath, dummyVMFullName, err)
			return "", err
		}
	}
	//  Delete the dummy VM
	err = dummyVM.DeleteVM(ctx)
	if err != nil {
		klog.Errorf("Failed to destroy the vm: %q with err: %+v", dummyVMFullName, err)
	}
	return vmdisk.diskPath, nil
}
422545
func CreateIsiSnapshot(
	ctx context.Context,
	client api.Client,
	path, name string) (resp *IsiSnapshot, err error) {
	// PAPI call: POST https://1.2.3.4:8080/platform/1/snapshot/snapshots
	//            Content-Type: application/json
	//            {path: "/path/to/volume"
	//             name: "snapshot_name"  <--- optional
	//            }
	if path == "" {
		return nil, errors.New("no path set")
	}

	data := &SnapshotPath{Path: path}
	if name != "" {
		data.Name = name
	}

	err = client.Post(ctx, snapshotsPath, "", nil, nil, data, &resp)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
153778
func CreateVolume(obj *Volume) error {
	// Validate parameters
	err := ValidateVolume(obj)
	if err != nil {
		log.Errorf("ValidateVolume retruned error for: %+v. Err: %v", obj, err)
		return err
	}

	// Check if we handle this object
	if objCallbackHandler.VolumeCb == nil {
		log.Errorf("No callback registered for volume object")
		return errors.New("Invalid object type")
	}

	saveObj := obj

	collections.volumeMutex.Lock()
	key := collections.volumes[obj.Key]
	collections.volumeMutex.Unlock()

	// Check if object already exists
	if key != nil {
		// Perform Update callback
		err = objCallbackHandler.VolumeCb.VolumeUpdate(collections.volumes[obj.Key], obj)
		if err != nil {
			log.Errorf("VolumeUpdate retruned error for: %+v. Err: %v", obj, err)
			return err
		}

		// save the original object after update
		collections.volumeMutex.Lock()
		saveObj = collections.volumes[obj.Key]
		collections.volumeMutex.Unlock()
	} else {
		// save it in cache
		collections.volumeMutex.Lock()
		collections.volumes[obj.Key] = obj
		collections.volumeMutex.Unlock()

		// Perform Create callback
		err = objCallbackHandler.VolumeCb.VolumeCreate(obj)
		if err != nil {
			log.Errorf("VolumeCreate retruned error for: %+v. Err: %v", obj, err)
			collections.volumeMutex.Lock()
			delete(collections.volumes, obj.Key)
			collections.volumeMutex.Unlock()
			return err
		}
	}

	// Write it to modeldb
	collections.volumeMutex.Lock()
	err = saveObj.Write()
	collections.volumeMutex.Unlock()
	if err != nil {
		log.Errorf("Error saving volume %s to db. Err: %v", saveObj.Key, err)
		return err
	}

	return nil
}