// creates a unique path for disks (even if they share the same *.vhd name)
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
}
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
}
601993
func NewDiskSystem(basePath ...string) FileSystem {

	base := ""

	if len(basePath) > 0 {
		base = basePath[0]
	}

	return &diskFileSystem{base}
}
228618
func workstationDataFilePaths() []string {
	leasesPath, err := workstationDhcpLeasesPathRegistry()
	if err != nil {
		log.Printf("Error getting DHCP leases path: %s", err)
	}

	if leasesPath != "" {
		leasesPath = filepath.Dir(leasesPath)
	}

	paths := make([]string, 0, 5)
	if os.Getenv("VMWARE_DATA") != "" {
		paths = append(paths, os.Getenv("VMWARE_DATA"))
	}

	if leasesPath != "" {
		paths = append(paths, leasesPath)
	}

	if os.Getenv("ProgramData") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramData"), "/VMware"))
	}

	if os.Getenv("ALLUSERSPROFILE") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ALLUSERSPROFILE"), "/Application Data/VMware"))
	}

	return paths
}
240875
func (d *driver) getNFSVolumePath(v *api.Volume) (string, error) {
	parentPath, err := d.getNFSPath(v)
	if err != nil {
		return "", err
	}

	return path.Join(parentPath, v.Id), nil
}
656321
func makeVDPDNameInternal(host volume.VolumeHost, pool string, image string) string {
	return filepath.Join(host.GetVolumeDevicePluginDir(rbdPluginName), pool+"-image-"+image)
}
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")
}
1118200
func (d *Parallels9Driver) CompactDisk(diskPath string) error {
	prlDiskToolPath, err := exec.LookPath("prl_disk_tool")
	if err != nil {
		return err
	}

	// Analyze the disk content and remove unused blocks
	command := []string{
		"compact",
		"--hdd", diskPath,
	}
	if err := exec.Command(prlDiskToolPath, command...).Run(); err != nil {
		return err
	}

	// Remove null blocks
	command = []string{
		"compact", "--buildmap",
		"--hdd", diskPath,
	}
	if err := exec.Command(prlDiskToolPath, command...).Run(); err != nil {
		return err
	}

	return nil
}
106362
func createConfigPath() error {
	path, err := GetConfigFilePath("")
	if err != nil {
		return err
	}
	return os.MkdirAll(path, 0700)
}
1074767
func (diskManager virtualDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (canonicalDiskPath string, err error) {
	if diskManager.volumeOptions.SCSIControllerType == "" {
		diskManager.volumeOptions.SCSIControllerType = vclib.LSILogicControllerType
	}
	// Create virtual disk
	diskFormat := vclib.DiskFormatValidType[diskManager.volumeOptions.DiskFormat]
	// Create a virtual disk manager
	vdm := object.NewVirtualDiskManager(datastore.Client())
	// Create specification for new virtual disk
	vmDiskSpec := &types.FileBackedVirtualDiskSpec{
		VirtualDiskSpec: types.VirtualDiskSpec{
			AdapterType: diskManager.volumeOptions.SCSIControllerType,
			DiskType:    diskFormat,
		},
		CapacityKb: int64(diskManager.volumeOptions.CapacityKB),
	}
	requestTime := time.Now()
	// Create virtual disk
	task, err := vdm.CreateVirtualDisk(ctx, diskManager.diskPath, datastore.Datacenter.Datacenter, vmDiskSpec)
	if err != nil {
		vclib.RecordvSphereMetric(vclib.APICreateVolume, requestTime, err)
		klog.Errorf("Failed to create virtual disk: %s. err: %+v", diskManager.diskPath, err)
		return "", err
	}
	taskInfo, err := task.WaitForResult(ctx, nil)
	vclib.RecordvSphereMetric(vclib.APICreateVolume, requestTime, err)
	if err != nil {
		klog.Errorf("Failed to complete virtual disk creation: %s. err: %+v", diskManager.diskPath, err)
		return "", err
	}
	canonicalDiskPath = taskInfo.Result.(string)
	return canonicalDiskPath, nil
}
117343
func SplitPathDirEntry(localizedPath string) (dir, base string) {
	normalizedPath := filepath.ToSlash(localizedPath)
	vol := filepath.VolumeName(normalizedPath)
	normalizedPath = normalizedPath[len(vol):]

	if normalizedPath == "/" {
		// Specifies the root path.
		return filepath.FromSlash(vol + normalizedPath), "."
	}

	trimmedPath := vol + strings.TrimRight(normalizedPath, "/")

	dir = filepath.FromSlash(path.Dir(trimmedPath))
	base = filepath.FromSlash(path.Base(trimmedPath))

	return dir, base
}
927791
func (f *FileNameV3) Path() string {
	return (&FileName{Name: f.Name, Length: f.Length}).Path()
}
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)
}
1315356
func workstationProgramFilePaths() []string {
	path, err := workstationVMwareRoot()
	if err != nil {
		log.Printf("Error finding VMware root: %s", err)
	}

	paths := make([]string, 0, 5)
	if os.Getenv("VMWARE_HOME") != "" {
		paths = append(paths, os.Getenv("VMWARE_HOME"))
	}

	if path != "" {
		paths = append(paths, path)
	}

	if os.Getenv("ProgramFiles(x86)") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles(x86)"), "/VMware/VMware Workstation"))
	}

	if os.Getenv("ProgramFiles") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles"), "/VMware/VMware Workstation"))
	}

	return paths
}
115179
func BlockDevicePath(device BlockDevice) (string, error) {
	if device.WWN != "" {
		return diskByWWN + device.WWN, nil
	}
	if device.HardwareId != "" {
		return path.Join(diskByID, device.HardwareId), nil
	}
	if len(device.DeviceLinks) > 0 {
		// return the first device link in the list
		return device.DeviceLinks[0], nil
	}
	if device.DeviceName != "" {
		return path.Join(diskByDeviceName, device.DeviceName), nil
	}
	return "", errors.Errorf("could not determine path for block device")
}
513628
func (s *Disk) SetDiskPath(v string) *Disk {
	s.DiskPath = &v
	return s
}
1204763
func guestPath(pathfinder func(string) (string, error)) (string, error) {
	baseDir, err := pathfinder(series.MustHostSeries())
	if err != nil {
		return "", errors.Trace(err)
	}
	return filepath.Join(baseDir, kvm, guestDir), nil
}