示例#1
0
 public static Version SelectHighestVersion(ArrayList<Version> versions) {
   Version retVersion = FirstOrDefault(versions);
   for (Version version : versions) {
     if (version.compareTo(retVersion) > 0) {
       retVersion = version;
     }
   }
   return retVersion;
 }
 private boolean isRngDeviceSupported(UnitVmModel model) {
   Version clusterVersion = clusterVersionOrNull(model);
   return clusterVersion == null
       ? false
       : (Boolean)
           AsyncDataProvider.getInstance()
               .getConfigValuePreConverted(
                   ConfigurationValues.VirtIoRngDeviceSupported, clusterVersion.getValue());
 }
  @Test
  public void testAddValueVersion() {
    Version verision = new Version(this.random.nextInt(), this.random.nextInt());

    paramSource.addValue(paramName, verision);
    assertEquals(
        "wrong value returned from parameter source",
        verision.toString(),
        paramSource.getValue(paramName));
  }
示例#4
0
 private void clusterHasVds() {
   VDS vds = new VDS();
   vds.setStatus(VDSStatus.Up);
   vds.setSupportedClusterLevels(VERSION_1_1.toString());
   List<VDS> vdsList = new ArrayList<>();
   vdsList.add(vds);
   when(vdsDao.getAllForCluster(any(Guid.class))).thenReturn(vdsList);
 }
示例#5
0
  /** Returns a friendly version, for example 4.4.x.x returned as 2.1.x.x. */
  public static Version GetFriendlyVersion(Version source) {
    if (source != null) {
      int major = source.getMajor();
      int minor = source.getMinor();

      if (major == 4 && minor == 4) {
        major = 2;
        minor = 1;
      } else if (major == 4 && minor == 5) {
        major = 2;
        minor = 2;
      } else if (major == 4 && minor == 9) {
        major = 3;
        minor = 0;
      } else if (major == 4 && minor == 10) {
        major = 3;
        minor = 1;
      }
      if (source.getBuild() == -1) {
        return new Version(major, minor);
      }
      if (source.getRevision() == -1) {
        return new Version(major, minor, source.getBuild());
      }
      return new Version(major, minor, source.getBuild(), source.getRevision());
    }
    return new Version();
  }
  @Before
  public void setupMocks() {
    when(dbFacade.getVdsDao()).thenReturn(vdsDao);

    when(vdsDao.get(eq(TARGET_HOST_ID))).thenReturn(targetHost);
    when(targetHost.getId()).thenReturn(TARGET_HOST_ID);

    when(vdsDao.get(eq(PROXY_HOST_ID))).thenReturn(proxyHost);
    when(proxyHost.getId()).thenReturn(PROXY_HOST_ID);
    when(proxyHost.getVdsGroupCompatibilityVersion()).thenReturn(Version.getLast());
  }
  private void assertQueryExecution(
      ConfigurationValues configValue, boolean isFiltered, boolean shouldSucceed) {
    // Mock the parameters
    Version version = RandomUtils.instance().pickRandom(Version.ALL);
    when(getQueryParameters().getVersion()).thenReturn(version.toString());
    when(getQueryParameters().getConfigValue()).thenReturn(configValue);
    when(getQueryParameters().isFiltered()).thenReturn(isFiltered);

    // Mock the config
    String expected = mockConfig(version, configValue);

    getQuery().executeQueryCommand();

    Object actual = getQuery().getQueryReturnValue().getReturnValue();

    if (shouldSucceed) {
      assertEquals("Got wrong expected value for " + configValue, expected, actual);
    } else {
      assertNull("Should get null result for " + configValue, actual);
    }
  }
示例#8
0
  private AddVmCommand<AddVmParameters> setupCanAddPpcTest() {
    final int domainSizeGB = 20;
    AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB);

    doReturn(true).when(cmd).validateSpaceRequirements();
    doReturn(true).when(cmd).buildAndCheckDestStorageDomains();
    cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64);
    Cluster cluster = new Cluster();
    cluster.setArchitecture(ArchitectureType.ppc64);
    cluster.setCompatibilityVersion(Version.getLast());
    doReturn(cluster).when(cmd).getCluster();

    return cmd;
  }
  protected void updateNumOfSockets() {
    Version version = getClusterCompatibilityVersion();
    if (version == null) {
      return;
    }

    AsyncDataProvider.getInstance()
        .getMaxNumOfVmSockets(
            new AsyncQuery(
                new Object[] {this, getModel()},
                new INewAsyncCallback() {
                  @Override
                  public void onSuccess(Object target, Object returnValue) {

                    Object[] array = (Object[]) target;
                    VmModelBehaviorBase behavior = (VmModelBehaviorBase) array[0];
                    behavior.maxNumOfSockets = ((Integer) returnValue);
                    behavior.updataMaxVmsInPool();
                  }
                },
                getModel().getHash()),
            version.toString());
  }
 @Override
 protected boolean validate() {
   boolean result = true;
   // set version to latest supported version if not given
   if (getStoragePool().getCompatibilityVersion().isNotValid()) {
     getStoragePool().setCompatibilityVersion(Version.getLast());
   }
   if (result && !isStoragePoolUnique(getStoragePool().getName())) {
     result = false;
     addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NAME_ALREADY_EXIST);
   } else if (!checkStoragePoolNameLengthValid()) {
     result = false;
   } else if (!VersionSupport.checkVersionSupported(getStoragePool().getCompatibilityVersion())) {
     addValidationMessage(VersionSupport.getUnsupportedVersionMessage());
     result = false;
   }
   return result;
 }
  protected boolean validate() {
    VM vm = parentCommand.getVm();
    if (vm == null) {
      parentCommand.addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND);
      return false;
    } else {
      targetCluster = DbFacade.getInstance().getVdsGroupDao().get(targetClusterId);
      if (targetCluster == null) {
        parentCommand.addCanDoActionMessage(EngineMessage.VM_CLUSTER_IS_NOT_VALID);
        return false;
      }

      // Check that the target cluster is in the same data center.
      if (!targetCluster.getStoragePoolId().equals(vm.getStoragePoolId())) {
        parentCommand.addCanDoActionMessage(
            EngineMessage.VM_CANNOT_MOVE_TO_CLUSTER_IN_OTHER_STORAGE_POOL);
        return false;
      }

      List<VmNic> interfaces = DbFacade.getInstance().getVmNicDao().getAllForVm(vm.getId());

      Version clusterCompatibilityVersion = targetCluster.getCompatibilityVersion();
      if (!validateDestinationClusterContainsNetworks(interfaces)
          || !validateNics(interfaces, clusterCompatibilityVersion)) {
        return false;
      }

      // Check if VM static parameters are compatible for new cluster.
      boolean isCpuSocketsValid =
          AddVmCommand.checkCpuSockets(
              vm.getStaticData().getNumOfSockets(),
              vm.getStaticData().getCpuPerSocket(),
              vm.getStaticData().getThreadsPerCpu(),
              clusterCompatibilityVersion.getValue(),
              parentCommand.getReturnValue().getCanDoActionMessages());
      if (!isCpuSocketsValid) {
        return false;
      }

      // Check that the USB policy is legal
      if (!VmHandler.isUsbPolicyLegal(
          vm.getUsbPolicy(),
          vm.getOs(),
          targetCluster,
          parentCommand.getReturnValue().getCanDoActionMessages())) {
        return false;
      }

      // Check if the display type is supported
      if (!VmHandler.isGraphicsAndDisplaySupported(
          vm.getOs(),
          VmDeviceUtils.getGraphicsTypesOfEntity(vm.getId()),
          vm.getDefaultDisplayType(),
          parentCommand.getReturnValue().getCanDoActionMessages(),
          clusterCompatibilityVersion)) {
        return false;
      }

      if (VmDeviceUtils.hasVirtioScsiController(vm.getId())) {
        // Verify cluster compatibility
        if (!FeatureSupported.virtIoScsi(targetCluster.getCompatibilityVersion())) {
          return parentCommand.failCanDoAction(
              EngineMessage.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL);
        }

        // Verify OS compatibility
        if (!VmHandler.isOsTypeSupportedForVirtioScsi(
            vm.getOs(),
            targetCluster.getCompatibilityVersion(),
            parentCommand.getReturnValue().getCanDoActionMessages())) {
          return false;
        }
      }

      // A existing VM cannot be changed into a cluster without a defined architecture
      if (targetCluster.getArchitecture() == ArchitectureType.undefined) {
        return parentCommand.failCanDoAction(
            EngineMessage.ACTION_TYPE_FAILED_CLUSTER_UNDEFINED_ARCHITECTURE);
      } else if (targetCluster.getArchitecture() != vm.getClusterArch()) {
        return parentCommand.failCanDoAction(
            EngineMessage.ACTION_TYPE_FAILED_VM_CLUSTER_DIFFERENT_ARCHITECTURES);
      }
    }
    return true;
  }
public class StartRemoveGlusterVolumeBricksCommandTest extends BaseCommandTest {
  private static final Version SUPPORTED_VERSION = new Version(3, 4);
  private static final Version UNSUPPORTED_VERSION = new Version(3, 3);

  @Mock GlusterVolumeDao volumeDao;
  @Mock protected BackendInternal backend;
  @Mock protected VDSBrokerFrontend vdsBrokerFrontend;

  private final Guid volumeId1 = new Guid("8bc6f108-c0ef-43ab-ba20-ec41107220f5");

  private final Guid volumeId2 = new Guid("b2cb2f73-fab3-4a42-93f0-d5e4c069a43e");

  private final Guid CLUSTER_ID = new Guid("b399944a-81ab-4ec5-8266-e19ba7c3c9d1");

  @ClassRule
  public static MockConfigRule mcr =
      new MockConfigRule(
          mockConfig(ConfigValues.GlusterAsyncTasksSupport, UNSUPPORTED_VERSION.getValue(), false),
          mockConfig(ConfigValues.GlusterAsyncTasksSupport, SUPPORTED_VERSION.getValue(), true));

  @Mock protected VDSGroup vdsGroup;

  GlusterAsyncTask asyncTaskToBeReturned = new GlusterAsyncTask();
  /** The command under test. */
  private StartRemoveGlusterVolumeBricksCommand cmd;

  private StartRemoveGlusterVolumeBricksCommand createTestCommand(Guid volumeId, int replicaCount) {
    return new StartRemoveGlusterVolumeBricksCommand(
        new GlusterVolumeRemoveBricksParameters(volumeId, getBricks(volumeId, 1), replicaCount));
  }

  private List<GlusterBrickEntity> getBricks(Guid volumeId, int max) {
    List<GlusterBrickEntity> bricks = new ArrayList<>();
    for (Integer i = 0; i < max; i++) {
      GlusterBrickEntity brick1 = new GlusterBrickEntity();
      brick1.setVolumeId(volumeId);
      brick1.setServerName("server1");
      brick1.setStatus(GlusterStatus.UP);
      brick1.setBrickDirectory("/tmp/s" + i.toString());
      bricks.add(brick1);
    }
    return bricks;
  }

  private void prepareMocks(StartRemoveGlusterVolumeBricksCommand command) {
    doReturn(volumeDao).when(command).getGlusterVolumeDao();
    doReturn(getVds(VDSStatus.Up)).when(command).getUpServer();
    doReturn(getSingleBrickVolume(volumeId1)).when(volumeDao).getById(volumeId1);
    doReturn(getMultiBrickVolume(volumeId2)).when(volumeDao).getById(volumeId2);
    doReturn(null).when(volumeDao).getById(null);
    doReturn(SUPPORTED_VERSION).when(vdsGroup).getCompatibilityVersion();
    doReturn(vdsGroup).when(command).getVdsGroup();
    doReturn(vdsBrokerFrontend).when(command).getVdsBroker();
  }

  private VDS getVds(VDSStatus status) {
    VDS vds = new VDS();
    vds.setId(Guid.newGuid());
    vds.setVdsName("gfs1");
    vds.setVdsGroupId(CLUSTER_ID);
    vds.setStatus(status);
    return vds;
  }

  private GlusterVolumeEntity getSingleBrickVolume(Guid volumeId) {
    GlusterVolumeEntity volume = getGlusterVolume(volumeId);
    volume.setStatus(GlusterStatus.UP);
    volume.setBricks(getBricks(volumeId, 1));
    volume.setClusterId(CLUSTER_ID);
    return volume;
  }

  private GlusterVolumeEntity getMultiBrickVolume(Guid volumeId) {
    GlusterVolumeEntity volume = getGlusterVolume(volumeId);
    volume.setStatus(GlusterStatus.UP);
    volume.setBricks(getBricks(volumeId, 2));
    volume.setClusterId(CLUSTER_ID);
    return volume;
  }

  private GlusterVolumeEntity getGlusterVolume(Guid id) {
    GlusterVolumeEntity volumeEntity = new GlusterVolumeEntity();
    volumeEntity.setId(id);
    volumeEntity.setName("test-vol");
    volumeEntity.addAccessProtocol(AccessProtocol.GLUSTER);
    volumeEntity.addTransportType(TransportType.TCP);
    volumeEntity.setVolumeType(GlusterVolumeType.DISTRIBUTE);
    return volumeEntity;
  }

  private void mockBackend(boolean succeeded, EngineError errorCode) {
    doReturn(backend).when(cmd).getBackend();
    doNothing().when(cmd).startSubStep();
    doReturn(asyncTaskToBeReturned).when(cmd).handleTaskReturn(asyncTaskToBeReturned);
    doNothing().when(cmd).updateBricksWithTaskID(asyncTaskToBeReturned);

    VDSReturnValue vdsReturnValue = new VDSReturnValue();
    vdsReturnValue.setReturnValue(asyncTaskToBeReturned);
    vdsReturnValue.setSucceeded(succeeded);
    if (!succeeded) {
      vdsReturnValue.setVdsError(new VDSError(errorCode, ""));
    }
    when(vdsBrokerFrontend.runVdsCommand(
            eq(VDSCommandType.StartRemoveGlusterVolumeBricks),
            argThat(anyGlusterVolumeRemoveBricksVDSParameters())))
        .thenReturn(vdsReturnValue);
  }

  private ArgumentMatcher<VDSParametersBase> anyGlusterVolumeRemoveBricksVDSParameters() {
    return new ArgumentMatcher<VDSParametersBase>() {

      @Override
      public boolean matches(Object argument) {
        if (!(argument instanceof GlusterVolumeRemoveBricksVDSParameters)) {
          return false;
        }
        return true;
      }
    };
  }

  @Test
  public void executeCommand() {
    cmd = spy(createTestCommand(volumeId2, 0));
    prepareMocks(cmd);
    mockBackend(true, null);
    assertTrue(cmd.canDoAction());
    cmd.executeCommand();

    verify(cmd).startSubStep();
    verify(cmd).handleTaskReturn(asyncTaskToBeReturned);
    verify(cmd).updateBricksWithTaskID(asyncTaskToBeReturned);
    assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.START_REMOVING_GLUSTER_VOLUME_BRICKS);
  }

  @Test
  public void executeCommandWhenFailed() {
    cmd = spy(createTestCommand(volumeId2, 0));
    prepareMocks(cmd);
    mockBackend(false, EngineError.GlusterVolumeRemoveBricksStartFailed);
    assertTrue(cmd.canDoAction());
    cmd.executeCommand();

    assertEquals(
        cmd.getAuditLogTypeValue(), AuditLogType.START_REMOVING_GLUSTER_VOLUME_BRICKS_FAILED);
  }

  @Test
  public void canDoActionSucceeds() {
    cmd = spy(createTestCommand(volumeId2, 0));
    prepareMocks(cmd);
    assertTrue(cmd.canDoAction());
  }

  @Test
  public void canDoActionFails() {
    cmd = spy(createTestCommand(volumeId1, 0));
    prepareMocks(cmd);
    assertFalse(cmd.canDoAction());
  }

  @Test
  public void canDoActionFailsOnNull() {
    cmd = spy(createTestCommand(null, 0));
    prepareMocks(cmd);
    assertFalse(cmd.canDoAction());
  }

  @Test
  public void canDoActionFailsOnCompat() {
    cmd = spy(createTestCommand(volumeId2, 0));
    prepareMocks(cmd);
    doReturn(UNSUPPORTED_VERSION).when(vdsGroup).getCompatibilityVersion();
    assertFalse(cmd.canDoAction());
    assertTrue(
        cmd.getReturnValue()
            .getCanDoActionMessages()
            .contains(EngineMessage.GLUSTER_TASKS_NOT_SUPPORTED_FOR_CLUSTER_LEVEL.toString()));
  }
}
  public void SetDefaultNames(VDS host, RefObject<String> message) {
    message.argvalue = null;
    setCommonName(StringFormat.format("%1$s-Local", host.getvds_name().replace('.', '-')));
    storage_pool candidate = null;

    // selecet all possible DCs
    VdcQueryReturnValue returnValue =
        Frontend.RunQuery(
            VdcQueryType.Search,
            new SearchParameters(
                StringFormat.format("DataCenter: name=%1$s", getCommonName() + "*"),
                SearchType.StoragePool));

    java.util.ArrayList<storage_pool> dataCenterList = new java.util.ArrayList<storage_pool>();
    java.util.ArrayList<VDSGroup> clusterList = null;
    if (returnValue != null && returnValue.getSucceeded() && returnValue.getReturnValue() != null) {
      dataCenterList =
          Linq.<storage_pool>Cast(
              (java.util.ArrayList<IVdcQueryable>) returnValue.getReturnValue());
    }
    // check if current settings suitable for local setup (in case just SD creation failed -
    // re-using the same setup)
    boolean useCurrentSettings = false;
    if (host.getstorage_pool_id() != null) {
      storage_pool tempCandidate = DataProvider.GetDataCenterById(host.getstorage_pool_id());
      if (IsLocalDataCenterEmpty(tempCandidate)) {
        candidate = tempCandidate;
        useCurrentSettings = true;
      } else {
        if (tempCandidate != null && tempCandidate.getstorage_pool_type() == StorageType.LOCALFS) {
          message.argvalue =
              "Note: Local Storage is already configured for this Host. The Host belongs to "
                  + host.getstorage_pool_name()
                  + " with local Storage Domain. If OK is clicked - this Host will be moved to a new Data Center, and a new Local Storage Domain will be created. Hit Cancel to abort the operation.";
        }
      }
    }
    // check if there is other DC suitable for re-use
    if (candidate == null) {
      for (storage_pool dataCenter : dataCenterList) {
        // need to check if the new DC is without host.
        if (IsLocalDataCenterEmpty(dataCenter)
            && DataProvider.GetLocalStorageHost(dataCenter.getname()) == null) {
          candidate = dataCenter;
          break;
        }
      }
    }
    java.util.ArrayList<String> listNames = new java.util.ArrayList<String>();
    // in case we found a suitable candidte for re-use:
    if (candidate != null) {
      getDataCenter().setDataCenterId(candidate.getId());
      getDataCenter().getName().setEntity(candidate.getname());
      getDataCenter().getDescription().setEntity(candidate.getdescription());
      Version compVersion = candidate.getcompatibility_version();
      getDataCenter().getVersion().setSelectedItem(compVersion);
      getCluster().getVersion().setSelectedItem(compVersion);
      setDontCreateDataCenter(true);
      // if we use current settings there is no need to create cluster.
      if (useCurrentSettings) {
        getCluster().setClusterId(host.getvds_group_id().getValue());
        getCluster().getName().setEntity(host.getvds_group_name());
        VDSGroup cluster = DataProvider.GetClusterById(host.getvds_group_id().getValue());
        if (cluster != null) {
          getCluster().getDescription().setEntity(cluster.getdescription());
          ServerCpu tempVar = new ServerCpu();
          tempVar.setCpuName(cluster.getcpu_name());
          getCluster().getCPU().setSelectedItem(tempVar);
        }
        setDontCreateCluster(true);
        setDontChangeHostCluster(true);
      }
      // use differnt cluster
      else {
        // check the DC cluster list (for re-use)
        clusterList = DataProvider.GetClusterList(candidate.getId());
        // no clusters avilable - pick up new name.
        if (clusterList.isEmpty()) {
          java.util.ArrayList<VDSGroup> listClusters = DataProvider.GetClusterList();
          listNames = new java.util.ArrayList<String>();
          for (VDSGroup cluster : listClusters) {
            listNames.add(cluster.getname());
          }
          getCluster().getName().setEntity(AvailableName(listNames));
        } else {
          // use the DC cluster.
          getCluster().setClusterId(clusterList.get(0).getId());
          getCluster().getName().setEntity(clusterList.get(0).getname());
          getCluster().getDescription().setEntity(clusterList.get(0).getdescription());
          VDSGroup cluster = DataProvider.GetClusterById(getCluster().getClusterId().getValue());
          if (cluster != null) {
            ServerCpu tempVar2 = new ServerCpu();
            tempVar2.setCpuName(cluster.getcpu_name());
            getCluster().getCPU().setSelectedItem(tempVar2);
          }
          setDontCreateCluster(true);
          if (host.getvds_group_id().getValue().equals(getCluster().getClusterId())) {
            setDontChangeHostCluster(true);
          }
        }
      }
    } else {
      // didn't found DC to re-use, so we select new names:
      listNames = new java.util.ArrayList<String>();
      for (storage_pool storagePool : dataCenterList) {
        listNames.add(storagePool.getname());
      }
      getDataCenter().getName().setEntity(AvailableName(listNames));

      // Choose a Data Center version corresponding to the host.
      if (!StringHelper.isNullOrEmpty(host.getsupported_cluster_levels())) {
        // the supported_cluster_levels are sorted.
        String[] array = host.getsupported_cluster_levels().split("[,]", -1);
        Version maxCombindVersion = null;

        for (int i = 0; i < array.length; i++) {
          Version vdsVersion = new Version(array[i]);
          for (Version version :
              (java.util.List<Version>) getDataCenter().getVersion().getItems()) {
            if (version.equals(vdsVersion) && version.compareTo(maxCombindVersion) > 0) {
              maxCombindVersion = version;
            }
          }
        }
        if (maxCombindVersion != null) {
          getDataCenter().getVersion().setSelectedItem(maxCombindVersion);
          getCluster().getVersion().setSelectedItem(maxCombindVersion);
        }
      }

      listNames = new java.util.ArrayList<String>();
      if (clusterList == null) {
        clusterList = DataProvider.GetClusterList();
      }

      for (VDSGroup cluster : clusterList) {
        listNames.add(cluster.getname());
      }
      getCluster().getName().setEntity(AvailableName(listNames));
    }

    // Choose default CPU name to match host.
    if (host.getCpuName() != null && getCluster().getCPU().getSelectedItem() != null) {
      getCluster()
          .getCPU()
          .setSelectedItem(
              Linq.FirstOrDefault(
                  (java.util.List<ServerCpu>) getCluster().getCPU().getItems(),
                  new Linq.ServerCpuPredicate(host.getCpuName().getCpuName())));
    }
    // always choose a avialable storage name.
    java.util.ArrayList<storage_domains> listStorageDomains = DataProvider.GetStorageDomainList();
    listNames = new java.util.ArrayList<String>();
    for (storage_domains storageDomain : listStorageDomains) {
      listNames.add(storageDomain.getstorage_name());
    }
    getFormattedStorageName().setEntity(AvailableName(listNames));
  }
 protected void updateMemoryBalloon(Version clusterVersion) {
   boolean hasMemoryBalloon =
       clusterVersion.compareTo(VmListModel.BALLOON_DEVICE_MIN_VERSION) >= 0;
   getModel().getMemoryBalloonDeviceEnabled().setIsAvailable(hasMemoryBalloon);
 }
@RunWith(MockitoJUnitRunner.class)
public class VmInterfaceManagerTest {

  private static final String NETWORK_NAME = "networkName";
  private static final String VM_NAME = "vmName";
  private static final Version VERSION_3_2 = new Version(3, 2);
  private static final int OS_ID = 0;

  @ClassRule
  public static MockConfigRule mcr =
      new MockConfigRule(mockConfig(ConfigValues.HotPlugEnabled, VERSION_3_2.getValue(), true));

  @Mock private MacPoolManagerStrategy macPoolManagerStrategy;

  @Mock private VmNetworkStatisticsDao vmNetworkStatisticsDao;

  @Mock private VmNetworkInterfaceDao vmNetworkInterfaceDao;

  @Mock private VmNicDao vmNicDao;

  @Mock private VmDao vmDao;

  @Mock private ExternalNetworkManager externalNetworkManager;

  private VmInterfaceManager vmInterfaceManager;

  @Mock private Version version;

  @Before
  @SuppressWarnings("unchecked")
  public void setupMocks() {
    vmInterfaceManager = Mockito.spy(new VmInterfaceManager(macPoolManagerStrategy));
    doReturn(vmNetworkStatisticsDao).when(vmInterfaceManager).getVmNetworkStatisticsDao();
    doReturn(vmNetworkInterfaceDao).when(vmInterfaceManager).getVmNetworkInterfaceDao();
    doReturn(vmNicDao).when(vmInterfaceManager).getVmNicDao();
    doReturn(vmDao).when(vmInterfaceManager).getVmDao();
    doNothing().when(vmInterfaceManager).auditLogMacInUseUnplug(any(VmNic.class));
    doNothing().when(vmInterfaceManager).removeFromExternalNetworks(anyList());

    doNothing().when(vmInterfaceManager).log(any(AuditLogableBase.class), any(AuditLogType.class));
  }

  @Test
  public void add() {
    runAddAndVerify(createNewInterface(), false, times(0), OS_ID, VERSION_3_2);
  }

  @Test
  public void addWithExistingMacAddressSucceed() {
    VmNic iface = createNewInterface();
    runAddAndVerify(iface, true, times(1), OS_ID, VERSION_3_2);
  }

  protected void runAddAndVerify(
      VmNic iface,
      boolean reserveExistingMac,
      VerificationMode addMacVerification,
      int osId,
      Version version) {
    OsRepository osRepository = mock(OsRepository.class);
    when(vmInterfaceManager.getOsRepository()).thenReturn(osRepository);
    when(osRepository.hasNicHotplugSupport(any(Integer.class), any(Version.class)))
        .thenReturn(true);
    vmInterfaceManager.add(
        iface, NoOpCompensationContext.getInstance(), reserveExistingMac, osId, version);
    if (reserveExistingMac) {
      verify(macPoolManagerStrategy, times(1)).forceAddMac((iface.getMacAddress()));
    } else {
      verifyZeroInteractions(macPoolManagerStrategy);
    }
    verifyAddDelegatedCorrectly(iface, addMacVerification);
  }

  @Test
  public void findActiveVmsUsingNetworks() {
    mockDaos(true);

    List<String> vmNames =
        vmInterfaceManager.findActiveVmsUsingNetworks(
            Guid.newGuid(), Collections.singletonList(NETWORK_NAME));
    assertTrue(vmNames.contains(VM_NAME));
  }

  @Test
  public void findActiveVmsUsingNetworksOnUnpluggedVnic() {
    mockDaos(false);

    List<String> vmNames =
        vmInterfaceManager.findActiveVmsUsingNetworks(
            Guid.newGuid(), Collections.singletonList(NETWORK_NAME));
    assertFalse(vmNames.contains(VM_NAME));
  }

  @Test
  public void findNoneOfActiveVmsUsingNetworks() {
    mockDaos(true);

    List<String> vmNames =
        vmInterfaceManager.findActiveVmsUsingNetworks(
            Guid.newGuid(), Collections.singletonList(NETWORK_NAME + "1"));
    assertTrue(vmNames.isEmpty());
  }

  @Test
  public void removeAll() {
    List<VmNic> interfaces = Arrays.asList(createNewInterface(), createNewInterface());

    when(vmNicDao.getAllForVm(any(Guid.class))).thenReturn(interfaces);

    vmInterfaceManager.removeAll(Guid.newGuid());

    for (VmNic iface : interfaces) {
      verifyRemoveAllDelegatedCorrectly(iface);
    }
  }

  private void mockDaos(boolean pluggedInterface) {
    VM vm = createVM(VM_NAME, NETWORK_NAME, pluggedInterface);
    when(vmDao.getAllRunningForVds(any(Guid.class))).thenReturn(Arrays.asList(vm));
    when(vmNetworkInterfaceDao.getAllForVm(vm.getId())).thenReturn(vm.getInterfaces());
  }

  /**
   * Verify that {@link VmInterfaceManager#add} delegated correctly to {@link
   * MacPoolManagerStrategy} & Daos.
   *
   * @param iface The interface to check for.
   * @param addMacVerification Mode to check (times(1), never(), etc) for {@link
   *     MacPoolManagerStrategy#addMac(String)}.
   */
  protected void verifyAddDelegatedCorrectly(VmNic iface, VerificationMode addMacVerification) {
    verify(macPoolManagerStrategy, addMacVerification).forceAddMac(iface.getMacAddress());
    verify(vmNicDao).save(iface);
    verify(vmNetworkStatisticsDao).save(iface.getStatistics());
  }

  /**
   * Verify that {@link VmInterfaceManager#removeAll} delegated correctly to {@link
   * MacPoolManagerStrategy} & Daos.
   *
   * @param iface The interface to check for.
   */
  protected void verifyRemoveAllDelegatedCorrectly(VmNic iface) {
    verify(macPoolManagerStrategy, times(1)).freeMac(iface.getMacAddress());
    verify(vmNicDao).remove(iface.getId());
    verify(vmNetworkStatisticsDao).remove(iface.getId());
  }

  /** @return A new interface that can be used in tests. */
  private static VmNic createNewInterface() {
    VmNic iface = new VmNic();
    iface.setId(Guid.newGuid());
    iface.setMacAddress(RandomUtils.instance().nextString(10));

    return iface;
  }

  private static VmNetworkInterface createNewViewableInterface(boolean plugged) {
    VmNetworkInterface iface = new VmNetworkInterface();
    iface.setId(Guid.newGuid());
    iface.setMacAddress(RandomUtils.instance().nextString(10));
    iface.setPlugged(plugged);
    return iface;
  }

  /**
   * Creates a VM instance with a given name, having an interface which uses a given network.
   *
   * @param vmName The VM name to be set
   * @param networkName The network name to be set for the VM interface
   * @param pluggedInterface whether the VM interface plugged or not
   * @return the VM instance with the appropriate data.
   */
  private static VM createVM(String vmName, String networkName, boolean pluggedInterface) {
    VM vm = new VM();
    vm.setId(Guid.newGuid());
    vm.setName(vmName);
    VmNetworkInterface vmIface = createNewViewableInterface(pluggedInterface);
    vmIface.setVmId(vm.getId());
    vmIface.setNetworkName(networkName);
    vm.getInterfaces().add(vmIface);
    return vm;
  }
}
示例#16
0
 public static boolean OpEquality(Version v1, Version v2) {
   if (v1 == null) return (v2 == null) ? true : false;
   else return v1.equals(v2);
 }
示例#17
0
 @Override
 public boolean Match(Version source) {
   return source.equals(version);
 }
 /** Mock VDS */
 protected void mockVds() {
   VDS vds = new VDS();
   vds.setClusterCompatibilityVersion(Version.getLast());
   when(vdsDao.get(any(Guid.class))).thenReturn(vds);
 }
示例#19
0
 public void setDataCenterVersion(Version dataCenterVersion) {
   if (dataCenterVersion != null && !dataCenterVersion.equals(this.dataCenterVersion)) {
     this.dataCenterVersion = dataCenterVersion;
     updateExtendImageSizeSupported();
   }
 }
示例#20
0
@RunWith(MockitoJUnitRunner.class)
public class UpdateClusterCommandTest {

  private static final Version VERSION_1_0 = new Version(1, 0);
  private static final Version VERSION_1_1 = new Version(1, 1);
  private static final Version VERSION_1_2 = new Version(1, 2);
  private static final Guid DC_ID1 = Guid.newGuid();
  private static final Guid DC_ID2 = Guid.newGuid();
  private static final Guid DEFAULT_CLUSTER_ID = new Guid("99408929-82CF-4DC7-A532-9D998063FA95");
  private static final Guid DEFAULT_FEATURE_ID = new Guid("99408929-82CF-4DC7-A532-9D998063FA96");
  private static final Guid TEST_MANAGEMENT_NETWORK_ID = Guid.newGuid();

  private static final Map<String, String> migrationMap =
      Collections.unmodifiableMap(
          new HashMap<String, String>() {
            {
              put("undefined", "true");
              put("x86_64", "true");
              put("ppc64", "false");
            }
          });

  private static final Set<Version> versions =
      Collections.unmodifiableSet(
          new HashSet<Version>() {
            {
              add(VERSION_1_0);
              add(VERSION_1_1);
              add(VERSION_1_2);
            }
          });

  @Rule
  public MockConfigRule mcr =
      new MockConfigRule(
          mockConfig(ConfigValues.IsMigrationSupported, VERSION_1_0.getValue(), migrationMap),
          mockConfig(ConfigValues.IsMigrationSupported, VERSION_1_1.getValue(), migrationMap),
          mockConfig(ConfigValues.IsMigrationSupported, VERSION_1_2.getValue(), migrationMap));

  @Rule public InjectorRule injectorRule = new InjectorRule();

  @Mock DbFacade dbFacadeMock;

  @Mock private ClusterDao clusterDao;
  @Mock private VdsDao vdsDao;
  @Mock private StoragePoolDao storagePoolDao;
  @Mock private GlusterVolumeDao glusterVolumeDao;
  @Mock private VmDao vmDao;
  @Mock private NetworkDao networkDao;
  @Mock private ClusterFeatureDao clusterFeatureDao;
  @Mock private SupportedHostFeatureDao hostFeatureDao;
  @Mock private DefaultManagementNetworkFinder defaultManagementNetworkFinder;
  @Mock private UpdateClusterNetworkClusterValidator networkClusterValidator;
  @Mock private CpuFlagsManagerHandler cpuFlagsManagerHandler;

  @Mock private Network mockManagementNetwork = createManagementNetwork();
  private Guid managementNetworkId;

  private Network createManagementNetwork() {
    final Network network = new Network();
    network.setId(TEST_MANAGEMENT_NETWORK_ID);
    return network;
  }

  private UpdateClusterCommand<ManagementNetworkOnClusterOperationParameters> cmd;

  @Test
  public void nameInUse() {
    createSimpleCommand();
    createCommandWithDifferentName();
    validateFailedWithReason(EngineMessage.CLUSTER_CANNOT_DO_ACTION_NAME_IN_USE);
  }

  @Test
  public void invalidCluster() {
    createSimpleCommand();
    when(clusterDao.get(any(Guid.class))).thenReturn(null);
    validateFailedWithReason(EngineMessage.VDS_CLUSTER_IS_NOT_VALID);
  }

  @Test
  public void legalArchitectureChange() {
    createCommandWithDefaultCluster();
    cpuExists();
    architectureIsUpdatable();
    assertTrue(cmd.validate());
  }

  @Test
  public void illegalArchitectureChange() {
    createCommandWithDefaultCluster();
    clusterHasVMs();
    cpuExists();
    architectureIsNotUpdatable();
    validateFailedWithReason(EngineMessage.CLUSTER_CANNOT_UPDATE_CPU_ARCHITECTURE_ILLEGAL);
  }

  @Test
  public void illegalCpuUpdate() {
    createCommandWithDifferentCpuName();
    cpuIsNotUpdatable();
    cpuManufacturersMatch();
    cpuExists();
    clusterHasVMs();
    clusterHasVds();
    architectureIsUpdatable();
    validateFailedWithReason(EngineMessage.CLUSTER_CPU_IS_NOT_UPDATABLE);
  }

  @Test
  public void legalCpuUpdate() {
    createCommandWithDifferentCpuName();
    cpuExists();
    architectureIsUpdatable();
    assertTrue(cmd.validate());
  }

  private void cpuIsNotUpdatable() {
    doReturn(false).when(cmd).isCpuUpdatable(any(Cluster.class));
  }

  @Test
  public void invalidCpuSelection() {
    createCommandWithDefaultCluster();
    validateFailedWithReason(EngineMessage.ACTION_TYPE_FAILED_CPU_NOT_FOUND);
  }

  @Test
  public void illegalCpuChange() {
    createCommandWithDefaultCluster();
    cpuExists();
    cpuManufacturersDontMatch();
    clusterHasVds();
    validateFailedWithReason(EngineMessage.CLUSTER_CANNOT_UPDATE_CPU_ILLEGAL);
  }

  @Test
  public void invalidVersion() {
    createCommandWithInvalidVersion();
    setupCpu();
    validateFailedWithReason(EngineMessage.ACTION_TYPE_FAILED_GIVEN_VERSION_NOT_SUPPORTED);
  }

  @Test
  public void versionDecreaseWithHost() {
    createCommandWithOlderVersion(true, false);
    setupCpu();
    vdsExist();
    validateFailedWithReason(
        EngineMessage.ACTION_TYPE_FAILED_CANNOT_DECREASE_COMPATIBILITY_VERSION);
  }

  @Test
  public void versionDecreaseNoHostsOrNetwork() {
    createCommandWithOlderVersion(true, false);
    setupCpu();
    StoragePoolDao storagePoolDao2 = Mockito.mock(StoragePoolDao.class);
    when(storagePoolDao2.get(any(Guid.class))).thenReturn(createStoragePoolLocalFS());
    doReturn(storagePoolDao2).when(cmd).getStoragePoolDao();
    assertTrue(cmd.validate());
  }

  @Test
  public void versionDecreaseLowerVersionThanDC() {
    createCommandWithOlderVersion(true, false);
    StoragePoolDao storagePoolDao2 = Mockito.mock(StoragePoolDao.class);
    when(storagePoolDao2.get(any(Guid.class))).thenReturn(createStoragePoolLocalFSOldVersion());
    doReturn(storagePoolDao2).when(cmd).getStoragePoolDao();
    doReturn(storagePoolDao2).when(dbFacadeMock).getStoragePoolDao();
    setupCpu();
    validateFailedWithReason(
        EngineMessage.ACTION_TYPE_FAILED_CANNOT_DECREASE_COMPATIBILITY_VERSION_UNDER_DC);
  }

  @Test
  public void updateWithLowerVersionThanHosts() {
    createCommandWithDefaultCluster();
    setupCpu();
    vdsExistWithHigherVersion();
    architectureIsUpdatable();
    validateFailedWithReason(
        EngineMessage.CLUSTER_CANNOT_UPDATE_COMPATIBILITY_VERSION_WITH_LOWER_HOSTS);
  }

  @Test
  public void updateWithCpuLowerThanHost() {
    createCommandWithDefaultCluster();
    setupCpu();
    clusterHasVds();
    cpuFlagsMissing();
    architectureIsUpdatable();
    validateFailedWithReason(EngineMessage.CLUSTER_CANNOT_UPDATE_CPU_WITH_LOWER_HOSTS);
  }

  @Test
  public void updateStoragePool() {
    createCommandWithDifferentPool();
    setupCpu();
    clusterHasVds();
    cpuFlagsNotMissing();
    validateFailedWithReason(EngineMessage.CLUSTER_CANNOT_CHANGE_STORAGE_POOL);
  }

  @Test
  public void clusterAlreadyInLocalFs() {
    prepareManagementNetworkMocks();

    createCommandWithDefaultCluster();
    oldGroupIsDetachedDefault();
    storagePoolIsLocalFS();
    setupCpu();
    allQueriesForVms();
    storagePoolAlreadyHasCluster();
    architectureIsUpdatable();
    validateFailedWithReason(EngineMessage.CLUSTER_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE);
  }

  @Test
  public void clusterMovesToDcWithNoDefaultManagementNetwork() {
    noNewDefaultManagementNetworkFound();

    createCommandWithDefaultCluster();
    oldGroupIsDetachedDefault();
    setupCpu();
    validateFailedWithReason(EngineMessage.ACTION_TYPE_FAILED_DEFAULT_MANAGEMENT_NETWORK_NOT_FOUND);
  }

  @Test
  public void detachedClusterMovesToDcWithNonExistentManagementNetwork() {
    managementNetworkNotFoundById();

    createCommandWithDefaultCluster();
    oldGroupIsDetachedDefault();
    setupCpu();

    validateFailedWithReason(EngineMessage.NETWORK_NOT_EXISTS);
  }

  @Test
  public void detachedClusterMovesToDcWithExistingManagementNetwork() {

    prepareManagementNetworkMocks();

    mcr.mockConfigValue(ConfigValues.AutoRegistrationDefaultClusterID, Guid.Empty);
    createCommandWithDefaultCluster();
    oldGroupIsDetachedDefault();
    setupCpu();
    storagePoolIsLocalFS();

    assertTrue(cmd.validate());
  }

  private void managementNetworkNotFoundById() {
    managementNetworkId = TEST_MANAGEMENT_NETWORK_ID;
    when(networkDao.get(TEST_MANAGEMENT_NETWORK_ID)).thenReturn(null);
  }

  @Test
  public void invalidDefaultManagementNetworkAttachement() {
    newDefaultManagementNetworkFound();
    final EngineMessage expected = EngineMessage.Unassigned;
    when(networkClusterValidator.managementNetworkChange())
        .thenReturn(new ValidationResult(expected));

    createCommandWithDefaultCluster();
    oldGroupIsDetachedDefault();
    setupCpu();
    validateFailedWithReason(expected);
  }

  private void setupCpu() {
    cpuExists();
    cpuManufacturersMatch();
  }

  @Test
  public void defaultClusterInLocalFs() {
    prepareManagementNetworkMocks();

    mcr.mockConfigValue(ConfigValues.AutoRegistrationDefaultClusterID, DEFAULT_CLUSTER_ID);
    createCommandWithDefaultCluster();
    oldGroupIsDetachedDefault();
    storagePoolIsLocalFS();
    setupCpu();
    allQueriesForVms();
    architectureIsUpdatable();
    validateFailedWithReason(EngineMessage.DEFAULT_CLUSTER_CANNOT_BE_ON_LOCALFS);
  }

  private void prepareManagementNetworkMocks() {
    newDefaultManagementNetworkFound();
    when(networkClusterValidator.managementNetworkChange()).thenReturn(ValidationResult.VALID);
  }

  private void newDefaultManagementNetworkFound() {
    managementNetworkId = null;
    when(defaultManagementNetworkFinder.findDefaultManagementNetwork(DC_ID1))
        .thenReturn(mockManagementNetwork);
  }

  private void noNewDefaultManagementNetworkFound() {
    managementNetworkId = null;
    when(defaultManagementNetworkFinder.findDefaultManagementNetwork(DC_ID1)).thenReturn(null);
  }

  @Test
  public void clusterWithNoCpu() {
    createCommandWithNoCpuName();
    when(clusterDao.get(any(Guid.class))).thenReturn(createClusterWithNoCpuName());
    when(clusterDao.getByName(anyString())).thenReturn(createClusterWithNoCpuName());
    when(glusterVolumeDao.getByClusterId(any(Guid.class))).thenReturn(new ArrayList<>());
    allQueriesForVms();
    assertTrue(cmd.validate());
  }

  @Test
  public void clusterWithNoServiceEnabled() {
    createCommandWithNoService();
    when(clusterDao.get(any(Guid.class))).thenReturn(createClusterWithNoCpuName());
    when(clusterDao.getByName(anyString())).thenReturn(createClusterWithNoCpuName());
    cpuExists();
    allQueriesForVms();
    validateFailedWithReason(EngineMessage.CLUSTER_AT_LEAST_ONE_SERVICE_MUST_BE_ENABLED);
  }

  @Test
  public void clusterWithVirtGlusterServicesNotAllowed() {
    createCommandWithVirtGlusterEnabled();
    when(clusterDao.get(any(Guid.class))).thenReturn(createClusterWithNoCpuName());
    when(clusterDao.getByName(anyString())).thenReturn(createClusterWithNoCpuName());
    mcr.mockConfigValue(ConfigValues.AllowClusterWithVirtGlusterEnabled, Boolean.FALSE);
    cpuExists();
    allQueriesForVms();
    validateFailedWithReason(
        EngineMessage.CLUSTER_ENABLING_BOTH_VIRT_AND_GLUSTER_SERVICES_NOT_ALLOWED);
  }

  @Test
  public void disableVirtWhenVmsExist() {
    createCommandWithGlusterEnabled();
    when(clusterDao.get(any(Guid.class))).thenReturn(createDefaultCluster());
    when(clusterDao.getByName(anyString())).thenReturn(createDefaultCluster());
    cpuExists();
    cpuFlagsNotMissing();
    clusterHasVds();
    clusterHasVMs();

    validateFailedWithReason(EngineMessage.CLUSTER_CANNOT_DISABLE_VIRT_WHEN_CLUSTER_CONTAINS_VMS);
  }

  @Test
  public void disableGlusterWhenVolumesExist() {
    createCommandWithVirtEnabled();
    when(clusterDao.get(any(Guid.class))).thenReturn(createClusterWithNoCpuName());
    when(clusterDao.getByName(anyString())).thenReturn(createClusterWithNoCpuName());
    cpuExists();
    cpuFlagsNotMissing();
    allQueriesForVms();
    clusterHasGlusterVolumes();

    validateFailedWithReason(
        EngineMessage.CLUSTER_CANNOT_DISABLE_GLUSTER_WHEN_CLUSTER_CONTAINS_VOLUMES);
  }

  @Test
  public void enableNewAddtionalFeatureWhenHostDoesnotSupport() {
    createCommandWithAddtionalFeature();
    when(clusterDao.get(any(Guid.class))).thenReturn(createClusterWithNoCpuName());
    when(clusterDao.getByName(anyString())).thenReturn(createClusterWithNoCpuName());
    cpuExists();
    cpuFlagsNotMissing();
    allQueriesForVms();
    clusterHasVds();
    when(clusterFeatureDao.getSupportedFeaturesByClusterId(any(Guid.class)))
        .thenReturn(Collections.EMPTY_SET);
    when(hostFeatureDao.getSupportedHostFeaturesByHostId(any(Guid.class)))
        .thenReturn(Collections.EMPTY_SET);
    validateFailedWithReason(
        EngineMessage.CLUSTER_CANNOT_UPDATE_SUPPORTED_FEATURES_WITH_LOWER_HOSTS);
  }

  @Test
  public void enableNewAddtionalFeatureWhenHostSupports() {
    createCommandWithAddtionalFeature();
    when(clusterDao.get(any(Guid.class))).thenReturn(createClusterWithNoCpuName());
    when(clusterDao.getByName(anyString())).thenReturn(createClusterWithNoCpuName());
    cpuExists();
    cpuFlagsNotMissing();
    allQueriesForVms();
    clusterHasVds();
    when(clusterFeatureDao.getSupportedFeaturesByClusterId(any(Guid.class)))
        .thenReturn(Collections.EMPTY_SET);
    when(hostFeatureDao.getSupportedHostFeaturesByHostId(any(Guid.class)))
        .thenReturn(new HashSet(Arrays.asList("TEST_FEATURE")));
    assertTrue(cmd.validate());
  }

  private void createSimpleCommand() {
    createCommand(createNewCluster());
  }

  private void createCommandWithOlderVersion(
      boolean supportsVirtService, boolean supportsGlusterService) {
    createCommand(createClusterWithOlderVersion(true, false));
  }

  private void createCommandWithInvalidVersion() {
    createCommand(createClusterWithBadVersion());
  }

  private void createCommandWithDifferentPool() {
    createCommand(createClusterWithDifferentPool());
  }

  private void createCommandWithDefaultCluster() {
    createCommand(createDefaultCluster());
  }

  private void createCommandWithDifferentCpuName() {
    createCommand(createDefaultClusterWithDifferentCpuName());
  }

  private void createCommandWithNoCpuName() {
    createCommand(createClusterWithNoCpuName());
  }

  private void createCommandWithNoService() {
    createCommand(createClusterWith(false, false));
  }

  private void createCommandWithVirtEnabled() {
    createCommand(createClusterWith(true, false));
  }

  private void createCommandWithAddtionalFeature() {
    createCommand(createClusterWithAddtionalFeature());
  }

  private void createCommandWithGlusterEnabled() {
    createCommand(createClusterWith(false, true));
  }

  private void createCommandWithVirtGlusterEnabled() {
    createCommand(createClusterWith(true, true));
  }

  private void createCommand(final Cluster group) {
    setValidCpuVersionMap();
    final ManagementNetworkOnClusterOperationParameters param;
    if (managementNetworkId == null) {
      param = new ManagementNetworkOnClusterOperationParameters(group);
    } else {
      param = new ManagementNetworkOnClusterOperationParameters(group, managementNetworkId);
    }
    injectorRule.bind(CpuFlagsManagerHandler.class, cpuFlagsManagerHandler);
    cmd =
        spy(
            new UpdateClusterCommand<ManagementNetworkOnClusterOperationParameters>(param, null) {
              @Override
              protected void initUser() {
                // Stub for testing
              }
            });

    doReturn(0).when(cmd).compareCpuLevels(any(Cluster.class));

    doReturn(cpuFlagsManagerHandler).when(cmd).getCpuFlagsManagerHandler();
    doReturn(dbFacadeMock).when(cmd).getDbFacade();
    doReturn(clusterDao).when(cmd).getClusterDao();
    doReturn(clusterDao).when(dbFacadeMock).getClusterDao();
    doReturn(vdsDao).when(cmd).getVdsDao();
    doReturn(storagePoolDao).when(cmd).getStoragePoolDao();
    doReturn(storagePoolDao).when(dbFacadeMock).getStoragePoolDao();
    doReturn(glusterVolumeDao).when(cmd).getGlusterVolumeDao();
    doReturn(vmDao).when(cmd).getVmDao();
    doReturn(networkDao).when(cmd).getNetworkDao();
    doReturn(defaultManagementNetworkFinder).when(cmd).getDefaultManagementNetworkFinder();
    doReturn(clusterFeatureDao).when(cmd).getClusterFeatureDao();
    doReturn(hostFeatureDao).when(cmd).getHostFeatureDao();
    doReturn(networkClusterValidator).when(cmd).createManagementNetworkClusterValidator();
    doReturn(true).when(cmd).validateClusterPolicy();
    doReturn(true).when(cmd).isSupportedEmulatedMachinesMatchClusterLevel(any(VDS.class));

    if (StringUtils.isEmpty(group.getCpuName())) {
      doReturn(ArchitectureType.undefined).when(cmd).getArchitecture();
    } else {
      doReturn(ArchitectureType.x86_64).when(cmd).getArchitecture();
    }

    when(clusterDao.get(any(Guid.class))).thenReturn(createDefaultCluster());
    when(clusterDao.getByName(anyString())).thenReturn(createDefaultCluster());
    List<Cluster> clusterList = new ArrayList<>();
    clusterList.add(createDefaultCluster());
    when(clusterDao.getByName(anyString(), anyBoolean())).thenReturn(clusterList);
  }

  private void createCommandWithDifferentName() {
    createCommand(createClusterWithDifferentName());
  }

  private static Cluster createClusterWithDifferentName() {
    Cluster group = new Cluster();
    group.setName("BadName");
    group.setCompatibilityVersion(VERSION_1_1);
    return group;
  }

  private static Cluster createNewCluster() {
    Cluster group = new Cluster();
    group.setCompatibilityVersion(VERSION_1_1);
    group.setName("Default");
    return group;
  }

  private static Cluster createDefaultCluster() {
    Cluster group = new Cluster();
    group.setName("Default");
    group.setId(DEFAULT_CLUSTER_ID);
    group.setCpuName("Intel Conroe");
    group.setCompatibilityVersion(VERSION_1_1);
    group.setStoragePoolId(DC_ID1);
    group.setArchitecture(ArchitectureType.x86_64);
    return group;
  }

  private static Cluster createDefaultClusterWithDifferentCpuName() {
    Cluster group = createDefaultCluster();

    group.setCpuName("Another CPU name");

    return group;
  }

  private static Cluster createClusterWithNoCpuName() {
    Cluster group = new Cluster();
    group.setName("Default");
    group.setId(DEFAULT_CLUSTER_ID);
    group.setCompatibilityVersion(VERSION_1_1);
    group.setStoragePoolId(DC_ID1);
    group.setArchitecture(ArchitectureType.undefined);
    return group;
  }

  private static Cluster createDetachedDefaultCluster() {
    Cluster group = createDefaultCluster();
    group.setStoragePoolId(null);
    return group;
  }

  private static Cluster createClusterWithOlderVersion(
      boolean supportsVirtService, boolean supportsGlusterService) {
    Cluster group = createNewCluster();
    group.setCompatibilityVersion(VERSION_1_0);
    group.setStoragePoolId(DC_ID1);
    group.setVirtService(supportsVirtService);
    group.setGlusterService(supportsGlusterService);
    return group;
  }

  private static Cluster createClusterWithBadVersion() {
    Cluster group = createNewCluster();
    group.setCompatibilityVersion(new Version(5, 0));
    return group;
  }

  private static Cluster createClusterWithDifferentPool() {
    Cluster group = createNewCluster();
    group.setStoragePoolId(DC_ID2);
    return group;
  }

  private static Cluster createClusterWith(boolean virtService, boolean glusterService) {
    Cluster group = createDefaultCluster();
    group.setVirtService(virtService);
    group.setGlusterService(glusterService);
    group.setCompatibilityVersion(VERSION_1_1);
    return group;
  }

  private static Cluster createClusterWithAddtionalFeature() {
    Cluster group = createDefaultCluster();
    group.setCompatibilityVersion(VERSION_1_1);
    Set<SupportedAdditionalClusterFeature> addtionalFeaturesSupported = new HashSet<>();
    AdditionalFeature feature =
        new AdditionalFeature(
            DEFAULT_FEATURE_ID,
            "TEST_FEATURE",
            VERSION_1_1,
            "Test Feature",
            ApplicationMode.AllModes);
    addtionalFeaturesSupported.add(
        new SupportedAdditionalClusterFeature(group.getId(), true, feature));
    group.setAddtionalFeaturesSupported(addtionalFeaturesSupported);
    return group;
  }

  private static StoragePool createStoragePoolLocalFSOldVersion() {
    StoragePool pool = new StoragePool();
    pool.setIsLocal(true);
    pool.setCompatibilityVersion(VERSION_1_2);
    return pool;
  }

  private static StoragePool createStoragePoolLocalFS() {
    StoragePool pool = new StoragePool();
    pool.setIsLocal(true);
    return pool;
  }

  private void storagePoolIsLocalFS() {
    when(storagePoolDao.get(DC_ID1)).thenReturn(createStoragePoolLocalFS());
  }

  private void oldGroupIsDetachedDefault() {
    when(clusterDao.get(DEFAULT_CLUSTER_ID)).thenReturn(createDetachedDefaultCluster());
  }

  private void storagePoolAlreadyHasCluster() {
    Cluster group = new Cluster();
    List<Cluster> groupList = new ArrayList<>();
    groupList.add(group);
    when(clusterDao.getAllForStoragePool(any(Guid.class))).thenReturn(groupList);
  }

  private void vdsExist() {
    VDS vds = new VDS();
    vds.setStatus(VDSStatus.Up);
    List<VDS> vdsList = new ArrayList<>();
    vdsList.add(vds);
    when(vdsDao.getAllForCluster(any(Guid.class))).thenReturn(vdsList);
  }

  private void vdsExistWithHigherVersion() {
    VDS vds = new VDS();
    vds.setStatus(VDSStatus.Up);
    vds.setClusterCompatibilityVersion(VERSION_1_2);
    List<VDS> vdsList = new ArrayList<>();
    vdsList.add(vds);
    when(vdsDao.getAllForCluster(any(Guid.class))).thenReturn(vdsList);
  }

  private void allQueriesForVms() {
    when(vmDao.getAllForCluster(any(Guid.class))).thenReturn(Collections.<VM>emptyList());
  }

  private void clusterHasVds() {
    VDS vds = new VDS();
    vds.setStatus(VDSStatus.Up);
    vds.setSupportedClusterLevels(VERSION_1_1.toString());
    List<VDS> vdsList = new ArrayList<>();
    vdsList.add(vds);
    when(vdsDao.getAllForCluster(any(Guid.class))).thenReturn(vdsList);
  }

  private void clusterHasGlusterVolumes() {
    List<GlusterVolumeEntity> volumes = new ArrayList<>();
    volumes.add(new GlusterVolumeEntity());
    when(glusterVolumeDao.getByClusterId(any(Guid.class))).thenReturn(volumes);
  }

  private void clusterHasVMs() {
    VM vm = new VM();
    vm.setClusterId(DEFAULT_CLUSTER_ID);
    List<VM> vmList = new ArrayList<>();
    vmList.add(vm);

    when(vmDao.getAllForCluster(any(Guid.class))).thenReturn(vmList);
  }

  private void cpuFlagsMissing() {
    List<String> strings = new ArrayList<>();
    strings.add("foo");
    doReturn(strings).when(cmd).missingServerCpuFlags(any(VDS.class));
  }

  private void cpuFlagsNotMissing() {
    doReturn(null).when(cmd).missingServerCpuFlags(any(VDS.class));
  }

  private void cpuManufacturersDontMatch() {
    doReturn(false).when(cmd).checkIfCpusSameManufacture(any(Cluster.class));
  }

  private void cpuManufacturersMatch() {
    doReturn(true).when(cmd).checkIfCpusSameManufacture(any(Cluster.class));
  }

  private void cpuExists() {
    doReturn(true).when(cmd).checkIfCpusExist();
  }

  private void architectureIsUpdatable() {
    doReturn(true).when(cmd).isArchitectureUpdatable();
  }

  private void architectureIsNotUpdatable() {
    doReturn(false).when(cmd).isArchitectureUpdatable();
  }

  private void setValidCpuVersionMap() {
    mcr.mockConfigValue(ConfigValues.SupportedClusterLevels, versions);
  }

  private void validateFailedWithReason(final EngineMessage message) {
    assertFalse(cmd.validate());
    assertTrue(cmd.getReturnValue().getValidationMessages().contains(message.toString()));
  }
}