You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by da...@apache.org on 2025/12/16 10:19:36 UTC
(cloudstack) branch 4.22 updated (0a13fb27f58 -> 7aba434dc42)
This is an automated email from the ASF dual-hosted git repository.
dahn pushed a change to branch 4.22
in repository https://gitbox.apache.org/repos/asf/cloudstack.git
from 0a13fb27f58 Prevent scaling of cluster if count / resources exceed account resource limits (#12167)
add 951649c420a Support iprange while creating remote access vpn (#12063)
add ba52db9b3e9 ui: allow macaddress input for add nic to vm (#12145)
add 43483869705 Optimize drs plan generation (#12014)
add 79ebf6959e1 refactor storapool automation (#11789)
add e1c48c3adca server,ui: prevent role change for default accounts (#11761)
add 494c56a499f check for active MSses before starting DB upgrade (#12140)
add 67217d4d2ea UI: Option to choose the isolation method when creating the public IP range (#12000)
new 7aba434dc42 merge forward 4.20 to 4.22 LTS
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../java/com/cloud/server/ManagementService.java | 16 +
.../network/CreateManagementNetworkIpRangeCmd.java | 3 +-
.../command/admin/vlan/CreateVlanIpRangeCmd.java | 3 +-
.../cloudstack/cluster/ClusterDrsAlgorithm.java | 198 ++++----
.../com/cloud/upgrade/DatabaseUpgradeChecker.java | 111 ++++-
.../DatabaseUpgradeCheckerDoUpgradesTest.java | 173 +++++++
.../cloud/upgrade/DatabaseUpgradeCheckerTest.java | 92 +++-
.../org/apache/cloudstack/cluster/Balanced.java | 25 +-
.../apache/cloudstack/cluster/BalancedTest.java | 61 ++-
.../org/apache/cloudstack/cluster/Condensed.java | 26 +-
.../apache/cloudstack/cluster/CondensedTest.java | 61 ++-
.../com/cloud/server/ManagementServerImpl.java | 133 +++++-
.../cloud/storage/StoragePoolAutomationImpl.java | 505 ++++++++++----------
.../java/com/cloud/user/AccountManagerImpl.java | 6 +
.../cloudstack/cluster/ClusterDrsServiceImpl.java | 288 ++++++++++--
.../com/cloud/server/ManagementServerImplTest.java | 234 +++++-----
.../com/cloud/user/AccountManagerImplTest.java | 16 +
.../cluster/ClusterDrsServiceImplTest.java | 506 ++++++++++++++++++++-
ui/public/locales/en.json | 4 +
ui/src/views/iam/EditAccount.vue | 6 +-
ui/src/views/infra/network/IpRangesTabPublic.vue | 26 +-
ui/src/views/network/NicsTab.vue | 65 +--
ui/src/views/network/VpnDetails.vue | 250 +++++-----
23 files changed, 2056 insertions(+), 752 deletions(-)
create mode 100644 engine/schema/src/test/java/com/cloud/upgrade/DatabaseUpgradeCheckerDoUpgradesTest.java
(cloudstack) 01/01: merge forward 4.20 to 4.22 LTS
Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
dahn pushed a commit to branch 4.22
in repository https://gitbox.apache.org/repos/asf/cloudstack.git
commit 7aba434dc42af6304def8ab8995d699b569eb7a8
Merge: 0a13fb27f58 67217d4d2ea
Author: Daan Hoogland <da...@apache.org>
AuthorDate: Tue Dec 16 11:19:04 2025 +0100
merge forward 4.20 to 4.22 LTS
.../java/com/cloud/server/ManagementService.java | 16 +
.../network/CreateManagementNetworkIpRangeCmd.java | 3 +-
.../command/admin/vlan/CreateVlanIpRangeCmd.java | 3 +-
.../cloudstack/cluster/ClusterDrsAlgorithm.java | 198 ++++----
.../com/cloud/upgrade/DatabaseUpgradeChecker.java | 111 ++++-
.../DatabaseUpgradeCheckerDoUpgradesTest.java | 173 +++++++
.../cloud/upgrade/DatabaseUpgradeCheckerTest.java | 92 +++-
.../org/apache/cloudstack/cluster/Balanced.java | 25 +-
.../apache/cloudstack/cluster/BalancedTest.java | 61 ++-
.../org/apache/cloudstack/cluster/Condensed.java | 26 +-
.../apache/cloudstack/cluster/CondensedTest.java | 61 ++-
.../com/cloud/server/ManagementServerImpl.java | 133 +++++-
.../cloud/storage/StoragePoolAutomationImpl.java | 505 ++++++++++----------
.../java/com/cloud/user/AccountManagerImpl.java | 6 +
.../cloudstack/cluster/ClusterDrsServiceImpl.java | 288 ++++++++++--
.../com/cloud/server/ManagementServerImplTest.java | 234 +++++-----
.../com/cloud/user/AccountManagerImplTest.java | 16 +
.../cluster/ClusterDrsServiceImplTest.java | 506 ++++++++++++++++++++-
ui/public/locales/en.json | 4 +
ui/src/views/iam/EditAccount.vue | 6 +-
ui/src/views/infra/network/IpRangesTabPublic.vue | 26 +-
ui/src/views/network/NicsTab.vue | 65 +--
ui/src/views/network/VpnDetails.vue | 250 +++++-----
23 files changed, 2056 insertions(+), 752 deletions(-)
diff --cc api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java
index 5cb384925e8,2a3b25c28f3..48a6ca620e0
--- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java
+++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java
@@@ -16,9 -16,8 +16,10 @@@
// under the License.
package org.apache.cloudstack.api.command.admin.vlan;
+import com.cloud.configuration.ConfigurationService;
+import com.cloud.network.Network;
import com.cloud.utils.net.NetUtils;
+ import com.cloud.utils.StringUtils;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
@@@ -163,7 -163,7 +164,7 @@@ public class CreateVlanIpRangeCmd exten
}
public String getVlan() {
- if ((vlan == null || vlan.isEmpty()) && !ConfigurationService.IsIpRangeForProvider(getProvider())) {
- if (StringUtils.isBlank(vlan) && !isForNsx()) {
++ if (StringUtils.isBlank(vlan) && !ConfigurationService.IsIpRangeForProvider(getProvider())) {
vlan = "untagged";
}
return vlan;
diff --cc server/src/main/java/com/cloud/server/ManagementServerImpl.java
index e6032662e92,580e82dbe6d..1a3f18011be
--- a/server/src/main/java/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/main/java/com/cloud/server/ManagementServerImpl.java
@@@ -714,8 -691,8 +714,9 @@@ import com.cloud.dc.dao.DomainVlanMapDa
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.PodVlanMapDao;
import com.cloud.dc.dao.VlanDao;
+import com.cloud.dc.dao.VlanDetailsDao;
import com.cloud.deploy.DataCenterDeployment;
+ import com.cloud.deploy.DeploymentPlan;
import com.cloud.deploy.DeploymentPlanner;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.deploy.DeploymentPlanningManager;
@@@ -962,8 -932,6 +963,8 @@@ public class ManagementServerImpl exten
@Inject
private HostPodDao _hostPodDao;
@Inject
- private VgpuProfileDao vgpuProfileDao;
++ VgpuProfileDao vgpuProfileDao;
+ @Inject
private VMInstanceDao _vmInstanceDao;
@Inject
private VolumeDao _volumeDao;
@@@ -1538,14 -1520,12 +1550,14 @@@
throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate");
}
+ validateVgpuProfileForVmMigration(vmProfile);
+
final Type hostType = srcHost.getType();
- Pair<List<HostVO>, Integer> allHostsPair = null;
- List<HostVO> allHosts = null;
+ Pair<List<HostVO>, Integer> allHostsPair;
+ List<HostVO> allHosts;
List<HostVO> filteredHosts = null;
final Map<Host, Boolean> requiresStorageMotion = new HashMap<>();
- DataCenterDeployment plan;
+
if (canMigrateWithStorage) {
Long podId = !VirtualMachine.Type.User.equals(vm.getType()) ? srcHost.getPodId() : null;
allHostsPair = searchForServers(startIndex, pageSize, null, hostType, null, srcHost.getDataCenterId(), podId, null, null, keyword,
diff --cc server/src/main/java/com/cloud/storage/StoragePoolAutomationImpl.java
index 7407de6c963,612582640f4..594bf3f90bb
--- a/server/src/main/java/com/cloud/storage/StoragePoolAutomationImpl.java
+++ b/server/src/main/java/com/cloud/storage/StoragePoolAutomationImpl.java
@@@ -24,16 -23,15 +23,19 @@@ import java.util.Map
import javax.inject.Inject;
- import org.apache.cloudstack.context.CallContext;
+ import com.cloud.exception.InsufficientCapacityException;
+ import com.cloud.exception.OperationTimedoutException;
+ import com.cloud.exception.ResourceUnavailableException;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManager;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
- import org.apache.commons.collections.MapUtils;
- import org.apache.logging.log4j.LogManager;
++
+ import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.Logger;
+ import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Component;
import com.cloud.agent.AgentManager;
@@@ -46,26 -43,13 +48,19 @@@ import com.cloud.host.Status
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.resource.ResourceManager;
import com.cloud.server.ManagementServer;
+import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.StoragePoolWorkDao;
import com.cloud.storage.dao.VolumeDao;
- import com.cloud.user.Account;
- import com.cloud.user.User;
+import com.cloud.user.dao.UserDao;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
- import com.cloud.vm.ConsoleProxyVO;
- import com.cloud.vm.DomainRouterVO;
- import com.cloud.vm.SecondaryStorageVmVO;
- import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
- import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.dao.ConsoleProxyDao;
+import com.cloud.vm.dao.DomainRouterDao;
+import com.cloud.vm.dao.SecondaryStorageVmDao;
+import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Component
@@@ -113,217 -76,207 +108,218 @@@ public class StoragePoolAutomationImpl
@Override
public boolean maintain(DataStore store) {
+ return maintain(store, null);
+ }
+
+ @Override
+ public boolean maintain(DataStore store, Map<String,String> details) {
- Long userId = CallContext.current().getCallingUserId();
- User user = _userDao.findById(userId);
- Account account = CallContext.current().getCallingAccount();
StoragePoolVO pool = primaryDataStoreDao.findById(store.getId());
try {
- List<StoragePoolVO> spes = null;
- // Handling Zone and Cluster wide storage scopes.
- // if the storage is ZONE wide then we pass podid and cluster id as null as they will be empty for ZWPS
- if (pool.getScope() == ScopeType.ZONE) {
- spes = primaryDataStoreDao.listBy(pool.getDataCenterId(), null, null, ScopeType.ZONE);
- } else {
- spes = primaryDataStoreDao.listBy(pool.getDataCenterId(), pool.getPodId(), pool.getClusterId(), ScopeType.CLUSTER);
- }
- for (StoragePoolVO sp : spes) {
- if (sp.getParent() != pool.getParent() && sp.getId() != pool.getParent()) { // If Datastore cluster is tried to prepare for maintenance then child storage pools are also kept in PrepareForMaintenance mode
- if (sp.getStatus() == StoragePoolStatus.PrepareForMaintenance) {
- throw new CloudRuntimeException(String.format("Only one storage pool in a cluster can be in PrepareForMaintenance mode, %s is already in PrepareForMaintenance mode ", sp));
- }
- }
- }
- StoragePool storagePool = (StoragePool)store;
-
- //Handeling the Zone wide and cluster wide primay storage
- List<HostVO> hosts = new ArrayList<HostVO>();
- // if the storage scope is ZONE wide, then get all the hosts for which hypervisor ZWSP created to send Modifystoragepoolcommand
- //TODO: if it's zone wide, this code will list a lot of hosts in the zone, which may cause performance/OOM issue.
- if (pool.getScope().equals(ScopeType.ZONE)) {
- if (HypervisorType.Any.equals(pool.getHypervisor())) {
- hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZone(pool.getDataCenterId());
- }
- else {
- hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(pool.getHypervisor(), pool.getDataCenterId());
- }
- } else {
- hosts = _resourceMgr.listHostsInClusterByStatus(pool.getClusterId(), Status.Up);
+ getStoragePoolForSpecification(pool);
+
+ List<HostVO> hosts = getHostsForStoragePool(pool);
+
+ if (setNextStateForMaintenance(hosts, pool) == StoragePoolStatus.PrepareForMaintenance) {
+ removeHeartbeatForHostsFromPool(hosts, pool);
+ // check to see if other ps exist
+ // if they do, then we can migrate over the system vms to them
+ // if they don't, then just stop all vms on this one
+ List<StoragePoolVO> upPools = primaryDataStoreDao.listByStatusInZone(pool.getDataCenterId(), StoragePoolStatus.Up);
+ boolean restart = !CollectionUtils.isEmpty(upPools);
+
+ // 2. Get a list of all the ROOT volumes within this storage pool
+ List<VolumeVO> allVolumes = volumeDao.findByPoolId(pool.getId());
+ // 3. Enqueue to the work queue
+ enqueueMigrationsForVolumes(allVolumes, pool);
+ // 4. Process the queue
+ processMigrationWorkloads(pool, restart);
}
+ } catch (Exception e) {
+ logger.error("Exception in enabling primary storage maintenance:", e);
+ pool.setStatus(StoragePoolStatus.ErrorInMaintenance);
+ primaryDataStoreDao.update(pool.getId(), pool);
+ // TODO decide on what recovery is possible
+ throw new CloudRuntimeException(e.getMessage());
+ }
+ return true;
+ }
- if (hosts == null || hosts.size() == 0) {
- pool.setStatus(StoragePoolStatus.Maintenance);
- primaryDataStoreDao.update(pool.getId(), pool);
- return true;
- } else {
- // set the pool state to prepare for maintenance
- pool.setStatus(StoragePoolStatus.PrepareForMaintenance);
- primaryDataStoreDao.update(pool.getId(), pool);
- }
- // remove heartbeat
- for (HostVO host : hosts) {
- ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(false, storagePool);
- if (MapUtils.isNotEmpty(details) && storageManager.canDisconnectHostFromStoragePool(host, storagePool)) {
- cmd.setDetails(details);
- }
- final Answer answer = agentMgr.easySend(host.getId(), cmd);
- if (answer == null || !answer.getResult()) {
- if (logger.isDebugEnabled()) {
- logger.debug("ModifyStoragePool false failed due to " + ((answer == null) ? "answer null" : answer.getDetails()));
- }
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("ModifyStoragePool false succeeded");
- }
- if (pool.getPoolType() == Storage.StoragePoolType.DatastoreCluster) {
- logger.debug("Started synchronising datastore cluster storage pool {} with vCenter", pool);
- storageManager.syncDatastoreClusterStoragePool(pool.getId(), ((ModifyStoragePoolAnswer) answer).getDatastoreClusterChildren(), host.getId());
- }
- }
- }
- // check to see if other ps exist
- // if they do, then we can migrate over the system vms to them
- // if they don't, then just stop all vms on this one
- List<StoragePoolVO> upPools = primaryDataStoreDao.listByStatusInZone(pool.getDataCenterId(), StoragePoolStatus.Up);
- boolean restart = true;
- if (upPools == null || upPools.size() == 0) {
- restart = false;
- }
+ @Override
+ public boolean cancelMaintain(DataStore store) {
++ return cancelMaintain(store, null);
++ }
+
- // 2. Get a list of all the ROOT volumes within this storage pool
- List<VolumeVO> allVolumes = volumeDao.findByPoolId(pool.getId());
++ @Override
++ public boolean cancelMaintain(DataStore store, Map<String,String> details) {
+ // Change the storage state back to up
+ StoragePoolVO poolVO = primaryDataStoreDao.findById(store.getId());
+ StoragePool pool = (StoragePool)store;
- // 3. Enqueue to the work queue
- for (VolumeVO volume : allVolumes) {
- VMInstanceVO vmInstance = vmDao.findById(volume.getInstanceId());
+ List<HostVO> hosts = getHostsForStoragePool(poolVO);
- if (vmInstance == null) {
- continue;
- }
+ if (CollectionUtils.isEmpty(hosts)) {
+ return true;
+ }
- // enqueue sp work
- if (vmInstance.getState().equals(State.Running) || vmInstance.getState().equals(State.Starting) || vmInstance.getState().equals(State.Stopping)) {
-
- try {
- StoragePoolWorkVO work = new StoragePoolWorkVO(vmInstance.getId(), pool.getId(), false, false, server.getId());
- _storagePoolWorkDao.persist(work);
- } catch (Exception e) {
- if (logger.isDebugEnabled()) {
- logger.debug("Work record already exists, re-using by re-setting values");
- }
- StoragePoolWorkVO work = _storagePoolWorkDao.findByPoolIdAndVmId(pool.getId(), vmInstance.getId());
- work.setStartedAfterMaintenance(false);
- work.setStoppedForMaintenance(false);
- work.setManagementServerId(server.getId());
- _storagePoolWorkDao.update(work.getId(), work);
- }
- }
+ Pair<Map<String, String>, Boolean> nfsMountOpts = storageManager.getStoragePoolNFSMountOpts(pool, null);
+ addHeartbeatToHostsInPool(hosts, pool, nfsMountOpts);
+
+ // 2. Get a list of pending work for this queue
+ List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForCancelMaintenanceByPoolId(poolVO.getId());
+
+ // 3. work through the queue
+ cancelMigrationWorkloads(pendingWork);
+ return false;
+ }
+
+ private StoragePoolStatus setNextStateForMaintenance(List<HostVO> hosts, StoragePoolVO pool) {
+ if (CollectionUtils.isEmpty(hosts)) {
+ pool.setStatus(StoragePoolStatus.Maintenance);
+ primaryDataStoreDao.update(pool.getId(), pool);
+ return StoragePoolStatus.Maintenance;
+ } else {
+ // set the pool state to prepare for maintenance
+ pool.setStatus(StoragePoolStatus.PrepareForMaintenance);
+ primaryDataStoreDao.update(pool.getId(), pool);
+ return StoragePoolStatus.PrepareForMaintenance;
+ }
+ }
+
+ private void processMigrationWorkloads(StoragePoolVO pool, boolean restart) throws ResourceUnavailableException, OperationTimedoutException, InsufficientCapacityException {
+ List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForPrepareForMaintenanceByPoolId(pool.getId());
+
+ for (StoragePoolWorkVO work : pendingWork) {
+ // shut down the running vms
+ VMInstanceVO vmInstance = vmDao.findById(work.getVmId());
+
+ if (vmInstance == null) {
+ continue;
}
- // 4. Process the queue
- List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForPrepareForMaintenanceByPoolId(pool.getId());
+ switch (vmInstance.getType()) {
+ case ConsoleProxy:
+ case SecondaryStorageVm:
+ case DomainRouter:
+ handleVmMigration(restart, work, vmInstance);
+ break;
+ case User:
+ handleStopVmForMigration(work, vmInstance);
+ break;
+ }
+ }
+ }
- for (StoragePoolWorkVO work : pendingWork) {
- // shut down the running vms
+ private void cancelMigrationWorkloads(List<StoragePoolWorkVO> pendingWork) {
+ for (StoragePoolWorkVO work : pendingWork) {
+ try {
VMInstanceVO vmInstance = vmDao.findById(work.getVmId());
if (vmInstance == null) {
continue;
}
- // if the instance is of type consoleproxy, call the console
- // proxy
- if (vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) {
- // call the consoleproxymanager
- ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(vmInstance.getId());
- vmMgr.advanceStop(consoleProxy.getUuid(), false);
- // update work status
- work.setStoppedForMaintenance(true);
- _storagePoolWorkDao.update(work.getId(), work);
+ switch (vmInstance.getType()) {
+ case ConsoleProxy:
+ case SecondaryStorageVm:
+ case DomainRouter:
+ handleVmStart(work, vmInstance);
+ break;
+ case User:
+ handleUserVmStart(work, vmInstance);
+ break;
+ }
+ } catch (Exception e) {
+ logger.debug("Failed start vm", e);
+ throw new CloudRuntimeException(e.toString());
+ }
+ }
+ }
- if (restart) {
+ private void handleStopVmForMigration(StoragePoolWorkVO work, VMInstanceVO vmInstance) throws ResourceUnavailableException, OperationTimedoutException {
+ vmMgr.advanceStop(vmInstance.getUuid(), false);
+ // update work status
+ work.setStoppedForMaintenance(true);
+ _storagePoolWorkDao.update(work.getId(), work);
+ }
- vmMgr.advanceStart(consoleProxy.getUuid(), null, null);
- // update work status
- work.setStartedAfterMaintenance(true);
- _storagePoolWorkDao.update(work.getId(), work);
- }
- }
+ private void handleVmMigration(boolean restart, StoragePoolWorkVO work, VMInstanceVO vmInstance) throws ResourceUnavailableException, OperationTimedoutException, InsufficientCapacityException {
+ handleStopVmForMigration(work, vmInstance);
- // if the instance is of type uservm, call the user vm manager
- if (vmInstance.getType() == VirtualMachine.Type.User) {
- UserVmVO userVm = userVmDao.findById(vmInstance.getId());
- vmMgr.advanceStop(userVm.getUuid(), false);
- // update work status
- work.setStoppedForMaintenance(true);
- _storagePoolWorkDao.update(work.getId(), work);
- }
+ if (restart) {
+ handleVmStart(work, vmInstance);
+ }
+ }
+
- // if the instance is of type secondary storage vm, call the
- // secondary storage vm manager
- if (vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) {
- SecondaryStorageVmVO secStrgVm = _secStrgDao.findById(vmInstance.getId());
- vmMgr.advanceStop(secStrgVm.getUuid(), false);
- // update work status
- work.setStoppedForMaintenance(true);
- _storagePoolWorkDao.update(work.getId(), work);
+ private void handleVmStart(StoragePoolWorkVO work, VMInstanceVO vmInstance) throws InsufficientCapacityException, ResourceUnavailableException, OperationTimedoutException {
+ vmMgr.advanceStart(vmInstance.getUuid(), null, null);
+ // update work queue
+ work.setStartedAfterMaintenance(true);
+ _storagePoolWorkDao.update(work.getId(), work);
+ }
- if (restart) {
- vmMgr.advanceStart(secStrgVm.getUuid(), null, null);
- // update work status
- work.setStartedAfterMaintenance(true);
- _storagePoolWorkDao.update(work.getId(), work);
- }
- }
+ private void enqueueMigrationsForVolumes(List<VolumeVO> allVolumes, StoragePoolVO pool) {
+ for (VolumeVO volume : allVolumes) {
+ VMInstanceVO vmInstance = vmDao.findById(volume.getInstanceId());
- // if the instance is of type domain router vm, call the network
- // manager
- if (vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) {
- DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
- vmMgr.advanceStop(domR.getUuid(), false);
- // update work status
- work.setStoppedForMaintenance(true);
- _storagePoolWorkDao.update(work.getId(), work);
+ if (vmInstance == null) {
+ continue;
+ }
- if (restart) {
- vmMgr.advanceStart(domR.getUuid(), null, null);
- // update work status
- work.setStartedAfterMaintenance(true);
- _storagePoolWorkDao.update(work.getId(), work);
+ // enqueue sp work
+ if (vmInstance.getState().equals(State.Running) || vmInstance.getState().equals(State.Starting) || vmInstance.getState().equals(State.Stopping)) {
+
+ try {
+ StoragePoolWorkVO work = new StoragePoolWorkVO(vmInstance.getId(), pool.getId(), false, false, server.getId());
+ _storagePoolWorkDao.persist(work);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Work record already exists, re-using by re-setting values");
}
+ StoragePoolWorkVO work = _storagePoolWorkDao.findByPoolIdAndVmId(pool.getId(), vmInstance.getId());
+ work.setStartedAfterMaintenance(false);
+ work.setStoppedForMaintenance(false);
+ work.setManagementServerId(server.getId());
+ _storagePoolWorkDao.update(work.getId(), work);
}
}
- } catch (Exception e) {
- logger.error("Exception in enabling primary storage maintenance:", e);
- pool.setStatus(StoragePoolStatus.ErrorInMaintenance);
- primaryDataStoreDao.update(pool.getId(), pool);
- throw new CloudRuntimeException(e.getMessage());
}
- return true;
}
- @Override
- public boolean cancelMaintain(DataStore store) {
- return cancelMaintain(store, null);
+ private void removeHeartbeatForHostsFromPool(List<HostVO> hosts, StoragePool storagePool) {
+ // remove heartbeat
+ for (HostVO host : hosts) {
+ ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(false, storagePool);
+ final Answer answer = agentMgr.easySend(host.getId(), cmd);
+ if (answer == null || !answer.getResult()) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("ModifyStoragePool false failed due to {}", ((answer == null) ? "answer null" : answer.getDetails()));
+ }
+ } else {
+ reportSucceededModifyStorePool(storagePool, (ModifyStoragePoolAnswer) answer, host, false);
+ }
+ }
}
- @Override
- public boolean cancelMaintain(DataStore store, Map<String,String> details) {
- // Change the storage state back to up
- Long userId = CallContext.current().getCallingUserId();
- User user = _userDao.findById(userId);
- Account account = CallContext.current().getCallingAccount();
- StoragePoolVO poolVO = primaryDataStoreDao.findById(store.getId());
- StoragePool pool = (StoragePool)store;
+ private void reportSucceededModifyStorePool(StoragePool storagePool, ModifyStoragePoolAnswer answer, HostVO host, boolean add) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("ModifyStoragePool succeeded for {}", add ? "adding" : "removing");
+ }
+ if (storagePool.getPoolType() == Storage.StoragePoolType.DatastoreCluster) {
+ logger.debug("Started synchronising datastore cluster storage pool {} with vCenter", storagePool);
+ storageManager.syncDatastoreClusterStoragePool(storagePool.getId(), answer.getDatastoreClusterChildren(), host.getId());
+ }
+ }
- //Handeling the Zone wide and cluster wide primay storage
- List<HostVO> hosts = new ArrayList<HostVO>();
- // if the storage scope is ZONE wide, then get all the hosts for which hypervisor ZWSP created to send Modifystoragepoolcommand
- if (poolVO.getScope().equals(ScopeType.ZONE)) {
+ /**
+ * Handling the Zone wide and cluster wide primary storage
+ * if the storage scope is ZONE wide, then get all the hosts for which hypervisor ZoneWideStoragePools created to send ModifyStoragePoolCommand
+ * TODO: if it's zone wide, this code will list a lot of hosts in the zone, which may cause performance/OOM issue.
+ * @param pool pool to check for connected hosts
+ * @return a list of connected hosts
+ */
+ private List<HostVO> getHostsForStoragePool(StoragePoolVO pool) {
+ List<HostVO> hosts;
+ if (pool.getScope().equals(ScopeType.ZONE)) {
if (HypervisorType.Any.equals(pool.getHypervisor())) {
hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZone(pool.getDataCenterId());
}
diff --cc server/src/test/java/com/cloud/server/ManagementServerImplTest.java
index 2f52df982b7,da2005f6136..b569368f248
--- a/server/src/test/java/com/cloud/server/ManagementServerImplTest.java
+++ b/server/src/test/java/com/cloud/server/ManagementServerImplTest.java
@@@ -16,65 -16,21 +16,67 @@@
// under the License.
package com.cloud.server;
-import com.cloud.api.ApiDBUtils;
-import com.cloud.dc.DataCenterVO;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
++import org.junit.After;
++import org.junit.Assert;
++import org.junit.Before;
++import org.junit.Test;
++import org.junit.runner.RunWith;
++import org.mockito.InjectMocks;
++import org.mockito.Mock;
++import org.mockito.MockedStatic;
++import org.mockito.Mockito;
++import org.mockito.MockitoAnnotations;
++import org.mockito.Spy;
++import org.mockito.junit.MockitoJUnitRunner;
++import org.mockito.stubbing.Answer;
++import org.springframework.test.util.ReflectionTestUtils;
++
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.cloudstack.annotation.dao.AnnotationDao;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd;
+import org.apache.cloudstack.api.command.admin.guest.AddGuestOsCategoryCmd;
+import org.apache.cloudstack.api.command.admin.guest.DeleteGuestOsCategoryCmd;
+import org.apache.cloudstack.api.command.admin.guest.UpdateGuestOsCategoryCmd;
+import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd;
+import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd;
+import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd;
+import org.apache.cloudstack.api.command.user.userdata.DeleteUserDataCmd;
+import org.apache.cloudstack.api.command.user.userdata.ListUserDataCmd;
+import org.apache.cloudstack.api.command.user.userdata.RegisterUserDataCmd;
+import org.apache.cloudstack.config.Configuration;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver;
+import org.apache.cloudstack.framework.config.ConfigDepot;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
+import org.apache.cloudstack.framework.config.impl.ConfigurationVO;
+import org.apache.cloudstack.framework.extensions.manager.ExtensionsManager;
+import org.apache.cloudstack.userdata.UserDataManager;
- import org.junit.After;
- import org.junit.Assert;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.mockito.InjectMocks;
- import org.mockito.Mock;
- import org.mockito.MockedStatic;
- import org.mockito.Mockito;
- import org.mockito.MockitoAnnotations;
- import org.mockito.Spy;
- import org.mockito.junit.MockitoJUnitRunner;
- import org.mockito.stubbing.Answer;
- import org.springframework.test.util.ReflectionTestUtils;
+
+import com.cloud.cpu.CPU;
import com.cloud.dc.Vlan.VlanType;
-import com.cloud.dc.dao.DataCenterDao;
-import com.cloud.deploy.DeploymentPlanningManager;
+import com.cloud.domain.dao.DomainDao;
++import com.cloud.api.ApiDBUtils;
import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.PermissionDeniedException;
-import com.cloud.gpu.GPU;
import com.cloud.host.DetailVO;
import com.cloud.host.Host;
-import com.cloud.host.Host.Type;
import com.cloud.host.HostVO;
-import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao;
-import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.IpAddress;
import com.cloud.network.IpAddressManagerImpl;
import com.cloud.network.dao.IPAddressVO;
@@@ -99,11 -59,57 +101,12 @@@ import com.cloud.utils.db.Filter
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.vm.UserVmDetailVO;
import com.cloud.vm.UserVmVO;
-import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.VMInstanceDetailVO;
import com.cloud.vm.VirtualMachine;
-import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.UserVmDao;
-import com.cloud.vm.dao.UserVmDetailsDao;
-import com.cloud.vm.dao.VMInstanceDao;
-import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
-import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
-import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
-import com.cloud.hypervisor.kvm.dpdk.DpdkHelper;
+import com.cloud.vm.dao.VMInstanceDetailsDao;
+ import com.cloud.agent.manager.allocator.HostAllocator;
-import org.apache.cloudstack.annotation.dao.AnnotationDao;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd;
-import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd;
-import org.apache.cloudstack.api.command.user.userdata.DeleteUserDataCmd;
-import org.apache.cloudstack.api.command.user.userdata.ListUserDataCmd;
-import org.apache.cloudstack.api.command.user.userdata.RegisterUserDataCmd;
-import org.apache.cloudstack.context.CallContext;
-import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore;
-import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver;
-import org.apache.cloudstack.framework.config.ConfigKey;
-import org.apache.cloudstack.userdata.UserDataManager;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockedStatic;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.nullable;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.lenient;
-import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ManagementServerImplTest {
@@@ -130,19 -136,19 +133,19 @@@
IpAddressManagerImpl ipAddressManagerImpl;
@Mock
-- AccountManager _accountMgr;
++ AccountManager accountManager;
@Mock
-- UserDataDao _userDataDao;
++ UserDataDao userDataDao;
@Mock
- VMTemplateDao _templateDao;
+ VMTemplateDao templateDao;
@Mock
AnnotationDao annotationDao;
@Mock
-- UserVmDao _userVmDao;
++ UserVmDao userVmDao;
@Mock
UserDataManager userDataManager;
@@@ -154,33 -160,74 +157,52 @@@
HostDetailsDao hostDetailsDao;
@Mock
- VMInstanceDao vmInstanceDao;
-
- @Mock
- HostDao hostDao;
-
- @Mock
- ServiceOfferingDetailsDao serviceOfferingDetailsDao;
-
- @Mock
- VolumeDao volumeDao;
+ ConfigurationDao configDao;
@Mock
- ServiceOfferingDao offeringDao;
+ ConfigDepot configDepot;
@Mock
- DiskOfferingDao diskOfferingDao;
+ DomainDao domainDao;
@Mock
- GuestOSCategoryDao _guestOSCategoryDao;
- HypervisorCapabilitiesDao hypervisorCapabilitiesDao;
++ GuestOSCategoryDao guestOSCategoryDao;
@Mock
- GuestOSDao _guestOSDao;
- DataStoreManager dataStoreManager;
++ GuestOSDao guestOSDao;
@Mock
- PrimaryDataStoreDao primaryDataStoreDao;
+ ExtensionsManager extensionManager;
- @Mock
- DpdkHelper dpdkHelper;
-
- @Mock
- AffinityGroupVMMapDao affinityGroupVMMapDao;
-
- @Mock
- DeploymentPlanningManager dpMgr;
-
- @Mock
- DataCenterDao dcDao;
+ @Spy
+ @InjectMocks
+ ManagementServerImpl spy = new ManagementServerImpl();
+ @Mock
+ HostAllocator hostAllocator;
+
- @InjectMocks
- @Spy
- ManagementServerImpl spy;
-
private AutoCloseable closeable;
+ private MockedStatic<ApiDBUtils> apiDBUtilsMock;
@Before
public void setup() throws IllegalAccessException, NoSuchFieldException {
closeable = MockitoAnnotations.openMocks(this);
CallContext.register(Mockito.mock(User.class), Mockito.mock(Account.class));
- spy._accountMgr = _accountMgr;
- spy.userDataDao = _userDataDao;
- spy.templateDao = _templateDao;
- spy._userVmDao = _userVmDao;
++ spy._accountMgr = accountManager;
++ spy.userDataDao = userDataDao;
++ spy.templateDao = templateDao;
++ spy._userVmDao = userVmDao;
+ spy.annotationDao = annotationDao;
- spy._UserVmDetailsDao = userVmDetailsDao;
+ spy._detailsDao = hostDetailsDao;
+ spy.userDataManager = userDataManager;
+
+ spy.setHostAllocators(List.of(hostAllocator));
+
+ // Mock ApiDBUtils static method
+ apiDBUtilsMock = Mockito.mockStatic(ApiDBUtils.class);
+ // Return empty list to avoid architecture filtering in most tests
+ apiDBUtilsMock.when(() -> ApiDBUtils.listZoneClustersArchs(Mockito.anyLong()))
+ .thenReturn(new ArrayList<>());
}
@After
@@@ -345,7 -395,7 +370,7 @@@
when(account.getAccountId()).thenReturn(1L);
when(account.getDomainId()).thenReturn(2L);
when(callContextMock.getCallingAccount()).thenReturn(account);
-- when(_accountMgr.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
++ when(accountManager.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
String testUserData = "testUserdata";
RegisterUserDataCmd cmd = Mockito.mock(RegisterUserDataCmd.class);
@@@ -353,8 -403,8 +378,8 @@@
when(cmd.getName()).thenReturn("testName");
when(cmd.getHttpMethod()).thenReturn(BaseCmd.HTTPMethod.GET);
-- when(_userDataDao.findByName(account.getAccountId(), account.getDomainId(), "testName")).thenReturn(null);
-- when(_userDataDao.findByUserData(account.getAccountId(), account.getDomainId(), testUserData)).thenReturn(null);
++ when(userDataDao.findByName(account.getAccountId(), account.getDomainId(), "testName")).thenReturn(null);
++ when(userDataDao.findByUserData(account.getAccountId(), account.getDomainId(), testUserData)).thenReturn(null);
when(userDataManager.validateUserData(testUserData, BaseCmd.HTTPMethod.GET)).thenReturn(testUserData);
UserData userData = spy.registerUserData(cmd);
@@@ -373,15 -423,15 +398,15 @@@
when(account.getAccountId()).thenReturn(1L);
when(account.getDomainId()).thenReturn(2L);
when(callContextMock.getCallingAccount()).thenReturn(account);
-- when(_accountMgr.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
++ when(accountManager.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
RegisterUserDataCmd cmd = Mockito.mock(RegisterUserDataCmd.class);
when(cmd.getUserData()).thenReturn("testUserdata");
when(cmd.getName()).thenReturn("testName");
UserDataVO userData = Mockito.mock(UserDataVO.class);
-- when(_userDataDao.findByName(account.getAccountId(), account.getDomainId(), "testName")).thenReturn(null);
-- when(_userDataDao.findByUserData(account.getAccountId(), account.getDomainId(), "testUserdata")).thenReturn(userData);
++ when(userDataDao.findByName(account.getAccountId(), account.getDomainId(), "testName")).thenReturn(null);
++ when(userDataDao.findByUserData(account.getAccountId(), account.getDomainId(), "testUserdata")).thenReturn(userData);
spy.registerUserData(cmd);
}
@@@ -395,13 -445,13 +420,13 @@@
when(account.getAccountId()).thenReturn(1L);
when(account.getDomainId()).thenReturn(2L);
Mockito.when(callContextMock.getCallingAccount()).thenReturn(account);
-- when(_accountMgr.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
++ when(accountManager.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
RegisterUserDataCmd cmd = Mockito.mock(RegisterUserDataCmd.class);
when(cmd.getName()).thenReturn("testName");
UserDataVO userData = Mockito.mock(UserDataVO.class);
-- when(_userDataDao.findByName(account.getAccountId(), account.getDomainId(), "testName")).thenReturn(userData);
++ when(userDataDao.findByName(account.getAccountId(), account.getDomainId(), "testName")).thenReturn(userData);
spy.registerUserData(cmd);
}
@@@ -413,7 -463,7 +438,7 @@@
CallContext callContextMock = Mockito.mock(CallContext.class);
when(CallContext.current()).thenReturn(callContextMock);
when(callContextMock.getCallingAccount()).thenReturn(account);
-- when(_accountMgr.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
++ when(accountManager.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
DeleteUserDataCmd cmd = Mockito.mock(DeleteUserDataCmd.class);
when(cmd.getAccountName()).thenReturn("testAccountName");
@@@ -423,10 -473,10 +448,10 @@@
UserDataVO userData = Mockito.mock(UserDataVO.class);
Mockito.when(userData.getId()).thenReturn(1L);
-- when(_userDataDao.findById(1L)).thenReturn(userData);
- when(_templateDao.findTemplatesLinkedToUserdata(1L)).thenReturn(new ArrayList<VMTemplateVO>());
- when(_userVmDao.findByUserDataId(1L)).thenReturn(new ArrayList<UserVmVO>());
- when(_userDataDao.remove(1L)).thenReturn(true);
++ when(userDataDao.findById(1L)).thenReturn(userData);
+ when(templateDao.findTemplatesLinkedToUserdata(1L)).thenReturn(new ArrayList<VMTemplateVO>());
- when(_userVmDao.findByUserDataId(1L)).thenReturn(new ArrayList<UserVmVO>());
- when(_userDataDao.remove(1L)).thenReturn(true);
++ when(userVmDao.findByUserDataId(1L)).thenReturn(new ArrayList<UserVmVO>());
++ when(userDataDao.remove(1L)).thenReturn(true);
boolean result = spy.deleteUserData(cmd);
Assert.assertEquals(true, result);
@@@ -439,7 -489,7 +464,7 @@@
CallContext callContextMock = Mockito.mock(CallContext.class);
when(CallContext.current()).thenReturn(callContextMock);
when(callContextMock.getCallingAccount()).thenReturn(account);
-- when(_accountMgr.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
++ when(accountManager.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
DeleteUserDataCmd cmd = Mockito.mock(DeleteUserDataCmd.class);
when(cmd.getAccountName()).thenReturn("testAccountName");
@@@ -449,7 -499,7 +474,7 @@@
UserDataVO userData = Mockito.mock(UserDataVO.class);
Mockito.when(userData.getId()).thenReturn(1L);
-- when(_userDataDao.findById(1L)).thenReturn(userData);
++ when(userDataDao.findById(1L)).thenReturn(userData);
VMTemplateVO vmTemplateVO = Mockito.mock(VMTemplateVO.class);
List<VMTemplateVO> linkedTemplates = new ArrayList<>();
@@@ -466,7 -516,7 +491,7 @@@
CallContext callContextMock = Mockito.mock(CallContext.class);
when(CallContext.current()).thenReturn(callContextMock);
when(callContextMock.getCallingAccount()).thenReturn(account);
-- when(_accountMgr.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
++ when(accountManager.finalizeOwner(nullable(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
DeleteUserDataCmd cmd = Mockito.mock(DeleteUserDataCmd.class);
when(cmd.getAccountName()).thenReturn("testAccountName");
@@@ -476,14 -526,14 +501,14 @@@
UserDataVO userData = Mockito.mock(UserDataVO.class);
Mockito.when(userData.getId()).thenReturn(1L);
-- when(_userDataDao.findById(1L)).thenReturn(userData);
++ when(userDataDao.findById(1L)).thenReturn(userData);
- when(_templateDao.findTemplatesLinkedToUserdata(1L)).thenReturn(new ArrayList<VMTemplateVO>());
+ when(templateDao.findTemplatesLinkedToUserdata(1L)).thenReturn(new ArrayList<VMTemplateVO>());
UserVmVO userVmVO = Mockito.mock(UserVmVO.class);
List<UserVmVO> vms = new ArrayList<>();
vms.add(userVmVO);
-- when(_userVmDao.findByUserDataId(1L)).thenReturn(vms);
++ when(userVmDao.findByUserDataId(1L)).thenReturn(vms);
spy.deleteUserData(cmd);
}
@@@ -504,7 -554,7 +529,7 @@@
UserDataVO userData = Mockito.mock(UserDataVO.class);
SearchBuilder<UserDataVO> sb = Mockito.mock(SearchBuilder.class);
-- when(_userDataDao.createSearchBuilder()).thenReturn(sb);
++ when(userDataDao.createSearchBuilder()).thenReturn(sb);
when(sb.entity()).thenReturn(userData);
SearchCriteria<UserDataVO> sc = Mockito.mock(SearchCriteria.class);
@@@ -513,9 -563,9 +538,9 @@@
List<UserDataVO> userDataList = new ArrayList<UserDataVO>();
userDataList.add(userData);
Pair<List<UserDataVO>, Integer> result = new Pair(userDataList, 1);
-- when(_userDataDao.searchAndCount(nullable(SearchCriteria.class), nullable(Filter.class))).thenReturn(result);
++ when(userDataDao.searchAndCount(nullable(SearchCriteria.class), nullable(Filter.class))).thenReturn(result);
- Pair<List<? extends UserData>, Integer> userdataResultList = spy.listUserDatas(cmd);
+ Pair<List<? extends UserData>, Integer> userdataResultList = spy.listUserDatas(cmd, false);
Assert.assertEquals(userdataResultList.first().get(0), userDataList.get(0));
}
@@@ -537,7 -587,7 +562,7 @@@
UserDataVO userData = Mockito.mock(UserDataVO.class);
SearchBuilder<UserDataVO> sb = Mockito.mock(SearchBuilder.class);
-- when(_userDataDao.createSearchBuilder()).thenReturn(sb);
++ when(userDataDao.createSearchBuilder()).thenReturn(sb);
when(sb.entity()).thenReturn(userData);
SearchCriteria<UserDataVO> sc = Mockito.mock(SearchCriteria.class);
@@@ -546,9 -596,9 +571,9 @@@
List<UserDataVO> userDataList = new ArrayList<UserDataVO>();
userDataList.add(userData);
Pair<List<UserDataVO>, Integer> result = new Pair(userDataList, 1);
-- when(_userDataDao.searchAndCount(nullable(SearchCriteria.class), nullable(Filter.class))).thenReturn(result);
++ when(userDataDao.searchAndCount(nullable(SearchCriteria.class), nullable(Filter.class))).thenReturn(result);
- Pair<List<? extends UserData>, Integer> userdataResultList = spy.listUserDatas(cmd);
+ Pair<List<? extends UserData>, Integer> userdataResultList = spy.listUserDatas(cmd, false);
Assert.assertEquals(userdataResultList.first().get(0), userDataList.get(0));
}
@@@ -570,7 -620,7 +595,7 @@@
UserDataVO userData = Mockito.mock(UserDataVO.class);
SearchBuilder<UserDataVO> sb = Mockito.mock(SearchBuilder.class);
-- when(_userDataDao.createSearchBuilder()).thenReturn(sb);
++ when(userDataDao.createSearchBuilder()).thenReturn(sb);
when(sb.entity()).thenReturn(userData);
SearchCriteria<UserDataVO> sc = Mockito.mock(SearchCriteria.class);
@@@ -579,9 -629,9 +604,9 @@@
List<UserDataVO> userDataList = new ArrayList<UserDataVO>();
userDataList.add(userData);
Pair<List<UserDataVO>, Integer> result = new Pair(userDataList, 1);
-- when(_userDataDao.searchAndCount(nullable(SearchCriteria.class), nullable(Filter.class))).thenReturn(result);
++ when(userDataDao.searchAndCount(nullable(SearchCriteria.class), nullable(Filter.class))).thenReturn(result);
- Pair<List<? extends UserData>, Integer> userdataResultList = spy.listUserDatas(cmd);
+ Pair<List<? extends UserData>, Integer> userdataResultList = spy.listUserDatas(cmd, false);
Assert.assertEquals(userdataResultList.first().get(0), userDataList.get(0));
}
@@@ -731,352 -844,1234 +756,307 @@@
}
@Test
- public void testListHostsForMigrationOfVMWithSystemVM() {
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.VMware);
- Mockito.when(vm.getType()).thenReturn(VirtualMachine.Type.ConsoleProxy);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.VMware);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // System VMs can use storage motion
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.VMware, null))
- .thenReturn(true);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers with zone-wide scope (storage motion enabled)
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.VMware);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.VMware);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.any(HypervisorType.class), Mockito.isNull(), Mockito.anyLong());
+ public void testSearchForConfigurations() {
+ Long poolId = 1L;
+ ListCfgsByCmd cmd = Mockito.mock(ListCfgsByCmd.class);
+ Mockito.when(cmd.getConfigName()).thenReturn("pool.storage.capacity.disablethreshold");
+ Mockito.when(cmd.getStoragepoolId()).thenReturn(poolId);
+ Mockito.when(cmd.getZoneId()).thenReturn(null);
+ Mockito.when(cmd.getClusterId()).thenReturn(null);
+ Mockito.when(cmd.getAccountId()).thenReturn(null);
+ Mockito.when(cmd.getDomainId()).thenReturn(null);
+ Mockito.when(cmd.getImageStoreId()).thenReturn(null);
- setupMigrationMocks(vm, srcHost, hosts, volume, true);
+ SearchCriteria<ConfigurationVO> sc = Mockito.mock(SearchCriteria.class);
+ Mockito.when(configDao.createSearchCriteria()).thenReturn(sc);
+ ConfigurationVO cfg = new ConfigurationVO("Advanced", "DEFAULT", "test", "pool.storage.capacity.disablethreshold", null, "description");
+ Mockito.when(configDao.searchAndCount(any(), any())).thenReturn(new Pair<>(List.of(cfg), 1));
+ Mockito.when(configDao.findByName("pool.storage.capacity.disablethreshold")).thenReturn(cfg);
- // Verify this doesn't throw exception - system VMs should be migratable
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
+ ConfigKey storageDisableThreshold = new ConfigKey<>(ConfigKey.CATEGORY_ALERT, Double.class, "pool.storage.capacity.disablethreshold", "0.85",
+ "Percentage (as a value between 0 and 1) of storage utilization above which allocators will disable using the pool for low storage available.",
+ true, List.of(ConfigKey.Scope.StoragePool, ConfigKey.Scope.Zone));
+ when(configDepot.get("pool.storage.capacity.disablethreshold")).thenReturn(storageDisableThreshold);
- // Verify storage motion capability was checked
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.VMware, null);
+ Pair<List<? extends Configuration>, Integer> result = spy.searchForConfigurations(cmd);
- // Verify result structure and data
- Assert.assertNotNull(result);
- Assert.assertNotNull("All hosts list should not be null", result.first());
- Assert.assertNotNull("Suitable hosts list should not be null", result.second());
- Assert.assertNotNull("Storage motion map should not be null", result.third());
-
- // Verify all hosts returned (from searchForServers)
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("All hosts list should contain 2 hosts", 2, result.first().first().size());
-
- // Verify suitable hosts (from host allocator)
- Assert.assertEquals("Should return 2 suitable hosts", 2, result.second().size());
- Assert.assertTrue("Suitable hosts should contain host1",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Suitable hosts should contain host2",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
+ Assert.assertEquals("0.85", result.first().get(0).getValue());
}
-
@Test
- public void testListHostsForMigrationOfVMWithDomainRouter() {
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Mockito.when(vm.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume);
-
- // Verify domain router can be migrated
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify hypervisor capabilities were checked
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.KVM, "");
-
- // Verify result contains expected hosts
+ public void testAddGuestOsCategory() {
+ AddGuestOsCategoryCmd addCmd = Mockito.mock(AddGuestOsCategoryCmd.class);
+ String name = "Ubuntu";
+ boolean featured = true;
+ Mockito.when(addCmd.getName()).thenReturn(name);
+ Mockito.when(addCmd.isFeatured()).thenReturn(featured);
- Mockito.doAnswer((Answer<GuestOSCategoryVO>) invocation -> (GuestOSCategoryVO)invocation.getArguments()[0]).when(_guestOSCategoryDao).persist(Mockito.any(GuestOSCategoryVO.class));
++ Mockito.doAnswer((Answer<GuestOSCategoryVO>) invocation -> (GuestOSCategoryVO)invocation.getArguments()[0]).when(guestOSCategoryDao).persist(Mockito.any(GuestOSCategoryVO.class));
+ GuestOsCategory result = spy.addGuestOsCategory(addCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should return 2 suitable hosts", 2, result.second().size());
- Assert.assertTrue("Result should contain host 101",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Result should contain host 102",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
+ Assert.assertEquals(name, result.getName());
+ Assert.assertEquals(featured, result.isFeatured());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).persist(any(GuestOSCategoryVO.class));
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).persist(any(GuestOSCategoryVO.class));
}
@Test
- public void testListHostsForMigrationOfVMWithMultipleVolumes() {
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- // Multiple volumes - root and data disk
- VolumeVO rootVolume = mockVolume(1L, 1L);
- VolumeVO dataVolume = mockVolume(2L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(rootVolume, dataVolume));
-
- DiskOfferingVO sharedOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(1L)).thenReturn(sharedOffering);
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, rootVolume);
-
- // Verify multiple volumes are handled
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify all volumes were checked
- Mockito.verify(volumeDao).findCreatedByInstance(vm.getId());
- Mockito.verify(diskOfferingDao, Mockito.times(2)).findById(1L);
-
- // Verify result
+ public void testUpdateGuestOsCategory() {
+ UpdateGuestOsCategoryCmd updateCmd = Mockito.mock(UpdateGuestOsCategoryCmd.class);
+ GuestOSCategoryVO guestOSCategory = new GuestOSCategoryVO("Old name", false);
+ long id = 1L;
+ String name = "Updated Name";
+ Boolean featured = true;
+ Integer sortKey = 10;
+ Mockito.when(updateCmd.getId()).thenReturn(id);
+ Mockito.when(updateCmd.getName()).thenReturn(name);
+ Mockito.when(updateCmd.isFeatured()).thenReturn(featured);
+ Mockito.when(updateCmd.getSortKey()).thenReturn(sortKey);
- Mockito.when(_guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
- Mockito.when(_guestOSCategoryDao.update(Mockito.eq(id), any(GuestOSCategoryVO.class))).thenReturn(true);
++ Mockito.when(guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
++ Mockito.when(guestOSCategoryDao.update(Mockito.eq(id), any(GuestOSCategoryVO.class))).thenReturn(true);
+ GuestOsCategory result = spy.updateGuestOsCategory(updateCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should return 2 suitable hosts for migration", 2, result.second().size());
- Assert.assertTrue("Suitable hosts should include host 101",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Suitable hosts should include host 102",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
+ Assert.assertEquals(name, result.getName());
+ Assert.assertEquals(featured, result.isFeatured());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).findById(id);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).update(Mockito.eq(id), any(GuestOSCategoryVO.class));
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).findById(id);
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).update(Mockito.eq(id), any(GuestOSCategoryVO.class));
}
@Test(expected = InvalidParameterValueException.class)
- public void testListHostsForMigrationOfVMWithMixedStorage() {
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.XenServer);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.XenServer);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // No storage motion support
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.XenServer, null))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- // Mixed storage - one shared, one local
- VolumeVO sharedVolume = mockVolume(1L, 1L);
- VolumeVO localVolume = mockVolume(2L, 2L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(sharedVolume, localVolume));
-
- DiskOfferingVO sharedOffering = mockSharedDiskOffering(1L);
- DiskOfferingVO localOffering = mockLocalDiskOffering(2L);
- Mockito.when(diskOfferingDao.findById(sharedVolume.getDiskOfferingId())).thenReturn(sharedOffering);
- Mockito.when(diskOfferingDao.findById(localVolume.getDiskOfferingId())).thenReturn(localOffering);
-
- // Should throw exception because we have local storage without storage motion support
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
+ public void testUpdateGuestOsCategory_ThrowsExceptionWhenCategoryNotFound() {
+ UpdateGuestOsCategoryCmd updateCmd = Mockito.mock(UpdateGuestOsCategoryCmd.class);
+ long id = 1L;
+ when(updateCmd.getId()).thenReturn(id);
- when(_guestOSCategoryDao.findById(id)).thenReturn(null);
++ when(guestOSCategoryDao.findById(id)).thenReturn(null);
+ spy.updateGuestOsCategory(updateCmd);
}
@Test
- public void testListHostsForMigrationOfVMKVMWithNullHypervisorVersion() {
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- // KVM host with null hypervisor version
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // KVM null version should be treated as empty string
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(true);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers with zone-wide scope (storage motion enabled)
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.anyLong(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.any(HypervisorType.class), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume, true);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify KVM null version was converted to empty string
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.KVM, "");
-
- // Verify result data
+ public void testUpdateGuestOsCategory_NoChanges() {
+ UpdateGuestOsCategoryCmd updateCmd = Mockito.mock(UpdateGuestOsCategoryCmd.class);
+ GuestOSCategoryVO guestOSCategory = new GuestOSCategoryVO("Old name", false);
+ long id = 1L;
+ when(updateCmd.getId()).thenReturn(id);
+ when(updateCmd.getName()).thenReturn(null);
+ when(updateCmd.isFeatured()).thenReturn(null);
+ when(updateCmd.getSortKey()).thenReturn(null);
- when(_guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
++ when(guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
+ GuestOsCategory result = spy.updateGuestOsCategory(updateCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Total hosts should be 2", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Suitable hosts should be 2", 2, result.second().size());
- Assert.assertTrue("Should contain host 101",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Should contain host 102",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
+ Assert.assertNotNull(result.getName());
+ Assert.assertFalse(result.isFeatured());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).findById(id);
- Mockito.verify(_guestOSCategoryDao, Mockito.never()).update(Mockito.eq(id), any(GuestOSCategoryVO.class));
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).findById(id);
++ Mockito.verify(guestOSCategoryDao, Mockito.never()).update(Mockito.eq(id), any(GuestOSCategoryVO.class));
}
@Test
- public void testListHostsForMigrationOfVMNonUefiVm() {
- // Test VM migration for non-UEFI VM (regular VM migration flow)
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify hosts are returned for migration (non-UEFI VMs don't need UEFI-enabled hosts)
+ public void testUpdateGuestOsCategory_UpdateNameOnly() {
+ UpdateGuestOsCategoryCmd updateCmd = Mockito.mock(UpdateGuestOsCategoryCmd.class);
+ GuestOSCategoryVO guestOSCategory = new GuestOSCategoryVO("Old name", false);
+ long id = 1L;
+ String name = "Updated Name";
+ Mockito.when(updateCmd.getId()).thenReturn(id);
+ Mockito.when(updateCmd.getName()).thenReturn(name);
+ Mockito.when(updateCmd.isFeatured()).thenReturn(null);
+ Mockito.when(updateCmd.getSortKey()).thenReturn(null);
- Mockito.when(_guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
- Mockito.when(_guestOSCategoryDao.update(Mockito.eq(id), any(GuestOSCategoryVO.class))).thenReturn(true);
++ Mockito.when(guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
++ Mockito.when(guestOSCategoryDao.update(Mockito.eq(id), any(GuestOSCategoryVO.class))).thenReturn(true);
+ GuestOsCategory result = spy.updateGuestOsCategory(updateCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Should have 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts", 2, result.second().size());
- Assert.assertTrue("Should contain host 101",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Should contain host 102",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
- }
-
- @Test
- public void testListHostsForMigrationOfVMWithUefiVmClusterScope() {
- // Test UEFI VM migration with cluster-scoped search (no storage motion)
- // This exercises the code path where filteredHosts is NULL and allocateTo without list is called
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // No storage motion support - cluster-scoped search
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- // Mock filterUefiHostsForMigration to return success with filtered hosts (only host1 is UEFI-compatible)
- List<HostVO> uefiCompatibleHosts = List.of(host1);
- Pair<Boolean, List<HostVO>> uefiFilterResult = new Pair<>(true, uefiCompatibleHosts);
- Mockito.doReturn(uefiFilterResult).when(spy).filterUefiHostsForMigration(
- Mockito.anyList(), Mockito.anyList(), Mockito.any());
-
- // Setup other mocks
- Mockito.when(dpdkHelper.isVMDpdkEnabled(vm.getId())).thenReturn(false);
- Mockito.when(affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId())).thenReturn(0L);
- DataCenterVO dc = Mockito.mock(DataCenterVO.class);
- Mockito.when(dcDao.findById(srcHost.getDataCenterId())).thenReturn(dc);
- Mockito.doNothing().when(dpMgr).checkForNonDedicatedResources(Mockito.any(), Mockito.any(), Mockito.any());
- Mockito.doNothing().when(dpMgr).reorderHostsByPriority(Mockito.any(), Mockito.anyList());
-
- // After UEFI filtering, filteredHosts is set to uefiCompatibleHosts (line 1582)
- // So allocateTo WITH list parameter is called (line 1608) even in cluster scope
- Mockito.when(hostAllocator.allocateTo(Mockito.any(), Mockito.any(), Mockito.any(),
- Mockito.any(), Mockito.anyList(), Mockito.anyInt(), Mockito.anyBoolean()))
- .thenReturn(new ArrayList<>(uefiCompatibleHosts));
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify result structure
- Assert.assertNotNull("Result should not be null", result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("All hosts list should contain 2 hosts", 2, result.first().first().size());
-
- // Verify only UEFI-compatible hosts are in suitable list
- Assert.assertEquals("Should have 1 UEFI-compatible suitable host", 1, result.second().size());
- Assert.assertTrue("Host 101 should be the only UEFI-compatible host",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertFalse("Host 102 should not be in suitable hosts (not UEFI-compatible)",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
+ Assert.assertEquals(name, result.getName());
+ Assert.assertFalse(result.isFeatured());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).findById(id);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).update(Mockito.eq(id), any(GuestOSCategoryVO.class));
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).findById(id);
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).update(Mockito.eq(id), any(GuestOSCategoryVO.class));
}
@Test
- public void testListHostsForMigrationOfVMWithUefiVmZoneWideScope() {
- // Test UEFI VM migration with zone-wide search (storage motion enabled)
- // This exercises the code path where filteredHosts IS populated and allocateTo WITH list is called
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.VMware);
- Mockito.when(vm.getType()).thenReturn(VirtualMachine.Type.User);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.VMware);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // Storage motion supported - zone-wide search with filteredHosts
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.VMware, null))
- .thenReturn(true);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for zone-wide search (storage motion enabled)
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.VMware);
- HostVO host2 = mockHost(102L, 2L, 1L, 1L, HypervisorType.VMware); // Different cluster
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.anyLong(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.any(HypervisorType.class), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume, true);
-
- // Mock filterUefiHostsForMigration to return success with filtered hosts (only host1 is UEFI-compatible)
- List<HostVO> uefiCompatibleHosts = List.of(host1);
- Pair<Boolean, List<HostVO>> uefiFilterResult = new Pair<>(true, uefiCompatibleHosts);
- Mockito.doReturn(uefiFilterResult).when(spy).filterUefiHostsForMigration(
- Mockito.anyList(), Mockito.anyList(), Mockito.any());
-
- // Override hostAllocator to return only UEFI-compatible hosts
- // Uses allocateTo WITH list parameter (filteredHosts is populated in zone-wide search)
- Mockito.when(hostAllocator.allocateTo(Mockito.any(), Mockito.any(), Mockito.any(),
- Mockito.any(), Mockito.anyList(), Mockito.anyInt(), Mockito.anyBoolean()))
- .thenReturn(new ArrayList<>(uefiCompatibleHosts));
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify result structure
- Assert.assertNotNull("Result should not be null", result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("All hosts list should contain 2 hosts", 2, result.first().first().size());
-
- // Verify only UEFI-compatible hosts are in suitable list
- Assert.assertEquals("Should have 1 UEFI-compatible suitable host", 1, result.second().size());
- Assert.assertTrue("Host 101 should be the only UEFI-compatible host",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertFalse("Host 102 should not be in suitable hosts (not UEFI-compatible)",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
-
- // Verify storage motion map is populated
- Assert.assertNotNull("Storage motion map should not be null", result.third());
- }
-
- @Test
- public void testListHostsForMigrationOfVMUefiFilteringReturnsEmpty() {
- // Test case where UEFI filtering results in no suitable hosts
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- // Mock filterUefiHostsForMigration FIRST to return false (no UEFI-enabled hosts found)
- // This simulates the scenario where UEFI VM has no compatible hosts
- Pair<Boolean, List<HostVO>> uefiFilterResult = new Pair<>(false, null);
- Mockito.doReturn(uefiFilterResult).when(spy).filterUefiHostsForMigration(
- Mockito.anyList(), Mockito.anyList(), Mockito.any());
-
- // Note: No other mocks needed because when filterUefiHostsForMigration returns false,
- // the method returns early and doesn't proceed to host allocation or other processing
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify result structure
- Assert.assertNotNull("Result should not be null", result);
- Assert.assertNotNull("All hosts list should not be null", result.first());
- Assert.assertNotNull("Suitable hosts list should not be null", result.second());
- Assert.assertNotNull("Storage motion map should not be null", result.third());
-
- // Verify all hosts are still returned (from searchForServers)
- Assert.assertEquals("Should still return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("All hosts list should contain 2 hosts", 2, result.first().first().size());
-
- // Verify suitable hosts list is empty due to UEFI filtering
- Assert.assertEquals("Should have 0 suitable hosts after UEFI filtering", 0, result.second().size());
-
- // Verify storage motion map is empty
- Assert.assertTrue("Storage motion map should be empty when no suitable hosts", result.third().isEmpty());
- }
-
- @Test
- public void testListHostsForMigrationOfVMStorageMotionCapabilityCheck() {
- // Test User VM with VMware - should check storage motion for User VMs
- VMInstanceVO userVm = mockRunningVM(1L, HypervisorType.VMware);
- Mockito.when(userVm.getType()).thenReturn(VirtualMachine.Type.User);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(userVm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(userVm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.VMware);
- Mockito.when(hostDao.findById(userVm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.VMware, null))
- .thenReturn(true);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(userVm.getId(), userVm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(userVm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers with zone-wide scope (storage motion enabled)
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.VMware);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.VMware);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.anyLong(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.any(HypervisorType.class), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(userVm, srcHost, hosts, volume, true);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify storage motion capability was checked for User VM
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.VMware, null);
-
- // Verify response data
- Assert.assertNotNull(result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts", 2, result.second().size());
- Assert.assertTrue("Host 101 should be in suitable list",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Host 102 should be in suitable list",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
- }
-
- @Test
- public void testListHostsForMigrationOfVMWithAllSupportedHypervisors() {
- // Test each supported hypervisor type
- HypervisorType[] supportedTypes = {
- HypervisorType.XenServer,
- HypervisorType.VMware,
- HypervisorType.KVM,
- HypervisorType.Ovm,
- HypervisorType.Hyperv,
- HypervisorType.Ovm3
- };
-
- for (HypervisorType hypervisorType : supportedTypes) {
- VMInstanceVO vm = mockRunningVM(1L, hypervisorType);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, hypervisorType);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- String version = hypervisorType == HypervisorType.KVM ? "" : null;
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(hypervisorType, version))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, hypervisorType);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, hypervisorType);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify hypervisor is in supported hypervisors list
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(hypervisorType, version);
-
- // Verify validation passed for this hypervisor
- Assert.assertNotNull("Result should not be null for " + hypervisorType, result);
- Assert.assertEquals("Should return 2 total hosts for " + hypervisorType,
- Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts for " + hypervisorType,
- 2, result.second().size());
- Assert.assertTrue("Host 101 should be available for " + hypervisorType,
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Host 102 should be available for " + hypervisorType,
- result.second().stream().anyMatch(h -> h.getId() == 102L));
-
- // Reset mocks for next iteration
- Mockito.reset(vmInstanceDao, hostDao, serviceOfferingDetailsDao, volumeDao,
- diskOfferingDao, hypervisorCapabilitiesDao, offeringDao, dpdkHelper,
- affinityGroupVMMapDao, dpMgr, dcDao, hostAllocator, dataStoreManager);
- Mockito.reset(spy);
- }
+ public void testDeleteGuestOsCategory_Successful() {
+ DeleteGuestOsCategoryCmd deleteCmd = Mockito.mock(DeleteGuestOsCategoryCmd.class);
+ GuestOSCategoryVO guestOSCategory = Mockito.mock(GuestOSCategoryVO.class);
+ long id = 1L;
+ Mockito.when(deleteCmd.getId()).thenReturn(id);
- Mockito.when(_guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
- Mockito.when(_guestOSDao.listIdsByCategoryId(id)).thenReturn(Arrays.asList());
- Mockito.when(_guestOSCategoryDao.remove(id)).thenReturn(true);
++ Mockito.when(guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
++ Mockito.when(guestOSDao.listIdsByCategoryId(id)).thenReturn(Arrays.asList());
++ Mockito.when(guestOSCategoryDao.remove(id)).thenReturn(true);
+ boolean result = spy.deleteGuestOsCategory(deleteCmd);
+ Assert.assertTrue(result);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).findById(id);
- Mockito.verify(_guestOSDao, Mockito.times(1)).listIdsByCategoryId(id);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).remove(id);
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).findById(id);
++ Mockito.verify(guestOSDao, Mockito.times(1)).listIdsByCategoryId(id);
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).remove(id);
}
@Test(expected = InvalidParameterValueException.class)
- public void testListHostsForMigrationOfVMSourceHostNotFound() {
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(null);
-
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
+ public void testDeleteGuestOsCategory_ThrowsExceptionWhenCategoryNotFound() {
+ DeleteGuestOsCategoryCmd deleteCmd = Mockito.mock(DeleteGuestOsCategoryCmd.class);
+ long id = 1L;
+ Mockito.when(deleteCmd.getId()).thenReturn(id);
- Mockito.when(_guestOSCategoryDao.findById(id)).thenReturn(null);
++ Mockito.when(guestOSCategoryDao.findById(id)).thenReturn(null);
+ spy.deleteGuestOsCategory(deleteCmd);
}
@Test(expected = InvalidParameterValueException.class)
- public void testListHostsForMigrationOfVMLocalStorageNoStorageMotion() {
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.XenServer);
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.XenServer);
- Account caller = mockRootAdminAccount();
-
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // Mock storage motion not supported
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.XenServer, null))
- .thenReturn(false);
-
- // Mock local storage usage
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockLocalDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
+ public void testDeleteGuestOsCategory_ThrowsExceptionWhenGuestOsExists() {
+ DeleteGuestOsCategoryCmd deleteCmd = Mockito.mock(DeleteGuestOsCategoryCmd.class);
+ GuestOSCategoryVO guestOSCategory = Mockito.mock(GuestOSCategoryVO.class);
+ long id = 1L;
+ Mockito.when(deleteCmd.getId()).thenReturn(id);
- Mockito.when(_guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
- Mockito.when(_guestOSDao.listIdsByCategoryId(id)).thenReturn(Arrays.asList(1L));
++ Mockito.when(guestOSCategoryDao.findById(id)).thenReturn(guestOSCategory);
++ Mockito.when(guestOSDao.listIdsByCategoryId(id)).thenReturn(Arrays.asList(1L));
+ spy.deleteGuestOsCategory(deleteCmd);
}
- @Test
- public void testListHostsForMigrationOfVMStorageMotionCheckForSystemVM() {
- // Test that storage motion capability is checked for System VMs
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.VMware);
- Mockito.when(vm.getType()).thenReturn(VirtualMachine.Type.ConsoleProxy);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.VMware);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // Storage motion supported for VMware
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.VMware, null))
- .thenReturn(true);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers with zone-wide scope (storage motion enabled)
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.VMware);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.VMware);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.any(HypervisorType.class), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume, true);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify that storage motion capability was checked for system VM (VMware is in hypervisorTypes list)
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.VMware, null);
-
- // Verify response structure
- Assert.assertNotNull(result);
- Assert.assertEquals("Should have 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertTrue("Should have suitable hosts", result.second().size() > 0);
+ private void mockGuestOsJoin() {
+ GuestOSVO vo = mock(GuestOSVO.class);
+ SearchBuilder<GuestOSVO> sb = mock(SearchBuilder.class);
+ when(sb.entity()).thenReturn(vo);
- when(_guestOSDao.createSearchBuilder()).thenReturn(sb);
++ when(guestOSDao.createSearchBuilder()).thenReturn(sb);
}
@Test
- public void testListHostsForMigrationOfVMStorageMotionCheckForUserVM() {
- // Test that storage motion capability is checked for User VMs
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
- Mockito.when(vm.getType()).thenReturn(VirtualMachine.Type.User);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // Storage motion supported for User VM with KVM
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(true);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers with zone-wide scope (storage motion enabled)
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.anyLong(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.any(HypervisorType.class), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume, true);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify User VM can migrate with storage (User VM type always checks)
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.KVM, "");
-
- // Verify response data
+ public void testListGuestOSCategoriesByCriteria_Success() {
+ ListGuestOsCategoriesCmd listCmd = Mockito.mock(ListGuestOsCategoriesCmd.class);
+ GuestOSCategoryVO guestOSCategory = Mockito.mock(GuestOSCategoryVO.class);
+ Filter filter = Mockito.mock(Filter.class);
+ Long id = 1L;
+ String name = "Ubuntu";
+ String keyword = "Linux";
+ Boolean featured = true;
+ Long zoneId = 1L;
+ CPU.CPUArch arch = CPU.CPUArch.getDefault();
+ Boolean isIso = true;
+ Boolean isVnf = false;
+ Mockito.when(listCmd.getId()).thenReturn(id);
+ Mockito.when(listCmd.getName()).thenReturn(name);
+ Mockito.when(listCmd.getKeyword()).thenReturn(keyword);
+ Mockito.when(listCmd.isFeatured()).thenReturn(featured);
+ Mockito.when(listCmd.getZoneId()).thenReturn(zoneId);
+ Mockito.when(listCmd.getArch()).thenReturn(arch);
+ Mockito.when(listCmd.isIso()).thenReturn(isIso);
+ Mockito.when(listCmd.isVnf()).thenReturn(isVnf);
+ SearchBuilder<GuestOSCategoryVO> searchBuilder = Mockito.mock(SearchBuilder.class);
+ Mockito.when(searchBuilder.entity()).thenReturn(guestOSCategory);
+ SearchCriteria<GuestOSCategoryVO> searchCriteria = Mockito.mock(SearchCriteria.class);
- Mockito.when(_guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
++ Mockito.when(guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
+ Mockito.when(searchBuilder.create()).thenReturn(searchCriteria);
+ Mockito.when(templateDao.listTemplateIsoByArchVnfAndZone(zoneId, arch, isIso, isVnf)).thenReturn(Arrays.asList(1L, 2L));
+ Pair<List<GuestOSCategoryVO>, Integer> mockResult = new Pair<>(Arrays.asList(guestOSCategory), 1);
+ mockGuestOsJoin();
- Mockito.when(_guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
++ Mockito.when(guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
+ Pair<List<? extends GuestOsCategory>, Integer> result = spy.listGuestOSCategoriesByCriteria(listCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Should have 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertTrue("Should have suitable hosts", result.second().size() > 0);
+ Assert.assertEquals(1, result.second().intValue());
+ Assert.assertEquals(1, result.first().size());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
+ Mockito.verify(templateDao, Mockito.times(1)).listTemplateIsoByArchVnfAndZone(zoneId, arch, isIso, isVnf);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
}
@Test
- public void testListHostsForMigrationOfVMWithoutStorageMotionClusterScope() {
- // When storage motion not supported, should search only in same cluster
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.XenServer);
- Mockito.when(vm.getType()).thenReturn(VirtualMachine.Type.User);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.XenServer);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // No storage motion support
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.XenServer, null))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers - verify cluster scope is used
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.XenServer);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.XenServer);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.eq(0L), Mockito.eq(20L), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.eq(1L), // cluster=1L
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.eq(100L));
-
- setupMigrationMocks(vm, srcHost, hosts, volume);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify XenServer without storage motion was checked
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.XenServer, null);
- // Verify cluster-scoped search was used (not zone-wide)
- Mockito.verify(spy).searchForServers(
- Mockito.eq(0L), Mockito.eq(20L), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.eq(1L),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.eq(100L));
-
- // Verify response data
+ public void testListGuestOSCategoriesByCriteria_NoResults() {
+ ListGuestOsCategoriesCmd listCmd = Mockito.mock(ListGuestOsCategoriesCmd.class);
+ GuestOSCategoryVO guestOSCategory = Mockito.mock(GuestOSCategoryVO.class);
+ Long id = 1L;
+ String name = "CentOS";
+ String keyword = "Linux";
+ Boolean featured = false;
+ Long zoneId = 1L;
+ CPU.CPUArch arch = CPU.CPUArch.getDefault();
+ Boolean isIso = false;
+ Boolean isVnf = false;
+ Mockito.when(listCmd.getId()).thenReturn(id);
+ Mockito.when(listCmd.getName()).thenReturn(name);
+ Mockito.when(listCmd.getKeyword()).thenReturn(keyword);
+ Mockito.when(listCmd.isFeatured()).thenReturn(featured);
+ Mockito.when(listCmd.getZoneId()).thenReturn(zoneId);
+ Mockito.when(listCmd.getArch()).thenReturn(arch);
+ Mockito.when(listCmd.isIso()).thenReturn(isIso);
+ Mockito.when(listCmd.isVnf()).thenReturn(isVnf);
+ SearchBuilder<GuestOSCategoryVO> searchBuilder = Mockito.mock(SearchBuilder.class);
+ Mockito.when(searchBuilder.entity()).thenReturn(guestOSCategory);
+ SearchCriteria<GuestOSCategoryVO> searchCriteria = Mockito.mock(SearchCriteria.class);
- Mockito.when(_guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
++ Mockito.when(guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
+ Mockito.when(searchBuilder.create()).thenReturn(searchCriteria);
+ Mockito.when(templateDao.listTemplateIsoByArchVnfAndZone(zoneId, arch, isIso, isVnf)).thenReturn(Arrays.asList(1L, 2L));
+ Pair<List<GuestOSCategoryVO>, Integer> mockResult = new Pair<>(Arrays.asList(), 0);
- Mockito.when(_guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
++ Mockito.when(guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
+ mockGuestOsJoin();
+ Pair<List<? extends GuestOsCategory>, Integer> result = spy.listGuestOSCategoriesByCriteria(listCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts", 2, result.second().size());
- Assert.assertTrue("Should contain host 101",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Should contain host 102",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
+ Assert.assertEquals(0, result.second().intValue());
+ Assert.assertEquals(0, result.first().size());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
+ Mockito.verify(templateDao, Mockito.times(1)).listTemplateIsoByArchVnfAndZone(zoneId, arch, isIso, isVnf);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
}
@Test
- public void testListHostsForMigrationOfVMWithNoVolumes() {
- // Edge case: VM with no volumes
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- // No volumes
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(new ArrayList<>());
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- // Set up mocks without volume since there are no volumes
- Pair<Boolean, List<HostVO>> uefiResult = new Pair<>(true, hosts);
- Mockito.doReturn(uefiResult).when(spy).filterUefiHostsForMigration(
- Mockito.anyList(), Mockito.anyList(), Mockito.any());
- Mockito.when(dpdkHelper.isVMDpdkEnabled(vm.getId())).thenReturn(false);
- Mockito.when(affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId())).thenReturn(0L);
- DataCenterVO dc = Mockito.mock(DataCenterVO.class);
- Mockito.when(dcDao.findById(1L)).thenReturn(dc);
- Mockito.doNothing().when(dpMgr).checkForNonDedicatedResources(Mockito.any(), Mockito.any(), Mockito.any());
- Mockito.doNothing().when(dpMgr).reorderHostsByPriority(Mockito.any(), Mockito.anyList());
-
- Mockito.when(hostAllocator.allocateTo(Mockito.any(), Mockito.any(), Mockito.any(),
- Mockito.any(), Mockito.anyList(), Mockito.anyInt(), Mockito.anyBoolean()))
- .thenReturn(new ArrayList<>(hosts));
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Should still process without throwing exception for usesLocal check
- Mockito.verify(volumeDao).findCreatedByInstance(vm.getId());
-
- // Verify response
+ public void testListGuestOSCategoriesByCriteria_NoGuestOsIdsFound() {
+ ListGuestOsCategoriesCmd listCmd = Mockito.mock(ListGuestOsCategoriesCmd.class);
+ GuestOSCategoryVO guestOSCategory = Mockito.mock(GuestOSCategoryVO.class);
+ Long id = 1L;
+ String name = "Ubuntu";
+ String keyword = "Linux";
+ Boolean featured = true;
+ Long zoneId = 1L;
+ CPU.CPUArch arch = CPU.CPUArch.getDefault();
+ Boolean isIso = true;
+ Boolean isVnf = false;
+ Mockito.when(listCmd.getId()).thenReturn(id);
+ Mockito.when(listCmd.getName()).thenReturn(name);
+ Mockito.when(listCmd.getKeyword()).thenReturn(keyword);
+ Mockito.when(listCmd.isFeatured()).thenReturn(featured);
+ Mockito.when(listCmd.getZoneId()).thenReturn(zoneId);
+ Mockito.when(listCmd.getArch()).thenReturn(arch);
+ Mockito.when(listCmd.isIso()).thenReturn(isIso);
+ Mockito.when(listCmd.isVnf()).thenReturn(isVnf);
+ SearchBuilder<GuestOSCategoryVO> searchBuilder = Mockito.mock(SearchBuilder.class);
+ Mockito.when(searchBuilder.entity()).thenReturn(guestOSCategory);
+ SearchCriteria<GuestOSCategoryVO> searchCriteria = Mockito.mock(SearchCriteria.class);
- Mockito.when(_guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
++ Mockito.when(guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
+ Mockito.when(searchBuilder.create()).thenReturn(searchCriteria);
+ Mockito.when(templateDao.listTemplateIsoByArchVnfAndZone(zoneId, arch, isIso, isVnf)).thenReturn(Arrays.asList(1L, 2L));
+ Pair<List<GuestOSCategoryVO>, Integer> mockResult = new Pair<>(Arrays.asList(), 0);
- when(_guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
++ when(guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
+ mockGuestOsJoin();
+ Pair<List<? extends GuestOsCategory>, Integer> result = spy.listGuestOSCategoriesByCriteria(listCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Should have 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts even with no volumes", 2, result.second().size());
- Assert.assertTrue("Storage motion map should be empty for VM with no volumes",
- result.third().isEmpty());
+ Assert.assertEquals(0, result.second().intValue());
+ Assert.assertEquals(0, result.first().size());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
+ Mockito.verify(templateDao, Mockito.times(1)).listTemplateIsoByArchVnfAndZone(zoneId, arch, isIso, isVnf);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
}
@Test
- public void testListHostsForMigrationOfVMOverloadedMethod() {
- // Test the overloaded method that takes vmId instead of vm object
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for cluster-scoped search with keyword
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.eq("keyword-test"), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume);
-
- // Call overloaded method with vmId
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, "keyword-test");
-
- // Verify VM was fetched by ID
- Mockito.verify(vmInstanceDao).findById(1L);
-
- // Verify keyword was passed to searchForServers
- Mockito.verify(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.eq("keyword-test"), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- // Verify response data
+ public void testListGuestOSCategoriesByCriteria_FilterById() {
+ ListGuestOsCategoriesCmd listCmd = Mockito.mock(ListGuestOsCategoriesCmd.class);
+ GuestOSCategoryVO guestOSCategory = Mockito.mock(GuestOSCategoryVO.class);
+ Long id = 1L;
+ Mockito.when(listCmd.getId()).thenReturn(id);
+ Mockito.when(listCmd.getZoneId()).thenReturn(null);
+ Mockito.when(listCmd.isIso()).thenReturn(null);
+ Mockito.when(listCmd.isVnf()).thenReturn(null);
+ SearchBuilder<GuestOSCategoryVO> searchBuilder = Mockito.mock(SearchBuilder.class);
+ Mockito.when(searchBuilder.entity()).thenReturn(guestOSCategory);
+ SearchCriteria<GuestOSCategoryVO> searchCriteria = Mockito.mock(SearchCriteria.class);
- Mockito.when(_guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
++ Mockito.when(guestOSCategoryDao.createSearchBuilder()).thenReturn(searchBuilder);
+ Mockito.when(searchBuilder.create()).thenReturn(searchCriteria);
+ Pair<List<GuestOSCategoryVO>, Integer> mockResult = new Pair<>(Arrays.asList(guestOSCategory), 1);
- Mockito.when(_guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
++ Mockito.when(guestOSCategoryDao.searchAndCount(Mockito.eq(searchCriteria), Mockito.any())).thenReturn(mockResult);
+ mockGuestOsJoin();
+ Pair<List<? extends GuestOsCategory>, Integer> result = spy.listGuestOSCategoriesByCriteria(listCmd);
Assert.assertNotNull(result);
- Assert.assertEquals("Should have 2 hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts", 2, result.second().size());
- }
-
- @Test
- public void testListHostsForMigrationOfVMVmwareStorageMotionCheck() {
- // VMware should check storage motion even for non-User VMs
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.VMware);
- Mockito.when(vm.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.VMware);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- // VMware with DomainRouter should still check storage motion
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.VMware, null))
- .thenReturn(true);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
+ Assert.assertEquals(1, result.second().intValue());
+ Assert.assertEquals(1, result.first().size());
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).createSearchBuilder();
+ Mockito.verify(searchCriteria, Mockito.times(1)).setParameters("id", id);
- Mockito.verify(_guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
++ Mockito.verify(guestOSCategoryDao, Mockito.times(1)).searchAndCount(Mockito.eq(searchCriteria), Mockito.any());
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers with zone-wide scope (storage motion enabled)
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.VMware);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.VMware);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.any(HypervisorType.class), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume, true);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify VMware always checks storage motion (hypervisorTypes list includes VMware)
- Mockito.verify(hypervisorCapabilitiesDao).isStorageMotionSupported(HypervisorType.VMware, null);
-
- // Verify response
- Assert.assertNotNull(result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts", 2, result.second().size());
- Assert.assertTrue("Host 101 should be in the list",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
}
-
@Test
- public void testListHostsForMigrationOfVMWithNullKeyword() {
- // Test with null keyword parameter
- VMInstanceVO vm = mockRunningVM(1L, HypervisorType.KVM);
-
- Account caller = mockRootAdminAccount();
- Mockito.doReturn(caller).when(spy).getCaller();
- Mockito.when(vmInstanceDao.findById(1L)).thenReturn(vm);
- Mockito.when(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()))
- .thenReturn(null);
-
- HostVO srcHost = mockHost(100L, 1L, 1L, 1L, HypervisorType.KVM);
- Mockito.when(hostDao.findById(vm.getHostId())).thenReturn(srcHost);
-
- Mockito.when(hypervisorCapabilitiesDao.isStorageMotionSupported(HypervisorType.KVM, ""))
- .thenReturn(false);
-
- ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class);
- Mockito.when(offeringDao.findById(vm.getId(), vm.getServiceOfferingId())).thenReturn(offering);
-
- VolumeVO volume = mockVolume(1L, 1L);
- Mockito.when(volumeDao.findCreatedByInstance(vm.getId())).thenReturn(List.of(volume));
-
- DiskOfferingVO diskOffering = mockSharedDiskOffering(1L);
- Mockito.when(diskOfferingDao.findById(volume.getDiskOfferingId())).thenReturn(diskOffering);
-
- // Mock searchForServers for cluster-scoped search
- HostVO host1 = mockHost(101L, 1L, 1L, 1L, HypervisorType.KVM);
- HostVO host2 = mockHost(102L, 1L, 1L, 1L, HypervisorType.KVM);
- List<HostVO> hosts = List.of(host1, host2);
- Pair<List<HostVO>, Integer> hostsPair = new Pair<>(hosts, 2);
- Mockito.doReturn(hostsPair).when(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- setupMigrationMocks(vm, srcHost, hosts, volume);
-
- Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> result =
- spy.listHostsForMigrationOfVM(1L, 0L, 20L, null);
-
- // Verify null keyword is handled
- Mockito.verify(vmInstanceDao).findById(1L);
-
- // Verify searchForServers was called with null keyword
- Mockito.verify(spy).searchForServers(
- Mockito.anyLong(), Mockito.anyLong(), Mockito.isNull(), Mockito.any(Type.class),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyLong(),
- Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(),
- Mockito.isNull(), Mockito.isNull(), Mockito.anyLong());
-
- // Verify response data
- Assert.assertNotNull(result);
- Assert.assertEquals("Should return 2 total hosts", Integer.valueOf(2), result.first().second());
- Assert.assertEquals("Should have 2 suitable hosts", 2, result.second().size());
- Assert.assertTrue("Host 101 should be available",
- result.second().stream().anyMatch(h -> h.getId() == 101L));
- Assert.assertTrue("Host 102 should be available",
- result.second().stream().anyMatch(h -> h.getId() == 102L));
- }
-
- // Note: Tests for success scenarios with complex flows (managed storage, zone-wide volumes,
- // DPDK exclusion, affinity groups, architecture filtering) require full setup with mocking
- // private methods like hasSuitablePoolsForVolume(), excludeNonDPDKEnabledHosts(), and
- // filterUefiHostsForMigration() which are better suited for integration tests.
-
- // ============= Helper methods for tests =============
-
- /**
- * Sets up common mocks for successful migration tests
- * For storage motion tests, set forceStorageMotion=true to configure volume in same cluster
- * (which avoids complex filtering logic for cross-cluster storage motion)
- */
- private void setupMigrationMocks(VMInstanceVO vm, HostVO srcHost,
- List<HostVO> targetHosts, VolumeVO volume) {
- setupMigrationMocks(vm, srcHost, targetHosts, volume, false);
- }
-
- private void setupMigrationMocks(VMInstanceVO vm, HostVO srcHost,
- List<HostVO> targetHosts, VolumeVO volume,
- boolean forceStorageMotion) {
- // Mock dataStoreManager for volume pool lookup (lenient as not used in all paths)
- // For storage motion tests, put volume in same cluster to avoid complex filtering
- PrimaryDataStore primaryDataStore = Mockito.mock(PrimaryDataStore.class);
- Mockito.when(dataStoreManager.getPrimaryDataStore(volume.getPoolId())).thenReturn(primaryDataStore);
- // If not forceStorageMotion, volume is in same cluster (no storage motion needed)
- // If forceStorageMotion, set volClusterId to null (zone-wide storage)
- Mockito.when(primaryDataStore.getClusterId()).thenReturn(forceStorageMotion ? null : srcHost.getClusterId());
-
- // Mock zoneWideVolumeRequiresStorageMotion for zone-wide volumes
- if (forceStorageMotion) {
- Mockito.doReturn(false).when(spy).zoneWideVolumeRequiresStorageMotion(
- Mockito.any(), Mockito.any(), Mockito.any());
- }
-
- // Mock filterUefiHostsForMigration - must return hosts properly
- Pair<Boolean, List<HostVO>> uefiResult = new Pair<>(true, new ArrayList<>(targetHosts));
- Mockito.doReturn(uefiResult).when(spy).filterUefiHostsForMigration(
- Mockito.anyList(), Mockito.anyList(), Mockito.any());
-
- // Mock DPDK check
- Mockito.when(dpdkHelper.isVMDpdkEnabled(vm.getId())).thenReturn(false);
-
- // Mock affinity group count
- Mockito.when(affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId())).thenReturn(0L);
-
- // Mock datacenter
- DataCenterVO dc = Mockito.mock(DataCenterVO.class);
- Mockito.when(dcDao.findById(srcHost.getDataCenterId())).thenReturn(dc);
-
- // Mock dedicated resources check
- Mockito.doNothing().when(dpMgr).checkForNonDedicatedResources(
- Mockito.any(), Mockito.any(), Mockito.any());
-
- // Mock priority reordering
- Mockito.doNothing().when(dpMgr).reorderHostsByPriority(Mockito.any(), Mockito.anyList());
-
- // Mock host allocators - both signatures
- // 1. Version with filteredHosts list (used when canMigrateWithStorage = true)
- Mockito.when(hostAllocator.allocateTo(Mockito.any(), Mockito.any(), Mockito.any(),
- Mockito.any(), Mockito.anyList(), Mockito.anyInt(), Mockito.anyBoolean()))
- .thenReturn(new ArrayList<>(targetHosts));
- }
-
- private VMInstanceVO mockRunningVM(Long id, HypervisorType hypervisorType) {
- return mockVM(id, hypervisorType, State.Running);
- }
-
- private VMInstanceVO mockVM(Long id, HypervisorType hypervisorType, State state) {
- VMInstanceVO vm = Mockito.mock(VMInstanceVO.class);
- when(vm.getId()).thenReturn(id);
- when(vm.getState()).thenReturn(state);
- when(vm.getHypervisorType()).thenReturn(hypervisorType);
- when(vm.getHostId()).thenReturn(100L);
- when(vm.getServiceOfferingId()).thenReturn(1L);
- when(vm.getType()).thenReturn(VirtualMachine.Type.User);
- when(vm.getUuid()).thenReturn("uuid-" + id);
- when(vm.getDataCenterId()).thenReturn(1L);
- return vm;
- }
-
- private Account mockRootAdminAccount() {
- Account account = Mockito.mock(Account.class);
- Mockito.when(account.getId()).thenReturn(1L);
- Mockito.when(_accountMgr.isRootAdmin(1L)).thenReturn(true);
- return account;
- }
-
- private HostVO mockHost(Long id, Long clusterId, Long podId, Long dcId, HypervisorType hypervisorType) {
- HostVO host = new HostVO("guid-" + id);
- ReflectionTestUtils.setField(host, "id", id);
- ReflectionTestUtils.setField(host, "clusterId", clusterId);
- ReflectionTestUtils.setField(host, "podId", podId);
- ReflectionTestUtils.setField(host, "dataCenterId", dcId);
- ReflectionTestUtils.setField(host, "hypervisorType", hypervisorType);
- ReflectionTestUtils.setField(host, "type", Host.Type.Routing);
- ReflectionTestUtils.setField(host, "hypervisorVersion", null);
- return host;
- }
-
- private VolumeVO mockVolume(Long id, Long poolId) {
- VolumeVO volume = Mockito.mock(VolumeVO.class);
- when(volume.getId()).thenReturn(id);
- when(volume.getPoolId()).thenReturn(poolId);
- when(volume.getDiskOfferingId()).thenReturn(1L);
- when(volume.getVolumeType()).thenReturn(Volume.Type.ROOT);
- return volume;
- }
-
- private DiskOfferingVO mockLocalDiskOffering(Long id) {
- DiskOfferingVO diskOffering = Mockito.mock(DiskOfferingVO.class);
- Mockito.when(diskOffering.getId()).thenReturn(id);
- Mockito.when(diskOffering.isUseLocalStorage()).thenReturn(true);
- return diskOffering;
- }
-
- private DiskOfferingVO mockSharedDiskOffering(Long id) {
- DiskOfferingVO diskOffering = Mockito.mock(DiskOfferingVO.class);
- Mockito.when(diskOffering.getId()).thenReturn(id);
- Mockito.when(diskOffering.isUseLocalStorage()).thenReturn(false);
- return diskOffering;
+ public void testGetExternalVmConsole() {
+ VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class);
+ Host host = Mockito.mock(Host.class);
+ Mockito.when(extensionManager.getInstanceConsole(virtualMachine, host)).thenReturn(Mockito.mock(com.cloud.agent.api.Answer.class));
+ Assert.assertNotNull(spy.getExternalVmConsole(virtualMachine, host));
+ Mockito.verify(extensionManager).getInstanceConsole(virtualMachine, host);
}
-
- @Test
- public void getStatesForIpAddressSearchReturnsValidStates() {
- ListPublicIpAddressesCmd cmd = Mockito.mock(ListPublicIpAddressesCmd.class);
- Mockito.when(cmd.getState()).thenReturn("Allocated ,free");
- List<IpAddress.State> result = spy.getStatesForIpAddressSearch(cmd);
- Assert.assertEquals(2, result.size());
- Assert.assertTrue(result.contains(IpAddress.State.Allocated));
- Assert.assertTrue(result.contains(IpAddress.State.Free));
- }
-
- @Test
- public void getStatesForIpAddressSearchReturnsEmptyListForNullState() {
- ListPublicIpAddressesCmd cmd = Mockito.mock(ListPublicIpAddressesCmd.class);
- Mockito.when(cmd.getState()).thenReturn(null);
- List<IpAddress.State> result = spy.getStatesForIpAddressSearch(cmd);
- Assert.assertTrue(result.isEmpty());
- }
-
- @Test
- public void getStatesForIpAddressSearchReturnsEmptyListForBlankState() {
- ListPublicIpAddressesCmd cmd = Mockito.mock(ListPublicIpAddressesCmd.class);
- Mockito.when(cmd.getState()).thenReturn(" ");
- List<IpAddress.State> result = spy.getStatesForIpAddressSearch(cmd);
- Assert.assertTrue(result.isEmpty());
- }
-
- @Test(expected = InvalidParameterValueException.class)
- public void getStatesForIpAddressSearchThrowsExceptionForInvalidState() {
- ListPublicIpAddressesCmd cmd = Mockito.mock(ListPublicIpAddressesCmd.class);
- Mockito.when(cmd.getState()).thenReturn("InvalidState");
- spy.getStatesForIpAddressSearch(cmd);
- }
-
- @Test
- public void getStatesForIpAddressSearchHandlesMixedValidAndInvalidStates() {
- ListPublicIpAddressesCmd cmd = Mockito.mock(ListPublicIpAddressesCmd.class);
- Mockito.when(cmd.getState()).thenReturn("Allocated,InvalidState");
- try {
- spy.getStatesForIpAddressSearch(cmd);
- Assert.fail("Expected InvalidParameterValueException to be thrown");
- } catch (InvalidParameterValueException e) {
- Assert.assertEquals("Invalid state: InvalidState", e.getMessage());
- }
- }
}
diff --cc server/src/test/java/org/apache/cloudstack/cluster/ClusterDrsServiceImplTest.java
index 81aac9e4b54,b76ef51c523..98b18c66305
--- a/server/src/test/java/org/apache/cloudstack/cluster/ClusterDrsServiceImplTest.java
+++ b/server/src/test/java/org/apache/cloudstack/cluster/ClusterDrsServiceImplTest.java
@@@ -219,6 -230,445 +230,420 @@@ public class ClusterDrsServiceImplTest
assertEquals(1, iterations.size());
}
+ @Test
+ public void testGetDrsPlanWithDisabledCluster() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Disabled);
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testGetDrsPlanWithZeroMaxIterations() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 0);
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testGetDrsPlanWithNegativeMaxIterations() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, -1);
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testGetDrsPlanWithSystemVMs() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ VMInstanceVO systemVm = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(systemVm.getId()).thenReturn(1L);
+ Mockito.when(systemVm.getHostId()).thenReturn(1L);
+ Mockito.when(systemVm.getType()).thenReturn(VirtualMachine.Type.SecondaryStorageVm);
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(systemVm);
+
+ HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin1.getId()).thenReturn(1L);
+ Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(true);
+ Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1));
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testGetDrsPlanWithNonRunningVMs() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ VMInstanceVO stoppedVm = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(stoppedVm.getId()).thenReturn(1L);
+ Mockito.when(stoppedVm.getHostId()).thenReturn(1L);
+ Mockito.when(stoppedVm.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(stoppedVm.getState()).thenReturn(VirtualMachine.State.Stopped);
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(stoppedVm);
+
+ HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin1.getId()).thenReturn(1L);
+ Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(true);
+ Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1));
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testGetDrsPlanWithSkipDrsFlag() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ VMInstanceVO skippedVm = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(skippedVm.getId()).thenReturn(1L);
+ Mockito.when(skippedVm.getHostId()).thenReturn(1L);
+ Mockito.when(skippedVm.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(skippedVm.getState()).thenReturn(VirtualMachine.State.Running);
+ Map<String, String> details = new HashMap<>();
+ details.put(VmDetailConstants.SKIP_DRS, "true");
+ Mockito.when(skippedVm.getDetails()).thenReturn(details);
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(skippedVm);
+
+ HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin1.getId()).thenReturn(1L);
+ Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(true);
+ Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1));
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testGetDrsPlanWithNoCompatibleHosts() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ VMInstanceVO vm1 = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(vm1.getId()).thenReturn(1L);
+ Mockito.when(vm1.getHostId()).thenReturn(1L);
+ Mockito.when(vm1.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(vm1.getState()).thenReturn(VirtualMachine.State.Running);
+ Mockito.when(vm1.getDetails()).thenReturn(Collections.emptyMap());
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(vm1);
+
+ HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin1.getId()).thenReturn(1L);
+ Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
+
+ ServiceOfferingVO serviceOffering = Mockito.mock(ServiceOfferingVO.class);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(true);
+ Mockito.when(serviceOfferingDao.findByIdIncludingRemoved(Mockito.anyLong(), Mockito.anyLong())).thenReturn(serviceOffering);
+ Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1));
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ Mockito.verify(managementServer, Mockito.times(1)).listHostsForMigrationOfVM(Mockito.eq(vm1), Mockito.anyLong(), Mockito.anyLong(), Mockito.any(), Mockito.anyList());
+ }
+
+ @Test
+ public void testGetDrsPlanWithExceptionInCompatibilityCheck() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ VMInstanceVO vm1 = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(vm1.getId()).thenReturn(1L);
+ Mockito.when(vm1.getHostId()).thenReturn(1L);
+ Mockito.when(vm1.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(vm1.getState()).thenReturn(VirtualMachine.State.Running);
+ Mockito.when(vm1.getDetails()).thenReturn(Collections.emptyMap());
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(vm1);
+
+ HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin1.getId()).thenReturn(1L);
+ Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
+
+ ServiceOfferingVO serviceOffering = Mockito.mock(ServiceOfferingVO.class);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(true);
+ Mockito.when(serviceOfferingDao.findByIdIncludingRemoved(Mockito.anyLong(), Mockito.anyLong())).thenReturn(serviceOffering);
+ Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1));
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ // Exception should be caught and logged, not propagated
+ Mockito.verify(managementServer, Mockito.times(1)).listHostsForMigrationOfVM(Mockito.eq(vm1), Mockito.anyLong(), Mockito.anyLong(), Mockito.any(), Mockito.anyList());
+ }
+
+ @Test
+ public void testGetDrsPlanWithNoBestMigration() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ VMInstanceVO vm1 = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(vm1.getId()).thenReturn(1L);
+ Mockito.when(vm1.getHostId()).thenReturn(1L);
+ Mockito.when(vm1.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(vm1.getState()).thenReturn(VirtualMachine.State.Running);
+ Mockito.when(vm1.getDetails()).thenReturn(Collections.emptyMap());
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(vm1);
+
+ HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin1.getId()).thenReturn(1L);
+ Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
+
+ ServiceOfferingVO serviceOffering = Mockito.mock(ServiceOfferingVO.class);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(true);
+ Mockito.when(serviceOfferingDao.findByIdIncludingRemoved(Mockito.anyLong(), Mockito.anyLong())).thenReturn(serviceOffering);
+ Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1));
+
+ HostVO compatibleHost = Mockito.mock(HostVO.class);
+
+ // Return null migration (no best migration found)
+ Mockito.doReturn(new Pair<>(null, null)).when(clusterDrsService).getBestMigration(
+ Mockito.any(Cluster.class), Mockito.any(ClusterDrsAlgorithm.class),
+ Mockito.anyList(), Mockito.anyMap(), Mockito.anyMap(), Mockito.anyMap(),
+ Mockito.anyMap(), Mockito.anyMap(), Mockito.anyMap());
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ public void testGetDrsPlanWithMultipleIterations() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ HostVO host2 = Mockito.mock(HostVO.class);
+ Mockito.when(host2.getId()).thenReturn(2L);
+
+ VMInstanceVO vm1 = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(vm1.getId()).thenReturn(1L);
+ Mockito.when(vm1.getHostId()).thenReturn(1L);
+ Mockito.when(vm1.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(vm1.getState()).thenReturn(VirtualMachine.State.Running);
+ Mockito.when(vm1.getDetails()).thenReturn(Collections.emptyMap());
+
+ VMInstanceVO vm2 = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(vm2.getId()).thenReturn(2L);
+ Mockito.when(vm2.getHostId()).thenReturn(1L);
+ Mockito.when(vm2.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(vm2.getState()).thenReturn(VirtualMachine.State.Running);
+ Mockito.when(vm2.getDetails()).thenReturn(Collections.emptyMap());
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+ hostList.add(host2);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(vm1);
+ vmList.add(vm2);
+
+ HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin1.getId()).thenReturn(1L);
+ Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
+
+ HostJoinVO hostJoin2 = Mockito.mock(HostJoinVO.class);
+ Mockito.when(hostJoin2.getId()).thenReturn(2L);
+ Mockito.when(hostJoin2.getCpuUsedCapacity()).thenReturn(1000L);
+ Mockito.when(hostJoin2.getCpuReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin2.getCpus()).thenReturn(4);
+ Mockito.when(hostJoin2.getSpeed()).thenReturn(1000L);
+ Mockito.when(hostJoin2.getMemUsedCapacity()).thenReturn(1024L);
+ Mockito.when(hostJoin2.getMemReservedCapacity()).thenReturn(0L);
+ Mockito.when(hostJoin2.getTotalMemory()).thenReturn(8192L);
+
+ ServiceOfferingVO serviceOffering = Mockito.mock(ServiceOfferingVO.class);
+ Mockito.when(serviceOffering.getCpu()).thenReturn(1);
+ Mockito.when(serviceOffering.getRamSize()).thenReturn(1024);
+ Mockito.when(serviceOffering.getSpeed()).thenReturn(1000);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(
+ true, true, false);
+ Mockito.when(serviceOfferingDao.findByIdIncludingRemoved(Mockito.anyLong(), Mockito.anyLong())).thenReturn(serviceOffering);
- Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1, hostJoin2));
-
- HostVO compatibleHost = Mockito.mock(HostVO.class);
++ Mockito.when(hostJoinDao.searchByIds(1L, 2L)).thenReturn(List.of(hostJoin1, hostJoin2));
+
+ // Return migrations for first two iterations, then null
+ Mockito.doReturn(new Pair<>(vm1, host2), new Pair<>(vm2, host2), new Pair<>(null, null))
+ .when(clusterDrsService).getBestMigration(
+ Mockito.any(Cluster.class), Mockito.any(ClusterDrsAlgorithm.class),
+ Mockito.anyList(), Mockito.anyMap(), Mockito.anyMap(), Mockito.anyMap(),
+ Mockito.anyMap(), Mockito.anyMap(), Mockito.anyMap());
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(2, result.size());
+ Mockito.verify(balancedAlgorithm, Mockito.times(3)).needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList());
+ }
+
+ @Test
+ public void testGetDrsPlanWithMigrationToOriginalHost() throws ConfigurationException {
+ ClusterVO cluster = Mockito.mock(ClusterVO.class);
+ Mockito.when(cluster.getId()).thenReturn(1L);
+ Mockito.when(cluster.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
+
+ HostVO host1 = Mockito.mock(HostVO.class);
+ Mockito.when(host1.getId()).thenReturn(1L);
+
+ HostVO host2 = Mockito.mock(HostVO.class);
+ Mockito.when(host2.getId()).thenReturn(2L);
+
+ VMInstanceVO vm1 = Mockito.mock(VMInstanceVO.class);
+ Mockito.when(vm1.getId()).thenReturn(1L);
+ Mockito.when(vm1.getHostId()).thenReturn(1L);
+ Mockito.when(vm1.getType()).thenReturn(VirtualMachine.Type.User);
+ Mockito.when(vm1.getState()).thenReturn(VirtualMachine.State.Running);
+ Mockito.when(vm1.getDetails()).thenReturn(Collections.emptyMap());
+
+ List<HostVO> hostList = new ArrayList<>();
+ hostList.add(host1);
+ hostList.add(host2);
+
+ List<VMInstanceVO> vmList = new ArrayList<>();
+ vmList.add(vm1);
+
- HostJoinVO hostJoin1 = Mockito.mock(HostJoinVO.class);
- Mockito.when(hostJoin1.getId()).thenReturn(1L);
- Mockito.when(hostJoin1.getCpuUsedCapacity()).thenReturn(1000L);
- Mockito.when(hostJoin1.getCpuReservedCapacity()).thenReturn(0L);
- Mockito.when(hostJoin1.getCpus()).thenReturn(4);
- Mockito.when(hostJoin1.getSpeed()).thenReturn(1000L);
- Mockito.when(hostJoin1.getMemUsedCapacity()).thenReturn(1024L);
- Mockito.when(hostJoin1.getMemReservedCapacity()).thenReturn(0L);
- Mockito.when(hostJoin1.getTotalMemory()).thenReturn(8192L);
-
- HostJoinVO hostJoin2 = Mockito.mock(HostJoinVO.class);
- Mockito.when(hostJoin2.getId()).thenReturn(2L);
- Mockito.when(hostJoin2.getCpuUsedCapacity()).thenReturn(1000L);
- Mockito.when(hostJoin2.getCpuReservedCapacity()).thenReturn(0L);
- Mockito.when(hostJoin2.getCpus()).thenReturn(4);
- Mockito.when(hostJoin2.getSpeed()).thenReturn(1000L);
- Mockito.when(hostJoin2.getMemUsedCapacity()).thenReturn(1024L);
- Mockito.when(hostJoin2.getMemReservedCapacity()).thenReturn(0L);
- Mockito.when(hostJoin2.getTotalMemory()).thenReturn(8192L);
-
+ ServiceOfferingVO serviceOffering = Mockito.mock(ServiceOfferingVO.class);
+
+ Mockito.when(hostDao.findByClusterId(1L)).thenReturn(hostList);
+ Mockito.when(vmInstanceDao.listByClusterId(1L)).thenReturn(vmList);
+ Mockito.when(balancedAlgorithm.needsDrs(Mockito.any(), Mockito.anyList(), Mockito.anyList())).thenReturn(true);
+ Mockito.when(serviceOfferingDao.findByIdIncludingRemoved(Mockito.anyLong(), Mockito.anyLong())).thenReturn(serviceOffering);
- Mockito.when(hostJoinDao.searchByIds(Mockito.any())).thenReturn(List.of(hostJoin1, hostJoin2));
-
- HostVO compatibleHost = Mockito.mock(HostVO.class);
+
+ // Return migration to original host (host1) - should break the loop
+ Mockito.doReturn(new Pair<>(vm1, host1)).when(clusterDrsService).getBestMigration(
+ Mockito.any(Cluster.class), Mockito.any(ClusterDrsAlgorithm.class),
+ Mockito.anyList(), Mockito.anyMap(), Mockito.anyMap(), Mockito.anyMap(),
+ Mockito.anyMap(), Mockito.anyMap(), Mockito.anyMap());
+
+ List<Ternary<VirtualMachine, Host, Host>> result = clusterDrsService.getDrsPlan(cluster, 5);
+ assertEquals(0, result.size());
+ // Should break early when VM would migrate to original host
+ }
+
@Test(expected = InvalidParameterValueException.class)
public void testGenerateDrsPlanClusterNotFound() {
Mockito.when(clusterDao.findById(1L)).thenReturn(null);
diff --cc ui/public/locales/en.json
index ecc24ecadea,624a13d1e21..5667fc33484
--- a/ui/public/locales/en.json
+++ b/ui/public/locales/en.json
@@@ -3347,8 -3055,9 +3349,9 @@@
"message.enable.vpn": "Please confirm that you want remote access VPN enabled for this IP address.",
"message.enable.vpn.failed": "Failed to enable VPN.",
"message.enable.vpn.processing": "Enabling VPN...",
-"message.enabled.vpn": "Your remote access VPN is currently enabled and can be accessed via the IP.",
+"message.enabled.vpn": "Your remote access VPN is currently enabled and can be accessed via the IP",
"message.enabled.vpn.ip.sec": "Your IPSec pre-shared key is",
+ "message.enabled.vpn.ip.range": "Your VPN IP Range is",
"message.enabling.security.group.provider": "Enabling security group provider",
"message.enter.valid.nic.ip": "Please enter a valid IP address for NIC",
"message.error.access.key": "Please enter access key.",
diff --cc ui/src/views/network/NicsTab.vue
index 0c62da47536,5da9ca4bb2b..9c16865e0c6
--- a/ui/src/views/network/NicsTab.vue
+++ b/ui/src/views/network/NicsTab.vue
@@@ -227,8 -247,9 +247,9 @@@
</template>
<script>
-import { api } from '@/api'
+import { getAPI, postAPI } from '@/api'
import NicsTable from '@/views/network/NicsTable'
+ import TooltipLabel from '@/components/widgets/TooltipLabel'
import TooltipButton from '@/components/widgets/TooltipButton'
import ResourceIcon from '@/components/view/ResourceIcon'
diff --cc ui/src/views/network/VpnDetails.vue
index c0cc4c6c2f1,d4c7a87ec79..2a75bb3c22e
--- a/ui/src/views/network/VpnDetails.vue
+++ b/ui/src/views/network/VpnDetails.vue
@@@ -16,131 -16,93 +16,153 @@@
// under the License.
<template>
- <div v-if="remoteAccessVpn">
- <div>
- <p>{{ $t('message.enabled.vpn') }} <strong>{{ remoteAccessVpn.publicip }}</strong></p>
- <p>{{ $t('message.enabled.vpn.ip.sec') }} <strong>{{ remoteAccessVpn.presharedkey }}</strong></p>
- <a-divider/>
- <a-button
- style="margin-left: 10px"
- type="primary"
- danger
- @click="disableVpn = true"
- :disabled="!('deleteRemoteAccessVpn' in $store.getters.apis)">
- {{ $t('label.disable.vpn') }}
- </a-button>
- <a-button><router-link :to="{ path: '/vpnuser'}">{{ $t('label.manage.vpn.user') }}</router-link></a-button>
- </div>
+ <div class="vpn-details">
+ <div v-if="remoteAccessVpn">
+ <div>
+ <p>{{ $t('message.enabled.vpn') }} <strong>{{ remoteAccessVpn.publicip }}</strong></p>
+ <p>{{ $t('message.enabled.vpn.ip.sec') }} <strong>{{ remoteAccessVpn.presharedkey }}</strong></p>
+ <p>{{ $t('message.enabled.vpn.ip.range') }} <strong>{{ remoteAccessVpn.iprange }}</strong></p>
+ <a-divider/>
+ <a-button><router-link :to="{ path: '/vpnuser'}">{{ $t('label.manage.vpn.user') }}</router-link></a-button>
+ <a-button
+ style="margin-left: 10px"
+ type="primary"
+ danger
+ @click="disableVpn = true"
+ :disabled="!('deleteRemoteAccessVpn' in $store.getters.apis)">
+ {{ $t('label.disable.vpn') }}
+ </a-button>
+ </div>
- <a-modal
- :visible="disableVpn"
- :footer="null"
- :title="$t('label.disable.vpn')"
- :closable="true"
- :maskClosable="false"
- @cancel="disableVpn = false">
- <div v-ctrl-enter="handleDisableVpn">
- <p>{{ $t('message.disable.vpn') }}</p>
+ <a-modal
+ :visible="disableVpn"
+ :footer="null"
+ :title="$t('label.disable.vpn')"
+ :closable="true"
+ :maskClosable="false"
+ @cancel="disableVpn = false">
+ <div v-ctrl-enter="handleDisableVpn">
+ <p>{{ $t('message.disable.vpn') }}</p>
- <a-divider />
+ <a-divider />
- <div class="actions">
- <a-button @click="() => disableVpn = false">{{ $t('label.cancel') }}</a-button>
- <a-button type="primary" @click="handleDisableVpn">{{ $t('label.yes') }}</a-button>
+ <div class="actions">
+ <a-button @click="() => disableVpn = false">{{ $t('label.cancel') }}</a-button>
+ <a-button type="primary" @click="handleDisableVpn">{{ $t('label.yes') }}</a-button>
+ </div>
</div>
- </div>
- </a-modal>
+ </a-modal>
- </div>
- <div v-else>
- <a-button
- :disabled="!('createRemoteAccessVpn' in $store.getters.apis)"
- type="primary"
- style="margin-left: 10px"
- @click="enableVpn = true">
- {{ $t('label.enable.vpn') }}
- </a-button>
+ </div>
+ <div v-else>
- <a-button :disabled="!('createRemoteAccessVpn' in $store.getters.apis)" type="primary" @click="enableVpn = true">
++ <a-button
++ :disabled="!('createRemoteAccessVpn' in $store.getters.apis)"
++ type="primary"
++ style="margin-left: 10px"
++ @click="enableVpn = true">
+ {{ $t('label.enable.vpn') }}
+ </a-button>
- <a-modal
- :visible="enableVpn"
- :footer="null"
- :title="$t('label.enable.vpn')"
- :maskClosable="false"
- :closable="true"
- @cancel="enableVpn = false">
- <div v-ctrl-enter="handleCreateVpn">
- <p>{{ $t('message.enable.vpn') }}</p>
+ <a-modal
+ :visible="enableVpn"
+ :footer="null"
+ :title="$t('label.enable.vpn')"
+ :maskClosable="false"
+ :closable="true"
+ @cancel="enableVpn = false">
+ <div v-ctrl-enter="handleCreateVpn">
+ <p>{{ $t('message.enable.vpn') }}</p>
+ <a-form-item>
+ <a-checkbox v-model:checked="specifyIpRange">
+ {{ $t('label.remote.access.vpn.specify.iprange') }}
+ </a-checkbox>
+ </a-form-item>
+ <a-form-item
+ v-if="specifyIpRange"
+ name="iprange"
+ :colon="false"
+ ref="iprange">
+ <template #label>
+ <tooltip-label :title="$t('label.ip.range')" :tooltip="$t('message.remote.access.vpn.iprange.description')"/>
+ </template>
+ <a-input
+ v-model:value="vpnIpRange"
+ :placeholder="'10.1.2.1-10.1.2.8'"
+ />
+ </a-form-item>
- <a-divider />
+ <a-divider />
- <div class="actions">
- <a-button @click="() => enableVpn = false">{{ $t('label.cancel') }}</a-button>
- <a-button type="primary" ref="submit" @click="handleCreateVpn">{{ $t('label.yes') }}</a-button>
+ <div class="actions">
+ <a-button @click="() => enableVpn = false">{{ $t('label.cancel') }}</a-button>
+ <a-button type="primary" ref="submit" @click="handleCreateVpn">{{ $t('label.yes') }}</a-button>
+ </div>
</div>
- </div>
- </a-modal>
+ </a-modal>
- </div>
-
- <br>
- <div v-if="vpnGateway">
- <div>
- <a-button
- :disabled="!('deleteVpnGateway' in $store.getters.apis)"
- style="margin-left: 10px"
- danger
- type="primary"
- @click="deleteVpnGateway = true">
- {{ $t('label.delete.vpn.gateway') }}
- </a-button>
</div>
- <a-modal
- :visible="deleteVpnGateway"
- :footer="null"
- :title="$t('label.enable.vpn')"
- :maskClosable="false"
- :closable="true"
- @cancel="deleteVpnGateway = false">
- <div v-ctrl-enter="handleDeleteVpnGateway">
- <p>{{ $t('message.delete.vpn.gateway') }}</p>
- <div :span="24" class="action-button">
- <a-button @click="deleteVpnGateway = false">{{ $t('label.cancel') }}</a-button>
- <a-button :loading="loading" type="primary" @click="handleDeleteVpnGateway" ref="submit">{{ $t('label.ok') }}</a-button>
- </div>
++
++ <br>
++ <div v-if="vpnGateway">
++ <div>
++ <a-button
++ :disabled="!('deleteVpnGateway' in $store.getters.apis)"
++ style="margin-left: 10px"
++ danger
++ type="primary"
++ @click="deleteVpnGateway = true">
++ {{ $t('label.delete.vpn.gateway') }}
++ </a-button>
+ </div>
- </a-modal>
- </div>
- <div v-else-if="vpnGatewayEnabled">
- <div>
- <a-button
- :disabled="!('createVpnGateway' in $store.getters.apis)"
- style="margin-left: 10px"
- type="primary"
- @click="createVpnGateway = true">
- {{ $t('label.add.vpn.gateway') }}
- </a-button>
- </div>
- <a-modal
- :visible="createVpnGateway"
- :footer="null"
- :title="$t('label.add.vpn.gateway')"
- :maskClosable="false"
- :closable="true"
- @cancel="createVpnGateway = false">
- <div v-ctrl-enter="handleCreateVpnGateway">
- <p>{{ $t('message.add.vpn.gateway') }}</p>
- <div :span="24" class="action-button">
- <a-button @click="createVpnGateway = false">{{ $t('label.cancel') }}</a-button>
- <a-button :loading="loading" type="primary" @click="handleCreateVpnGateway" ref="submit">{{ $t('label.ok') }}</a-button>
++ <a-modal
++ :visible="deleteVpnGateway"
++ :footer="null"
++ :title="$t('label.enable.vpn')"
++ :maskClosable="false"
++ :closable="true"
++ @cancel="deleteVpnGateway = false">
++ <div v-ctrl-enter="handleDeleteVpnGateway">
++ <p>{{ $t('message.delete.vpn.gateway') }}</p>
++ <div :span="24" class="action-button">
++ <a-button @click="deleteVpnGateway = false">{{ $t('label.cancel') }}</a-button>
++ <a-button :loading="loading" type="primary" @click="handleDeleteVpnGateway" ref="submit">{{ $t('label.ok') }}</a-button>
++ </div>
+ </div>
++ </a-modal>
++ </div>
++ <div v-else-if="vpnGatewayEnabled">
++ <div>
++ <a-button
++ :disabled="!('createVpnGateway' in $store.getters.apis)"
++ style="margin-left: 10px"
++ type="primary"
++ @click="createVpnGateway = true">
++ {{ $t('label.add.vpn.gateway') }}
++ </a-button>
+ </div>
- </a-modal>
++ <a-modal
++ :visible="createVpnGateway"
++ :footer="null"
++ :title="$t('label.add.vpn.gateway')"
++ :maskClosable="false"
++ :closable="true"
++ @cancel="createVpnGateway = false">
++ <div v-ctrl-enter="handleCreateVpnGateway">
++ <p>{{ $t('message.add.vpn.gateway') }}</p>
++ <div :span="24" class="action-button">
++ <a-button @click="createVpnGateway = false">{{ $t('label.cancel') }}</a-button>
++ <a-button :loading="loading" type="primary" @click="handleCreateVpnGateway" ref="submit">{{ $t('label.ok') }}</a-button>
++ </div>
++ </div>
++ </a-modal>
++ </div>
</div>
+
</template>
<script>
-import { api } from '@/api'
+import { getAPI, postAPI } from '@/api'
+ import TooltipLabel from '@/components/widgets/TooltipLabel'
export default {
props: {
@@@ -154,11 -119,9 +179,13 @@@
remoteAccessVpn: null,
enableVpn: false,
disableVpn: false,
+ vpnGateway: null,
+ vpnGatewayEnabled: false,
+ createVpnGateway: false,
+ deleteVpnGateway: false,
- isSubmitted: false
+ isSubmitted: false,
+ specifyIpRange: false,
+ vpnIpRange: ''
}
},
inject: ['parentFetchData', 'parentToggleLoading'],
@@@ -215,7 -161,11 +242,11 @@@
publicipid: this.resource.id,
domainid: this.resource.domainid,
account: this.resource.account
- }).then(response => {
+ }
+ if (this.specifyIpRange && this.vpnIpRange?.trim()) {
+ params.iprange = this.vpnIpRange.trim()
+ }
- api('createRemoteAccessVpn', params).then(response => {
++ postAPI('createRemoteAccessVpn', params).then(response => {
this.$pollJob({
jobId: response.createremoteaccessvpnresponse.jobid,
successMethod: result => {