Skip to content

Commit 84676af

Browse files
Check for null host before proceeding with VM volume operations in managed storage while restoring VM (#12879)
1 parent d6c3977 commit 84676af

File tree

1 file changed

+41
-37
lines changed

1 file changed

+41
-37
lines changed

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

Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,21 +1194,21 @@ private UserVm rebootVirtualMachine(long userId, long vmId, boolean enterSetup,
11941194
List<Long> vmNetworks = _vmNetworkMapDao.getNetworks(vmId);
11951195
List<DomainRouterVO> routers = new ArrayList<DomainRouterVO>();
11961196
//List the stopped routers
1197-
for(long vmNetworkId : vmNetworks) {
1197+
for (long vmNetworkId : vmNetworks) {
11981198
List<DomainRouterVO> router = _routerDao.listStopped(vmNetworkId);
11991199
routers.addAll(router);
12001200
}
12011201
//A vm may not have many nics attached and even fewer routers might be stopped (only in exceptional cases)
12021202
//Safe to start the stopped router serially, this is consistent with the way how multiple networks are added to vm during deploy
12031203
//and routers are started serially ,may revisit to make this process parallel
1204-
for(DomainRouterVO routerToStart : routers) {
1204+
for (DomainRouterVO routerToStart : routers) {
12051205
logger.warn("Trying to start router {} as part of vm: {} reboot", routerToStart, vm);
12061206
_virtualNetAppliance.startRouter(routerToStart.getId(),true);
12071207
}
12081208
}
12091209
} catch (ConcurrentOperationException e) {
12101210
throw new CloudRuntimeException("Concurrent operations on starting router. " + e);
1211-
} catch (Exception ex){
1211+
} catch (Exception ex) {
12121212
throw new CloudRuntimeException("Router start failed due to" + ex);
12131213
} finally {
12141214
if (logger.isInfoEnabled()) {
@@ -1493,7 +1493,7 @@ public UserVm addNicToVirtualMachine(AddNicToVMCmd cmd) throws InvalidParameterV
14931493

14941494
macAddress = validateOrReplaceMacAddress(macAddress, network);
14951495

1496-
if(_nicDao.findByNetworkIdAndMacAddress(networkId, macAddress) != null) {
1496+
if (_nicDao.findByNetworkIdAndMacAddress(networkId, macAddress) != null) {
14971497
throw new CloudRuntimeException("A NIC with this MAC address exists for network: " + network.getUuid());
14981498
}
14991499

@@ -1519,7 +1519,7 @@ public UserVm addNicToVirtualMachine(AddNicToVMCmd cmd) throws InvalidParameterV
15191519
vmInstance, dc, network, dataCenterDao.findById(network.getDataCenterId())));
15201520
}
15211521

1522-
if(_networkModel.getNicInNetwork(vmInstance.getId(),network.getId()) != null){
1522+
if (_networkModel.getNicInNetwork(vmInstance.getId(),network.getId()) != null) {
15231523
logger.debug("Instance {} already in network {} going to add another NIC", vmInstance, network);
15241524
} else {
15251525
//* get all vms hostNames in the network
@@ -1547,7 +1547,7 @@ public UserVm addNicToVirtualMachine(AddNicToVMCmd cmd) throws InvalidParameterV
15471547
} catch (ConcurrentOperationException e) {
15481548
throw new CloudRuntimeException("Concurrent operations on adding NIC to " + vmInstance + ": " + e);
15491549
} finally {
1550-
if(cleanUp) {
1550+
if (cleanUp) {
15511551
try {
15521552
_itMgr.removeVmFromNetwork(vmInstance, network, null);
15531553
} catch (ResourceUnavailableException e) {
@@ -2295,7 +2295,7 @@ public HashMap<String, VolumeStatsEntry> getVolumeStatistics(long clusterId, Str
22952295
answer = _agentMgr.easySend(neighbor.getId(), cmd);
22962296
}
22972297

2298-
if (answer != null && answer instanceof GetVolumeStatsAnswer){
2298+
if (answer != null && answer instanceof GetVolumeStatsAnswer) {
22992299
GetVolumeStatsAnswer volstats = (GetVolumeStatsAnswer)answer;
23002300
if (volstats.getVolumeStats() != null) {
23012301
volumeStatsByUuid.putAll(volstats.getVolumeStats());
@@ -2306,7 +2306,7 @@ public HashMap<String, VolumeStatsEntry> getVolumeStatistics(long clusterId, Str
23062306
return volumeStatsByUuid.size() > 0 ? volumeStatsByUuid : null;
23072307
}
23082308

2309-
private List<String> getVolumesByHost(HostVO host, StoragePool pool){
2309+
private List<String> getVolumesByHost(HostVO host, StoragePool pool) {
23102310
List<VMInstanceVO> vmsPerHost = _vmInstanceDao.listByHostId(host.getId());
23112311
return vmsPerHost.stream()
23122312
.flatMap(vm -> _volsDao.findNonDestroyedVolumesByInstanceIdAndPoolId(vm.getId(),pool.getId()).stream().map(vol ->
@@ -2602,7 +2602,7 @@ private void transitionExpungingToError(long vmId) {
26022602
*/
26032603
private void releaseNetworkResourcesOnExpunge(long id) throws ConcurrentOperationException, ResourceUnavailableException {
26042604
final VMInstanceVO vmInstance = _vmDao.findById(id);
2605-
if (vmInstance != null){
2605+
if (vmInstance != null) {
26062606
final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vmInstance);
26072607
_networkMgr.release(profile, false);
26082608
}
@@ -2867,17 +2867,17 @@ private void adjustVmLimits(Account owner, UserVmVO vmInstance, ServiceOfferingV
28672867
) {
28682868
if (newCpu > currentCpu) {
28692869
_resourceLimitMgr.incrementVmCpuResourceCount(owner.getAccountId(), vmInstance.isDisplay(), svcOffering, template, newCpu - currentCpu);
2870-
} else if (newCpu > 0 && currentCpu > newCpu){
2870+
} else if (newCpu > 0 && currentCpu > newCpu) {
28712871
_resourceLimitMgr.decrementVmCpuResourceCount(owner.getAccountId(), vmInstance.isDisplay(), svcOffering, template, currentCpu - newCpu);
28722872
}
28732873
if (newMemory > currentMemory) {
28742874
_resourceLimitMgr.incrementVmMemoryResourceCount(owner.getAccountId(), vmInstance.isDisplay(), svcOffering, template, newMemory - currentMemory);
2875-
} else if (newMemory > 0 && currentMemory > newMemory){
2875+
} else if (newMemory > 0 && currentMemory > newMemory) {
28762876
_resourceLimitMgr.decrementVmMemoryResourceCount(owner.getAccountId(), vmInstance.isDisplay(), svcOffering, template, currentMemory - newMemory);
28772877
}
28782878
if (newGpu > currentGpu) {
28792879
_resourceLimitMgr.incrementVmGpuResourceCount(owner.getAccountId(), vmInstance.isDisplay(), svcOffering, template, newGpu - currentGpu);
2880-
} else if (newGpu > 0 && currentGpu > newGpu){
2880+
} else if (newGpu > 0 && currentGpu > newGpu) {
28812881
_resourceLimitMgr.decrementVmGpuResourceCount(owner.getAccountId(), vmInstance.isDisplay(), svcOffering, template, currentGpu - newGpu);
28822882
}
28832883
}
@@ -2931,7 +2931,7 @@ public UserVm updateVirtualMachine(UpdateVMCmd cmd) throws ResourceUnavailableEx
29312931
.map(item -> (item).trim())
29322932
.collect(Collectors.toList());
29332933
List<VMInstanceDetailVO> existingDetails = vmInstanceDetailsDao.listDetails(id);
2934-
if (cleanupDetails){
2934+
if (cleanupDetails) {
29352935
if (template != null && template.isDeployAsIs()) {
29362936
throw new InvalidParameterValueException("Detail settings are read from OVA, it cannot be cleaned up by API call.");
29372937
}
@@ -2991,7 +2991,7 @@ public UserVm updateVirtualMachine(UpdateVMCmd cmd) throws ResourceUnavailableEx
29912991
if (userReadOnlySettings.contains(detailName)) {
29922992
throw new InvalidParameterValueException("You're not allowed to add or edit the read-only setting: " + detailName);
29932993
}
2994-
if (existingDetails.stream().anyMatch(d -> Objects.equals(d.getName(), detailName) && !d.isDisplay())){
2994+
if (existingDetails.stream().anyMatch(d -> Objects.equals(d.getName(), detailName) && !d.isDisplay())) {
29952995
throw new InvalidParameterValueException("You're not allowed to add or edit the non-displayable setting: " + detailName);
29962996
}
29972997
}
@@ -3090,25 +3090,24 @@ protected void validateGuestOsIdForUpdateVirtualMachineCommand(UpdateVMCmd cmd)
30903090
private void saveUsageEvent(UserVmVO vm) {
30913091

30923092
// If vm not destroyed
3093-
if( vm.getState() != State.Destroyed && vm.getState() != State.Expunging && vm.getState() != State.Error){
3093+
if (vm.getState() != State.Destroyed && vm.getState() != State.Expunging && vm.getState() != State.Error) {
30943094

3095-
if(vm.isDisplayVm()){
3095+
if (vm.isDisplayVm()) {
30963096
//1. Allocated VM Usage Event
30973097
generateUsageEvent(vm, true, EventTypes.EVENT_VM_CREATE);
30983098

3099-
if(vm.getState() == State.Running || vm.getState() == State.Stopping){
3099+
if (vm.getState() == State.Running || vm.getState() == State.Stopping) {
31003100
//2. Running VM Usage Event
31013101
generateUsageEvent(vm, true, EventTypes.EVENT_VM_START);
31023102

31033103
// 3. Network offering usage
31043104
generateNetworkUsageForVm(vm, true, EventTypes.EVENT_NETWORK_OFFERING_ASSIGN);
31053105
}
3106-
3107-
}else {
3106+
} else {
31083107
//1. Allocated VM Usage Event
31093108
generateUsageEvent(vm, true, EventTypes.EVENT_VM_DESTROY);
31103109

3111-
if(vm.getState() == State.Running || vm.getState() == State.Stopping){
3110+
if (vm.getState() == State.Running || vm.getState() == State.Stopping) {
31123111
//2. Running VM Usage Event
31133112
generateUsageEvent(vm, true, EventTypes.EVENT_VM_STOP);
31143113

@@ -3120,8 +3119,7 @@ private void saveUsageEvent(UserVmVO vm) {
31203119

31213120
}
31223121

3123-
private void generateNetworkUsageForVm(VirtualMachine vm, boolean isDisplay, String eventType){
3124-
3122+
private void generateNetworkUsageForVm(VirtualMachine vm, boolean isDisplay, String eventType) {
31253123
List<NicVO> nics = _nicDao.listByVmId(vm.getId());
31263124
for (NicVO nic : nics) {
31273125
NetworkVO network = _networkDao.findById(nic.getNetworkId());
@@ -3146,9 +3144,9 @@ public UserVm updateVirtualMachine(long id, String displayName, String group, Bo
31463144
throw new CloudRuntimeException("Unable to find virtual machine with id " + id);
31473145
}
31483146

3149-
if(instanceName != null){
3147+
if (instanceName != null) {
31503148
VMInstanceVO vmInstance = _vmInstanceDao.findVMByInstanceName(instanceName);
3151-
if(vmInstance != null && vmInstance.getId() != id){
3149+
if (vmInstance != null && vmInstance.getId() != id) {
31523150
throw new CloudRuntimeException("Instance name : " + instanceName + " is not unique");
31533151
}
31543152
}
@@ -3290,7 +3288,7 @@ private void checkAndUpdateSecurityGroupForVM(List<Long> securityGroupIdList, Us
32903288
networkIds = networks.stream().map(Network::getId).collect(Collectors.toList());
32913289
}
32923290
} catch (InvalidParameterValueException e) {
3293-
if(logger.isDebugEnabled()) {
3291+
if (logger.isDebugEnabled()) {
32943292
logger.debug(e.getMessage(),e);
32953293
}
32963294
}
@@ -5152,7 +5150,7 @@ public void validateRootDiskResize(final HypervisorType hypervisorType, Long roo
51525150

51535151

51545152
@Override
5155-
public void generateUsageEvent(VirtualMachine vm, boolean isDisplay, String eventType){
5153+
public void generateUsageEvent(VirtualMachine vm, boolean isDisplay, String eventType) {
51565154
ServiceOfferingVO serviceOffering = serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
51575155
if (!serviceOffering.isDynamic()) {
51585156
UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(),
@@ -5408,7 +5406,7 @@ public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, Depl
54085406
}
54095407
// add userdata info into vm profile
54105408
Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
5411-
if(defaultNic != null) {
5409+
if (defaultNic != null) {
54125410
Network network = _networkModel.getNetwork(defaultNic.getNetworkId());
54135411
if (_networkModel.isSharedNetworkWithoutServices(network.getId())) {
54145412
final String serviceOffering = serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()).getDisplayText();
@@ -5659,7 +5657,7 @@ public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOpe
56595657
try {
56605658
VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
56615659

5662-
if(forced) {
5660+
if (forced) {
56635661
status = vmEntity.stopForced(Long.toString(userId));
56645662
} else {
56655663
status = vmEntity.stop(Long.toString(userId));
@@ -5839,7 +5837,7 @@ public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMach
58395837
params = createParameterInParameterMap(params, additionalParams, VirtualMachineProfile.Param.VmPassword, password);
58405838
}
58415839

5842-
if(additionalParams.containsKey(VirtualMachineProfile.Param.BootIntoSetup)) {
5840+
if (additionalParams.containsKey(VirtualMachineProfile.Param.BootIntoSetup)) {
58435841
if (! HypervisorType.VMware.equals(vm.getHypervisorType())) {
58445842
throw new InvalidParameterValueException(ApiConstants.BOOT_INTO_SETUP + " makes no sense for " + vm.getHypervisorType());
58455843
}
@@ -6317,8 +6315,8 @@ private void verifyServiceOffering(BaseDeployVMCmd cmd, ServiceOffering serviceO
63176315
}
63186316

63196317
if (!serviceOffering.isDynamic()) {
6320-
for(String detail: cmd.getDetails().keySet()) {
6321-
if(detail.equalsIgnoreCase(VmDetailConstants.CPU_NUMBER) || detail.equalsIgnoreCase(VmDetailConstants.CPU_SPEED) || detail.equalsIgnoreCase(VmDetailConstants.MEMORY)) {
6318+
for (String detail: cmd.getDetails().keySet()) {
6319+
if (detail.equalsIgnoreCase(VmDetailConstants.CPU_NUMBER) || detail.equalsIgnoreCase(VmDetailConstants.CPU_SPEED) || detail.equalsIgnoreCase(VmDetailConstants.MEMORY)) {
63226320
throw new InvalidParameterValueException("cpuNumber or cpuSpeed or memory should not be specified for static service offering");
63236321
}
63246322
}
@@ -6537,8 +6535,8 @@ private UserVm createVirtualMachine(BaseDeployVMCmd cmd, DataCenter zone, Accoun
65376535

65386536
// check if this templateId has a child ISO
65396537
List<VMTemplateVO> child_templates = _templateDao.listByParentTemplatetId(template.getId());
6540-
for (VMTemplateVO tmpl: child_templates){
6541-
if (tmpl.getFormat() == Storage.ImageFormat.ISO){
6538+
for (VMTemplateVO tmpl: child_templates) {
6539+
if (tmpl.getFormat() == Storage.ImageFormat.ISO) {
65426540
logger.info("MDOV trying to attach disk {} to the VM {}", tmpl, vm);
65436541
_tmplService.attachIso(tmpl.getId(), vm.getId(), true);
65446542
}
@@ -7195,7 +7193,7 @@ public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) thr
71957193

71967194
checkIfHostOfVMIsInPrepareForMaintenanceState(vm, "Migrate");
71977195

7198-
if(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
7196+
if (serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
71997197
throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
72007198
}
72017199

@@ -7810,7 +7808,7 @@ public VirtualMachine migrateVirtualMachineWithVolume(Long vmId, Host destinatio
78107808
throw ex;
78117809
}
78127810

7813-
if(serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
7811+
if (serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
78147812
throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
78157813
}
78167814

@@ -9221,8 +9219,14 @@ private void handleManagedStorage(UserVmVO vm, VolumeVO root) {
92219219
Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
92229220

92239221
if (hostId != null) {
9224-
VolumeInfo volumeInfo = volFactory.getVolume(root.getId());
9222+
// default findById() won't search entries with removed field not null
92259223
Host host = _hostDao.findById(hostId);
9224+
if (host == null) {
9225+
logger.warn("Host {} not found", hostId);
9226+
return;
9227+
}
9228+
9229+
VolumeInfo volumeInfo = volFactory.getVolume(root.getId());
92269230

92279231
final Command cmd;
92289232

@@ -9978,7 +9982,7 @@ private void collectVmDiskAndNetworkStatistics(UserVm vm, State expectedState) {
99789982
}
99799983
}
99809984

9981-
public Boolean getDestroyRootVolumeOnVmDestruction(Long domainId){
9985+
public Boolean getDestroyRootVolumeOnVmDestruction(Long domainId) {
99829986
return DestroyRootVolumeOnVmDestruction.valueIn(domainId);
99839987
}
99849988

0 commit comments

Comments
 (0)