private boolean isPlugAvailableByDisks(boolean plug) {
    ArrayList<Disk> disks =
        getSelectedItems() != null ? Linq.<Disk>cast(getSelectedItems()) : new ArrayList<Disk>();

    for (Disk disk : disks) {
      boolean isLocked =
          disk.getDiskStorageType() == DiskStorageType.IMAGE
              && ((DiskImage) disk).getImageStatus() == ImageStatus.LOCKED;

      boolean isDiskHotpluggableInterface = false;
      if (getEntity() != null) {
        isDiskHotpluggableInterface =
            AsyncDataProvider.getInstance()
                .getDiskHotpluggableInterfaces(
                    getEntity().getOs(), getEntity().getVdsGroupCompatibilityVersion())
                .contains(disk.getDiskInterface());
      }

      if (disk.getPlugged() == plug || isLocked || (!isDiskHotpluggableInterface && !isVmDown())) {
        return false;
      }
    }

    return true;
  }
  private void updateActionAvailability() {
    Disk disk = getSelectedItem();

    getNewCommand().setIsExecutionAllowed(true);

    getAttachCommand().setIsExecutionAllowed(true);

    getEditCommand()
        .setIsExecutionAllowed(
            disk != null
                && isSingleDiskSelected()
                && !isDiskLocked(disk)
                && (isVmDown()
                    || !disk.getPlugged()
                    || (isExtendImageSizeSupported() && isExtendImageSizeEnabled())));

    getRemoveCommand()
        .setIsExecutionAllowed(atLeastOneDiskSelected() && isRemoveCommandAvailable());

    getMoveCommand()
        .setIsExecutionAllowed(
            atLeastOneDiskSelected() && (isMoveCommandAvailable() || isLiveMoveCommandAvailable()));

    updateScanAlignmentCommandAvailability();

    getPlugCommand().setIsExecutionAllowed(isPlugCommandAvailable(true));

    getUnPlugCommand().setIsExecutionAllowed(isPlugCommandAvailable(false));

    ChangeQuotaModel.updateChangeQuotaActionAvailability(
        getItems() != null ? (List<Disk>) getItems() : null,
        getSelectedItems() != null ? getSelectedItems() : null,
        getSystemTreeSelectedItem(),
        getChangeQuotaCommand());
  }
  private void canDoActionMakeDiskBootableOnOtherVm(boolean boot) {
    UpdateVmDiskParameters parameters = createParameters();
    Disk newDisk = parameters.getDiskInfo();
    newDisk.setBoot(true);

    Guid otherVmId = Guid.newGuid();
    VM otherVm = new VM();
    otherVm.setId(otherVmId);

    DiskImage otherDisk = new DiskImage();
    otherDisk.setId(Guid.newGuid());
    otherDisk.setActive(true);
    otherDisk.setBoot(boot);
    if (boot) {
      when(diskDao.getVmBootActiveDisk(otherVmId)).thenReturn(otherDisk);
    }
    when(diskDao.get(diskImageGuid)).thenReturn(createDiskImage());

    initializeCommand(parameters, Arrays.asList(createVmStatusDown(), otherVm));

    mockInterfaceList();

    // The command should only succeed if there is no other bootable disk
    assertEquals(!boot, command.canDoAction());
  }
 public static void fillImagesBySnapshots(VM vm) {
   for (Disk disk : vm.getDiskMap().values()) {
     if (disk.getDiskStorageType().isInternal()) {
       DiskImage diskImage = (DiskImage) disk;
       diskImage.getSnapshots().addAll(getAllImageSnapshots(diskImage.getImageId()));
     }
   }
 }
 public static List<LunDisk> filterDiskBasedOnLuns(
     Collection<? extends Disk> listOfDisks, boolean allowShareableDisks) {
   List<LunDisk> lunDisks = new ArrayList<>();
   for (Disk disk : listOfDisks) {
     if (disk.getDiskStorageType() == DiskStorageType.LUN
         && (allowShareableDisks || !disk.isShareable())) {
       lunDisks.add((LunDisk) disk);
     }
   }
   return lunDisks;
 }
  private boolean isRemoveCommandAvailable() {
    ArrayList<Disk> disks =
        getSelectedItems() != null ? Linq.<Disk>cast(getSelectedItems()) : new ArrayList<Disk>();

    for (Disk disk : disks) {
      if (isDiskLocked(disk) || (!isVmDown() && disk.getPlugged())) {
        return false;
      }
    }

    return true;
  }
 public static List<CinderDisk> filterDisksBasedOnCinder(
     Collection<? extends Disk> listOfDisks, boolean onlyPluggedDisks) {
   List<CinderDisk> cinderDisks = new ArrayList<>();
   for (Disk disk : listOfDisks) {
     if (disk.getDiskStorageType() == DiskStorageType.CINDER) {
       if (!onlyPluggedDisks || disk.getPlugged()) {
         cinderDisks.add((CinderDisk) disk);
       }
     }
   }
   return cinderDisks;
 }
  private boolean isMoveCommandAvailable() {
    ArrayList<Disk> disks =
        getSelectedItems() != null ? Linq.<Disk>cast(getSelectedItems()) : new ArrayList<Disk>();

    for (Disk disk : disks) {
      if (!isImageDiskOK(disk) || (!isVmDown() && disk.getPlugged()) || disk.isDiskSnapshot()) {
        return false;
      }
    }

    return true;
  }
  private ArrayList<VdcActionParametersBase> createHotPlugDiskToVmParameters(boolean plug) {
    ArrayList<VdcActionParametersBase> parametersList = new ArrayList<VdcActionParametersBase>();
    VM vm = getEntity();

    for (Object item : getSelectedItems()) {
      Disk disk = (Disk) item;
      disk.setPlugged(plug);

      parametersList.add(new HotPlugDiskToVmParameters(vm.getId(), disk.getId()));
    }

    return parametersList;
  }
  private boolean canRemoveVmWithDetachDisks() {
    if (!Guid.Empty.equals(getVm().getVmtGuid())) {
      return failValidation(EngineMessage.VM_CANNOT_REMOVE_WITH_DETACH_DISKS_BASED_ON_TEMPLATE);
    }

    for (Disk disk : getVm().getDiskList()) {
      List<DiskImage> diskImageList = diskImageDao.getAllSnapshotsForImageGroup(disk.getId());
      if (diskImageList.size() > 1) {
        return failValidation(EngineMessage.VM_CANNOT_REMOVE_WITH_DETACH_DISKS_SNAPSHOTS_EXIST);
      }
    }

    return true;
  }
 public static boolean checkImagesConfiguration(
     Guid storageDomainId, Collection<? extends Disk> disksConfigList, List<String> messages) {
   boolean result = true;
   StorageDomainStatic storageDomain =
       DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId);
   for (Disk diskInfo : disksConfigList) {
     if (DiskStorageType.IMAGE == diskInfo.getDiskStorageType()) {
       result = checkImageConfiguration(storageDomain, (DiskImage) diskInfo, messages);
     }
     if (!result) {
       break;
     }
   }
   return result;
 }
  @Override
  protected void executeVmCommand() {
    if (!isOperationPerformedOnDiskSnapshot()) {
      getVmStaticDao().incrementDbGeneration(getVm().getId());
    }

    final VmDevice vmDevice = createVmDevice();
    getVmDeviceDao().save(vmDevice);

    // update cached image
    List<Disk> imageList = new ArrayList<>();
    imageList.add(disk);
    VmHandler.updateDisksForVm(getVm(), imageList);

    if (!isOperationPerformedOnDiskSnapshot()) {
      if (disk.isAllowSnapshot()) {
        updateDiskVmSnapshotId();
      }
    }

    // update vm device boot order
    updateBootOrderInVmDevice();

    if (getParameters().isPlugUnPlug() && getVm().getStatus() != VMStatus.Down) {
      performPlugCommand(VDSCommandType.HotPlugDisk, disk, vmDevice);
    }
    setSucceeded(true);
  }
 @Test
 public void testValidateOvfDiskNotIllegal() {
   ((DiskImage) disk).setImageStatus(ImageStatus.OK);
   disk.setContentType(DiskContentType.OVF_STORE);
   ValidateTestUtils.runAndAssertValidateFailure(
       cmd, EngineMessage.ACTION_TYPE_FAILED_OVF_DISK_NOT_IN_APPLICABLE_STATUS);
 }
 /**
  * Filter image disks by attributes.
  *
  * @param listOfDisks - The list of disks to be filtered.
  * @param allowOnlyNotShareableDisks - Indication whether to allow only disks that are not
  *     shareable
  * @param allowOnlySnapableDisks - Indication whether to allow only disks which are allowed to be
  *     snapshoted.
  * @param allowOnlyActiveDisks - Indication whether to allow only disks that are not disk
  *     snapshots.
  * @return - List filtered of disk images according to the given filters.
  */
 public static List<DiskImage> filterImageDisks(
     Collection<? extends Disk> listOfDisks,
     boolean allowOnlyNotShareableDisks,
     boolean allowOnlySnapableDisks,
     boolean allowOnlyActiveDisks) {
   List<DiskImage> diskImages = new ArrayList<>();
   for (Disk disk : listOfDisks) {
     if (disk.getDiskStorageType() == DiskStorageType.IMAGE
         && (!allowOnlyNotShareableDisks || !disk.isShareable())
         && (!allowOnlySnapableDisks || disk.isAllowSnapshot())
         && (!allowOnlyActiveDisks || Boolean.TRUE.equals(((DiskImage) disk).getActive()))) {
       diskImages.add((DiskImage) disk);
     }
   }
   return diskImages;
 }
  private void scanAlignment() {
    ArrayList<VdcActionParametersBase> parameterList = new ArrayList<VdcActionParametersBase>();

    for (Disk disk : getSelectedItems()) {
      parameterList.add(new GetDiskAlignmentParameters(disk.getId()));
    }

    Frontend.getInstance()
        .runMultipleAction(
            VdcActionType.GetDiskAlignment,
            parameterList,
            new IFrontendMultipleActionAsyncCallback() {
              @Override
              public void executed(FrontendMultipleActionAsyncResult result) {}
            },
            this);
  }
 @Test
 public void testPreImportedHostedEngineLunDiskRemove() {
   disk = new LunDisk();
   setupDisk();
   disk.setDiskAlias(StorageConstants.HOSTED_ENGINE_LUN_DISK_ALIAS);
   doReturn(disk).when(cmd).getDisk();
   ValidateTestUtils.runAndAssertValidateSuccess(cmd);
 }
 private boolean isDiskLocked(Disk disk) {
   switch (disk.getDiskStorageType()) {
     case IMAGE:
       return ((DiskImage) disk).getImageStatus() == ImageStatus.LOCKED;
     case CINDER:
       return ((CinderDisk) disk).getImageStatus() == ImageStatus.LOCKED;
   }
   return false;
 }
 @Override
 public List<PermissionSubject> getPermissionCheckSubjects() {
   if (permsList == null) {
     permsList = super.getPermissionCheckSubjects();
     Guid diskId = disk == null ? null : disk.getId();
     permsList.add(new PermissionSubject(diskId, VdcObjectType.Disk, ActionGroup.ATTACH_DISK));
   }
   return permsList;
 }
 @Test
 public void testImportedHostedEngineLunDiskRemove() {
   vm.setOrigin(OriginType.MANAGED_HOSTED_ENGINE);
   vm.setStatus(VMStatus.Up);
   disk = new LunDisk();
   setupDisk();
   disk.setDiskAlias(StorageConstants.HOSTED_ENGINE_LUN_DISK_ALIAS);
   doReturn(disk).when(cmd).getDisk();
   ValidateTestUtils.runAndAssertValidateSuccess(cmd);
 }
  public void updateBootableFrom(List<Disk> vmDisks) {
    getIsBootable().setEntity(true);
    getIsBootable().setIsChangeable(true);
    if (getDisk() == null || !getDisk().isDiskSnapshot()) {
      for (Disk disk : vmDisks) {
        if (disk.isBoot() && !disk.equals(getDisk())) {
          getIsBootable().setEntity(false);
          if (!disk.isDiskSnapshot()) {
            getIsBootable().setChangeProhibitionReason(constants.onlyOneBootableDisk());
            getIsBootable().setIsChangeable(false);
            break;
          }
        }
      }
    }

    if (!getIsNew()) {
      getIsBootable().setEntity(getDisk().isBoot());
    }
  }
  private void confirmUnplug() {
    ConfirmationModel model = new ConfirmationModel();
    model.setTitle(ConstantsManager.getInstance().getConstants().deactivateVmDisksTitle());
    model.setMessage(
        ConstantsManager.getInstance().getConstants().areYouSureYouWantDeactivateVMDisksMsg());
    model.setHashName("deactivate_vm_disk"); // $NON-NLS-1$
    setWindow(model);

    ArrayList<String> items = new ArrayList<String>();
    for (Disk selected : getSelectedItems()) {
      items.add(selected.getDiskAlias());
    }
    model.setItems(items);

    UICommand unPlug = UICommand.createDefaultOkUiCommand("OnUnplug", this); // $NON-NLS-1$
    model.getCommands().add(unPlug);

    UICommand cancel = UICommand.createCancelUiCommand("Cancel", this); // $NON-NLS-1$
    model.getCommands().add(cancel);
  }
 private void updateDiskVmSnapshotId() {
   Guid snapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE);
   if (disk.getDiskStorageType().isInternal()) {
     DiskImage diskImage = ((DiskImage) disk);
     getImageDao().updateImageVmSnapshotId(diskImage.getImageId(), snapshotId);
   } else {
     throw new EngineException(
         EngineError.StorageException,
         "update of snapshot id was initiated for unsupported disk type");
   }
 }
  @Test
  public void canDoActionFailedWipeVmAttachedToPool() {
    Disk oldDisk = createDiskImage();
    oldDisk.setWipeAfterDelete(true);
    when(diskDao.get(diskImageGuid)).thenReturn(oldDisk);

    UpdateVmDiskParameters parameters = createParameters();
    parameters.getDiskInfo().setWipeAfterDelete(false);
    VM vm = createVm(VMStatus.Down);
    vm.setVmPoolId(Guid.newGuid());
    initializeCommand(parameters, Collections.singletonList(vm));

    CanDoActionTestUtils.runAndAssertCanDoActionFailure(
        command, EngineMessage.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL);

    oldDisk.setWipeAfterDelete(false);
    parameters.getDiskInfo().setWipeAfterDelete(true);
    CanDoActionTestUtils.runAndAssertCanDoActionFailure(
        command, EngineMessage.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL);
  }
  private boolean isLiveMoveCommandAvailable() {
    if (!getIsLiveStorageMigrationEnabled()) {
      return false;
    }

    VM vm = getEntity();
    if (vm == null || !vm.getStatus().isUpOrPaused() || vm.isStateless()) {
      return false;
    }

    ArrayList<Disk> disks =
        getSelectedItems() != null ? Linq.<Disk>cast(getSelectedItems()) : new ArrayList<Disk>();

    for (Disk disk : disks) {
      if (!isImageDiskOK(disk) || disk.isDiskSnapshot()) {
        return false;
      }
    }

    return true;
  }
  @Override
  protected Map<String, Pair<String, String>> getExclusiveLocks() {
    if (disk == null) {
      return null;
    }

    Map<String, Pair<String, String>> locks = new HashMap<>();
    if (!disk.isShareable()) {
      locks.put(
          disk.getId().toString(),
          LockMessagesMatchUtil.makeLockingPair(
              LockingGroup.DISK, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED));
    }

    if (disk.isBoot()) {
      locks.put(
          getParameters().getVmId().toString(),
          LockMessagesMatchUtil.makeLockingPair(
              LockingGroup.VM_DISK_BOOT, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED));
    }

    return locks;
  }
 protected VmDevice createVmDevice() {
   return new VmDevice(
       new VmDeviceId(disk.getId(), getVmId()),
       VmDeviceGeneralType.DISK,
       VmDeviceType.DISK.getName(),
       "",
       0,
       null,
       true,
       getParameters().isPlugUnPlug(),
       getParameters().isReadOnly(),
       "",
       null,
       getParameters().getSnapshotId(),
       null);
 }
  @Mapping(
      from = org.ovirt.engine.core.common.businessentities.storage.Disk.class,
      to = DiskSnapshot.class)
  public static DiskSnapshot map(
      org.ovirt.engine.core.common.businessentities.storage.Disk entity, DiskSnapshot template) {
    if (template == null) {
      template = new DiskSnapshot();
    }
    DiskSnapshot model = (DiskSnapshot) DiskMapper.map(entity, template);

    Disk disk = new Disk();
    disk.setId(entity.getId().toString());
    model.setDisk(disk);

    DiskImage diskImage = (DiskImage) entity;
    model.setId(diskImage.getImageId().toString());
    model.setImageId(null);

    return model;
  }
  @Override
  protected void executeVmCommand() {
    if (getVm().getStatus().isUpOrPaused()) {
      updateDisksFromDb();
      performPlugCommand(getPlugAction(), getDisk(), oldVmDevice);
    }

    // At this point disk is already plugged to or unplugged from VM (depends on the command),
    // so we can update the needed device properties
    updateDeviceProperties();

    // Now after updating 'isPlugged' property of the plugged/unplugged device, its time to
    // update the boot order for all VM devices. Failure to do that doesn't change the fact that
    // device is already plugged to or unplugged from VM.
    if (disk.isBoot()) {
      updateBootOrder();
    }

    getVmStaticDao().incrementDbGeneration(getVm().getId());
    setSucceeded(true);
  }
  @Test
  public void testValidateTemplateEntity() {
    disk.setVmEntityType(VmEntityType.TEMPLATE);

    StorageDomain domain = new StorageDomain();
    domain.setId(Guid.newGuid());
    domain.setStatus(StorageDomainStatus.Active);
    cmd.getParameters().setStorageDomainId(domain.getId());

    ArrayList<Guid> storageIds = new ArrayList<>();
    storageIds.add(domain.getId());
    storageIds.add(Guid.newGuid());
    ((DiskImage) disk).setStorageIds(storageIds);

    doReturn(domain).when(cmd).getStorageDomain();
    doReturn(new VmTemplate()).when(cmd).getVmTemplate();
    doReturn(true).when(cmd).checkDerivedDisksFromDiskNotExist(any(DiskImage.class));
    doReturn(disk).when(diskImageDao).get(any(Guid.class));

    ValidateTestUtils.runAndAssertValidateSuccess(cmd);
  }
  @Override
  protected boolean canDoAction() {
    if (disk == null) {
      return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST);
    }

    DiskValidator oldDiskValidator = new DiskValidator(disk);
    ValidationResult isHostedEngineDisk = oldDiskValidator.validateNotHostedEngineDisk();
    if (!isHostedEngineDisk.isValid()) {
      return validate(isHostedEngineDisk);
    }

    disk.setReadOnly(getParameters().isReadOnly());
    DiskValidator diskValidator = getDiskValidator(disk);

    if (!checkDiskUsedAsOvfStore(diskValidator)) {
      return false;
    }

    if (isOperationPerformedOnDiskSnapshot()
        && (!validate(getSnapshotsValidator().snapshotExists(getSnapshot()))
            || !validate(
                getSnapshotsValidator()
                    .snapshotTypeSupported(
                        getSnapshot(), Collections.singletonList(SnapshotType.REGULAR))))) {
      return false;
    }

    boolean isImageDisk = disk.getDiskStorageType().isInternal();

    if (isImageDisk) {
      // TODO : this load and check of the active disk will be removed
      // after inspecting upgrade
      Disk activeDisk = loadActiveDisk(disk.getId());

      if (((DiskImage) activeDisk).getImageStatus() == ImageStatus.ILLEGAL) {
        return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_DISK_OPERATION);
      }

      if (((DiskImage) disk).getImageStatus() == ImageStatus.LOCKED) {
        addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_DISKS_LOCKED);
        addCanDoActionMessageVariable("diskAliases", disk.getDiskAlias());
        return false;
      }
    }

    if (!isVmExist() || !isVmInUpPausedDownStatus()) {
      return false;
    }

    if (!canRunActionOnNonManagedVm()) {
      return false;
    }

    updateDisksFromDb();
    if (!isDiskCanBeAddedToVm(disk, getVm()) || !isDiskPassPciAndIdeLimit(disk)) {
      return false;
    }

    if (getVmDeviceDao().exists(new VmDeviceId(disk.getId(), getVmId()))) {
      return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_DISK_ALREADY_ATTACHED);
    }

    if (disk.isShareable()
        && !isVersionSupportedForShareable(
            disk,
            getStoragePoolDao()
                .get(getVm().getStoragePoolId())
                .getCompatibilityVersion()
                .getValue())) {
      return failCanDoAction(EngineMessage.ACTION_NOT_SUPPORTED_FOR_CLUSTER_POOL_LEVEL);
    }

    if (!isOperationPerformedOnDiskSnapshot() && !disk.isShareable() && disk.getNumberOfVms() > 0) {
      return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NOT_SHAREABLE_DISK_ALREADY_ATTACHED);
    }

    if (isImageDisk
        && getStoragePoolIsoMapDao()
                .get(
                    new StoragePoolIsoMapId(
                        ((DiskImage) disk).getStorageIds().get(0), getVm().getStoragePoolId()))
            == null) {
      return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_MATCH);
    }
    if (isImageDisk) {
      StorageDomain storageDomain =
          getStorageDomainDao()
              .getForStoragePool(
                  ((DiskImage) disk).getStorageIds().get(0), ((DiskImage) disk).getStoragePoolId());
      StorageDomainValidator storageDomainValidator = getStorageDomainValidator(storageDomain);
      if (!validate(storageDomainValidator.isDomainExistAndActive())) {
        return false;
      }
    }

    if (!validate(diskValidator.isReadOnlyPropertyCompatibleWithInterface())) {
      return false;
    }

    if (!validate(diskValidator.isVirtIoScsiValid(getVm()))) {
      return false;
    }

    if (!validate(diskValidator.isDiskInterfaceSupported(getVm()))) {
      return false;
    }

    if (!isVmNotInPreviewSnapshot()) {
      return false;
    }

    if (getParameters().isPlugUnPlug() && getVm().getStatus() != VMStatus.Down) {
      return canPerformDiskHotPlug(disk);
    }
    return true;
  }