Skip to content

Commit d1e1aa5

Browse files
authored
VM Deployment using snapshot in new zone (#13178)
1 parent 35ac91e commit d1e1aa5

2 files changed

Lines changed: 391 additions & 283 deletions

File tree

server/src/main/java/com/cloud/vm/UserVmManagerImpl.java

Lines changed: 37 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,6 @@
155155
import org.apache.commons.collections.MapUtils;
156156
import org.apache.commons.lang.math.NumberUtils;
157157
import org.apache.commons.lang3.ObjectUtils;
158-
import org.apache.commons.lang3.StringUtils;
159158
import org.apache.commons.lang3.builder.ToStringBuilder;
160159
import org.apache.commons.lang3.builder.ToStringStyle;
161160
import org.jetbrains.annotations.NotNull;
@@ -376,6 +375,7 @@
376375
import com.cloud.utils.Journal;
377376
import com.cloud.utils.NumbersUtil;
378377
import com.cloud.utils.Pair;
378+
import com.cloud.utils.StringUtils;
379379
import com.cloud.utils.component.ComponentContext;
380380
import com.cloud.utils.component.ManagerBase;
381381
import com.cloud.utils.concurrency.NamedThreadFactory;
@@ -619,7 +619,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
619619
@Inject
620620
BackupScheduleDao backupScheduleDao;
621621
@Inject
622-
private StatsCollector statsCollector;
622+
StatsCollector statsCollector;
623623
@Inject
624624
private UserDataDao userDataDao;
625625
@Inject
@@ -903,10 +903,10 @@ public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws Re
903903
}
904904

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

909-
if (password == null || password.equals("")) {
909+
if (StringUtils.isEmpty(password)) {
910910
return false;
911911
}
912912

@@ -1091,7 +1091,7 @@ protected void removeEncryptedPasswordFromUserVmVoDetails(long vmId) {
10911091
}
10921092

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

10971097
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId());
@@ -1263,7 +1263,7 @@ public UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) throws ResourceAllocationE
12631263
if (vmInstance == null) {
12641264
throw new InvalidParameterValueException("unable to find an Instance with id " + vmId);
12651265
} else if (!(vmInstance.getState().equals(State.Stopped))) {
1266-
throw new InvalidParameterValueException("Unable to upgrade Instance " + vmInstance.toString() + " " + " in state " + vmInstance.getState()
1266+
throw new InvalidParameterValueException("Unable to upgrade Instance " + vmInstance + " " + " in state " + vmInstance.getState()
12671267
+ "; make sure the Instance is stopped");
12681268
}
12691269

@@ -1756,7 +1756,7 @@ public UserVm updateDefaultNicForVirtualMachine(UpdateDefaultNicForVMCmd cmd) th
17561756
oldNetworkOfferingId = oldDefaultNetwork.getNetworkOfferingId();
17571757
}
17581758
NicVO existingVO = _nicDao.findById(existing.id);
1759-
Integer chosenID = nic.getDeviceId();
1759+
int chosenID = nic.getDeviceId();
17601760
Integer existingID = existing.getDeviceId();
17611761

17621762
Network newdefault = null;
@@ -2136,14 +2136,14 @@ private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingI
21362136

21372137
// Check vm flag
21382138
if (!vmInstance.isDynamicallyScalable()) {
2139-
throw new CloudRuntimeException(String.format("Unable to scale %s as it does not have tools to support dynamic scaling.", vmInstance.toString()));
2139+
throw new CloudRuntimeException(String.format("Unable to scale %s as it does not have tools to support dynamic scaling.", vmInstance));
21402140
}
21412141

21422142
// Check disable threshold for cluster is not crossed
21432143
HostVO host = _hostDao.findById(vmInstance.getHostId());
21442144
_hostDao.loadDetails(host);
21452145
if (_capacityMgr.checkIfClusterCrossesThreshold(host.getClusterId(), cpuDiff, memoryDiff)) {
2146-
throw new CloudRuntimeException(String.format("Unable to scale %s due to insufficient resources.", vmInstance.toString()));
2146+
throw new CloudRuntimeException(String.format("Unable to scale %s due to insufficient resources.", vmInstance));
21472147
}
21482148

21492149
while (retry-- != 0) { // It's != so that it can match -1.
@@ -2180,7 +2180,7 @@ private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingI
21802180
success = true;
21812181
return success;
21822182
} catch (InsufficientCapacityException | ResourceUnavailableException | ConcurrentOperationException e) {
2183-
logger.error(String.format("Unable to scale %s due to [%s].", vmInstance.toString(), e.getMessage()), e);
2183+
logger.error(String.format("Unable to scale %s due to [%s].", vmInstance, e.getMessage()), e);
21842184
} finally {
21852185
if (!success) {
21862186
// Decrement CPU and Memory count accordingly.
@@ -4485,7 +4485,7 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri
44854485
}
44864486

44874487
NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
4488-
Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
4488+
long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
44894489

44904490
String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);
44914491
if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {
@@ -4703,7 +4703,7 @@ protected long configureCustomRootDiskSize(Map<String, String> customParameters,
47034703
}
47044704

47054705
if (customParameters.containsKey(VmDetailConstants.ROOT_DISK_SIZE)) {
4706-
Long rootDiskSize = NumbersUtil.parseLong(customParameters.get(VmDetailConstants.ROOT_DISK_SIZE), -1);
4706+
long rootDiskSize = NumbersUtil.parseLong(customParameters.get(VmDetailConstants.ROOT_DISK_SIZE), -1);
47074707
if (rootDiskSize <= 0) {
47084708
throw new InvalidParameterValueException("Root disk size should be a positive number.");
47094709
}
@@ -4822,7 +4822,7 @@ private UserVmVO commitUserVm(final boolean isImport, final DataCenter zone, fin
48224822
final Map<String, Map<Integer, String>> extraDhcpOptionMap, final Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap,
48234823
final Map<String, String> userVmOVFPropertiesMap, final VirtualMachine.PowerState powerState, final boolean dynamicScalingEnabled, String vmType, final Long rootDiskOfferingId, String sshkeypairs,
48244824
List<VmDiskInfo> dataDiskInfoList, Volume volume, Snapshot snapshot) throws InsufficientCapacityException {
4825-
Long selectedGuestOsId = guestOsId != null ? guestOsId : template.getGuestOSId();
4825+
long selectedGuestOsId = guestOsId != null ? guestOsId : template.getGuestOSId();
48264826
UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, selectedGuestOsId, offering.isOfferHA(),
48274827
offering.getLimitCpuUse(), owner.getDomainId(), owner.getId(), userId, offering.getId(), userData, userDataId, userDataDetails, hostName);
48284828
vm.setUuid(uuidName);
@@ -5381,7 +5381,7 @@ private void addUserVMCmdlineArgs(Long vmId, VirtualMachineProfile profile, Depl
53815381
if (dc.getDns2() != null) {
53825382
buf.append(" dns2=").append(dc.getDns2());
53835383
}
5384-
logger.info("cmdline details: "+ buf.toString());
5384+
logger.info("cmdline details: "+ buf);
53855385
}
53865386

53875387
@Override
@@ -5641,7 +5641,7 @@ private void checkForceStopVmPermission(Account callingAccount) {
56415641
public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException {
56425642
// Input validation
56435643
Account caller = CallContext.current().getCallingAccount();
5644-
Long userId = CallContext.current().getCallingUserId();
5644+
long userId = CallContext.current().getCallingUserId();
56455645

56465646
// if account is removed, return error
56475647
if (caller != null && caller.getRemoved() != null) {
@@ -6413,7 +6413,13 @@ public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityE
64136413
}
64146414
_accountMgr.checkAccess(caller, null, true, snapshot);
64156415
VolumeInfo volumeOfSnapshot = getVolume(snapshot.getVolumeId(), templateId, true);
6416-
templateId = volumeOfSnapshot.getTemplateId();
6416+
if (volumeOfSnapshot != null) {
6417+
templateId = volumeOfSnapshot.getTemplateId();
6418+
} else if (templateId == null) {
6419+
throw new InvalidParameterValueException(
6420+
"Could not determine template from snapshot id=" + cmd.getSnapshotId() +
6421+
"; the source volume no longer exists. Please specify a templateId.");
6422+
}
64176423
}
64186424

64196425
VirtualMachineTemplate template = null;
@@ -6695,7 +6701,9 @@ protected void addLeaseDetailsForInstance(UserVm vm, Integer leaseDuration, VMLe
66956701
private VolumeInfo getVolume(long id, Long templateId, boolean isSnapshot) {
66966702
VolumeInfo volume = volFactory.getVolume(id);
66976703
if (volume != null) {
6698-
if (volume.getDataStore() == null || !ScopeType.ZONE.equals(volume.getDataStore().getScope().getScopeType())) {
6704+
if (!isSnapshot
6705+
&& (volume.getDataStore() == null
6706+
|| !ScopeType.ZONE.equals(volume.getDataStore().getScope().getScopeType()))) {
66996707
throw new InvalidParameterValueException("Deployment of virtual machine is supported only for Zone-wide storage pools");
67006708
}
67016709
checkIfVolumeTemplateIsTheSameAsTheProvided(volume, templateId);
@@ -6911,7 +6919,7 @@ protected void addExtraConfig(UserVm vm, String extraConfig) {
69116919
} else if (hypervisorType.equals(HypervisorType.VMware)) {
69126920
persistExtraConfigVmware(decodedUrl, vm);
69136921
} else {
6914-
String msg = String.format("This hypervisor %s is not supported for use with this feature", hypervisorType.toString());
6922+
String msg = String.format("This hypervisor %s is not supported for use with this feature", hypervisorType);
69156923
throw new CloudRuntimeException(msg);
69166924
}
69176925
}
@@ -7257,7 +7265,7 @@ private DeployDestination chooseVmMigrationDestination(VMInstanceVO vm, Host src
72577265
vm.setLastHostId(null); // Last host does not have higher priority in vm migration
72587266
final ServiceOfferingVO offering = serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
72597267
final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, null, offering, null, null);
7260-
final Long srcHostId = srcHost.getId();
7268+
final long srcHostId = srcHost.getId();
72617269
final Host host = _hostDao.findById(srcHostId);
72627270
ExcludeList excludes = new ExcludeList();
72637271
excludes.addHost(srcHostId);
@@ -7910,7 +7918,7 @@ public UserVm moveVmToUser(final AssignVMCmd cmd) throws ResourceAllocationExcep
79107918

79117919
Long domainId = cmd.getDomainId();
79127920
Long projectId = cmd.getProjectId();
7913-
Long oldAccountId = vm.getAccountId();
7921+
long oldAccountId = vm.getAccountId();
79147922
String newAccountName = cmd.getAccountName();
79157923
final Account oldAccount = _accountService.getActiveAccountById(oldAccountId);
79167924
final Account newAccount = _accountMgr.finalizeOwner(caller, newAccountName, domainId, projectId);
@@ -8539,7 +8547,7 @@ protected void selectApplicableNetworkToCreateVm(Account newAccount, DataCenterV
85398547
protected void addDefaultSecurityGroupToSecurityGroupIdList(Account newAccount, List<Long> securityGroupIdList) {
85408548
logger.debug("Adding default security group to security group list if not already in it.");
85418549

8542-
Long newAccountId = newAccount.getId();
8550+
long newAccountId = newAccount.getId();
85438551
SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccountId);
85448552
boolean defaultGroupPresent = false;
85458553

@@ -8686,7 +8694,7 @@ protected NetworkVO createApplicableNetworkToCreateVm(Account newAccount, DataCe
86868694
logger.trace("Creating an applicable network to create the VM.");
86878695

86888696
NetworkVO defaultNetwork;
8689-
Long zoneId = zone.getId();
8697+
long zoneId = zone.getId();
86908698
Account caller = CallContext.current().getCallingAccount();
86918699
NetworkOfferingVO requiredOffering = getOfferingWithRequiredAvailabilityForNetworkCreation();
86928700
String requiredOfferingTags = requiredOffering.getTags();
@@ -9446,7 +9454,7 @@ private boolean checkStatusOfVolumeSnapshots(VirtualMachine vm, Volume.Type type
94469454
}
94479455
logger.debug("Found {} no. of volumes of type {} for vm with VM ID {}", listVolumes.size(), type, vm);
94489456
for (VolumeVO volume : listVolumes) {
9449-
Long volumeId = volume.getId();
9457+
long volumeId = volume.getId();
94509458
logger.debug("Checking status of snapshots for Volume: {}", volume);
94519459
List<SnapshotVO> ongoingSnapshots = _snapshotDao.listByStatus(volumeId, Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp);
94529460
int ongoingSnapshotsCount = ongoingSnapshots.size();
@@ -9465,20 +9473,20 @@ private void checkForUnattachedVolumes(long vmId, List<VolumeVO> volumes) {
94659473

94669474
for (VolumeVO volume : volumes) {
94679475
if (volume.getInstanceId() == null || vmId != volume.getInstanceId() || volume.getVolumeType() != Volume.Type.DATADISK) {
9468-
sb.append(volume.toString() + "; ");
9476+
sb.append(volume + "; ");
94699477
}
94709478
}
94719479

94729480
if (!StringUtils.isEmpty(sb.toString())) {
9473-
throw new InvalidParameterValueException("The following supplied volumes are not DATADISK attached to the VM: " + sb.toString());
9481+
throw new InvalidParameterValueException("The following supplied volumes are not DATADISK attached to the VM: " + sb);
94749482
}
94759483
}
94769484

94779485
private void validateVolumes(List<VolumeVO> volumes) {
94789486

94799487
for (VolumeVO volume : volumes) {
94809488
if (!(volume.getVolumeType() == Volume.Type.ROOT || volume.getVolumeType() == Volume.Type.DATADISK)) {
9481-
throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK.toString() + " or " + Volume.Type.ROOT.toString());
9489+
throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK + " or " + Volume.Type.ROOT);
94829490
}
94839491
if (volume.isDeleteProtection()) {
94849492
throw new InvalidParameterValueException(String.format(
@@ -9572,7 +9580,7 @@ public UserVm importVM(final DataCenter zone, final Host host, final VirtualMach
95729580

95739581
final String uuidName = _uuidMgr.generateUuid(UserVm.class, null);
95749582
final Host lastHost = powerState != VirtualMachine.PowerState.PowerOn ? host : null;
9575-
final Boolean dynamicScalingEnabled = checkIfDynamicScalingCanBeEnabled(null, serviceOffering, template, zone.getId());
9583+
final boolean dynamicScalingEnabled = checkIfDynamicScalingCanBeEnabled(null, serviceOffering, template, zone.getId());
95769584
return commitUserVm(true, zone, host, lastHost, template, hostName, displayName, owner,
95779585
null, null, userData, null, null, isDisplayVm, keyboard,
95789586
accountId, userId, serviceOffering, template.getFormat().equals(ImageFormat.ISO), guestOsId, sshPublicKeys, networkNicMap,
@@ -9634,7 +9642,7 @@ private void updateDetailsWithRootDiskAttributes(Map<String, String> details, Vm
96349642
}
96359643

96369644
private void checkRootDiskSizeAgainstBackup(Long instanceVolumeSize,DiskOffering rootDiskOffering, Long backupVolumeSize) {
9637-
Long instanceRootDiskSize = rootDiskOffering.isCustomized() ? instanceVolumeSize : rootDiskOffering.getDiskSize() / GiB_TO_BYTES;
9645+
long instanceRootDiskSize = rootDiskOffering.isCustomized() ? instanceVolumeSize : rootDiskOffering.getDiskSize() / GiB_TO_BYTES;
96389646
if (instanceRootDiskSize < backupVolumeSize) {
96399647
throw new InvalidParameterValueException(
96409648
String.format("Instance volume root disk size %d[GiB] cannot be less than the backed-up volume size %d[GiB].",
@@ -9711,7 +9719,7 @@ public UserVm allocateVMFromBackup(CreateVMFromBackupCmd cmd) throws Insufficien
97119719
Long size = cmd.getSize();
97129720

97139721
Long diskOfferingId = cmd.getDiskOfferingId();
9714-
Boolean isIso = template.getFormat().equals(ImageFormat.ISO);
9722+
boolean isIso = template.getFormat().equals(ImageFormat.ISO);
97159723
if (diskOfferingId != null) {
97169724
if (!isIso) {
97179725
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);

0 commit comments

Comments
 (0)