// VolumeCreate creates a new volume.
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,
	})
}
378688
func (d *driver) createVolume(
	ctx types.Context,
	volumeName, snapshotID string,
	opts *types.VolumeCreateOpts) (*awsec2.Volume, error) {

	var (
		encryption bool
		kmsKeyID   string
	)

	if opts.Encrypted != nil && *opts.Encrypted {
		encryption = true
		if opts.EncryptionKey != nil && len(*opts.EncryptionKey) > 0 {
			ctx.Debug("creating encrypted volume w client enc key")
			kmsKeyID = *opts.EncryptionKey
		} else if len(d.kmsKeyID) > 0 {
			ctx.Debug("creating encrypted volume w server enc key")
			kmsKeyID = *aws.String(d.kmsKeyID)
		} else {
			ctx.Debug("creating encrypted volume w default enc key")
		}
	}

	var resp *awsec2.Volume

	_, err := fcagent.CreateVol(volumeName, int(*opts.Size), encryption, kmsKeyID)
	if err != nil {
		return &awsec2.Volume{}, goof.WithError(
			"error creating FittedCloud volume", err)
	}
	ec2vols, err1 := d.getVolume(ctx, "", volumeName)
	if err1 != nil {
		return &awsec2.Volume{}, goof.WithError(
			"error getting volume", err1)
	}
	resp = ec2vols[0]

	return resp, nil
}
530481
func NewVolume(
	volumeID string,
	fsType api.FSType,
	volumeLocator *api.VolumeLocator,
	source *api.Source,
	volumeSpec *api.VolumeSpec,
) *api.Volume {
	return &api.Volume{
		Id:       volumeID,
		Locator:  volumeLocator,
		Ctime:    prototime.Now(),
		Spec:     volumeSpec,
		Source:   source,
		LastScan: prototime.Now(),
		Format:   fsType,
		State:    api.VolumeState_VOLUME_STATE_AVAILABLE,
		Status:   api.VolumeStatus_VOLUME_STATUS_UP,
	}
}
1153428
func VolumeChange(listener func(*vecty.Event)) *vecty.EventListener {
	return &vecty.EventListener{Name: "volumechange", Listener: listener}
}
1116013
func (v *azureVolumeSource) createManagedDiskVolume(ctx context.ProviderCallContext, p storage.VolumeParams) (*storage.Volume, error) {
	cfg, err := newAzureStorageConfig(p.Attributes)
	if err != nil {
		return nil, errors.Trace(err)
	}

	diskTags := make(map[string]*string)
	for k, v := range p.ResourceTags {
		diskTags[k] = to.StringPtr(v)
	}
	diskName := p.Tag.String()
	sizeInGib := mibToGib(p.Size)
	diskModel := compute.Disk{
		Name:     to.StringPtr(diskName),
		Location: to.StringPtr(v.env.location),
		Tags:     diskTags,
		Sku: &compute.DiskSku{
			Name: cfg.storageType,
		},
		DiskProperties: &compute.DiskProperties{
			CreationData: &compute.CreationData{CreateOption: compute.Empty},
			DiskSizeGB:   to.Int32Ptr(int32(sizeInGib)),
		},
	}

	diskClient := compute.DisksClient{v.env.disk}
	sdkCtx := stdcontext.Background()
	future, err := diskClient.CreateOrUpdate(sdkCtx, v.env.resourceGroup, diskName, diskModel)
	if err != nil {
		return nil, errorutils.HandleCredentialError(errors.Annotatef(err, "creating disk for volume %q", p.Tag.Id()), ctx)
	}
	err = future.WaitForCompletionRef(sdkCtx, diskClient.Client)
	if err != nil {
		return nil, errorutils.HandleCredentialError(errors.Annotatef(err, "creating disk for volume %q", p.Tag.Id()), ctx)
	}
	result, err := future.Result(diskClient)
	if err != nil && !isNotFoundResult(result.Response) {
		return nil, errors.Annotatef(err, "creating disk for volume %q", p.Tag.Id())
	}

	volume := storage.Volume{
		p.Tag,
		storage.VolumeInfo{
			VolumeId:   diskName,
			Size:       gibToMib(uint64(to.Int32(result.DiskSizeGB))),
			Persistent: true,
		},
	}
	return &volume, nil
}
278438
func (m *MockCommonAPIClient) VolumeCreate(ctx context.Context, options volume.VolumesCreateBody) (types.Volume, error) {
	ret := m.ctrl.Call(m, "VolumeCreate", ctx, options)
	ret0, _ := ret[0].(types.Volume)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
909735
func (c *Client) CreateVolumeDir(
	ctx context.Context,
	volumeName, dirPath string,
	fileMode os.FileMode,
	overwrite, recursive bool) error {

	return apiv2.ContainerCreateDir(
		ctx, c.API, volumeName, dirPath,
		apiv2.FileMode(fileMode), overwrite, recursive)
}
101674
func (m *Manager) NewVolume(info *volume.Info) (volume.Volume, error) {
	return m.NewVolumeFromProvider("default", info)
}
638472
func NewVolumeDriver(name string, baseDirPath string, provider Provider) volume.VolumeDriver {
	return newVolumeDriver(name, baseDirPath, provider)
}
800501
func (mr *MockVolumeAPIClientMockRecorder) VolumeCreate(ctx, options interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VolumeCreate", reflect.TypeOf((*MockVolumeAPIClient)(nil).VolumeCreate), ctx, options)
}
1134268
func httpCreateVolume(w http.ResponseWriter, r *http.Request, vars map[string]string) (interface{}, error) {
	log.Debugf("Received httpGetVolume: %+v", vars)

	var obj Volume
	key := vars["key"]

	// Get object from the request
	err := json.NewDecoder(r.Body).Decode(&obj)
	if err != nil {
		log.Errorf("Error decoding volume create request. Err %v", err)
		return nil, err
	}

	// set the key
	obj.Key = key

	// Create the object
	err = CreateVolume(&obj)
	if err != nil {
		log.Errorf("CreateVolume error for: %+v. Err: %v", obj, err)
		return nil, err
	}

	// Return the obj
	return obj, nil
}
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
}
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
}
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,
		},
	)
}
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
}
1129167
func createVolumes(ctx *context, ops map[names.VolumeTag]*createVolumeOp) error {
	volumeParams := make([]storage.VolumeParams, 0, len(ops))
	for _, op := range ops {
		volumeParams = append(volumeParams, op.args)
	}
	paramsBySource, volumeSources, err := volumeParamsBySource(
		ctx.config.StorageDir, volumeParams, ctx.config.Registry,
	)
	if err != nil {
		return errors.Trace(err)
	}
	var reschedule []scheduleOp
	var volumes []storage.Volume
	var volumeAttachments []storage.VolumeAttachment
	var statuses []params.EntityStatusArgs
	for sourceName, volumeParams := range paramsBySource {
		logger.Debugf("creating volumes: %v", volumeParams)
		volumeSource := volumeSources[sourceName]
		validVolumeParams, validationErrors := validateVolumeParams(volumeSource, volumeParams)
		for i, err := range validationErrors {
			if err == nil {
				continue
			}
			statuses = append(statuses, params.EntityStatusArgs{
				Tag:    volumeParams[i].Tag.String(),
				Status: status.Error.String(),
				Info:   err.Error(),
			})
			logger.Debugf(
				"failed to validate parameters for %s: %v",
				names.ReadableString(volumeParams[i].Tag), err,
			)
		}
		volumeParams = validVolumeParams
		if len(volumeParams) == 0 {
			continue
		}
		results, err := volumeSource.CreateVolumes(ctx.config.CloudCallContext, volumeParams)
		if err != nil {
			return errors.Annotatef(err, "creating volumes from source %q", sourceName)
		}
		for i, result := range results {
			statuses = append(statuses, params.EntityStatusArgs{
				Tag:    volumeParams[i].Tag.String(),
				Status: status.Attaching.String(),
			})
			entityStatus := &statuses[len(statuses)-1]
			if result.Error != nil {
				// Reschedule the volume creation.
				reschedule = append(reschedule, ops[volumeParams[i].Tag])

				// Note: we keep the status as "pending" to indicate
				// that we will retry. When we distinguish between
				// transient and permanent errors, we will set the
				// status to "error" for permanent errors.
				entityStatus.Status = status.Pending.String()
				entityStatus.Info = result.Error.Error()
				logger.Debugf(
					"failed to create %s: %v",
					names.ReadableString(volumeParams[i].Tag),
					result.Error,
				)
				continue
			}
			volumes = append(volumes, *result.Volume)
			if result.VolumeAttachment != nil {
				entityStatus.Status = status.Attached.String()
				volumeAttachments = append(volumeAttachments, *result.VolumeAttachment)
			}
		}
	}
	scheduleOperations(ctx, reschedule...)
	setStatus(ctx, statuses)
	if len(volumes) == 0 {
		return nil
	}
	// TODO(axw) we need to be able to list volumes in the provider,
	// by environment, so that we can "harvest" them if they're
	// unknown. This will take care of killing volumes that we fail
	// to record in state.
	errorResults, err := ctx.config.Volumes.SetVolumeInfo(volumesFromStorage(volumes))
	if err != nil {
		return errors.Annotate(err, "publishing volumes to state")
	}
	for i, result := range errorResults {
		if result.Error != nil {
			logger.Errorf(
				"publishing volume %s to state: %v",
				volumes[i].Tag.Id(),
				result.Error,
			)
		}
	}
	for _, v := range volumes {
		updateVolume(ctx, v)
	}
	// Note: the storage provisioner that creates a volume is also
	// responsible for creating the volume attachment. It is therefore
	// safe to set the volume attachment info after the volume info,
	// without leading to the possibility of concurrent, duplicate
	// attachments.
	err = setVolumeAttachmentInfo(ctx, volumeAttachments)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
893521
func (v *volumeClient) CredsCreate(params map[string]string) (string, error) {
	createResponse := api.CredCreateResponse{}
	request := &api.CredCreateRequest{
		InputParams: params,
	}
	req := v.c.Post().Resource(api.OsdCredsPath).Body(request)
	response := req.Do()
	if response.Error() != nil {
		return "", response.FormatError()
	}
	if err := response.Unmarshal(&createResponse); err != nil {
		return "", err
	}
	return createResponse.UUID, nil
}