Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 37 additions & 29 deletions server/src/main/java/com/cloud/vm/UserVmManagerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@
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;
Expand Down Expand Up @@ -376,6 +375,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;
Expand Down Expand Up @@ -619,7 +619,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
@Inject
BackupScheduleDao backupScheduleDao;
@Inject
private StatsCollector statsCollector;
StatsCollector statsCollector;
@Inject
private UserDataDao userDataDao;
@Inject
Expand Down Expand Up @@ -903,10 +903,10 @@ public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws Re
}

private boolean resetVMPasswordInternal(Long vmId, String password) throws ResourceUnavailableException, InsufficientCapacityException {
Long userId = CallContext.current().getCallingUserId();
long userId = CallContext.current().getCallingUserId();
VMInstanceVO vmInstance = _vmDao.findById(vmId);

if (password == null || password.equals("")) {
if (StringUtils.isEmpty(password)) {
return false;
}

Expand Down Expand Up @@ -1091,7 +1091,7 @@ protected void removeEncryptedPasswordFromUserVmVoDetails(long vmId) {
}

private boolean resetVMSSHKeyInternal(Long vmId, String sshPublicKeys, String keypairnames) throws ResourceUnavailableException, InsufficientCapacityException {
Long userId = CallContext.current().getCallingUserId();
long userId = CallContext.current().getCallingUserId();
VMInstanceVO vmInstance = _vmDao.findById(vmId);

VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId());
Expand Down Expand Up @@ -1263,7 +1263,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");
}

Expand Down Expand Up @@ -1756,7 +1756,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;
Expand Down Expand Up @@ -2136,14 +2136,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.
Expand Down Expand Up @@ -2180,7 +2180,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.
Expand Down Expand Up @@ -4485,7 +4485,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)) {
Expand Down Expand Up @@ -4703,7 +4703,7 @@ protected long configureCustomRootDiskSize(Map<String, String> 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.");
}
Expand Down Expand Up @@ -4822,7 +4822,7 @@ private UserVmVO commitUserVm(final boolean isImport, final DataCenter zone, fin
final Map<String, Map<Integer, String>> extraDhcpOptionMap, final Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap,
final Map<String, String> userVmOVFPropertiesMap, final VirtualMachine.PowerState powerState, final boolean dynamicScalingEnabled, String vmType, final Long rootDiskOfferingId, String sshkeypairs,
List<VmDiskInfo> dataDiskInfoList, Volume volume, Snapshot snapshot) throws InsufficientCapacityException {
Long selectedGuestOsId = guestOsId != null ? guestOsId : template.getGuestOSId();
long selectedGuestOsId = guestOsId != null ? guestOsId : template.getGuestOSId();
UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, selectedGuestOsId, offering.isOfferHA(),
offering.getLimitCpuUse(), owner.getDomainId(), owner.getId(), userId, offering.getId(), userData, userDataId, userDataDetails, hostName);
vm.setUuid(uuidName);
Expand Down Expand Up @@ -5381,7 +5381,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
Expand Down Expand Up @@ -5641,7 +5641,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) {
Expand Down Expand Up @@ -6413,7 +6413,13 @@ public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityE
}
_accountMgr.checkAccess(caller, null, true, snapshot);
VolumeInfo volumeOfSnapshot = getVolume(snapshot.getVolumeId(), templateId, true);
templateId = volumeOfSnapshot.getTemplateId();
if (volumeOfSnapshot != null) {
templateId = volumeOfSnapshot.getTemplateId();
} else if (templateId == null) {
throw new InvalidParameterValueException(
"Could not determine template from snapshot id=" + cmd.getSnapshotId() +
"; the source volume no longer exists. Please specify a templateId.");
}
}

VirtualMachineTemplate template = null;
Expand Down Expand Up @@ -6695,7 +6701,9 @@ protected void addLeaseDetailsForInstance(UserVm vm, Integer leaseDuration, VMLe
private VolumeInfo getVolume(long id, Long templateId, boolean isSnapshot) {
VolumeInfo volume = volFactory.getVolume(id);
if (volume != null) {
if (volume.getDataStore() == null || !ScopeType.ZONE.equals(volume.getDataStore().getScope().getScopeType())) {
if (!isSnapshot
&& (volume.getDataStore() == null
|| !ScopeType.ZONE.equals(volume.getDataStore().getScope().getScopeType()))) {
throw new InvalidParameterValueException("Deployment of virtual machine is supported only for Zone-wide storage pools");
}
checkIfVolumeTemplateIsTheSameAsTheProvided(volume, templateId);
Expand Down Expand Up @@ -6911,7 +6919,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);
}
}
Expand Down Expand Up @@ -7257,7 +7265,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);
Expand Down Expand Up @@ -7910,7 +7918,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);
Expand Down Expand Up @@ -8539,7 +8547,7 @@ protected void selectApplicableNetworkToCreateVm(Account newAccount, DataCenterV
protected void addDefaultSecurityGroupToSecurityGroupIdList(Account newAccount, List<Long> securityGroupIdList) {
logger.debug("Adding default security group to security group list if not already in it.");

Long newAccountId = newAccount.getId();
long newAccountId = newAccount.getId();
SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccountId);
boolean defaultGroupPresent = false;

Expand Down Expand Up @@ -8686,7 +8694,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();
Expand Down Expand Up @@ -9446,7 +9454,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<SnapshotVO> ongoingSnapshots = _snapshotDao.listByStatus(volumeId, Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp);
int ongoingSnapshotsCount = ongoingSnapshots.size();
Expand All @@ -9465,20 +9473,20 @@ private void checkForUnattachedVolumes(long vmId, List<VolumeVO> volumes) {

for (VolumeVO volume : volumes) {
if (volume.getInstanceId() == null || vmId != volume.getInstanceId() || volume.getVolumeType() != Volume.Type.DATADISK) {
sb.append(volume.toString() + "; ");
sb.append(volume + "; ");
}
}

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);
}
}

private void validateVolumes(List<VolumeVO> 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(
Expand Down Expand Up @@ -9572,7 +9580,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), guestOsId, sshPublicKeys, networkNicMap,
Expand Down Expand Up @@ -9634,7 +9642,7 @@ private void updateDetailsWithRootDiskAttributes(Map<String, String> 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].",
Expand Down Expand Up @@ -9711,7 +9719,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);
Expand Down
Loading
Loading