// DiskIsAttached implements Volumes.DiskIsAttached
12380
func (c *Cloud) DiskIsAttached(diskName KubernetesVolumeID, nodeName types.NodeName) (bool, error) {
	_, instance, err := c.getFullInstance(nodeName)
	if err != nil {
		if err == cloudprovider.ErrInstanceNotFound {
			// If instance no longer exists, safe to assume volume is not attached.
			glog.Warningf(
				"Instance %q does not exist. DiskIsAttached will assume disk %q is not attached to it.",
				nodeName,
				diskName)
			return false, nil
		}

		return false, err
	}

	diskID, err := diskName.mapToAWSVolumeID()
	if err != nil {
		return false, fmt.Errorf("error mapping volume spec %q to aws id: %v", diskName, err)
	}

	for _, blockDevice := range instance.BlockDeviceMappings {
		id := awsVolumeID(aws.StringValue(blockDevice.Ebs.VolumeId))
		if id == diskID {
			return true, nil
		}
	}
	return false, nil
}
6623
func diskSetUp(manager diskManager, b rbdMounter, volPath string, mounter mount.Interface, fsGroup *int64) error {
	globalPDPath := manager.MakeGlobalPDName(*b.rbd)
	notMnt, err := mounter.IsLikelyNotMountPoint(globalPDPath)
	if err != nil && !os.IsNotExist(err) {
		klog.Errorf("cannot validate mountpoint: %s", globalPDPath)
		return err
	}
	if notMnt {
		return fmt.Errorf("no device is mounted at %s", globalPDPath)
	}

	notMnt, err = mounter.IsLikelyNotMountPoint(volPath)
	if err != nil && !os.IsNotExist(err) {
		klog.Errorf("cannot validate mountpoint: %s", volPath)
		return err
	}
	if !notMnt {
		return nil
	}

	if err := os.MkdirAll(volPath, 0750); err != nil {
		klog.Errorf("failed to mkdir:%s", volPath)
		return err
	}
	// Perform a bind mount to the full path to allow duplicate mounts of the same disk.
	options := []string{"bind"}
	if (&b).GetAttributes().ReadOnly {
		options = append(options, "ro")
	}
	mountOptions := util.JoinMountOptions(b.mountOptions, options)
	err = mounter.Mount(globalPDPath, volPath, "", mountOptions)
	if err != nil {
		klog.Errorf("failed to bind mount:%s", globalPDPath)
		return err
	}
	klog.V(3).Infof("rbd: successfully bind mount %s to %s with options %v", globalPDPath, volPath, mountOptions)

	if !b.ReadOnly {
		volume.SetVolumeOwnership(&b, fsGroup)
	}

	return nil
}
399233
func (v *sioVolume) TearDownAt(dir string) error {
	v.plugin.volumeMtx.LockKey(v.volSpecName)
	defer v.plugin.volumeMtx.UnlockKey(v.volSpecName)

	mounter := v.plugin.host.GetMounter(v.plugin.GetPluginName())
	dev, _, err := mount.GetDeviceNameFromMount(mounter, dir)
	if err != nil {
		klog.Errorf(log("failed to get reference count for volume: %s", dir))
		return err
	}

	klog.V(4).Info(log("attempting to unmount %s", dir))
	if err := mount.CleanupMountPoint(dir, mounter, false); err != nil {
		klog.Error(log("teardown failed while unmounting dir %s: %v ", dir, err))
		return err
	}
	klog.V(4).Info(log("dir %s unmounted successfully", dir))

	// detach/unmap
	deviceBusy, err := mounter.DeviceOpened(dev)
	if err != nil {
		klog.Error(log("teardown unable to get status for device %s: %v", dev, err))
		return err
	}

	// Detach volume from node:
	// use "last attempt wins" strategy to detach volume from node
	// only allow volume to detach when it is not busy (not being used by other pods)
	if !deviceBusy {
		klog.V(4).Info(log("teardown is attempting to detach/unmap volume for PV %s", v.volSpecName))
		if err := v.resetSioMgr(); err != nil {
			klog.Error(log("teardown failed, unable to reset scalio mgr: %v", err))
		}
		volName := v.volName
		if err := v.sioMgr.DetachVolume(volName); err != nil {
			klog.Warning(log("warning: detaching failed for volume %s:  %v", volName, err))
			return nil
		}
		klog.V(4).Infof(log("teardown of volume %v detached successfully", volName))
	}
	return nil
}
1089176
func (d *driver) VolumeRemove(
	ctx types.Context,
	volumeID string,
	opts *types.VolumeRemoveOpts) error {

	zone, err := d.validZone(ctx)
	if err != nil {
		return err
	}

	if zone == nil || *zone == "" {
		return goof.New("Zone is required for VolumeRemove")
	}

	// TODO: check if disk is still attached first
	asyncOp, err := mustSession(ctx).Disks.Delete(
		*d.projectID, *zone, volumeID).Do()
	if err != nil {
		return goof.WithError("Failed to initiate disk deletion", err)
	}

	err = d.waitUntilOperationIsFinished(
		ctx, zone, asyncOp)
	if err != nil {
		return err
	}

	return nil
}
790551
func (sb *storageBackend) FilesystemAttachment(host names.Tag, filesystem names.FilesystemTag) (FilesystemAttachment, error) {
	coll, cleanup := sb.mb.db().GetCollection(filesystemAttachmentsC)
	defer cleanup()

	var att filesystemAttachment
	err := coll.FindId(filesystemAttachmentId(host.Id(), filesystem.Id())).One(&att.doc)
	if err == mgo.ErrNotFound {
		return nil, errors.NotFoundf("filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
	} else if err != nil {
		return nil, errors.Annotatef(err, "getting filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
	}
	return &att, nil
}
1091949
func (os *OpenStack) DisksAreAttached(instanceID string, volumeIDs []string) (map[string]bool, error) {
	attached := make(map[string]bool)
	for _, volumeID := range volumeIDs {
		isAttached, err := os.DiskIsAttached(instanceID, volumeID)
		if err != nil && err != ErrNotFound {
			attached[volumeID] = true
			continue
		}
		attached[volumeID] = isAttached
	}
	return attached, nil
}
680056
func (b *storageosUnmounter) TearDownAt(dir string) error {
	if err := mount.CleanupMountPoint(dir, b.mounter, false); err != nil {
		klog.V(4).Infof("Unmounted StorageOS volume %s failed with: %v", b.pvName, err)
	}
	if err := b.manager.UnmountVolume(b); err != nil {
		klog.V(4).Infof("Mount reference for volume %s could not be removed from StorageOS: %v", b.pvName, err)
	}
	return nil
}
1139141
func (sb *storageBackend) RemoveVolumeAttachment(host names.Tag, volume names.VolumeTag) (err error) {
	defer errors.DeferredAnnotatef(&err, "removing attachment of volume %s from %s", volume.Id(), names.ReadableString(host))
	buildTxn := func(attempt int) ([]txn.Op, error) {
		attachment, err := sb.VolumeAttachment(host, volume)
		if errors.IsNotFound(err) && attempt > 0 {
			// We only ignore IsNotFound on attempts after the
			// first, since we expect the volume attachment to
			// be there initially.
			return nil, jujutxn.ErrNoOperations
		}
		if err != nil {
			return nil, errors.Trace(err)
		}
		if attachment.Life() != Dying {
			return nil, errors.New("volume attachment is not dying")
		}
		v, err := getVolumeByTag(sb.mb, volume)
		if err != nil {
			return nil, errors.Trace(err)
		}
		return removeVolumeAttachmentOps(host, v), nil
	}
	return sb.mb.db().Run(buildTxn)
}
1352582
func (api *DiskAPI) CanEditDisk(id int64) (bool, error) {

	disk, err := api.Read(id)
	if err != nil {
		return false, err
	}

	if disk == nil {
		return false, nil
	}

	// BundleInfoがあれば編集不可
	if disk.BundleInfo != nil && disk.BundleInfo.HostClass == bundleInfoWindowsHostClass {
		// Windows
		return false, nil
	}

	// SophosUTMであれば編集不可
	if disk.HasTag("pkg-sophosutm") || disk.IsSophosUTM() {
		return false, nil
	}
	// OPNsenseであれば編集不可
	if disk.HasTag("distro-opnsense") {
		return false, nil
	}
	// Netwiser VEであれば編集不可
	if disk.HasTag("pkg-netwiserve") {
		return false, nil
	}

	// ソースアーカイブ/ソースディスクともに持っていない場合
	if disk.SourceArchive == nil && disk.SourceDisk == nil {
		//ブランクディスクがソース
		return false, nil
	}

	for _, t := range allowDiskEditTags {
		if disk.HasTag(t) {
			// 対応OSインストール済みディスク
			return true, nil
		}
	}

	// ここまできても判定できないならソースに投げる
	if disk.SourceDisk != nil && disk.SourceDisk.Availability != "discontinued" {
		return api.client.Disk.CanEditDisk(disk.SourceDisk.ID)
	}
	if disk.SourceArchive != nil && disk.SourceArchive.Availability != "discontinued" {
		return api.client.Archive.CanEditDisk(disk.SourceArchive.ID)
	}

	return false, nil

}
919657
func (d *driver) VolumeRemove(
	ctx types.Context,
	volumeID string,
	opts *types.VolumeRemoveOpts) error {

	svc := mustSession(ctx)

	// Remove MountTarget(s)
	resp, err := svc.DescribeMountTargets(
		&awsefs.DescribeMountTargetsInput{
			FileSystemId: aws.String(volumeID),
		})
	if err != nil {
		return err
	}

	for _, mountTarget := range resp.MountTargets {
		_, err = svc.DeleteMountTarget(
			&awsefs.DeleteMountTargetInput{
				MountTargetId: aws.String(*mountTarget.MountTargetId),
			})

		if err != nil {
			return err
		}
	}

	// FileSystem can be deleted only after all mountpoints are deleted (
	// just in "deleting" life cycle state). Here code will wait until all
	// mountpoints are deleted.
	f := func() (interface{}, error) {
		duration := d.statusDelay
		for i := 1; i <= d.maxAttempts; i++ {
			resp, err := svc.DescribeMountTargets(
				&awsefs.DescribeMountTargetsInput{
					FileSystemId: aws.String(volumeID),
				})
			if err != nil {
				return nil, err
			}

			if len(resp.MountTargets) == 0 {
				return nil, nil
			}
			ctx.WithFields(log.Fields{
				"mounttargets": resp.MountTargets,
				"filesystemid": volumeID,
			}).Debug("waiting for MountTargets deletion")

			time.Sleep(time.Duration(duration) * time.Nanosecond)
			duration = int64(2) * duration
		}
		return nil, goof.WithField("maxAttempts", d.maxAttempts,
			"Status attempts exhausted")
	}
	_, ok, err := apiUtils.WaitFor(f, d.statusTimeout)
	if !ok {
		return goof.WithFields(goof.Fields{
			"filesystemid":  volumeID,
			"statusTimeout": d.statusTimeout},
			"Timeout occured waiting for MountTargets deletion")
	}
	if err != nil {
		return goof.WithFieldE("filesystemid", volumeID,
			"Error while waiting for MountTargets deletion", err)
	}

	// Remove FileSystem
	_, err = svc.DeleteFileSystem(
		&awsefs.DeleteFileSystemInput{
			FileSystemId: aws.String(volumeID),
		})
	if err != nil {
		return err
	}

	f = func() (interface{}, error) {
		duration := d.statusDelay
		for i := 1; i <= d.maxAttempts; i++ {
			ctx.WithFields(log.Fields{
				"filesystemid": volumeID,
			}).Info("waiting for FileSystem deletion")

			_, err := svc.DescribeFileSystems(
				&awsefs.DescribeFileSystemsInput{
					FileSystemId: aws.String(volumeID),
				})
			if err != nil {
				if awsErr, ok := err.(awserr.Error); ok {
					if awsErr.Code() == "FileSystemNotFound" {
						return nil, nil
					}
					return nil, err
				}
				return nil, err
			}
			time.Sleep(time.Duration(duration) * time.Nanosecond)
			duration = int64(2) * duration
		}
		return nil, goof.WithField("maxAttempts", d.maxAttempts,
			"Status attempts exhausted")
	}
	_, ok, err = apiUtils.WaitFor(f, d.statusTimeout)
	if !ok {
		return goof.WithFields(goof.Fields{
			"filesystemid":  volumeID,
			"statusTimeout": d.statusTimeout},
			"Timeout occured waiting for FileSystem deletion")
	}
	if err != nil {
		return goof.WithFieldE("filesystemid", volumeID,
			"Error while waiting for FileSystem deletion", err)
	}

	return nil
}
179195
func (util *RBDUtil) DetachDisk(plugin *rbdPlugin, deviceMountPath string, device string) error {
	if len(device) == 0 {
		return fmt.Errorf("DetachDisk failed , device is empty")
	}

	exec := plugin.host.GetExec(plugin.GetPluginName())

	var rbdCmd string

	// Unlike map, we cannot fallthrough for unmap
	// the tool to unmap is based on device type
	if strings.HasPrefix(device, "/dev/nbd") {
		rbdCmd = "rbd-nbd"
	} else {
		rbdCmd = "rbd"
	}

	// rbd unmap
	output, err := exec.Run(rbdCmd, "unmap", device)
	if err != nil {
		return rbdErrors(err, fmt.Errorf("rbd: failed to unmap device %s, error %v, rbd output: %v", device, err, output))
	}
	klog.V(3).Infof("rbd: successfully unmap device %s", device)

	// Currently, we don't persist rbd info on the disk, but for backward
	// compatbility, we need to clean it if found.
	rbdFile := filepath.Join(deviceMountPath, "rbd.json")
	exists, err := utilpath.Exists(utilpath.CheckFollowSymlink, rbdFile)
	if err != nil {
		return err
	}
	if exists {
		klog.V(3).Infof("rbd: old rbd.json is found under %s, cleaning it", deviceMountPath)
		err = util.cleanOldRBDFile(plugin, rbdFile)
		if err != nil {
			klog.Errorf("rbd: failed to clean %s", rbdFile)
			return err
		}
		klog.V(3).Infof("rbd: successfully remove %s", rbdFile)
	}
	return nil
}
1133245
func DiskRestGetUsage(context *gin.Context) {
	body, err := disk.ServiceGetUsage()
	util.RestHandleResponse(context, body, err)
}
773174
func (s *GCMChannelResponse) SetIsArchived(v bool) *GCMChannelResponse {
	s.IsArchived = &v
	return s
}
707976
func (dc *Datacenter) CheckDisksAttached(ctx context.Context, nodeVolumes map[string][]string) (map[string]map[string]bool, error) {
	attached := make(map[string]map[string]bool)
	var vmList []*VirtualMachine
	for nodeName, volPaths := range nodeVolumes {
		for _, volPath := range volPaths {
			setNodeVolumeMap(attached, volPath, nodeName, false)
		}
		vm, err := dc.GetVMByPath(ctx, nodeName)
		if err != nil {
			if IsNotFound(err) {
				klog.Warningf("Node %q does not exist, vSphere CP will assume disks %v are not attached to it.", nodeName, volPaths)
			}
			continue
		}
		vmList = append(vmList, vm)
	}
	if len(vmList) == 0 {
		klog.V(2).Infof("vSphere CP will assume no disks are attached to any node.")
		return attached, nil
	}
	vmMoList, err := dc.GetVMMoList(ctx, vmList, []string{"config.hardware.device", "name"})
	if err != nil {
		// When there is an error fetching instance information
		// it is safer to return nil and let volume information not be touched.
		klog.Errorf("Failed to get VM Managed object for nodes: %+v. err: +%v", vmList, err)
		return nil, err
	}

	for _, vmMo := range vmMoList {
		if vmMo.Config == nil {
			klog.Errorf("Config is not available for VM: %q", vmMo.Name)
			continue
		}
		for nodeName, volPaths := range nodeVolumes {
			if nodeName == vmMo.Name {
				verifyVolumePathsForVM(vmMo, volPaths, attached)
			}
		}
	}
	return attached, nil
}
1203137
func (st *State) FilesystemAttachments(ids []params.MachineStorageId) ([]params.FilesystemAttachmentResult, error) {
	args := params.MachineStorageIds{ids}
	var results params.FilesystemAttachmentResults
	err := st.facade.FacadeCall("FilesystemAttachments", args, &results)
	if err != nil {
		return nil, err
	}
	if len(results.Results) != len(ids) {
		return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results))
	}
	return results.Results, nil
}
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
}
403073
func (s *LoadBalancerTlsCertificate) SetIsAttached(v bool) *LoadBalancerTlsCertificate {
	s.IsAttached = &v
	return s
}