protected List<VmTemplate> filterNotBaseTemplates(List<VmTemplate> templates) {
    List<VmTemplate> baseTemplates = new ArrayList<VmTemplate>();
    for (VmTemplate template : templates) {
      if (template.getId().equals(template.getBaseTemplateId())) {
        baseTemplates.add(template);
        baseTemplateToSubTemplates.put(template.getId(), new ArrayList<VmTemplate>());
      }
    }

    for (VmTemplate template : templates) {
      Guid baseTemplateId = template.getBaseTemplateId();
      if (baseTemplateToSubTemplates.containsKey(baseTemplateId)) {
        baseTemplateToSubTemplates.get(baseTemplateId).add(template);
      }
    }

    for (List<VmTemplate> subversions : baseTemplateToSubTemplates.values()) {
      Collections.sort(
          subversions,
          new Comparator<VmTemplate>() {
            @Override
            public int compare(VmTemplate o1, VmTemplate o2) {
              return o2.getTemplateVersionNumber() - o1.getTemplateVersionNumber();
            }
          });
    }

    for (List<VmTemplate> subversions : baseTemplateToSubTemplates.values()) {
      subversions.add(0, createLatestTemplate(subversions.get(0)));
    }

    return baseTemplates;
  }
  @Override
  protected void init() {
    // skipped if participating in compensation flow
    if (getParameters() == null) {
      return;
    }

    Guid templateIdToUse = getParameters().getVmStaticData().getVmtGuid();
    // if set to use latest version, get it from db and use it as template
    if (getParameters().getVmStaticData().isUseLatestVersion()) {
      VmTemplate latest = getVmTemplateDao().getTemplateWithLatestVersionInChain(templateIdToUse);

      if (latest != null) {
        // if not using original template, need to override storage mappings
        // as it may have different set of disks
        if (!templateIdToUse.equals(latest.getId())) {
          getParameters().setDiskInfoDestinationMap(null);
        }

        setVmTemplate(latest);
        templateIdToUse = latest.getId();
        getParameters().getVmStaticData().setVmtGuid(templateIdToUse);
      }
    }

    setVmTemplateId(templateIdToUse);
    initTemplate();
    ensureDestinationImageMap();

    nameForVmInPoolGenerator = new NameForVmInPoolGenerator(getParameters().getVmPool().getName());
  }
 private String createSubTemplateLockMessage(VmTemplate template) {
   return String.format(
       "%s$templateName %s$templateId %s",
       EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_IS_BEING_SET_AS_BASE_TEMPLATE,
       template.getName(),
       template.getId());
 }
  protected void baseTemplateSelectedItemChanged() {
    VmTemplate baseTemplate = getModel().getBaseTemplate().getSelectedItem();
    if (baseTemplate != null) {
      List<VmTemplate> subVersions = baseTemplateToSubTemplates.get(baseTemplate.getId());
      getModel().getTemplate().setItems(new ArrayList<VmTemplate>(subVersions));

      // it's safe because in index 0 there's the latest version and
      // in index 1 the base version or the last custom version
      getModel().getTemplate().setSelectedItem(subVersions.get(1));
    }
  }
Example #5
0
  @Override
  protected void readGeneralData(XmlNode content) {
    // General Vm
    XmlNode node = content.SelectSingleNode(OvfProperties.NAME);
    if (node != null) {
      _vmTemplate.setName(node.innerText);
      name = _vmTemplate.getName();
    }
    node = content.SelectSingleNode(OvfProperties.TEMPLATE_ID);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        _vmTemplate.setId(new Guid(node.innerText));
      }
    }

    node = content.SelectSingleNode(OvfProperties.IS_DISABLED);
    if (node != null) {
      _vmTemplate.setDisabled(Boolean.parseBoolean(node.innerText));
    }

    node = content.SelectSingleNode(OvfProperties.TRUSTED_SERVICE);
    if (node != null) {
      _vmTemplate.setTrustedService(Boolean.parseBoolean(node.innerText));
    }

    node = content.SelectSingleNode(OvfProperties.TEMPLATE_TYPE);
    if (node != null) {
      _vmTemplate.setTemplateType(VmEntityType.valueOf(node.innerText));
    }

    node = content.SelectSingleNode(OvfProperties.BASE_TEMPLATE_ID);
    if (node != null) {
      _vmTemplate.setBaseTemplateId(Guid.createGuidFromString(node.innerText));
    } else {
      // in case base template is missing, we assume it is a base template
      _vmTemplate.setBaseTemplateId(_vmTemplate.getId());
    }

    node = content.SelectSingleNode(OvfProperties.TEMPLATE_VERSION_NUMBER);
    if (node != null) {
      _vmTemplate.setTemplateVersionNumber(Integer.parseInt(node.innerText));
    }

    node = content.SelectSingleNode(OvfProperties.TEMPLATE_VERSION_NAME);
    if (node != null) {
      _vmTemplate.setTemplateVersionName(node.innerText);
    }

    node = content.SelectSingleNode("AutoStartup");
    if (node != null) {
      _vmTemplate.setAutoStartup(Boolean.parseBoolean(node.innerText));
    }
  }
 /**
  * It locks direct sub-template of deleted template if it exits.
  *
  * @return true if locking was successful or there is no direct sub-template, false otherwise
  */
 private boolean tryLockSubVersionIfExists() {
   final List<VmTemplate> templateSubVersions =
       getVmTemplateDao().getTemplateVersionsForBaseTemplate(getVmTemplateId());
   if (templateSubVersions.isEmpty()) {
     return true;
   }
   baseTemplateSuccessor =
       templateSubVersions
           .stream()
           .min(Comparator.comparing(VmTemplate::getTemplateVersionNumber))
           .get();
   if (!acquireBaseTemplateSuccessorLock()) {
     return false;
   }
   if (getVmTemplateDao().get(baseTemplateSuccessor.getId()) == null) {
     return failCanDoAction(
         EngineMessage.ACTION_TYPE_FAILED_SUBVERSION_BEING_CONCURRENTLY_REMOVED,
         String.format("$subVersionId %s", baseTemplateSuccessor.getId().toString()));
   }
   return true;
 }
  private String createSearchPattern(Collection<VmTemplate> templates) {
    String vmt_guidKey = "_VMT_ID ="; // $NON-NLS-1$
    String orKey = " or "; // $NON-NLS-1$
    StringBuilder searchPattern = new StringBuilder();
    searchPattern.append("Template: "); // $NON-NLS-1$

    for (VmTemplate template : templates) {
      searchPattern.append(vmt_guidKey);
      searchPattern.append(template.getId().toString());
      searchPattern.append(orKey);
    }

    return searchPattern.substring(0, searchPattern.length() - orKey.length());
  }
  public void initDisks() {
    VmTemplate template = getModel().getTemplate().getSelectedItem();

    AsyncDataProvider.getInstance()
        .getTemplateDiskList(
            new AsyncQuery(
                getModel(),
                new INewAsyncCallback() {
                  @Override
                  public void onSuccess(Object target, Object returnValue) {

                    UnitVmModel model = (UnitVmModel) target;
                    ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue;
                    Collections.sort(disks, new Linq.DiskByAliasComparer());
                    ArrayList<DiskModel> list = new ArrayList<DiskModel>();

                    for (Disk disk : disks) {
                      DiskModel diskModel = new DiskModel();
                      diskModel.getAlias().setEntity(disk.getDiskAlias());

                      if (disk.getDiskStorageType() == DiskStorageType.IMAGE) {
                        DiskImage diskImage = (DiskImage) disk;

                        EntityModel tempVar = new EntityModel();
                        tempVar.setEntity(diskImage.getSizeInGigabytes());
                        diskModel.setSize(tempVar);
                        ListModel tempVar2 = new ListModel();
                        tempVar2.setItems(
                            (diskImage.getVolumeType() == VolumeType.Preallocated
                                ? new ArrayList<VolumeType>(
                                    Arrays.asList(new VolumeType[] {VolumeType.Preallocated}))
                                : AsyncDataProvider.getInstance().getVolumeTypeList()));
                        tempVar2.setSelectedItem(diskImage.getVolumeType());
                        diskModel.setVolumeType(tempVar2);
                        diskModel.getVolumeType().setIsAvailable(false);
                      }

                      diskModel.setDisk(disk);
                      list.add(diskModel);
                    }

                    model.setDisks(list);
                    updateIsDisksAvailable();
                    initStorageDomains();
                  }
                },
                getModel().getHash()),
            template.getId());
  }
  public void initStorageDomains() {
    if (getModel().getDisks() == null) {
      return;
    }

    VmTemplate template = getModel().getTemplate().getSelectedItem();

    if (template != null && !template.getId().equals(Guid.Empty)) {
      postInitStorageDomains();
    } else {
      getModel().getStorageDomain().setItems(new ArrayList<StorageDomain>());
      getModel().getStorageDomain().setSelectedItem(null);
      getModel().getStorageDomain().setIsChangable(false);
    }
  }
 public ValidationResult clusterNetworkNotUsedByTemplates() {
   List<VmTemplate> templatesUsingNetwork = new ArrayList<>();
   for (VmTemplate template :
       getVmTemplateDao().getAllForVdsGroup(networkCluster.getClusterId())) {
     for (VmNetworkInterface nic :
         getVmNetworkInterfaceDao().getAllForTemplate(template.getId())) {
       if (network.getName().equals(nic.getNetworkName())) {
         templatesUsingNetwork.add(template);
       }
     }
   }
   return networkNotUsed(
       templatesUsingNetwork,
       EngineMessage.VAR__ENTITIES__VM_TEMPLATES,
       EngineMessage.VAR__ENTITIES__VM_TEMPLATE);
 }
 /**
  * To prevent concurrent deletion.
  *
  * @return first: true ~ successfully locked, false otherwise; second: fail reasons in form
  *     suitable for canDoActionMessages
  */
 private boolean acquireBaseTemplateSuccessorLock() {
   final Map<String, Pair<String, String>> lockSharedMap =
       Collections.singletonMap(
           baseTemplateSuccessor.getId().toString(),
           LockMessagesMatchUtil.makeLockingPair(
               LockingGroup.TEMPLATE, createSubTemplateLockMessage(baseTemplateSuccessor)));
   baseTemplateSuccessorLock = new EngineLock(null, lockSharedMap);
   final Pair<Boolean, Set<String>> isLockedAndFailReason =
       getLockManager().acquireLock(baseTemplateSuccessorLock);
   if (isLockedAndFailReason.getFirst()) {
     return true;
   }
   baseTemplateSuccessorLock = null;
   getReturnValue()
       .getCanDoActionMessages()
       .addAll(extractVariableDeclarations(isLockedAndFailReason.getSecond()));
   return false;
 }
Example #12
0
 @Override
 public boolean Match(VmTemplate source) {
   return source.getId().equals(id);
 }
 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;
 }