@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());
 }
Пример #3
0
  /**
   * @param template - the template that the latest template should be based on
   * @return template representing the latest template
   */
  private VmTemplate createLatestTemplate(VmTemplate template) {
    VmTemplate latestTemplate = new VmTemplate(template);
    latestTemplate.setTemplateVersionName(constants.latestTemplateVersionName());
    latestTemplate.setDescription(constants.latestTemplateVersionDescription());

    return latestTemplate;
  }
 @Override
 public InstanceType getInstanceType(Guid id) {
   VmTemplate result = get(id);
   if (result != null && result.getTemplateType() != VmEntityType.INSTANCE_TYPE) {
     result = null;
   }
   return result;
 }
 @Override
 public ImageType getImageType(Guid id) {
   VmTemplate result = get(id);
   if (result != null && result.getTemplateType() != VmEntityType.IMAGE_TYPE) {
     result = null;
   }
   return result;
 }
Пример #6
0
 /**
  * OvfReader can't provide proper value of {@link VmBase#maxMemorySizeMb} since it depends on
  * effective compatibility version of target cluster.
  */
 public static void updateMaxMemorySize(
     VmTemplate template, Version effectiveCompatibilityVersion) {
   if (template.getMaxMemorySizeMb() == 0) {
     final int maxMemorySize =
         VmCommonUtils.maxMemorySizeWithHotplugInMb(
             template.getOsId(), effectiveCompatibilityVersion);
     template.setMaxMemorySizeMb(maxMemorySize);
   }
 }
  @Override
  public void updateTabsData(ImportEntityData<VmTemplate> importEntityData) {
    VmTemplate vmTemplate = ((ImportTemplateData) importEntityData).getTemplate();

    templateGeneralModel.setEntity(vmTemplate);
    generalView.setMainTabSelectedItem(vmTemplate);

    disksTable.setRowData((List) Arrays.asList(vmTemplate.getDiskTemplateMap().values().toArray()));
    nicsTable.setRowData((List) Arrays.asList(vmTemplate.getInterfaces().toArray()));
  }
Пример #8
0
  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));
    }
  }
Пример #9
0
 /**
  * parses a given ovf to a VmTemplate, initialized with images and interfaces.
  *
  * @param ovf
  * @return VmTemplate that represents the given ovf data
  * @throws OvfReaderException
  */
 public VmTemplate readVmTemplateFromOvf(String ovf) throws OvfReaderException {
   ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>();
   ArrayList<VmNetworkInterface> interfaces = new ArrayList<VmNetworkInterface>();
   VmTemplate template = new VmTemplate();
   ovfManager.ImportTemplate(ovf, template, diskImages, interfaces);
   template.setInterfaces(interfaces);
   // add disk map
   for (DiskImage disk : diskImages) {
     template.getDiskTemplateMap().put(disk.getId(), disk);
   }
   return template;
 }
Пример #10
0
 @Override
 protected void readOsSection(XmlNode section) {
   _vmTemplate.setId(new Guid(section.attributes.get("ovf:id").getValue()));
   XmlNode node = section.SelectSingleNode("Description");
   if (node != null) {
     int osId = osRepository.getOsIdByUniqueName(node.innerText);
     _vmTemplate.setOsId(osId);
     _vmTemplate.setClusterArch(osRepository.getArchitectureFromOS(osId));
   } else {
     _vmTemplate.setClusterArch(ArchitectureType.undefined);
   }
 }
Пример #11
0
 private VmTemplate createVmTemplate() {
   if (vmTemplate == null) {
     vmTemplate = new VmTemplate();
     vmTemplate.setStoragePoolId(STORAGE_POOL_ID);
     DiskImage image = createDiskImageTemplate();
     vmTemplate.getDiskTemplateMap().put(image.getImageId(), image);
     HashMap<Guid, DiskImage> diskImageMap = new HashMap<>();
     DiskImage diskImage = createDiskImage(REQUIRED_DISK_SIZE_GB);
     diskImageMap.put(diskImage.getId(), diskImage);
     vmTemplate.setDiskImageMap(diskImageMap);
   }
   return vmTemplate;
 }
Пример #12
0
 private void loadVmData(VM vm) {
   if (vm.getInterfaces().isEmpty()) {
     vm.setInterfaces(getDbFacade().getVmNetworkInterfaceDao().getAllForVm(vm.getId()));
   }
   if (StringUtils.isEmpty(vm.getVmtName())) {
     if (!Guid.Empty.equals(vm.getVmtGuid())) {
       VmTemplate t = getDbFacade().getVmTemplateDao().get(vm.getVmtGuid());
       vm.setVmtName(t.getName());
     } else {
       vm.setVmtName(VmTemplateHandler.BLANK_VM_TEMPLATE_NAME);
     }
   }
 }
  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());
  }
Пример #14
0
  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());
  }
 @Override
 protected void initDisksStorageDomainsList() {
   for (Object item : getItems()) {
     VmTemplate template = ((ImportTemplateData) item).getTemplate();
     for (Disk disk : template.getDiskList()) {
       DiskImage diskImage = (DiskImage) disk;
       addDiskImportData(
           diskImage.getId(),
           filteredStorageDomains,
           diskImage.getVolumeType(),
           new EntityModel(true));
     }
   }
   postInitDisks();
 }
Пример #16
0
  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);
    }
  }
Пример #17
0
  public static void fillImagesMapBasedOnTemplate(
      VmTemplate template,
      List<StorageDomain> domains,
      Map<Guid, DiskImage> diskInfoDestinationMap,
      Map<Guid, StorageDomain> destStorages) {
    Map<Guid, StorageDomain> storageDomainsMap = new HashMap<>();
    for (StorageDomain storageDomain : domains) {
      StorageDomainValidator validator = new StorageDomainValidator(storageDomain);
      if (validator.isDomainExistAndActive().isValid()
          && validator.domainIsValidDestination().isValid()) {
        storageDomainsMap.put(storageDomain.getId(), storageDomain);
      }
    }
    for (DiskImage image : template.getDiskTemplateMap().values()) {
      for (Guid storageId : image.getStorageIds()) {
        if (storageDomainsMap.containsKey(storageId)) {
          ArrayList<Guid> storageIds = new ArrayList<>();
          storageIds.add(storageId);
          image.setStorageIds(storageIds);
          diskInfoDestinationMap.put(image.getId(), image);
          break;
        }
      }
    }

    if (destStorages != null) {
      for (DiskImage diskImage : diskInfoDestinationMap.values()) {
        Guid storageDomainId = diskImage.getStorageIds().get(0);
        destStorages.put(storageDomainId, storageDomainsMap.get(storageDomainId));
      }
    }
  }
 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);
 }
  /**
   * Generate a string containing the given VM's configuration.
   *
   * @param vm The VM to generate configuration from.
   * @return A String containing the VM configuration.
   */
  protected String generateVmConfiguration(VM vm) {
    if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) {
      vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId()));
    }

    if (StringHelper.isNullOrEmpty(vm.getvmt_name())) {
      VmTemplate t = getVmTemplateDao().get(vm.getvmt_guid());
      vm.setvmt_name(t.getname());
    }

    RefObject<String> tempRefObject = new RefObject<String>("");
    new OvfManager()
        .ExportVm(
            tempRefObject, vm, new ArrayList<DiskImage>(getDiskImageDao().getAllForVm(vm.getId())));
    return tempRefObject.argvalue;
  }
Пример #20
0
 /**
  * The following method will find all images and storages where they located for provide template
  * and will fill an diskInfoDestinationMap by imageId mapping on active storage id where image is
  * located. The second map is mapping of founded storage ids to storage object
  */
 public static void fillImagesMapBasedOnTemplate(
     VmTemplate template,
     Map<Guid, DiskImage> diskInfoDestinationMap,
     Map<Guid, StorageDomain> destStorages) {
   List<StorageDomain> domains =
       DbFacade.getInstance()
           .getStorageDomainDao()
           .getAllForStoragePool(template.getStoragePoolId());
   fillImagesMapBasedOnTemplate(template, domains, diskInfoDestinationMap, destStorages);
 }
 /**
  * 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;
 }
Пример #22
0
  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 MapSqlParameterSource createFullParametersMapper(VmTemplate template) {
   return createBaseParametersMapper(template)
       .addValue("child_count", template.getChildCount())
       .addValue("name", template.getName())
       .addValue("status", template.getStatus())
       .addValue("is_disabled", template.isDisabled())
       .addValue("template_type", template.getTemplateType().name())
       .addValue("base_template_id", template.getBaseTemplateId())
       .addValue("template_version_name", template.getTemplateVersionName());
 }
    @Override
    public VdcActionParametersBase getParameters(VmPool incoming, vm_pools current) {
      int currentVmCount = current.getvm_assigned_count();
      vm_pools entity = map(incoming, current);

      VM vm = mapToVM(map(entity));

      int size =
          incoming.isSetSize() && incoming.getSize() > currentVmCount
              ? incoming.getSize() - currentVmCount
              : 0;

      if (incoming.isSetTemplate()) {
        vm.setvmt_guid(new Guid(incoming.getTemplate().getId()));
      } else {
        VM existing =
            currentVmCount > 0
                ? getEntity(VM.class, SearchType.VM, "Vms: pool=" + incoming.getName())
                : null;
        if (existing != null) {
          vm.setvmt_guid(existing.getvmt_guid());
        }
      }

      if (vm.getvmt_guid() != null) {
        VmTemplate template =
            getEntity(
                VmTemplate.class,
                VdcQueryType.GetVmTemplate,
                new GetVmTemplateParameters(vm.getvm_guid()),
                vm.getvm_guid().toString());
        vm.getStaticData().setmem_size_mb(template.getmem_size_mb());
      }

      AddVmPoolWithVmsParameters parameters = new AddVmPoolWithVmsParameters(entity, vm, size, -1);
      parameters.setStorageDomainId(getStorageDomainId(vm.getvmt_guid()));
      return parameters;
    }
Пример #25
0
  @Mapping(from = VmTemplate.class, to = Display.class)
  public static Display map(VmTemplate vmTemplate, Display display) {
    Display result = (display == null) ? new Display() : display;

    result.setMonitors(vmTemplate.getNumOfMonitors());
    result.setSingleQxlPci(vmTemplate.getSingleQxlPci());
    result.setAllowOverride(vmTemplate.isAllowConsoleReconnect());
    result.setSmartcardEnabled(vmTemplate.isSmartcardEnabled());
    result.setKeyboardLayout(vmTemplate.getVncKeyboardLayout());
    result.setFileTransferEnabled(vmTemplate.isSpiceFileTransferEnabled());
    result.setCopyPasteEnabled(vmTemplate.isSpiceCopyPasteEnabled());

    return result;
  }
 /**
  * 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;
 }
Пример #27
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));
    }
  }
Пример #28
0
 @Override
 public boolean Match(VmTemplate source) {
   return source.getId().equals(id);
 }
Пример #29
0
 @Override
 public int compare(VmTemplate x, VmTemplate y) {
   return x.getname().compareTo(y.getname());
 }
    @Override
    public VmTemplate mapRow(ResultSet rs, int rowNum) throws SQLException {
      final VmTemplate entity = new VmTemplate();
      map(rs, entity);

      entity.setId(getGuidDefaultEmpty(rs, "vmt_guid"));
      entity.setChildCount(rs.getInt("child_count"));
      entity.setName(rs.getString("name"));
      entity.setVdsGroupId(getGuid(rs, "vds_group_id"));
      entity.setAllowConsoleReconnect(rs.getBoolean("allow_console_reconnect"));
      entity.setStatus(VmTemplateStatus.forValue(rs.getInt("status")));
      entity.setVdsGroupName(rs.getString("vds_group_name"));
      entity.setStoragePoolId(getGuid(rs, "storage_pool_id"));
      entity.setStoragePoolName(rs.getString("storage_pool_name"));
      entity.setQuotaName(rs.getString("quota_name"));
      entity.setQuotaEnforcementType(
          QuotaEnforcementTypeEnum.forValue(rs.getInt("quota_enforcement_type")));
      entity.setDisabled(rs.getBoolean("is_disabled"));
      entity.setTrustedService(rs.getBoolean("trusted_service"));
      entity.setTemplateType(VmEntityType.valueOf(rs.getString("entity_type")));
      entity.setClusterArch(ArchitectureType.forValue(rs.getInt("architecture")));
      entity.setBaseTemplateId(getGuidDefaultEmpty(rs, "base_template_id"));
      entity.setTemplateVersionNumber(rs.getInt("template_version_number"));
      entity.setTemplateVersionName(rs.getString("template_version_name"));
      return entity;
    }