private void fetchImageTemplates() {
   if (imageTemplates == null) {
     List<Disk> allImages = DbFacade.getInstance().getDiskDao().getAllForVm(getVmTemplateId());
     imageTemplates = ImagesHandler.filterImageDisks(allImages, false, false, true);
     imageTemplates.addAll(ImagesHandler.filterDisksBasedOnCinder(allImages, true));
   }
 }
 public static List<DiskImage> getCinderLeafImages(List<Disk> disks, boolean onlyPluggedDisks) {
   List<DiskImage> leafCinderDisks = new ArrayList<>();
   List<CinderDisk> cinderDisks = ImagesHandler.filterDisksBasedOnCinder(disks, onlyPluggedDisks);
   for (CinderDisk cinder : cinderDisks) {
     leafCinderDisks.add(ImagesHandler.getSnapshotLeaf(cinder.getId()));
   }
   return leafCinderDisks;
 }
  @Override
  protected void executeCommand() {
    List<DiskImage> images =
        diskImageDao.getAllSnapshotsForImageGroup(getParameters().getImageGroupID());
    ImagesHandler.sortImageList(images);
    getParameters().setImageIds(ImagesHandler.getDiskImageIds(images));

    prepareWeights(images);

    persistCommand(getParameters().getParentCommand(), getCallback() != null);
    setSucceeded(true);
  }
Example #4
0
  private boolean removeVm() {
    final List<DiskImage> diskImages =
        DisksFilter.filterImageDisks(getVm().getDiskList(), ONLY_NOT_SHAREABLE, ONLY_ACTIVE);

    final List<LunDisk> lunDisks =
        DisksFilter.filterLunDisks(getVm().getDiskMap().values(), ONLY_NOT_SHAREABLE);

    for (VmNic nic : getInterfaces()) {
      new ExternalNetworkManager(nic).deallocateIfExternal();
    }

    removeMemoryVolumes();

    TransactionSupport.executeInNewTransaction(
        () -> {
          removeVmFromDb();
          if (getParameters().isRemoveDisks()) {
            for (DiskImage image : diskImages) {
              getCompensationContext().snapshotEntityStatus(image.getImage(), ImageStatus.ILLEGAL);
              ImagesHandler.updateImageStatus(image.getImage().getId(), ImageStatus.LOCKED);
            }

            for (LunDisk lunDisk : lunDisks) {
              ImagesHandler.removeLunDisk(lunDisk);
            }

            getCompensationContext().stateChanged();
          } else {
            for (DiskImage image : diskImages) {
              imageDao.updateImageVmSnapshotId(image.getImageId(), null);
            }
          }
          return null;
        });

    Collection<DiskImage> unremovedDisks = Collections.emptyList();
    if (getParameters().isRemoveDisks()) {
      if (!diskImages.isEmpty()) {
        unremovedDisks = removeVmImages(diskImages).getActionReturnValue();
      }
      unremovedDisks.addAll(removeCinderDisks());
      if (!unremovedDisks.isEmpty()) {
        processUnremovedDisks(unremovedDisks);
        return false;
      }
    }

    vmDeleted.fire(getVmId());
    return true;
  }
Example #5
0
 @Override
 public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() {
   if (getParameters().isRemoveDisks()) {
     List<QuotaConsumptionParameter> list = new ArrayList<>();
     ImagesHandler.fillImagesBySnapshots(getVm());
     for (DiskImage disk : getVm().getDiskList()) {
       for (DiskImage snapshot : disk.getSnapshots()) {
         if (snapshot.getQuotaId() != null && !Guid.Empty.equals(snapshot.getQuotaId())) {
           if (snapshot.getActive()) {
             list.add(
                 new QuotaStorageConsumptionParameter(
                     snapshot.getQuotaId(),
                     null,
                     QuotaStorageConsumptionParameter.QuotaAction.RELEASE,
                     disk.getStorageIds().get(0),
                     (double) snapshot.getSizeInGigabytes()));
           } else {
             list.add(
                 new QuotaStorageConsumptionParameter(
                     snapshot.getQuotaId(),
                     null,
                     QuotaStorageConsumptionParameter.QuotaAction.RELEASE,
                     disk.getStorageIds().get(0),
                     snapshot.getActualSize()));
           }
         }
       }
     }
     return list;
   }
   return Collections.emptyList();
 }
  @Override
  protected void executeCommand() {
    if (getVmTemplate().isBaseTemplate()) {
      shiftBaseTemplateToSuccessor();
    }
    final List<CinderDisk> cinderDisks =
        ImagesHandler.filterDisksBasedOnCinder(
            DbFacade.getInstance().getDiskDao().getAllForVm(getVmTemplateId()));
    // Set VM to lock status immediately, for reducing race condition.
    VmTemplateHandler.lockVmTemplateInTransaction(getVmTemplateId(), getCompensationContext());

    if (!imageTemplates.isEmpty() || !cinderDisks.isEmpty()) {
      TransactionSupport.executeInNewTransaction(
          new TransactionMethod<Void>() {

            @Override
            public Void runInTransaction() {
              if (!imageTemplates.isEmpty() && removeVmTemplateImages()) {
                VmHandler.removeVmInitFromDB(getVmTemplate());
                setSucceeded(true);
              }
              if (!cinderDisks.isEmpty()) {
                removeCinderDisks(cinderDisks);
                setSucceeded(true);
              }
              return null;
            }
          });
    } else {
      // if for some reason template doesn't have images, remove it now and not in end action
      handleEndAction();
    }
  }
  @Override
  public void onFailed(Guid cmdId, List<Guid> childCmdIds) {
    super.onFailed(cmdId, childCmdIds);

    ImagesHandler.updateImageStatus(getDiskId(), ImageStatus.ILLEGAL);
    log.error("Failed extending disk. ID: {}", getDiskId());
    updateAuditLog(AuditLogType.USER_EXTEND_DISK_SIZE_FAILURE, getCommand().getNewDiskSizeInGB());

    getCommand().getParameters().setTaskGroupSuccess(false);
    getCommand().endAction();
    CommandCoordinatorUtil.removeAllCommandsInHierarchy(cmdId);
  }
 private void updateImagesStatus(ImageStatus imageStatus) {
   ImagesHandler.updateAllDiskImageSnapshotsStatusWithCompensation(
       imageGroupId, imageStatus, ImageStatus.ILLEGAL, null);
 }
Example #9
0
  @Override
  protected boolean validate() {
    if (getVm() == null) {
      return failValidation(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND);
    }

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

    if (getVm().isDeleteProtected()) {
      return failValidation(EngineMessage.ACTION_TYPE_FAILED_DELETE_PROTECTION_ENABLED);
    }

    vmHandler.updateDisksFromDb(getVm());
    getParameters()
        .setUseCinderCommandCallback(
            getParameters().isRemoveDisks() && !getCinderDisks().isEmpty());

    if (!getParameters().isRemoveDisks() && !canRemoveVmWithDetachDisks()) {
      return false;
    }

    switch (getVm().getStatus()) {
      case Unassigned:
      case Down:
      case ImageIllegal:
      case ImageLocked:
        break;
      case Suspended:
        return failValidation(EngineMessage.VM_CANNOT_REMOVE_VM_WHEN_STATUS_IS_NOT_DOWN);
      default:
        return (getVm().isHostedEngine() && isInternalExecution())
            || failValidation(EngineMessage.ACTION_TYPE_FAILED_VM_IS_RUNNING);
    }

    if (getVm().getVmPoolId() != null) {
      return failValidation(EngineMessage.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL);
    }

    // enable to remove vms without images
    SnapshotsValidator snapshotsValidator = new SnapshotsValidator();
    if (!validate(snapshotsValidator.vmNotDuringSnapshot(getVmId()))) {
      return false;
    }

    if (!getVm().getDiskMap().isEmpty()
        && !validate(new StoragePoolValidator(getStoragePool()).isUp())) {
      return false;
    }

    Collection<Disk> vmDisks = getVm().getDiskMap().values();
    List<DiskImage> vmImages =
        DisksFilter.filterImageDisks(vmDisks, ONLY_NOT_SHAREABLE, ONLY_ACTIVE);
    vmImages.addAll(DisksFilter.filterCinderDisks(vmDisks));
    if (!vmImages.isEmpty()) {
      Set<Guid> storageIds = ImagesHandler.getAllStorageIdsForImageIds(vmImages);
      MultipleStorageDomainsValidator storageValidator =
          new MultipleStorageDomainsValidator(getVm().getStoragePoolId(), storageIds);
      if (!validate(storageValidator.allDomainsExistAndActive())) {
        return false;
      }

      DiskImagesValidator diskImagesValidator = new DiskImagesValidator(vmImages);
      if (!getParameters().getForce() && !validate(diskImagesValidator.diskImagesNotLocked())) {
        return false;
      }
    }

    // Handle VM status with ImageLocked
    VmValidator vmValidator = new VmValidator(getVm());
    ValidationResult vmLockedValidatorResult = vmValidator.vmNotLocked();
    if (!vmLockedValidatorResult.isValid()) {
      // without force remove, we can't remove the VM
      if (!getParameters().getForce()) {
        return failValidation(vmLockedValidatorResult.getMessages());
      }

      // If it is force, we cannot remove if there are task
      if (CommandCoordinatorUtil.hasTasksByStoragePoolId(getVm().getStoragePoolId())) {
        return failValidation(EngineMessage.VM_CANNOT_REMOVE_HAS_RUNNING_TASKS);
      }
    }

    if (getParameters().isRemoveDisks()
        && !validate(vmValidator.vmNotHavingDeviceSnapshotsAttachedToOtherVms(false))) {
      return false;
    }

    return true;
  }
 public static boolean isVmTemplateImagesReady(
     VmTemplate vmTemplate,
     Guid storageDomainId,
     List<String> reasons,
     boolean checkImagesExists,
     boolean checkLocked,
     boolean checkIllegal,
     boolean checkStorageDomain,
     List<DiskImage> providedVmtImages) {
   boolean returnValue = true;
   List<DiskImage> vmtImages = providedVmtImages;
   if (checkStorageDomain) {
     StorageDomainValidator storageDomainValidator =
         new StorageDomainValidator(
             DbFacade.getInstance()
                 .getStorageDomainDao()
                 .getForStoragePool(storageDomainId, vmTemplate.getStoragePoolId()));
     ValidationResult res = storageDomainValidator.isDomainExistAndActive();
     returnValue = res.isValid();
     if (!returnValue) {
       reasons.add(res.getMessage().toString());
       reasons.addAll(res.getVariableReplacements());
     }
   }
   if (returnValue && checkImagesExists) {
     if (vmtImages == null) {
       vmtImages =
           ImagesHandler.filterImageDisks(
               DbFacade.getInstance().getDiskDao().getAllForVm(vmTemplate.getId()),
               false,
               false,
               true);
     }
     if (vmtImages.size() > 0
         && !ImagesHandler.isImagesExists(vmtImages, vmtImages.get(0).getStoragePoolId())) {
       reasons.add(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST.toString());
       returnValue = false;
     }
   }
   if (returnValue && checkLocked) {
     if (vmTemplate.getStatus() == VmTemplateStatus.Locked) {
       returnValue = false;
     } else {
       if (vmtImages != null) {
         for (DiskImage image : vmtImages) {
           if (image.getImageStatus() == ImageStatus.LOCKED) {
             returnValue = false;
             break;
           }
         }
       }
     }
     if (!returnValue) {
       reasons.add(EngineMessage.VM_TEMPLATE_IMAGE_IS_LOCKED.toString());
     }
   }
   if (returnValue && checkIllegal && (vmTemplate.getStatus() == VmTemplateStatus.Illegal)) {
     returnValue = false;
     reasons.add(EngineMessage.VM_TEMPLATE_IMAGE_IS_ILLEGAL.toString());
   }
   return returnValue;
 }