@Test
  public void testRemoveImageFromSnapshotConfiguration() throws OvfReaderException {
    Guid vmId = Guid.newGuid();
    VM vm = new VM();
    vm.setId(vmId);
    vm.setStoragePoolId(Guid.newGuid());
    vm.setVmtName(RandomUtils.instance().nextString(10));
    vm.setOrigin(OriginType.OVIRT);
    vm.setDbGeneration(1L);
    Guid vmSnapshotId = Guid.newGuid();

    DiskImage disk1 = addTestDisk(vm, vmSnapshotId);
    DiskImage disk2 = addTestDisk(vm, vmSnapshotId);

    OvfManager ovfManager = new OvfManager();
    ArrayList<DiskImage> disks = new ArrayList<DiskImage>(Arrays.asList(disk1, disk2));
    String ovf = ovfManager.ExportVm(vm, disks, Version.v3_1);
    Snapshot snap = new Snapshot();
    snap.setVmConfiguration(ovf);
    snap.setId(vmSnapshotId);

    when(snapshotDAO.get(vmSnapshotId)).thenReturn(snap);
    doReturn(disk2).when(cmd).getDiskImage();
    doReturn(disk2).when(cmd).getImage();
    doReturn(disk2.getId()).when(cmd).getImageId();
    Snapshot actual =
        cmd.prepareSnapshotConfigWithoutImageSingleImage(vmSnapshotId, disk2.getImageId());
    String actualOvf = actual.getVmConfiguration();

    ArrayList<DiskImage> actualImages = new ArrayList<DiskImage>();
    ovfManager.ImportVm(actualOvf, new VM(), actualImages, new ArrayList<VmNetworkInterface>());
    assertEquals("Wrong number of disks", 1, actualImages.size());
    assertEquals("Wrong disk", disk1, actualImages.get(0));
  }
 @Override
 protected MapSqlParameterSource createFullParametersMapper(CommandEntity entity) {
   return getCustomMapSqlParameterSource()
       .addValue(
           "user_id", Guid.isNullOrEmpty(entity.getUserId()) ? Guid.Empty : entity.getUserId())
       .addValue("command_id", Guid.isNullOrEmpty(entity.getId()) ? Guid.Empty : entity.getId())
       .addValue("command_type", entity.getCommandType().getValue())
       .addValue("parent_command_id", entity.getParentCommandId())
       .addValue(
           "root_command_id",
           Guid.isNullOrEmpty(entity.getRootCommandId()) ? Guid.Empty : entity.getRootCommandId())
       .addValue("job_id", Guid.isNullOrEmpty(entity.getJobId()) ? Guid.Empty : entity.getJobId())
       .addValue(
           "step_id", Guid.isNullOrEmpty(entity.getStepId()) ? Guid.Empty : entity.getStepId())
       .addValue("command_parameters", serializeParameters(entity.getCommandParameters()))
       .addValue(
           "command_params_class",
           entity.getCommandParameters() == null
               ? null
               : entity.getCommandParameters().getClass().getName())
       .addValue("created_at", entity.getCreatedAt())
       .addValue("status", entity.getCommandStatus().toString())
       .addValue("executed", entity.isExecuted())
       .addValue("callback_enabled", entity.isCallbackEnabled())
       .addValue("return_value", serializeReturnValue(entity.getReturnValue()))
       .addValue(
           "return_value_class",
           entity.getReturnValue() == null ? null : entity.getReturnValue().getClass().getName());
 }
Example #3
0
  protected boolean initVdss() {
    setVdsIdRef(getVm().getRunOnVds());
    Guid vdsToRunOn =
        schedulingManager.schedule(
            getVdsGroup(),
            getVm(),
            getVdsBlackList(),
            getVdsWhiteList(),
            getDestinationHostList(),
            new ArrayList<String>(),
            new VdsFreeMemoryChecker(this),
            getCorrelationId());
    setDestinationVdsId(vdsToRunOn);
    if (vdsToRunOn != null && !Guid.Empty.equals(vdsToRunOn)) {
      getRunVdssList().add(vdsToRunOn);
    }
    VmHandler.updateVmGuestAgentVersion(getVm());

    if (vdsToRunOn != null && vdsToRunOn.equals(Guid.Empty)) {
      return false;
    }

    if (getDestinationVds() == null || getVds() == null) {
      return false;
    }

    return true;
  }
  @Before
  public void setUp() {
    cpuProfile1.setId(Guid.newGuid());
    cpuProfile1.setClusterId(CLUSTER_ID);
    cpuProfile1.setName("CpuProfile 1");

    cpuProfile2.setId(Guid.newGuid());
    cpuProfile2.setClusterId(CLUSTER_ID);
    cpuProfile2.setName("CpuProfile 2");

    when(cpuProfileDao.get(cpuProfile1.getId())).thenReturn(cpuProfile1);
    when(cpuProfileDao.get(cpuProfile2.getId())).thenReturn(cpuProfile2);
    when(cpuProfileDao.getAllForCluster(CLUSTER_ID))
        .thenReturn(Arrays.asList(cpuProfile1, cpuProfile2));

    when(permissionDao.getEntityPermissions(
            USER_1_ID,
            ActionGroup.ASSIGN_CPU_PROFILE,
            cpuProfile1.getId(),
            VdcObjectType.CpuProfile))
        .thenReturn(Guid.newGuid());

    when(permissionDao.getEntityPermissions(
            USER_2_ID,
            ActionGroup.ASSIGN_CPU_PROFILE,
            cpuProfile2.getId(),
            VdcObjectType.CpuProfile))
        .thenReturn(Guid.newGuid());
  }
Example #5
0
  private static List<VdsNumaNode> createTestVdsNumaNodes() {

    NumaNodeStatistics newNodeStatistics = new NumaNodeStatistics();
    newNodeStatistics.setCpuUsagePercent(20);
    newNodeStatistics.setMemUsagePercent(50);

    List<VdsNumaNode> newVdsNodes = new ArrayList<>();

    VdsNumaNode newVdsNumaNode = new VdsNumaNode();
    newVdsNumaNode.setCpuIds(generateCpuList(0, 4));
    newVdsNumaNode.setId(Guid.newGuid());
    newVdsNumaNode.setIndex(0);
    newVdsNumaNode.setNumaNodeDistances(generateDistance(2, 0));
    newVdsNumaNode.setNumaNodeStatistics(newNodeStatistics);
    newVdsNodes.add(newVdsNumaNode);

    newVdsNumaNode = new VdsNumaNode();
    newVdsNumaNode.setCpuIds(generateCpuList(4, 4));
    newVdsNumaNode.setId(Guid.newGuid());
    newVdsNumaNode.setIndex(1);
    newVdsNumaNode.setNumaNodeDistances(generateDistance(2, 1));
    newVdsNumaNode.setNumaNodeStatistics(newNodeStatistics);
    newVdsNodes.add(newVdsNumaNode);

    return newVdsNodes;
  }
  /**
   * Checks if the user needs additional permissions in order to connect to the console.
   *
   * @return <code>true</code> if additional permissions are needed, <code>false</code> otherwise
   */
  private boolean needPermissionForConnectingToConsole() {
    // Check if the virtual machine has the flag that allows forced connection to
    // any user, in that case no additional permission is needed:
    final VM vm = getVm();
    if (vm == null || vm.getAllowConsoleReconnect()) {
      return false;
    }

    // If this is not the first user to connect to the console then it does need
    // additional permissions:
    final Guid currentId = getCurrentUser().getId();
    final Guid previousId = vm.getConsoleUserId();
    if (previousId != null && !previousId.equals(currentId)) {
      log.warn(
          "User '{}' is trying to take the console of virtual machine '{}', but the console is already"
              + " taken by user '{}'.",
          currentId,
          vm.getId(),
          previousId);
      return true;
    }

    // If we are here then the user is the first to connect to the console, so no
    // additional permissions are needed:
    return false;
  }
  @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());
  }
Example #8
0
  @Override
  public VM update(VM incoming) {
    validateEnums(VM.class, incoming);
    validateParameters(incoming);
    if (incoming.isSetCluster()
        && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) {
      Guid clusterId = lookupClusterId(incoming);
      if (!clusterId.toString().equals(get().getCluster().getId())) {
        performAction(
            VdcActionType.ChangeVMCluster, new ChangeVMClusterParameters(clusterId, guid));
      }
    }
    if (!isFiltered()) {
      if (incoming.isSetPlacementPolicy()) {
        parent.validateAndUpdateHostsInPlacementPolicy(incoming.getPlacementPolicy());
      }
    } else {
      incoming.setPlacementPolicy(null);
    }

    VM vm =
        performUpdate(
            incoming,
            new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class),
            VdcActionType.UpdateVm,
            new UpdateParametersProvider());

    if (vm != null) {
      DisplayHelper.adjustDisplayData(this, vm);
      removeRestrictedInfo(vm);
    }

    return vm;
  }
Example #9
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) {
     return true;
   }
   if (obj == null) {
     return false;
   }
   if (!(obj instanceof NetworkClusterId)) {
     return false;
   }
   NetworkClusterId other = (NetworkClusterId) obj;
   if (clusterId == null) {
     if (other.clusterId != null) {
       return false;
     }
   } else if (!clusterId.equals(other.clusterId)) {
     return false;
   }
   if (networkId == null) {
     if (other.networkId != null) {
       return false;
     }
   } else if (!networkId.equals(other.networkId)) {
     return false;
   }
   return true;
 }
  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());
  }
  @Test
  public void testImport() throws Exception {
    setUpEntityQueryExpectations(
        VdcQueryType.GetStoragePoolsByStorageDomainId,
        IdQueryParameters.class,
        new String[] {"Id"},
        new Object[] {DESTINATION_DOMAIN_ID},
        getStoragePoolList());

    setUriInfo(
        setUpActionExpectations(
            VdcActionType.ImportRepoImage,
            ImportRepoImageParameters.class,
            new String[] {
              "SourceRepoImageId", "SourceStorageDomainId", "StoragePoolId", "StorageDomainId"
            },
            new Object[] {IMAGE_ID.toString(), DOMAIN_ID, STORAGE_POOL_ID, DESTINATION_DOMAIN_ID},
            true,
            true,
            null,
            null,
            true));

    Action action = new Action();
    action.setStorageDomain(new StorageDomain());
    action.getStorageDomain().setId(DESTINATION_DOMAIN_ID.toString());

    verifyActionResponse(
        resource.doImport(action), "storagedomains/" + DOMAIN_ID + "/images/" + IMAGE_ID, false);
  }
Example #12
0
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (autoStartup ? 1231 : 1237);
    result = prime * result + (autosuspend ? 1231 : 1237);
    result = prime * result + cpusPerSocket;
    result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
    result = prime * result + ((defaultBootSequence == null) ? 0 : defaultBootSequence.hashCode());
    result = prime * result + ((description == null) ? 0 : description.hashCode());
    result = prime * result + ((domain == null) ? 0 : domain.hashCode());
    result = prime * result + (fail_back ? 1231 : 1237);
    result = prime * result + ((hypervisorType == null) ? 0 : hypervisorType.hashCode());
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    result = prime * result + ((initrdUrl == null) ? 0 : initrdUrl.hashCode());
    result = prime * result + ((isoPath == null) ? 0 : isoPath.hashCode());
    result = prime * result + ((kernelParams == null) ? 0 : kernelParams.hashCode());
    result = prime * result + ((kernelUrl == null) ? 0 : kernelUrl.hashCode());
    result = prime * result + ((mOs == null) ? 0 : mOs.hashCode());
    result = prime * result + memSizeMB;
    result = prime * result + niceLevel;
    result = prime * result + numOfSockets;
    result = prime * result + numOfMonitors;
    result = prime * result + ((operationMode == null) ? 0 : operationMode.hashCode());
    result = prime * result + ((origin == null) ? 0 : origin.hashCode());
    result = prime * result + priority;
    result = prime * result + (stateless ? 1231 : 1237);
    result = prime * result + ((timezone == null) ? 0 : timezone.hashCode());
    result = prime * result + ((usbPolicy == null) ? 0 : usbPolicy.hashCode());
    result = prime * result + ((vds_group_id == null) ? 0 : vds_group_id.hashCode());
    result = prime * result + ((vmType == null) ? 0 : vmType.hashCode());
    result = prime * result + ((quotaId == null) ? 0 : quotaId.hashCode());

    return result;
  }
Example #13
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((clusterId == null) ? 0 : clusterId.hashCode());
   result = prime * result + ((networkId == null) ? 0 : networkId.hashCode());
   return result;
 }
 private DiskImage createDiskImage(boolean active) {
   DiskImage di = new DiskImage();
   di.setId(Guid.newGuid());
   di.setImageId(Guid.newGuid());
   di.setParentId(Guid.newGuid());
   di.setImageStatus(ImageStatus.OK);
   di.setActive(active);
   return di;
 }
Example #15
0
 @Override
 public void save(Cluster group) {
   Guid id = group.getId();
   if (Guid.isNullOrEmpty(id)) {
     id = Guid.newGuid();
     group.setId(id);
   }
   getCallsHandler().executeModification("InsertCluster", getClusterParamSource(group));
 }
 private DiskImage createDiskSnapshot(Guid diskId) {
   DiskImage di = new DiskImage();
   di.setActive(false);
   di.setId(diskId);
   di.setImageId(Guid.newGuid());
   di.setParentId(Guid.newGuid());
   di.setImageStatus(ImageStatus.OK);
   return di;
 }
Example #17
0
 private static DiskImage createDiskImage(int size) {
   DiskImage diskImage = new DiskImage();
   diskImage.setSizeInGigabytes(size);
   diskImage.setActualSize(size);
   diskImage.setId(Guid.newGuid());
   diskImage.setImageId(Guid.newGuid());
   diskImage.setStorageIds(new ArrayList<>(Collections.singletonList(STORAGE_DOMAIN_ID_1)));
   return diskImage;
 }
  @Test
  public void testAddValueGuid() {
    Guid guid = new Guid(UUID.randomUUID());

    paramSource.addValue(paramName, guid);
    assertEquals(
        "wrong value returned from parameter source",
        guid.getUuid(),
        paramSource.getValue(paramName));
  }
  /** @return A disk to add to the VM */
  private static DiskImage mockDisk() {
    // Prepare the disk
    Guid diskGuid = Guid.newGuid();
    Guid itGuid = Guid.newGuid();
    final DiskImage expectedDisk = new DiskImage();
    expectedDisk.setImageId(diskGuid);
    expectedDisk.setImageTemplateId(itGuid);

    return expectedDisk;
  }
 @Override
 public void save(VdsStatic vds) {
   Guid id = vds.getId();
   if (Guid.isNullOrEmpty(id)) {
     id = Guid.newGuid();
     vds.setId(id);
   }
   new SimpleJdbcCall(jdbcTemplate)
       .withProcedureName("InsertVdsStatic")
       .execute(getInsertOrUpdateParams(vds));
 }
Example #21
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((quotaId == null) ? 0 : quotaId.hashCode());
   result = prime * result + ((quotaStorageId == null) ? 0 : quotaStorageId.hashCode());
   result = prime * result + ((storageId == null) ? 0 : storageId.hashCode());
   result =
       prime * result + ((storageLimitGigaByte == null) ? 0 : storageLimitGigaByte.hashCode());
   return result;
 }
 @Test
 public void testInterfaceInHostWhenInDifferentHost() throws Exception {
   VdsNetworkInterface vdsNetworkInterface = createVdsNetworkInterfaceWithName();
   vdsNetworkInterface.setVdsId(Guid.newGuid());
   Guid hostId = Guid.newGuid();
   final EngineMessage engineMessage = EngineMessage.NIC_NOT_EXISTS_ON_HOST;
   Matcher<ValidationResult> matcher =
       failsWith(
           engineMessage,
           ReplacementUtils.getVariableAssignmentString(engineMessage, hostId.toString()));
   assertThat(new HostInterfaceValidator(vdsNetworkInterface).interfaceInHost(hostId), matcher);
 }
  @Test
  public void testCredentialsWithConnectionExtensionDifferentHostSameTarget() {
    StorageServerConnections conn =
        createConnectionWithCredentials("target1", "userConn", "pwdConn");
    StorageServerConnectionExtension connExt =
        createConnectionExtension(Guid.newGuid(), "target1", "userConnExt", "pwdConnExt");
    when(connExtDaoMock.getByHostIdAndTarget(Guid.newGuid(), connExt.getIqn())).thenReturn(connExt);

    Pair<String, String> credentials =
        helper.getStorageConnectionCredentialsForhost(connExt.getHostId(), conn);
    assertCredentials(credentials, conn.getuser_name(), conn.getpassword());
  }
Example #24
0
 protected List<DiskImage> createDiskSnapshot(Guid diskId, int numOfImages) {
   List<DiskImage> disksList = new ArrayList<>();
   for (int i = 0; i < numOfImages; ++i) {
     DiskImage diskImage = new DiskImage();
     diskImage.setActive(false);
     diskImage.setId(diskId);
     diskImage.setImageId(Guid.newGuid());
     diskImage.setParentId(Guid.newGuid());
     diskImage.setImageStatus(ImageStatus.OK);
     disksList.add(diskImage);
   }
   return disksList;
 }
 private void updateActionAvailability() {
   getRemoveCommand()
       .setIsExecutionAllowed((getSelectedItems() != null && getSelectedItems().size() > 0));
   if (getRemoveCommand().getIsExecutionAllowed() == false) {
     return;
   }
   Guid entityGuid = getEntityGuid();
   for (Object p : getSelectedItems()) {
     if (!entityGuid.equals(((Permissions) p).getObjectId())) {
       getRemoveCommand().setIsExecutionAllowed(false);
       return;
     }
   }
 }
 public LiveSnapshotMemoryImageBuilder(
     VM vm,
     Guid storageDomainId,
     StoragePool storagePool,
     TaskHandlerCommand<?> enclosingCommand) {
   this.vm = vm;
   this.enclosingCommand = enclosingCommand;
   this.storageDomainId = storageDomainId;
   this.storagePool = storagePool;
   this.memoryDumpImageGroupId = Guid.newGuid();
   this.memoryDumpVolumeId = Guid.newGuid();
   this.vmConfImageGroupId = Guid.newGuid();
   this.vmConfVolumeId = Guid.newGuid();
 }
Example #27
0
  @Test
  public void testImagesSubtract() {
    disk1.setId(Guid.newGuid());
    disk2.setId(Guid.newGuid());
    disk3.setId(Guid.newGuid());

    List<DiskImage> list1 = new ArrayList<>(Arrays.asList(disk1, disk2, disk3));
    List<DiskImage> list2 = new ArrayList<>(Arrays.asList(disk2, disk3));

    List<DiskImage> intersection = ImagesHandler.imagesSubtract(list1, list2);

    assertEquals("Intersection should contain only one disk", intersection.size(), 1);
    assertTrue("Intersection should contains disk1", intersection.contains(disk1));
  }
Example #28
0
  @Test
  public void testGetAllStorageIdsForImageIds() {
    Guid sdIdShared = Guid.newGuid();
    Guid sdId1 = Guid.newGuid();
    Guid sdId2 = Guid.newGuid();

    disk1.setStorageIds(new ArrayList<Guid>(Arrays.asList(sdId1, sdIdShared)));
    disk2.setStorageIds(new ArrayList<Guid>(Arrays.asList(sdId2, sdIdShared)));

    Set<Guid> result = ImagesHandler.getAllStorageIdsForImageIds(Arrays.asList(disk1, disk2));

    assertEquals("Wrong number of Guids returned", 3, result.size());
    assertTrue("Wrong Guids returned", result.containsAll(Arrays.asList(sdId1, sdId2, sdIdShared)));
  }
  @Test
  public void canDoActionSucceedsOnDiskDomainCheckWhenStorageGuidInParamsMismatches()
      throws Exception {
    Guid storageId = Guid.newGuid();
    initializeCommand(storageId);

    mockVmWithDisk(Guid.newGuid());
    mockStorageDomain(storageId);
    mockStoragePoolIsoMap();
    mockInterfaceList();
    mockMaxPciSlots();

    assertTrue(command.canDoAction());
  }
 @Before
 @Override
 public void setUp() throws Exception {
   super.setUp();
   vmID = Guid.newGuid();
   Guid snapshotId = Guid.newGuid();
   pluggedDisk = createDiskImage(true);
   unpluggedDisk = createDiskImage(true);
   pluggedDiskSnapshot = createDiskImage(false);
   pluggedDiskSnapshot.setVmSnapshotId(snapshotId);
   unpluggedDiskSnapshot = createDiskImage(false);
   unpluggedDiskSnapshot.setVmSnapshotId(snapshotId);
   setUpDaoMocks();
 }