From 8f9f39fa39867467d73b58cd4b7de118cd8fa47f Mon Sep 17 00:00:00 2001 From: wilderrodrigues Date: Fri, 12 Dec 2014 15:44:36 +0100 Subject: [PATCH] [TK-3119] Fix NPEs and improve exception handling + error messages --- .../cloud/vm/VirtualMachineManagerImpl.java | 1595 +++++++++-------- .../VirtualNetworkApplianceManagerImpl.java | 35 +- 2 files changed, 830 insertions(+), 800 deletions(-) diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java index 58e80302a0e..d6b2da5f45e 100644 --- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -38,9 +38,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import com.cloud.network.router.VirtualRouter; -import org.apache.log4j.Logger; - import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; @@ -69,6 +66,7 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; @@ -149,6 +147,7 @@ import com.cloud.network.Network; import com.cloud.network.NetworkModel; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; +import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.RulesManager; import com.cloud.offering.DiskOfferingInfo; import com.cloud.offering.ServiceOffering; @@ -284,7 +283,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return hostAllocators; } - public void setHostAllocators(List hostAllocators) { + public void setHostAllocators(final List hostAllocators) { this.hostAllocators = hostAllocators; } @@ -358,7 +357,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac protected long _nodeId; @Override - public void registerGuru(VirtualMachine.Type type, VirtualMachineGuru guru) { + public void registerGuru(final VirtualMachine.Type type, final VirtualMachineGuru guru) { synchronized (_vmGurus) { _vmGurus.put(type, guru); } @@ -366,12 +365,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override @DB - public void allocate(String vmInstanceName, final VirtualMachineTemplate template, ServiceOffering serviceOffering, + public void allocate(final String vmInstanceName, final VirtualMachineTemplate template, final ServiceOffering serviceOffering, final DiskOfferingInfo rootDiskOfferingInfo, final List dataDiskOfferings, - final LinkedHashMap> auxiliaryNetworks, DeploymentPlan plan, HypervisorType hyperType) + final LinkedHashMap> auxiliaryNetworks, final DeploymentPlan plan, final HypervisorType hyperType) throws InsufficientCapacityException { - VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName); + final VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName); final Account owner = _entityMgr.findById(Account.class, vm.getAccountId()); if (s_logger.isDebugEnabled()) { @@ -382,78 +381,79 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (plan.getPodId() != null) { vm.setPodIdToDeployIn(plan.getPodId()); } - assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet"; + assert plan.getClusterId() == null && plan.getPoolId() == null : "We currently don't support cluster and pool preset yet"; final VMInstanceVO vmFinal = _vmDao.persist(vm); - final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmFinal, template, serviceOffering, null, null); + final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmFinal, template, serviceOffering, null, null); - Transaction.execute(new TransactionCallbackWithExceptionNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientCapacityException { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Allocating nics for " + vmFinal); - } + Transaction.execute(new TransactionCallbackWithExceptionNoReturn() { + @Override + public void doInTransactionWithoutResult(final TransactionStatus status) throws InsufficientCapacityException { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Allocating nics for " + vmFinal); + } - try { - _networkMgr.allocate(vmProfile, auxiliaryNetworks); - } catch (ConcurrentOperationException e) { - throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Allocating disks for " + vmFinal); - } - - if (template.getFormat() == ImageFormat.ISO) { - volumeMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), rootDiskOfferingInfo.getSize(), - rootDiskOfferingInfo.getMinIops(), rootDiskOfferingInfo.getMaxIops(), vmFinal, template, owner); - } else if (template.getFormat() == ImageFormat.BAREMETAL) { - // Do nothing - } else { - volumeMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), rootDiskOfferingInfo.getSize(), - rootDiskOfferingInfo.getMinIops(), rootDiskOfferingInfo.getMaxIops(), template, vmFinal, owner); - } - - if (dataDiskOfferings != null) { - for (DiskOfferingInfo dataDiskOfferingInfo : dataDiskOfferings) { - volumeMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vmFinal.getId(), dataDiskOfferingInfo.getDiskOffering(), dataDiskOfferingInfo.getSize(), - dataDiskOfferingInfo.getMinIops(), dataDiskOfferingInfo.getMaxIops(), vmFinal, template, owner); - } - } - } - }); + try { + _networkMgr.allocate(vmProfile, auxiliaryNetworks); + } catch (final ConcurrentOperationException e) { + throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e); + } if (s_logger.isDebugEnabled()) { - s_logger.debug("Allocation completed for VM: " + vmFinal); + s_logger.debug("Allocating disks for " + vmFinal); } + + if (template.getFormat() == ImageFormat.ISO) { + volumeMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), rootDiskOfferingInfo.getSize(), + rootDiskOfferingInfo.getMinIops(), rootDiskOfferingInfo.getMaxIops(), vmFinal, template, owner); + } else if (template.getFormat() == ImageFormat.BAREMETAL) { + // Do nothing + } else { + volumeMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), rootDiskOfferingInfo.getSize(), + rootDiskOfferingInfo.getMinIops(), rootDiskOfferingInfo.getMaxIops(), template, vmFinal, owner); + } + + if (dataDiskOfferings != null) { + for (final DiskOfferingInfo dataDiskOfferingInfo : dataDiskOfferings) { + volumeMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vmFinal.getId(), dataDiskOfferingInfo.getDiskOffering(), dataDiskOfferingInfo.getSize(), + dataDiskOfferingInfo.getMinIops(), dataDiskOfferingInfo.getMaxIops(), vmFinal, template, owner); + } + } + } + }); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Allocation completed for VM: " + vmFinal); + } } @Override - public void allocate(String vmInstanceName, VirtualMachineTemplate template, ServiceOffering serviceOffering, - LinkedHashMap> networks, DeploymentPlan plan, HypervisorType hyperType) throws InsufficientCapacityException { + public void allocate(final String vmInstanceName, final VirtualMachineTemplate template, final ServiceOffering serviceOffering, + final LinkedHashMap> networks, final DeploymentPlan plan, final HypervisorType hyperType) throws InsufficientCapacityException { allocate(vmInstanceName, template, serviceOffering, new DiskOfferingInfo(serviceOffering), new ArrayList(), networks, plan, hyperType); } - private VirtualMachineGuru getVmGuru(VirtualMachine vm) { - if(vm != null) + private VirtualMachineGuru getVmGuru(final VirtualMachine vm) { + if(vm != null) { return _vmGurus.get(vm.getType()); + } return null; } @Override - public void expunge(String vmUuid) throws ResourceUnavailableException { + public void expunge(final String vmUuid) throws ResourceUnavailableException { try { advanceExpunge(vmUuid); - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { throw new CloudRuntimeException("Operation timed out", e); - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation ", e); } } @Override - public void advanceExpunge(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + public void advanceExpunge(final String vmUuid) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); advanceExpunge(vm); } @@ -474,7 +474,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new CloudRuntimeException("Unable to destroy " + vm); } - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); throw new CloudRuntimeException("Unable to destroy " + vm, e); } @@ -483,31 +483,31 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.debug("Destroying vm " + vm); } - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); s_logger.debug("Cleaning up NICS"); - List nicExpungeCommands = hvGuru.finalizeExpungeNics(vm, profile.getNics()); + final List nicExpungeCommands = hvGuru.finalizeExpungeNics(vm, profile.getNics()); _networkMgr.cleanupNics(profile); s_logger.debug("Cleaning up hypervisor data structures (ex. SRs in XenServer) for managed storage"); - List volumeExpungeCommands = hvGuru.finalizeExpungeVolumes(vm); + final List volumeExpungeCommands = hvGuru.finalizeExpungeVolumes(vm); - Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); + final Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); if (volumeExpungeCommands != null && volumeExpungeCommands.size() > 0 && hostId != null) { - Commands cmds = new Commands(Command.OnError.Stop); + final Commands cmds = new Commands(Command.OnError.Stop); - for (Command volumeExpungeCommand : volumeExpungeCommands) { + for (final Command volumeExpungeCommand : volumeExpungeCommands) { cmds.addCommand(volumeExpungeCommand); } _agentMgr.send(hostId, cmds); if (!cmds.isSuccessful()) { - for (Answer answer : cmds.getAnswers()) { + for (final Answer answer : cmds.getAnswers()) { if (!answer.getResult()) { s_logger.warn("Failed to expunge vm due to: " + answer.getDetails()); @@ -524,27 +524,27 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // Clean up volumes based on the vm's instance id volumeMgr.cleanupVolumes(vm.getId()); - VirtualMachineGuru guru = getVmGuru(vm); + final VirtualMachineGuru guru = getVmGuru(vm); guru.finalizeExpunge(vm); //remove the overcommit detials from the uservm details _uservmDetailsDao.removeDetails(vm.getId()); // send hypervisor-dependent commands before removing - List finalizeExpungeCommands = hvGuru.finalizeExpunge(vm); + final List finalizeExpungeCommands = hvGuru.finalizeExpunge(vm); if (finalizeExpungeCommands != null && finalizeExpungeCommands.size() > 0) { if (hostId != null) { - Commands cmds = new Commands(Command.OnError.Stop); - for (Command command : finalizeExpungeCommands) { + final Commands cmds = new Commands(Command.OnError.Stop); + for (final Command command : finalizeExpungeCommands) { cmds.addCommand(command); } if (nicExpungeCommands != null) { - for (Command command : nicExpungeCommands) { + for (final Command command : nicExpungeCommands) { cmds.addCommand(command); } } _agentMgr.send(hostId, cmds); if (!cmds.isSuccessful()) { - for (Answer answer : cmds.getAnswers()) { + for (final Answer answer : cmds.getAnswers()) { if (!answer.getResult()) { s_logger.warn("Failed to expunge vm due to: " + answer.getDetails()); throw new CloudRuntimeException("Unable to expunge " + vm + " due to " + answer.getDetails()); @@ -579,7 +579,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public boolean configure(String name, Map xmlParams) throws ConfigurationException { + public boolean configure(final String name, final Map xmlParams) throws ConfigurationException { ReservationContextImpl.init(_entityMgr); VirtualMachineProfileImpl.init(_entityMgr); VmWorkMigrate.init(_entityMgr); @@ -599,19 +599,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void start(String vmUuid, Map params) { + public void start(final String vmUuid, final Map params) { start(vmUuid, params, null, null); } @Override - public void start(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) { + public void start(final String vmUuid, final Map params, final DeploymentPlan planToDeploy, final DeploymentPlanner planner) { try { advanceStart(vmUuid, params, planToDeploy, planner); - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e).add(VirtualMachine.class, vmUuid); - } catch (InsufficientCapacityException e) { + } catch (final InsufficientCapacityException e) { throw new CloudRuntimeException("Unable to start a VM due to insufficient capacity", e).add(VirtualMachine.class, vmUuid); - } catch (ResourceUnavailableException e) { + } catch (final ResourceUnavailableException e) { if(e.getScope() != null && e.getScope().equals(VirtualRouter.class)){ throw new CloudRuntimeException("Network is unavailable. Please contact administrator", e).add(VirtualMachine.class, vmUuid); } @@ -620,9 +620,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } - protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException { + protected boolean checkWorkItems(final VMInstanceVO vm, final State state) throws ConcurrentOperationException { while (true) { - ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state); + final ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state); if (vo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state); @@ -638,7 +638,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } // also check DB to get latest VM state to detect vm update from concurrent process before idle waiting to get an early exit - VMInstanceVO instance = _vmDao.findById(vm.getId()); + final VMInstanceVO instance = _vmDao.findById(vm.getId()); if (instance != null && instance.getState() == State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already started in DB: " + vm); @@ -653,7 +653,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { Thread.sleep(VmOpWaitInterval.value()*1000); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { s_logger.info("Waiting for " + vm + " but is interrupted"); throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted"); } @@ -663,22 +663,22 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @DB - protected Ternary changeToStartState(VirtualMachineGuru vmGuru, final VMInstanceVO vm, final User caller, + protected Ternary changeToStartState(final VirtualMachineGuru vmGuru, final VMInstanceVO vm, final User caller, final Account account) throws ConcurrentOperationException { - long vmId = vm.getId(); + final long vmId = vm.getId(); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId()); int retry = VmOpLockStateRetry.value(); while (retry-- != 0) { try { final ItWorkVO workFinal = work; - Ternary result = + final Ternary result = Transaction.execute(new TransactionCallbackWithException, NoTransitionException>() { @Override - public Ternary doInTransaction(TransactionStatus status) throws NoTransitionException { - Journal journal = new Journal.LogJournal("Creating " + vm, s_logger); - ItWorkVO work = _workDao.persist(workFinal); - ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account); + public Ternary doInTransaction(final TransactionStatus status) throws NoTransitionException { + final Journal journal = new Journal.LogJournal("Creating " + vm, s_logger); + final ItWorkVO work = _workDao.persist(workFinal); + final ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account); if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) { if (s_logger.isDebugEnabled()) { @@ -692,15 +692,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac }); work = result.third(); - if (result.first() != null) + if (result.first() != null) { return result; - } catch (NoTransitionException e) { + } + } catch (final NoTransitionException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to transition into Starting state due to " + e.getMessage()); } } - VMInstanceVO instance = _vmDao.findById(vmId); + final VMInstanceVO instance = _vmDao.findById(vmId); if (instance == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + vm); } @@ -709,7 +710,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ". Retry=" + retry); } - State state = instance.getState(); + final State state = instance.getState(); if (state == State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already started: " + vm); @@ -734,9 +735,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new ConcurrentOperationException("Unable to change the state of " + vm); } - protected boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) throws NoTransitionException { + protected boolean changeState(final T vm, final Event event, final Long hostId, final ItWorkVO work, final Step step) throws NoTransitionException { // FIXME: We should do this better. - Step previousStep = work.getStep(); + final Step previousStep = work.getStep(); _workDao.updateStep(work, step); boolean result = false; try { @@ -749,9 +750,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - protected boolean areAffinityGroupsAssociated(VirtualMachineProfile vmProfile) { - VirtualMachine vm = vmProfile.getVirtualMachine(); - long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId()); + protected boolean areAffinityGroupsAssociated(final VirtualMachineProfile vmProfile) { + final VirtualMachine vm = vmProfile.getVirtualMachine(); + final long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId()); if (vmGroupCount > 0) { return true; @@ -760,20 +761,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void advanceStart(String vmUuid, Map params, DeploymentPlanner planner) + public void advanceStart(final String vmUuid, final Map params, final DeploymentPlanner planner) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { advanceStart(vmUuid, params, null, planner); } @Override - public void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) + public void advanceStart(final String vmUuid, final Map params, final DeploymentPlan planToDeploy, final DeploymentPlanner planner) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if ( jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { orchestrateStart(vmUuid, params, planToDeploy, planner); @@ -783,57 +784,58 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } } else { - Outcome outcome = startVmThroughJobQueue(vmUuid, params, planToDeploy, planner); + final Outcome outcome = startVmThroughJobQueue(vmUuid, params, planToDeploy, planner); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof ConcurrentOperationException) + if (jobResult instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobResult; - else if (jobResult instanceof ResourceUnavailableException) + } else if (jobResult instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobResult; - else if (jobResult instanceof InsufficientCapacityException) + } else if (jobResult instanceof InsufficientCapacityException) { throw (InsufficientCapacityException)jobResult; - else if (jobResult instanceof RuntimeException) + } else if (jobResult instanceof RuntimeException) { throw (RuntimeException)jobResult; - else if (jobResult instanceof Throwable) + } else if (jobResult instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } } } } @Override - public void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) + public void orchestrateStart(final String vmUuid, final Map params, final DeploymentPlan planToDeploy, final DeploymentPlanner planner) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { - CallContext cctxt = CallContext.current(); - Account account = cctxt.getCallingAccount(); - User caller = cctxt.getCallingUser(); + final CallContext cctxt = CallContext.current(); + final Account account = cctxt.getCallingAccount(); + final User caller = cctxt.getCallingUser(); VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - VirtualMachineGuru vmGuru = getVmGuru(vm); + final VirtualMachineGuru vmGuru = getVmGuru(vm); - Ternary start = changeToStartState(vmGuru, vm, caller, account); + final Ternary start = changeToStartState(vmGuru, vm, caller, account); if (start == null) { return; } vm = start.first(); - ReservationContext ctx = start.second(); + final ReservationContext ctx = start.second(); ItWorkVO work = start.third(); VMInstanceVO startedVm = null; - ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()); - VirtualMachineTemplate template = _entityMgr.findByIdIncludingRemoved(VirtualMachineTemplate.class, vm.getTemplateId()); + final ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()); + final VirtualMachineTemplate template = _entityMgr.findByIdIncludingRemoved(VirtualMachineTemplate.class, vm.getTemplateId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to deploy VM, vm has dcId: " + vm.getDataCenterId() + " and podId: " + vm.getPodIdToDeployIn()); @@ -849,12 +851,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac planToDeploy.getPoolId(), planToDeploy.getPhysicalNetworkId(), ctx); } - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); boolean canRetry = true; ExcludeList avoids = null; try { - Journal journal = start.second().getJournal(); + final Journal journal = start.second().getJournal(); if (planToDeploy != null) { avoids = planToDeploy.getAvoids(); @@ -868,19 +870,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac boolean planChangedByVolume = false; boolean reuseVolume = true; - DataCenterDeployment originalPlan = plan; + final DataCenterDeployment originalPlan = plan; int retry = StartRetry.value(); while (retry-- != 0) { // It's != so that it can match -1. if (reuseVolume) { // edit plan if this vm's ROOT volume is in READY state already - List vols = _volsDao.findReadyRootVolumesByInstance(vm.getId()); - for (VolumeVO vol : vols) { + final List vols = _volsDao.findReadyRootVolumesByInstance(vm.getId()); + for (final VolumeVO vol : vols) { // make sure if the templateId is unchanged. If it is changed, // let planner // reassign pool for the volume even if it ready. - Long volTemplateId = vol.getTemplateId(); + final Long volTemplateId = vol.getTemplateId(); if (volTemplateId != null && volTemplateId.longValue() != template.getId()) { if (s_logger.isDebugEnabled()) { s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool"); @@ -888,16 +890,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac continue; } - StoragePool pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(vol.getPoolId()); + final StoragePool pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(vol.getPoolId()); if (!pool.isInMaintenance()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Root volume is ready, need to place VM in volume's cluster"); } - long rootVolDcId = pool.getDataCenterId(); - Long rootVolPodId = pool.getPodId(); - Long rootVolClusterId = pool.getClusterId(); + final long rootVolDcId = pool.getDataCenterId(); + final Long rootVolPodId = pool.getPodId(); + final Long rootVolClusterId = pool.getClusterId(); if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) { - Long clusterIdSpecified = planToDeploy.getClusterId(); + final Long clusterIdSpecified = planToDeploy.getClusterId(); if (clusterIdSpecified != null && rootVolClusterId != null) { if (rootVolClusterId.longValue() != clusterIdSpecified.longValue()) { // cannot satisfy the plan passed in to the @@ -926,12 +928,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - Account owner = _entityMgr.findById(Account.class, vm.getAccountId()); - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, params); + final Account owner = _entityMgr.findById(Account.class, vm.getAccountId()); + final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, params); DeployDestination dest = null; try { dest = _dpMgr.planDeployment(vmProfile, plan, avoids, planner); - } catch (AffinityConflictException e2) { + } catch (final AffinityConflictException e2) { s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2); throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict"); @@ -956,12 +958,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac long destHostId = dest.getHost().getId(); vm.setPodIdToDeployIn(dest.getPod().getId()); - Long cluster_id = dest.getCluster().getId(); - ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio"); - ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio"); + final Long cluster_id = dest.getCluster().getId(); + final ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio"); + final ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio"); //storing the value of overcommit in the vm_details table for doing a capacity check in case the cluster overcommit ratio is changed. if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") == null && - ((Float.parseFloat(cluster_detail_cpu.getValue()) > 1f || Float.parseFloat(cluster_detail_ram.getValue()) > 1f))) { + (Float.parseFloat(cluster_detail_cpu.getValue()) > 1f || Float.parseFloat(cluster_detail_ram.getValue()) > 1f)) { _uservmDetailsDao.addDetail(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue(), true); _uservmDetailsDao.addDetail(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue(), true); } else if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") != null) { @@ -976,7 +978,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) { throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine"); } - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { throw new ConcurrentOperationException(e1.getMessage()); } @@ -996,7 +998,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac Commands cmds = null; vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx); - VirtualMachineTO vmTO = hvGuru.implement(vmProfile); + final VirtualMachineTO vmTO = hvGuru.implement(vmProfile); handlePath(vmTO.getDisks(), vm.getHypervisorType()); @@ -1021,9 +1023,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac startAnswer = cmds.getAnswer(StartAnswer.class); if (startAnswer != null && startAnswer.getResult()) { handlePath(vmTO.getDisks(), startAnswer.getIqnToPath()); - String host_guid = startAnswer.getHost_guid(); + final String host_guid = startAnswer.getHost_guid(); if (host_guid != null) { - HostVO finalHost = _resourceMgr.findHostByGuid(host_guid); + final HostVO finalHost = _resourceMgr.findHostByGuid(host_guid); if (finalHost == null) { throw new CloudRuntimeException("Host Guid " + host_guid + " doesn't exist in DB, something wrong here"); } @@ -1037,7 +1039,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } // Update GPU device capacity - GPUDeviceTO gpuDevice = startAnswer.getVirtualMachine().getGpuDevice(); + final GPUDeviceTO gpuDevice = startAnswer.getVirtualMachine().getGpuDevice(); if (gpuDevice != null) { _resourceMgr.updateGPUDetails(destHostId, gpuDevice.getGroupDetails()); } @@ -1052,14 +1054,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.info("The guru did not like the answers so stopping " + vm); } - StopCommand cmd = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false); - Answer answer = _agentMgr.easySend(destHostId, cmd); + final StopCommand cmd = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false); + final Answer answer = _agentMgr.easySend(destHostId, cmd); if (answer != null && answer instanceof StopAnswer) { - StopAnswer stopAns = (StopAnswer)answer; + final StopAnswer stopAns = (StopAnswer)answer; if (vm.getType() == VirtualMachine.Type.User) { - String platform = stopAns.getPlatform(); + final String platform = stopAns.getPlatform(); if (platform != null) { - Map vmmetadata = new HashMap(); + final Map vmmetadata = new HashMap(); vmmetadata.put(vm.getInstanceName(), platform); syncVMMetaData(vmmetadata); } @@ -1079,14 +1081,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac break; } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { s_logger.debug("Unable to send the start command to host " + dest.getHost()); if (e.isActive()) { _haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop); } canRetry = false; throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e); - } catch (ResourceUnavailableException e) { + } catch (final ResourceUnavailableException e) { s_logger.info("Unable to contact resource.", e); if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { @@ -1096,7 +1098,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw e; } } - } catch (InsufficientCapacityException e) { + } catch (final InsufficientCapacityException e) { s_logger.info("Insufficient capacity ", e); if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { @@ -1105,15 +1107,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e); } } - } catch (Exception e) { + } catch (final ExecutionException e) { + s_logger.error("Failed to start instance " + vm, e); + throw new AgentUnavailableException("Unable to start instance due to " + e.getMessage(), destHostId, e); + } catch (final NoTransitionException e) { s_logger.error("Failed to start instance " + vm, e); throw new AgentUnavailableException("Unable to start instance due to " + e.getMessage(), destHostId, e); } finally { if (startedVm == null && canRetry) { - Step prevStep = work.getStep(); + final Step prevStep = work.getStep(); _workDao.updateStep(work, Step.Release); // If previous step was started/ing && we got a valid answer - if ((prevStep == Step.Started || prevStep == Step.Starting) && (startAnswer != null && startAnswer.getResult())) { //TODO check the response of cleanup and record it in DB for retry + if ((prevStep == Step.Started || prevStep == Step.Starting) && startAnswer != null && startAnswer.getResult()) { //TODO check the response of cleanup and record it in DB for retry cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false); } else { //if step is not starting/started, send cleanup command with force=true @@ -1127,7 +1132,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (canRetry) { try { changeState(vm, Event.OperationFailed, null, work, Step.Done); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { throw new ConcurrentOperationException(e.getMessage()); } } @@ -1144,24 +1149,24 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } // for managed storage on KVM, need to make sure the path field of the volume in question is populated with the IQN - private void handlePath(DiskTO[] disks, HypervisorType hypervisorType) { + private void handlePath(final DiskTO[] disks, final HypervisorType hypervisorType) { if (hypervisorType != HypervisorType.KVM) { return; } if (disks != null) { - for (DiskTO disk : disks) { - Map details = disk.getDetails(); - boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + for (final DiskTO disk : disks) { + final Map details = disk.getDetails(); + final boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); if (isManaged && disk.getPath() == null) { - Long volumeId = disk.getData().getId(); - VolumeVO volume = _volsDao.findById(volumeId); + final Long volumeId = disk.getData().getId(); + final VolumeVO volume = _volsDao.findById(volumeId); disk.setPath(volume.get_iScsiName()); if (disk.getData() instanceof VolumeObjectTO) { - VolumeObjectTO volTo = (VolumeObjectTO)disk.getData(); + final VolumeObjectTO volTo = (VolumeObjectTO)disk.getData(); volTo.setPath(volume.get_iScsiName()); } @@ -1175,17 +1180,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } // for managed storage on XenServer and VMware, need to update the DB with a path if the VDI/VMDK file was newly created - private void handlePath(DiskTO[] disks, Map iqnToPath) { + private void handlePath(final DiskTO[] disks, final Map iqnToPath) { if (disks != null && iqnToPath != null) { - for (DiskTO disk : disks) { - Map details = disk.getDetails(); - boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + for (final DiskTO disk : disks) { + final Map details = disk.getDetails(); + final boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); if (isManaged) { - Long volumeId = disk.getData().getId(); - VolumeVO volume = _volsDao.findById(volumeId); - String iScsiName = volume.get_iScsiName(); - String path = iqnToPath.get(iScsiName); + final Long volumeId = disk.getData().getId(); + final VolumeVO volume = _volsDao.findById(volumeId); + final String iScsiName = volume.get_iScsiName(); + final String path = iqnToPath.get(iScsiName); if (path != null) { volume.setPath(path); @@ -1197,13 +1202,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - private void syncDiskChainChange(StartAnswer answer) { - VirtualMachineTO vmSpec = answer.getVirtualMachine(); + private void syncDiskChainChange(final StartAnswer answer) { + final VirtualMachineTO vmSpec = answer.getVirtualMachine(); - for (DiskTO disk : vmSpec.getDisks()) { + for (final DiskTO disk : vmSpec.getDisks()) { if (disk.getType() != Volume.Type.ISO) { - VolumeObjectTO vol = (VolumeObjectTO)disk.getData(); - VolumeVO volume = _volsDao.findById(vol.getId()); + final VolumeObjectTO vol = (VolumeObjectTO)disk.getData(); + final VolumeVO volume = _volsDao.findById(vol.getId()); // Use getPath() from VolumeVO to get a fresh copy of what's in the DB. // Before doing this, in a certain situation, getPath() from VolumeObjectTO @@ -1218,51 +1223,51 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void stop(String vmUuid) throws ResourceUnavailableException { + public void stop(final String vmUuid) throws ResourceUnavailableException { try { advanceStop(vmUuid, false); - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", e.getAgentId(), e); - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e); } } - protected boolean getExecuteInSequence(HypervisorType hypervisorType) { + protected boolean getExecuteInSequence(final HypervisorType hypervisorType) { if (HypervisorType.KVM == hypervisorType || HypervisorType.LXC == hypervisorType || HypervisorType.XenServer == hypervisorType) { return false; } else if(HypervisorType.VMware == hypervisorType) { - Boolean fullClone = HypervisorGuru.VmwareFullClone.value(); + final Boolean fullClone = HypervisorGuru.VmwareFullClone.value(); return fullClone; } else { return ExecuteInSequence.value(); } } - protected boolean sendStop(VirtualMachineGuru guru, VirtualMachineProfile profile, boolean force, boolean checkBeforeCleanup) { - VirtualMachine vm = profile.getVirtualMachine(); - StopCommand stop = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), checkBeforeCleanup); + protected boolean sendStop(final VirtualMachineGuru guru, final VirtualMachineProfile profile, final boolean force, final boolean checkBeforeCleanup) { + final VirtualMachine vm = profile.getVirtualMachine(); + final StopCommand stop = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), checkBeforeCleanup); try { - Answer answer = _agentMgr.send(vm.getHostId(), stop); + final Answer answer = _agentMgr.send(vm.getHostId(), stop); if (answer != null && answer instanceof StopAnswer) { - StopAnswer stopAns = (StopAnswer)answer; + final StopAnswer stopAns = (StopAnswer)answer; if (vm.getType() == VirtualMachine.Type.User) { - String platform = stopAns.getPlatform(); + final String platform = stopAns.getPlatform(); if (platform != null) { - UserVmVO userVm = _userVmDao.findById(vm.getId()); + final UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); } } - GPUDeviceTO gpuDevice = stop.getGpuDevice(); + final GPUDeviceTO gpuDevice = stop.getGpuDevice(); if (gpuDevice != null) { _resourceMgr.updateGPUDetails(vm.getHostId(), gpuDevice.getGroupDetails()); } if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "null answer returned"; + final String details = answer != null ? answer.getDetails() : "null answer returned"; s_logger.debug("Unable to stop VM due to " + details); return false; } @@ -1273,11 +1278,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return false; } - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { if (!force) { return false; } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { if (!force) { return false; } @@ -1286,14 +1291,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return true; } - protected boolean cleanup(VirtualMachineGuru guru, VirtualMachineProfile profile, ItWorkVO work, Event event, boolean cleanUpEvenIfUnableToStop) { - VirtualMachine vm = profile.getVirtualMachine(); - State state = vm.getState(); + protected boolean cleanup(final VirtualMachineGuru guru, final VirtualMachineProfile profile, final ItWorkVO work, final Event event, final boolean cleanUpEvenIfUnableToStop) { + final VirtualMachine vm = profile.getVirtualMachine(); + final State state = vm.getState(); s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state"); try { if (state == State.Starting) { if (work != null) { - Step step = work.getStep(); + final Step step = work.getStep(); if (step == Step.Starting && !cleanUpEvenIfUnableToStop) { s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step); return false; @@ -1311,7 +1316,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) { s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step); return true; - } + } } else { if (vm.getHostId() != null) { if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop, false)) { @@ -1351,7 +1356,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { _networkMgr.release(profile, cleanUpEvenIfUnableToStop); s_logger.debug("Successfully released network resources for the vm " + vm); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Unable to release some network resources.", e); } @@ -1363,15 +1368,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void advanceStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) + public void advanceStop(final String vmUuid, final boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop); @@ -1382,41 +1387,42 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } else { - Outcome outcome = stopVmThroughJobQueue(vmUuid, cleanUpEvenIfUnableToStop); + final Outcome outcome = stopVmThroughJobQueue(vmUuid, cleanUpEvenIfUnableToStop); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof AgentUnavailableException) + if (jobResult instanceof AgentUnavailableException) { throw (AgentUnavailableException)jobResult; - else if (jobResult instanceof ConcurrentOperationException) + } else if (jobResult instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobResult; - else if (jobResult instanceof OperationTimedoutException) + } else if (jobResult instanceof OperationTimedoutException) { throw (OperationTimedoutException)jobResult; - else if (jobResult instanceof RuntimeException) + } else if (jobResult instanceof RuntimeException) { throw (RuntimeException)jobResult; - else if (jobResult instanceof Throwable) + } else if (jobResult instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } } } } - private void orchestrateStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + private void orchestrateStop(final String vmUuid, final boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); advanceStop(vm, cleanUpEvenIfUnableToStop); } - private void advanceStop(VMInstanceVO vm, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, + private void advanceStop(final VMInstanceVO vm, final boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { - State state = vm.getState(); + final State state = vm.getState(); if (state == State.Stopped) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already stopped: " + vm); @@ -1431,13 +1437,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return; } // grab outstanding work item if any - ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); + final ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); if (work != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found an outstanding work item for this vm " + vm + " with state:" + vm.getState() + ", work id:" + work.getId()); } } - Long hostId = vm.getHostId(); + final Long hostId = vm.getHostId(); if (hostId == null) { if (!cleanUpEvenIfUnableToStop) { if (s_logger.isDebugEnabled()) { @@ -1447,7 +1453,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } try { stateTransitTo(vm, Event.AgentReportStopped, null, null); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn(e.getMessage()); } // mark outstanding work item if any as done @@ -1461,18 +1467,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return; } - VirtualMachineGuru vmGuru = getVmGuru(vm); - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final VirtualMachineGuru vmGuru = getVmGuru(vm); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); try { if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) { throw new ConcurrentOperationException("VM is being operated on."); } - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { if (!cleanUpEvenIfUnableToStop) { throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState()); } - boolean doCleanup = true; + final boolean doCleanup = true; if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to transition the state but we're moving on because it's forced stop"); } @@ -1486,7 +1492,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (!changeState(vm, Event.AgentReportStopped, null, work, Step.Done)) { throw new CloudRuntimeException("Unable to stop " + vm); } - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn("Unable to cleanup " + vm); throw new CloudRuntimeException("Unable to stop " + vm, e); } @@ -1505,7 +1511,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac vmGuru.prepareStop(profile); - StopCommand stop = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false); + final StopCommand stop = new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false); boolean stopped = false; Answer answer = null; @@ -1513,11 +1519,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac answer = _agentMgr.send(vm.getHostId(), stop); if (answer != null) { if (answer instanceof StopAnswer) { - StopAnswer stopAns = (StopAnswer)answer; + final StopAnswer stopAns = (StopAnswer)answer; if (vm.getType() == VirtualMachine.Type.User) { - String platform = stopAns.getPlatform(); + final String platform = stopAns.getPlatform(); if (platform != null) { - UserVmVO userVm = _userVmDao.findById(vm.getId()); + final UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); @@ -1529,7 +1535,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails()); } vmGuru.finalizeStop(profile, answer); - GPUDeviceTO gpuDevice = stop.getGpuDevice(); + final GPUDeviceTO gpuDevice = stop.getGpuDevice(); if (gpuDevice != null) { _resourceMgr.updateGPUDetails(vm.getHostId(), gpuDevice.getGroupDetails()); } @@ -1537,9 +1543,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new CloudRuntimeException("Invalid answer received in response to a StopCommand on " + vm.instanceName); } - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { s_logger.warn("Unable to stop vm, agent unavailable: " + e.toString()); - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { s_logger.warn("Unable to stop vm, operation timed out: " + e.toString()); } finally { if (!stopped) { @@ -1547,7 +1553,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.warn("Unable to stop vm " + vm); try { stateTransitTo(vm, Event.OperationFailed, vm.getHostId()); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn("Unable to transition the state " + vm); } throw new CloudRuntimeException("Unable to stop " + vm); @@ -1565,7 +1571,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { _networkMgr.release(profile, cleanUpEvenIfUnableToStop); s_logger.debug("Successfully released network resources for the vm " + vm); - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Unable to release some network resources.", e); } @@ -1574,7 +1580,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac volumeMgr.release(profile); s_logger.debug("Successfully released storage resources for the vm " + vm); } - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Unable to release storage resources.", e); } @@ -1590,7 +1596,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (!stateTransitTo(vm, Event.OperationSucceeded, null)) { throw new CloudRuntimeException("unable to stop " + vm); } - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn(e.getMessage()); throw new CloudRuntimeException("Unable to stop " + vm); } @@ -1600,7 +1606,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac _stateMachine = VirtualMachine.State.getStateMachine(); } - protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException { + protected boolean stateTransitTo(final VMInstanceVO vm, final VirtualMachine.Event e, final Long hostId, final String reservationId) throws NoTransitionException { // if there are active vm snapshots task, state change is not allowed // Disable this hacking thing, VM snapshot task need to be managed by its orchestartion flow istelf instead of @@ -1610,14 +1616,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.error("State transit with event: " + e + " failed due to: " + vm.getInstanceName() + " has active VM snapshots tasks"); return false; } - */ + */ vm.setReservationId(reservationId); return _stateMachine.transitTo(vm, e, new Pair(vm.getHostId(), hostId), _vmDao); } @Override - public boolean stateTransitTo(VirtualMachine vm1, VirtualMachine.Event e, Long hostId) throws NoTransitionException { - VMInstanceVO vm = (VMInstanceVO)vm1; + public boolean stateTransitTo(final VirtualMachine vm1, final VirtualMachine.Event e, final Long hostId) throws NoTransitionException { + final VMInstanceVO vm = (VMInstanceVO)vm1; /* * Remove the hacking logic here. @@ -1626,9 +1632,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.error("State transit with event: " + e + " failed due to: " + vm.getInstanceName() + " has active VM snapshots tasks"); return false; } - */ + */ - State oldState = vm.getState(); + final State oldState = vm.getState(); if (oldState == State.Starting) { if (e == Event.OperationSucceeded) { vm.setLastHostId(hostId); @@ -1642,7 +1648,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void destroy(String vmUuid) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { + public void destroy(final String vmUuid) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { @@ -1669,19 +1675,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); throw new CloudRuntimeException("Unable to destroy " + vm); } - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.debug(e.getMessage()); throw new CloudRuntimeException("Unable to destroy " + vm, e); } } - protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException { - Answer answer = _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName())); + protected boolean checkVmOnHost(final VirtualMachine vm, final long hostId) throws AgentUnavailableException, OperationTimedoutException { + final Answer answer = _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName())); if (answer == null || !answer.getResult()) { return false; } if (answer instanceof CheckVirtualMachineAnswer) { - CheckVirtualMachineAnswer vmAnswer = (CheckVirtualMachineAnswer)answer; + final CheckVirtualMachineAnswer vmAnswer = (CheckVirtualMachineAnswer)answer; if (vmAnswer.getState() == PowerState.PowerOff) { return false; } @@ -1691,12 +1697,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void storageMigration(String vmUuid, StoragePool destPool) { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + public void storageMigration(final String vmUuid, final StoragePool destPool) { + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { orchestrateStorageMigration(vmUuid, destPool); @@ -1706,40 +1712,41 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } } else { - Outcome outcome = migrateVmStorageThroughJobQueue(vmUuid, destPool); + final Outcome outcome = migrateVmStorageThroughJobQueue(vmUuid, destPool); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof RuntimeException) + if (jobResult instanceof RuntimeException) { throw (RuntimeException)jobResult; - else if (jobResult instanceof Throwable) + } else if (jobResult instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } } } } - private void orchestrateStorageMigration(String vmUuid, StoragePool destPool) { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Long srchostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); - HostVO srcHost = _hostDao.findById(srchostId); - Long srcClusterId = srcHost.getClusterId(); + private void orchestrateStorageMigration(final String vmUuid, final StoragePool destPool) { + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + final Long srchostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); + final HostVO srcHost = _hostDao.findById(srchostId); + final Long srcClusterId = srcHost.getClusterId(); try { stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.debug("Unable to migrate vm: " + e.toString()); throw new CloudRuntimeException("Unable to migrate vm: " + e.toString()); } - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); boolean migrationResult = false; try { migrationResult = volumeMgr.storageMigration(profile, destPool); @@ -1748,8 +1755,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac //if the vm is migrated to different pod in basic mode, need to reallocate ip if (!vm.getPodIdToDeployIn().equals(destPool.getPodId())) { - DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, null, null); - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, null, null, null, null); + final DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, null, null); + final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, null, null, null, null); _networkMgr.reallocate(vmProfile, plan); } @@ -1760,18 +1767,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // If VM was cold migrated between clusters belonging to two different VMware DCs, // unregister the VM from the source host and cleanup the associated VM files. if (vm.getHypervisorType().equals(HypervisorType.VMware)) { - Long destClusterId = destPool.getClusterId(); - if (srcClusterId != null && destClusterId != null && !srcClusterId.equals(destClusterId)) { - String srcDcName = _clusterDetailsDao.getVmwareDcName(srcClusterId); - String destDcName = _clusterDetailsDao.getVmwareDcName(destClusterId); + final Long destClusterId = destPool.getClusterId(); + if (srcClusterId != null && destClusterId != null && srcClusterId != destClusterId) { + final String srcDcName = _clusterDetailsDao.getVmwareDcName(srcClusterId); + final String destDcName = _clusterDetailsDao.getVmwareDcName(destClusterId); if (srcDcName != null && destDcName != null && !srcDcName.equals(destDcName)) { s_logger.debug("Since VM's storage was successfully migrated across VMware Datacenters, unregistering VM: " + vm.getInstanceName() + " from source host: " + srcHost.getId()); - UnregisterVMCommand uvc = new UnregisterVMCommand(vm.getInstanceName()); + final UnregisterVMCommand uvc = new UnregisterVMCommand(vm.getInstanceName()); uvc.setCleanupVmFiles(true); try { _agentMgr.send(srcHost.getId(), uvc); - } catch (Exception e) { + } catch (final Exception e) { throw new CloudRuntimeException("Failed to unregister VM: " + vm.getInstanceName() + " from source host: " + srcHost.getId() + " after successfully migrating VM's storage across VMware Datacenters"); } @@ -1782,25 +1789,25 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } else { s_logger.debug("Storage migration failed"); } - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); - } catch (InsufficientVirtualNetworkCapacityException e) { + } catch (final InsufficientVirtualNetworkCapacityException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); - } catch (InsufficientAddressCapacityException e) { + } catch (final InsufficientAddressCapacityException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); - } catch (InsufficientCapacityException e) { + } catch (final InsufficientCapacityException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); - } catch (StorageUnavailableException e) { + } catch (final StorageUnavailableException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); } finally { try { stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.debug("Failed to change vm state: " + e.toString()); throw new CloudRuntimeException("Failed to change vm state: " + e.toString()); } @@ -1808,14 +1815,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void migrate(String vmUuid, long srcHostId, DeployDestination dest) + public void migrate(final String vmUuid, final long srcHostId, final DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { orchestrateMigrate(vmUuid, srcHostId, dest); @@ -1825,33 +1832,34 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } } else { - Outcome outcome = migrateVmThroughJobQueue(vmUuid, srcHostId, dest); + final Outcome outcome = migrateVmThroughJobQueue(vmUuid, srcHostId, dest); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof ResourceUnavailableException) + if (jobResult instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobResult; - else if (jobResult instanceof ConcurrentOperationException) + } else if (jobResult instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobResult; - else if (jobResult instanceof RuntimeException) + } else if (jobResult instanceof RuntimeException) { throw (RuntimeException)jobResult; - else if (jobResult instanceof Throwable) + } else if (jobResult instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } } } } - private void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + private void orchestrateMigrate(final String vmUuid, final long srcHostId, final DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException { + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); if (vm == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the vm " + vmUuid); @@ -1861,20 +1869,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac migrate(vm, srcHostId, dest); } - protected void migrate(VMInstanceVO vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException { + protected void migrate(final VMInstanceVO vm, final long srcHostId, final DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException { s_logger.info("Migrating " + vm + " to " + dest); - long dstHostId = dest.getHost().getId(); - Host fromHost = _hostDao.findById(srcHostId); + final long dstHostId = dest.getHost().getId(); + final Host fromHost = _hostDao.findById(srcHostId); if (fromHost == null) { s_logger.info("Unable to find the host to migrate from: " + srcHostId); throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId); } if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) { - List volumes = _volsDao.findCreatedByInstance(vm.getId()); - for (VolumeVO volume : volumes) { - if (!(_storagePoolDao.findById(volume.getPoolId())).getScope().equals(ScopeType.ZONE)) { + final List volumes = _volsDao.findCreatedByInstance(vm.getId()); + for (final VolumeVO volume : volumes) { + if (!_storagePoolDao.findById(volume.getPoolId()).getScope().equals(ScopeType.ZONE)) { s_logger.info("Source and destination host are not in same cluster and all volumes are not on zone wide primary store, unable to migrate to host: " + dest.getHost().getId()); throw new CloudRuntimeException( @@ -1884,7 +1892,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - VirtualMachineGuru vmGuru = getVmGuru(vm); + final VirtualMachineGuru vmGuru = getVmGuru(vm); if (vm.getState() != State.Running) { if (s_logger.isDebugEnabled()) { @@ -1900,17 +1908,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } - VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm); - for (NicProfile nic : _networkMgr.getNicProfiles(vm)) { + final VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm); + for (final NicProfile nic : _networkMgr.getNicProfiles(vm)) { vmSrc.addNic(nic); } - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, null, _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()), null, null); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, null, _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()), null, null); _networkMgr.prepareNicForMigration(profile, dest); volumeMgr.prepareForMigration(profile, dest); - VirtualMachineTO to = toVmTO(profile); - PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to); + final VirtualMachineTO to = toVmTO(profile); + final PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId()); work.setStep(Step.Prepare); @@ -1922,12 +1930,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { pfma = _agentMgr.send(dstHostId, pfmc); if (pfma == null || !pfma.getResult()) { - String details = (pfma != null) ? pfma.getDetails() : "null answer returned"; - String msg = "Unable to prepare for migration due to " + details; + final String details = pfma != null ? pfma.getDetails() : "null answer returned"; + final String msg = "Unable to prepare for migration due to " + details; pfma = null; throw new AgentUnavailableException(msg, dstHostId); } - } catch (OperationTimedoutException e1) { + } catch (final OperationTimedoutException e1) { throw new AgentUnavailableException("Operation timed out", dstHostId); } finally { if (pfma == null) { @@ -1944,7 +1952,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.info("Migration cancelled because state has changed: " + vm); throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm); } - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { _networkMgr.rollbackNicForMigration(vmSrc, profile); s_logger.info("Migration cancelled because " + e1.getMessage()); throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage()); @@ -1952,17 +1960,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac boolean migrated = false; try { - boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); - MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, getExecuteInSequence(vm.getHypervisorType())); + final boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); + final MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, getExecuteInSequence(vm.getHypervisorType())); mc.setHostGuid(dest.getHost().getGuid()); try { - Answer ma = _agentMgr.send(vm.getLastHostId(), mc); + final Answer ma = _agentMgr.send(vm.getLastHostId(), mc); if (ma == null || !ma.getResult()) { - String details = (ma != null) ? ma.getDetails() : "null answer returned"; + final String details = ma != null ? ma.getDetails() : "null answer returned"; throw new CloudRuntimeException(details); } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { if (e.isActive()) { s_logger.warn("Active migration command so scheduling a restart for " + vm); _haMgr.scheduleRestart(vm, true); @@ -1974,7 +1982,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) { throw new ConcurrentOperationException("Unable to change the state for " + vm); } - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage()); } @@ -1983,13 +1991,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.error("Unable to complete migration for " + vm); try { _agentMgr.send(srcHostId, new Commands(cleanup(vm)), null); - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId); } cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true); throw new CloudRuntimeException("Unable to complete migration for " + vm); } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { s_logger.debug("Error while checking the vm " + vm + " on host " + dstHostId, e); } @@ -2004,13 +2012,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac dest.getPod().getName(), "Migrate Command failed. Please check logs."); try { _agentMgr.send(dstHostId, new Commands(cleanup(vm)), null); - } catch (AgentUnavailableException ae) { + } catch (final AgentUnavailableException ae) { s_logger.info("Looks like the destination Host is unavailable for cleanup"); } try { stateTransitTo(vm, Event.OperationFailed, srcHostId); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn(e.getMessage()); } } else { @@ -2022,14 +2030,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - private Map getPoolListForVolumesForMigration(VirtualMachineProfile profile, Host host, Map volumeToPool) { - List allVolumes = _volsDao.findUsableVolumesForInstance(profile.getId()); - Map volumeToPoolObjectMap = new HashMap (); - for (VolumeVO volume : allVolumes) { - Long poolId = volumeToPool.get(Long.valueOf(volume.getId())); - StoragePoolVO pool = _storagePoolDao.findById(poolId); - StoragePoolVO currentPool = _storagePoolDao.findById(volume.getPoolId()); - DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); + private Map getPoolListForVolumesForMigration(final VirtualMachineProfile profile, final Host host, final Map volumeToPool) { + final List allVolumes = _volsDao.findUsableVolumesForInstance(profile.getId()); + final Map volumeToPoolObjectMap = new HashMap (); + for (final VolumeVO volume : allVolumes) { + final Long poolId = volumeToPool.get(Long.valueOf(volume.getId())); + final StoragePoolVO pool = _storagePoolDao.findById(poolId); + final StoragePoolVO currentPool = _storagePoolDao.findById(volume.getPoolId()); + final DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); if (pool != null) { // Check if pool is accessible from the destination host and disk offering with which the volume was // created is compliant with the pool type. @@ -2045,14 +2053,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } else { // Find a suitable pool for the volume. Call the storage pool allocator to find the list of pools. - DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType()); - DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), null, null); - ExcludeList avoid = new ExcludeList(); + final DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType()); + final DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), null, null); + final ExcludeList avoid = new ExcludeList(); boolean currentPoolAvailable = false; - List poolList = new ArrayList(); - for (StoragePoolAllocator allocator : _storagePoolAllocators) { - List poolListFromAllocator = allocator.allocateToPool(diskProfile, profile, plan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL); + final List poolList = new ArrayList(); + for (final StoragePoolAllocator allocator : _storagePoolAllocators) { + final List poolListFromAllocator = allocator.allocateToPool(diskProfile, profile, plan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL); if (poolListFromAllocator != null && !poolListFromAllocator.isEmpty()) { poolList.addAll(poolListFromAllocator); } @@ -2062,7 +2070,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // Volume needs to be migrated. Pick the first pool from the list. Add a mapping to migrate the // volume to a pool only if it is required; that is the current pool on which the volume resides // is not available on the destination host. - Iterator iter = poolList.iterator(); + final Iterator iter = poolList.iterator(); while (iter.hasNext()) { if (currentPool.getId() == iter.next().getId()) { currentPoolAvailable = true; @@ -2087,42 +2095,42 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return volumeToPoolObjectMap; } - private void moveVmToMigratingState(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException { + private void moveVmToMigratingState(final T vm, final Long hostId, final ItWorkVO work) throws ConcurrentOperationException { // Put the vm in migrating state. try { if (!changeState(vm, Event.MigrationRequested, hostId, work, Step.Migrating)) { s_logger.info("Migration cancelled because state has changed: " + vm); throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm); } - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.info("Migration cancelled because " + e.getMessage()); throw new ConcurrentOperationException("Migration cancelled because " + e.getMessage()); } } - private void moveVmOutofMigratingStateOnSuccess(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException { + private void moveVmOutofMigratingStateOnSuccess(final T vm, final Long hostId, final ItWorkVO work) throws ConcurrentOperationException { // Put the vm in running state. try { if (!changeState(vm, Event.OperationSucceeded, hostId, work, Step.Started)) { s_logger.error("Unable to change the state for " + vm); throw new ConcurrentOperationException("Unable to change the state for " + vm); } - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.error("Unable to change state due to " + e.getMessage()); throw new ConcurrentOperationException("Unable to change state due to " + e.getMessage()); } } @Override - public void migrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool) + public void migrateWithStorage(final String vmUuid, final long srcHostId, final long destHostId, final Map volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool); @@ -2133,47 +2141,48 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } else { - Outcome outcome = migrateVmWithStorageThroughJobQueue(vmUuid, srcHostId, destHostId, volumeToPool); + final Outcome outcome = migrateVmWithStorageThroughJobQueue(vmUuid, srcHostId, destHostId, volumeToPool); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) + if (jobException instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) + } else if (jobException instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobException; - else if (jobException instanceof RuntimeException) + } else if (jobException instanceof RuntimeException) { throw (RuntimeException)jobException; - else if (jobException instanceof Throwable) + } else if (jobException instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobException); - } + } + } } } - private void orchestrateMigrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool) throws ResourceUnavailableException, + private void orchestrateMigrateWithStorage(final String vmUuid, final long srcHostId, final long destHostId, final Map volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - HostVO srcHost = _hostDao.findById(srcHostId); - HostVO destHost = _hostDao.findById(destHostId); - VirtualMachineGuru vmGuru = getVmGuru(vm); + final HostVO srcHost = _hostDao.findById(srcHostId); + final HostVO destHost = _hostDao.findById(destHostId); + final VirtualMachineGuru vmGuru = getVmGuru(vm); - DataCenterVO dc = _dcDao.findById(destHost.getDataCenterId()); - HostPodVO pod = _podDao.findById(destHost.getPodId()); - Cluster cluster = _clusterDao.findById(destHost.getClusterId()); - DeployDestination destination = new DeployDestination(dc, pod, cluster, destHost); + final DataCenterVO dc = _dcDao.findById(destHost.getDataCenterId()); + final HostPodVO pod = _podDao.findById(destHost.getPodId()); + final Cluster cluster = _clusterDao.findById(destHost.getClusterId()); + final DeployDestination destination = new DeployDestination(dc, pod, cluster, destHost); // Create a map of which volume should go in which storage pool. - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); - Map volumeToPoolMap = getPoolListForVolumesForMigration(profile, destHost, volumeToPool); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final Map volumeToPoolMap = getPoolListForVolumesForMigration(profile, destHost, volumeToPool); // If none of the volumes have to be migrated, fail the call. Administrator needs to make a call for migrating // a vm and not migrating a vm with storage. @@ -2191,8 +2200,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac _networkMgr.prepareNicForMigration(profile, destination); volumeMgr.prepareForMigration(profile, destination); - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); - VirtualMachineTO to = hvGuru.implement(profile); + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); + final VirtualMachineTO to = hvGuru.implement(profile); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId()); work.setStep(Step.Prepare); @@ -2217,13 +2226,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm); try { _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null); - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId); } cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true); throw new CloudRuntimeException("VM not found on desintation host. Unable to complete migration for " + vm); } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e); } @@ -2237,9 +2246,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null); stateTransitTo(vm, Event.OperationFailed, srcHostId); - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.error("Error while transitioning vm from migrating to running state.", e); } } @@ -2250,23 +2259,23 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public VirtualMachineTO toVmTO(VirtualMachineProfile profile) { - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(profile.getVirtualMachine().getHypervisorType()); - VirtualMachineTO to = hvGuru.implement(profile); + public VirtualMachineTO toVmTO(final VirtualMachineProfile profile) { + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(profile.getVirtualMachine().getHypervisorType()); + final VirtualMachineTO to = hvGuru.implement(profile); return to; } - protected void cancelWorkItems(long nodeId) { - GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem"); + protected void cancelWorkItems(final long nodeId) { + final GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem"); try { if (scanLock.lock(3)) { try { - List works = _workDao.listWorkInProgressFor(nodeId); - for (ItWorkVO work : works) { + final List works = _workDao.listWorkInProgressFor(nodeId); + for (final ItWorkVO work : works) { s_logger.info("Handling unfinished work item: " + work); try { - VMInstanceVO vm = _vmDao.findById(work.getInstanceId()); + final VMInstanceVO vm = _vmDao.findById(work.getInstanceId()); if (vm != null) { if (work.getType() == State.Starting) { _haMgr.scheduleRestart(vm, true); @@ -2284,7 +2293,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac _workDao.update(work.getId(), work); } } - } catch (Exception e) { + } catch (final Exception e) { s_logger.error("Error while handling " + work, e); } } @@ -2298,18 +2307,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void migrateAway(String vmUuid, long srcHostId) throws InsufficientServerCapacityException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + public void migrateAway(final String vmUuid, final long srcHostId) throws InsufficientServerCapacityException { + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { try { orchestrateMigrateAway(vmUuid, srcHostId, null); - } catch (InsufficientServerCapacityException e) { + } catch (final InsufficientServerCapacityException e) { s_logger.warn("Failed to deploy vm " + vmUuid + " with original planner, sending HAPlanner"); orchestrateMigrateAway(vmUuid, srcHostId, _haMgr.getHAPlanner()); } @@ -2317,57 +2326,58 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac _workJobDao.expunge(placeHolder.getId()); } } else { - Outcome outcome = migrateVmAwayThroughJobQueue(vmUuid, srcHostId); + final Outcome outcome = migrateVmAwayThroughJobQueue(vmUuid, srcHostId); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobException != null) { - if (jobException instanceof InsufficientServerCapacityException) + if (jobException instanceof InsufficientServerCapacityException) { throw (InsufficientServerCapacityException)jobException; - else if (jobException instanceof ConcurrentOperationException) + } else if (jobException instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobException; - else if (jobException instanceof RuntimeException) + } else if (jobException instanceof RuntimeException) { throw (RuntimeException)jobException; - else if (jobException instanceof Throwable) + } else if (jobException instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobException); + } } } } - private void orchestrateMigrateAway(String vmUuid, long srcHostId, DeploymentPlanner planner) throws InsufficientServerCapacityException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + private void orchestrateMigrateAway(final String vmUuid, final long srcHostId, final DeploymentPlanner planner) throws InsufficientServerCapacityException { + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); if (vm == null) { s_logger.debug("Unable to find a VM for " + vmUuid); throw new CloudRuntimeException("Unable to find " + vmUuid); } - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); - Long hostId = vm.getHostId(); + final Long hostId = vm.getHostId(); if (hostId == null) { s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm); throw new CloudRuntimeException("Unable to migrate " + vmUuid); } - Host host = _hostDao.findById(hostId); + final Host host = _hostDao.findById(hostId); Long poolId = null; - List vols = _volsDao.findReadyRootVolumesByInstance(vm.getId()); - for (VolumeVO rootVolumeOfVm : vols) { - StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); + final List vols = _volsDao.findReadyRootVolumesByInstance(vm.getId()); + for (final VolumeVO rootVolumeOfVm : vols) { + final StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); if (rootDiskPool != null) { poolId = rootDiskPool.getId(); } } - DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, poolId, null); - ExcludeList excludes = new ExcludeList(); + final DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, poolId, null); + final ExcludeList excludes = new ExcludeList(); excludes.addHost(hostId); DeployDestination dest = null; @@ -2375,7 +2385,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { dest = _dpMgr.planDeployment(profile, plan, excludes, planner); - } catch (AffinityConflictException e2) { + } catch (final AffinityConflictException e2) { s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2); throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict"); } @@ -2395,22 +2405,22 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { migrate(vm, srcHostId, dest); return; - } catch (ResourceUnavailableException e) { + } catch (final ResourceUnavailableException e) { s_logger.debug("Unable to migrate to unavailable " + dest); - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { s_logger.debug("Unable to migrate VM due to: " + e.getMessage()); } try { advanceStop(vmUuid, true); throw new CloudRuntimeException("Unable to migrate " + vm); - } catch (ResourceUnavailableException e) { + } catch (final ResourceUnavailableException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); throw new CloudRuntimeException("Unable to migrate " + vm); - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); throw new CloudRuntimeException("Unable to migrate " + vm); - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); throw new CloudRuntimeException("Unable to migrate " + vm); } @@ -2425,46 +2435,47 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac _workDao.cleanup(VmOpCleanupWait.value()); // TODO. hard-coded to one hour after job has been completed - Date cutDate = new Date(new Date().getTime() - 3600000); + final Date cutDate = new Date(new Date().getTime() - 3600000); _workJobDao.expungeCompletedWorkJobs(cutDate); - } catch (Exception e) { + } catch (final Exception e) { s_logger.error("VM Operations failed due to ", e); } } } @Override - public boolean isVirtualMachineUpgradable(VirtualMachine vm, ServiceOffering offering) { + public boolean isVirtualMachineUpgradable(final VirtualMachine vm, final ServiceOffering offering) { boolean isMachineUpgradable = true; - for (HostAllocator allocator : hostAllocators) { + for (final HostAllocator allocator : hostAllocators) { isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering); - if (isMachineUpgradable) + if (isMachineUpgradable) { continue; - else + } else { break; + } } return isMachineUpgradable; } @Override - public void reboot(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException { + public void reboot(final String vmUuid, final Map params) throws InsufficientCapacityException, ResourceUnavailableException { try { advanceReboot(vmUuid, params); - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e); } } @Override - public void advanceReboot(String vmUuid, Map params) + public void advanceReboot(final String vmUuid, final Map params) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if ( jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { orchestrateReboot(vmUuid, params); @@ -2474,88 +2485,89 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } } else { - Outcome outcome = rebootVmThroughJobQueue(vmUuid, params); + final Outcome outcome = rebootVmThroughJobQueue(vmUuid, params); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof ResourceUnavailableException) + if (jobResult instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobResult; - else if (jobResult instanceof ConcurrentOperationException) + } else if (jobResult instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobResult; - else if (jobResult instanceof InsufficientCapacityException) + } else if (jobResult instanceof InsufficientCapacityException) { throw (InsufficientCapacityException)jobResult; - else if (jobResult instanceof RuntimeException) + } else if (jobResult instanceof RuntimeException) { throw (RuntimeException)jobResult; - else if (jobResult instanceof Throwable) + } else if (jobResult instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } } } } - private void orchestrateReboot(String vmUuid, Map params) throws InsufficientCapacityException, ConcurrentOperationException, + private void orchestrateReboot(final String vmUuid, final Map params) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - DataCenter dc = _entityMgr.findById(DataCenter.class, vm.getDataCenterId()); - Host host = _hostDao.findById(vm.getHostId()); + final DataCenter dc = _entityMgr.findById(DataCenter.class, vm.getDataCenterId()); + final Host host = _hostDao.findById(vm.getHostId()); if (host == null) { // Should findById throw an Exception is the host is not found? throw new CloudRuntimeException("Unable to retrieve host with id " + vm.getHostId()); } - Cluster cluster = _entityMgr.findById(Cluster.class, host.getClusterId()); - Pod pod = _entityMgr.findById(Pod.class, host.getPodId()); - DeployDestination dest = new DeployDestination(dc, pod, cluster, host); + final Cluster cluster = _entityMgr.findById(Cluster.class, host.getClusterId()); + final Pod pod = _entityMgr.findById(Pod.class, host.getPodId()); + final DeployDestination dest = new DeployDestination(dc, pod, cluster, host); try { - Commands cmds = new Commands(Command.OnError.Stop); + final Commands cmds = new Commands(Command.OnError.Stop); cmds.addCommand(new RebootCommand(vm.getInstanceName())); _agentMgr.send(host.getId(), cmds); - Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class); + final Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class); if (rebootAnswer != null && rebootAnswer.getResult()) { return; } s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails())); - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e); throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost()); } } - public Command cleanup(VirtualMachine vm) { + public Command cleanup(final VirtualMachine vm) { return new StopCommand(vm, getExecuteInSequence(vm.getHypervisorType()), false); } - public Command cleanup(String vmName) { + public Command cleanup(final String vmName) { return new StopCommand(vmName, getExecuteInSequence(null), false); } // this is XenServer specific - public void syncVMMetaData(Map vmMetadatum) { + public void syncVMMetaData(final Map vmMetadatum) { if (vmMetadatum == null || vmMetadatum.isEmpty()) { return; } - for (Map.Entry entry : vmMetadatum.entrySet()) { - String name = entry.getKey(); - String platform = entry.getValue(); + for (final Map.Entry entry : vmMetadatum.entrySet()) { + final String name = entry.getKey(); + final String platform = entry.getValue(); if (platform == null || platform.isEmpty()) { continue; } - VMInstanceVO vm = _vmDao.findVMByInstanceName(name); + final VMInstanceVO vm = _vmDao.findVMByInstanceName(name); if (vm != null && vm.getType() == VirtualMachine.Type.User) { boolean changed = false; - UserVmVO userVm = _userVmDao.findById(vm.getId()); + final UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); if ( userVm.details.containsKey("timeoffset")) { userVm.details.remove("timeoffset"); @@ -2581,15 +2593,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } - private void ensureVmRunningContext(long hostId, VMInstanceVO vm, Event cause) throws OperationTimedoutException, ResourceUnavailableException, + private void ensureVmRunningContext(final long hostId, VMInstanceVO vm, final Event cause) throws OperationTimedoutException, ResourceUnavailableException, NoTransitionException, InsufficientAddressCapacityException { - VirtualMachineGuru vmGuru = getVmGuru(vm); + final VirtualMachineGuru vmGuru = getVmGuru(vm); s_logger.debug("VM state is starting on full sync so updating it to running"); vm = _vmDao.findById(vm.getId()); // grab outstanding work item if any - ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); + final ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); if (work != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found an outstanding work item for this vm " + vm + " in state:" + vm.getState() + ", work id:" + work.getId()); @@ -2598,7 +2610,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { stateTransitTo(vm, cause, hostId); - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { s_logger.warn(e1.getMessage()); } @@ -2606,17 +2618,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac vm = _vmDao.findById(vm.getId()); // this should ensure vm has the most // up to date info - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); - List nics = _nicsDao.listByVmId(profile.getId()); - for (NicVO nic : nics) { - Network network = _networkModel.getNetwork(nic.getNetworkId()); - NicProfile nicProfile = + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final List nics = _nicsDao.listByVmId(profile.getId()); + for (final NicVO nic : nics) { + final Network network = _networkModel.getNetwork(nic.getNetworkId()); + final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(profile.getHypervisorType(), network)); profile.addNic(nicProfile); } - Commands cmds = new Commands(Command.OnError.Stop); + final Commands cmds = new Commands(Command.OnError.Stop); s_logger.debug("Finalizing commands that need to be send to complete Start process for the vm " + vm); if (vmGuru.finalizeCommandsOnStart(cmds, profile)) { @@ -2648,10 +2660,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public boolean processAnswers(long agentId, long seq, Answer[] answers) { + public boolean processAnswers(final long agentId, final long seq, final Answer[] answers) { for (final Answer answer : answers) { if ( answer instanceof ClusterVMMetaDataSyncAnswer) { - ClusterVMMetaDataSyncAnswer cvms = (ClusterVMMetaDataSyncAnswer)answer; + final ClusterVMMetaDataSyncAnswer cvms = (ClusterVMMetaDataSyncAnswer)answer; if (!cvms.isExecuted()) { syncVMMetaData(cvms.getVMMetaDatum()); cvms.setExecuted(); @@ -2662,7 +2674,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public boolean processTimeout(long agentId, long seq) { + public boolean processTimeout(final long agentId, final long seq) { return true; } @@ -2672,11 +2684,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public boolean processCommands(long agentId, long seq, Command[] cmds) { + public boolean processCommands(final long agentId, final long seq, final Command[] cmds) { boolean processed = false; - for (Command cmd : cmds) { + for (final Command cmd : cmds) { if (cmd instanceof PingRoutingCommand) { - PingRoutingCommand ping = (PingRoutingCommand)cmd; + final PingRoutingCommand ping = (PingRoutingCommand)cmd; if (ping.getHostVmStateReport() != null) { _syncMgr.processHostVmStatePingReport(agentId, ping.getHostVmStateReport()); } @@ -2691,23 +2703,24 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) { + public AgentControlAnswer processControlCommand(final long agentId, final AgentControlCommand cmd) { return null; } @Override - public boolean processDisconnect(long agentId, Status state) { + public boolean processDisconnect(final long agentId, final Status state) { return true; } @Override - public void processConnect(Host agent, StartupCommand cmd, boolean forRebalance) throws ConnectionException { + public void processConnect(final Host agent, final StartupCommand cmd, final boolean forRebalance) throws ConnectionException { if (!(cmd instanceof StartupRoutingCommand)) { return; } - if(s_logger.isDebugEnabled()) + if(s_logger.isDebugEnabled()) { s_logger.debug("Received startup command from hypervisor host. host id: " + agent.getId()); + } _syncMgr.resetHostSyncState(agent.getId()); @@ -2715,16 +2728,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process"); return; } - Long clusterId = agent.getClusterId(); - long agentId = agent.getId(); + final Long clusterId = agent.getClusterId(); + final long agentId = agent.getId(); if (agent.getHypervisorType() == HypervisorType.XenServer) { // only for Xen // initiate the cron job - ClusterVMMetaDataSyncCommand syncVMMetaDataCmd = new ClusterVMMetaDataSyncCommand(ClusterVMMetaDataSyncInterval.value(), clusterId); + final ClusterVMMetaDataSyncCommand syncVMMetaDataCmd = new ClusterVMMetaDataSyncCommand(ClusterVMMetaDataSyncInterval.value(), clusterId); try { - long seq_no = _agentMgr.send(agentId, new Commands(syncVMMetaDataCmd), this); + final long seq_no = _agentMgr.send(agentId, new Commands(syncVMMetaDataCmd), this); s_logger.debug("Cluster VM metadata sync started with jobid " + seq_no); - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { s_logger.fatal("The Cluster VM metadata sync process failed for cluster id " + clusterId + " with ", e); } } @@ -2733,7 +2746,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac protected class TransitionTask extends ManagedContextRunnable { @Override protected void runInContext() { - GlobalLock lock = GlobalLock.getInternLock("TransitionChecking"); + final GlobalLock lock = GlobalLock.getInternLock("TransitionChecking"); if (lock == null) { s_logger.debug("Couldn't get the global lock"); return; @@ -2746,16 +2759,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { scanStalledVMInTransitionStateOnDisconnectedHosts(); - List instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (AgentManager.Wait.value() * 1000)), State.Starting, State.Stopping); - for (VMInstanceVO instance : instances) { - State state = instance.getState(); + final List instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - AgentManager.Wait.value() * 1000), State.Starting, State.Stopping); + for (final VMInstanceVO instance : instances) { + final State state = instance.getState(); if (state == State.Stopping) { _haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop); } else if (state == State.Starting) { _haMgr.scheduleRestart(instance, true); } } - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Caught the following exception on transition checking", e); } finally { lock.unlock(); @@ -2764,12 +2777,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public VMInstanceVO findById(long vmId) { + public VMInstanceVO findById(final long vmId) { return _vmDao.findById(vmId); } @Override - public void checkIfCanUpgrade(VirtualMachine vmInstance, ServiceOffering newServiceOffering) { + public void checkIfCanUpgrade(final VirtualMachine vmInstance, final ServiceOffering newServiceOffering) { if (newServiceOffering == null) { throw new InvalidParameterValueException("Invalid parameter, newServiceOffering can't be null"); } @@ -2792,7 +2805,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac newServiceOffering.getName() + ")"); } - ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId()); + final ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId()); // Check that the service offering being upgraded to has the same Guest IP type as the VM's current service offering // NOTE: With the new network refactoring in 2.2, we shouldn't need the check for same guest IP type anymore. @@ -2823,8 +2836,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } // Check that the service offering being upgraded to has storage tags subset of the current service offering storage tags, since volume is not migrated. - List currentTags = StringUtils.csvTagsToList(currentServiceOffering.getTags()); - List newTags = StringUtils.csvTagsToList(newServiceOffering.getTags()); + final List currentTags = StringUtils.csvTagsToList(currentServiceOffering.getTags()); + final List newTags = StringUtils.csvTagsToList(newServiceOffering.getTags()); if (!currentTags.containsAll(newTags)) { throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering " + " should have tags as subset of " + "current service offering tags. Current service offering tags: " + currentTags + "; " + "new service " + "offering tags: " + newTags); @@ -2832,10 +2845,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public boolean upgradeVmDb(long vmId, long serviceOfferingId) { - VMInstanceVO vmForUpdate = _vmDao.createForUpdate(); + public boolean upgradeVmDb(final long vmId, final long serviceOfferingId) { + final VMInstanceVO vmForUpdate = _vmDao.createForUpdate(); vmForUpdate.setServiceOfferingId(serviceOfferingId); - ServiceOffering newSvcOff = _entityMgr.findById(ServiceOffering.class, serviceOfferingId); + final ServiceOffering newSvcOff = _entityMgr.findById(ServiceOffering.class, serviceOfferingId); vmForUpdate.setHaEnabled(newSvcOff.getOfferHA()); vmForUpdate.setLimitCpuUse(newSvcOff.getLimitCpuUse()); vmForUpdate.setServiceOfferingId(newSvcOff.getId()); @@ -2843,10 +2856,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) + public NicProfile addVmToNetwork(final VirtualMachine vm, final Network network, final NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; @@ -2859,61 +2872,62 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } } else { - Outcome outcome = addVmToNetworkThroughJobQueue(vm, network, requested); + final Outcome outcome = addVmToNetworkThroughJobQueue(vm, network, requested); try { outcome.get(); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution exception", e); } - Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) + if (jobException instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) + } else if (jobException instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobException; - else if (jobException instanceof InsufficientCapacityException) + } else if (jobException instanceof InsufficientCapacityException) { throw (InsufficientCapacityException)jobException; - else if (jobException instanceof RuntimeException) + } else if (jobException instanceof RuntimeException) { throw (RuntimeException)jobException; - else if (jobException instanceof Throwable) + } else if (jobException instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobException); - else if (jobException instanceof NicProfile) + } else if (jobException instanceof NicProfile) { return (NicProfile)jobException; + } } throw new RuntimeException("Unexpected job execution result"); } } - private NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, + private NicProfile orchestrateAddVmToNetwork(final VirtualMachine vm, final Network network, final NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - CallContext cctx = CallContext.current(); + final CallContext cctx = CallContext.current(); s_logger.debug("Adding vm " + vm + " to network " + network + "; requested nic profile " + requested); - VMInstanceVO vmVO = _vmDao.findById(vm.getId()); - ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); + final VMInstanceVO vmVO = _vmDao.findById(vm.getId()); + final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null); + final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null); - DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - Host host = _hostDao.findById(vm.getHostId()); - DeployDestination dest = new DeployDestination(dc, null, null, host); + final DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); + final Host host = _hostDao.findById(vm.getHostId()); + final DeployDestination dest = new DeployDestination(dc, null, null, host); //check vm state if (vm.getState() == State.Running) { //1) allocate and prepare nic - NicProfile nic = _networkMgr.createNicForVm(network, requested, context, vmProfile, true); + final NicProfile nic = _networkMgr.createNicForVm(network, requested, context, vmProfile, true); //2) Convert vmProfile to vmTO - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); - VirtualMachineTO vmTO = hvGuru.implement(vmProfile); + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); + final VirtualMachineTO vmTO = hvGuru.implement(vmProfile); //3) Convert nicProfile to NicTO - NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType()); + final NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType()); //4) plug the nic to the vm s_logger.debug("Plugging nic for vm " + vm + " in network " + network); @@ -2923,7 +2937,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac result = plugNic(network, nicTO, vmTO, context, dest); if (result) { s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm is a part of network now"); - long isDefault = (nic.isDefaultNic()) ? 1 : 0; + final long isDefault = nic.isDefaultNic() ? 1 : 0; // insert nic's Id into DB as resource_name if(VirtualMachine.Type.User.equals(vmVO.getType())) { //Log usage event for user Vms only @@ -2951,18 +2965,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public NicTO toNicTO(NicProfile nic, HypervisorType hypervisorType) { - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(hypervisorType); + public NicTO toNicTO(final NicProfile nic, final HypervisorType hypervisorType) { + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(hypervisorType); - NicTO nicTO = hvGuru.toNicTO(nic); + final NicTO nicTO = hvGuru.toNicTO(nic); return nicTO; } @Override - public boolean removeNicFromVm(VirtualMachine vm, Nic nic) + public boolean removeNicFromVm(final VirtualMachine vm, final Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; @@ -2976,60 +2990,61 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } else { - Outcome outcome = removeNicFromVmThroughJobQueue(vm, nic); + final Outcome outcome = removeNicFromVmThroughJobQueue(vm, nic); try { outcome.get(); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof ResourceUnavailableException) + if (jobResult instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobResult; - else if (jobResult instanceof ConcurrentOperationException) + } else if (jobResult instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobResult; - else if (jobResult instanceof RuntimeException) + } else if (jobResult instanceof RuntimeException) { throw (RuntimeException)jobResult; - else if (jobResult instanceof Throwable) + } else if (jobResult instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobResult); - else if (jobResult instanceof Boolean) + } else if (jobResult instanceof Boolean) { return (Boolean)jobResult; + } } throw new RuntimeException("Job failed with un-handled exception"); } } - private boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { - CallContext cctx = CallContext.current(); - VMInstanceVO vmVO = _vmDao.findById(vm.getId()); - NetworkVO network = _networkDao.findById(nic.getNetworkId()); - ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); + private boolean orchestrateRemoveNicFromVm(final VirtualMachine vm, final Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { + final CallContext cctx = CallContext.current(); + final VMInstanceVO vmVO = _vmDao.findById(vm.getId()); + final NetworkVO network = _networkDao.findById(nic.getNetworkId()); + final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null); + final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null); - DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - Host host = _hostDao.findById(vm.getHostId()); - DeployDestination dest = new DeployDestination(dc, null, null, host); - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); - VirtualMachineTO vmTO = hvGuru.implement(vmProfile); + final DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); + final Host host = _hostDao.findById(vm.getHostId()); + final DeployDestination dest = new DeployDestination(dc, null, null, host); + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); + final VirtualMachineTO vmTO = hvGuru.implement(vmProfile); - NicProfile nicProfile = + final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()), _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network)); //1) Unplug the nic if (vm.getState() == State.Running) { - NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType()); + final NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType()); s_logger.debug("Un-plugging nic " + nic + " for vm " + vm + " from network " + network); - boolean result = unplugNic(network, nicTO, vmTO, context, dest); + final boolean result = unplugNic(network, nicTO, vmTO, context, dest); if (result) { s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network); - long isDefault = (nic.isDefaultNic()) ? 1 : 0; + final long isDefault = nic.isDefaultNic() ? 1 : 0; UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay()); } else { @@ -3053,24 +3068,24 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override @DB - public boolean removeVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean removeVmFromNetwork(final VirtualMachine vm, final Network network, final URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { // TODO will serialize on the VM object later to resolve operation conflicts return orchestrateRemoveVmFromNetwork(vm, network, broadcastUri); } @DB - private boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { - CallContext cctx = CallContext.current(); - VMInstanceVO vmVO = _vmDao.findById(vm.getId()); - ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); + private boolean orchestrateRemoveVmFromNetwork(final VirtualMachine vm, final Network network, final URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { + final CallContext cctx = CallContext.current(); + final VMInstanceVO vmVO = _vmDao.findById(vm.getId()); + final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null); + final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null); - DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - Host host = _hostDao.findById(vm.getHostId()); - DeployDestination dest = new DeployDestination(dc, null, null, host); - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); - VirtualMachineTO vmTO = hvGuru.implement(vmProfile); + final DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); + final Host host = _hostDao.findById(vm.getHostId()); + final DeployDestination dest = new DeployDestination(dc, null, null, host); + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); + final VirtualMachineTO vmTO = hvGuru.implement(vmProfile); Nic nic = null; if (broadcastUri != null) { @@ -3091,7 +3106,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } //Lock on nic is needed here - Nic lock = _nicsDao.acquireInLockTable(nic.getId()); + final Nic lock = _nicsDao.acquireInLockTable(nic.getId()); if (lock == null) { //check if nic is still there. Return if it was released already if (_nicsDao.findById(nic.getId()) == null) { @@ -3108,15 +3123,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } try { - NicProfile nicProfile = + final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()), _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network)); //1) Unplug the nic if (vm.getState() == State.Running) { - NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType()); + final NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType()); s_logger.debug("Un-plugging nic for vm " + vm + " from network " + network); - boolean result = unplugNic(network, nicTO, vmTO, context, dest); + final boolean result = unplugNic(network, nicTO, vmTO, context, dest); if (result) { s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network); } else { @@ -3146,23 +3161,23 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void findHostAndMigrate(String vmUuid, Long newSvcOfferingId, ExcludeList excludes) throws InsufficientCapacityException, ConcurrentOperationException, + public void findHostAndMigrate(final String vmUuid, final Long newSvcOfferingId, final ExcludeList excludes) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); if (vm == null) { throw new CloudRuntimeException("Unable to find " + vmUuid); } - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); - Long srcHostId = vm.getHostId(); - Long oldSvcOfferingId = vm.getServiceOfferingId(); + final Long srcHostId = vm.getHostId(); + final Long oldSvcOfferingId = vm.getServiceOfferingId(); if (srcHostId == null) { throw new CloudRuntimeException("Unable to scale the vm because it doesn't have a host id"); } - Host host = _hostDao.findById(srcHostId); - DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null, null); + final Host host = _hostDao.findById(srcHostId); + final DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null, null); excludes.addHost(vm.getHostId()); vm.setServiceOfferingId(newSvcOfferingId); // Need to find the destination host based on new svc offering @@ -3170,7 +3185,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { dest = _dpMgr.planDeployment(profile, plan, excludes, null); - } catch (AffinityConflictException e2) { + } catch (final AffinityConflictException e2) { s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2); throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict"); } @@ -3188,23 +3203,23 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac excludes.addHost(dest.getHost().getId()); try { migrateForScale(vm.getUuid(), srcHostId, dest, oldSvcOfferingId); - } catch (ResourceUnavailableException e) { + } catch (final ResourceUnavailableException e) { s_logger.debug("Unable to migrate to unavailable " + dest); throw e; - } catch (ConcurrentOperationException e) { + } catch (final ConcurrentOperationException e) { s_logger.debug("Unable to migrate VM due to: " + e.getMessage()); throw e; } } @Override - public void migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) + public void migrateForScale(final String vmUuid, final long srcHostId, final DeployDestination dest, final Long oldSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId); @@ -3214,39 +3229,40 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } } else { - Outcome outcome = migrateVmForScaleThroughJobQueue(vmUuid, srcHostId, dest, oldSvcOfferingId); + final Outcome outcome = migrateVmForScaleThroughJobQueue(vmUuid, srcHostId, dest, oldSvcOfferingId); try { - VirtualMachine vm = outcome.get(); - } catch (InterruptedException e) { + final VirtualMachine vm = outcome.get(); + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof ResourceUnavailableException) + if (jobResult instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobResult; - else if (jobResult instanceof ConcurrentOperationException) + } else if (jobResult instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobResult; - else if (jobResult instanceof RuntimeException) + } else if (jobResult instanceof RuntimeException) { throw (RuntimeException)jobResult; - else if (jobResult instanceof Throwable) + } else if (jobResult instanceof Throwable) { throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } } } } - private void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) + private void orchestrateMigrateForScale(final String vmUuid, final long srcHostId, final DeployDestination dest, final Long oldSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); s_logger.info("Migrating " + vm + " to " + dest); vm.getServiceOfferingId(); - long dstHostId = dest.getHost().getId(); - Host fromHost = _hostDao.findById(srcHostId); + final long dstHostId = dest.getHost().getId(); + final Host fromHost = _hostDao.findById(srcHostId); if (fromHost == null) { s_logger.info("Unable to find the host to migrate from: " + srcHostId); throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId); @@ -3257,9 +3273,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId()); } - VirtualMachineGuru vmGuru = getVmGuru(vm); + final VirtualMachineGuru vmGuru = getVmGuru(vm); - long vmId = vm.getId(); + final long vmId = vm.getId(); vm = _vmDao.findByUuid(vmUuid); if (vm == null) { if (s_logger.isDebugEnabled()) { @@ -3282,13 +3298,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); _networkMgr.prepareNicForMigration(profile, dest); volumeMgr.prepareForMigration(profile, dest); - VirtualMachineTO to = toVmTO(profile); - PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to); + final VirtualMachineTO to = toVmTO(profile); + final PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId()); work.setStep(Step.Prepare); @@ -3300,12 +3316,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { pfma = _agentMgr.send(dstHostId, pfmc); if (pfma == null || !pfma.getResult()) { - String details = (pfma != null) ? pfma.getDetails() : "null answer returned"; - String msg = "Unable to prepare for migration due to " + details; + final String details = pfma != null ? pfma.getDetails() : "null answer returned"; + final String msg = "Unable to prepare for migration due to " + details; pfma = null; throw new AgentUnavailableException(msg, dstHostId); } - } catch (OperationTimedoutException e1) { + } catch (final OperationTimedoutException e1) { throw new AgentUnavailableException("Operation timed out", dstHostId); } finally { if (pfma == null) { @@ -3320,26 +3336,26 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.info("Migration cancelled because state has changed: " + vm); throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm); } - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { s_logger.info("Migration cancelled because " + e1.getMessage()); throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage()); } boolean migrated = false; try { - boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); - MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, getExecuteInSequence(vm.getHypervisorType())); + final boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); + final MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, getExecuteInSequence(vm.getHypervisorType())); mc.setHostGuid(dest.getHost().getGuid()); try { - Answer ma = _agentMgr.send(vm.getLastHostId(), mc); + final Answer ma = _agentMgr.send(vm.getLastHostId(), mc); if (ma == null || !ma.getResult()) { - String details = (ma != null) ? ma.getDetails() : "null answer returned"; - String msg = "Unable to migrate due to " + details; + final String details = ma != null ? ma.getDetails() : "null answer returned"; + final String msg = "Unable to migrate due to " + details; s_logger.error(msg); throw new CloudRuntimeException(msg); } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { if (e.isActive()) { s_logger.warn("Active migration command so scheduling a restart for " + vm); _haMgr.scheduleRestart(vm, true); @@ -3348,13 +3364,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } try { - long newServiceOfferingId = vm.getServiceOfferingId(); + final long newServiceOfferingId = vm.getServiceOfferingId(); vm.setServiceOfferingId(oldSvcOfferingId); // release capacity for the old service offering only if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) { throw new ConcurrentOperationException("Unable to change the state for " + vm); } vm.setServiceOfferingId(newServiceOfferingId); - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage()); } @@ -3363,13 +3379,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.error("Unable to complete migration for " + vm); try { _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null); - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId); } cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true); throw new CloudRuntimeException("Unable to complete migration for " + vm); } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { s_logger.debug("Error while checking the vm " + vm + " on host " + dstHostId, e); } @@ -3383,13 +3399,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac dest.getPod().getName(), "Migrate Command failed. Please check logs."); try { _agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null); - } catch (AgentUnavailableException ae) { + } catch (final AgentUnavailableException ae) { s_logger.info("Looks like the destination Host is unavailable for cleanup"); } try { stateTransitTo(vm, Event.OperationFailed, srcHostId); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn(e.getMessage()); } } @@ -3399,24 +3415,24 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, + public boolean plugNic(final Network network, final NicTO nic, final VirtualMachineTO vm, final ReservationContext context, final DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { boolean result = true; - VMInstanceVO router = _vmDao.findById(vm.getId()); + final VMInstanceVO router = _vmDao.findById(vm.getId()); if (router.getState() == State.Running) { try { - PlugNicCommand plugNicCmd = new PlugNicCommand(nic, vm.getName(), vm.getType()); + final PlugNicCommand plugNicCmd = new PlugNicCommand(nic, vm.getName(), vm.getType()); - Commands cmds = new Commands(Command.OnError.Stop); + final Commands cmds = new Commands(Command.OnError.Stop); cmds.addCommand("plugnic", plugNicCmd); _agentMgr.send(dest.getHost().getId(), cmds); - PlugNicAnswer plugNicAnswer = cmds.getAnswer(PlugNicAnswer.class); + final PlugNicAnswer plugNicAnswer = cmds.getAnswer(PlugNicAnswer.class); if (!(plugNicAnswer != null && plugNicAnswer.getResult())) { s_logger.warn("Unable to plug nic for vm " + vm.getName()); result = false; } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { throw new AgentUnavailableException("Unable to plug nic for router " + vm.getName() + " in network " + network, dest.getHost().getId(), e); } } else { @@ -3429,25 +3445,25 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return result; } - public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, - ResourceUnavailableException { + public boolean unplugNic(final Network network, final NicTO nic, final VirtualMachineTO vm, final ReservationContext context, final DeployDestination dest) throws ConcurrentOperationException, + ResourceUnavailableException { boolean result = true; - VMInstanceVO router = _vmDao.findById(vm.getId()); + final VMInstanceVO router = _vmDao.findById(vm.getId()); if (router.getState() == State.Running) { try { - Commands cmds = new Commands(Command.OnError.Stop); - UnPlugNicCommand unplugNicCmd = new UnPlugNicCommand(nic, vm.getName()); + final Commands cmds = new Commands(Command.OnError.Stop); + final UnPlugNicCommand unplugNicCmd = new UnPlugNicCommand(nic, vm.getName()); cmds.addCommand("unplugnic", unplugNicCmd); _agentMgr.send(dest.getHost().getId(), cmds); - UnPlugNicAnswer unplugNicAnswer = cmds.getAnswer(UnPlugNicAnswer.class); + final UnPlugNicAnswer unplugNicAnswer = cmds.getAnswer(UnPlugNicAnswer.class); if (!(unplugNicAnswer != null && unplugNicAnswer.getResult())) { s_logger.warn("Unable to unplug nic from router " + router); result = false; } - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { throw new AgentUnavailableException("Unable to unplug nic from rotuer " + router + " from network " + network, dest.getHost().getId(), e); } } else if (router.getState() == State.Stopped || router.getState() == State.Stopping) { @@ -3463,15 +3479,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public VMInstanceVO reConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, - boolean reconfiguringOnExistingHost) - throws ResourceUnavailableException, InsufficientServerCapacityException, ConcurrentOperationException { + public VMInstanceVO reConfigureVm(final String vmUuid, final ServiceOffering oldServiceOffering, + final boolean reconfiguringOnExistingHost) + throws ResourceUnavailableException, InsufficientServerCapacityException, ConcurrentOperationException { - AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance VmWorkJobVO placeHolder = null; - VirtualMachine vm = _vmDao.findByUuid(vmUuid); + final VirtualMachine vm = _vmDao.findByUuid(vmUuid); placeHolder = createPlaceHolderWork(vm.getId()); try { return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost); @@ -3481,26 +3497,26 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } } else { - Outcome outcome = reconfigureVmThroughJobQueue(vmUuid, oldServiceOffering, reconfiguringOnExistingHost); + final Outcome outcome = reconfigureVmThroughJobQueue(vmUuid, oldServiceOffering, reconfiguringOnExistingHost); VirtualMachine vm = null; try { vm = outcome.get(); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { throw new RuntimeException("Operation is interrupted", e); - } catch (java.util.concurrent.ExecutionException e) { + } catch (final java.util.concurrent.ExecutionException e) { throw new RuntimeException("Execution excetion", e); } - Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobResult != null) { - if (jobResult instanceof ResourceUnavailableException) + if (jobResult instanceof ResourceUnavailableException) { throw (ResourceUnavailableException)jobResult; - else if (jobResult instanceof ConcurrentOperationException) + } else if (jobResult instanceof ConcurrentOperationException) { throw (ConcurrentOperationException)jobResult; - else if (jobResult instanceof InsufficientServerCapacityException) + } else if (jobResult instanceof InsufficientServerCapacityException) { throw (InsufficientServerCapacityException)jobResult; - else if (jobResult instanceof Throwable) { + } else if (jobResult instanceof Throwable) { s_logger.error("Unhandled exception", (Throwable)jobResult); throw new RuntimeException("Unhandled exception", (Throwable)jobResult); } @@ -3510,30 +3526,31 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - private VMInstanceVO orchestrateReConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException, + private VMInstanceVO orchestrateReConfigureVm(final String vmUuid, final ServiceOffering oldServiceOffering, final boolean reconfiguringOnExistingHost) throws ResourceUnavailableException, ConcurrentOperationException { - VMInstanceVO vm = _vmDao.findByUuid(vmUuid); + final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - long newServiceofferingId = vm.getServiceOfferingId(); - ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), newServiceofferingId); - HostVO hostVo = _hostDao.findById(vm.getHostId()); + final long newServiceofferingId = vm.getServiceOfferingId(); + final ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), newServiceofferingId); + final HostVO hostVo = _hostDao.findById(vm.getHostId()); - Float memoryOvercommitRatio = CapacityManager.MemOverprovisioningFactor.valueIn(hostVo.getClusterId()); - Float cpuOvercommitRatio = CapacityManager.CpuOverprovisioningFactor.valueIn(hostVo.getClusterId()); - long minMemory = (long)(newServiceOffering.getRamSize() / memoryOvercommitRatio); - ScaleVmCommand reconfigureCmd = + final Float memoryOvercommitRatio = CapacityManager.MemOverprovisioningFactor.valueIn(hostVo.getClusterId()); + final Float cpuOvercommitRatio = CapacityManager.CpuOverprovisioningFactor.valueIn(hostVo.getClusterId()); + final long minMemory = (long)(newServiceOffering.getRamSize() / memoryOvercommitRatio); + final ScaleVmCommand reconfigureCmd = new ScaleVmCommand(vm.getInstanceName(), newServiceOffering.getCpu(), (int)(newServiceOffering.getSpeed() / cpuOvercommitRatio), newServiceOffering.getSpeed(), minMemory * 1024L * 1024L, newServiceOffering.getRamSize() * 1024L * 1024L, newServiceOffering.getLimitCpuUse()); - Long dstHostId = vm.getHostId(); + final Long dstHostId = vm.getHostId(); if(vm.getHypervisorType().equals(HypervisorType.VMware)) { - HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); + final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); Map details = null; details = hvGuru.getClusterSettings(vm.getId()); reconfigureCmd.getVirtualMachine().setDetails(details); } - ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Running, vm.getType(), vm.getId()); + final ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Running, vm.getType(), vm.getId()); + work.setStep(Step.Prepare); work.setResourceType(ItWorkVO.ResourceType.Host); work.setResourceId(vm.getHostId()); @@ -3547,16 +3564,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac _capacityMgr.allocateVmCapacity(vm, false); // lock the new capacity } - Answer reconfigureAnswer = _agentMgr.send(vm.getHostId(), reconfigureCmd); + final Answer reconfigureAnswer = _agentMgr.send(vm.getHostId(), reconfigureCmd); if (reconfigureAnswer == null || !reconfigureAnswer.getResult()) { s_logger.error("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails())); throw new CloudRuntimeException("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails())); } success = true; - } catch (OperationTimedoutException e) { + } catch (final OperationTimedoutException e) { throw new AgentUnavailableException("Operation timed out on reconfiguring " + vm, dstHostId); - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { throw e; } finally { if (!success) { @@ -3587,7 +3604,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Inject - public void setStoragePoolAllocators(List storagePoolAllocators) { + public void setStoragePoolAllocators(final List storagePoolAllocators) { _storagePoolAllocators = storagePoolAllocators; } @@ -3596,15 +3613,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // @MessageHandler(topic = Topics.VM_POWER_STATE) - private void HandlePowerStateReport(String subject, String senderAddress, Object args) { - assert (args != null); - Long vmId = (Long)args; + private void HandlePowerStateReport(final String subject, final String senderAddress, final Object args) { + assert args != null; + final Long vmId = (Long)args; - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vmId); if (pendingWorkJobs.size() == 0 && !_haMgr.hasPendingHaWork(vmId)) { // there is no pending operation job - VMInstanceVO vm = _vmDao.findById(vmId); + final VMInstanceVO vm = _vmDao.findById(vmId); if (vm != null) { switch (vm.getPowerState()) { case PowerOn: @@ -3616,11 +3633,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac handlePowerOffReportWithNoPendingJobsOnVM(vm); break; - // PowerUnknown shouldn't be reported, it is a derived - // VM power state from host state (host un-reachable) + // PowerUnknown shouldn't be reported, it is a derived + // VM power state from host state (host un-reachable) case PowerUnknown: default: - assert (false); + assert false; break; } } else { @@ -3635,7 +3652,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - private void handlePowerOnReportWithNoPendingJobsOnVM(VMInstanceVO vm) { + private void handlePowerOnReportWithNoPendingJobsOnVM(final VMInstanceVO vm) { // // 1) handle left-over transitional VM states // 2) handle out of band VM live migration @@ -3648,7 +3665,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn("Unexpected VM state transition exception, race-condition?", e); } @@ -3657,15 +3674,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // we need to alert admin or user about this risky state transition _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() - + ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset"); + + ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset"); break; case Running: try { - if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue()) + if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue()) { s_logger.info("Detected out of band VM migration from host " + vm.getHostId() + " to host " + vm.getPowerHostId()); + } stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn("Unexpected VM state transition exception, race-condition?", e); } @@ -3677,12 +3695,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn("Unexpected VM state transition exception, race-condition?", e); } _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() - + " -> Running) from out-of-context transition. VM network environment may need to be reset"); + + " -> Running) from out-of-context transition. VM network environment may need to be reset"); s_logger.info("VM " + vm.getInstanceName() + " is sync-ed to at Running state according to power-on report from hypervisor"); break; @@ -3697,7 +3715,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.info("VM " + vm.getInstanceName() + " is at " + vm.getState() + " and we received a power-on report while there is no pending jobs on it"); try { stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn("Unexpected VM state transition exception, race-condition?", e); } s_logger.info("VM " + vm.getInstanceName() + " is sync-ed to at Running state according to power-on report from hypervisor"); @@ -3711,7 +3729,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - private void handlePowerOffReportWithNoPendingJobsOnVM(VMInstanceVO vm) { + private void handlePowerOffReportWithNoPendingJobsOnVM(final VMInstanceVO vm) { // 1) handle left-over transitional VM states // 2) handle out of sync stationary states, schedule force-stop to release resources @@ -3725,15 +3743,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.info("VM " + vm.getInstanceName() + " is at " + vm.getState() + " and we received a power-off report while there is no pending jobs on it"); if(vm.isHaEnabled() && vm.getState() == State.Running && vm.getHypervisorType() != HypervisorType.VMware && vm.getHypervisorType() != HypervisorType.Hyperv) { s_logger.info("Detected out-of-band stop of a HA enabled VM " + vm.getInstanceName() + ", will schedule restart"); - if(!_haMgr.hasPendingHaWork(vm.getId())) + if(!_haMgr.hasPendingHaWork(vm.getId())) { _haMgr.scheduleRestart(vm, true); - else + } else { s_logger.info("VM " + vm.getInstanceName() + " already has an pending HA task working on it"); + } return; } - VirtualMachineGuru vmGuru = getVmGuru(vm); - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + final VirtualMachineGuru vmGuru = getVmGuru(vm); + final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); if (!sendStop(vmGuru, profile, true, true)) { // In case StopCommand fails, don't proceed further return; @@ -3741,13 +3760,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac try { stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOffReport, null); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.warn("Unexpected VM state transition exception, race-condition?", e); } _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() - + " -> Stopped) from out-of-context transition."); + + " -> Stopped) from out-of-context transition."); s_logger.info("VM " + vm.getInstanceName() + " is sync-ed to at Stopped state according to power-off report from hypervisor"); @@ -3763,7 +3782,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - private void scanStalledVMInTransitionStateOnUpHost(long hostId) { + private void scanStalledVMInTransitionStateOnUpHost(final long hostId) { // // Check VM that is stuck in Starting, Stopping, Migrating states, we won't check // VMs in expunging state (this need to be handled specially) @@ -3780,47 +3799,48 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // and a VM stalls for status update, we will consider them to be powered off // (which is relatively safe to do so) - long stallThresholdInMs = VmJobStateReportInterval.value() + (VmJobStateReportInterval.value() >> 1); - Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - stallThresholdInMs); - List mostlikelyStoppedVMs = listStalledVMInTransitionStateOnUpHost(hostId, cutTime); - for (Long vmId : mostlikelyStoppedVMs) { - VMInstanceVO vm = _vmDao.findById(vmId); - assert (vm != null); + final long stallThresholdInMs = VmJobStateReportInterval.value() + (VmJobStateReportInterval.value() >> 1); + final Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - stallThresholdInMs); + final List mostlikelyStoppedVMs = listStalledVMInTransitionStateOnUpHost(hostId, cutTime); + for (final Long vmId : mostlikelyStoppedVMs) { + final VMInstanceVO vm = _vmDao.findById(vmId); + assert vm != null; handlePowerOffReportWithNoPendingJobsOnVM(vm); } - List vmsWithRecentReport = listVMInTransitionStateWithRecentReportOnUpHost(hostId, cutTime); - for (Long vmId : vmsWithRecentReport) { - VMInstanceVO vm = _vmDao.findById(vmId); - assert (vm != null); - if (vm.getPowerState() == PowerState.PowerOn) + final List vmsWithRecentReport = listVMInTransitionStateWithRecentReportOnUpHost(hostId, cutTime); + for (final Long vmId : vmsWithRecentReport) { + final VMInstanceVO vm = _vmDao.findById(vmId); + assert vm != null; + if (vm.getPowerState() == PowerState.PowerOn) { handlePowerOnReportWithNoPendingJobsOnVM(vm); - else + } else { handlePowerOffReportWithNoPendingJobsOnVM(vm); + } } } private void scanStalledVMInTransitionStateOnDisconnectedHosts() { - Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - VmOpWaitInterval.value() * 1000); - List stuckAndUncontrollableVMs = listStalledVMInTransitionStateOnDisconnectedHosts(cutTime); - for (Long vmId : stuckAndUncontrollableVMs) { - VMInstanceVO vm = _vmDao.findById(vmId); + final Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - VmOpWaitInterval.value() * 1000); + final List stuckAndUncontrollableVMs = listStalledVMInTransitionStateOnDisconnectedHosts(cutTime); + for (final Long vmId : stuckAndUncontrollableVMs) { + final VMInstanceVO vm = _vmDao.findById(vmId); // We now only alert administrator about this situation _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState() - + " state and its host is unreachable for too long"); + + " state and its host is unreachable for too long"); } } // VMs that in transitional state without recent power state report - private List listStalledVMInTransitionStateOnUpHost(long hostId, Date cutTime) { - String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + + private List listStalledVMInTransitionStateOnUpHost(final long hostId, final Date cutTime) { + final String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + "AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; - List l = new ArrayList(); + final List l = new ArrayList(); TransactionLegacy txn = null; try { txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); @@ -3832,29 +3852,30 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac pstmt.setLong(1, hostId); pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime)); pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal()); - ResultSet rs = pstmt.executeQuery(); + final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { l.add(rs.getLong(1)); } - } catch (SQLException e) { - } catch (Throwable e) { + } catch (final SQLException e) { + } catch (final Throwable e) { } } finally { - if (txn != null) + if (txn != null) { txn.close(); + } } return l; } // VMs that in transitional state and recently have power state update - private List listVMInTransitionStateWithRecentReportOnUpHost(long hostId, Date cutTime) { - String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + + private List listVMInTransitionStateWithRecentReportOnUpHost(final long hostId, final Date cutTime) { + final String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + "AND h.id = ? AND i.power_state_update_time > ? AND i.host_id = h.id " + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; - List l = new ArrayList(); + final List l = new ArrayList(); TransactionLegacy txn = null; try { txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); @@ -3865,27 +3886,28 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac pstmt.setLong(1, hostId); pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime)); pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal()); - ResultSet rs = pstmt.executeQuery(); + final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { l.add(rs.getLong(1)); } - } catch (SQLException e) { - } catch (Throwable e) { + } catch (final SQLException e) { + } catch (final Throwable e) { } return l; } finally { - if (txn != null) + if (txn != null) { txn.close(); + } } } - private List listStalledVMInTransitionStateOnDisconnectedHosts(Date cutTime) { - String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status != 'UP' " + + private List listStalledVMInTransitionStateOnDisconnectedHosts(final Date cutTime) { + final String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status != 'UP' " + "AND i.power_state_update_time < ? AND i.host_id = h.id " + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; - List l = new ArrayList(); + final List l = new ArrayList(); TransactionLegacy txn = null; try { txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); @@ -3895,17 +3917,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime)); pstmt.setInt(2, JobInfo.Status.IN_PROGRESS.ordinal()); - ResultSet rs = pstmt.executeQuery(); + final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { l.add(rs.getLong(1)); } - } catch (SQLException e) { - } catch (Throwable e) { + } catch (final SQLException e) { + } catch (final Throwable e) { } return l; } finally { - if (txn != null) + if (txn != null) { txn.close(); + } } } @@ -3920,10 +3943,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() { @Override public boolean checkCondition() { - AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); - assert (jobVo != null); - if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) + final AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); + assert jobVo != null; + if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) { return true; + } return false; } }, Topics.VM_POWER_STATE, AsyncJob.Topics.JOB_STATE); @@ -3943,10 +3967,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() { @Override public boolean checkCondition() { - AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); - assert (jobVo != null); - if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) + final AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); + assert jobVo != null; + if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) { return true; + } return false; } @@ -3975,11 +4000,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); VmWorkJobVO workJob = null; - List pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkStart.class.getName()); if (pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { workJob = new VmWorkJobVO(context.getContextId()); @@ -3995,7 +4020,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER); + final VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER); workInfo.setPlan(planToDeploy); workInfo.setParams(params); if (planner != null) { @@ -4019,13 +4044,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( vm.getType(), vm.getId(), VmWorkStop.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { workJob = new VmWorkJobVO(context.getContextId()); @@ -4041,7 +4066,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, cleanup); + final VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, cleanup); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); @@ -4062,13 +4087,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkReboot.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { workJob = new VmWorkJobVO(context.getContextId()); @@ -4084,7 +4109,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, params); + final VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, params); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); @@ -4103,13 +4128,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkMigrate.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4125,7 +4150,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest); + final VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); @@ -4144,13 +4169,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkMigrateAway.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { workJob = new VmWorkJobVO(context.getContextId()); @@ -4165,7 +4190,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkMigrateAway workInfo = new VmWorkMigrateAway(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId); + final VmWorkMigrateAway workInfo = new VmWorkMigrateAway(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); } @@ -4186,13 +4211,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkMigrateWithStorage.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4208,7 +4233,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(), + final VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, destHostId, volumeToPool); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); @@ -4229,13 +4254,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkMigrateForScale.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4251,7 +4276,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(), + final VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest, newSvcOfferingId); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); @@ -4271,13 +4296,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkStorageMigration.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4293,7 +4318,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(), + final VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, destPool.getId()); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); @@ -4311,13 +4336,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkAddVmToNetwork.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4333,7 +4358,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(), + final VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network.getId(), requested); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); @@ -4351,13 +4376,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkRemoveNicFromVm.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4373,7 +4398,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(), + final VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, nic.getId()); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); @@ -4391,13 +4416,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkRemoveVmFromNetwork.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4413,7 +4438,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(), + final VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network, broadcastUri); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); @@ -4434,13 +4459,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + final List pendingWorkJobs = _workJobDao.listPendingWorkJobs( VirtualMachine.Type.Instance, vm.getId(), VmWorkReconfigure.class.getName()); VmWorkJobVO workJob = null; if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); + assert pendingWorkJobs.size() == 1; workJob = pendingWorkJobs.get(0); } else { @@ -4456,7 +4481,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac workJob.setRelated(AsyncJobExecutionContext.getOriginJobId()); // save work context info (there are some duplications) - VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(), + final VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, newServiceOffering.getId(), reconfiguringOnExistingHost); workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); @@ -4468,52 +4493,52 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @ReflectionUse - private Pair orchestrateStart(VmWorkStart work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateStart(final VmWorkStart work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; orchestrateStart(vm.getUuid(), work.getParams(), work.getPlan(), _dpMgr.getDeploymentPlannerByName(work.getDeploymentPlanner())); return new Pair(JobInfo.Status.SUCCEEDED, null); } @ReflectionUse - private Pair orchestrateStop(VmWorkStop work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateStop(final VmWorkStop work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; orchestrateStop(vm.getUuid(), work.isCleanup()); return new Pair(JobInfo.Status.SUCCEEDED, null); } @ReflectionUse - private Pair orchestrateMigrate(VmWorkMigrate work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateMigrate(final VmWorkMigrate work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; orchestrateMigrate(vm.getUuid(), work.getSrcHostId(), work.getDeployDestination()); return new Pair(JobInfo.Status.SUCCEEDED, null); } @ReflectionUse - private Pair orchestrateMigrateAway(VmWorkMigrateAway work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateMigrateAway(final VmWorkMigrateAway work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; try { orchestrateMigrateAway(vm.getUuid(), work.getSrcHostId(), null); - } catch (InsufficientServerCapacityException e) { + } catch (final InsufficientServerCapacityException e) { s_logger.warn("Failed to deploy vm " + vm.getId() + " with original planner, sending HAPlanner"); orchestrateMigrateAway(vm.getUuid(), work.getSrcHostId(), _haMgr.getHAPlanner()); } @@ -4522,12 +4547,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @ReflectionUse - private Pair orchestrateMigrateWithStorage(VmWorkMigrateWithStorage work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateMigrateWithStorage(final VmWorkMigrateWithStorage work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; orchestrateMigrateWithStorage(vm.getUuid(), work.getSrcHostId(), work.getDestHostId(), @@ -4536,12 +4561,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @ReflectionUse - private Pair orchestrateMigrateForScale(VmWorkMigrateForScale work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateMigrateForScale(final VmWorkMigrateForScale work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; orchestrateMigrateForScale(vm.getUuid(), work.getSrcHostId(), work.getDeployDestination(), @@ -4550,66 +4575,66 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @ReflectionUse - private Pair orchestrateReboot(VmWorkReboot work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateReboot(final VmWorkReboot work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; orchestrateReboot(vm.getUuid(), work.getParams()); return new Pair(JobInfo.Status.SUCCEEDED, null); } @ReflectionUse - private Pair orchestrateAddVmToNetwork(VmWorkAddVmToNetwork work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateAddVmToNetwork(final VmWorkAddVmToNetwork work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; - Network network = _networkDao.findById(work.getNetworkId()); - NicProfile nic = orchestrateAddVmToNetwork(vm, network, + final Network network = _networkDao.findById(work.getNetworkId()); + final NicProfile nic = orchestrateAddVmToNetwork(vm, network, work.getRequestedNicProfile()); return new Pair(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(nic)); } @ReflectionUse - private Pair orchestrateRemoveNicFromVm(VmWorkRemoveNicFromVm work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateRemoveNicFromVm(final VmWorkRemoveNicFromVm work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); - NicVO nic = _entityMgr.findById(NicVO.class, work.getNicId()); - boolean result = orchestrateRemoveNicFromVm(vm, nic); + assert vm != null; + final NicVO nic = _entityMgr.findById(NicVO.class, work.getNicId()); + final boolean result = orchestrateRemoveNicFromVm(vm, nic); return new Pair(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(result)); } @ReflectionUse - private Pair orchestrateRemoveVmFromNetwork(VmWorkRemoveVmFromNetwork work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateRemoveVmFromNetwork(final VmWorkRemoveVmFromNetwork work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); - boolean result = orchestrateRemoveVmFromNetwork(vm, + assert vm != null; + final boolean result = orchestrateRemoveVmFromNetwork(vm, work.getNetwork(), work.getBroadcastUri()); return new Pair(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(result)); } @ReflectionUse - private Pair orchestrateReconfigure(VmWorkReconfigure work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateReconfigure(final VmWorkReconfigure work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); + assert vm != null; - ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), work.getNewServiceOfferingId()); + final ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), work.getNewServiceOfferingId()); reConfigureVm(vm.getUuid(), newServiceOffering, work.isSameHost()); @@ -4617,25 +4642,25 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @ReflectionUse - private Pair orchestrateStorageMigration(VmWorkStorageMigration work) throws Exception { - VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + private Pair orchestrateStorageMigration(final VmWorkStorageMigration work) throws Exception { + final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); if (vm == null) { s_logger.info("Unable to find vm " + work.getVmId()); } - assert (vm != null); - StoragePool pool = (PrimaryDataStoreInfo)dataStoreMgr.getPrimaryDataStore(work.getDestStoragePoolId()); + assert vm != null; + final StoragePool pool = (PrimaryDataStoreInfo)dataStoreMgr.getPrimaryDataStore(work.getDestStoragePoolId()); orchestrateStorageMigration(vm.getUuid(), pool); return new Pair(JobInfo.Status.SUCCEEDED, null); } @Override - public Pair handleVmWorkJob(VmWork work) throws Exception { + public Pair handleVmWorkJob(final VmWork work) throws Exception { return _jobHandlerProxy.handleVmWorkJob(work); } - private VmWorkJobVO createPlaceHolderWork(long instanceId) { - VmWorkJobVO workJob = new VmWorkJobVO(""); + private VmWorkJobVO createPlaceHolderWork(final long instanceId) { + final VmWorkJobVO workJob = new VmWorkJobVO(""); workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_PLACEHOLDER); workJob.setCmd(""); diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index a9ab0c953f3..37abd7182a7 100644 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -169,13 +169,13 @@ import com.cloud.network.router.VirtualRouter.RedundantState; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; +import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.LoadBalancerContainer.Scheme; import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.StaticNatImpl; import com.cloud.network.rules.StaticNatRule; -import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.vpn.Site2SiteVpnManager; import com.cloud.offering.NetworkOffering; @@ -745,10 +745,14 @@ Configurable, StateListener { final List routerNics = _nicDao.listByVmId(router.getId()); for (final Nic routerNic : routerNics) { final Network network = _networkModel.getNetwork(routerNic.getNetworkId()); - // Send network usage command for public nic in VPC - // VR - // Send network usage command for isolated guest nic - // of non VPC VR + // Send network usage command for public nic in VPC VR + // Send network usage command for isolated guest nic of non) VPC VR + + //[TODO] Avoiding the NPE now, but I have to find out what is going on with the network. - Wilder Rodrigues + if (network == null) { + s_logger.error("Could not find a network with ID => " + routerNic.getNetworkId() + ". It might be a problem!"); + continue; + } if (forVpc && network.getTrafficType() == TrafficType.Public || !forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Isolated) { final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(), forVpc, routerNic.getIp4Address()); @@ -1917,12 +1921,12 @@ Configurable, StateListener { } } - private void createDefaultEgressFirewallRule(List rules, long networkId) { + private void createDefaultEgressFirewallRule(final List rules, final long networkId) { String systemRule = null; Boolean defaultEgressPolicy = false; - NetworkVO network = _networkDao.findById(networkId); - NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + final NetworkVO network = _networkDao.findById(networkId); + final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); defaultEgressPolicy = offering.getEgressDefaultPolicy(); @@ -1930,10 +1934,10 @@ Configurable, StateListener { if (!defaultEgressPolicy) { systemRule = String.valueOf(FirewallRule.FirewallRuleType.System); - List sourceCidr = new ArrayList(); + final List sourceCidr = new ArrayList(); sourceCidr.add(NetUtils.ALL_CIDRS); - FirewallRule rule = new FirewallRuleVO(null, null, null, null, "all", networkId, network.getAccountId(), network.getDomainId(), Purpose.Firewall, sourceCidr, + final FirewallRule rule = new FirewallRuleVO(null, null, null, null, "all", networkId, network.getAccountId(), network.getDomainId(), Purpose.Firewall, sourceCidr, null, null, null, FirewallRule.TrafficType.Egress, FirewallRule.FirewallRuleType.System); rules.add(rule); @@ -2023,6 +2027,7 @@ Configurable, StateListener { final String errorDetails = "Details: " + answer.getDetails() + " " + answer.toString(); // add alerts for the failed commands _alertMgr.sendAlert(AlertService.AlertType.ALERT_TYPE_DOMAIN_ROUTER, router.getDataCenterId(), router.getPodIdToDeployIn(), errorMessage, errorDetails); + s_logger.error(answer.getDetails()); s_logger.warn(errorMessage); // Stop the router if any of the commands failed return false; @@ -2590,12 +2595,12 @@ Configurable, StateListener { if (vo.getType() == VirtualMachine.Type.DomainRouter) { // opaque -> if (opaque != null && opaque instanceof Pair) { - Pair pair = (Pair)opaque; - Object first = pair.first(); - Object second = pair.second(); + final Pair pair = (Pair)opaque; + final Object first = pair.first(); + final Object second = pair.second(); // powerHostId cannot be null in case of out-of-band VM movement if (second != null && second instanceof Long) { - Long powerHostId = (Long)second; + final Long powerHostId = (Long)second; Long hostId = null; if (first != null && first instanceof Long) { hostId = (Long)first; @@ -2603,7 +2608,7 @@ Configurable, StateListener { // The following scenarios are due to out-of-band VM movement // 1. If VM is in stopped state in CS due to 'PowerMissing' report from old host (hostId is null) and then there is a 'PowerOn' report from new host // 2. If VM is in running state in CS and there is a 'PowerOn' report from new host - if (hostId == null || (hostId.longValue() != powerHostId.longValue())) { + if (hostId == null || hostId.longValue() != powerHostId.longValue()) { s_logger.info("Schedule a router reboot task as router " + vo.getId() + " is powered-on out-of-band, need to reboot to refresh network rules"); _executor.schedule(new RebootTask(vo.getId()), 1000, TimeUnit.MICROSECONDS); }