// CreateIsiVolume makes a new volume on the cluster
492496
func CreateIsiVolume(
	ctx context.Context,
	client api.Client,
	name string) (resp *getIsiVolumesResp, err error) {

	// PAPI calls: PUT https://1.2.3.4:8080/namespace/path/to/volumes/volume_name
	//             x-isi-ifs-target-type: container
	//             x-isi-ifs-access-control: public_read_write
	//
	//             PUT https://1.2.3.4:8080/namespace/path/to/volumes/volume_name?acl
	//             {authoritative: "acl",
	//              action: "update",
	//              owner: {name: "username", type: "user"},
	//              group: {name: "groupname", type: "group"}
	//             }

	// create the volume
	err = client.Put(
		ctx,
		realNamespacePath(client),
		name,
		nil,
		createVolumeHeaders,
		nil,
		&resp)

	if err != nil {
		return resp, err
	}

	var data = &AclRequest{
		"acl",
		"update",
		&Ownership{client.User(), "user"},
		nil,
	}

	if group := client.Group(); group != "" {
		data.Group = &Ownership{group, "group"}
	}

	// set the ownership of the volume
	err = client.Put(
		ctx,
		realNamespacePath(client),
		name,
		aclQS,
		nil,
		data,
		&resp)

	return resp, err
}
94262
func (d *driver) Create(
	locator *api.VolumeLocator,
	source *api.Source,
	spec *api.VolumeSpec) (string, error) {

	if spec.Size == 0 {
		return "", fmt.Errorf("Volume size cannot be zero")
	} else if spec.GetHaLevel() == 0 {
		return "", fmt.Errorf("HA level cannot be zero")
	}

	volumeID := strings.TrimSuffix(uuid.New(), "\n")

	if _, err := d.GetVol(volumeID); err == nil {
		return "", fmt.Errorf("volume with that id already exists")
	}

	// snapshot passes nil volumelabels
	if locator.VolumeLabels == nil {
		locator.VolumeLabels = make(map[string]string)
	}

	v := common.NewVolume(
		volumeID,
		api.FSType_FS_TYPE_XFS,
		locator,
		source,
		spec,
	)

	if err := d.CreateVol(v); err != nil {
		return "", err
	}
	return v.Id, nil
}
80296
func (e *defaultStoreEnumerator) CreateVol(vol *api.Volume) error {
	_, err := e.kvdb.Create(e.volKey(vol.Id), vol, 0)
	return err
}
829007
func (virtualDisk *VirtualDisk) Create(ctx context.Context, datastore *vclib.Datastore) (string, error) {
	if virtualDisk.VolumeOptions.DiskFormat == "" {
		virtualDisk.VolumeOptions.DiskFormat = vclib.ThinDiskType
	}
	if !virtualDisk.VolumeOptions.VerifyVolumeOptions() {
		klog.Error("VolumeOptions verification failed. volumeOptions: ", virtualDisk.VolumeOptions)
		return "", vclib.ErrInvalidVolumeOptions
	}
	if virtualDisk.VolumeOptions.StoragePolicyID != "" && virtualDisk.VolumeOptions.StoragePolicyName != "" {
		return "", fmt.Errorf("Storage Policy ID and Storage Policy Name both set, Please set only one parameter")
	}
	return getDiskManager(virtualDisk, VirtualDiskCreateOperation).Create(ctx, datastore)
}
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})
}
582402
func (os *OpenStack) CreateVolume(name string, size int, vtype, availability, snapshotID string, tags *map[string]string) (string, string, error) {
	volumes, err := os.volumeService("")
	if err != nil || volumes == nil {
		glog.Errorf("Unable to initialize cinder client for region: %s", os.region)
		return "", "", err
	}

	opts := VolumeCreateOpts{
		Name:             name,
		Size:             size,
		VolumeType:       vtype,
		Availability:     availability,
		SourceSnapshotID: snapshotID,
	}
	if tags != nil {
		opts.Metadata = *tags
	}

	volumeID, volumeAZ, err := volumes.createVolume(opts)

	if err != nil {
		glog.Errorf("Failed to create a %d GB volume: %v", size, err)
		return "", "", err
	}

	glog.Infof("Created volume %v in Availability Zone: %v", volumeID, volumeAZ)
	return volumeID, volumeAZ, nil
}
15164
func (d *driver) VolumeCreate(ctx types.Context, volumeName string,
	opts *types.VolumeCreateOpts) (*types.Volume, error) {
	// Initialize for logging
	fields := map[string]interface{}{
		"driverName": d.Name(),
		"volumeName": volumeName,
		"opts":       opts,
	}

	ctx.WithFields(fields).Debug("creating volume")

	if opts.Size == nil {
		size := int64(minSizeGiB)
		opts.Size = &size
	}

	fields["size"] = *opts.Size

	if *opts.Size < minSizeGiB {
		fields["minSize"] = minSizeGiB
		return nil, goof.WithFields(fields, "volume size too small")
	}

	// Check if volume with same name exists
	ec2vols, err := d.getVolume(ctx, "", volumeName)
	if err != nil {
		return nil, goof.WithFieldsE(fields, "error getting volume", err)
	}
	volumes, convErr := d.toTypesVolume(ctx, ec2vols, 0)
	if convErr != nil {
		return nil, goof.WithFieldsE(
			fields, "error converting to types.Volume", convErr)
	}

	if len(volumes) > 0 {
		return nil, goof.WithFields(fields, "volume name already exists")
	}

	// Pass libStorage types.Volume to helper function which calls EC2 API
	vol, err := d.createVolume(ctx, volumeName, "", opts)
	if err != nil {
		return nil, goof.WithFieldsE(fields, "error creating volume", err)
	}

	// Return the volume created
	return d.VolumeInspect(ctx, *vol.VolumeId, &types.VolumeInspectOpts{
		Attachments: types.VolAttReqTrue,
	})
}
1272307
func (d *DeviceMapperDriver) Create(volumeName string) (volume.Volume, error) {
	glog.V(2).Infof("Create() (%s) START", volumeName)
	defer glog.V(2).Infof("Create() (%s) END", volumeName)

	// Do not create if the device already exists
	if d.Exists(volumeName) {
		return nil, volume.ErrVolumeExists
	}

	// Create a new device
	deviceHash, err := d.addDevice("")
	if err != nil {
		return nil, err
	}
	glog.V(1).Infof("Allocated new device %s", deviceHash)

	// Create the mount target directory if it doesn't exist
	mountpoint := d.volumeDir(volumeName)
	if err := os.MkdirAll(mountpoint, 0755); err != nil && !os.IsExist(err) {
		return nil, err
	}
	glog.V(1).Infof("Ensured existence of mount point %s", mountpoint)

	// Create the metadata directory if it doesn't exist.
	md := d.MetadataDir()
	if err := os.MkdirAll(md, 0755); err != nil && !os.IsExist(err) {
		return nil, err
	}
	glog.V(1).Infof("Ensured existence of metadata dir %s", md)

	// Instantiate the volume
	vol, err := d.getVolume(volumeName, true)
	if err != nil {
		return nil, err
	}

	// Set the device as HEAD
	if err := vol.Metadata.SetCurrentDevice(deviceHash); err != nil {
		return nil, err
	}
	glog.V(1).Infof("Set current device to %s", deviceHash)

	// Mount the device
	if err := d.DeviceSet.MountDevice(deviceHash, mountpoint, volumeName); err != nil {
		return nil, err
	}
	glog.V(1).Infof("Mounted device %s to %s", deviceHash, mountpoint)

	return vol, nil
}
817606
func (c *Client) DeleteVolume(
	ctx context.Context, name string) error {
	_, err := apiv1.DeleteIsiVolume(ctx, c.API, name)
	return err
}
585236
func (d *driver) VolumeCreate(
	ctx types.Context,
	volumeName string,
	opts *types.VolumeCreateOpts) (*types.Volume, error) {

	fields := map[string]interface{}{
		"driverName": d.Name(),
		"volumeName": volumeName,
		"opts":       opts,
	}

	zone, err := d.validZone(ctx)
	if err != nil {
		return nil, err
	}

	// No zone information from request, driver, or IID
	if (zone == nil || *zone == "") && (opts.AvailabilityZone == nil || *opts.AvailabilityZone == "") {
		return nil, goof.New("Zone is required for VolumeCreate")
	}

	if zone != nil && *zone != "" {
		if opts.AvailabilityZone != nil && *opts.AvailabilityZone != "" {
			// If request and driver/IID have zone, they must match
			if *zone != *opts.AvailabilityZone {
				return nil, goof.WithFields(fields,
					"Cannot create volume in given zone")
			}
		} else {
			// Set the zone to the driver/IID config
			opts.AvailabilityZone = zone
		}

	}

	volumeName = d.convUnderscores(volumeName)
	fields["volumeName"] = volumeName
	if !utils.IsValidDiskName(&volumeName) {
		return nil, goof.WithFields(fields,
			"Volume name does not meet GCE naming requirements")
	}

	if opts.Size == nil {
		size := int64(minDiskSizeGB)
		opts.Size = &size
	}

	fields["size"] = *opts.Size

	if *opts.Size < minDiskSizeGB {
		fields["minSize"] = minDiskSizeGB
		return nil, goof.WithFields(fields, "volume size too small")
	}

	ctx.WithFields(fields).Debug("creating volume")

	// Check if volume with same name exists
	gceDisk, err := d.getDisk(ctx, opts.AvailabilityZone, &volumeName)
	if err != nil {
		return nil, goof.WithFieldsE(fields,
			"error querying for existing volume", err)
	}
	if gceDisk != nil {
		return nil, goof.WithFields(fields,
			"volume name already exists")
	}

	err = d.createVolume(ctx, &volumeName, opts)
	if err != nil {
		return nil, goof.WithFieldsE(
			fields, "error creating volume", err)
	}

	// Return the volume created
	return d.VolumeInspect(ctx, volumeName,
		&types.VolumeInspectOpts{
			Attachments: types.VolAttNone,
		},
	)
}
539047
func (c *Cloud) CreateDisk(volumeOptions *VolumeOptions) (KubernetesVolumeID, error) {
	allZones, err := c.getCandidateZonesForDynamicVolume()
	if err != nil {
		return "", fmt.Errorf("error querying for all zones: %v", err)
	}

	createAZ := volumeOptions.AvailabilityZone
	if createAZ == "" {
		createAZ = util.ChooseZoneForVolume(allZones, volumeOptions.PVCName)
	}

	var createType string
	var iops int64
	switch volumeOptions.VolumeType {
	case VolumeTypeGP2, VolumeTypeSC1, VolumeTypeST1:
		createType = volumeOptions.VolumeType

	case VolumeTypeIO1:
		// See http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html
		// for IOPS constraints. AWS will throw an error if IOPS per GB gets out
		// of supported bounds, no need to check it here.
		createType = volumeOptions.VolumeType
		iops = int64(volumeOptions.CapacityGB * volumeOptions.IOPSPerGB)

		// Cap at min/max total IOPS, AWS would throw an error if it gets too
		// low/high.
		if iops < MinTotalIOPS {
			iops = MinTotalIOPS
		}
		if iops > MaxTotalIOPS {
			iops = MaxTotalIOPS
		}

	case "":
		createType = DefaultVolumeType

	default:
		return "", fmt.Errorf("invalid AWS VolumeType %q", volumeOptions.VolumeType)
	}

	// TODO: Should we tag this with the cluster id (so it gets deleted when the cluster does?)
	request := &ec2.CreateVolumeInput{}
	request.AvailabilityZone = aws.String(createAZ)
	request.Size = aws.Int64(int64(volumeOptions.CapacityGB))
	request.VolumeType = aws.String(createType)
	request.Encrypted = aws.Bool(volumeOptions.Encrypted)
	if len(volumeOptions.KmsKeyID) > 0 {
		request.KmsKeyId = aws.String(volumeOptions.KmsKeyID)
		request.Encrypted = aws.Bool(true)
	}
	if iops > 0 {
		request.Iops = aws.Int64(iops)
	}
	if len(volumeOptions.SnapshotID) > 0 {
		request.SnapshotId = aws.String(volumeOptions.SnapshotID)
	}

	response, err := c.ec2.CreateVolume(request)
	if err != nil {
		return "", err
	}

	awsID := awsVolumeID(aws.StringValue(response.VolumeId))
	if awsID == "" {
		return "", fmt.Errorf("VolumeID was not returned by CreateVolume")
	}
	volumeName := KubernetesVolumeID("aws://" + aws.StringValue(response.AvailabilityZone) + "/" + string(awsID))

	// apply tags
	if err := c.tagging.createTags(c.ec2, string(awsID), ResourceLifecycleOwned, volumeOptions.Tags); err != nil {
		// delete the volume and hope it succeeds
		_, delerr := c.DeleteDisk(volumeName)
		if delerr != nil {
			// delete did not succeed, we have a stray volume!
			return "", fmt.Errorf("error tagging volume %s, could not delete the volume: %v", volumeName, delerr)
		}
		return "", fmt.Errorf("error tagging volume %s: %v", volumeName, err)
	}

	return volumeName, nil
}
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})
}
382273
func NewVolume(projectName, name string, config *config.VolumeConfig, client client.VolumeAPIClient) *Volume {
	vol := &Volume{
		client:      client,
		projectName: projectName,
		name:        name,
	}
	if config != nil {
		vol.driver = config.Driver
		vol.driverOptions = config.DriverOpts
		vol.external = config.External.External

	}
	return vol
}
171867
func (util *portworxVolumeUtil) CreateVolume(p *portworxVolumeProvisioner) (string, int64, map[string]string, error) {
	driver, err := util.getPortworxDriver(p.plugin.host)
	if err != nil || driver == nil {
		klog.Errorf("Failed to get portworx driver. Err: %v", err)
		return "", 0, nil, err
	}

	klog.Infof("Creating Portworx volume for PVC: %v", p.options.PVC.Name)

	capacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
	// Portworx Volumes are specified in GiB
	requestGiB := volumehelpers.RoundUpToGiB(capacity)

	// Perform a best-effort parsing of parameters. Portworx 1.2.9 and later parses volume parameters from
	// spec.VolumeLabels. So even if below SpecFromOpts() fails to parse certain parameters or
	// doesn't support new parameters, the server-side processing will parse it correctly.
	// We still need to call SpecFromOpts() here to handle cases where someone is running Portworx 1.2.8 and lower.
	specHandler := osdspec.NewSpecHandler()
	spec, locator, source, _ := specHandler.SpecFromOpts(p.options.Parameters)
	if spec == nil {
		spec = specHandler.DefaultSpec()
	}

	// Pass all parameters as volume labels for Portworx server-side processing
	if spec.VolumeLabels == nil {
		spec.VolumeLabels = make(map[string]string, 0)
	}

	for k, v := range p.options.Parameters {
		spec.VolumeLabels[k] = v
	}

	// Update the requested size in the spec
	spec.Size = uint64(requestGiB * volumehelpers.GiB)

	// Change the Portworx Volume name to PV name
	if locator == nil {
		locator = &osdapi.VolumeLocator{
			VolumeLabels: make(map[string]string),
		}
	}
	locator.Name = p.options.PVName

	// Add claim Name as a part of Portworx Volume Labels
	locator.VolumeLabels[pvcClaimLabel] = p.options.PVC.Name
	locator.VolumeLabels[pvcNamespaceLabel] = p.options.PVC.Namespace

	for k, v := range p.options.PVC.Annotations {
		if _, present := spec.VolumeLabels[k]; present {
			klog.Warningf("not saving annotation: %s=%s in spec labels due to an existing key", k, v)
			continue
		}
		spec.VolumeLabels[k] = v
	}

	volumeID, err := driver.Create(locator, source, spec)
	if err != nil {
		klog.Errorf("Error creating Portworx Volume : %v", err)
		return "", 0, nil, err
	}

	klog.Infof("Successfully created Portworx volume for PVC: %v", p.options.PVC.Name)
	return volumeID, requestGiB, nil, err
}
307677
func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error) {
	if err := r.validateName(name); err != nil {
		return nil, err
	}

	r.m.Lock()
	defer r.m.Unlock()

	v, exists := r.volumes[name]
	if exists {
		return v, nil
	}

	path := r.DataPath(name)
	if err := idtools.MkdirAllAndChown(path, 0755, r.rootIdentity); err != nil {
		return nil, errors.Wrapf(errdefs.System(err), "error while creating volume path '%s'", path)
	}

	var err error
	defer func() {
		if err != nil {
			os.RemoveAll(filepath.Dir(path))
		}
	}()

	v = &localVolume{
		driverName: r.Name(),
		name:       name,
		path:       path,
	}

	if len(opts) != 0 {
		if err = setOpts(v, opts); err != nil {
			return nil, err
		}
		var b []byte
		b, err = json.Marshal(v.opts)
		if err != nil {
			return nil, err
		}
		if err = ioutil.WriteFile(filepath.Join(filepath.Dir(path), "opts.json"), b, 600); err != nil {
			return nil, errdefs.System(errors.Wrap(err, "error while persisting volume options"))
		}
	}

	r.volumes[name] = v
	return v, nil
}
1152355
func (os *OpenStack) CreateVolume(name string, size int, vtype, availability string, tags *map[string]string) (string, string, string, bool, error) {
	volumes, err := os.volumeService("")
	if err != nil {
		return "", "", "", os.bsOpts.IgnoreVolumeAZ, fmt.Errorf("unable to initialize cinder client for region: %s, err: %v", os.region, err)
	}

	opts := volumeCreateOpts{
		Name:         name,
		Size:         size,
		VolumeType:   vtype,
		Availability: availability,
	}
	if tags != nil {
		opts.Metadata = *tags
	}

	volumeID, volumeAZ, err := volumes.createVolume(opts)

	if err != nil {
		return "", "", "", os.bsOpts.IgnoreVolumeAZ, fmt.Errorf("failed to create a %d GB volume: %v", size, err)
	}

	klog.Infof("Created volume %v in Availability Zone: %v Region: %v Ignore volume AZ: %v", volumeID, volumeAZ, os.region, os.bsOpts.IgnoreVolumeAZ)
	return volumeID, volumeAZ, os.region, os.bsOpts.IgnoreVolumeAZ, 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
}