// CreateSharedVolumesPath ensures the sharedVolumePath for the pod root passed
// in exists. It returns the shared volume path or an error.
195362
func CreateSharedVolumesPath(root string) (string, error) {
	sharedVolPath := SharedVolumesPath(root)

	if err := os.MkdirAll(sharedVolPath, SharedVolumePerm); err != nil {
		return "", errwrap.Wrap(errors.New("could not create shared volumes directory"), err)
	}
	// In case it already existed and we didn't make it, ensure permissions are
	// what the caller expects them to be.
	if err := os.Chmod(sharedVolPath, SharedVolumePerm); err != nil {
		return "", errwrap.Wrap(fmt.Errorf("could not change permissions of %q", sharedVolPath), err)
	}

	return sharedVolPath, nil
}
1153561
func (v *ebsVolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) (_ []storage.CreateVolumesResult, err error) {

	// First, validate the params before we use them.
	results := make([]storage.CreateVolumesResult, len(params))
	instanceIds := set.NewStrings()
	for i, p := range params {
		if err := v.ValidateVolumeParams(p); err != nil {
			results[i].Error = err
			continue
		}
		instanceIds.Add(string(p.Attachment.InstanceId))
	}

	instances := make(instanceCache)
	if instanceIds.Size() > 1 {
		if err := instances.update(v.env.ec2, ctx, instanceIds.Values()...); err != nil {
			err := maybeConvertCredentialError(err, ctx)
			logger.Debugf("querying running instances: %v", err)
			// We ignore the error, because we don't want an invalid
			// InstanceId reference from one VolumeParams to prevent
			// the creation of another volume.
			// Except if it is a credential error...
			if common.IsCredentialNotValid(err) {
				return nil, errors.Trace(err)
			}
		}
	}

	for i, p := range params {
		if results[i].Error != nil {
			continue
		}
		volume, attachment, err := v.createVolume(ctx, p, instances)
		if err != nil {
			results[i].Error = err
			continue
		}
		results[i].Volume = volume
		results[i].VolumeAttachment = attachment
	}
	return results, nil
}
228050
func (p *glusterBlockProvisioner) createVolume(volSizeInt int, blockVol string, config *provisionerConfig) (*glusterBlockVolume, error) {

	blockRes := &glusterBlockVolume{}
	sizeStr := strconv.Itoa(volSizeInt)
	haCountStr := strconv.Itoa(config.haCount)

	klog.V(2).Infof("create block volume of size %d  and configuration %+v", volSizeInt, config)

	// Possible opModes are gluster-block and heketi:
	switch config.opMode {

	// An experimental/Test Mode:
	case glusterBlockOpmode:

		gBlockCreateErr := p.glusterBlockExecCreate(blockRes, config, sizeStr, haCountStr, blockVol)
		if gBlockCreateErr != nil {
			klog.Errorf("gluster block volume creation failed: %v", gBlockCreateErr)
			return nil, fmt.Errorf("gluster block volume creation failed: %v", gBlockCreateErr)
		}

	case heketiOpmode:
		hBlockCreateErr := p.heketiBlockVolCreate(blockRes, config, volSizeInt, haCountStr, blockVol)
		if hBlockCreateErr != nil {
			klog.Errorf("heketi block volume creation failed: %v", hBlockCreateErr)
			return nil, fmt.Errorf("heketi block volume creation failed: %v", hBlockCreateErr)
		}

	default:
		return nil, fmt.Errorf("error parsing value for 'opmode' for volume plugin %s", provisionerName)
	}
	return blockRes, nil
}
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
}
644479
func NewPodVolume(name, path string) *PodVolume {
	return &PodVolume{
		Name: name,
		Host: path,
	}
}
80361
func (s *posix) CreateFile(volume, path string, fileSize int64, r io.Reader) (err error) {
	if fileSize < -1 {
		return errInvalidArgument
	}
	defer func() {
		if err == errFaultyDisk {
			atomic.AddInt32(&s.ioErrCount, 1)
		}
	}()

	if atomic.LoadInt32(&s.ioErrCount) > maxAllowedIOError {
		return errFaultyDisk
	}

	// Validate if disk is indeed free.
	if err = checkDiskFree(s.diskPath, fileSize); err != nil {
		if isSysErrIO(err) {
			return errFaultyDisk
		}
		return err
	}

	if err = s.checkDiskFound(); err != nil {
		return err
	}

	volumeDir, err := s.getVolDir(volume)
	if err != nil {
		return err
	}
	// Stat a volume entry.
	_, err = os.Stat((volumeDir))
	if err != nil {
		if os.IsNotExist(err) {
			return errVolumeNotFound
		} else if isSysErrIO(err) {
			return errFaultyDisk
		}
		return err
	}

	filePath := pathJoin(volumeDir, path)
	if err = checkPathLength((filePath)); err != nil {
		return err
	}

	// Create top level directories if they don't exist.
	// with mode 0777 mkdir honors system umask.
	if err = mkdirAll(slashpath.Dir(filePath), 0777); err != nil {
		return err
	}

	w, err := disk.OpenFileDirectIO(filePath, os.O_CREATE|os.O_WRONLY|os.O_EXCL|os.O_SYNC, 0666)
	if err != nil {
		switch {
		case os.IsPermission(err):
			return errFileAccessDenied
		case os.IsExist(err):
			return errFileAccessDenied
		case isSysErrIO(err):
			return errFaultyDisk
		default:
			return err
		}
	}
	defer w.Close()

	var e error
	if fileSize > 0 {
		// Allocate needed disk space to append data
		e = Fallocate(int(w.Fd()), 0, fileSize)
	}

	// Ignore errors when Fallocate is not supported in the current system
	if e != nil && !isSysErrNoSys(e) && !isSysErrOpNotSupported(e) {
		switch {
		case isSysErrNoSpace(e):
			err = errDiskFull
		case isSysErrIO(e):
			err = errFaultyDisk
		default:
			// For errors: EBADF, EINTR, EINVAL, ENODEV, EPERM, ESPIPE  and ETXTBSY
			// Appending was failed anyway, returns unexpected error
			err = errUnexpected
		}
		return err
	}

	bufp := s.pool.Get().(*[]byte)
	defer s.pool.Put(bufp)

	buf := *bufp

	// Writes remaining bytes in the buffer.
	writeRemaining := func(w *os.File, buf []byte) (remainingWritten int, err error) {
		var n int
		remaining := len(buf)
		// The following logic writes the remainging data such that it writes whatever best is possible (aligned buffer)
		// in O_DIRECT mode and remaining (unaligned buffer) in non-O_DIRECT mode.
		remainingAligned := (remaining / directioAlignSize) * directioAlignSize
		remainingAlignedBuf := buf[:remainingAligned]
		remainingUnalignedBuf := buf[remainingAligned:]
		if len(remainingAlignedBuf) > 0 {
			n, err = w.Write(remainingAlignedBuf)
			if err != nil {
				return 0, err
			}
			remainingWritten += n
		}
		if len(remainingUnalignedBuf) > 0 {
			// Write on O_DIRECT fds fail if buffer is not 4K aligned, hence disable O_DIRECT.
			if err = disk.DisableDirectIO(w); err != nil {
				return 0, err
			}
			n, err = w.Write(remainingUnalignedBuf)
			if err != nil {
				return 0, err
			}
			remainingWritten += n
		}
		return remainingWritten, nil
	}

	var written int
	for {
		var n int
		n, err = io.ReadFull(r, buf)
		switch err {
		case nil:
			n, err = w.Write(buf)
			if err != nil {
				return err
			}
			written += n
		case io.ErrUnexpectedEOF:
			n, err = writeRemaining(w, buf[:n])
			if err != nil {
				return err
			}
			written += n
			fallthrough
		case io.EOF:
			if fileSize != -1 {
				if written < int(fileSize) {
					return errLessData
				}
				if written > int(fileSize) {
					return errMoreData
				}
			}
			return nil
		default:
			return err
		}
	}
}
424655
func makeGlobalPDPath(host volume.VolumeHost, diskUri string, isManaged bool) (string, error) {
	diskUri = libstrings.ToLower(diskUri) // always lower uri because users may enter it in caps.
	uniqueDiskNameTemplate := "%s%s"
	hashedDiskUri := azure.MakeCRC32(diskUri)
	prefix := "b"
	if isManaged {
		prefix = "m"
	}
	// "{m for managed b for blob}{hashed diskUri or DiskId depending on disk kind }"
	diskName := fmt.Sprintf(uniqueDiskNameTemplate, prefix, hashedDiskUri)
	pdPath := filepath.Join(host.GetPluginDir(azureDataDiskPluginName), util.MountsInGlobalPDPath, diskName)

	return pdPath, nil
}
1028826
func (c *FakePersistentVolumeClaims) Create(persistentVolumeClaim *corev1.PersistentVolumeClaim) (result *corev1.PersistentVolumeClaim, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(persistentvolumeclaimsResource, c.ns, persistentVolumeClaim), &corev1.PersistentVolumeClaim{})

	if obj == nil {
		return nil, err
	}
	return obj.(*corev1.PersistentVolumeClaim), err
}
763137
func (d *BtrfsDriver) Create(volumeName string) (volume.Volume, error) {
	d.Lock()
	defer d.Unlock()
	rootDir := d.root
	if _, err := volume.RunBtrFSCmd(d.sudoer, "subvolume", "list", rootDir); err != nil {
		if _, err := volume.RunBtrFSCmd(d.sudoer, "subvolume", "create", rootDir); err != nil {
			glog.Errorf("Could not create subvolume at: %s", rootDir)
			return nil, ErrBtrfsCreatingSubvolume
		}
	}
	vdir := path.Join(rootDir, volumeName)
	if _, err := volume.RunBtrFSCmd(d.sudoer, "subvolume", "list", vdir); err != nil {
		if _, err = volume.RunBtrFSCmd(d.sudoer, "subvolume", "create", vdir); err != nil {
			glog.Errorf("Could not create volume at: %s", vdir)
			return nil, ErrBtrfsCreatingSubvolume
		}
	}
	return d.Get(volumeName)
}
1095290
func (z *zookeeperKV) createFullPath(key string, ephemeral bool) error {
	key = z.domain + normalize(key)
	path := strings.Split(strings.TrimPrefix(key, "/"), "/")

	for i := 1; i <= len(path); i++ {
		newPath := "/" + strings.Join(path[:i], "/")

		if i == len(path) {
			flags := int32(0)
			if ephemeral {
				flags = zk.FlagEphemeral
			}
			_, err := z.client.Create(newPath, []byte{},
				flags, zk.WorldACL(zk.PermAll))
			return err
		}

		_, err := z.client.Create(newPath, []byte{},
			0, zk.WorldACL(zk.PermAll))
		if err != nil && err != zk.ErrNodeExists {
			return err
		}
	}
	return nil
}
498048
func (ec2i *FakeEC2Impl) CreateVolume(request *ec2.CreateVolumeInput) (resp *ec2.Volume, err error) {
	panic("Not implemented")
}
374138
func (kl *Kubelet) podVolumeSubpathsDirExists(podUID types.UID) (bool, error) {
	podVolDir := kl.getPodVolumeSubpathsDir(podUID)

	if pathExists, pathErr := mount.PathExists(podVolDir); pathErr != nil {
		return true, fmt.Errorf("Error checking if path %q exists: %v", podVolDir, pathErr)
	} else if !pathExists {
		return false, nil
	}
	return true, nil
}
679850
func (plugin *localVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
	fs := v1.PersistentVolumeFilesystem
	localVolume := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: volumeName,
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeSource: v1.PersistentVolumeSource{
				Local: &v1.LocalVolumeSource{
					Path: "",
				},
			},
			VolumeMode: &fs,
		},
	}
	return volume.NewSpecFromPersistentVolume(localVolume, false), nil
}
1238336
func (util *VsphereDiskUtil) CreateVolume(v *vsphereVolumeProvisioner, selectedZone []string) (volSpec *VolumeSpec, err error) {
	var fstype string
	cloud, err := getCloudProvider(v.plugin.host.GetCloudProvider())
	if err != nil {
		return nil, err
	}

	capacity := v.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
	// vSphere works with KiB, but its minimum allocation unit is 1 MiB
	volSizeMiB, err := volumehelpers.RoundUpToMiBInt(capacity)
	if err != nil {
		return nil, err
	}
	volSizeKiB := volSizeMiB * 1024
	name := volumeutil.GenerateVolumeName(v.options.ClusterName, v.options.PVName, 255)
	volumeOptions := &vclib.VolumeOptions{
		CapacityKB: volSizeKiB,
		Tags:       *v.options.CloudTags,
		Name:       name,
	}

	volumeOptions.Zone = selectedZone
	// Apply Parameters (case-insensitive). We leave validation of
	// the values to the cloud provider.
	for parameter, value := range v.options.Parameters {
		switch strings.ToLower(parameter) {
		case diskformat:
			volumeOptions.DiskFormat = value
		case datastore:
			volumeOptions.Datastore = value
		case volume.VolumeParameterFSType:
			fstype = value
			klog.V(4).Infof("Setting fstype as %q", fstype)
		case StoragePolicyName:
			volumeOptions.StoragePolicyName = value
			klog.V(4).Infof("Setting StoragePolicyName as %q", volumeOptions.StoragePolicyName)
		case HostFailuresToTolerateCapability, ForceProvisioningCapability,
			CacheReservationCapability, DiskStripesCapability,
			ObjectSpaceReservationCapability, IopsLimitCapability:
			capabilityData, err := validateVSANCapability(strings.ToLower(parameter), value)
			if err != nil {
				return nil, err
			}
			volumeOptions.VSANStorageProfileData += capabilityData
		default:
			return nil, fmt.Errorf("invalid option %q for volume plugin %s", parameter, v.plugin.GetPluginName())
		}
	}

	if volumeOptions.VSANStorageProfileData != "" {
		if volumeOptions.StoragePolicyName != "" {
			return nil, fmt.Errorf("Cannot specify storage policy capabilities along with storage policy name. Please specify only one")
		}
		volumeOptions.VSANStorageProfileData = "(" + volumeOptions.VSANStorageProfileData + ")"
	}
	klog.V(4).Infof("VSANStorageProfileData in vsphere volume %q", volumeOptions.VSANStorageProfileData)
	// TODO: implement PVC.Selector parsing
	if v.options.PVC.Spec.Selector != nil {
		return nil, fmt.Errorf("claim.Spec.Selector is not supported for dynamic provisioning on vSphere")
	}

	vmDiskPath, err := cloud.CreateVolume(volumeOptions)
	if err != nil {
		return nil, err
	}
	labels, err := cloud.GetVolumeLabels(vmDiskPath)
	if err != nil {
		return nil, err
	}
	volSpec = &VolumeSpec{
		Path:              vmDiskPath,
		Size:              volSizeKiB,
		Fstype:            fstype,
		StoragePolicyName: volumeOptions.StoragePolicyName,
		StoragePolicyID:   volumeOptions.StoragePolicyID,
		Labels:            labels,
	}
	klog.V(2).Infof("Successfully created vsphere volume %s", name)
	return volSpec, nil
}
414948
func (p *Pod) Stage1RootfsPath() (string, error) {
	stage1RootfsPath := "stage1/rootfs"
	if p.UsesOverlay() {
		stage1TreeStoreID, err := p.GetStage1TreeStoreID()
		if err != nil {
			return "", err
		}
		stage1RootfsPath = fmt.Sprintf("overlay/%s/upper/", stage1TreeStoreID)
	}

	return filepath.Join(p.Path(), stage1RootfsPath), nil
}
1005599
func (dfs *DistributedFilesystem) Create(tenantID string) error {
	glog.V(1).Infof("Creating volume for %s", tenantID)
	vol, err := dfs.disk.Create(tenantID)
	if err != nil {
		glog.Errorf("Could not create volume for tenant %s: %s", tenantID, err)
		return err
	}
	glog.V(1).Infof("Volume created for %s at %s", tenantID, vol.Path())
	if err := dfs.export(vol.Path()); err != nil {
		glog.Errorf("Could not export volume at %s: %s", vol.Path(), err)
		return err
	}
	return nil
}
401099
func AppCreatedPathFromStage1Rootfs(rootfs, appName string) string {
	return filepath.Join(AppsStatusesPathFromStage1Rootfs(rootfs), fmt.Sprintf("%s-created", appName))
}