// addVolumeOps returns txn.Ops to create a new volume with the specified
// parameters. If the supplied host ID is non-empty, and the storage
// provider is machine-scoped, then the volume will be scoped to that
// machine.
778624
func (sb *storageBackend) addVolumeOps(params VolumeParams, hostId string) ([]txn.Op, names.VolumeTag, error) {
	params, err := sb.volumeParamsWithDefaults(params)
	if err != nil {
		return nil, names.VolumeTag{}, errors.Trace(err)
	}
	detachable, err := isDetachableVolumePool(sb, params.Pool)
	if err != nil {
		return nil, names.VolumeTag{}, errors.Trace(err)
	}
	origHostId := hostId
	hostId, err = sb.validateVolumeParams(params, hostId)
	if err != nil {
		return nil, names.VolumeTag{}, errors.Annotate(err, "validating volume params")
	}
	name, err := newVolumeName(sb.mb, hostId)
	if err != nil {
		return nil, names.VolumeTag{}, errors.Annotate(err, "cannot generate volume name")
	}
	statusDoc := statusDoc{
		Status:  status.Pending,
		Updated: sb.mb.clock().Now().UnixNano(),
	}
	doc := volumeDoc{
		Name:      name,
		StorageId: params.storage.Id(),
	}
	if params.volumeInfo != nil {
		// We're importing an already provisioned volume into the
		// model. Set provisioned info rather than params, and set
		// the status to "detached".
		statusDoc.Status = status.Detached
		doc.Info = params.volumeInfo
	} else {
		// Every new volume is created with one attachment.
		doc.Params = &params
		doc.AttachmentCount = 1
	}
	if !detachable {
		doc.HostId = origHostId
	}
	return sb.newVolumeOps(doc, statusDoc), names.NewVolumeTag(name), nil
}
319744
func (s *UpdateLayerInput) SetVolumeConfigurations(v []*VolumeConfiguration) *UpdateLayerInput {
	s.VolumeConfigurations = v
	return s
}
79597
func (c *Host) CreateVolume(providerId string, info *volume.Info) error {
	return c.c.Post(fmt.Sprintf("/storage/providers/%s/volumes", providerId), info, info)
}
481175
func mergeVolumeMounts(volumeMounts []api.VolumeMount, podPresets []*settingsv1alpha1.PodPreset) ([]api.VolumeMount, error) {

	origVolumeMounts := map[string]api.VolumeMount{}
	volumeMountsByPath := map[string]api.VolumeMount{}
	for _, v := range volumeMounts {
		origVolumeMounts[v.Name] = v
		volumeMountsByPath[v.MountPath] = v
	}

	mergedVolumeMounts := make([]api.VolumeMount, len(volumeMounts))
	copy(mergedVolumeMounts, volumeMounts)

	var errs []error

	for _, pp := range podPresets {
		for _, v := range pp.Spec.VolumeMounts {
			internalVolumeMount := api.VolumeMount{}
			if err := apiscorev1.Convert_v1_VolumeMount_To_core_VolumeMount(&v, &internalVolumeMount, nil); err != nil {
				return nil, err
			}
			found, ok := origVolumeMounts[v.Name]
			if !ok {
				// if we don't already have it append it and continue
				origVolumeMounts[v.Name] = internalVolumeMount
				mergedVolumeMounts = append(mergedVolumeMounts, internalVolumeMount)
			} else {
				// make sure they are identical or throw an error
				// shall we throw an error for identical volumeMounts ?
				if !reflect.DeepEqual(found, internalVolumeMount) {
					errs = append(errs, fmt.Errorf("merging volume mounts for %s has a conflict on %s: \n%#v\ndoes not match\n%#v\n in container", pp.GetName(), v.Name, v, found))
				}
			}

			found, ok = volumeMountsByPath[v.MountPath]
			if !ok {
				// if we don't already have it append it and continue
				volumeMountsByPath[v.MountPath] = internalVolumeMount
			} else {
				// make sure they are identical or throw an error
				if !reflect.DeepEqual(found, internalVolumeMount) {
					errs = append(errs, fmt.Errorf("merging volume mounts for %s has a conflict on mount path %s: \n%#v\ndoes not match\n%#v\n in container", pp.GetName(), v.MountPath, v, found))
				}
			}
		}
	}

	err := utilerrors.NewAggregate(errs)
	if err != nil {
		return nil, err
	}

	return mergedVolumeMounts, err
}
1216335
func mirrorVolumeMounts(sourceContainer, targetContainer *apiv1.Container) {
	for _, volMnt := range sourceContainer.VolumeMounts {
		if targetContainer.VolumeMounts == nil {
			targetContainer.VolumeMounts = make([]apiv1.VolumeMount, 0)
		}
		log.Debugf("Adding volume mount %v to container %v", volMnt.Name, targetContainer.Name)
		targetContainer.VolumeMounts = append(targetContainer.VolumeMounts, volMnt)

	}
}
698290
func (c *Client) ListVolumes(opts ListVolumesOptions) ([]Volume, error) {
	resp, err := c.do("GET", "/volumes?"+queryString(opts), doOptions{
		context: opts.Context,
	})
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	m := make(map[string]interface{})
	if err = json.NewDecoder(resp.Body).Decode(&m); err != nil {
		return nil, err
	}
	var volumes []Volume
	volumesJSON, ok := m["Volumes"]
	if !ok {
		return volumes, nil
	}
	data, err := json.Marshal(volumesJSON)
	if err != nil {
		return nil, err
	}
	if err := json.Unmarshal(data, &volumes); err != nil {
		return nil, err
	}
	return volumes, nil
}
1260138
func (s *oracleVolumeSource) createVolume(p storage.VolumeParams) (_ *storage.Volume, err error) {
	var details ociResponse.StorageVolume
	defer func() {
		// gsamfira: not really sure if this is needed. The only relevant error
		// on which we act is the one returned by the oracle API when creating
		// the volume. If the API returned an error, there is little chance, that
		// a volume was created. But for the sake of thoroughness, let's leave this
		// here
		if err != nil && details.Name != "" {
			_ = s.api.DeleteStorageVolume(details.Name)
		}
	}()

	// validate the parameters
	if err := s.ValidateVolumeParams(p); err != nil {
		return nil, errors.Trace(err)
	}
	name := s.resourceName(p.Tag.String())
	size := mibToGib(p.Size)
	if size > maxVolumeSizeInGB || size < minVolumeSizeInGB {
		return nil, errors.Errorf("invalid size for volume: %d", size)
	}

	poolType, err := s.getStoragePool(p.Attributes)
	if err != nil {
		return nil, errors.Trace(err)
	}
	volumeTags := []string{p.Tag.String()}
	for k, v := range p.ResourceTags {
		volumeTags = append(volumeTags, fmt.Sprintf("%s=%s", k, v))
	}

	params := oci.StorageVolumeParams{
		Bootable:    false,
		Description: fmt.Sprintf("Juju created volume for %q", p.Tag.String()),
		Name:        name,
		Properties: []ociCommon.StoragePool{
			poolType,
		},
		Size: ociCommon.NewStorageSize(size, ociCommon.G),
		Tags: volumeTags,
	}
	logger.Infof("creating volume: %v", params)
	details, err = s.api.CreateStorageVolume(params)
	if oci.IsStatusConflict(err) {
		// Volume already exists, so return its details.
		conflictErr := err
		details, err = s.api.StorageVolumeDetails(name)
		if err != nil {
			return nil, errors.Trace(err)
		}
		var modelTagValue string
		for _, tag := range details.Tags {
			prefix := tags.JujuModel + "="
			if !strings.HasPrefix(tag, prefix) {
				continue
			}
			modelTagValue = tag[len(prefix):]
		}
		if modelTagValue != s.modelUUID {
			return nil, errors.Trace(conflictErr)
		}
		return &storage.Volume{p.Tag, makeVolumeInfo(details)}, nil
	} else if err != nil {
		return nil, errors.Trace(err)
	}

	// wait for the newly created volume to reach "Online" status
	logger.Debugf("waiting for resource %v", details.Name)
	if err := s.waitForResourceStatus(
		s.fetchVolumeStatus,
		details.Name,
		string(ociCommon.VolumeOnline), 5*time.Minute); err != nil {
		return nil, errors.Trace(err)
	}
	volume := &storage.Volume{p.Tag, makeVolumeInfo(details)}
	logger.Debugf("volume details: %v", volume)
	return volume, nil
}
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")
}
218072
func (s *VolumeService) NewUpdateVolumeParams() *UpdateVolumeParams {
	p := &UpdateVolumeParams{}
	p.p = make(map[string]interface{})
	return p
}
1074792
func (v *volumeSource) AttachVolumes(ctx context.ProviderCallContext, attachParams []storage.VolumeAttachmentParams) ([]storage.AttachVolumesResult, error) {
	// noop
	return nil, nil
}
416072
func (v *ebsVolumeSource) ReleaseVolumes(ctx context.ProviderCallContext, volIds []string) ([]error, error) {
	return foreachVolume(v.env.ec2, ctx, volIds, releaseVolume), nil
}
205391
func (v *version) PersistentVolumes() PersistentVolumeInformer {
	return &persistentVolumeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}
}
153346
func (v *volumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) (_ []storage.CreateVolumesResult, err error) {
	// noop
	return nil, nil
}
1367244
func addUnitOps(st *State, args addUnitOpsArgs) ([]txn.Op, error) {
	name := args.unitDoc.Name
	agentGlobalKey := unitAgentGlobalKey(name)

	// TODO: consider the constraints op
	// TODO: consider storageOps
	var prereqOps []txn.Op
	if args.containerDoc != nil {
		prereqOps = append(prereqOps, txn.Op{
			C:      cloudContainersC,
			Id:     args.containerDoc.Id,
			Insert: args.containerDoc,
			Assert: txn.DocMissing,
		})
	}
	prereqOps = append(prereqOps,
		createStatusOp(st, agentGlobalKey, args.agentStatusDoc),
		createStatusOp(st, unitGlobalKey(name), *args.workloadStatusDoc),
		createMeterStatusOp(st, agentGlobalKey, args.meterStatusDoc),
		createStatusOp(st, globalWorkloadVersionKey(name), *args.workloadVersionDoc),
	)

	// Freshly-created units will not have a charm URL set; migrated
	// ones will, and they need to maintain their refcounts. If we
	// relax the restrictions on migrating apps mid-upgrade, this
	// will need to be more sophisticated, because it might need to
	// create the settings doc.
	if curl := args.unitDoc.CharmURL; curl != nil {
		appName := args.unitDoc.Application
		charmRefOps, err := appCharmIncRefOps(st, appName, curl, false)
		if err != nil {
			return nil, errors.Trace(err)
		}
		prereqOps = append(prereqOps, charmRefOps...)
	}

	return append(prereqOps, txn.Op{
		C:      unitsC,
		Id:     name,
		Assert: txn.DocMissing,
		Insert: args.unitDoc,
	}), nil
}
912431
func addOrgs(stub shim.ChaincodeStubInterface) pb.Response {
	_, parameters := stub.GetFunctionAndParameters()
	if len(parameters) < 2 {
		return shim.Error("No orgs to add specified")
	}

	// get the endorsement policy for the key
	var epBytes []byte
	var err error
	if parameters[0] == "pub" {
		epBytes, err = stub.GetStateValidationParameter("pub")
	} else if parameters[0] == "priv" {
		epBytes, err = stub.GetPrivateDataValidationParameter("col", "priv")
	} else {
		return shim.Error("Unknown key specified")
	}
	if err != nil {
		return shim.Error(err.Error())
	}
	ep, err := statebased.NewStateEP(epBytes)
	if err != nil {
		return shim.Error(err.Error())
	}

	// add organizations to endorsement policy
	err = ep.AddOrgs(statebased.RoleTypePeer, parameters[1:]...)
	if err != nil {
		return shim.Error(err.Error())
	}
	epBytes, err = ep.Policy()
	if err != nil {
		return shim.Error(err.Error())
	}

	// set the modified endorsement policy for the key
	if parameters[0] == "pub" {
		err = stub.SetStateValidationParameter("pub", epBytes)
	} else if parameters[0] == "priv" {
		err = stub.SetPrivateDataValidationParameter("col", "priv", epBytes)
	}
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success([]byte{})
}
331344
func (ev *ExternalVolume) AddOption(name, value string) *ExternalVolume {
	if ev.Options == nil {
		ev.EmptyOptions()
	}
	(*ev.Options)[name] = value

	return ev
}
669316
func (v *azureVolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) (_ []storage.CreateVolumesResult, err error) {
	results := make([]storage.CreateVolumesResult, len(params))
	for i, p := range params {
		if err := v.ValidateVolumeParams(p); err != nil {
			results[i].Error = err
			continue
		}
	}
	if v.maybeStorageClient == nil {
		v.createManagedDiskVolumes(ctx, params, results)
		return results, nil
	}
	return results, v.createUnmanagedDiskVolumes(ctx, params, results)
}