// Create will create a new volume with the volumeName and opts.
182747
func (d *driver) Create(
	ctx types.Context,
	volumeName string,
	opts *types.VolumeCreateOpts) (*types.Volume, error) {

	if volumeName == "" {
		return nil, goof.New("missing volume name or ID")
	}

	optsNew := &types.VolumeCreateOpts{}
	az := d.availabilityZone()
	optsNew.AvailabilityZone = &az
	size := d.size()
	optsNew.Size = &size
	volumeType := d.volumeType()
	optsNew.Type = &volumeType
	iops := d.iops()
	optsNew.IOPS = &iops
	optsNew.Encrypted = opts.Encrypted
	optsNew.EncryptionKey = opts.EncryptionKey

	if opts.Opts.IsSet("availabilityZone") {
		az = opts.Opts.GetString("availabilityZone")
	}
	if opts.Opts.IsSet("size") {
		size = opts.Opts.GetInt64("size")
	}
	if opts.Opts.IsSet("volumeType") {
		volumeType = opts.Opts.GetString("volumeType")
	}
	if opts.Opts.IsSet("type") {
		volumeType = opts.Opts.GetString("type")
	}
	if opts.Opts.IsSet("iops") {
		iops = opts.Opts.GetInt64("iops")
	}

	optsNew.Opts = opts.Opts

	ctx.WithFields(log.Fields{
		"volumeName":       volumeName,
		"availabilityZone": az,
		"size":             size,
		"volumeType":       volumeType,
		"IOPS":             iops,
		"encrypted":        optsNew.Encrypted,
		"encryptionKey":    optsNew.EncryptionKey,
		"opts":             opts}).Info("creating volume")

	client := context.MustClient(ctx)
	vol, err := client.Storage().VolumeCreate(ctx, volumeName, optsNew)
	if err != nil {
		return nil, err
	}

	ctx.WithFields(log.Fields{
		"volumeName": volumeName,
		"vol":        vol}).Info("volume created")

	return vol, nil
}
1052356
func (c *FakePersistentVolumes) Create(persistentVolume *corev1.PersistentVolume) (result *corev1.PersistentVolume, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(persistentvolumesResource, persistentVolume), &corev1.PersistentVolume{})
	if obj == nil {
		return nil, err
	}
	return obj.(*corev1.PersistentVolume), err
}
1097240
func (client QuobyteClient) CreateVolume(request *CreateVolumeRequest) (string, error) {
	var response volumeUUID
	tenantUUID, err := client.GetTenantUUID(request.TenantID)
	if err != nil {
		return "", err
	}
	request.TenantID = tenantUUID

	if err = client.sendRequest("createVolume", request, &response); err != nil {
		return "", err
	}

	return response.VolumeUUID, nil
}
751834
func (c *clusters) Create(cluster *v1alpha2.Cluster) (result *v1alpha2.Cluster, err error) {
	result = &v1alpha2.Cluster{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("clusters").
		Body(cluster).
		Do().
		Into(result)
	return
}
118697
func (ga *openstackStorageAdapter) CreateVolume(args cinder.CreateVolumeVolumeParams) (*cinder.Volume, error) {
	resp, err := ga.cinderClient.CreateVolume(args)
	if err != nil {
		return nil, err
	}
	return &resp.Volume, nil
}
880879
func (s *VolumeService) NewCreateVolumeParams() *CreateVolumeParams {
	p := &CreateVolumeParams{}
	p.p = make(map[string]interface{})
	return p
}
462458
func (util *DiskUtil) CreateVolume(c *cinderVolumeProvisioner, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (volumeID string, volumeSizeGB int, volumeLabels map[string]string, fstype string, err error) {
	cloud, err := c.plugin.getCloudProvider()
	if err != nil {
		return "", 0, nil, "", err
	}

	capacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
	// Cinder works with gigabytes, convert to GiB with rounding up
	volSizeGiB, err := volumehelpers.RoundUpToGiBInt(capacity)
	if err != nil {
		return "", 0, nil, "", err
	}

	name := volutil.GenerateVolumeName(c.options.ClusterName, c.options.PVName, 255) // Cinder volume name can have up to 255 characters
	vtype := ""
	availability := ""
	// Apply ProvisionerParameters (case-insensitive). We leave validation of
	// the values to the cloud provider.
	for k, v := range c.options.Parameters {
		switch strings.ToLower(k) {
		case "type":
			vtype = v
		case "availability":
			availability = v
		case volume.VolumeParameterFSType:
			fstype = v
		default:
			return "", 0, nil, "", fmt.Errorf("invalid option %q for volume plugin %s", k, c.plugin.GetPluginName())
		}
	}
	// TODO: implement PVC.Selector parsing
	if c.options.PVC.Spec.Selector != nil {
		return "", 0, nil, "", fmt.Errorf("claim.Spec.Selector is not supported for dynamic provisioning on Cinder")
	}

	if availability == "" {
		// No zone specified, choose one randomly in the same region
		zones, err := getZonesFromNodes(c.plugin.host.GetKubeClient())
		if err != nil {
			klog.V(2).Infof("error getting zone information: %v", err)
			return "", 0, nil, "", err
		}
		// if we did not get any zones, lets leave it blank and gophercloud will
		// use zone "nova" as default
		if len(zones) > 0 {
			availability, err = volumehelpers.SelectZoneForVolume(false, false, "", nil, zones, node, allowedTopologies, c.options.PVC.Name)
			if err != nil {
				klog.V(2).Infof("error selecting zone for volume: %v", err)
				return "", 0, nil, "", err
			}
		}
	}

	volumeID, volumeAZ, volumeRegion, IgnoreVolumeAZ, err := cloud.CreateVolume(name, volSizeGiB, vtype, availability, c.options.CloudTags)
	if err != nil {
		klog.V(2).Infof("Error creating cinder volume: %v", err)
		return "", 0, nil, "", err
	}
	klog.V(2).Infof("Successfully created cinder volume %s", volumeID)

	// these are needed that pod is spawning to same AZ
	volumeLabels = make(map[string]string)
	if IgnoreVolumeAZ == false {
		if volumeAZ != "" {
			volumeLabels[v1.LabelZoneFailureDomain] = volumeAZ
		}
		if volumeRegion != "" {
			volumeLabels[v1.LabelZoneRegion] = volumeRegion
		}
	}
	return volumeID, volSizeGiB, volumeLabels, fstype, nil
}
31653
func (s *oracleVolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) ([]storage.CreateVolumesResult, error) {
	if params == nil {
		return []storage.CreateVolumesResult{}, nil
	}
	results := make([]storage.CreateVolumesResult, len(params))
	for i, volume := range params {
		vol, err := s.createVolume(volume)
		if err != nil {
			results[i].Error = errors.Trace(err)
			continue
		}
		results[i].Volume = vol
	}
	return results, nil
}
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
}
212850
func (s *VolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) ([]storage.CreateVolumesResult, error) {
	s.MethodCall(s, "CreateVolumes", ctx, params)
	if s.CreateVolumesFunc != nil {
		return s.CreateVolumesFunc(ctx, params)
	}
	return nil, errors.NotImplementedf("CreateVolumes")
}
320326
func createVolume(path string, name string) {
	directory := GetDefaultDriver(path)
	driver, err := InitDriverIfExists(directory)
	if err != nil {
		log.Fatal(err)
	}
	logger := log.WithFields(log.Fields{
		"directory": driver.Root(),
		"type":      driver.DriverType(),
		"volume":    name,
	})
	logger.Info("Creating volume")
	vol, err := driver.Create(name)
	if err != nil {
		logger.Fatal(err)
	}
	log.WithFields(log.Fields{
		"mount": vol.Path(),
	}).Info("Volume Mounted")
}
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
}
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})
}
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
}
1273039
func (r *realFS) Create(path string) (io.WriteCloser, error) {
	return os.Create(path)
}
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
}
403221
func (c *Client) CreateVolume(opts CreateVolumeOptions) (*Volume, error) {
	resp, err := c.do("POST", "/volumes/create", doOptions{
		data:    opts,
		context: opts.Context,
	})
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var volume Volume
	if err := json.NewDecoder(resp.Body).Decode(&volume); err != nil {
		return nil, err
	}
	return &volume, nil
}