diff --git a/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java b/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java index b8c646048b97..cb221c357315 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 enum TemplateFilter { String getTemplateTag(); - Map getDetails(); + Map 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 01f11b73cd41..9bec28f35577 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.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 @@ UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering s String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Map requestedIps, IpAddresses defaultIp, Boolean displayVm, String keyboard, List affinityGroupIdList, Map customParameter, String customId, Map> dhcpOptionMap, Map dataDiskTemplateToDiskOfferingMap, - Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + Map 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 @@ UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOfferin List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, List dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, Map customParameters, String customId, Map> dhcpOptionMap, - Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + Map dataDiskTemplateToDiskOfferingMap, Map 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 @@ UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffe Map customParameters, String customId, Map> dhcpOptionMap, Map dataDiskTemplateToDiskOfferingMap, Map 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 @@ UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffe 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 @@ UserVm upgradeVirtualMachine(ScaleVMCmd cmd) throws ResourceUnavailableException * 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 f36c851e5bb3..9b6e314f87ca 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 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.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.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.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.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.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.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 vmIdCountMap = new ConcurrentHashMap<>(); + private final Map 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 getKubernetesServiceHelpers() { return kubernetesServiceHelpers; } @@ -682,19 +671,19 @@ public void setKubernetesServiceHelpers(final List kube @Inject VnfTemplateManager vnfTemplateManager; - private static final ConfigKey VmIpFetchWaitInterval = new ConfigKey("Advanced", Integer.class, "externaldhcp.vmip.retrieval.interval", "180", + private static final ConfigKey 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 VmIpFetchTrialMax = new ConfigKey("Advanced", Integer.class, "externaldhcp.vmip.max.retry", "10", + private static final ConfigKey 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 VmIpFetchThreadPoolMax = new ConfigKey("Advanced", Integer.class, "externaldhcp.vmipFetch.threadPool.max", "10", + private static final ConfigKey VmIpFetchThreadPoolMax = new ConfigKey<>("Advanced", Integer.class, "externaldhcp.vmipFetch.threadPool.max", "10", "number of threads for fetching vms ip address", true); - private static final ConfigKey VmIpFetchTaskWorkers = new ConfigKey("Advanced", Integer.class, "externaldhcp.vmipfetchtask.workers", "10", + private static final ConfigKey VmIpFetchTaskWorkers = new ConfigKey<>("Advanced", Integer.class, "externaldhcp.vmipfetchtask.workers", "10", "number of worker threads for vm ip fetch task ", true); - private static final ConfigKey AllowDeployVmIfGivenHostFails = new ConfigKey("Advanced", Boolean.class, "allow.deploy.vm.if.deploy.on.given.host.fails", "false", + private static final ConfigKey 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 KvmAdditionalConfigAllowList = new ConfigKey<>(String.class, @@ -706,7 +695,7 @@ public void setKubernetesServiceHelpers(final List kube private static final ConfigKey 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 VmDestroyForcestop = new ConfigKey("Advanced", Boolean.class, "vm.destroy.forcestop", "false", + private static final ConfigKey VmDestroyForcestop = new ConfigKey<>("Advanced", Boolean.class, "vm.destroy.forcestop", "false", "On destroy, force-stop takes this value ", true); @Override @@ -731,31 +720,20 @@ protected void resourceCountDecrement(long accountId, Boolean displayVm, Service } } - 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 UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws Re } 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 (StringUtils.isBlank(password)) { return false; } @@ -949,7 +926,7 @@ private boolean resetVMPasswordInternal(Long vmId, String password) throws Resou 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 @@ private UserVmVO resetVMSSHKeyInternal(UserVmVO userVm, Account owner, List 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 @@ protected void removeEncryptedPasswordFromUserVmVoDetails(long vmId) { } 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 @@ private boolean resetVMSSHKeyInternal(Long vmId, String sshPublicKeys, String ke 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 boolean stopVirtualMachine(long userId, long vmId) { 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 @@ private UserVm rebootVirtualMachine(long userId, long vmId, boolean enterSetup, if (dc.getNetworkType() == DataCenter.NetworkType.Advanced) { //List all networks of vm List vmNetworks = _vmNetworkMapDao.getNetworks(vmId); - List routers = new ArrayList(); + List routers = new ArrayList<>(); //List the stopped routers for(long vmNetworkId : vmNetworks) { List router = _routerDao.listStopped(vmNetworkId); @@ -1216,7 +1191,7 @@ private UserVm rebootVirtualMachine(long userId, long vmId, boolean enterSetup, } Map 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 UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) throws ResourceAllocationE 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 @@ private void validateOfferingMaxResource(ServiceOfferingVO offering) { @Override public void validateCustomParameters(ServiceOfferingVO serviceOffering, Map 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 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 void validateCustomParameters(ServiceOfferingVO serviceOffering, Map 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 void validateCustomParameters(ServiceOfferingVO serviceOffering, Map customParameters) throws ResourceAllocationException { + private void upgradeStoppedVirtualMachine(Long vmId, Long svcOffId, Map customParameters) throws ResourceAllocationException { VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); // Check resource limits for CPU and Memory. @@ -1415,9 +1390,6 @@ private UserVm upgradeStoppedVirtualMachine(Long vmId, Long svcOffId, Map 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 @@ protected ResizeVolumeCmd prepareResizeVolumeCmd(VolumeVO rootVolume, DiskOfferi @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 UserVm addNicToVirtualMachine(AddNicToVMCmd cmd) throws InvalidParameterV } // 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 UserVm addNicToVirtualMachine(AddNicToVMCmd cmd) throws InvalidParameterV } 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 @@ private void saveExtraDhcpOptions(long nicId, Map dhcpOptions) @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 UserVm removeNicFromVirtualMachine(RemoveNicFromVMCmd cmd) throws Invalid } // 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 UserVm removeNicFromVirtualMachine(RemoveNicFromVMCmd cmd) throws Invalid } // 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 UserVm removeNicFromVirtualMachine(RemoveNicFromVMCmd cmd) throws Invalid @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 UserVm updateDefaultNicForVirtualMachine(UpdateDefaultNicForVMCmd cmd) th } // 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 UserVm updateDefaultNicForVirtualMachine(UpdateDefaultNicForVMCmd cmd) th 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 UserVm upgradeVirtualMachine(ScaleVMCmd cmd) throws ResourceUnavailableEx 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 boolean upgradeVirtualMachine(Long vmId, Long newServiceOfferingId, Map customParameters) throws ResourceUnavailableException, - ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { + private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingId, Map customParameters) + throws ConcurrentOperationException, ManagementServerException { Account caller = CallContext.current().getCallingAccount(); VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); @@ -2092,7 +2068,7 @@ private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingI } 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 @@ private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingI // 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 @@ private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingI 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 HashMap getVolumeStatistics(long clusterId, Str 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 HashMap getVolumeStatistics(long clusterId, Str } } } - return volumeStatsByUuid.size() > 0 ? volumeStatsByUuid : null; + return !volumeStatsByUuid.isEmpty() ? volumeStatsByUuid : null; } private List getVolumesByHost(HostVO host, StoragePool pool){ @@ -2441,7 +2417,7 @@ public boolean configure(String name, Map params) throws Configu _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")); @@ -2450,20 +2426,13 @@ public boolean configure(String name, Map params) throws Configu int _usageAggregationRange = NumbersUtil.parseInt(aggregationRange, 1440); int HOURLY_TIME = 60; final int DAILY_TIME = 60 * 24; - if (_usageAggregationRange == DAILY_TIME) { - _dailyOrHourly = true; - } else if (_usageAggregationRange == HOURLY_TIME) { - _dailyOrHourly = true; - } else { - _dailyOrHourly = false; - } - + _dailyOrHourly = (_usageAggregationRange == DAILY_TIME || _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 +2443,6 @@ public boolean configure(String name, Map params) throws Configu return true; } - @Override - public String getName() { - return _name; - } - @Override public boolean start() { _executor.scheduleWithFixedDelay(new ExpungeTask(), _expungeInterval, _expungeInterval, TimeUnit.SECONDS); @@ -2520,10 +2484,6 @@ public boolean stop() { return true; } - public String getRandomPrivateTemplateName() { - return UUID.randomUUID().toString(); - } - @Override public boolean expunge(UserVmVO vm) { vm = _vmDao.acquireInLockTable(vm.getId()); @@ -2538,7 +2498,6 @@ public boolean expunge(UserVmVO vm) { releaseNetworkResourcesOnExpunge(vm.getId()); - List rootVol = _volsDao.findByInstanceAndType(vm.getId(), Volume.Type.ROOT); // expunge the vm _itMgr.advanceExpunge(vm.getUuid()); @@ -2615,7 +2574,7 @@ private boolean cleanupVmResources(UserVmVO vm) { // 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 +2724,8 @@ protected void runInContext() { try { List 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 +2867,11 @@ public UserVm updateVirtualMachine(UpdateVMCmd cmd) throws ResourceUnavailableEx } final Account caller = CallContext.current().getCallingAccount(); final List userDenyListedSettings = Stream.of(QueryService.UserVMDeniedDetails.value().split(",")) - .map(item -> (item).trim()) + .map(String::trim) .collect(Collectors.toList()); userDenyListedSettings.addAll(QueryService.RootAdminOnlyVmSettings); final List userReadOnlySettings = Stream.of(QueryService.UserVMReadOnlyDetails.value().split(",")) - .map(item -> (item).trim()) + .map(String::trim) .collect(Collectors.toList()); List existingDetails = vmInstanceDetailsDao.listDetails(id); if (cleanupDetails){ @@ -3085,7 +3044,7 @@ private void saveUsageEvent(UserVmVO vm) { 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 +3056,21 @@ private void saveUsageEvent(UserVmVO vm) { 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 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 +3152,7 @@ public UserVm updateVirtualMachine(long id, String displayName, String group, Bo 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 +3179,7 @@ public UserVm updateVirtualMachine(long id, String displayName, String group, Bo // Verify that vm's hostName is unique - List vmNtwks = new ArrayList(nics.size()); + List vmNtwks = new ArrayList<>(nics.size()); for (Nic nic : nics) { vmNtwks.add(_networkDao.findById(nic.getNetworkId())); } @@ -3438,18 +3397,18 @@ public UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityE 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"); } - Boolean enterSetup = cmd.getBootIntoSetup(); - if (enterSetup != null && enterSetup && !HypervisorType.VMware.equals(vmInstance.getHypervisorType())) { + boolean enterSetup = Boolean.TRUE.equals(cmd.getBootIntoSetup()); + if (enterSetup && !HypervisorType.VMware.equals(vmInstance.getHypervisorType())) { 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, cmd.getBootIntoSetup(), cmd.isForced()); if (userVm != null ) { // update the vmIdCountMap if the vm is in advanced shared network with out services final List nics = _nicDao.listByVmId(vmId); @@ -3673,11 +3632,7 @@ public boolean deleteVmGroup(long groupId) { _groupVMMapDao.expunge(sc); } - if (_vmGroupDao.remove(groupId)) { - return true; - } else { - return false; - } + return _vmGroupDao.remove(groupId); } @Override @@ -3742,9 +3697,8 @@ public InstanceGroupVO getGroupForVm(long vmId) { try { List 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 +3723,7 @@ public void removeInstanceFromInstanceGroup(long vmId) { } private boolean validPassword(String password) { - if (password == null || password.length() == 0) { + if (StringUtils.isBlank(password)) { return false; } for (int i = 0; i < password.length(); i++) { @@ -3786,11 +3740,11 @@ public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOff Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, List dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, Map customParametes, String customId, Map> dhcpOptionMap, - Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, - StorageUnavailableException, ResourceAllocationException { + Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); - List networkList = new ArrayList(); + List networkList = new ArrayList<>(); // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, null, true, owner); @@ -3808,7 +3762,7 @@ public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOff 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 +3770,7 @@ public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOff //add the default securityGroup only if no security group is specified if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { if (securityGroupIdList == null) { - securityGroupIdList = new ArrayList(); + securityGroupIdList = new ArrayList<>(); } SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(owner.getId()); if (defaultGroup != null) { @@ -3845,12 +3799,13 @@ public UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, Service List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, List dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, Map customParameters, String customId, Map> dhcpOptionMap, - Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { + Map dataDiskTemplateToDiskOfferingMap, Map userVmOVFProperties, boolean dynamicScalingEnabled, Long overrideDiskOfferingId, String vmType, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); - List networkList = new ArrayList(); + List 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 +3857,7 @@ public UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, Service 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 +3881,7 @@ public UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, Service //add the default securityGroup only if no security group is specified if (securityGroupIdList == null || securityGroupIdList.isEmpty()) { if (securityGroupIdList == null) { - securityGroupIdList = new ArrayList(); + securityGroupIdList = new ArrayList<>(); } SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(owner.getId()); @@ -3957,11 +3912,11 @@ public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serv String hostName, String displayName, Long diskOfferingId, Long diskSize, List dataDiskInfoList, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, Map requestedIps, IpAddresses defaultIps, Boolean displayvm, String keyboard, List affinityGroupIdList, Map customParametrs, String customId, Map> dhcpOptionsMap, Map dataDiskTemplateToDiskOfferingMap, - Map userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, - StorageUnavailableException, ResourceAllocationException { + Map userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); - List networkList = new ArrayList(); + List networkList = new ArrayList<>(); // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, null, true, owner); @@ -3982,7 +3937,7 @@ public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serv 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 +3981,6 @@ public UserVm finalizeCreateVirtualMachine(long vmId) { return userVm; } - private NetworkVO getNetworkToAddToNetworkList(VirtualMachineTemplate template, Account owner, HypervisorType hypervisor, - List 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 +3993,7 @@ private NetworkVO getDefaultNetwork(DataCenter zone, Account owner, boolean sele // * if network is not found, create a new one and use it List 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 +4069,8 @@ private UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffe Long userDataId, String userDataDetails, List sshKeyPairs, HypervisorType hypervisor, Account caller, Map requestedIps, IpAddresses defaultIps, Boolean isDisplayVm, String keyboard, List affinityGroupIdList, Map customParameters, String customId, Map> dhcpOptionMap, Map datadiskTemplateToDiskOfferringMap, - Map userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) throws InsufficientCapacityException, ResourceUnavailableException, - ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { + Map userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String vmType, Long overrideDiskOfferingId, Volume volume, Snapshot snapshot) + throws ConcurrentOperationException, ResourceAllocationException { _accountMgr.checkAccess(caller, null, true, owner); @@ -4155,19 +4082,7 @@ private UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffe _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 +4116,7 @@ private UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffe 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 +4156,25 @@ private UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffe 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 dataDiskInfoList, List networkList, List securityGroupIdList, String group, HTTPMethod httpmethod, String userData, Long userDataId, String userDataDetails, List sshKeyPairs, @@ -4252,11 +4186,11 @@ private UserVm getCheckedUserVmResource(DataCenter zone, String hostName, String Long rootDiskOfferingId, long volumesSize, Volume volume, Snapshot snapshot) throws ResourceAllocationException { if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) { List 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, isIso, rootDiskOfferingId, volumesSize, volume, snapshot); } catch (ResourceAllocationException | CloudRuntimeException e) { @@ -4286,12 +4220,12 @@ private List reserveStorageResourcesForVm(Account owner, Lon checkedReservations.add(rootPrimaryStorageReservation); if (diskOfferingId != null) { - List additionalResourceLimitStorageTags = diskOfferingId != null ? getResourceLimitStorageTags(diskOfferingId) : null; + List 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 +4280,6 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri || (!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 +4381,7 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri 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 +4397,7 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri } 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 +4432,12 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri } 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 +4470,6 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri // 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 +4506,9 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri } } - 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 +4532,7 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri 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 +4544,17 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri 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); - } + closeCheckedReservations(checkedReservations); + } + } + + private void closeCheckedReservations(List 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 +4563,7 @@ private void assignInstanceToGroup(String group, long id) { // 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 +4574,7 @@ private void assignInstanceToGroup(String group, long id) { } private long verifyAndGetDiskSize(DiskOffering diskOffering, Long diskSize) { - long size = 0l; + long size; if (diskOffering == null) { throw new InvalidParameterValueException("Specified disk offering cannot be found"); } @@ -4659,7 +4593,7 @@ private long verifyAndGetDiskSize(DiskOffering diskOffering, Long diskSize) { @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 +4623,11 @@ protected long configureCustomRootDiskSize(Map customParameters, } 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 +4792,7 @@ private UserVmVO commitUserVm(final boolean isImport, final DataCenter zone, fin validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters); } - if (isDisplayVm != null) { - vm.setDisplayVm(isDisplayVm); - } else { - vm.setDisplayVm(true); - } + vm.setDisplayVm(!Boolean.FALSE.equals(isDisplayVm)); setVmRequiredFieldsForImport(isImport, vm, zone, hypervisorType, host, lastHost, powerState); @@ -4916,10 +4846,10 @@ private UserVmVO commitUserVm(final boolean isImport, final DataCenter zone, fin logger.debug("Allocating in the DB for vm"); DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); - List computeTags = new ArrayList(); + List computeTags = new ArrayList<>(); computeTags.add(offering.getHostTag()); - List rootDiskTags = new ArrayList(); + List rootDiskTags = new ArrayList<>(); DiskOfferingVO rootDiskOfferingVO = _diskOfferingDao.findById(rootDiskOfferingId); rootDiskTags.add(rootDiskOfferingVO.getTags()); @@ -4944,7 +4874,7 @@ private UserVmVO commitUserVm(final boolean isImport, final DataCenter zone, fin resourceCountIncrement(accountId, isDisplayVm, offering, template); } catch (CloudRuntimeException cre) { ArrayList 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 +4905,14 @@ private void orchestrateVirtualMachineCreate(UserVmVO vm, GuestOSCategoryVO gues } } catch (CloudRuntimeException cre) { ArrayList 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 idList = ice.getIdProxyList(); + if (idList == null || idList.stream().noneMatch(i -> i.equals(vm.getUuid()))) { ice.addProxyObject(vm.getUuid()); } throw ice; @@ -5057,7 +4987,6 @@ private void updateVMDiskController(UserVmVO vm, Map customParam private void persistVMDeployAsIsProperties(UserVmVO vm, Map 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 +5005,16 @@ private void persistVMDeployAsIsProperties(UserVmVO vm, Map user 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> networkNicMap, final long id, final String instanceName, final String uuidName, final HypervisorType hypervisorType, final Map customParameters, final Map> extraDhcpOptionMap, final Map dataDiskTemplateToDiskOfferingMap, @@ -5133,7 +5062,7 @@ public void generateUsageEvent(VirtualMachine vm, boolean isDisplay, String even VirtualMachine.class.getName(), vm.getUuid(), isDisplay); } else { - Map customParameters = new HashMap(); + Map 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 +5079,7 @@ public void collectVmNetworkStatistics (final UserVm userVm) { } logger.debug("Collect vm network statistics from host before stopping Vm"); long hostId = userVm.getHostId(); - List vmNames = new ArrayList(); + List vmNames = new ArrayList<>(); vmNames.add(userVm.getInstanceName()); final HostVO host = _hostDao.findById(hostId); Account account = _accountMgr.getAccount(userVm.getAccountId()); @@ -5186,7 +5115,7 @@ public void doInTransactionWithoutResult(TransactionStatus status) { sc_nic.addAnd("macAddress", SearchCriteria.Op.EQ, vmNetworkStat.getMacAddress()); NicVO nic = _nicDao.search(sc_nic, null).get(0); List vlan = _vlanDao.listVlansByNetworkId(nic.getNetworkId()); - if (vlan == null || vlan.size() == 0 || vlan.get(0).getVlanType() != VlanType.DirectAttached) + if (CollectionUtils.isEmpty(vlan) || 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 +5136,8 @@ public void doInTransactionWithoutResult(TransactionStatus status) { 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 +5295,7 @@ private void addUserVMCmdlineArgs(Long vmId, VirtualMachineProfile profile, Depl if (dc.getDns2() != null) { buf.append(" dns2=").append(dc.getDns2()); } - logger.info("cmdline details: "+ buf.toString()); + logger.info("cmdline details: {}", buf); } @Override @@ -5428,11 +5356,7 @@ public boolean setupVmForPvlan(boolean add, Long hostId, NicProfile nic) { return false; } - boolean result = true; - if (answer == null || !answer.getResult()) { - result = false; - } - return result; + return answer != null && answer.getResult(); } @Override @@ -5484,14 +5408,13 @@ public boolean finalizeStart(VirtualMachineProfile profile, long hostId, Command } 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 +5483,9 @@ public boolean finalizeStart(VirtualMachineProfile profile, long hostId, Command } 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 +5521,7 @@ public void finalizeExpunge(VirtualMachine vm) { } 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 +5532,7 @@ private void checkForceStopVmPermission(Account callingAccount) { 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 +5565,6 @@ public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOpe } 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 +5581,7 @@ public void finalizeStop(VirtualMachineProfile profile, Answer answer) { 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 +5663,7 @@ public Pair> startVirtualMach SecurityGroup defaultSecurityGroup = _securityGroupMgr.getDefaultSecurityGroup(vm.getAccountId()); if (defaultSecurityGroup != null) { - List groupList = new ArrayList(); + List groupList = new ArrayList<>(); groupList.add(defaultSecurityGroup.getId()); _securityGroupMgr.addInstanceToGroups(vm, groupList); } @@ -5773,7 +5694,7 @@ public Pair> startVirtualMach 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,7 +5716,7 @@ public Pair> startVirtualMach } // Set parameters - Map params = null; + Map params = new HashMap<>(additionalParams); if (vm.isUpdateParameters()) { _vmDao.loadDetails(vm); @@ -5809,18 +5730,19 @@ public Pair> startVirtualMach // use it to encrypt & save the vm password encryptAndStorePassword(vm, password); - params = createParameterInParameterMap(params, additionalParams, VirtualMachineProfile.Param.VmPassword, password); + // overwrite VmPassword + params = createParameterInParameterMap(params, VirtualMachineProfile.Param.VmPassword, password); } if(additionalParams.containsKey(VirtualMachineProfile.Param.BootIntoSetup)) { if (! HypervisorType.VMware.equals(vm.getHypervisorType())) { throw new InvalidParameterValueException(ApiConstants.BOOT_INTO_SETUP + " makes no sense for " + vm.getHypervisorType()); } + + //overwrite BootIntoSetup Object paramValue = additionalParams.get(VirtualMachineProfile.Param.BootIntoSetup); - if (logger.isTraceEnabled()) { - logger.trace("It was specified whether to enter setup mode: " + paramValue.toString()); - } - params = createParameterInParameterMap(params, additionalParams, VirtualMachineProfile.Param.BootIntoSetup, paramValue); + logger.trace("It was specified whether to enter setup mode: {}", paramValue); + params = createParameterInParameterMap(params, VirtualMachineProfile.Param.BootIntoSetup, paramValue); } VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid()); @@ -5839,8 +5761,8 @@ public Pair> startVirtualMach String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId())); vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params, deployOnGivenHost); - Pair> vmParamPair = new Pair(vm, params); - if (vm != null && vm.isUpdateParameters()) { + Pair> 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()) { @@ -5888,20 +5810,18 @@ protected String getCurrentVmPasswordOrDefineNewPassword(String newPassword, Use return password; } - private Map createParameterInParameterMap(Map params, Map parameterMap, VirtualMachineProfile.Param parameter, + /** + * Create or overwrite a parameter in the list + * @param params the list of parameters + * @param parameter the parameter to creat/overwrite + * @param parameterValue the value to give to the parameter + * @return the resulting updated list of parameters + */ + private Map createParameterInParameterMap( + Map params, + VirtualMachineProfile.Param parameter, Object parameterValue) { - if (logger.isTraceEnabled()) { - logger.trace(String.format("createParameterInParameterMap(%s, %s)", parameter, parameterValue)); - } - if (params == null) { - if (logger.isTraceEnabled()) { - logger.trace("creating new Parameter map"); - } - params = new HashMap<>(); - if (parameterMap != null) { - params.putAll(parameterMap); - } - } + logger.trace("createParameterInParameterMap({}, {})", parameter, parameterValue); params.put(parameter, parameterValue); return params; } @@ -5958,8 +5878,7 @@ public UserVm destroyVm(long vmId, boolean expunge) throws ResourceUnavailableEx // 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 +5899,7 @@ public UserVm destroyVm(long vmId, boolean expunge) throws ResourceUnavailableEx 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 +5950,7 @@ public void collectVmDiskStatistics(final UserVm userVm) { return; } long hostId = userVm.getHostId(); - List vmNames = new ArrayList(); + List vmNames = new ArrayList<>(); vmNames.add(userVm.getInstanceName()); final HostVO host = _hostDao.findById(hostId); Account account = _accountMgr.getAccount(userVm.getAccountId()); @@ -6066,7 +5985,7 @@ public void doInTransactionWithoutResult(TransactionStatus status) { SearchCriteria sc_volume = _volsDao.createSearchCriteria(); sc_volume.addAnd("path", SearchCriteria.Op.LIKE, vmDiskStat.getPath() + "%"); List volumes = _volsDao.search(sc_volume, null); - if ((volumes == null) || (volumes.size() == 0)) { + if (CollectionUtils.isEmpty(volumes)) { break; } VolumeVO volume = volumes.get(0); @@ -6324,8 +6243,8 @@ private void verifyTemplate(BaseDeployVMCmd cmd, VirtualMachineTemplate template } @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 +6265,11 @@ public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityE 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 +6322,7 @@ public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityE List 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 +6357,7 @@ private UserVm createVirtualMachine(BaseDeployVMCmd cmd, DataCenter zone, Accoun String userData = null; Long userDataId = null; String userDataDetails = null; - List sshKeyPairNames = new ArrayList(); + List 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 +6365,6 @@ private UserVm createVirtualMachine(BaseDeployVMCmd cmd, DataCenter zone, Accoun } else { userData = cmd.getUserData(); userDataId = cmd.getUserdataId(); - userDataDetails = null; if (MapUtils.isNotEmpty(cmd.getUserdataDetails())) { userDataDetails = cmd.getUserdataDetails().toString(); } @@ -6566,10 +6483,6 @@ protected void validateLeaseProperties(Integer leaseDuration, VMLeaseManager.Exp * 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 +6630,7 @@ protected void persistExtraConfigXenServer(String decodedUrl, UserVm vm) { 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 +6711,7 @@ protected void persistExtraConfigKvm(String decodedUrl, UserVm vm) { 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 +6755,7 @@ protected void validateKvmExtraConfig(String decodedUrl, long accountId) { for (String tag : allowedConfigOptionList) { if (currentConfig.equals(tag.trim())) { isValidConfig = true; + break; } } if (!isValidConfig) { @@ -6869,7 +6783,7 @@ protected void addExtraConfig(UserVm vm, String extraConfig) { } 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 +6794,7 @@ protected void addExtraConfig(UserVm vm, String extraConfig) { * @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 getSecurityGroupIdList(SecurityGroupAction cmd) { @@ -6896,7 +6804,7 @@ protected List getSecurityGroupIdList(SecurityGroupAction cmd) { //transform group names to ids here if (cmd.getSecurityGroupNameList() != null) { - List securityGroupIds = new ArrayList(); + List securityGroupIds = new ArrayList<>(); for (String groupName : cmd.getSecurityGroupNameList()) { SecurityGroup sg = _securityGroupMgr.getSecurityGroup(groupName, cmd.getEntityOwnerId()); if (sg == null) { @@ -7037,7 +6945,7 @@ private VMInstanceVO preVmStorageMigrationCheck(Long vmId) { } // 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 +7123,7 @@ private DeployDestination chooseVmMigrationDestination(VMInstanceVO vm, Host src 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 +7164,7 @@ protected void validateStorageAccessGroupsOnHosts(Host srcHost, Host destination 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 +7230,6 @@ private DeployDestination checkVmMigrationDestination(VMInstanceVO vm, Host srcH 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 +7255,7 @@ private boolean checkIfHostIsDedicated(HostVO host) { 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 +7325,13 @@ public void checkHostsDedication(VMInstanceVO vm, long srcHostId, long destHostI //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 +7408,7 @@ public void checkHostsDedication(VMInstanceVO vm, long srcHostId, long destHostI private List getVmsOnHost(long hostId) { List vms = _vmInstanceDao.listUpByHostId(hostId); List 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 +7584,7 @@ private List getVmVolumesForMigrateVmWithStorage(VMInstanceVO vm) { } private Map getVolumePoolMappingForMigrateVmWithStorage(VMInstanceVO vm, Map volumeToPool) { - Map volToPoolObjectMap = new HashMap(); + Map volToPoolObjectMap = new HashMap<>(); List vmVolumes = getVmVolumesForMigrateVmWithStorage(vm); @@ -7722,7 +7625,7 @@ private Map getVolumePoolMappingForMigrateVmWithStorage(VMInstanceVO DiskOffering diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DiskProfile diskProfile = new DiskProfile(volume, diskOffering, _volsDao.getHypervisorType(volume.getId())); Pair 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 +7780,7 @@ public UserVm moveVmToUser(final AssignVMCmd cmd) throws ResourceAllocationExcep 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 +7814,7 @@ public UserVm moveVmToUser(final AssignVMCmd cmd) throws ResourceAllocationExcep 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 +7997,10 @@ protected NetworkOfferingVO getOfferingWithRequiredAvailabilityForNetworkCreatio * 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 +8009,7 @@ protected NetworkOfferingVO getOfferingWithRequiredAvailabilityForNetworkCreatio * @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 volumes, VirtualMachineTemplate template, Long domainId) { logger.trace("Generating destroy event for VM [{}].", vm); @@ -8129,7 +8031,7 @@ protected void executeStepsToChangeOwnershipOfVm(AssignVMCmd cmd, Account caller 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 +8087,15 @@ protected void updateVolumesOwner(final List volumes, Account oldAccou * 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 +8113,7 @@ protected void updateVmNetwork(AssignVMCmd cmd, Account caller, UserVmVO vm, Acc return; } - updateAdvancedTypeNetworkForVm(caller, vm, newAccount, template, vmOldProfile, zone, networkIdList, securityGroupIdList); + updateAdvancedTypeNetworkForVm(vm, newAccount, template, vmOldProfile, zone, networkIdList, securityGroupIdList); } /** @@ -8293,7 +8194,7 @@ protected void updateBasicTypeNetworkForVm(UserVmVO vm, Account newAccount, Virt LinkedHashMap> 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 +8209,6 @@ protected void updateBasicTypeNetworkForVm(UserVmVO vm, Account newAccount, Virt * 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 +8220,7 @@ protected void updateBasicTypeNetworkForVm(UserVmVO vm, Account newAccount, Virt * @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 networkIdList, List securityGroupIdList) throws InsufficientCapacityException, ResourceAllocationException, InvalidParameterValueException { @@ -8453,7 +8353,7 @@ protected NetworkVO addNicsToApplicableNetworksAndReturnDefaultNetwork(LinkedHas 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 +8400,7 @@ protected void selectApplicableNetworkToCreateVm(Account newAccount, DataCenterV protected void addDefaultSecurityGroupToSecurityGroupIdList(Account newAccount, List 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 +8535,8 @@ protected void updateBackupScheduleOwnership(UserVmVO vm, Account newAccount) { /** * 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 +8547,7 @@ protected NetworkVO createApplicableNetworkToCreateVm(Account newAccount, DataCe 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 +8695,16 @@ public UserVm restoreVM(RestoreVMCmd cmd) throws InsufficientCapacityException, 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 details) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException { + public UserVm restoreVMInternal(UserVmVO vm, Long newTemplateId, Long rootDiskOfferingId, boolean expunge, Map 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 rootVols, UserVmVO vm) { @@ -8892,7 +8790,7 @@ public UserVm restoreVirtualMachine(final Account caller, final long vmId, final // If target VM has associated VM snapshots then don't allow restore of VM List 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 +8884,7 @@ public Pair doInTransaction(final TransactionStatus status) th _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 +9056,7 @@ private void checkRestoreVmFromTemplate(UserVmVO vm, VMTemplateVO template, List } } 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 +9219,7 @@ public void finalizeUnmanage(VirtualMachine vm) { 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 (!StringUtils.isEmpty(sshPublicKeys) && 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 +9293,7 @@ private boolean checkStatusOfVolumeSnapshots(VirtualMachine vm, Volume.Type type } 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 ongoingSnapshots = _snapshotDao.listByStatus(volumeId, Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp); int ongoingSnapshotsCount = ongoingSnapshots.size(); @@ -9414,12 +9312,12 @@ private void checkForUnattachedVolumes(long vmId, List volumes) { 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 +9325,7 @@ private void validateVolumes(List volumes) { 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 +9419,7 @@ public UserVm importVM(final DataCenter zone, final Host host, final VirtualMach 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 +9481,7 @@ private void updateDetailsWithRootDiskAttributes(Map details, Vm } 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 +9522,7 @@ public UserVm allocateVMFromBackup(CreateVMFromBackupCmd cmd) throws Insufficien 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 +9558,7 @@ public UserVm allocateVMFromBackup(CreateVMFromBackupCmd cmd) throws Insufficien 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 +9617,7 @@ public UserVm allocateVMFromBackup(CreateVMFromBackupCmd cmd) throws Insufficien Map ipToNetworkMap = cmd.getIpToNetworkMap(); if (networkIds == null && ipToNetworkMap == null) { - networkIds = new ArrayList(); + networkIds = new ArrayList<>(); ipToNetworkMap = backupManager.getIpToNetworkMapFromBackup(backup, cmd.getPreserveIp(), networkIds); } @@ -9828,7 +9726,7 @@ void unmanageVMFromDB(long vmId) { */ private void removeVMFromAffinityGroups(long vmId) { List 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 1ea78bff3db9..b98b2a22f8ba 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 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 @@ private void configureDoNothingForMethodsThatWeDoNotWantToTest() throws Resource 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 void updateVmNetworkTestCallsUpdateBasicTypeNetworkForVmIfBasicTypeZone() 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 void updateVmNetworkTestCallsUpdateAdvancedTypeNetworkForVmIfNotBasicType 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 void updateAdvancedTypeNetworkForVmTestSecurityGroupIsEnabledApplicableNe 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 void updateAdvancedTypeNetworkForVmTestSecurityGroupIsEnabledApplicableNe 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 void updateAdvancedTypeNetworkForVmTestSecurityGroupIsNotEnabledSecurityG 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 void updateAdvancedTypeNetworkForVmTestSecurityGroupIsNotEnabledApplicabl 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 void updateAdvancedTypeNetworkForVmTestSecurityGroupIsNotEnabledApplicabl 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 void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsInsufficie 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 void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsResourceAl 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 void executeStepsToChangeOwnershipOfVmTestResourceCountRunningVmsOnlyEnab 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 void executeStepsToChangeOwnershipOfVmTestResourceCountRunningVmsOnlyEnab 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()); } }