// ChildDisk creates a new VirtualDisk device, linked to the given parent disk, which can be added to a VM.
484787
func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk {
	disk := *parent
	backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)
	p := new(DatastorePath)
	p.FromString(backing.FileName)
	p.Path = ""

	// Use specified disk as parent backing to a new disk.
	disk.Backing = &types.VirtualDiskFlatVer2BackingInfo{
		VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
			FileName:  p.String(),
			Datastore: backing.Datastore,
		},
		Parent:          backing,
		DiskMode:        backing.DiskMode,
		ThinProvisioned: backing.ThinProvisioned,
	}

	return &disk
}
987582
func (virtualDisk *VirtualDisk) Delete(ctx context.Context, datacenter *vclib.Datacenter) error {
	return getDiskManager(virtualDisk, VirtualDiskDeleteOperation).Delete(ctx, datacenter)
}
14734
func (ci CellID) ChildEnd() CellID {
	ol := ci.lsb()
	return CellID(uint64(ci) + ol + ol>>2)
}
325074
func virtioBlkStorageHandler(storage pb.Storage, s *sandbox) (string, error) {
	// Get the device node path based on the PCI address provided
	// in Storage Source
	devPath, err := getPCIDeviceName(s, storage.Source)
	if err != nil {
		return "", err
	}
	storage.Source = devPath

	return commonStorageHandler(storage)
}
982968
func (d *LogDatastore) DiskUsage() (uint64, error) {
	log.Printf("%s: DiskUsage\n", d.Name)
	return DiskUsage(d.child)
}
109323
func (client *Client) DetachDisk(instanceId string, diskId string) error {
	args := DetachDiskArgs{
		InstanceId: instanceId,
		DiskId:     diskId,
	}
	response := DetachDiskResponse{}
	err := client.Invoke("DetachDisk", &args, &response)
	return err
}
283870
func getChildDevice(d *device, deviceType string) *device {
	for i := range d.DeviceList.Device {
		if d.DeviceList.Device[i].DeviceType == deviceType {
			return &d.DeviceList.Device[i]
		}
	}
	return nil
}
876510
func (ci CellID) ChildBeginAtLevel(level int) CellID {
	return CellID(uint64(ci) - ci.lsb() + lsbForLevel(level))
}
391166
func (vm *VirtualMachine) DetachDisk(ctx context.Context, vmDiskPath string) error {
	vmDiskPath = RemoveStorageClusterORFolderNameFromVDiskPath(vmDiskPath)
	device, err := vm.getVirtualDeviceByPath(ctx, vmDiskPath)
	if err != nil {
		klog.Errorf("Disk ID not found for VM: %q with diskPath: %q", vm.InventoryPath, vmDiskPath)
		return err
	}
	if device == nil {
		klog.Errorf("No virtual device found with diskPath: %q on VM: %q", vmDiskPath, vm.InventoryPath)
		return fmt.Errorf("No virtual device found with diskPath: %q on VM: %q", vmDiskPath, vm.InventoryPath)
	}
	// Detach disk from VM
	requestTime := time.Now()
	err = vm.RemoveDevice(ctx, true, device)
	RecordvSphereMetric(APIDetachVolume, requestTime, err)
	if err != nil {
		klog.Errorf("Error occurred while removing disk device for VM: %q. err: %v", vm.InventoryPath, err)
		return err
	}
	return nil
}
247567
func (client *Client) ReInitDisk(diskId string) error {
	args := ReInitDiskArgs{
		DiskId: diskId,
	}
	response := ReInitDiskResponse{}
	err := client.Invoke("ReInitDisk", &args, &response)
	return err
}
1140352
func (d *Dataset) OnDisk(fn func(*Dataset) *Dataset) *Dataset {
	ret := fn(d)

	var parents, currents []*Dataset
	currents = append(currents, ret)
	for {
		for _, t := range currents {
			isFirstDataset, isLastDataset := false, false
			if t == ret {
				isLastDataset = true
			} else if t.Step.OutputDataset != nil {
				t.Step.OutputDataset.Meta.OnDisk = ModeOnDisk
			}
			for _, p := range t.Step.InputDatasets {
				if p != d {
					parents = append(parents, p)
				} else {
					isFirstDataset = true
				}
			}
			if !isFirstDataset && !isLastDataset {
				t.Step.Meta.IsRestartable = true
			}
		}
		if len(parents) == 0 {
			break
		}
		currents = parents
		parents = nil
	}

	return ret
}
790756
func (util *RBDUtil) AttachDisk(b rbdMounter) (string, error) {
	var output []byte

	globalPDPath := util.MakeGlobalPDName(*b.rbd)
	if pathExists, pathErr := mount.PathExists(globalPDPath); pathErr != nil {
		return "", fmt.Errorf("Error checking if path exists: %v", pathErr)
	} else if !pathExists {
		if err := os.MkdirAll(globalPDPath, 0750); err != nil {
			return "", err
		}
	}

	// Evalute whether this device was mapped with rbd.
	devicePath, mapped := waitForPath(b.Pool, b.Image, 1 /*maxRetries*/, false /*useNbdDriver*/)

	// If rbd-nbd tools are found, we will fallback to it should the default krbd driver fail.
	nbdToolsFound := false

	if !mapped {
		nbdToolsFound = checkRbdNbdTools(b.exec)
		if nbdToolsFound {
			devicePath, mapped = waitForPath(b.Pool, b.Image, 1 /*maxRetries*/, true /*useNbdDriver*/)
		}
	}

	if !mapped {
		// Currently, we don't acquire advisory lock on image, but for backward
		// compatibility, we need to check if the image is being used by nodes running old kubelet.
		// osd_client_watch_timeout defaults to 30 seconds, if the watcher stays active longer than 30 seconds,
		// rbd image does not get mounted and failure message gets generated.
		backoff := wait.Backoff{
			Duration: rbdImageWatcherInitDelay,
			Factor:   rbdImageWatcherFactor,
			Steps:    rbdImageWatcherSteps,
		}
		needValidUsed := true
		if b.accessModes != nil {
			// If accessModes only contains ReadOnlyMany, we don't need check rbd status of being used.
			if len(b.accessModes) == 1 && b.accessModes[0] == v1.ReadOnlyMany {
				needValidUsed = false
			}
		}
		// If accessModes is nil, the volume is referenced by in-line volume.
		// We can assume the AccessModes to be {"RWO" and "ROX"}, which is what the volume plugin supports.
		// We do not need to consider ReadOnly here, because it is used for VolumeMounts.

		if needValidUsed {
			err := wait.ExponentialBackoff(backoff, func() (bool, error) {
				used, rbdOutput, err := util.rbdStatus(&b)
				if err != nil {
					return false, fmt.Errorf("fail to check rbd image status with: (%v), rbd output: (%s)", err, rbdOutput)
				}
				return !used, nil
			})
			// Return error if rbd image has not become available for the specified timeout.
			if err == wait.ErrWaitTimeout {
				return "", fmt.Errorf("rbd image %s/%s is still being used", b.Pool, b.Image)
			}
			// Return error if any other errors were encountered during waiting for the image to become available.
			if err != nil {
				return "", err
			}
		}

		mon := util.kernelRBDMonitorsOpt(b.Mon)
		klog.V(1).Infof("rbd: map mon %s", mon)

		_, err := b.exec.Run("modprobe", "rbd")
		if err != nil {
			klog.Warningf("rbd: failed to load rbd kernel module:%v", err)
		}
		output, err = execRbdMap(b, "rbd", mon)
		if err != nil {
			if !nbdToolsFound {
				klog.V(1).Infof("rbd: map error %v, rbd output: %s", err, string(output))
				return "", fmt.Errorf("rbd: map failed %v, rbd output: %s", err, string(output))
			}
			klog.V(3).Infof("rbd: map failed with %v, %s. Retrying with rbd-nbd", err, string(output))
			errList := []error{err}
			outputList := output
			output, err = execRbdMap(b, "rbd-nbd", mon)
			if err != nil {
				errList = append(errList, err)
				outputList = append(outputList, output...)
				return "", fmt.Errorf("rbd: map failed %v, rbd output: %s", errors.NewAggregate(errList), string(outputList))
			}
			devicePath, mapped = waitForPath(b.Pool, b.Image, 10 /*maxRetries*/, true /*useNbdDrive*/)
		} else {
			devicePath, mapped = waitForPath(b.Pool, b.Image, 10 /*maxRetries*/, false /*useNbdDriver*/)
		}
		if !mapped {
			return "", fmt.Errorf("Could not map image %s/%s, Timeout after 10s", b.Pool, b.Image)
		}
	}
	return devicePath, nil
}
209675
func NewMockDisk(ctrl *gomock.Controller) *MockDisk {
	mock := &MockDisk{ctrl: ctrl}
	mock.recorder = &MockDiskMockRecorder{mock}
	return mock
}
110458
func (gce *Connection) AttachDisk(zone, volumeName, instanceId string, mode DiskMode) (*AttachedDisk, error) {
	disk, err := gce.raw.GetDisk(gce.projectID, zone, volumeName)
	if err != nil {
		return nil, errors.Annotatef(err, "cannot obtain disk %q to attach it", volumeName)
	}
	attachedDisk := &compute.AttachedDisk{
		// Specifies a unique device name of your choice that
		// is reflected into the /dev/disk/by-id/google-*
		DeviceName: deviceName(zone, disk.Id),
		Source:     disk.SelfLink,
		Mode:       string(mode),
	}
	err = gce.raw.AttachDisk(gce.projectID, zone, instanceId, attachedDisk)
	if err != nil {
		return nil, errors.Annotate(err, "cannot attach disk")
	}
	return &AttachedDisk{
		VolumeName: volumeName,
		DeviceName: attachedDisk.DeviceName,
		Mode:       mode,
	}, nil
}
1246228
func (v *azureVolumeSource) createUnmanagedDiskVolume(
	vm *compute.VirtualMachine,
	p storage.VolumeParams,
) (*storage.Volume, *storage.VolumeAttachment, error) {

	diskName := p.Tag.String()
	sizeInGib := mibToGib(p.Size)
	volumeAttachment, err := v.addDataDisk(
		vm,
		diskName,
		p.Tag,
		p.Attachment.Machine,
		compute.DiskCreateOptionTypesEmpty,
		to.Int32Ptr(int32(sizeInGib)),
	)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	// Data disks associate VHDs to machines. In Juju's storage model,
	// the VHD is the volume and the disk is the volume attachment.
	volume := storage.Volume{
		p.Tag,
		storage.VolumeInfo{
			VolumeId:   diskName,
			Size:       gibToMib(sizeInGib),
			Persistent: true,
		},
	}
	return &volume, volumeAttachment, nil
}
725785
func (dc *Datacenter) createFolders() {
	folders := []struct {
		ref   *types.ManagedObjectReference
		name  string
		types []string
	}{
		{&dc.VmFolder, "vm", []string{"VirtualMachine", "VirtualApp", "Folder"}},
		{&dc.HostFolder, "host", []string{"ComputeResource", "Folder"}},
		{&dc.DatastoreFolder, "datastore", []string{"Datastore", "StoragePod", "Folder"}},
		{&dc.NetworkFolder, "network", []string{"Network", "DistributedVirtualSwitch", "Folder"}},
	}

	for _, f := range folders {
		folder := &Folder{}
		folder.Name = f.name

		if dc.isESX {
			folder.ChildType = f.types[:1]
			folder.Self = *f.ref
			Map.PutEntity(dc, folder)
		} else {
			folder.ChildType = f.types
			e := Map.PutEntity(dc, folder)

			// propagate the generated morefs to Datacenter
			ref := e.Reference()
			f.ref.Type = ref.Type
			f.ref.Value = ref.Value
		}
	}

	net := Map.Get(dc.NetworkFolder).(*Folder)

	for _, ref := range esx.Datacenter.Network {
		// Add VM Network by default to each Datacenter
		network := &mo.Network{}
		network.Self = ref
		network.Name = strings.Split(ref.Value, "-")[1]
		network.Entity().Name = network.Name
		if !dc.isESX {
			network.Self.Value = "" // we want a different moid per-DC
		}

		net.putChild(network)
	}
}
690605
func (c *VSphereCloud) CreateLinkClonedVm(vmName, vmImage *string) (string, error) {
	f := find.NewFinder(c.Client.Client, true)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dc, err := f.Datacenter(ctx, c.Datacenter)
	if err != nil {
		return "", err
	}
	f.SetDatacenter(dc)

	templateVm, err := f.VirtualMachine(ctx, *vmImage)
	if err != nil {
		return "", err
	}

	glog.V(2).Infof("Template VM ref is %+v", templateVm)
	datacenterFolders, err := dc.Folders(ctx)
	if err != nil {
		return "", err
	}

	// Create snapshot of the template VM if not already snapshotted.
	snapshot, err := createSnapshot(ctx, templateVm, snapshotName, snapshotDesc)
	if err != nil {
		return "", err
	}

	clsComputeRes, err := f.ClusterComputeResource(ctx, c.Cluster)
	glog.V(4).Infof("Cluster compute resource is %+v", clsComputeRes)
	if err != nil {
		return "", err
	}

	resPool, err := clsComputeRes.ResourcePool(ctx)
	glog.V(4).Infof("Cluster resource pool is %+v", resPool)
	if err != nil {
		return "", err
	}

	if resPool == nil {
		return "", errors.New(fmt.Sprintf("No resource pool found for cluster %s", c.Cluster))
	}

	resPoolRef := resPool.Reference()
	snapshotRef := snapshot.Reference()

	cloneSpec := &types.VirtualMachineCloneSpec{
		Config: &types.VirtualMachineConfigSpec{
			Flags: &types.VirtualMachineFlagInfo{
				DiskUuidEnabled: fi.Bool(true),
			},
		},
		Location: types.VirtualMachineRelocateSpec{
			Pool:         &resPoolRef,
			DiskMoveType: "createNewChildDiskBacking",
		},
		Snapshot: &snapshotRef,
	}

	// Create a link cloned VM from the template VM's snapshot
	clonedVmTask, err := templateVm.Clone(ctx, datacenterFolders.VmFolder, *vmName, *cloneSpec)
	if err != nil {
		return "", err
	}

	clonedVmTaskInfo, err := clonedVmTask.WaitForResult(ctx, nil)
	if err != nil {
		return "", err
	}

	clonedVm := clonedVmTaskInfo.Result.(object.Reference)
	glog.V(2).Infof("Created VM %s successfully", clonedVm)

	return clonedVm.Reference().Value, nil
}