@SuppressWarnings("serial")
  @Before
  public void setUp() {
    RemoveImageParameters params = new RemoveImageParameters(Guid.newGuid());
    cmd =
        spy(
            new RemoveImageCommand<RemoveImageParameters>(params) {
              @Override
              protected void initImage() {
                // Stub implementation for testing
              }

              @Override
              protected void initStoragePoolId() {
                // Stub implementation for testing
              }

              @Override
              protected void initStorageDomainId() {
                // Stub implementation for testing
              }

              @Override
              protected void initContainerDetails(ImagesContainterParametersBase parameters) {
                // Stub implementation for testing
              }
            });
    doReturn(snapshotDAO).when(cmd).getSnapshotDao();

    SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository);
  }
Пример #2
0
  protected void mockInterfaceList() {
    SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository);

    ArrayList<String> diskInterfaces =
        new ArrayList<String>(Arrays.asList(new String[] {"IDE", "VirtIO", "VirtIO_SCSI"}));

    when(osRepository.getDiskInterfaces(anyInt(), any(Version.class))).thenReturn(diskInterfaces);
  }
Пример #3
0
 public RunVmValidator(
     VM vm, RunVmParams rumVmParam, boolean isInternalExecution, Guid activeIsoDomainId) {
   this.vm = vm;
   this.runVmParam = rumVmParam;
   this.isInternalExecution = isInternalExecution;
   this.activeIsoDomainId = activeIsoDomainId;
   this.osRepository = SimpleDependecyInjector.getInstance().get(OsRepository.class);
 }
  protected void initializeCommand(UpdateVmDiskParameters params, List<VM> vms) {
    // Done before creating the spy to have correct values during the ctor run
    mockCtorRelatedDaoCalls(vms);
    command =
        spy(
            new UpdateVmDiskCommand<UpdateVmDiskParameters>(params) {
              // Overridden here and not during spying, since it's called in the constructor
              @SuppressWarnings("synthetic-access")
              @Override
              public DiskDao getDiskDao() {
                return diskDao;
              }

              @Override
              public VmDao getVmDao() {
                return vmDao;
              }
            });
    doReturn(true).when(command).acquireLockInternal();
    doReturn(snapshotDao).when(command).getSnapshotDao();
    doReturn(diskImageDao).when(command).getDiskImageDao();
    doReturn(storagePoolDao).when(command).getStoragePoolDao();
    doReturn(storageDomainStaticDao).when(command).getStorageDomainStaticDao();
    doReturn(storageDomainDao).when(command).getStorageDomainDao();
    doReturn(vmStaticDao).when(command).getVmStaticDao();
    doReturn(baseDiskDao).when(command).getBaseDiskDao();
    doReturn(imageDao).when(command).getImageDao();
    doReturn(vmDeviceDao).when(command).getVmDeviceDao();
    doReturn(vmDao).when(command).getVmDao();
    doReturn(diskDao).when(command).getDiskDao();
    doNothing().when(command).reloadDisks();
    doNothing().when(command).updateBootOrder();
    doNothing().when(vmStaticDao).incrementDbGeneration(any(Guid.class));

    SnapshotsValidator snapshotsValidator = mock(SnapshotsValidator.class);
    doReturn(snapshotsValidator).when(command).getSnapshotsValidator();
    doReturn(ValidationResult.VALID).when(snapshotsValidator).vmNotDuringSnapshot(any(Guid.class));
    doReturn(ValidationResult.VALID).when(snapshotsValidator).vmNotInPreview(any(Guid.class));
    when(diskValidator.isVirtIoScsiValid(any(VM.class))).thenReturn(ValidationResult.VALID);
    when(diskValidator.isDiskUsedAsOvfStore()).thenReturn(ValidationResult.VALID);
    doReturn(true).when(command).setAndValidateDiskProfiles();

    SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository);

    mockVds();
    mockVmsStoragePoolInfo(vms);
    mockToUpdateDiskVm(vms);

    StorageDomain sd = new StorageDomain();
    sd.setAvailableDiskSize(Integer.MAX_VALUE);
    sd.setStatus(StorageDomainStatus.Active);
    when(storageDomainDao.getForStoragePool(any(Guid.class), any(Guid.class))).thenReturn(sd);
    StorageDomainValidator sdValidator = new StorageDomainValidator(sd);
    doReturn(sdValidator).when(command).getStorageDomainValidator(any(DiskImage.class));
  }
Пример #5
0
 private void initializeCommand(Guid storageId, AddDiskParameters params) {
   params.setStorageDomainId(storageId);
   command = spy(new AddDiskCommand<AddDiskParameters>(params));
   doReturn(true).when(command).acquireLockInternal();
   doReturn(storageDomainDao).when(command).getStorageDomainDao();
   doReturn(storagePoolIsoMapDao).when(command).getStoragePoolIsoMapDao();
   doReturn(storagePoolDao).when(command).getStoragePoolDao();
   doReturn(vmNicDao).when(command).getVmNicDao();
   doReturn(diskLunMapDao).when(command).getDiskLunMapDao();
   doReturn(vmDao).when(command).getVmDao();
   doNothing().when(command).updateDisksFromDb();
   doReturn(true).when(command).checkImageConfiguration();
   doReturn(mockSnapshotValidator()).when(command).getSnapshotsValidator();
   doReturn(false).when(command).isVirtioScsiControllerAttached(any(Guid.class));
   doReturn(false).when(command).hasWatchdog(any(Guid.class));
   doReturn(false).when(command).isBalloonEnabled(any(Guid.class));
   doReturn(false).when(command).isSoundDeviceEnabled(any(Guid.class));
   doReturn(true).when(command).setAndValidateDiskProfiles();
   SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository);
 }
public abstract class VmInfoBuilderBase {

  protected static final Log log = LogFactory.getLog(VmInfoBuilderBase.class);
  protected Map<String, Object> createInfo;
  protected VM vm;
  // IDE supports only 4 slots , slot 2 is preserved by VDSM to the CDROM
  protected int[] ideIndexSlots = new int[] {0, 1, 3};

  protected OsRepository osRepository =
      SimpleDependecyInjector.getInstance().get(OsRepository.class);
  private VDSGroup vdsGroup;

  private static class DiskImageByBootAndSnapshotComparator
      implements Comparator<Disk>, Serializable {
    private static final long serialVersionUID = 4732164571328497830L;

    @Override
    public int compare(Disk o1, Disk o2) {
      Boolean boot1 = o1.isBoot();
      Boolean boot2 = o2.isBoot();
      int bootResult = boot1.compareTo(boot2);
      if (bootResult == 0 && o1.isBoot()) {
        return Boolean.compare(o2.isDiskSnapshot(), o1.isDiskSnapshot());
      }
      return bootResult;
    }
  }

  protected void buildVmProperties() {
    createInfo.put(VdsProperties.vm_guid, vm.getId().toString());
    createInfo.put(VdsProperties.vm_name, vm.getName());
    createInfo.put(VdsProperties.mem_size_mb, vm.getVmMemSizeMb());
    createInfo.put(VdsProperties.mem_guaranteed_size_mb, vm.getMinAllocatedMem());
    createInfo.put(VdsProperties.smartcardEnabled, Boolean.toString(vm.isSmartcardEnabled()));
    createInfo.put(VdsProperties.num_of_cpus, String.valueOf(vm.getNumOfCpus()));
    if (Config.<Boolean>getValue(ConfigValues.SendSMPOnRunVm)) {
      createInfo.put(VdsProperties.cores_per_socket, (Integer.toString(vm.getCpuPerSocket())));
      if (FeatureSupported.supportedInConfig(
          ConfigValues.HotPlugCpuSupported,
          vm.getVdsGroupCompatibilityVersion(),
          vm.getClusterArch())) {
        createInfo.put(
            VdsProperties.max_number_of_cpus,
            String.valueOf(
                Config.<Integer>getValue(
                    ConfigValues.MaxNumOfVmCpus, vm.getVdsGroupCompatibilityVersion().getValue())));
      }
    }
    final String compatibilityVersion = vm.getVdsGroupCompatibilityVersion().toString();
    addCpuPinning(compatibilityVersion);
    createInfo.put(VdsProperties.emulatedMachine, getVdsGroup().getEmulatedMachine());
    // send cipher suite and spice secure channels parameters only if ssl
    // enabled.
    if (Config.<Boolean>getValue(ConfigValues.SSLEnabled)) {
      createInfo.put(
          VdsProperties.spiceSslCipherSuite, Config.<String>getValue(ConfigValues.CipherSuite));
      createInfo.put(
          VdsProperties.SpiceSecureChannels,
          Config.<String>getValue(ConfigValues.SpiceSecureChannels, compatibilityVersion));
    }
    createInfo.put(VdsProperties.kvmEnable, vm.getKvmEnable().toString().toLowerCase());
    createInfo.put(VdsProperties.acpiEnable, vm.getAcpiEnable().toString().toLowerCase());

    createInfo.put(
        VdsProperties.Custom,
        VmPropertiesUtils.getInstance()
            .getVMProperties(vm.getVdsGroupCompatibilityVersion(), vm.getStaticData()));
    createInfo.put(VdsProperties.vm_type, "kvm"); // "qemu", "kvm"
    if (vm.isRunAndPause()) {
      createInfo.put(VdsProperties.launch_paused_param, "true");
    }
    if (vm.isUseHostCpuFlags()) {
      createInfo.put(VdsProperties.cpuType, "hostPassthrough");
    } else if (vm.getVdsGroupCpuFlagsData() != null) {
      createInfo.put(VdsProperties.cpuType, vm.getVdsGroupCpuFlagsData());
    }
    createInfo.put(VdsProperties.niceLevel, String.valueOf(vm.getNiceLevel()));
    if (vm.getCpuShares() > 0) {
      createInfo.put(VdsProperties.cpuShares, String.valueOf(vm.getCpuShares()));
    }
    if (!StringUtils.isEmpty(vm.getHibernationVolHandle())) {
      createInfo.put(VdsProperties.hiberVolHandle, vm.getHibernationVolHandle());
    }

    String keyboardLayout = vm.getDynamicData().getVncKeyboardLayout();
    if (keyboardLayout == null) {
      keyboardLayout = vm.getDefaultVncKeyboardLayout();
      if (keyboardLayout == null) {
        keyboardLayout = Config.<String>getValue(ConfigValues.VncKeyboardLayout);
      }
    }

    createInfo.put(VdsProperties.KeyboardLayout, keyboardLayout);
    if (osRepository.isLinux(vm.getVmOsId())) {
      createInfo.put(VdsProperties.PitReinjection, "false");
    }

    if (vm.getDisplayType() == DisplayType.vnc) {
      createInfo.put(VdsProperties.TabletEnable, "true");
    }
    createInfo.put(
        VdsProperties.transparent_huge_pages, vm.isTransparentHugePages() ? "true" : "false");
  }

  private void addCpuPinning(final String compatibilityVersion) {
    final String cpuPinning = vm.getCpuPinning();
    if (StringUtils.isNotEmpty(cpuPinning)
        && Boolean.TRUE.equals(
            Config.<Boolean>getValue(ConfigValues.CpuPinningEnabled, compatibilityVersion))) {
      final Map<String, Object> pinDict = new HashMap<String, Object>();
      for (String pin : cpuPinning.split("_")) {
        final String[] split = pin.split("#");
        pinDict.put(split[0], split[1]);
      }
      createInfo.put(VdsProperties.cpuPinning, pinDict);
    }
  }

  protected void buildVmNetworkCluster() {
    // set Display network
    List<NetworkCluster> all =
        DbFacade.getInstance().getNetworkClusterDao().getAllForCluster(vm.getVdsGroupId());
    NetworkCluster networkCluster = null;
    for (NetworkCluster tempNetworkCluster : all) {
      if (tempNetworkCluster.isDisplay()) {
        networkCluster = tempNetworkCluster;
        break;
      }
    }
    if (networkCluster != null) {
      Network net = null;
      List<Network> allNetworks = DbFacade.getInstance().getNetworkDao().getAll();
      for (Network tempNetwork : allNetworks) {
        if (tempNetwork.getId().equals(networkCluster.getNetworkId())) {
          net = tempNetwork;
          break;
        }
      }
      if (net != null) {
        createInfo.put(VdsProperties.DISPLAY_NETWORK, net.getName());
      }
    }
  }

  protected void buildVmBootOptions() {
    // Boot Options
    if (!StringUtils.isEmpty(vm.getInitrdUrl())) {
      createInfo.put(VdsProperties.InitrdUrl, vm.getInitrdUrl());
    }
    if (!StringUtils.isEmpty(vm.getKernelUrl())) {
      createInfo.put(VdsProperties.KernelUrl, vm.getKernelUrl());

      if (!StringUtils.isEmpty(vm.getKernelParams())) {
        createInfo.put(VdsProperties.KernelParams, vm.getKernelParams());
      }
    }
  }

  protected void buildVmTimeZone() {
    // get vm timezone
    String timeZone = getTimeZoneForVm(vm);

    String javaZoneId = null;
    if (osRepository.isWindows(vm.getOs())) {
      // convert to java & calculate offset
      javaZoneId = WindowsJavaTimezoneMapping.windowsToJava.get(timeZone);
    } else {
      javaZoneId = timeZone;
    }

    int offset = 0;
    if (javaZoneId != null) {
      offset = (TimeZone.getTimeZone(javaZoneId).getOffset(new Date().getTime()) / 1000);
    }
    createInfo.put(VdsProperties.utc_diff, "" + offset);
  }

  private String getTimeZoneForVm(VM vm) {
    if (!StringUtils.isEmpty(vm.getTimeZone())) {
      return vm.getTimeZone();
    }

    // else fallback to engine config default for given OS type
    if (osRepository.isWindows(vm.getOs())) {
      return Config.<String>getValue(ConfigValues.DefaultWindowsTimeZone);
    } else {
      return "Etc/GMT";
    }
  }

  protected List<Disk> getSortedDisks() {
    // order first by drive numbers and then order by boot for the bootable
    // drive to be first (important for IDE to be index 0) !
    List<Disk> diskImages = new ArrayList<Disk>(vm.getDiskMap().values());
    Collections.sort(diskImages, new DiskImageByDiskAliasComparator());
    Collections.sort(
        diskImages, Collections.reverseOrder(new DiskImageByBootAndSnapshotComparator()));
    return diskImages;
  }

  protected void logUnsupportedInterfaceType() {
    log.error("Unsupported interface type, ISCSI interface type is not supported.");
  }

  protected static void reportUnsupportedVnicProfileFeatures(
      VM vm,
      VmNic nic,
      VnicProfile vnicProfile,
      List<VNIC_PROFILE_PROPERTIES> unsupportedFeatures) {

    if (unsupportedFeatures.isEmpty()) {
      return;
    }

    AuditLogableBase event = new AuditLogableBase();
    event.setVmId(vm.getId());
    event.setVdsGroupId(vm.getVdsGroupId());
    event.setCustomId(nic.getId().toString());
    event.setCompatibilityVersion(vm.getVdsGroupCompatibilityVersion().toString());
    event.addCustomValue("NicName", nic.getName());
    event.addCustomValue("VnicProfile", vnicProfile == null ? null : vnicProfile.getName());
    String[] unsupportedFeatureNames = new String[unsupportedFeatures.size()];
    for (int i = 0; i < unsupportedFeatures.size(); i++) {
      unsupportedFeatureNames[i] = unsupportedFeatures.get(i).getFeatureName();
    }

    event.addCustomValue("UnsupportedFeatures", StringUtils.join(unsupportedFeatureNames, ", "));
    AuditLogDirector.log(event, AuditLogType.VNIC_PROFILE_UNSUPPORTED_FEATURES);
  }

  protected static VmDevice getVmDeviceByDiskId(Guid diskId, Guid vmId) {
    // get vm device for this disk from DB
    return DbFacade.getInstance().getVmDeviceDao().get(new VmDeviceId(diskId, vmId));
  }

  public void buildVmSerialNumber() {
    new VmSerialNumberBuilder(vm, getVdsGroup(), createInfo).buildVmSerialNumber();
  }

  protected abstract void buildVmVideoCards();

  protected abstract void buildVmCD();

  protected abstract void buildVmFloppy();

  protected abstract void buildVmDrives();

  protected abstract void buildVmNetworkInterfaces();

  protected abstract void buildVmSoundDevices();

  protected abstract void buildVmConsoleDevice();

  protected abstract void buildUnmanagedDevices();

  protected abstract void buildVmBootSequence();

  protected abstract void buildSysprepVmPayload(String strSysPrepContent);

  protected abstract void buildCloudInitVmPayload(Map<String, byte[]> cloudInitContent);

  protected abstract void buildVmUsbDevices();

  protected abstract void buildVmMemoryBalloon();

  protected abstract void buildVmWatchdog();

  protected abstract void buildVmVirtioScsi();

  protected static enum VNIC_PROFILE_PROPERTIES {
    PORT_MIRRORING("Port Mirroring"),
    CUSTOM_PROPERTIES("Custom Properties"),
    NETWORK_QOS("Network QoS");

    private String featureName;

    private VNIC_PROFILE_PROPERTIES(String featureName) {
      this.featureName = featureName;
    }

    public String getFeatureName() {
      return featureName;
    }
  };

  protected VDSGroup getVdsGroup() {
    if (vdsGroup == null) {
      vdsGroup = DbFacade.getInstance().getVdsGroupDao().get(vm.getVdsGroupId());
    }
    return vdsGroup;
  }
}
Пример #7
0
 private void mockMaxPciSlots() {
   SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository);
   doReturn(MAX_PCI_SLOTS).when(osRepository).getMaxPciDevices(anyInt(), any(Version.class));
 }
Пример #8
0
public class OvfTemplateReader extends OvfReader {
  protected VmTemplate _vmTemplate;
  private final OsRepository osRepository =
      SimpleDependecyInjector.getInstance().get(OsRepository.class);

  public OvfTemplateReader(
      XmlDocument document,
      VmTemplate vmTemplate,
      ArrayList<DiskImage> images,
      ArrayList<VmNetworkInterface> interfaces) {
    super(document, images, interfaces, vmTemplate);
    _vmTemplate = vmTemplate;
  }

  @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);
    }
  }

  @Override
  protected void readDiskImageItem(XmlNode node) {
    final Guid guid = new Guid(node.SelectSingleNode("rasd:InstanceId", _xmlNS).innerText);

    DiskImage image =
        LinqUtils.firstOrNull(
            _images,
            new Predicate<DiskImage>() {
              @Override
              public boolean eval(DiskImage diskImage) {
                return diskImage.getImageId().equals(guid);
              }
            });
    image.setId(
        OvfParser.GetImageGrupIdFromImageFile(
            node.SelectSingleNode("rasd:HostResource", _xmlNS).innerText));
    if (StringUtils.isNotEmpty(node.SelectSingleNode("rasd:Parent", _xmlNS).innerText)) {
      image.setParentId(new Guid(node.SelectSingleNode("rasd:Parent", _xmlNS).innerText));
    }
    if (StringUtils.isNotEmpty(node.SelectSingleNode("rasd:Template", _xmlNS).innerText)) {
      image.setImageTemplateId(new Guid(node.SelectSingleNode("rasd:Template", _xmlNS).innerText));
    }
    image.setAppList(node.SelectSingleNode("rasd:ApplicationList", _xmlNS).innerText);
    if (StringUtils.isNotEmpty(node.SelectSingleNode("rasd:StorageId", _xmlNS).innerText)) {
      image.setStorageIds(
          new ArrayList<Guid>(
              Arrays.asList(new Guid(node.SelectSingleNode("rasd:StorageId", _xmlNS).innerText))));
    }
    if (StringUtils.isNotEmpty(node.SelectSingleNode("rasd:StoragePoolId", _xmlNS).innerText)) {
      image.setStoragePoolId(
          new Guid(node.SelectSingleNode("rasd:StoragePoolId", _xmlNS).innerText));
    }
    final Date creationDate =
        OvfParser.UtcDateStringToLocaDate(
            node.SelectSingleNode("rasd:CreationDate", _xmlNS).innerText);
    if (creationDate != null) {
      image.setCreationDate(creationDate);
    }
    final Date lastModified =
        OvfParser.UtcDateStringToLocaDate(
            node.SelectSingleNode("rasd:LastModified", _xmlNS).innerText);
    if (lastModified != null) {
      image.setLastModified(lastModified);
    }
    readManagedVmDevice(node, image.getId());
  }

  @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));
    }
  }

  @Override
  protected String getDefaultDisplayTypeStringRepresentation() {
    return OvfProperties.TEMPLATE_DEFAULT_DISPLAY_TYPE;
  }
}