This is an automated email from the ASF dual-hosted git repository. dahn pushed a commit to branch UserVmManagerCleanup in repository https://gitbox.apache.org/repos/asf/cloudstack.git
commit f237082579486ec6d1e53b05a4efa6e016a9ea09 Author: Daan Hoogland <[email protected]> AuthorDate: Tue Mar 10 10:31:28 2026 +0100 static analysis warnings in User Vm Manager --- .../com/cloud/template/VirtualMachineTemplate.java | 2 +- api/src/main/java/com/cloud/vm/UserVmService.java | 17 +- .../main/java/com/cloud/vm/UserVmManagerImpl.java | 549 +++++++++------------ .../java/com/cloud/vm/UserVmManagerImplTest.java | 45 +- 4 files changed, 256 insertions(+), 357 deletions(-) diff --git a/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java b/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java index b8c646048b9..cb221c35731 100644 --- a/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java +++ b/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java @@ -131,7 +131,7 @@ public interface VirtualMachineTemplate extends ControlledEntity, Identity, Inte String getTemplateTag(); - Map getDetails(); + Map<String, String> getDetails(); boolean isDynamicallyScalable(); diff --git a/api/src/main/java/com/cloud/vm/UserVmService.java b/api/src/main/java/com/cloud/vm/UserVmService.java index 01f11b73cd4..9bec28f3557 100644 --- a/api/src/main/java/com/cloud/vm/UserVmService.java +++ b/api/src/main/java/com/cloud/vm/UserVmService.java @@ -53,7 +53,6 @@ import com.cloud.exception.ManagementServerException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.StorageUnavailableException; import com.cloud.exception.VirtualMachineMigrationException; import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -111,7 +110,7 @@ public interface UserVmService { UserVm resetVMUserData(ResetVMUserDataCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException; - UserVm startVirtualMachine(StartVMCmd cmd) throws StorageUnavailableException, ExecutionException, ConcurrentOperationException, ResourceUnavailableException, + UserVm startVirtualMachine(StartVMCmd cmd) throws ExecutionException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException; UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException; @@ -226,8 +225,8 @@ public interface UserVmService { String userData, Long userDataId, String userDataDetails, List<String> sshKeyPairs, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIp, Boolean displayVm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParameter, String customId, Map<String, Map<Integer, String>> dhcpOptionMap, Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, - Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException; /** * Creates a User VM in Advanced Zone (Security Group feature is enabled) in @@ -302,7 +301,8 @@ public interface UserVmService { List<Long> securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, List<VmDiskInfo> dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List<String> sshKeyPairs, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParameters, String customId, Map<String, Map<Integer, String>> dhcpOptionMap, - Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException; /** * Creates a User VM in Advanced Zone (Security Group feature is disabled) @@ -376,7 +376,7 @@ public interface UserVmService { Map<String, String> customParameters, String customId, Map<String, Map<Integer, String>> dhcpOptionMap, Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, Map<String, String> templateOvfPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException; /** * Starts the virtual machine created from createVirtualMachine. @@ -418,8 +418,7 @@ public interface UserVmService { HypervisorType getHypervisorTypeOfUserVM(long vmid); - UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, - StorageUnavailableException, ResourceAllocationException; + UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, ResourceAllocationException; /** * This API is mostly to trigger VM.CREATE event for deployVirtualMachine with startvm=false, because there is no code in "execute" part of VM creation. @@ -502,7 +501,7 @@ public interface UserVmService { * determine whether the uservm should be visible to the end user * @return value of the display flag */ - public boolean isDisplayResourceEnabled(Long vmId); + boolean isDisplayResourceEnabled(Long vmId); void collectVmDiskStatistics(UserVm userVm); diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index ea2d00e85fa..ea97c7eb0a6 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -24,7 +24,6 @@ import static org.apache.cloudstack.api.ApiConstants.MIN_IOPS; import java.io.IOException; import java.io.StringReader; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.net.URLDecoder; import java.text.SimpleDateFormat; @@ -60,8 +59,6 @@ import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; -import com.cloud.storage.SnapshotPolicyVO; -import com.cloud.storage.dao.SnapshotPolicyDao; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -150,12 +147,10 @@ import org.apache.cloudstack.utils.bytescale.ByteScaleUtils; import org.apache.cloudstack.utils.security.ParserUtils; import org.apache.cloudstack.vm.UnmanagedVMsManager; import org.apache.cloudstack.vm.lease.VMLeaseManager; -import org.apache.cloudstack.vm.schedule.VMScheduleManager; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.jetbrains.annotations.NotNull; @@ -315,7 +310,6 @@ import com.cloud.resource.ResourceState; import com.cloud.resourcelimit.CheckedReservation; import com.cloud.server.ManagementService; import com.cloud.server.ResourceTag; -import com.cloud.server.StatsCollector; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.service.dao.ServiceOfferingDetailsDao; @@ -325,6 +319,7 @@ import com.cloud.storage.GuestOSCategoryVO; import com.cloud.storage.GuestOSVO; import com.cloud.storage.ScopeType; import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.SnapshotVO; import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; @@ -343,6 +338,7 @@ import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotPolicyDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateZoneDao; import com.cloud.storage.dao.VolumeDao; @@ -373,6 +369,7 @@ import com.cloud.utils.DateUtil; import com.cloud.utils.Journal; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; +import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -616,8 +613,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Inject BackupScheduleDao backupScheduleDao; - @Inject - private StatsCollector statsCollector; @Inject private UserDataDao userDataDao; @@ -627,8 +622,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Inject private AutoScaleManager autoScaleManager; - @Inject - VMScheduleManager vmScheduleManager; @Inject NsxProviderDao nsxProviderDao; @@ -651,14 +644,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir private String _instance; private boolean _instanceNameFlag; private int _scaleRetry; - private Map<Long, VmAndCountDetails> vmIdCountMap = new ConcurrentHashMap<>(); + private final Map<Long, VmAndCountDetails> vmIdCountMap = new ConcurrentHashMap<>(); protected static long ROOT_DEVICE_ID = 0; - private static final int MAX_HTTP_GET_LENGTH = 2 * MAX_USER_DATA_LENGTH_BYTES; - private static final int NUM_OF_2K_BLOCKS = 512; - private static final int MAX_HTTP_POST_LENGTH = NUM_OF_2K_BLOCKS * MAX_USER_DATA_LENGTH_BYTES; - public List<KubernetesServiceHelper> getKubernetesServiceHelpers() { return kubernetesServiceHelpers; } @@ -682,19 +671,19 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Inject VnfTemplateManager vnfTemplateManager; - private static final ConfigKey<Integer> VmIpFetchWaitInterval = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmip.retrieval.interval", "180", + private static final ConfigKey<Integer> VmIpFetchWaitInterval = new ConfigKey<>("Advanced", Integer.class, "externaldhcp.vmip.retrieval.interval", "180", "Wait Interval (in seconds) for shared network vm dhcp ip addr fetch for next iteration ", true); - private static final ConfigKey<Integer> VmIpFetchTrialMax = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmip.max.retry", "10", + private static final ConfigKey<Integer> VmIpFetchTrialMax = new ConfigKey<>("Advanced", Integer.class, "externaldhcp.vmip.max.retry", "10", "The max number of retrieval times for shared network vm dhcp ip fetch, in case of failures", true); - private static final ConfigKey<Integer> VmIpFetchThreadPoolMax = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmipFetch.threadPool.max", "10", + private static final ConfigKey<Integer> VmIpFetchThreadPoolMax = new ConfigKey<>("Advanced", Integer.class, "externaldhcp.vmipFetch.threadPool.max", "10", "number of threads for fetching vms ip address", true); - private static final ConfigKey<Integer> VmIpFetchTaskWorkers = new ConfigKey<Integer>("Advanced", Integer.class, "externaldhcp.vmipfetchtask.workers", "10", + private static final ConfigKey<Integer> VmIpFetchTaskWorkers = new ConfigKey<>("Advanced", Integer.class, "externaldhcp.vmipfetchtask.workers", "10", "number of worker threads for vm ip fetch task ", true); - private static final ConfigKey<Boolean> AllowDeployVmIfGivenHostFails = new ConfigKey<Boolean>("Advanced", Boolean.class, "allow.deploy.vm.if.deploy.on.given.host.fails", "false", + private static final ConfigKey<Boolean> AllowDeployVmIfGivenHostFails = new ConfigKey<>("Advanced", Boolean.class, "allow.deploy.vm.if.deploy.on.given.host.fails", "false", "allow vm to deploy on different host if vm fails to deploy on the given host ", true); private static final ConfigKey<String> KvmAdditionalConfigAllowList = new ConfigKey<>(String.class, @@ -706,7 +695,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir private static final ConfigKey<String> VmwareAdditionalConfigAllowList = new ConfigKey<>(String.class, "allow.additional.vm.configuration.list.vmware", "Advanced", "", "Comma separated list of allowed additional configuration options.", true, ConfigKey.Scope.Global, null, null, EnableAdditionalVmConfig.key(), null, null, ConfigKey.Kind.CSV, null); - private static final ConfigKey<Boolean> VmDestroyForcestop = new ConfigKey<Boolean>("Advanced", Boolean.class, "vm.destroy.forcestop", "false", + private static final ConfigKey<Boolean> VmDestroyForcestop = new ConfigKey<>("Advanced", Boolean.class, "vm.destroy.forcestop", "false", "On destroy, force-stop takes this value ", true); @Override @@ -731,31 +720,20 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } } - public class VmAndCountDetails { + public static class VmAndCountDetails { long vmId; int retrievalCount = VmIpFetchTrialMax.value(); - public VmAndCountDetails() { - } - public VmAndCountDetails (long vmId, int retrievalCount) { this.vmId = vmId; this.retrievalCount = retrievalCount; } - public VmAndCountDetails (long vmId) { - this.vmId = vmId; - } - public int getRetrievalCount() { return retrievalCount; } - public void setRetrievalCount(int retrievalCount) { - this.retrievalCount = retrievalCount; - } - public long getVmId() { return vmId; } @@ -903,10 +881,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private boolean resetVMPasswordInternal(Long vmId, String password) throws ResourceUnavailableException, InsufficientCapacityException { - Long userId = CallContext.current().getCallingUserId(); VMInstanceVO vmInstance = _vmDao.findById(vmId); - if (password == null || password.equals("")) { + if (password == null || password.isEmpty()) { return false; } @@ -949,7 +926,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return true; } - if (rebootVirtualMachine(userId, vmId, false, false) == null) { + if (rebootVirtualMachine(vmId, false, false) == null) { logger.warn("Failed to reboot the Instance " + vmInstance); return false; } else { @@ -1067,7 +1044,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (pairs == null || pairs.size() != names.size()) { throw new InvalidParameterValueException("Not all specified keypairs exist"); } - sshPublicKeys = pairs.stream().map(p -> p.getPublicKey()).collect(Collectors.joining("\n")); + sshPublicKeys = pairs.stream().map(SSHKeyPairVO::getPublicKey).collect(Collectors.joining("\n")); keypairnames = String.join(",", names); _accountMgr.checkAccess(caller, null, true, userVm); @@ -1091,7 +1068,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private boolean resetVMSSHKeyInternal(Long vmId, String sshPublicKeys, String keypairnames) throws ResourceUnavailableException, InsufficientCapacityException { - Long userId = CallContext.current().getCallingUserId(); VMInstanceVO vmInstance = _vmDao.findById(vmId); VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId()); @@ -1127,7 +1103,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir logger.debug("Vm " + vmInstance + " is stopped, not rebooting it as a part of SSH Key reset"); return true; } - if (rebootVirtualMachine(userId, vmId, false, false) == null) { + if (rebootVirtualMachine(vmId, false, false) == null) { logger.warn("Failed to reboot the vm " + vmInstance); return false; } else { @@ -1157,14 +1133,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir status = vmEntity.stop(Long.toString(userId)); } catch (ResourceUnavailableException e) { logger.debug("Unable to stop due to ", e); - status = false; } catch (CloudException e) { throw new CloudRuntimeException("Unable to contact the agent to stop the Instance " + vm, e); } return status; } - private UserVm rebootVirtualMachine(long userId, long vmId, boolean enterSetup, boolean forced) throws InsufficientCapacityException, ResourceUnavailableException { + private UserVm rebootVirtualMachine(long vmId, boolean enterSetup, boolean forced) throws InsufficientCapacityException, ResourceUnavailableException { UserVmVO vm = _vmDao.findById(vmId); if (logger.isTraceEnabled()) { @@ -1192,7 +1167,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (dc.getNetworkType() == DataCenter.NetworkType.Advanced) { //List all networks of vm List<Long> vmNetworks = _vmNetworkMapDao.getNetworks(vmId); - List<DomainRouterVO> routers = new ArrayList<DomainRouterVO>(); + List<DomainRouterVO> routers = new ArrayList<>(); //List the stopped routers for(long vmNetworkId : vmNetworks) { List<DomainRouterVO> router = _routerDao.listStopped(vmNetworkId); @@ -1216,7 +1191,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } Map<VirtualMachineProfile.Param,Object> params = null; if (enterSetup) { - params = new HashMap(); + params = new HashMap<>(); params.put(VirtualMachineProfile.Param.BootIntoSetup, Boolean.TRUE); if (logger.isTraceEnabled()) { logger.trace(String.format("Adding %s to paramlist", VirtualMachineProfile.Param.BootIntoSetup)); @@ -1263,7 +1238,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (vmInstance == null) { throw new InvalidParameterValueException("unable to find an Instance with id " + vmId); } else if (!(vmInstance.getState().equals(State.Stopped))) { - throw new InvalidParameterValueException("Unable to upgrade Instance " + vmInstance.toString() + " " + " in state " + vmInstance.getState() + throw new InvalidParameterValueException("Unable to upgrade Instance " + vmInstance + " " + " in state " + vmInstance.getState() + "; make sure the Instance is stopped"); } @@ -1326,13 +1301,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override public void validateCustomParameters(ServiceOfferingVO serviceOffering, Map<String, String> customParameters) { //TODO need to validate custom cpu, and memory against min/max CPU/Memory ranges from service_offering_details table - if (customParameters.size() != 0) { + if (!customParameters.isEmpty()) { Map<String, String> offeringDetails = serviceOfferingDetailsDao.listDetailsKeyPairs(serviceOffering.getId()); if (serviceOffering.getCpu() == null) { int minCPU = NumbersUtil.parseInt(offeringDetails.get(ApiConstants.MIN_CPU_NUMBER), 1); int maxCPU = NumbersUtil.parseInt(offeringDetails.get(ApiConstants.MAX_CPU_NUMBER), Integer.MAX_VALUE); int cpuNumber = NumbersUtil.parseInt(customParameters.get(UsageEventVO.DynamicParameters.cpuNumber.name()), -1); - Integer maxCPUCores = ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_CPU_CORES.value() == 0 ? Integer.MAX_VALUE: ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_CPU_CORES.value(); + int maxCPUCores = ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_CPU_CORES.value() == 0 ? Integer.MAX_VALUE: ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_CPU_CORES.value(); if (cpuNumber < minCPU || cpuNumber > maxCPU || cpuNumber > maxCPUCores) { throw new InvalidParameterValueException(String.format("Invalid CPU cores value, specify a value between %d and %d", minCPU, Math.min(maxCPUCores, maxCPU))); } @@ -1355,7 +1330,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir int minMemory = NumbersUtil.parseInt(offeringDetails.get(ApiConstants.MIN_MEMORY), 32); int maxMemory = NumbersUtil.parseInt(offeringDetails.get(ApiConstants.MAX_MEMORY), Integer.MAX_VALUE); int memory = NumbersUtil.parseInt(customParameters.get(UsageEventVO.DynamicParameters.memory.name()), -1); - Integer maxRAMSize = ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_RAM_SIZE.value() == 0 ? Integer.MAX_VALUE: ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_RAM_SIZE.value(); + int maxRAMSize = ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_RAM_SIZE.value() == 0 ? Integer.MAX_VALUE: ConfigurationManagerImpl.VM_SERVICE_OFFERING_MAX_RAM_SIZE.value(); if (memory < minMemory || memory > maxMemory || memory > maxRAMSize) { throw new InvalidParameterValueException(String.format("Invalid memory value, specify a value between %d and %d", minMemory, Math.min(maxRAMSize, maxMemory))); } @@ -1367,7 +1342,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } } - private UserVm upgradeStoppedVirtualMachine(Long vmId, Long svcOffId, Map<String, String> customParameters) throws ResourceAllocationException { + private void upgradeStoppedVirtualMachine(Long vmId, Long svcOffId, Map<String, String> customParameters) throws ResourceAllocationException { VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); // Check resource limits for CPU and Memory. @@ -1415,9 +1390,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _resourceLimitMgr.updateVmResourceCountForServiceOfferingChange(owner.getAccountId(), vmInstance.isDisplay(), (long) currentCpu, (long) newCpu, (long) currentMemory, (long) newMemory, currentServiceOffering, newServiceOffering, template); } - - return _vmDao.findById(vmInstance.getId()); - } /** @@ -1446,7 +1418,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir resizeVolumeCmd = new ResizeVolumeCmd(rootVolume.getId(), newRootDiskOffering.getMinIops(), newRootDiskOffering.getMaxIops(), newRootDiskOffering.getId()); logger.debug("Preparing command to resize VM Root disk from {} GB to {} GB; current offering: {}, new offering: {}.", currentRootDiskOfferingGiB, newNewOfferingRootSizeInGiB, currentRootDiskOffering, newRootDiskOffering); - } else if (newNewOfferingRootSizeInBytes > 0l && newNewOfferingRootSizeInBytes < currentRootDiskOffering.getDiskSize()) { + } else if (newNewOfferingRootSizeInBytes > 0L && newNewOfferingRootSizeInBytes < currentRootDiskOffering.getDiskSize()) { throw new InvalidParameterValueException(String.format( "Failed to resize Root volume. The new Service Offering [%s] has a smaller disk size [%d GB] than the current disk [%d GB].", newRootDiskOffering, newNewOfferingRootSizeInGiB, currentRootDiskOfferingGiB)); @@ -1456,7 +1428,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override @ActionEvent(eventType = EventTypes.EVENT_NIC_CREATE, eventDescription = "Creating NIC", async = true) - public UserVm addNicToVirtualMachine(AddNicToVMCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, CloudRuntimeException { + public UserVm addNicToVirtualMachine(AddNicToVMCmd cmd) throws CloudRuntimeException { Long vmId = cmd.getVmId(); Long networkId = cmd.getNetworkId(); String ipAddress = cmd.getIpAddress(); @@ -1469,7 +1441,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Check that Vm does not have VM Snapshots - if (_vmSnapshotDao.findByVm(vmId).size() > 0) { + if (!_vmSnapshotDao.findByVm(vmId).isEmpty()) { throw new InvalidParameterValueException("NIC cannot be added to Instance with Instance Snapshots"); } @@ -1547,19 +1519,23 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operations on adding NIC to " + vmInstance + ": " + e); } finally { - if(cleanUp) { - try { - _itMgr.removeVmFromNetwork(vmInstance, network, null); - } catch (ResourceUnavailableException e) { - throw new CloudRuntimeException("Error while cleaning up NIC " + e); - } - } + cleanupConditionally(cleanUp, vmInstance, network); } CallContext.current().putContextParameter(Nic.class, guestNic.getUuid()); logger.debug(String.format("Successful addition of %s from %s through %s", network, vmInstance, guestNic)); return _vmDao.findById(vmInstance.getId()); } + private void cleanupConditionally(boolean cleanUp, UserVmVO vmInstance, NetworkVO network) { + if(cleanUp) { + try { + _itMgr.removeVmFromNetwork(vmInstance, network, null); + } catch (ResourceUnavailableException e) { + throw new CloudRuntimeException("Error while cleaning up NIC " + e); + } + } + } + /** * Set NIC as default if VM has no default NIC * @param vmInstance VM instance to be checked @@ -1610,7 +1586,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override @ActionEvent(eventType = EventTypes.EVENT_NIC_DELETE, eventDescription = "Removing NIC", async = true) - public UserVm removeNicFromVirtualMachine(RemoveNicFromVMCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, CloudRuntimeException { + public UserVm removeNicFromVirtualMachine(RemoveNicFromVMCmd cmd) throws CloudRuntimeException { Long vmId = cmd.getVmId(); Long nicId = cmd.getNicId(); Account caller = CallContext.current().getCallingAccount(); @@ -1621,7 +1597,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Check that Vm does not have VM Snapshots - if (_vmSnapshotDao.findByVm(vmId).size() > 0) { + if (!_vmSnapshotDao.findByVm(vmId).isEmpty()) { throw new InvalidParameterValueException("NIC cannot be removed from Instance with Instance Snapshots"); } @@ -1655,7 +1631,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // if specified nic is associated with PF/LB/Static NAT - if (_rulesMgr.listAssociatedRulesForGuestNic(nic).size() > 0) { + if (!_rulesMgr.listAssociatedRulesForGuestNic(nic).isEmpty()) { throw new InvalidParameterValueException("Unable to remove NIC from " + vmInstance + " in " + network + ", NIC has associated Port forwarding or Load balancer or Static NAT rules."); } @@ -1679,7 +1655,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override @ActionEvent(eventType = EventTypes.EVENT_NIC_UPDATE, eventDescription = "Creating NIC", async = true) - public UserVm updateDefaultNicForVirtualMachine(UpdateDefaultNicForVMCmd cmd) throws InvalidParameterValueException, CloudRuntimeException { + public UserVm updateDefaultNicForVirtualMachine(UpdateDefaultNicForVMCmd cmd) throws CloudRuntimeException { Long vmId = cmd.getVmId(); Long nicId = cmd.getNicId(); Account caller = CallContext.current().getCallingAccount(); @@ -1690,7 +1666,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Check that Vm does not have VM Snapshots - if (_vmSnapshotDao.findByVm(vmId).size() > 0) { + if (!_vmSnapshotDao.findByVm(vmId).isEmpty()) { throw new InvalidParameterValueException("NIC cannot be updated for Instance with Instance Snapshots"); } @@ -1751,7 +1727,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir oldNetworkOfferingId = oldDefaultNetwork.getNetworkOfferingId(); } NicVO existingVO = _nicDao.findById(existing.id); - Integer chosenID = nic.getDeviceId(); + int chosenID = nic.getDeviceId(); Integer existingID = existing.getDeviceId(); Network newdefault = null; @@ -1968,7 +1944,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Long vmId = cmd.getId(); Long newServiceOfferingId = cmd.getServiceOfferingId(); - VirtualMachine vm = (VirtualMachine) this._entityMgr.findById(VirtualMachine.class, vmId); + VirtualMachine vm = this._entityMgr.findById(VirtualMachine.class, vmId); if (vm == null) { throw new InvalidParameterValueException("Unable to find VM's UUID"); } @@ -2032,8 +2008,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return upgradeRunningVirtualMachine(vmId, newServiceOfferingId, customParameters); } - private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingId, Map<String, String> customParameters) throws ResourceUnavailableException, - ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { + private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingId, Map<String, String> customParameters) + throws ConcurrentOperationException, ManagementServerException { Account caller = CallContext.current().getCallingAccount(); VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); @@ -2092,7 +2068,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } if (vmHypervisorType.equals(HypervisorType.KVM) && !currentServiceOffering.isDynamic()) { - String message = String.format("Unable to live scale VM on KVM when current service offering is a \"Fixed Offering\". KVM needs the tag \"maxMemory\" to live scale and it is only configured when VM is deployed with a custom service offering and \"Dynamic Scalable\" is enabled."); + String message = "Unable to live scale VM on KVM when current service offering is a \"Fixed Offering\". KVM needs the tag \"maxMemory\" to live scale and it is only configured when VM is deployed with a custom service offering and \"Dynamic Scalable\" is enabled."; logger.info(message); throw new InvalidParameterValueException(message); } @@ -2129,14 +2105,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Check vm flag if (!vmInstance.isDynamicallyScalable()) { - throw new CloudRuntimeException(String.format("Unable to scale %s as it does not have tools to support dynamic scaling.", vmInstance.toString())); + throw new CloudRuntimeException(String.format("Unable to scale %s as it does not have tools to support dynamic scaling.", vmInstance)); } // Check disable threshold for cluster is not crossed HostVO host = _hostDao.findById(vmInstance.getHostId()); _hostDao.loadDetails(host); if (_capacityMgr.checkIfClusterCrossesThreshold(host.getClusterId(), cpuDiff, memoryDiff)) { - throw new CloudRuntimeException(String.format("Unable to scale %s due to insufficient resources.", vmInstance.toString())); + throw new CloudRuntimeException(String.format("Unable to scale %s due to insufficient resources.", vmInstance)); } while (retry-- != 0) { // It's != so that it can match -1. @@ -2173,7 +2149,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir success = true; return success; } catch (InsufficientCapacityException | ResourceUnavailableException | ConcurrentOperationException e) { - logger.error(String.format("Unable to scale %s due to [%s].", vmInstance.toString(), e.getMessage()), e); + logger.error(String.format("Unable to scale %s due to [%s].", vmInstance, e.getMessage()), e); } finally { if (!success) { // Decrement CPU and Memory count accordingly. @@ -2295,7 +2271,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir answer = _agentMgr.easySend(neighbor.getId(), cmd); } - if (answer != null && answer instanceof GetVolumeStatsAnswer){ + if (answer instanceof GetVolumeStatsAnswer){ GetVolumeStatsAnswer volstats = (GetVolumeStatsAnswer)answer; if (volstats.getVolumeStats() != null) { volumeStatsByUuid.putAll(volstats.getVolumeStats()); @@ -2303,7 +2279,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } } } - return volumeStatsByUuid.size() > 0 ? volumeStatsByUuid : null; + return !volumeStatsByUuid.isEmpty() ? volumeStatsByUuid : null; } private List<String> getVolumesByHost(HostVO host, StoragePool pool){ @@ -2441,7 +2417,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("UserVm-Scavenger")); - String vmIpWorkers = configs.get(VmIpFetchTaskWorkers.value()); + String vmIpWorkers = configs.get(VmIpFetchTaskWorkers.value().toString()); int vmipwrks = NumbersUtil.parseInt(vmIpWorkers, 10); _vmIpFetchExecutor = Executors.newScheduledThreadPool(vmipwrks, new NamedThreadFactory("UserVm-ipfetch")); @@ -2452,18 +2428,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir final int DAILY_TIME = 60 * 24; if (_usageAggregationRange == DAILY_TIME) { _dailyOrHourly = true; - } else if (_usageAggregationRange == HOURLY_TIME) { - _dailyOrHourly = true; - } else { - _dailyOrHourly = false; - } + } else _dailyOrHourly = _usageAggregationRange == HOURLY_TIME; _itMgr.registerGuru(VirtualMachine.Type.User, this); VirtualMachine.State.getStateMachine().registerListener(new UserVmStateListener(_usageEventDao, _networkDao, _nicDao, serviceOfferingDao, _vmDao, this, _configDao)); String value = _configDao.getValue(Config.SetVmInternalNameUsingDisplayName.key()); - _instanceNameFlag = (value == null) ? false : Boolean.parseBoolean(value); + _instanceNameFlag = Boolean.parseBoolean(value); _scaleRetry = NumbersUtil.parseInt(configs.get(Config.ScaleRetry.key()), 2); @@ -2474,11 +2446,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return true; } - @Override - public String getName() { - return _name; - } - @Override public boolean start() { _executor.scheduleWithFixedDelay(new ExpungeTask(), _expungeInterval, _expungeInterval, TimeUnit.SECONDS); @@ -2520,10 +2487,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return true; } - public String getRandomPrivateTemplateName() { - return UUID.randomUUID().toString(); - } - @Override public boolean expunge(UserVmVO vm) { vm = _vmDao.acquireInLockTable(vm.getId()); @@ -2538,7 +2501,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir releaseNetworkResourcesOnExpunge(vm.getId()); - List<VolumeVO> rootVol = _volsDao.findByInstanceAndType(vm.getId(), Volume.Type.ROOT); // expunge the vm _itMgr.advanceExpunge(vm.getUuid()); @@ -2615,7 +2577,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // cleanup port forwarding rules VMInstanceVO vmInstanceVO = _vmInstanceDao.findById(vmId); NsxProviderVO nsx = nsxProviderDao.findByZoneId(vmInstanceVO.getDataCenterId()); - if (Objects.isNull(nsx) || Objects.isNull(kubernetesServiceHelpers.get(0).findByVmId(vmId))) { + if (Objects.isNull(nsx) || Objects.isNull(getKubernetesServiceHelpers().get(0).findByVmId(vmId))) { if (_rulesMgr.revokePortForwardingRulesForVm(vmId)) { logger.debug("Port forwarding rules are removed successfully as a part of vm {} expunge", vm); } else { @@ -2765,8 +2727,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir try { List<UserVmVO> vms = _vmDao.findDestroyedVms(new Date(System.currentTimeMillis() - ((long)_expungeDelay << 10))); if (logger.isInfoEnabled()) { - if (vms.size() == 0) { - logger.trace("Found " + vms.size() + " Instances to expunge."); + if (vms.isEmpty()) { + logger.trace("Found no Instances to expunge."); } else { logger.info("Found " + vms.size() + " Instances to expunge."); } @@ -2908,11 +2870,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } final Account caller = CallContext.current().getCallingAccount(); final List<String> userDenyListedSettings = Stream.of(QueryService.UserVMDeniedDetails.value().split(",")) - .map(item -> (item).trim()) + .map(String::trim) .collect(Collectors.toList()); userDenyListedSettings.addAll(QueryService.RootAdminOnlyVmSettings); final List<String> userReadOnlySettings = Stream.of(QueryService.UserVMReadOnlyDetails.value().split(",")) - .map(item -> (item).trim()) + .map(String::trim) .collect(Collectors.toList()); List<VMInstanceDetailVO> existingDetails = vmInstanceDetailsDao.listDetails(id); if (cleanupDetails){ @@ -3085,7 +3047,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir generateUsageEvent(vm, true, EventTypes.EVENT_VM_START); // 3. Network offering usage - generateNetworkUsageForVm(vm, true, EventTypes.EVENT_NETWORK_OFFERING_ASSIGN); + generateNetworkUsageForVm(vm, EventTypes.EVENT_NETWORK_OFFERING_ASSIGN); } }else { @@ -3097,21 +3059,21 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir generateUsageEvent(vm, true, EventTypes.EVENT_VM_STOP); // 3. Network offering usage - generateNetworkUsageForVm(vm, true, EventTypes.EVENT_NETWORK_OFFERING_REMOVE); + generateNetworkUsageForVm(vm, EventTypes.EVENT_NETWORK_OFFERING_REMOVE); } } } } - private void generateNetworkUsageForVm(VirtualMachine vm, boolean isDisplay, String eventType){ + private void generateNetworkUsageForVm(VirtualMachine vm, String eventType){ List<NicVO> nics = _nicDao.listByVmId(vm.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); long isDefault = (nic.isDefaultNic()) ? 1 : 0; UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), - Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, vm.getClass().getName(), vm.getUuid(), isDisplay); + Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, vm.getClass().getName(), vm.getUuid(), true); } } @@ -3193,7 +3155,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (isDynamicallyScalable == null) { isDynamicallyScalable = vm.isDynamicallyScalable(); } else { - if (isDynamicallyScalable == true) { + if (isDynamicallyScalable) { VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId()); if (!template.isDynamicallyScalable()) { throw new InvalidParameterValueException("Dynamic Scaling cannot be enabled for the Instance since its Template does not have dynamic scaling enabled"); @@ -3220,7 +3182,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Verify that vm's hostName is unique - List<NetworkVO> vmNtwks = new ArrayList<NetworkVO>(nics.size()); + List<NetworkVO> vmNtwks = new ArrayList<>(nics.size()); for (Nic nic : nics) { vmNtwks.add(_networkDao.findById(nic.getNetworkId())); } @@ -3438,7 +3400,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir ServiceOfferingVO offering = serviceOfferingDao.findById(vmInstance.getId(), serviceOfferingId); if (offering != null && offering.getRemoved() == null) { if (offering.isVolatileVm()) { - return restoreVMInternal(caller, vmInstance); + return restoreVMInternal(vmInstance); } } else { throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId + " corresponding to the Instance"); @@ -3449,7 +3411,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("Booting into a hardware setup menu is not implemented on " + vmInstance.getHypervisorType()); } - UserVm userVm = rebootVirtualMachine(CallContext.current().getCallingUserId(), vmId, enterSetup == null ? false : cmd.getBootIntoSetup(), cmd.isForced()); + UserVm userVm = rebootVirtualMachine(vmId, enterSetup != null && cmd.getBootIntoSetup(), cmd.isForced()); if (userVm != null ) { // update the vmIdCountMap if the vm is in advanced shared network with out services final List<NicVO> nics = _nicDao.listByVmId(vmId); @@ -3673,11 +3635,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _groupVMMapDao.expunge(sc); } - if (_vmGroupDao.remove(groupId)) { - return true; - } else { - return false; - } + return _vmGroupDao.remove(groupId); } @Override @@ -3742,9 +3700,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir try { List<InstanceGroupVMMapVO> groupsToVmMap = _groupVMMapDao.listByInstanceId(vmId); - if (groupsToVmMap != null && groupsToVmMap.size() != 0) { - InstanceGroupVO group = _vmGroupDao.findById(groupsToVmMap.get(0).getGroupId()); - return group; + if (groupsToVmMap != null && !groupsToVmMap.isEmpty()) { + return _vmGroupDao.findById(groupsToVmMap.get(0).getGroupId()); } else { return null; } @@ -3769,7 +3726,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private boolean validPassword(String password) { - if (password == null || password.length() == 0) { + if (password == null || password.isEmpty()) { return false; } for (int i = 0; i < password.length(); i++) { @@ -3786,11 +3743,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, List<VmDiskInfo> dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List<String> sshKeyPairs, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParametes, String customId, Map<String, Map<Integer, String>> dhcpOptionMap, - Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, - StorageUnavailableException, ResourceAllocationException { + Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); - List<NetworkVO> networkList = new ArrayList<NetworkVO>(); + List<NetworkVO> networkList = new ArrayList<>(); // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, null, true, owner); @@ -3808,7 +3765,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir networkList.add(_networkDao.findById(defaultNetwork.getId())); } - boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); + boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor == HypervisorType.VMware)); if (securityGroupIdList != null && isVmWare) { throw new InvalidParameterValueException("Security group feature is not supported for VMware hypervisor"); @@ -3816,7 +3773,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir //add the default securityGroup only if no security group is specified if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { if (securityGroupIdList == null) { - securityGroupIdList = new ArrayList<Long>(); + securityGroupIdList = new ArrayList<>(); } SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(owner.getId()); if (defaultGroup != null) { @@ -3845,12 +3802,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir List<Long> securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, List<VmDiskInfo> dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List<String> sshKeyPairs, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParameters, String customId, Map<String, Map<Integer, String>> dhcpOptionMap, - Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { + Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, Map<String, String> userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); - List<NetworkVO> networkList = new ArrayList<NetworkVO>(); + List<NetworkVO> networkList = new ArrayList<>(); boolean isSecurityGroupEnabledNetworkUsed = false; - boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); + boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor == HypervisorType.VMware)); // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, null, true, owner); @@ -3902,7 +3860,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir NetworkVO network = _networkDao.findById(networkId); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); + throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0)); } boolean isSecurityGroupEnabled = _networkModel.isSecurityGroupSupportedInNetwork(network); @@ -3926,7 +3884,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir //add the default securityGroup only if no security group is specified if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { if (securityGroupIdList == null) { - securityGroupIdList = new ArrayList<Long>(); + securityGroupIdList = new ArrayList<>(); } SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(owner.getId()); @@ -3957,11 +3915,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir String hostName, String displayName, Long diskOfferingId, Long diskSize, List<VmDiskInfo> dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List<String> sshKeyPairs, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayvm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParametrs, String customId, Map<String, Map<Integer, String>> dhcpOptionsMap, Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, - Map<String, String> userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, - StorageUnavailableException, ResourceAllocationException { + Map<String, String> userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); - List<NetworkVO> networkList = new ArrayList<NetworkVO>(); + List<NetworkVO> networkList = new ArrayList<>(); // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, null, true, owner); @@ -3982,7 +3940,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (Long networkId : networkIdList) { NetworkVO network = _networkDao.findById(networkId); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); + throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0)); } if (network.getVpcId() != null) { // Only ISOs, XenServer, KVM, and VmWare template types are @@ -4026,34 +3984,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return userVm; } - private NetworkVO getNetworkToAddToNetworkList(VirtualMachineTemplate template, Account owner, HypervisorType hypervisor, - List<HypervisorType> vpcSupportedHTypes, Long networkId) { - NetworkVO network = _networkDao.findById(networkId); - if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + networkId); - } - if (network.getVpcId() != null) { - // Only ISOs, XenServer, KVM, and VmWare template types are - // supported for vpc networks - if (template.getFormat() != ImageFormat.ISO && !vpcSupportedHTypes.contains(template.getHypervisorType())) { - throw new InvalidParameterValueException("Can't create Instance from Template with hypervisor " + template.getHypervisorType() + " in VPC Network " + network); - } else if (template.getFormat() == ImageFormat.ISO && !vpcSupportedHTypes.contains(hypervisor)) { - // Only XenServer, KVM, and VMware hypervisors are supported - // for vpc networks - throw new InvalidParameterValueException("Can't create Instance of hypervisor type " + hypervisor + " in VPC Network"); - } - } - - _networkModel.checkNetworkPermissions(owner, network); - - // don't allow to use system networks - NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); - if (networkOffering.isSystemOnly()) { - throw new InvalidParameterValueException(String.format("Network id=%s is system only and can't be used for vm deployment", network.getUuid())); - } - return network; - } - private NetworkVO getDefaultNetwork(DataCenter zone, Account owner, boolean selectAny) throws InsufficientCapacityException, ResourceAllocationException { NetworkVO defaultNetwork = null; @@ -4066,7 +3996,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // * if network is not found, create a new one and use it List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); - if (requiredOfferings.size() < 1) { + if (requiredOfferings.isEmpty()) { throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation"); } @@ -4142,8 +4072,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Long userDataId, String userDataDetails, List<String> sshKeyPairs, HypervisorType hypervisor, Account caller, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean isDisplayVm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParameters, String customId, Map<String, Map<Integer, String>> dhcpOptionMap, Map<Long, DiskOffering> datadiskTemplateToDiskOfferringMap, - Map<String, String> userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ResourceUnavailableException, - ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { + Map<String, String> userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) + throws ConcurrentOperationException, ResourceAllocationException { _accountMgr.checkAccess(caller, null, true, owner); @@ -4155,19 +4085,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _templateDao.loadDetails(template); } - HypervisorType hypervisorType = null; - if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) { - if (hypervisor == null || hypervisor == HypervisorType.None) { - throw new InvalidParameterValueException("Hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid"); - } - hypervisorType = hypervisor; - } else { - if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) { - throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the Template"); - } - hypervisorType = template.getHypervisorType(); - } - + HypervisorType hypervisorType = getHypervisorTypeFromHypervisorAndTemplate(hypervisor, template); long accountId = owner.getId(); assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be specified together"; @@ -4201,7 +4119,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir validateOfferingMaxResource(offering); } // check if account/domain is with in resource limits to create a new vm - boolean isIso = Storage.ImageFormat.ISO == template.getFormat(); + boolean isIso = (template != null && Storage.ImageFormat.ISO == template.getFormat()); Long rootDiskOfferingId = offering.getDiskOfferingId(); if (isIso) { @@ -4241,6 +4159,25 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return vm; } + @Nullable + private static HypervisorType getHypervisorTypeFromHypervisorAndTemplate(HypervisorType hypervisor, VMTemplateVO template) { + HypervisorType hypervisorType = null; + if (template != null) { + if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) { + if (hypervisor == null || hypervisor == HypervisorType.None) { + throw new InvalidParameterValueException("Hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid"); + } + hypervisorType = hypervisor; + } else { + if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) { + throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the Template"); + } + hypervisorType = template.getHypervisorType(); + } + } + return hypervisorType; + } + private UserVm getCheckedUserVmResource(DataCenter zone, String hostName, String displayName, Account owner, Long diskOfferingId, Long diskSize, List<VmDiskInfo> dataDiskInfoList, List<NetworkVO> networkList, List<Long> securityGroupIdList, String group, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List<String> sshKeyPairs, @@ -4252,11 +4189,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Long rootDiskOfferingId, long volumesSize, Volume volume, Snapshot snapshot) throws ResourceAllocationException { if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) { List<String> resourceLimitHostTags = resourceLimitService.getResourceLimitHostTags(offering, template); - try (CheckedReservation vmReservation = new CheckedReservation(owner, ResourceType.user_vm, resourceLimitHostTags, 1l, reservationDao, resourceLimitService); + try (CheckedReservation vmReservation = new CheckedReservation(owner, ResourceType.user_vm, resourceLimitHostTags, 1L, reservationDao, resourceLimitService); CheckedReservation cpuReservation = new CheckedReservation(owner, ResourceType.cpu, resourceLimitHostTags, Long.valueOf(offering.getCpu()), reservationDao, resourceLimitService); CheckedReservation memReservation = new CheckedReservation(owner, ResourceType.memory, resourceLimitHostTags, Long.valueOf(offering.getRamSize()), reservationDao, resourceLimitService); - CheckedReservation gpuReservation = offering.getGpuCount() != null && offering.getGpuCount() > 0 ? - new CheckedReservation(owner, ResourceType.gpu, resourceLimitHostTags, Long.valueOf(offering.getGpuCount()), reservationDao, resourceLimitService) : null; + CheckedReservation gpuReservation = (offering.getGpuCount() != null && offering.getGpuCount() > 0) ? + new CheckedReservation(owner, ResourceType.gpu, resourceLimitHostTags, Long.valueOf(offering.getGpuCount()), reservationDao, resourceLimitService) : null ) { return getUncheckedUserVmResource(zone, hostName, displayName, owner, diskOfferingId, diskSize, dataDiskInfoList, networkList, securityGroupIdList, group, httpmethod, userData, userDataId, userDataDetails, sshKeyPairs, caller, requestedIps, defaultIps, isDisplayVm, keyboard, affinityGroupIdList, customParameters, customId, dhcpOptionMap, datadiskTemplateToDiskOfferringMap, userVmOVFPropertiesMap, dynamicScalingEnabled, vmType, template, hypervisorType, accountId, offering [...] } catch (ResourceAllocationException | CloudRuntimeException e) { @@ -4286,12 +4223,12 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir checkedReservations.add(rootPrimaryStorageReservation); if (diskOfferingId != null) { - List<String> additionalResourceLimitStorageTags = diskOfferingId != null ? getResourceLimitStorageTags(diskOfferingId) : null; + List<String> additionalResourceLimitStorageTags = getResourceLimitStorageTags(diskOfferingId); DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); Long size = verifyAndGetDiskSize(diskOffering, diskSize); - CheckedReservation additionalVolumeReservation = diskOfferingId != null ? new CheckedReservation(owner, ResourceType.volume, additionalResourceLimitStorageTags, 1L, reservationDao, resourceLimitService) : null; + CheckedReservation additionalVolumeReservation = new CheckedReservation(owner, ResourceType.volume, additionalResourceLimitStorageTags, 1L, reservationDao, resourceLimitService); checkedReservations.add(additionalVolumeReservation); - CheckedReservation additionalPrimaryStorageReservation = diskOfferingId != null ? new CheckedReservation(owner, ResourceType.primary_storage, additionalResourceLimitStorageTags, size, reservationDao, resourceLimitService) : null; + CheckedReservation additionalPrimaryStorageReservation = new CheckedReservation(owner, ResourceType.primary_storage, additionalResourceLimitStorageTags, size, reservationDao, resourceLimitService); checkedReservations.add(additionalPrimaryStorageReservation); } @@ -4346,7 +4283,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir || (!dataDiskTemplate.getTemplateType().equals(TemplateType.DATADISK)) && (dataDiskTemplate.getState().equals(VirtualMachineTemplate.State.Active))) { throw new InvalidParameterValueException("Invalid Template ID specified for Datadisk Template" + datadiskTemplateToDiskOffering.getKey()); } - long dataDiskTemplateId = datadiskTemplateToDiskOffering.getKey(); if (!dataDiskTemplate.getParentTemplateId().equals(template.getId())) { throw new InvalidParameterValueException(String.format("Invalid Datadisk Template. Specified Datadisk Template %s doesn't belong to Template %s", dataDiskTemplate, template)); } @@ -4448,7 +4384,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new InvalidParameterValueException("Not all specified keypairs exist"); } - sshPublicKeys = pairs.stream().map(p -> p.getPublicKey()).collect(Collectors.joining("\n")); + sshPublicKeys = pairs.stream().map(SSHKeyPairVO::getPublicKey).collect(Collectors.joining("\n")); keypairnames = String.join(",", sshKeyPairs); } @@ -4464,7 +4400,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType()); + long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType()); String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity); if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) { @@ -4499,12 +4435,12 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } profile.setDefaultNic(true); - if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[]{Service.UserData})) { + if (!_networkModel.areServicesSupportedInNetwork(network.getId(), Service.UserData)) { if ((userData != null) && (!userData.isEmpty())) { throw new InvalidParameterValueException(String.format("Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for %s service in the default network %s/%s.", Service.UserData.getName(), network.getName(), network.getUuid())); } - if ((sshPublicKeys != null) && (!sshPublicKeys.isEmpty())) { + if (!sshPublicKeys.isEmpty()) { throw new InvalidParameterValueException(String.format("Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for %s service in the default network %s/%s", Service.UserData.getName(), network.getName(), network.getUuid())); } @@ -4537,8 +4473,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // gateway for the vm if (defaultNetworkNumber == 0) { throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm"); - } else if (defaultNetworkNumber > 1) { - throw new InvalidParameterValueException("Only 1 default network per vm is supported"); } long id = _vmDao.getNextInSequence(Long.class, "id"); @@ -4575,10 +4509,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } } - if (hostName != null) { - // Check is hostName is RFC compliant - checkNameForRFCCompliance(hostName); - } + // Check is hostName is RFC compliant + checkNameForRFCCompliance(hostName); + instanceName = VirtualMachineName.getVmName(id, owner.getId(), instanceSuffix); if (_instanceNameFlag && HypervisorType.VMware.equals(hypervisorType) && !instanceSuffix.equals(_instance)) { customParameters.put(VmDetailConstants.NAME_ON_HYPERVISOR, instanceName); @@ -4602,7 +4535,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir dynamicScalingEnabled = dynamicScalingEnabled && checkIfDynamicScalingCanBeEnabled(null, offering, template, zone.getId()); - UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, userDataId, userDataDetails, caller, isDisplayVm, keyboard, accountId, userId, offering, + UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, userDataId, userDataDetails, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKeys, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters, dhcpOptionMap, datadiskTemplateToDiskOfferringMap, userVmOVFPropertiesMap, dynamicScalingEnabled, vmType, rootDiskOfferingId, keypairnames, dataDiskInfoList, volume, snapshot); @@ -4614,13 +4547,17 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir logger.error("error during resource reservation and allocation", e); throw new CloudRuntimeException(e); } finally { - for (CheckedReservation checkedReservation : checkedReservations) { - try { - checkedReservation.close(); - } catch (Exception e) { - logger.error("error during resource reservation and allocation", e); - throw new CloudRuntimeException(e); - } + closeCheckeReservation(checkedReservations); + } + } + + private void closeCheckeReservation(List<CheckedReservation> checkedReservations) { + for (CheckedReservation checkedReservation : checkedReservations) { + try { + checkedReservation.close(); + } catch (Exception e) { + logger.error("error during resource reservation and allocation", e); + throw new CloudRuntimeException(e); } } } @@ -4629,7 +4566,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Assign instance to the group try { if (group != null) { - boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group); + boolean addToGroup = addInstanceToGroup(id, group); if (!addToGroup) { throw new CloudRuntimeException("Unable to assign Vm to the group " + group); } @@ -4640,7 +4577,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private long verifyAndGetDiskSize(DiskOffering diskOffering, Long diskSize) { - long size = 0l; + long size = 0L; if (diskOffering == null) { throw new InvalidParameterValueException("Specified disk offering cannot be found"); } @@ -4659,7 +4596,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override public boolean checkIfDynamicScalingCanBeEnabled(VirtualMachine vm, ServiceOffering offering, VirtualMachineTemplate template, Long zoneId) { - boolean canEnableDynamicScaling = (vm != null ? vm.isDynamicallyScalable() : true) && offering.isDynamicScalingEnabled() && template.isDynamicallyScalable() && UserVmManager.EnableDynamicallyScaleVm.valueIn(zoneId); + boolean canEnableDynamicScaling = (vm == null || vm.isDynamicallyScalable()) && offering.isDynamicScalingEnabled() && template.isDynamicallyScalable() && UserVmManager.EnableDynamicallyScaleVm.valueIn(zoneId); if (!canEnableDynamicScaling) { logger.info("VM cannot be configured to be dynamically scalable if any of the service offering's dynamic scaling property, template's dynamic scaling property or global setting is false"); } @@ -4689,11 +4626,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } if (customParameters.containsKey(VmDetailConstants.ROOT_DISK_SIZE)) { - Long rootDiskSize = NumbersUtil.parseLong(customParameters.get(VmDetailConstants.ROOT_DISK_SIZE), -1); + long rootDiskSize = NumbersUtil.parseLong(customParameters.get(VmDetailConstants.ROOT_DISK_SIZE), -1); if (rootDiskSize <= 0) { throw new InvalidParameterValueException("Root disk size should be a positive number."); } - rootDiskSize = rootDiskSizeCustomParam * GiB_TO_BYTES; + rootDiskSize = (rootDiskSizeCustomParam == null ? 0 : rootDiskSizeCustomParam) * GiB_TO_BYTES; _volumeService.validateVolumeSizeInBytes(rootDiskSize); return rootDiskSize; } else { @@ -4858,11 +4795,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters); } - if (isDisplayVm != null) { - vm.setDisplayVm(isDisplayVm); - } else { - vm.setDisplayVm(true); - } + vm.setDisplayVm(isDisplayVm == null || isDisplayVm); setVmRequiredFieldsForImport(isImport, vm, zone, hypervisorType, host, lastHost, powerState); @@ -4916,10 +4849,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir logger.debug("Allocating in the DB for vm"); DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); - List<String> computeTags = new ArrayList<String>(); + List<String> computeTags = new ArrayList<>(); computeTags.add(offering.getHostTag()); - List<String> rootDiskTags = new ArrayList<String>(); + List<String> rootDiskTags = new ArrayList<>(); DiskOfferingVO rootDiskOfferingVO = _diskOfferingDao.findById(rootDiskOfferingId); rootDiskTags.add(rootDiskOfferingVO.getTags()); @@ -4944,7 +4877,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir resourceCountIncrement(accountId, isDisplayVm, offering, template); } catch (CloudRuntimeException cre) { ArrayList<ExceptionProxyObject> epoList = cre.getIdProxyList(); - if (epoList == null || !epoList.stream().anyMatch( e -> e.getUuid().equals(vm.getUuid()))) { + if (epoList == null || epoList.stream().noneMatch(e -> e.getUuid().equals(vm.getUuid()))) { cre.addProxyObject(vm.getUuid(), ApiConstants.VIRTUAL_MACHINE_ID); } throw cre; @@ -4975,14 +4908,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } } catch (CloudRuntimeException cre) { ArrayList<ExceptionProxyObject> epoList = cre.getIdProxyList(); - if (epoList == null || !epoList.stream().anyMatch(e -> e.getUuid().equals(vm.getUuid()))) { + if (epoList == null || epoList.stream().noneMatch(e -> e.getUuid().equals(vm.getUuid()))) { cre.addProxyObject(vm.getUuid(), ApiConstants.VIRTUAL_MACHINE_ID); } throw cre; } catch (InsufficientCapacityException ice) { - ArrayList idList = ice.getIdProxyList(); - if (idList == null || !idList.stream().anyMatch(i -> i.equals(vm.getUuid()))) { + ArrayList<String> idList = ice.getIdProxyList(); + if (idList == null || idList.stream().noneMatch(i -> i.equals(vm.getUuid()))) { ice.addProxyObject(vm.getUuid()); } throw ice; @@ -5057,7 +4990,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir private void persistVMDeployAsIsProperties(UserVmVO vm, Map<String, String> userVmOVFPropertiesMap) { if (MapUtils.isNotEmpty(userVmOVFPropertiesMap)) { for (String key : userVmOVFPropertiesMap.keySet()) { - String detailKey = key; String value = userVmOVFPropertiesMap.get(key); // Sanitize boolean values to expected format and encrypt passwords @@ -5076,16 +5008,16 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir value = ""; } if (logger.isTraceEnabled()) { - logger.trace(String.format("setting property '%s' as '%s' with value '%s'", key, detailKey, value)); + logger.trace(String.format("setting property '%s' as '%s' with value '%s'", key, key, value)); } - UserVmDeployAsIsDetailVO detail = new UserVmDeployAsIsDetailVO(vm.getId(), detailKey, value); + UserVmDeployAsIsDetailVO detail = new UserVmDeployAsIsDetailVO(vm.getId(), key, value); userVmDeployAsIsDetailsDao.persist(detail); } } } private UserVmVO commitUserVm(final DataCenter zone, final VirtualMachineTemplate template, final String hostName, final String displayName, final Account owner, - final Long diskOfferingId, final Long diskSize, final String userData, Long userDataId, String userDataDetails, final Account caller, final Boolean isDisplayVm, final String keyboard, + final Long diskOfferingId, final Long diskSize, final String userData, Long userDataId, String userDataDetails, final Boolean isDisplayVm, final String keyboard, final long accountId, final long userId, final ServiceOfferingVO offering, final boolean isIso, final String sshPublicKeys, final LinkedHashMap<String, List<NicProfile>> networkNicMap, final long id, final String instanceName, final String uuidName, final HypervisorType hypervisorType, final Map<String, String> customParameters, final Map<String, Map<Integer, String>> extraDhcpOptionMap, final Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap, @@ -5133,7 +5065,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir VirtualMachine.class.getName(), vm.getUuid(), isDisplay); } else { - Map<String, String> customParameters = new HashMap<String, String>(); + Map<String, String> customParameters = new HashMap<>(); customParameters.put(UsageEventVO.DynamicParameters.cpuNumber.name(), serviceOffering.getCpu().toString()); customParameters.put(UsageEventVO.DynamicParameters.cpuSpeed.name(), serviceOffering.getSpeed().toString()); customParameters.put(UsageEventVO.DynamicParameters.memory.name(), serviceOffering.getRamSize().toString()); @@ -5150,7 +5082,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } logger.debug("Collect vm network statistics from host before stopping Vm"); long hostId = userVm.getHostId(); - List<String> vmNames = new ArrayList<String>(); + List<String> vmNames = new ArrayList<>(); vmNames.add(userVm.getInstanceName()); final HostVO host = _hostDao.findById(hostId); Account account = _accountMgr.getAccount(userVm.getAccountId()); @@ -5186,7 +5118,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir sc_nic.addAnd("macAddress", SearchCriteria.Op.EQ, vmNetworkStat.getMacAddress()); NicVO nic = _nicDao.search(sc_nic, null).get(0); List<VlanVO> vlan = _vlanDao.listVlansByNetworkId(nic.getNetworkId()); - if (vlan == null || vlan.size() == 0 || vlan.get(0).getVlanType() != VlanType.DirectAttached) + if (vlan == null || vlan.isEmpty() || vlan.get(0).getVlanType() != VlanType.DirectAttached) { break; // only get network statistics for DirectAttached network (shared networks in Basic zone and Advanced zone with/without SG) } @@ -5207,9 +5139,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir continue; } - if (previousvmNetworkStats != null - && ((previousvmNetworkStats.getCurrentBytesSent() != vmNetworkStat_lock.getCurrentBytesSent()) - || (previousvmNetworkStats.getCurrentBytesReceived() != vmNetworkStat_lock.getCurrentBytesReceived()))) { + if ((previousvmNetworkStats.getCurrentBytesSent() != vmNetworkStat_lock.getCurrentBytesSent()) + || (previousvmNetworkStats.getCurrentBytesReceived() != vmNetworkStat_lock.getCurrentBytesReceived())) { logger.debug("vm network stats changed from the time GetNmNetworkStatsCommand was sent. " + "Ignoring current answer. Host: " + host + " . VM: " + vmNetworkStat.getVmName() + " Sent(Bytes): " + toHumanReadableSize(vmNetworkStat.getBytesSent()) + " Received(Bytes): " + toHumanReadableSize(vmNetworkStat.getBytesReceived())); @@ -5367,7 +5298,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (dc.getDns2() != null) { buf.append(" dns2=").append(dc.getDns2()); } - logger.info("cmdline details: "+ buf.toString()); + logger.info("cmdline details: "+ buf); } @Override @@ -5428,11 +5359,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return false; } - boolean result = true; - if (answer == null || !answer.getResult()) { - result = false; - } - return result; + return answer != null && answer.getResult(); } @Override @@ -5484,14 +5411,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } return true; } - Answer startAnswer = cmds.getAnswer(StartAnswer.class); + StartAnswer startAnswer = cmds.getAnswer(StartAnswer.class); String returnedIp = null; String originalIp = null; String originalVncPassword = profile.getVirtualMachine().getVncPassword(); String returnedVncPassword = null; if (startAnswer != null) { - StartAnswer startAns = (StartAnswer)startAnswer; - VirtualMachineTO vmTO = startAns.getVirtualMachine(); + VirtualMachineTO vmTO = startAnswer.getVirtualMachine(); for (NicTO nicTO : vmTO.getNics()) { if (nicTO.getType() == TrafficType.Guest) { returnedIp = nicTO.getIp(); @@ -5560,9 +5486,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } Answer answer = cmds.getAnswer("restoreVMSnapshot"); - if (answer != null && answer instanceof RestoreVMSnapshotAnswer) { + if (answer instanceof RestoreVMSnapshotAnswer) { RestoreVMSnapshotAnswer restoreVMSnapshotAnswer = (RestoreVMSnapshotAnswer) answer; - if (restoreVMSnapshotAnswer == null || !restoreVMSnapshotAnswer.getResult()) { + if (!restoreVMSnapshotAnswer.getResult()) { logger.warn("Unable to restore the Instance Snapshot from image file to the Instance: " + restoreVMSnapshotAnswer.getDetails()); } } @@ -5598,7 +5524,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private void checkForceStopVmPermission(Account callingAccount) { - if (!AllowUserForceStopVm.valueIn(callingAccount.getId())) { + if (callingAccount == null || !AllowUserForceStopVm.valueIn(callingAccount.getId())) { logger.error("Parameter [{}] can only be passed by Admin accounts or when the allow.user.force.stop.vm config is true for the account.", ApiConstants.FORCED); throw new PermissionDeniedException("Account does not have the permission to force stop the vm."); } @@ -5609,7 +5535,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException { // Input validation Account caller = CallContext.current().getCallingAccount(); - Long userId = CallContext.current().getCallingUserId(); + long userId = CallContext.current().getCallingUserId(); // if account is removed, return error if (caller != null && caller.getRemoved() != null) { @@ -5642,8 +5568,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } else { return null; } - } catch (ResourceUnavailableException e) { - throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e); } catch (CloudException e) { throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e); } @@ -5660,7 +5584,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir long networkId = ip.getAssociatedWithNetworkId(); Network guestNetwork = _networkDao.findById(networkId); NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId()); - assert (offering.isAssociatePublicIP() == true) : "User VM should not have system owned public IP associated with it when offering configured not to associate public IP."; + assert (offering.isAssociatePublicIP()) : "User VM should not have system owned public IP associated with it when offering configured not to associate public IP."; _rulesMgr.disableStaticNat(ip.getId(), ctx.getCallingAccount(), ctx.getCallingUserId(), true); } catch (Exception ex) { logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); @@ -5742,7 +5666,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir SecurityGroup defaultSecurityGroup = _securityGroupMgr.getDefaultSecurityGroup(vm.getAccountId()); if (defaultSecurityGroup != null) { - List<Long> groupList = new ArrayList<Long>(); + List<Long> groupList = new ArrayList<>(); groupList.add(defaultSecurityGroup.getId()); _securityGroupMgr.addInstanceToGroups(vm, groupList); } @@ -5773,7 +5697,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir logger.info(errorMsg); if (!AllowDeployVmIfGivenHostFails.value()) { throw new InvalidParameterValueException(errorMsg); - }; + } } else { plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null); if (!AllowDeployVmIfGivenHostFails.value()) { @@ -5795,8 +5719,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Set parameters - Map<VirtualMachineProfile.Param, Object> params = new HashMap<>(); - params.putAll(additionalParams); + Map<VirtualMachineProfile.Param, Object> params = new HashMap<>(additionalParams); if (vm.isUpdateParameters()) { _vmDao.loadDetails(vm); @@ -5841,8 +5764,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId())); vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params, deployOnGivenHost); - Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params); - if (vm != null && vm.isUpdateParameters()) { + Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair<>(vm, params); + if (vm.isUpdateParameters()) { // this value is not being sent to the backend; need only for api // display purposes if (template.isEnablePassword()) { @@ -5958,8 +5881,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Verify input parameters UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getRemoved() != null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId"); - throw ex; + throw new InvalidParameterValueException("Unable to find a virtual machine with specified vmId"); } if (vm.getState() == State.Destroyed || vm.getState() == State.Expunging) { @@ -5980,7 +5902,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir CheckedReservation cpuReservation = new CheckedReservation(owner, ResourceType.cpu, vmId, null, -1 * Long.valueOf(offering.getCpu()), reservationDao, resourceLimitService); CheckedReservation memReservation = new CheckedReservation(owner, ResourceType.memory, vmId, null, -1 * Long.valueOf(offering.getRamSize()), reservationDao, resourceLimitService); CheckedReservation gpuReservation = offering.getGpuCount() != null && offering.getGpuCount() > 0 ? - new CheckedReservation(owner, ResourceType.gpu, vmId, null, -1 * Long.valueOf(offering.getGpuCount()), reservationDao, resourceLimitService) : null; + new CheckedReservation(owner, ResourceType.gpu, vmId, null, -1 * Long.valueOf(offering.getGpuCount()), reservationDao, resourceLimitService) : null ) { try { VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid()); @@ -6031,7 +5953,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return; } long hostId = userVm.getHostId(); - List<String> vmNames = new ArrayList<String>(); + List<String> vmNames = new ArrayList<>(); vmNames.add(userVm.getInstanceName()); final HostVO host = _hostDao.findById(hostId); Account account = _accountMgr.getAccount(userVm.getAccountId()); @@ -6066,7 +5988,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir SearchCriteria<VolumeVO> sc_volume = _volsDao.createSearchCriteria(); sc_volume.addAnd("path", SearchCriteria.Op.LIKE, vmDiskStat.getPath() + "%"); List<VolumeVO> volumes = _volsDao.search(sc_volume, null); - if ((volumes == null) || (volumes.size() == 0)) { + if ((volumes == null) || (volumes.isEmpty())) { break; } VolumeVO volume = volumes.get(0); @@ -6324,8 +6246,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } @Override - public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, - StorageUnavailableException, ResourceAllocationException { + public UserVm createVirtualMachine(DeployVMCmd cmd) + throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, ResourceAllocationException { //Verify that all objects exist before passing them to the service Account owner = _accountService.getActiveAccountById(cmd.getEntityOwnerId()); @@ -6346,12 +6268,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOffering.getId()); + throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); } verifyServiceOffering(cmd, serviceOffering); Account caller = CallContext.current().getCallingAccount(); - Long callerId = caller.getId(); Long templateId = cmd.getTemplateId(); VolumeInfo volume = null; @@ -6404,7 +6325,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir List<VmDiskInfo> dataDiskInfoList = cmd.getDataDiskInfoList(); if (dataDiskInfoList != null && diskOfferingId != null) { - new InvalidParameterValueException("Cannot specify both disk offering id and data disk offering details"); + throw new InvalidParameterValueException("Cannot specify both disk offering id and data disk offering details"); } if (!zone.isLocalStorageEnabled()) { @@ -6439,7 +6360,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir String userData = null; Long userDataId = null; String userDataDetails = null; - List<String> sshKeyPairNames = new ArrayList<String>(); + List<String> sshKeyPairNames = new ArrayList<>(); if (cmd instanceof CreateVMFromBackupCmd) { if (cmd.getUserData() != null) { throw new InvalidParameterValueException("User data not supported for instance created from backup"); @@ -6447,7 +6368,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } else { userData = cmd.getUserData(); userDataId = cmd.getUserdataId(); - userDataDetails = null; if (MapUtils.isNotEmpty(cmd.getUserdataDetails())) { userDataDetails = cmd.getUserdataDetails().toString(); } @@ -6566,10 +6486,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * if lease feature is enabled * use leaseDuration and leaseExpiryAction passed in the cmd * get leaseDuration from service_offering if leaseDuration is not passed - * @param vm - * @param leaseDuration - * @param leaseExpiryAction - * @param serviceOfferingJoinVO */ void applyLeaseOnCreateInstance(UserVm vm, Integer leaseDuration, VMLeaseManager.ExpiryAction leaseExpiryAction, ServiceOfferingJoinVO serviceOfferingJoinVO) { if (leaseDuration == null) { @@ -6717,7 +6633,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir String[] allowedKeyList = XenServerAdditionalConfigAllowList.value().split(","); boolean validXenOrVmwareConfiguration = isValidXenOrVmwareConfiguration(cfg, allowedKeyList); if (validXenOrVmwareConfiguration) { - vmInstanceDetailsDao.addDetail(vm.getId(), extraConfigKey + String.valueOf(i), cfg, true); + vmInstanceDetailsDao.addDetail(vm.getId(), extraConfigKey + i, cfg, true); i++; } else { throw new CloudRuntimeException("Extra config " + cfg + " is not on the list of allowed keys for XenServer hypervisor hosts."); @@ -6798,7 +6714,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir extraConfigKey += "-" + cfgParts[0].substring(0, cfgParts[0].length() - 1); extraConfigValue = cfg.replace(cfgParts[0] + "\n", ""); } else { - extraConfigKey += "-" + String.valueOf(i); + extraConfigKey += "-" + i; extraConfigValue = cfg; } vmInstanceDetailsDao.addDetail(vm.getId(), extraConfigKey, extraConfigValue, true); @@ -6842,6 +6758,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (String tag : allowedConfigOptionList) { if (currentConfig.equals(tag.trim())) { isValidConfig = true; + break; } } if (!isValidConfig) { @@ -6869,7 +6786,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } else if (hypervisorType.equals(HypervisorType.VMware)) { persistExtraConfigVmware(decodedUrl, vm); } else { - String msg = String.format("This hypervisor %s is not supported for use with this feature", hypervisorType.toString()); + String msg = String.format("This hypervisor %s is not supported for use with this feature", hypervisorType); throw new CloudRuntimeException(msg); } } @@ -6880,13 +6797,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * @return String result of decoded URL */ protected String decodeExtraConfig(String encodeString) { - String decodedUrl; - try { - decodedUrl = URLDecoder.decode(encodeString, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new CloudRuntimeException("Failed to provided decode URL string: " + e.getMessage()); - } - return decodedUrl; + return URLDecoder.decode(encodeString, StringUtils.getPreferredCharset()); } protected List<Long> getSecurityGroupIdList(SecurityGroupAction cmd) { @@ -6896,7 +6807,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir //transform group names to ids here if (cmd.getSecurityGroupNameList() != null) { - List<Long> securityGroupIds = new ArrayList<Long>(); + List<Long> securityGroupIds = new ArrayList<>(); for (String groupName : cmd.getSecurityGroupNameList()) { SecurityGroup sg = _securityGroupMgr.getSecurityGroup(groupName, cmd.getEntityOwnerId()); if (sg == null) { @@ -7037,7 +6948,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // Check that Vm does not have VM Snapshots - if (_vmSnapshotDao.findByVm(vmId).size() > 0) { + if (!_vmSnapshotDao.findByVm(vmId).isEmpty()) { throw new InvalidParameterValueException("Instance's disk cannot be migrated, please remove all the Instance Snapshots for this Instance"); } @@ -7215,7 +7126,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir vm.setLastHostId(null); // Last host does not have higher priority in vm migration final ServiceOfferingVO offering = serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId()); final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, null, offering, null, null); - final Long srcHostId = srcHost.getId(); + final long srcHostId = srcHost.getId(); final Host host = _hostDao.findById(srcHostId); ExcludeList excludes = new ExcludeList(); excludes.addHost(srcHostId); @@ -7256,7 +7167,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new CloudRuntimeException("Source host has storage access groups, but destination host has none."); } - if (!destHostStorageAccessGroupsList.containsAll(srcHostStorageAccessGroupsList)) { + if (!new HashSet<>(destHostStorageAccessGroupsList).containsAll(srcHostStorageAccessGroupsList)) { throw new CloudRuntimeException("Storage access groups on the source and destination hosts did not match."); } } @@ -7322,7 +7233,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new VirtualMachineMigrationException(String.format("Destination host: %s already has max Running VMs(count includes system VMs), cannot migrate to this host", destinationHost)); } //check if there are any ongoing volume snapshots on the volumes associated with the VM. - Long vmId = vm.getId(); logger.debug("Checking if there are any ongoing snapshots volumes associated with VM {}", vm); if (checkStatusOfVolumeSnapshots(vm, null)) { throw new CloudRuntimeException("There is/are unbacked up snapshot(s) on volume(s) attached to this VM, VM Migration is not permitted, please try again later."); @@ -7348,11 +7258,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir DedicatedResourceVO dedicatedHost = _dedicatedDao.findByHostId(hostId); DedicatedResourceVO dedicatedClusterOfHost = _dedicatedDao.findByClusterId(host.getClusterId()); DedicatedResourceVO dedicatedPodOfHost = _dedicatedDao.findByPodId(host.getPodId()); - if (dedicatedHost != null || dedicatedClusterOfHost != null || dedicatedPodOfHost != null) { - return true; - } else { - return false; - } + return dedicatedHost != null || dedicatedClusterOfHost != null || dedicatedPodOfHost != null; } private void checkIfHostOfVMIsInPrepareForMaintenanceState(VirtualMachine vm, String operation) { @@ -7422,13 +7328,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir //if hosts are dedicated to different account/domains, raise an alert if (srcExplDedicated && destExplDedicated) { - if (!((accountOfDedicatedHost(srcHost) == null) || (accountOfDedicatedHost(srcHost).equals(accountOfDedicatedHost(destHost))))) { + if (!((accountOfDedicatedHost(srcHost) == null) || (Objects.equals(accountOfDedicatedHost(srcHost), accountOfDedicatedHost(destHost))))) { String msg = String.format("VM is being migrated from host %s explicitly dedicated to account %d to host %s explicitly dedicated to account %d", srcHost, accountOfDedicatedHost(srcHost), destHost, accountOfDedicatedHost(destHost)); _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_USERVM, vm.getDataCenterId(), vm.getPodIdToDeployIn(), msg, msg); logger.warn(msg); } - if (!((domainOfDedicatedHost(srcHost) == null) || (domainOfDedicatedHost(srcHost).equals(domainOfDedicatedHost(destHost))))) { + if (!((domainOfDedicatedHost(srcHost) == null) || (Objects.equals(domainOfDedicatedHost(srcHost), domainOfDedicatedHost(destHost))))) { String msg = String.format("VM is being migrated from host %s explicitly dedicated to domain %d to host %s explicitly dedicated to domain %d", srcHost, domainOfDedicatedHost(srcHost), destHost, domainOfDedicatedHost(destHost)); _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_USERVM, vm.getDataCenterId(), vm.getPodIdToDeployIn(), msg, msg); @@ -7505,7 +7411,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir private List<VMInstanceVO> getVmsOnHost(long hostId) { List<VMInstanceVO> vms = _vmInstanceDao.listUpByHostId(hostId); List<VMInstanceVO> vmsByLastHostId = _vmInstanceDao.listByLastHostId(hostId); - if (vmsByLastHostId.size() > 0) { + if (!vmsByLastHostId.isEmpty()) { // check if any VMs are within skip.counting.hours, if yes we have to consider the host. for (VMInstanceVO stoppedVM : vmsByLastHostId) { long secondsSinceLastUpdate = (DateUtil.currentGMTTime().getTime() - stoppedVM.getUpdateTime().getTime()) / 1000; @@ -7681,7 +7587,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private Map<Long, Long> getVolumePoolMappingForMigrateVmWithStorage(VMInstanceVO vm, Map<String, String> volumeToPool) { - Map<Long, Long> volToPoolObjectMap = new HashMap<Long, Long>(); + Map<Long, Long> volToPoolObjectMap = new HashMap<>(); List<VolumeVO> vmVolumes = getVmVolumesForMigrateVmWithStorage(vm); @@ -7722,7 +7628,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir DiskOffering diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DiskProfile diskProfile = new DiskProfile(volume, diskOffering, _volsDao.getHypervisorType(volume.getId())); Pair<Volume, DiskProfile> volumeDiskProfilePair = new Pair<>(volume, diskProfile); - boolean isStoragePoolStoragepolicyCompliance = storageManager.isStoragePoolCompliantWithStoragePolicy(Arrays.asList(volumeDiskProfilePair), pool); + boolean isStoragePoolStoragepolicyCompliance = storageManager.isStoragePoolCompliantWithStoragePolicy(List.of(volumeDiskProfilePair), pool); if (!isStoragePoolStoragepolicyCompliance) { throw new CloudRuntimeException(String.format("Storage pool %s is not storage policy compliance with the volume %s", pool.getUuid(), volume.getUuid())); } @@ -7877,7 +7783,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Long domainId = cmd.getDomainId(); Long projectId = cmd.getProjectId(); - Long oldAccountId = vm.getAccountId(); + long oldAccountId = vm.getAccountId(); String newAccountName = cmd.getAccountName(); final Account oldAccount = _accountService.getActiveAccountById(oldAccountId); final Account newAccount = _accountMgr.finalizeOwner(caller, newAccountName, domainId, projectId); @@ -7911,7 +7817,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - executeStepsToChangeOwnershipOfVm(cmd, caller, oldAccount, newAccount, vm, offering, volumes, template, domainId); + executeStepsToChangeOwnershipOfVm(cmd, oldAccount, newAccount, vm, offering, volumes, template, domainId); } }); } catch (Exception e) { @@ -8094,11 +8000,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * removing the VM from its instance group ({@link #removeInstanceFromInstanceGroup(long)}), * updating the VM owner to the new account ({@link #updateVmOwner(Account, UserVmVO, Long, Long)}), * updating the volumes to the new account ({@link #updateVolumesOwner(List, Account, Account, Long)}), - * updating the network for the VM ({@link #updateVmNetwork(AssignVMCmd, Account, UserVmVO, Account, VirtualMachineTemplate)}), + * updating the network for the VM ({@link #updateVmNetwork(AssignVMCmd, UserVmVO, Account, VirtualMachineTemplate)}), * incrementing the new user resource count ({@link #resourceCountIncrement(long, Boolean, ServiceOffering, VirtualMachineTemplate)}), * and generating a create VM event ({@link EventTypes}). * @param cmd The assignVMCmd. - * @param caller The account calling the assignVMCmd. * @param oldAccount The old account from whom the VM will be moved. * @param newAccount The new account to whom the VM will move. * @param vm The VM to be moved between accounts. @@ -8107,7 +8012,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * @param template The template of the VM which will be assigned to another user. * @param domainId The ID of the domain where the VM which will be assigned to another user is. */ - protected void executeStepsToChangeOwnershipOfVm(AssignVMCmd cmd, Account caller, Account oldAccount, Account newAccount, UserVmVO vm, ServiceOfferingVO offering, + protected void executeStepsToChangeOwnershipOfVm(AssignVMCmd cmd, Account oldAccount, Account newAccount, UserVmVO vm, ServiceOfferingVO offering, List<VolumeVO> volumes, VirtualMachineTemplate template, Long domainId) { logger.trace("Generating destroy event for VM [{}].", vm); @@ -8129,7 +8034,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir updateBackupScheduleOwnership(vm, newAccount); try { - updateVmNetwork(cmd, caller, vm, newAccount, template); + updateVmNetwork(cmd, vm, newAccount, template); } catch (InsufficientCapacityException | ResourceAllocationException e) { throw new CloudRuntimeException(String.format("Unable to update networks when assigning VM [%s] due to [%s].", vm, e.getMessage()), e); } @@ -8185,16 +8090,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * If the network type for the zone is basic, calls * {@link #updateBasicTypeNetworkForVm(UserVmVO, Account, VirtualMachineTemplate, VirtualMachineProfileImpl, DataCenterVO, List, List)}. * If the network type for the zone is advanced, calls - * {@link #updateAdvancedTypeNetworkForVm(Account, UserVmVO, Account, VirtualMachineTemplate, VirtualMachineProfileImpl, DataCenterVO, List, List)}. + * {@link #updateAdvancedTypeNetworkForVm(UserVmVO, Account, VirtualMachineTemplate, VirtualMachineProfileImpl, DataCenterVO, List, List)}. * @param cmd The assignVMCmd. - * @param caller The account calling the assignVMCmd. * @param vm The VM to be assigned to another user, which has to have networks updated. * @param newAccount The account to whom the VM will be assigned to. * @param template The template of the VM which will be assigned to another account. * @throws InsufficientCapacityException * @throws ResourceAllocationException */ - protected void updateVmNetwork(AssignVMCmd cmd, Account caller, UserVmVO vm, Account newAccount, VirtualMachineTemplate template) + protected void updateVmNetwork(AssignVMCmd cmd, UserVmVO vm, Account newAccount, VirtualMachineTemplate template) throws InsufficientCapacityException, ResourceAllocationException { logger.trace("Updating network for VM [{}].", vm); @@ -8212,7 +8116,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return; } - updateAdvancedTypeNetworkForVm(caller, vm, newAccount, template, vmOldProfile, zone, networkIdList, securityGroupIdList); + updateAdvancedTypeNetworkForVm(vm, newAccount, template, vmOldProfile, zone, networkIdList, securityGroupIdList); } /** @@ -8293,7 +8197,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>(); NicProfile profile = new NicProfile(); profile.setDefaultNic(true); - networks.put(networkList.get(0), new ArrayList<>(Arrays.asList(profile))); + networks.put(networkList.get(0), new ArrayList<>(List.of(profile))); allocateNetworksForVm(vm, networks); @@ -8308,7 +8212,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * and adding security groups to the VM ({@link #addSecurityGroupsToVm(Account, UserVmVO, VirtualMachineTemplate, List, Network)}) - if enabled in the zone. * If no applicable network is provided and the zone has security groups enabled, throws a {@link InvalidParameterValueException}. * If security groups are not enabled, but security groups have been provided, throws a {@link InvalidParameterValueException}. - * @param caller The caller of the assignVMCmd. * @param vm The VM for which the networks are allocated or selected. * @param newAccount The new account to which the VM will be assigned to. * @param template The template of the VM. @@ -8320,7 +8223,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * @throws ResourceAllocationException * @throws InvalidParameterValueException */ - protected void updateAdvancedTypeNetworkForVm(Account caller, UserVmVO vm, Account newAccount, VirtualMachineTemplate template, + protected void updateAdvancedTypeNetworkForVm(UserVmVO vm, Account newAccount, VirtualMachineTemplate template, VirtualMachineProfileImpl vmOldProfile, DataCenterVO zone, List<Long> networkIdList, List<Long> securityGroupIdList) throws InsufficientCapacityException, ResourceAllocationException, InvalidParameterValueException { @@ -8453,7 +8356,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (NetworkVO appNet : applicableNetworks) { defaultNic.setRequestedIPv4(requestedIPv4ForNics.get(appNet.getId())); defaultNic.setRequestedIPv6(requestedIPv6ForNics.get(appNet.getId())); - networks.put(appNet, new ArrayList<>(Arrays.asList(defaultNic))); + networks.put(appNet, new ArrayList<>(List.of(defaultNic))); defaultNic = new NicProfile(); } @@ -8500,7 +8403,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir protected void addDefaultSecurityGroupToSecurityGroupIdList(Account newAccount, List<Long> securityGroupIdList) { logger.debug("Adding default security group to security group list if not already in it."); - Long newAccountId = newAccount.getId(); + long newAccountId = newAccount.getId(); SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccountId); boolean defaultGroupPresent = false; @@ -8635,10 +8538,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir /** * Attempts to create a network suitable for the creation of a VM ({@link NetworkOrchestrationService#createGuestNetwork}). * If no physical network is found, throws a {@link InvalidParameterValueException}. - * @param caller The account which calls for the network creation. * @param newAccount The account to which the network will be created. * @param zone The zone where the network will be created. - * @param requiredOffering The network offering required to create the network. * @return The NetworkVO for the network created. * @throws InsufficientCapacityException * @throws ResourceAllocationException @@ -8649,7 +8550,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir logger.trace("Creating an applicable network to create the VM."); NetworkVO defaultNetwork; - Long zoneId = zone.getId(); + long zoneId = zone.getId(); Account caller = CallContext.current().getCallingAccount(); NetworkOfferingVO requiredOffering = getOfferingWithRequiredAvailabilityForNetworkCreation(); String requiredOfferingTags = requiredOffering.getTags(); @@ -8797,16 +8698,16 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw new CloudRuntimeException("There is/are unbacked up snapshot(s) on ROOT volume, Re-install VM is not permitted, please try again later."); } logger.debug("Found no ongoing snapshots on volume of type ROOT, for the vm {}", vm); - return restoreVMInternal(caller, vm, newTemplateId, rootDiskOfferingId, expunge, details); + return restoreVMInternal(vm, newTemplateId, rootDiskOfferingId, expunge, details); } - public UserVm restoreVMInternal(Account caller, UserVmVO vm, Long newTemplateId, Long rootDiskOfferingId, boolean expunge, Map<String, String> details) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException { + public UserVm restoreVMInternal(UserVmVO vm, Long newTemplateId, Long rootDiskOfferingId, boolean expunge, Map<String, String> details) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException { return _itMgr.restoreVirtualMachine(vm.getId(), newTemplateId, rootDiskOfferingId, expunge, details); } - public UserVm restoreVMInternal(Account caller, UserVmVO vm) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException { - return restoreVMInternal(caller, vm, null, null, false, null); + public UserVm restoreVMInternal( UserVmVO vm) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException { + return restoreVMInternal(vm, null, null, false, null); } private VMTemplateVO getRestoreVirtualMachineTemplate(Account caller, Long newTemplateId, List<VolumeVO> rootVols, UserVmVO vm) { @@ -8892,7 +8793,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // If target VM has associated VM snapshots then don't allow restore of VM List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId); - if (vmSnapshots.size() > 0) { + if (!vmSnapshots.isEmpty()) { throw new InvalidParameterValueException("Unable to restore Instance, please remove Instance Snapshots before restoring Instance"); } @@ -8986,7 +8887,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _volsDao.detachVolume(root.getId()); destroyVolumeInContext(vm, Volume.State.Allocated.equals(root.getState()) || expunge, root); - if (currentTemplate.getId() != template.getId() && VirtualMachine.Type.User.equals(vm.type) && !VirtualMachineManager.ResourceCountRunningVMsonly.value()) { + if (currentTemplate != null && currentTemplate.getId() != template.getId() && VirtualMachine.Type.User.equals(vm.type) && !VirtualMachineManager.ResourceCountRunningVMsonly.value()) { ServiceOfferingVO serviceOffering = serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId()); _resourceLimitMgr.updateVmResourceCountForTemplateChange(vm.getAccountId(), vm.isDisplay(), serviceOffering, currentTemplate, template); } @@ -9158,7 +9059,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } } else { tmplStore = _templateStoreDao.findByTemplate(template.getId(), DataStoreRole.Image); - if (tmplStore == null || (tmplStore != null && !tmplStore.getDownloadState().equals(VMTemplateStorageResourceAssoc.Status.BYPASSED))) { + if (tmplStore == null || !tmplStore.getDownloadState().equals(VMTemplateStorageResourceAssoc.Status.BYPASSED)) { throw new InvalidParameterValueException("Cannot restore the vm as the bypassed template " + template.getUuid() + " isn't available in the zone"); } } @@ -9321,7 +9222,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir private void encryptAndStorePassword(UserVmVO vm, String password) { String sshPublicKeys = vm.getDetail(VmDetailConstants.SSH_PUBLIC_KEY); - if (sshPublicKeys != null && !sshPublicKeys.equals("") && password != null && !password.equals("saved_password")) { + if (sshPublicKeys != null && !sshPublicKeys.isEmpty() && password != null && !password.equals("saved_password")) { if (!sshPublicKeys.startsWith("ssh-rsa")) { logger.warn("Only RSA public keys can be used to encrypt a vm password."); return; @@ -9395,7 +9296,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } logger.debug("Found {} no. of volumes of type {} for vm with VM ID {}", listVolumes.size(), type, vm); for (VolumeVO volume : listVolumes) { - Long volumeId = volume.getId(); + long volumeId = volume.getId(); logger.debug("Checking status of snapshots for Volume: {}", volume); List<SnapshotVO> ongoingSnapshots = _snapshotDao.listByStatus(volumeId, Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp); int ongoingSnapshotsCount = ongoingSnapshots.size(); @@ -9414,12 +9315,12 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (VolumeVO volume : volumes) { if (volume.getInstanceId() == null || vmId != volume.getInstanceId() || volume.getVolumeType() != Volume.Type.DATADISK) { - sb.append(volume.toString() + "; "); + sb.append(volume).append("; "); } } if (!StringUtils.isEmpty(sb.toString())) { - throw new InvalidParameterValueException("The following supplied volumes are not DATADISK attached to the VM: " + sb.toString()); + throw new InvalidParameterValueException("The following supplied volumes are not DATADISK attached to the VM: " + sb); } } @@ -9427,7 +9328,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (VolumeVO volume : volumes) { if (!(volume.getVolumeType() == Volume.Type.ROOT || volume.getVolumeType() == Volume.Type.DATADISK)) { - throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK.toString() + " or " + Volume.Type.ROOT.toString()); + throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK + " or " + Volume.Type.ROOT); } if (volume.isDeleteProtection()) { throw new InvalidParameterValueException(String.format( @@ -9521,7 +9422,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir final String uuidName = _uuidMgr.generateUuid(UserVm.class, null); final Host lastHost = powerState != VirtualMachine.PowerState.PowerOn ? host : null; - final Boolean dynamicScalingEnabled = checkIfDynamicScalingCanBeEnabled(null, serviceOffering, template, zone.getId()); + final boolean dynamicScalingEnabled = checkIfDynamicScalingCanBeEnabled(null, serviceOffering, template, zone.getId()); return commitUserVm(true, zone, host, lastHost, template, hostName, displayName, owner, null, null, userData, null, null, isDisplayVm, keyboard, accountId, userId, serviceOffering, template.getFormat().equals(ImageFormat.ISO), sshPublicKeys, networkNicMap, @@ -9583,7 +9484,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private void checkRootDiskSizeAgainstBackup(Long instanceVolumeSize,DiskOffering rootDiskOffering, Long backupVolumeSize) { - Long instanceRootDiskSize = rootDiskOffering.isCustomized() ? instanceVolumeSize : rootDiskOffering.getDiskSize() / GiB_TO_BYTES; + long instanceRootDiskSize = rootDiskOffering.isCustomized() ? instanceVolumeSize : rootDiskOffering.getDiskSize() / GiB_TO_BYTES; if (instanceRootDiskSize < backupVolumeSize) { throw new InvalidParameterValueException( String.format("Instance volume root disk size %d[GiB] cannot be less than the backed-up volume size %d[GiB].", @@ -9624,7 +9525,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (serviceOfferingId != null) { serviceOffering = serviceOfferingDao.findById(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOffering.getId()); + throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); } } else { String serviceOfferingUuid = backup.getDetail(ApiConstants.SERVICE_OFFERING_ID); @@ -9660,7 +9561,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Long size = cmd.getSize(); Long diskOfferingId = cmd.getDiskOfferingId(); - Boolean isIso = template.getFormat().equals(ImageFormat.ISO); + boolean isIso = template.getFormat().equals(ImageFormat.ISO); if (diskOfferingId != null) { if (!isIso) { throw new InvalidParameterValueException(ApiConstants.DISK_OFFERING_ID + " parameter is supported for creating instance from backup only for ISO. For creating VMs with templates, please use the parameter " + ApiConstants.DATADISKS_DETAILS); @@ -9719,7 +9620,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Map<Long, IpAddresses> ipToNetworkMap = cmd.getIpToNetworkMap(); if (networkIds == null && ipToNetworkMap == null) { - networkIds = new ArrayList<Long>(); + networkIds = new ArrayList<>(); ipToNetworkMap = backupManager.getIpToNetworkMapFromBackup(backup, cmd.getPreserveIp(), networkIds); } @@ -9828,7 +9729,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir */ private void removeVMFromAffinityGroups(long vmId) { List<AffinityGroupVMMapVO> affinityGroups = _affinityGroupVMMapDao.listByInstanceId(vmId); - if (affinityGroups.size() > 0) { + if (!affinityGroups.isEmpty()) { logger.debug("Cleaning up VM from affinity groups after unmanaging"); for (AffinityGroupVMMapVO map : affinityGroups) { _affinityGroupVMMapDao.expunge(map.getId()); diff --git a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java index 1ea78bff3db..b98b2a22f8b 100644 --- a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java +++ b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java @@ -446,7 +446,7 @@ public class UserVmManagerImplTest { MockedStatic<UnmanagedVMsManager> unmanagedVMsManagerMockedStatic; - private static final long vmId = 1l; + private static final long vmId = 1L; private static final long zoneId = 2L; private static final long accountId = 3L; private static final long serviceOfferingId = 10L; @@ -695,7 +695,7 @@ public class UserVmManagerImplTest { Mockito.doNothing().when(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.doNothing().when(userVmManagerImpl).updateVolumesOwner(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); - Mockito.doNothing().when(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.doNothing().when(userVmManagerImpl).resourceCountIncrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); } @@ -2061,7 +2061,7 @@ public class UserVmManagerImplTest { Mockito.doNothing().when(userVmManagerImpl).updateBasicTypeNetworkForVm(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); - userVmManagerImpl.updateVmNetwork(assignVmCmdMock, callerAccount, userVmVoMock, accountMock, virtualMachineTemplateMock); + userVmManagerImpl.updateVmNetwork(assignVmCmdMock, userVmVoMock, accountMock, virtualMachineTemplateMock); Mockito.verify(userVmManagerImpl).updateBasicTypeNetworkForVm(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); @@ -2072,12 +2072,12 @@ public class UserVmManagerImplTest { Mockito.doReturn(_dcMock).when(_dcDao).findById(Mockito.anyLong()); Mockito.doReturn(DataCenter.NetworkType.Advanced).when(_dcMock).getNetworkType(); Mockito.doNothing().when(userVmManagerImpl).updateAdvancedTypeNetworkForVm(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.any(), Mockito.any()); - userVmManagerImpl.updateVmNetwork(assignVmCmdMock, callerAccount, userVmVoMock, accountMock, virtualMachineTemplateMock); + userVmManagerImpl.updateVmNetwork(assignVmCmdMock, userVmVoMock, accountMock, virtualMachineTemplateMock); Mockito.verify(userVmManagerImpl).updateAdvancedTypeNetworkForVm(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.any(), Mockito.any()); } @Test @@ -2802,7 +2802,7 @@ public class UserVmManagerImplTest { Mockito.doReturn(true).when(networkModel).checkSecurityGroupSupportForNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.updateAdvancedTypeNetworkForVm(callerAccount, userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, + userVmManagerImpl.updateAdvancedTypeNetworkForVm(userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, networkIdList, securityGroupIdList); }); @@ -2823,7 +2823,7 @@ public class UserVmManagerImplTest { Mockito.doReturn(true).when(networkModel).checkSecurityGroupSupportForNetwork(accountMock, _dcMock, networkIdList, securityGroupIdList); - userVmManagerImpl.updateAdvancedTypeNetworkForVm(callerAccount, userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, + userVmManagerImpl.updateAdvancedTypeNetworkForVm(userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, networkIdList, securityGroupIdList); Mockito.verify(securityGroupManagerMock).removeInstanceFromGroups(Mockito.any()); @@ -2842,7 +2842,7 @@ public class UserVmManagerImplTest { Mockito.doReturn(false).when(networkModel).checkSecurityGroupSupportForNetwork(accountMock, _dcMock, networkIdList, securityGroupIdList); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.updateAdvancedTypeNetworkForVm(callerAccount, userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, + userVmManagerImpl.updateAdvancedTypeNetworkForVm(userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, networkIdList, securityGroupIdList); }); @@ -2862,7 +2862,7 @@ public class UserVmManagerImplTest { Mockito.doReturn(false).when(networkModel).checkSecurityGroupSupportForNetwork(accountMock, _dcMock, networkIdList, securityGroupIdList); Mockito.doReturn(true).when(securityGroupIdList).isEmpty(); - userVmManagerImpl.updateAdvancedTypeNetworkForVm(callerAccount, userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, + userVmManagerImpl.updateAdvancedTypeNetworkForVm(userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, networkIdList, securityGroupIdList); Mockito.verify(userVmManagerImpl).addNetworksToNetworkIdList(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap(), Mockito.anyMap()); @@ -2886,7 +2886,7 @@ public class UserVmManagerImplTest { Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); Mockito.doReturn(true).when(userVmManagerImpl).canAccountUseNetwork(accountMock, networkMock); - userVmManagerImpl.updateAdvancedTypeNetworkForVm(callerAccount, userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, + userVmManagerImpl.updateAdvancedTypeNetworkForVm(userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, networkIdList, securityGroupIdList); Mockito.verify(userVmManagerImpl).addNetworksToNetworkIdList(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap(), Mockito.anyMap()); @@ -3123,11 +3123,11 @@ public class UserVmManagerImplTest { configureDoNothingForMethodsThatWeDoNotWantToTest(); - doThrow(InsufficientAddressCapacityException.class).when(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + doThrow(InsufficientAddressCapacityException.class).when(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); - Assert.assertThrows(CloudRuntimeException.class, () -> userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, callerAccount, accountMock, accountMock, - userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1l)); + Assert.assertThrows(CloudRuntimeException.class, () -> userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, accountMock, accountMock, + userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1L)); Mockito.verify(userVmManagerImpl).resourceCountDecrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()); @@ -3146,11 +3146,10 @@ public class UserVmManagerImplTest { configureDoNothingForMethodsThatWeDoNotWantToTest(); - doThrow(ResourceAllocationException.class).when(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any()); + doThrow(ResourceAllocationException.class).when(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); - Assert.assertThrows(CloudRuntimeException.class, () -> userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, callerAccount, accountMock, accountMock, - userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1l)); + Assert.assertThrows(CloudRuntimeException.class, () -> userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, accountMock, accountMock, + userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1L)); Mockito.verify(userVmManagerImpl).resourceCountDecrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()); @@ -3171,13 +3170,13 @@ public class UserVmManagerImplTest { configureDoNothingForMethodsThatWeDoNotWantToTest(); - userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, callerAccount, accountMock, accountMock, userVmVoMock, serviceOfferingVoMock, volumes, + userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, accountMock, accountMock, userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1L); Mockito.verify(userVmManagerImpl).resourceCountDecrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()); Mockito.verify(userVmManagerImpl).updateVolumesOwner(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyLong()); - Mockito.verify(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).resourceCountIncrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); } } @@ -3194,13 +3193,13 @@ public class UserVmManagerImplTest { configureDoNothingForMethodsThatWeDoNotWantToTest(); - userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, callerAccount, accountMock, accountMock, userVmVoMock, serviceOfferingVoMock, volumes, - virtualMachineTemplateMock, 1l); + userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, accountMock, accountMock, userVmVoMock, serviceOfferingVoMock, volumes, + virtualMachineTemplateMock, 1L); Mockito.verify(userVmManagerImpl).resourceCountDecrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()); Mockito.verify(userVmManagerImpl).updateVolumesOwner(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyLong()); - Mockito.verify(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(userVmManagerImpl).updateVmNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl, Mockito.never()).resourceCountIncrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); } }
