diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index 1a2f4e4bca1..3d8f86ce2dc 100644 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -30,12 +30,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.commons.lang.ObjectUtils; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - -import com.google.gson.Gson; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd; import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd; @@ -51,6 +45,9 @@ import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.commons.lang.ObjectUtils; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -172,6 +169,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.dao.VMInstanceDao; +import com.google.gson.Gson; @Component @Local({ResourceManager.class, ResourceService.class}) @@ -237,7 +235,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, return _discoverers; } - public void setDiscoverers(List discoverers) { + public void setDiscoverers(final List discoverers) { _discoverers = discoverers; } @@ -266,7 +264,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, private SearchBuilder _gpuAvailability; - private void insertListener(Integer event, ResourceListener listener) { + private void insertListener(final Integer event, final ResourceListener listener) { List lst = _lifeCycleListeners.get(event); if (lst == null) { lst = new ArrayList(); @@ -281,7 +279,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public void registerResourceEvent(Integer event, ResourceListener listener) { + public void registerResourceEvent(final Integer event, final ResourceListener listener) { synchronized (_lifeCycleListeners) { if ((event & ResourceListener.EVENT_DISCOVER_BEFORE) != 0) { insertListener(ResourceListener.EVENT_DISCOVER_BEFORE, listener); @@ -311,28 +309,28 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public void unregisterResourceEvent(ResourceListener listener) { + public void unregisterResourceEvent(final ResourceListener listener) { synchronized (_lifeCycleListeners) { - Iterator it = _lifeCycleListeners.entrySet().iterator(); + final Iterator it = _lifeCycleListeners.entrySet().iterator(); while (it.hasNext()) { - Map.Entry> items = (Map.Entry>)it.next(); - List lst = items.getValue(); + final Map.Entry> items = (Map.Entry>)it.next(); + final List lst = items.getValue(); lst.remove(listener); } } } - protected void processResourceEvent(Integer event, Object... params) { - List lst = _lifeCycleListeners.get(event); + protected void processResourceEvent(final Integer event, final Object... params) { + final List lst = _lifeCycleListeners.get(event); if (lst == null || lst.size() == 0) { return; } String eventName; - for (ResourceListener l : lst) { + for (final ResourceListener l : lst) { if (event.equals(ResourceListener.EVENT_DISCOVER_BEFORE)) { l.processDiscoverEventBefore((Long)params[0], (Long)params[1], (Long)params[2], (URI)params[3], (String)params[4], (String)params[5], - (List)params[6]); + (List)params[6]); eventName = "EVENT_DISCOVER_BEFORE"; } else if (event.equals(ResourceListener.EVENT_DISCOVER_AFTER)) { l.processDiscoverEventAfter((Map>)params[0]); @@ -365,13 +363,13 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @DB @Override - public List discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, ResourceInUseException { - long dcId = cmd.getZoneId(); - long podId = cmd.getPodId(); - String clusterName = cmd.getClusterName(); + public List discoverCluster(final AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, ResourceInUseException { + final long dcId = cmd.getZoneId(); + final long podId = cmd.getPodId(); + final String clusterName = cmd.getClusterName(); String url = cmd.getUrl(); - String username = cmd.getUsername(); - String password = cmd.getPassword(); + final String username = cmd.getUsername(); + final String password = cmd.getPassword(); if (url != null) { url = URLDecoder.decode(url); @@ -380,21 +378,21 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, URI uri = null; // Check if the zone exists in the system - DataCenterVO zone = _dcDao.findById(dcId); + final DataCenterVO zone = _dcDao.findById(dcId); if (zone == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can't find zone by the id specified"); + final InvalidParameterValueException ex = new InvalidParameterValueException("Can't find zone by the id specified"); ex.addProxyObject(String.valueOf(dcId), "dcId"); throw ex; } - Account account = CallContext.current().getCallingAccount(); + final Account account = CallContext.current().getCallingAccount(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) { - PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); + final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); ex.addProxyObject(zone.getUuid(), "dcId"); throw ex; } - HostPodVO pod = _podDao.findById(podId); + final HostPodVO pod = _podDao.findById(podId); if (pod == null) { throw new InvalidParameterValueException("Can't find pod with specified podId " + podId); } @@ -405,7 +403,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } // check if pod belongs to the zone if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Pod with specified id doesn't belong to the zone " + dcId); + final InvalidParameterValueException ex = new InvalidParameterValueException("Pod with specified id doesn't belong to the zone " + dcId); ex.addProxyObject(pod.getUuid(), "podId"); ex.addProxyObject(zone.getUuid(), "dcId"); throw ex; @@ -420,7 +418,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, throw new InvalidParameterValueException("Please specify a hypervisor"); } - Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(cmd.getHypervisor()); + final Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(cmd.getHypervisor()); if (hypervisorType == null) { s_logger.error("Unable to resolve " + cmd.getHypervisor() + " to a valid supported hypervisor type"); throw new InvalidParameterValueException("Unable to resolve " + cmd.getHypervisor() + " to a supported "); @@ -445,7 +443,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (cmd.getAllocationState() != null && !cmd.getAllocationState().isEmpty()) { try { allocationState = Grouping.AllocationState.valueOf(cmd.getAllocationState()); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { throw new InvalidParameterValueException("Unable to resolve Allocation State '" + cmd.getAllocationState() + "' to a supported state"); } } @@ -453,18 +451,18 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, allocationState = Grouping.AllocationState.Enabled; } - Discoverer discoverer = getMatchingDiscover(hypervisorType); + final Discoverer discoverer = getMatchingDiscover(hypervisorType); if (discoverer == null) { throw new InvalidParameterValueException("Could not find corresponding resource manager for " + cmd.getHypervisor()); } if (hypervisorType == HypervisorType.VMware) { - Map allParams = cmd.getFullUrlParams(); + final Map allParams = cmd.getFullUrlParams(); discoverer.putParam(allParams); } - List result = new ArrayList(); + final List result = new ArrayList(); ClusterVO cluster = new ClusterVO(dcId, podId, clusterName); cluster.setHypervisorType(hypervisorType.toString()); @@ -473,9 +471,9 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, cluster.setAllocationState(allocationState); try { cluster = _clusterDao.persist(cluster); - } catch (Exception e) { + } catch (final Exception e) { // no longer tolerate exception during the cluster creation phase - CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod and data center with specified ids", e); + final CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod and data center with specified ids", e); // Get the pod VO object's table name. ex.addProxyObject(pod.getUuid(), "podId"); ex.addProxyObject(zone.getUuid(), "dcId"); @@ -484,10 +482,10 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, result.add(cluster); if (clusterType == Cluster.ClusterType.CloudManaged) { - Map details = new HashMap(); + final Map details = new HashMap(); // should do this nicer perhaps ? if (hypervisorType == HypervisorType.Ovm3) { - Map allParams = cmd.getFullUrlParams(); + final Map allParams = cmd.getFullUrlParams(); details.put("ovm3vip", allParams.get("ovm3vip")); details.put("ovm3pool", allParams.get("ovm3pool")); details.put("ovm3cluster", allParams.get("ovm3cluster")); @@ -499,7 +497,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } // save cluster details for later cluster/host cross-checking - Map details = new HashMap(); + final Map details = new HashMap(); details.put("url", url); details.put("username", username); details.put("password", password); @@ -518,19 +516,19 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format http://hostname/path"); } } - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new InvalidParameterValueException(url + " is not a valid uri"); } - List hosts = new ArrayList(); + final List hosts = new ArrayList(); Map> resources = null; resources = discoverer.find(dcId, podId, cluster.getId(), uri, username, password, null); if (resources != null) { - for (Map.Entry> entry : resources.entrySet()) { - ServerResource resource = entry.getKey(); + for (final Map.Entry> entry : resources.entrySet()) { + final ServerResource resource = entry.getKey(); - HostVO host = (HostVO)createHostAndAgent(resource, entry.getValue(), true, null, false); + final HostVO host = (HostVO)createHostAndAgent(resource, entry.getValue(), true, null, false); if (host != null) { hosts.add(host); } @@ -552,8 +550,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public Discoverer getMatchingDiscover(Hypervisor.HypervisorType hypervisorType) { - for (Discoverer discoverer : _discoverers) { + public Discoverer getMatchingDiscover(final Hypervisor.HypervisorType hypervisorType) { + for (final Discoverer discoverer : _discoverers) { if (discoverer.getHypervisorType() == hypervisorType) { return discoverer; } @@ -562,15 +560,15 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List discoverHosts(AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { + public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); - Long podId = cmd.getPodId(); - Long clusterId = cmd.getClusterId(); + final Long podId = cmd.getPodId(); + final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); - String url = cmd.getUrl(); - String username = cmd.getUsername(); - String password = cmd.getPassword(); - List hostTags = cmd.getHostTags(); + final String url = cmd.getUrl(); + final String username = cmd.getUsername(); + final String password = cmd.getPassword(); + final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); @@ -580,17 +578,17 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } if (clusterId != null) { - ClusterVO cluster = _clusterDao.findById(clusterId); + final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); + final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { - List hosts = listAllHostsInCluster(clusterId); + final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { - CloudRuntimeException ex = - new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); + final CloudRuntimeException ex = + new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } @@ -602,40 +600,40 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List discoverHosts(AddSecondaryStorageCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { - Long dcId = cmd.getZoneId(); - String url = cmd.getUrl(); + public List discoverHosts(final AddSecondaryStorageCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { + final Long dcId = cmd.getZoneId(); + final String url = cmd.getUrl(); return discoverHostsFull(dcId, null, null, null, url, null, null, "SecondaryStorage", null, null, false); } - private List discoverHostsFull(Long dcId, Long podId, Long clusterId, String clusterName, String url, String username, String password, - String hypervisorType, List hostTags, Map params, boolean deferAgentCreation) throws IllegalArgumentException, DiscoveryException, - InvalidParameterValueException { + private List discoverHostsFull(final Long dcId, final Long podId, Long clusterId, final String clusterName, String url, String username, String password, + final String hypervisorType, final List hostTags, final Map params, final boolean deferAgentCreation) throws IllegalArgumentException, DiscoveryException, + InvalidParameterValueException { URI uri = null; // Check if the zone exists in the system - DataCenterVO zone = _dcDao.findById(dcId); + final DataCenterVO zone = _dcDao.findById(dcId); if (zone == null) { throw new InvalidParameterValueException("Can't find zone by id " + dcId); } - Account account = CallContext.current().getCallingAccount(); + final Account account = CallContext.current().getCallingAccount(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) { - PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); + final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); ex.addProxyObject(zone.getUuid(), "dcId"); throw ex; } // Check if the pod exists in the system if (podId != null) { - HostPodVO pod = _podDao.findById(podId); + final HostPodVO pod = _podDao.findById(podId); if (pod == null) { throw new InvalidParameterValueException("Can't find pod by id " + podId); } // check if pod belongs to the zone if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) { - InvalidParameterValueException ex = - new InvalidParameterValueException("Pod with specified podId" + podId + " doesn't belong to the zone with specified zoneId" + dcId); + final InvalidParameterValueException ex = + new InvalidParameterValueException("Pod with specified podId" + podId + " doesn't belong to the zone with specified zoneId" + dcId); ex.addProxyObject(pod.getUuid(), "podId"); ex.addProxyObject(zone.getUuid(), "dcId"); throw ex; @@ -665,25 +663,25 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, // already have a lot of information // in cluster object, to simplify user input, we will construct // neccessary information here - Map clusterDetails = _clusterDetailsDao.findDetails(clusterId); + final Map clusterDetails = _clusterDetailsDao.findDetails(clusterId); username = clusterDetails.get("username"); - assert (username != null); + assert username != null; password = clusterDetails.get("password"); - assert (password != null); + assert password != null; try { uri = new URI(UriUtils.encodeURIComponent(url)); url = clusterDetails.get("url") + "/" + uri.getHost(); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new InvalidParameterValueException(url + " is not a valid uri"); } } } if (clusterName != null) { - HostPodVO pod = _podDao.findById(podId); + final HostPodVO pod = _podDao.findById(podId); if (pod == null) { throw new InvalidParameterValueException("Can't find pod by id " + podId); } @@ -691,11 +689,11 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, cluster.setHypervisorType(hypervisorType); try { cluster = _clusterDao.persist(cluster); - } catch (Exception e) { + } catch (final Exception e) { cluster = _clusterDao.findBy(clusterName, podId); if (cluster == null) { - CloudRuntimeException ex = - new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod with specified podId and data center with specified dcID", e); + final CloudRuntimeException ex = + new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod with specified podId and data center with specified dcID", e); ex.addProxyObject(pod.getUuid(), "podId"); ex.addProxyObject(zone.getUuid(), "dcId"); throw ex; @@ -703,8 +701,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } clusterId = cluster.getId(); if (_clusterDetailsDao.findDetail(clusterId, "cpuOvercommitRatio") == null) { - ClusterDetailsVO cluster_cpu_detail = new ClusterDetailsVO(clusterId, "cpuOvercommitRatio", "1"); - ClusterDetailsVO cluster_memory_detail = new ClusterDetailsVO(clusterId, "memoryOvercommitRatio", "1"); + final ClusterDetailsVO cluster_cpu_detail = new ClusterDetailsVO(clusterId, "cpuOvercommitRatio", "1"); + final ClusterDetailsVO cluster_memory_detail = new ClusterDetailsVO(clusterId, "memoryOvercommitRatio", "1"); _clusterDetailsDao.persist(cluster_cpu_detail); _clusterDetailsDao.persist(cluster_memory_detail); } @@ -721,20 +719,20 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } else if (uri.getScheme().equalsIgnoreCase("cifs")) { // Don't validate against a URI encoded URI. - URI cifsUri = new URI(url); - String warnMsg = UriUtils.getCifsUriParametersProblems(cifsUri); + final URI cifsUri = new URI(url); + final String warnMsg = UriUtils.getCifsUriParametersProblems(cifsUri); if (warnMsg != null) { throw new InvalidParameterValueException(warnMsg); } } - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new InvalidParameterValueException(url + " is not a valid uri"); } - List hosts = new ArrayList(); + final List hosts = new ArrayList(); s_logger.info("Trying to add a new host at " + url + " in data center " + dcId); boolean isHypervisorTypeSupported = false; - for (Discoverer discoverer : _discoverers) { + for (final Discoverer discoverer : _discoverers) { if (params != null) { discoverer.putParam(params); } @@ -748,25 +746,25 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, processResourceEvent(ResourceListener.EVENT_DISCOVER_BEFORE, dcId, podId, clusterId, uri, username, password, hostTags); try { resources = discoverer.find(dcId, podId, clusterId, uri, username, password, hostTags); - } catch (DiscoveryException e) { + } catch (final DiscoveryException e) { throw e; - } catch (Exception e) { + } catch (final Exception e) { s_logger.info("Exception in host discovery process with discoverer: " + discoverer.getName() + ", skip to another discoverer if there is any"); } processResourceEvent(ResourceListener.EVENT_DISCOVER_AFTER, resources); if (resources != null) { - for (Map.Entry> entry : resources.entrySet()) { - ServerResource resource = entry.getKey(); + for (final Map.Entry> entry : resources.entrySet()) { + final ServerResource resource = entry.getKey(); /* * For KVM, if we go to here, that means kvm agent is * already connected to mgt svr. */ if (resource instanceof KvmDummyResourceBase) { - Map details = entry.getValue(); - String guid = details.get("guid"); - List kvmHosts = listAllUpAndEnabledHosts(Host.Type.Routing, clusterId, podId, dcId); - for (HostVO host : kvmHosts) { + final Map details = entry.getValue(); + final String guid = details.get("guid"); + final List kvmHosts = listAllUpAndEnabledHosts(Host.Type.Routing, clusterId, podId, dcId); + for (final HostVO host : kvmHosts) { if (host.getGuid().equalsIgnoreCase(guid)) { if (hostTags != null) { if (s_logger.isTraceEnabled()) { @@ -798,7 +796,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } if (!isHypervisorTypeSupported) { - String msg = "Do not support HypervisorType " + hypervisorType + " for " + url; + final String msg = "Do not support HypervisorType " + hypervisorType + " for " + url; s_logger.warn(msg); throw new DiscoveryException(msg); } @@ -807,12 +805,12 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public Host getHost(long hostId) { + public Host getHost(final long hostId) { return _hostDao.findById(hostId); } @DB - protected boolean doDeleteHost(final long hostId, boolean isForced, final boolean isForceDeleteStorage) { + protected boolean doDeleteHost(final long hostId, final boolean isForced, final boolean isForceDeleteStorage) { _accountMgr.getActiveUser(CallContext.current().getCallingUserId()); // Verify that host exists final HostVO host = _hostDao.findById(hostId); @@ -823,20 +821,20 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (!isForced && host.getResourceState() != ResourceState.Maintenance) { throw new CloudRuntimeException("Host " + host.getUuid() + - " cannot be deleted as it is not in maintenance mode. Either put the host into maintenance or perform a forced deletion."); + " cannot be deleted as it is not in maintenance mode. Either put the host into maintenance or perform a forced deletion."); } // Get storage pool host mappings here because they can be removed as a // part of handleDisconnect later // TODO: find out the bad boy, what's a buggy logic! final List pools = _storagePoolHostDao.listByHostIdIncludingRemoved(hostId); - ResourceStateAdapter.DeleteHostAnswer answer = - (ResourceStateAdapter.DeleteHostAnswer)dispatchToStateAdapters(ResourceStateAdapter.Event.DELETE_HOST, false, host, isForced, - isForceDeleteStorage); + final ResourceStateAdapter.DeleteHostAnswer answer = + (ResourceStateAdapter.DeleteHostAnswer)dispatchToStateAdapters(ResourceStateAdapter.Event.DELETE_HOST, false, host, isForced, + isForceDeleteStorage); if (answer == null) { throw new CloudRuntimeException("No resource adapter respond to DELETE_HOST event for " + host.getName() + " id = " + hostId + ", hypervisorType is " + - host.getHypervisorType() + ", host type is " + host.getType()); + host.getHypervisorType() + ", host type is " + host.getType()); } if (answer.getIsException()) { @@ -849,78 +847,78 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, Transaction.execute(new TransactionCallbackNoReturn() { @Override - public void doInTransactionWithoutResult(TransactionStatus status) { + public void doInTransactionWithoutResult(final TransactionStatus status) { - _dcDao.releasePrivateIpAddress(host.getPrivateIpAddress(), host.getDataCenterId(), null); - _agentMgr.disconnectWithoutInvestigation(hostId, Status.Event.Remove); + _dcDao.releasePrivateIpAddress(host.getPrivateIpAddress(), host.getDataCenterId(), null); + _agentMgr.disconnectWithoutInvestigation(hostId, Status.Event.Remove); - // delete host details - _hostDetailsDao.deleteDetails(hostId); + // delete host details + _hostDetailsDao.deleteDetails(hostId); - // if host is GPU enabled, delete GPU entries - _hostGpuGroupsDao.deleteGpuEntries(hostId); + // if host is GPU enabled, delete GPU entries + _hostGpuGroupsDao.deleteGpuEntries(hostId); - // delete host tags - _hostTagsDao.deleteTags(hostId); + // delete host tags + _hostTagsDao.deleteTags(hostId); - host.setGuid(null); - Long clusterId = host.getClusterId(); - host.setClusterId(null); - _hostDao.update(host.getId(), host); + host.setGuid(null); + final Long clusterId = host.getClusterId(); + host.setClusterId(null); + _hostDao.update(host.getId(), host); - _hostDao.remove(hostId); - if (clusterId != null) { - List hosts = listAllHostsInCluster(clusterId); - if (hosts.size() == 0) { - ClusterVO cluster = _clusterDao.findById(clusterId); - cluster.setGuid(null); - _clusterDao.update(clusterId, cluster); - } - } + _hostDao.remove(hostId); + if (clusterId != null) { + final List hosts = listAllHostsInCluster(clusterId); + if (hosts.size() == 0) { + final ClusterVO cluster = _clusterDao.findById(clusterId); + cluster.setGuid(null); + _clusterDao.update(clusterId, cluster); + } + } - try { - resourceStateTransitTo(host, ResourceState.Event.DeleteHost, _nodeId); - } catch (NoTransitionException e) { + try { + resourceStateTransitTo(host, ResourceState.Event.DeleteHost, _nodeId); + } catch (final NoTransitionException e) { s_logger.debug("Cannot transmit host " + host.getId() + " to Enabled state", e); - } + } - // Delete the associated entries in host ref table - _storagePoolHostDao.deletePrimaryRecordsForHost(hostId); + // Delete the associated entries in host ref table + _storagePoolHostDao.deletePrimaryRecordsForHost(hostId); - // Make sure any VMs that were marked as being on this host are cleaned up - List vms = _vmDao.listByHostId(hostId); - for (VMInstanceVO vm : vms) { - // this is how VirtualMachineManagerImpl does it when it syncs VM states - vm.setState(State.Stopped); - vm.setHostId(null); - _vmDao.persist(vm); - } + // Make sure any VMs that were marked as being on this host are cleaned up + final List vms = _vmDao.listByHostId(hostId); + for (final VMInstanceVO vm : vms) { + // this is how VirtualMachineManagerImpl does it when it syncs VM states + vm.setState(State.Stopped); + vm.setHostId(null); + _vmDao.persist(vm); + } - // For pool ids you got, delete local storage host entries in pool table - // where - for (StoragePoolHostVO pool : pools) { - Long poolId = pool.getPoolId(); - StoragePoolVO storagePool = _storagePoolDao.findById(poolId); - if (storagePool.isLocal() && isForceDeleteStorage) { - storagePool.setUuid(null); - storagePool.setClusterId(null); - _storagePoolDao.update(poolId, storagePool); - _storagePoolDao.remove(poolId); - s_logger.debug("Local storage id=" + poolId + " is removed as a part of host removal id=" + hostId); - } - } + // For pool ids you got, delete local storage host entries in pool table + // where + for (final StoragePoolHostVO pool : pools) { + final Long poolId = pool.getPoolId(); + final StoragePoolVO storagePool = _storagePoolDao.findById(poolId); + if (storagePool.isLocal() && isForceDeleteStorage) { + storagePool.setUuid(null); + storagePool.setClusterId(null); + _storagePoolDao.update(poolId, storagePool); + _storagePoolDao.remove(poolId); + s_logger.debug("Local storage id=" + poolId + " is removed as a part of host removal id=" + hostId); + } + } - // delete the op_host_capacity entry - Object[] capacityTypes = {Capacity.CAPACITY_TYPE_CPU, Capacity.CAPACITY_TYPE_MEMORY}; - SearchCriteria hostCapacitySC = _capacityDao.createSearchCriteria(); - hostCapacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, hostId); - hostCapacitySC.addAnd("capacityType", SearchCriteria.Op.IN, capacityTypes); - _capacityDao.remove(hostCapacitySC); - // remove from dedicated resources - DedicatedResourceVO dr = _dedicatedDao.findByHostId(hostId); - if (dr != null) { - _dedicatedDao.remove(dr.getId()); - } + // delete the op_host_capacity entry + final Object[] capacityTypes = {Capacity.CAPACITY_TYPE_CPU, Capacity.CAPACITY_TYPE_MEMORY}; + final SearchCriteria hostCapacitySC = _capacityDao.createSearchCriteria(); + hostCapacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, hostId); + hostCapacitySC.addAnd("capacityType", SearchCriteria.Op.IN, capacityTypes); + _capacityDao.remove(hostCapacitySC); + // remove from dedicated resources + final DedicatedResourceVO dr = _dedicatedDao.findByHostId(hostId); + if (dr != null) { + _dedicatedDao.remove(dr.getId()); + } } }); @@ -928,13 +926,13 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public boolean deleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage) { + public boolean deleteHost(final long hostId, final boolean isForced, final boolean isForceDeleteStorage) { try { - Boolean result = propagateResourceEvent(hostId, ResourceState.Event.DeleteHost); + final Boolean result = propagateResourceEvent(hostId, ResourceState.Event.DeleteHost); if (result != null) { return result; } - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { return false; } @@ -947,56 +945,56 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, try { Transaction.execute(new TransactionCallbackNoReturn() { @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - ClusterVO cluster = _clusterDao.lockRow(cmd.getId(), true); - if (cluster == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Cluster: " + cmd.getId() + " does not even exist. Delete call is ignored."); - } - throw new CloudRuntimeException("Cluster: " + cmd.getId() + " does not exist"); - } + public void doInTransactionWithoutResult(final TransactionStatus status) { + final ClusterVO cluster = _clusterDao.lockRow(cmd.getId(), true); + if (cluster == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Cluster: " + cmd.getId() + " does not even exist. Delete call is ignored."); + } + throw new CloudRuntimeException("Cluster: " + cmd.getId() + " does not exist"); + } - Hypervisor.HypervisorType hypervisorType = cluster.getHypervisorType(); + final Hypervisor.HypervisorType hypervisorType = cluster.getHypervisorType(); - List hosts = listAllHostsInCluster(cmd.getId()); - if (hosts.size() > 0) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Cluster: " + cmd.getId() + " still has hosts, can't remove"); - } - throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has hosts"); - } + final List hosts = listAllHostsInCluster(cmd.getId()); + if (hosts.size() > 0) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Cluster: " + cmd.getId() + " still has hosts, can't remove"); + } + throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has hosts"); + } - // don't allow to remove the cluster if it has non-removed storage - // pools - List storagePools = _storagePoolDao.listPoolsByCluster(cmd.getId()); - if (storagePools.size() > 0) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Cluster: " + cmd.getId() + " still has storage pools, can't remove"); - } - throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has storage pools"); - } + // don't allow to remove the cluster if it has non-removed storage + // pools + final List storagePools = _storagePoolDao.listPoolsByCluster(cmd.getId()); + if (storagePools.size() > 0) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Cluster: " + cmd.getId() + " still has storage pools, can't remove"); + } + throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has storage pools"); + } - if (_clusterDao.remove(cmd.getId())) { - _capacityDao.removeBy(null, null, null, cluster.getId(), null); - // If this cluster is of type vmware, and if the nexus vswitch - // global parameter setting is turned - // on, remove the row in cluster_vsm_map for this cluster id. - if (hypervisorType == HypervisorType.VMware && Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) { - _clusterVSMMapDao.removeByClusterId(cmd.getId()); - } - // remove from dedicated resources - DedicatedResourceVO dr = _dedicatedDao.findByClusterId(cluster.getId()); - if (dr != null) { - _dedicatedDao.remove(dr.getId()); - } - } + if (_clusterDao.remove(cmd.getId())) { + _capacityDao.removeBy(null, null, null, cluster.getId(), null); + // If this cluster is of type vmware, and if the nexus vswitch + // global parameter setting is turned + // on, remove the row in cluster_vsm_map for this cluster id. + if (hypervisorType == HypervisorType.VMware && Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) { + _clusterVSMMapDao.removeByClusterId(cmd.getId()); + } + // remove from dedicated resources + final DedicatedResourceVO dr = _dedicatedDao.findByClusterId(cluster.getId()); + if (dr != null) { + _dedicatedDao.remove(dr.getId()); + } + } } }); return true; - } catch (CloudRuntimeException e) { + } catch (final CloudRuntimeException e) { throw e; - } catch (Throwable t) { + } catch (final Throwable t) { s_logger.error("Unable to delete cluster: " + cmd.getId(), t); return false; } @@ -1004,14 +1002,14 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override @DB - public Cluster updateCluster(Cluster clusterToUpdate, String clusterType, String hypervisor, String allocationState, String managedstate) { + public Cluster updateCluster(final Cluster clusterToUpdate, final String clusterType, final String hypervisor, final String allocationState, final String managedstate) { - ClusterVO cluster = (ClusterVO)clusterToUpdate; + final ClusterVO cluster = (ClusterVO)clusterToUpdate; // Verify cluster information and update the cluster if needed boolean doUpdate = false; if (hypervisor != null && !hypervisor.isEmpty()) { - Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(hypervisor); + final Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(hypervisor); if (hypervisorType == null) { s_logger.error("Unable to resolve " + hypervisor + " to a valid supported hypervisor type"); throw new InvalidParameterValueException("Unable to resolve " + hypervisor + " to a supported type"); @@ -1025,7 +1023,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (clusterType != null && !clusterType.isEmpty()) { try { newClusterType = Cluster.ClusterType.valueOf(clusterType); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { throw new InvalidParameterValueException("Unable to resolve " + clusterType + " to a supported type"); } if (newClusterType == null) { @@ -1041,7 +1039,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (allocationState != null && !allocationState.isEmpty()) { try { newAllocationState = Grouping.AllocationState.valueOf(allocationState); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationState + "' to a supported state"); } if (newAllocationState == null) { @@ -1054,11 +1052,11 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } Managed.ManagedState newManagedState = null; - Managed.ManagedState oldManagedState = cluster.getManagedState(); + final Managed.ManagedState oldManagedState = cluster.getManagedState(); if (managedstate != null && !managedstate.isEmpty()) { try { newManagedState = Managed.ManagedState.valueOf(managedstate); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { throw new InvalidParameterValueException("Unable to resolve Managed State '" + managedstate + "' to a supported state"); } if (newManagedState == null) { @@ -1070,7 +1068,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } if (doUpdate) { - _clusterDao.update(cluster.getId(), cluster); + _clusterDao.update(cluster.getId(), cluster); } if (newManagedState != null && !newManagedState.equals(oldManagedState)) { @@ -1080,29 +1078,29 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, cluster.setManagedState(Managed.ManagedState.PrepareUnmanaged); _clusterDao.update(cluster.getId(), cluster); List hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId()); - for (HostVO host : hosts) { + for (final HostVO host : hosts) { if (host.getType().equals(Host.Type.Routing) && !host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected) && - !host.getStatus().equals(Status.Up) && !host.getStatus().equals(Status.Alert)) { - String msg = "host " + host.getPrivateIpAddress() + " should not be in " + host.getStatus().toString() + " status"; + !host.getStatus().equals(Status.Up) && !host.getStatus().equals(Status.Alert)) { + final String msg = "host " + host.getPrivateIpAddress() + " should not be in " + host.getStatus().toString() + " status"; throw new CloudRuntimeException("PrepareUnmanaged Failed due to " + msg); } } - for (HostVO host : hosts) { + for (final HostVO host : hosts) { if (host.getStatus().equals(Status.Up)) { umanageHost(host.getId()); } } - int retry = 40; + final int retry = 40; boolean lsuccess = true; for (int i = 0; i < retry; i++) { lsuccess = true; try { Thread.sleep(5 * 1000); - } catch (Exception e) { + } catch (final Exception e) { } hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId()); - for (HostVO host : hosts) { + for (final HostVO host : hosts) { if (!host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected) && !host.getStatus().equals(Status.Alert)) { lsuccess = false; break; @@ -1131,17 +1129,17 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public Host cancelMaintenance(CancelMaintenanceCmd cmd) { - Long hostId = cmd.getId(); + public Host cancelMaintenance(final CancelMaintenanceCmd cmd) { + final Long hostId = cmd.getId(); // verify input parameters - HostVO host = _hostDao.findById(hostId); + final HostVO host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist"); } processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE, hostId); - boolean success = cancelMaintenance(hostId); + final boolean success = cancelMaintenance(hostId); processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER, hostId); if (!success) { throw new CloudRuntimeException("Internal error cancelling maintenance."); @@ -1150,36 +1148,36 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public Host reconnectHost(ReconnectHostCmd cmd) { - Long hostId = cmd.getId(); + public Host reconnectHost(final ReconnectHostCmd cmd) { + final Long hostId = cmd.getId(); - HostVO host = _hostDao.findById(hostId); + final HostVO host = _hostDao.findById(hostId); if (host == null) { throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist"); } - return (_agentMgr.reconnect(hostId) ? host : null); + return _agentMgr.reconnect(hostId) ? host : null; } @Override - public boolean resourceStateTransitTo(Host host, ResourceState.Event event, long msId) throws NoTransitionException { - ResourceState currentState = host.getResourceState(); - ResourceState nextState = currentState.getNextState(event); + public boolean resourceStateTransitTo(final Host host, final ResourceState.Event event, final long msId) throws NoTransitionException { + final ResourceState currentState = host.getResourceState(); + final ResourceState nextState = currentState.getNextState(event); if (nextState == null) { throw new NoTransitionException("No next resource state found for current state = " + currentState + " event = " + event); } // TO DO - Make it more granular and have better conversion into capacity type if(host.getType() == Type.Routing){ - CapacityState capacityState = (nextState == ResourceState.Enabled) ? CapacityState.Enabled : CapacityState.Disabled; + final CapacityState capacityState = nextState == ResourceState.Enabled ? CapacityState.Enabled : CapacityState.Disabled; _capacityDao.updateCapacityState(null, null, null, host.getId(), capacityState.toString()); } return _hostDao.updateResourceState(currentState, event, nextState, host); } private boolean doMaintain(final long hostId) { - HostVO host = _hostDao.findById(hostId); - MaintainAnswer answer = (MaintainAnswer)_agentMgr.easySend(hostId, new MaintainCommand()); + final HostVO host = _hostDao.findById(hostId); + final MaintainAnswer answer = (MaintainAnswer)_agentMgr.easySend(hostId, new MaintainCommand()); if (answer == null || !answer.getResult()) { s_logger.warn("Unable to send MaintainCommand to host: " + hostId); return false; @@ -1187,8 +1185,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, try { resourceStateTransitTo(host, ResourceState.Event.AdminAskMaintenace, _nodeId); - } catch (NoTransitionException e) { - String err = "Cannot transmit resource state of host " + host.getId() + " to " + ResourceState.Maintenance; + } catch (final NoTransitionException e) { + final String err = "Cannot transmit resource state of host " + host.getId() + " to " + ResourceState.Maintenance; s_logger.debug(err, e); throw new CloudRuntimeException(err + e.getMessage()); } @@ -1204,7 +1202,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, return true; } - List hosts = listAllUpAndEnabledHosts(Host.Type.Routing, host.getClusterId(), host.getPodId(), host.getDataCenterId()); + final List hosts = listAllUpAndEnabledHosts(Host.Type.Routing, host.getClusterId(), host.getPodId(), host.getDataCenterId()); for (final VMInstanceVO vm : vms) { if (hosts == null || hosts.isEmpty() || !answer.getMigrate() || _serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.vgpuType.toString()) != null) { @@ -1224,7 +1222,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public boolean maintain(final long hostId) throws AgentUnavailableException { - Boolean result = propagateResourceEvent(hostId, ResourceState.Event.AdminAskMaintenace); + final Boolean result = propagateResourceEvent(hostId, ResourceState.Event.AdminAskMaintenace); if (result != null) { return result; } @@ -1233,9 +1231,9 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public Host maintain(PrepareForMaintenanceCmd cmd) { - Long hostId = cmd.getId(); - HostVO host = _hostDao.findById(hostId); + public Host maintain(final PrepareForMaintenanceCmd cmd) { + final Long hostId = cmd.getId(); + final HostVO host = _hostDao.findById(hostId); if (host == null) { s_logger.debug("Unable to find host " + hostId); @@ -1258,7 +1256,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } else { throw new CloudRuntimeException("Unable to prepare for maintenance host " + hostId); } - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { throw new CloudRuntimeException("Unable to prepare for maintenance host " + hostId); } } @@ -1266,37 +1264,37 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public boolean checkAndMaintain(final long hostId) { boolean hostInMaintenance = false; - HostVO host = _hostDao.findById(hostId); + final HostVO host = _hostDao.findById(hostId); try { if (host.getType() != Host.Type.Storage) { - List vos = _vmDao.listByHostId(hostId); - List vosMigrating = _vmDao.listVmsMigratingFromHost(hostId); + final List vos = _vmDao.listByHostId(hostId); + final List vosMigrating = _vmDao.listVmsMigratingFromHost(hostId); if (vos.isEmpty() && vosMigrating.isEmpty()) { resourceStateTransitTo(host, ResourceState.Event.InternalEnterMaintenance, _nodeId); hostInMaintenance = true; ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), CallContext.current().getCallingAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_MAINTENANCE_PREPARE, "completed maintenance for host " + hostId, 0); } } - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.debug("Cannot transmit host " + host.getId() + "to Maintenance state", e); } return hostInMaintenance; } @Override - public Host updateHost(UpdateHostCmd cmd) throws NoTransitionException { - Long hostId = cmd.getId(); - Long guestOSCategoryId = cmd.getOsCategoryId(); + public Host updateHost(final UpdateHostCmd cmd) throws NoTransitionException { + final Long hostId = cmd.getId(); + final Long guestOSCategoryId = cmd.getOsCategoryId(); // Verify that the host exists - HostVO host = _hostDao.findById(hostId); + final HostVO host = _hostDao.findById(hostId); if (host == null) { throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist"); } if (cmd.getAllocationState() != null) { - ResourceState.Event resourceEvent = ResourceState.Event.toEvent(cmd.getAllocationState()); + final ResourceState.Event resourceEvent = ResourceState.Event.toEvent(cmd.getAllocationState()); if (resourceEvent != ResourceState.Event.Enable && resourceEvent != ResourceState.Event.Disable) { throw new CloudRuntimeException("Invalid allocation state:" + cmd.getAllocationState() + ", only Enable/Disable are allowed"); } @@ -1307,11 +1305,11 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (guestOSCategoryId != null) { // Verify that the guest OS Category exists if (!(guestOSCategoryId > 0) || _guestOSCategoryDao.findById(guestOSCategoryId) == null) { - throw new InvalidParameterValueException("Please specify a valid guest OS category."); - } + throw new InvalidParameterValueException("Please specify a valid guest OS category."); + } - GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId); - DetailVO guestOSDetail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id"); + final GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId); + final DetailVO guestOSDetail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id"); if (guestOSCategory != null && !GuestOSCategoryVO.CATEGORY_NONE.equalsIgnoreCase(guestOSCategory.getName())) { // Create/Update an entry for guest.os.category.id @@ -1319,7 +1317,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, guestOSDetail.setValue(String.valueOf(guestOSCategory.getId())); _hostDetailsDao.update(guestOSDetail.getId(), guestOSDetail); } else { - Map detail = new HashMap(); + final Map detail = new HashMap(); detail.put("guest.os.category.id", String.valueOf(guestOSCategory.getId())); _hostDetailsDao.persist(hostId, detail); } @@ -1331,7 +1329,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } - List hostTags = cmd.getHostTags(); + final List hostTags = cmd.getHostTags(); if (hostTags != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Updating Host Tags to :" + hostTags); @@ -1339,22 +1337,22 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, _hostTagsDao.persist(hostId, hostTags); } - String url = cmd.getUrl(); + final String url = cmd.getUrl(); if (url != null) { _storageMgr.updateSecondaryStorage(cmd.getId(), cmd.getUrl()); } - HostVO updatedHost = _hostDao.findById(hostId); + final HostVO updatedHost = _hostDao.findById(hostId); return updatedHost; } @Override - public Cluster getCluster(Long clusterId) { + public Cluster getCluster(final Long clusterId) { return _clusterDao.findById(clusterId); } @Override - public boolean configure(String name, Map params) throws ConfigurationException { + public boolean configure(final String name, final Map params) throws ConfigurationException { _defaultSystemVMHypervisor = HypervisorType.getType(_configDao.getValue(Config.SystemVMDefaultHypervisor.toString())); _gson = GsonHelper.getGson(); @@ -1369,7 +1367,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, _gpuAvailability = _hostGpuGroupsDao.createSearchBuilder(); _gpuAvailability.and("hostId", _gpuAvailability.entity().getHostId(), Op.EQ); _gpuAvailability.and("groupName", _gpuAvailability.entity().getGroupName(), Op.EQ); - SearchBuilder join1 = _vgpuTypesDao.createSearchBuilder(); + final SearchBuilder join1 = _vgpuTypesDao.createSearchBuilder(); join1.and("vgpuType", join1.entity().getVgpuType(), Op.EQ); join1.and("remainingCapacity", join1.entity().getRemainingCapacity(), Op.GT); _gpuAvailability.join("groupId", join1, _gpuAvailability.entity().getId(), join1.entity().getGpuGroupId(), JoinBuilder.JoinType.INNER); @@ -1379,8 +1377,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List getSupportedHypervisorTypes(long zoneId, boolean forVirtualRouter, Long podId) { - List hypervisorTypes = new ArrayList(); + public List getSupportedHypervisorTypes(final long zoneId, final boolean forVirtualRouter, final Long podId) { + final List hypervisorTypes = new ArrayList(); List clustersForZone = new ArrayList(); if (podId != null) { @@ -1389,9 +1387,9 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, clustersForZone = _clusterDao.listByZoneId(zoneId); } - for (ClusterVO cluster : clustersForZone) { - HypervisorType hType = cluster.getHypervisorType(); - if (!forVirtualRouter || (forVirtualRouter && hType != HypervisorType.BareMetal && hType != HypervisorType.Ovm)) { + for (final ClusterVO cluster : clustersForZone) { + final HypervisorType hType = cluster.getHypervisorType(); + if (!forVirtualRouter || forVirtualRouter && hType != HypervisorType.BareMetal && hType != HypervisorType.Ovm) { hypervisorTypes.add(hType); } } @@ -1400,25 +1398,25 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public HypervisorType getDefaultHypervisor(long zoneId) { + public HypervisorType getDefaultHypervisor(final long zoneId) { HypervisorType defaultHyper = HypervisorType.None; if (_defaultSystemVMHypervisor != HypervisorType.None) { defaultHyper = _defaultSystemVMHypervisor; } - DataCenterVO dc = _dcDao.findById(zoneId); + final DataCenterVO dc = _dcDao.findById(zoneId); if (dc == null) { return HypervisorType.None; } _dcDao.loadDetails(dc); - String defaultHypervisorInZone = dc.getDetail("defaultSystemVMHypervisorType"); + final String defaultHypervisorInZone = dc.getDetail("defaultSystemVMHypervisorType"); if (defaultHypervisorInZone != null) { defaultHyper = HypervisorType.getType(defaultHypervisorInZone); } - List systemTemplates = _templateDao.listAllSystemVMTemplates(); + final List systemTemplates = _templateDao.listAllSystemVMTemplates(); boolean isValid = false; - for (VMTemplateVO template : systemTemplates) { + for (final VMTemplateVO template : systemTemplates) { if (template.getHypervisorType() == defaultHyper) { isValid = true; break; @@ -1426,7 +1424,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } if (isValid) { - List clusters = _clusterDao.listByDcHyType(zoneId, defaultHyper.toString()); + final List clusters = _clusterDao.listByDcHyType(zoneId, defaultHyper.toString()); if (clusters.size() <= 0) { isValid = false; } @@ -1440,10 +1438,10 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public HypervisorType getAvailableHypervisor(long zoneId) { + public HypervisorType getAvailableHypervisor(final long zoneId) { HypervisorType defaultHype = getDefaultHypervisor(zoneId); if (defaultHype == HypervisorType.None) { - List supportedHypes = getSupportedHypervisorTypes(zoneId, false, null); + final List supportedHypes = getSupportedHypervisorTypes(zoneId, false, null); if (supportedHypes.size() > 0) { Collections.shuffle(supportedHypes); defaultHype = supportedHypes.get(0); @@ -1457,7 +1455,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public void registerResourceStateAdapter(String name, ResourceStateAdapter adapter) { + public void registerResourceStateAdapter(final String name, final ResourceStateAdapter adapter) { synchronized (_resourceStateAdapters) { if (_resourceStateAdapters.get(name) != null) { throw new CloudRuntimeException(name + " has registered"); @@ -1467,21 +1465,21 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public void unregisterResourceStateAdapter(String name) { + public void unregisterResourceStateAdapter(final String name) { synchronized (_resourceStateAdapters) { _resourceStateAdapters.remove(name); } } - private Object dispatchToStateAdapters(ResourceStateAdapter.Event event, boolean singleTaker, Object... args) { + private Object dispatchToStateAdapters(final ResourceStateAdapter.Event event, final boolean singleTaker, final Object... args) { synchronized (_resourceStateAdapters) { - Iterator> it = _resourceStateAdapters.entrySet().iterator(); + final Iterator> it = _resourceStateAdapters.entrySet().iterator(); Object result = null; while (it.hasNext()) { - Map.Entry item = it.next(); - ResourceStateAdapter adapter = item.getValue(); + final Map.Entry item = it.next(); + final ResourceStateAdapter adapter = item.getValue(); - String msg = "Dispatching resource state event " + event + " to " + item.getKey(); + final String msg = "Dispatching resource state event " + event + " to " + item.getKey(); s_logger.debug(msg); if (event == ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_CONNECTED) { @@ -1491,8 +1489,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } else if (event == ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT) { result = - adapter.createHostVOForDirectConnectAgent((HostVO)args[0], (StartupCommand[])args[1], (ServerResource)args[2], (Map)args[3], - (List)args[4]); + adapter.createHostVOForDirectConnectAgent((HostVO)args[0], (StartupCommand[])args[1], (ServerResource)args[2], (Map)args[3], + (List)args[4]); if (result != null && singleTaker) { break; } @@ -1502,7 +1500,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (result != null) { break; } - } catch (UnableDeleteHostException e) { + } catch (final UnableDeleteHostException e) { s_logger.debug("Adapter " + adapter.getName() + " says unable to delete host", e); result = new ResourceStateAdapter.DeleteHostAnswer(false, true); } @@ -1516,67 +1514,67 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public void checkCIDR(HostPodVO pod, DataCenterVO dc, String serverPrivateIP, String serverPrivateNetmask) throws IllegalArgumentException { + public void checkCIDR(final HostPodVO pod, final DataCenterVO dc, final String serverPrivateIP, final String serverPrivateNetmask) throws IllegalArgumentException { if (serverPrivateIP == null) { return; } // Get the CIDR address and CIDR size - String cidrAddress = pod.getCidrAddress(); - long cidrSize = pod.getCidrSize(); + final String cidrAddress = pod.getCidrAddress(); + final long cidrSize = pod.getCidrSize(); // If the server's private IP address is not in the same subnet as the // pod's CIDR, return false - String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); - String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); + final String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); + final String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); if (!cidrSubnet.equals(serverSubnet)) { s_logger.warn("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() + " and zone: " + - dc.getName()); + dc.getName()); throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() + - " and zone: " + dc.getName()); + " and zone: " + dc.getName()); } // If the server's private netmask is less inclusive than the pod's CIDR // netmask, return false - String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); - long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); - long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); + final String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); + final long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); + final long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); if (serverNetmaskNumeric > cidrNetmaskNumeric) { throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() + - " and zone: " + dc.getName()); + " and zone: " + dc.getName()); } } - private boolean checkCIDR(HostPodVO pod, String serverPrivateIP, String serverPrivateNetmask) { + private boolean checkCIDR(final HostPodVO pod, final String serverPrivateIP, final String serverPrivateNetmask) { if (serverPrivateIP == null) { return true; } // Get the CIDR address and CIDR size - String cidrAddress = pod.getCidrAddress(); - long cidrSize = pod.getCidrSize(); + final String cidrAddress = pod.getCidrAddress(); + final long cidrSize = pod.getCidrSize(); // If the server's private IP address is not in the same subnet as the // pod's CIDR, return false - String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); - String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); + final String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); + final String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); if (!cidrSubnet.equals(serverSubnet)) { return false; } // If the server's private netmask is less inclusive than the pod's CIDR // netmask, return false - String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); - long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); - long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); + final String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); + final long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); + final long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); if (serverNetmaskNumeric > cidrNetmaskNumeric) { return false; } return true; } - protected HostVO createHostVO(StartupCommand[] cmds, ServerResource resource, Map details, List hostTags, - ResourceStateAdapter.Event stateEvent) { - StartupCommand startup = cmds[0]; + protected HostVO createHostVO(final StartupCommand[] cmds, final ServerResource resource, final Map details, List hostTags, + final ResourceStateAdapter.Event stateEvent) { + final StartupCommand startup = cmds[0]; HostVO host = findHostByGuid(startup.getGuid()); boolean isNew = false; if (host == null) { @@ -1589,11 +1587,11 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, String dataCenter = startup.getDataCenter(); String pod = startup.getPod(); - String cluster = startup.getCluster(); + final String cluster = startup.getCluster(); if (pod != null && dataCenter != null && pod.equalsIgnoreCase("default") && dataCenter.equalsIgnoreCase("default")) { - List pods = _podDao.listAllIncludingRemoved(); - for (HostPodVO hpv : pods) { + final List pods = _podDao.listAllIncludingRemoved(); + for (final HostPodVO hpv : pods) { if (checkCIDR(hpv, startup.getPrivateIpAddress(), startup.getPrivateNetmask())) { pod = hpv.getName(); dataCenter = _dcDao.findById(hpv.getDataCenterId()).getName(); @@ -1631,13 +1629,13 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, * null and non-null is required. for example, XcpServerDiscoever. * Others, like PxeServer, ExternalFireware don't require Pod */ - Long podId = (p == null ? null : p.getId()); + final Long podId = p == null ? null : p.getId(); Long clusterId = null; if (cluster != null) { try { clusterId = Long.valueOf(cluster); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { if (podId != null) { ClusterVO c = _clusterDao.findBy(cluster, podId.longValue()); if (c == null) { @@ -1650,8 +1648,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } if (startup instanceof StartupRoutingCommand) { - StartupRoutingCommand ssCmd = ((StartupRoutingCommand)startup); - List implicitHostTags = ssCmd.getHostTags(); + final StartupRoutingCommand ssCmd = (StartupRoutingCommand)startup; + final List implicitHostTags = ssCmd.getHostTags(); if (!implicitHostTags.isEmpty()) { if (hostTags == null) { hostTags = _hostTagsDao.gethostTags(host.getId()); @@ -1709,12 +1707,12 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, resourceStateTransitTo(host, ResourceState.Event.InternalCreated, _nodeId); /* Agent goes to Connecting status */ _agentMgr.agentStatusTransitTo(host, Status.Event.AgentConnected, _nodeId); - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Cannot transmit host " + host.getId() + " to Creating state", e); _agentMgr.agentStatusTransitTo(host, Status.Event.Error, _nodeId); try { resourceStateTransitTo(host, ResourceState.Event.Error, _nodeId); - } catch (NoTransitionException e1) { + } catch (final NoTransitionException e1) { s_logger.debug("Cannot transmit host " + host.getId() + "to Error state", e); } } @@ -1722,17 +1720,17 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, return host; } - private boolean isFirstHostInCluster(HostVO host) { + private boolean isFirstHostInCluster(final HostVO host) { boolean isFirstHost = true; if (host.getClusterId() != null) { - SearchBuilder sb = _hostDao.createSearchBuilder(); + final SearchBuilder sb = _hostDao.createSearchBuilder(); sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NULL); sb.and("cluster", sb.entity().getClusterId(), SearchCriteria.Op.EQ); sb.done(); - SearchCriteria sc = sb.create(); + final SearchCriteria sc = sb.create(); sc.setParameters("cluster", host.getClusterId()); - List hosts = _hostDao.search(sc, null); + final List hosts = _hostDao.search(sc, null); if (hosts != null && hosts.size() > 1) { isFirstHost = false; } @@ -1740,11 +1738,11 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, return isFirstHost; } - private void markHostAsDisconnected(HostVO host, StartupCommand[] cmds) { + private void markHostAsDisconnected(HostVO host, final StartupCommand[] cmds) { if (host == null) { // in case host is null due to some errors, try // reloading the host from db if (cmds != null) { - StartupCommand firstCmd = cmds[0]; + final StartupCommand firstCmd = cmds[0]; host = findHostByGuid(firstCmd.getGuid()); if (host == null) { host = findHostByGuid(firstCmd.getGuidWithoutResource()); @@ -1759,7 +1757,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } - private Host createHostAndAgent(ServerResource resource, Map details, boolean old, List hostTags, boolean forRebalance) { + private Host createHostAndAgent(final ServerResource resource, final Map details, final boolean old, final List hostTags, final boolean forRebalance) { HostVO host = null; StartupCommand[] cmds = null; boolean hostExists = false; @@ -1774,7 +1772,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, /* Generate a random version in a dev setup situation */ if (this.getClass().getPackage().getImplementationVersion() == null) { - for (StartupCommand cmd : cmds) { + for (final StartupCommand cmd : cmds) { if (cmd.getVersion() == null) { cmd.setVersion(Long.toString(System.currentTimeMillis())); } @@ -1786,7 +1784,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } if (old) { - StartupCommand firstCmd = cmds[0]; + final StartupCommand firstCmd = cmds[0]; host = findHostByGuid(firstCmd.getGuid()); if (host == null) { host = findHostByGuid(firstCmd.getGuidWithoutResource()); @@ -1804,7 +1802,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, /* reload myself from database */ host = _hostDao.findById(host.getId()); } - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Unable to connect due to ", e); } finally { if (hostExists) { @@ -1824,7 +1822,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, return host; } - private Host createHostAndAgentDeferred(ServerResource resource, Map details, boolean old, List hostTags, boolean forRebalance) { + private Host createHostAndAgentDeferred(final ServerResource resource, final Map details, final boolean old, final List hostTags, final boolean forRebalance) { HostVO host = null; StartupCommand[] cmds = null; boolean hostExists = false; @@ -1840,7 +1838,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, /* Generate a random version in a dev setup situation */ if (this.getClass().getPackage().getImplementationVersion() == null) { - for (StartupCommand cmd : cmds) { + for (final StartupCommand cmd : cmds) { if (cmd.getVersion() == null) { cmd.setVersion(Long.toString(System.currentTimeMillis())); } @@ -1852,7 +1850,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } if (old) { - StartupCommand firstCmd = cmds[0]; + final StartupCommand firstCmd = cmds[0]; host = findHostByGuid(firstCmd.getGuid()); if (host == null) { host = findHostByGuid(firstCmd.getGuidWithoutResource()); @@ -1870,7 +1868,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } host = null; - GlobalLock addHostLock = GlobalLock.getInternLock("AddHostLock"); + final GlobalLock addHostLock = GlobalLock.getInternLock("AddHostLock"); try { if (addHostLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { // to safely determine first host in cluster in multi-MS scenario @@ -1904,7 +1902,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } - } catch (Exception e) { + } catch (final Exception e) { s_logger.warn("Unable to connect due to ", e); } finally { if (hostExists) { @@ -1925,22 +1923,22 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public Host createHostAndAgent(Long hostId, ServerResource resource, Map details, boolean old, List hostTags, boolean forRebalance) { - Host host = createHostAndAgent(resource, details, old, hostTags, forRebalance); + public Host createHostAndAgent(final Long hostId, final ServerResource resource, final Map details, final boolean old, final List hostTags, final boolean forRebalance) { + final Host host = createHostAndAgent(resource, details, old, hostTags, forRebalance); return host; } @Override - public Host addHost(long zoneId, ServerResource resource, Type hostType, Map hostDetails) { + public Host addHost(final long zoneId, final ServerResource resource, final Type hostType, final Map hostDetails) { // Check if the zone exists in the system if (_dcDao.findById(zoneId) == null) { throw new InvalidParameterValueException("Can't find zone with id " + zoneId); } - Map details = hostDetails; - String guid = details.get("guid"); - List currentHosts = listAllUpAndEnabledHostsInOneZoneByType(hostType, zoneId); - for (HostVO currentHost : currentHosts) { + final Map details = hostDetails; + final String guid = details.get("guid"); + final List currentHosts = listAllUpAndEnabledHostsInOneZoneByType(hostType, zoneId); + for (final HostVO currentHost : currentHosts) { if (currentHost.getGuid().equals(guid)) { return currentHost; } @@ -1950,11 +1948,11 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public HostVO createHostVOForConnectedAgent(StartupCommand[] cmds) { + public HostVO createHostVOForConnectedAgent(final StartupCommand[] cmds) { return createHostVO(cmds, null, null, null, ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_CONNECTED); } - private void checkIPConflicts(HostPodVO pod, DataCenterVO dc, String serverPrivateIP, String serverPrivateNetmask, String serverPublicIP, String serverPublicNetmask) { + private void checkIPConflicts(final HostPodVO pod, final DataCenterVO dc, final String serverPrivateIP, final String serverPrivateNetmask, final String serverPublicIP, final String serverPublicNetmask) { // If the server's private IP is the same as is public IP, this host has // a host-only private network. Don't check for conflicts with the // private IP address table. @@ -1962,18 +1960,18 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (!_privateIPAddressDao.mark(dc.getId(), pod.getId(), serverPrivateIP)) { // If the server's private IP address is already in the // database, return false - List existingPrivateIPs = _privateIPAddressDao.listByPodIdDcIdIpAddress(pod.getId(), dc.getId(), serverPrivateIP); + final List existingPrivateIPs = _privateIPAddressDao.listByPodIdDcIdIpAddress(pod.getId(), dc.getId(), serverPrivateIP); assert existingPrivateIPs.size() <= 1 : " How can we get more than one ip address with " + serverPrivateIP; if (existingPrivateIPs.size() > 1) { throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is already in use in pod: " + pod.getName() + - " and zone: " + dc.getName()); + " and zone: " + dc.getName()); } if (existingPrivateIPs.size() == 1) { - DataCenterIpAddressVO vo = existingPrivateIPs.get(0); + final DataCenterIpAddressVO vo = existingPrivateIPs.get(0); if (vo.getInstanceId() != null) { throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is already in use in pod: " + pod.getName() + - " and zone: " + dc.getName()); + " and zone: " + dc.getName()); } } } @@ -1982,7 +1980,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (serverPublicIP != null && !_publicIPAddressDao.mark(dc.getId(), new Ip(serverPublicIP))) { // If the server's public IP address is already in the database, // return false - List existingPublicIPs = _publicIPAddressDao.listByDcIdIpAddress(dc.getId(), serverPublicIP); + final List existingPublicIPs = _publicIPAddressDao.listByDcIdIpAddress(dc.getId(), serverPublicIP); if (existingPublicIPs.size() > 0) { throw new IllegalArgumentException("The public ip address of the server (" + serverPublicIP + ") is already in use in zone: " + dc.getName()); } @@ -1990,16 +1988,16 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public HostVO fillRoutingHostVO(HostVO host, StartupRoutingCommand ssCmd, HypervisorType hyType, Map details, List hostTags) { + public HostVO fillRoutingHostVO(final HostVO host, final StartupRoutingCommand ssCmd, final HypervisorType hyType, Map details, final List hostTags) { if (host.getPodId() == null) { s_logger.error("Host " + ssCmd.getPrivateIpAddress() + " sent incorrect pod, pod id is null"); throw new IllegalArgumentException("Host " + ssCmd.getPrivateIpAddress() + " sent incorrect pod, pod id is null"); } - ClusterVO clusterVO = _clusterDao.findById(host.getClusterId()); + final ClusterVO clusterVO = _clusterDao.findById(host.getClusterId()); if (clusterVO.getHypervisorType() != hyType) { throw new IllegalArgumentException("Can't add host whose hypervisor type is: " + hyType + " into cluster: " + clusterVO.getId() + - " whose hypervisor type is: " + clusterVO.getHypervisorType()); + " whose hypervisor type is: " + clusterVO.getHypervisorType()); } final Map hostDetails = ssCmd.getHostDetails(); @@ -2011,8 +2009,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } - HostPodVO pod = _podDao.findById(host.getPodId()); - DataCenterVO dc = _dcDao.findById(host.getDataCenterId()); + final HostPodVO pod = _podDao.findById(host.getPodId()); + final DataCenterVO dc = _dcDao.findById(host.getDataCenterId()); checkIPConflicts(pod, dc, ssCmd.getPrivateIpAddress(), ssCmd.getPublicIpAddress(), ssCmd.getPublicIpAddress(), ssCmd.getPublicNetmask()); host.setType(com.cloud.host.Host.Type.Routing); host.setDetails(details); @@ -2028,7 +2026,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public void deleteRoutingHost(HostVO host, boolean isForced, boolean forceDestroyStorage) throws UnableDeleteHostException { + public void deleteRoutingHost(final HostVO host, final boolean isForced, final boolean forceDestroyStorage) throws UnableDeleteHostException { if (host.getType() != Host.Type.Routing) { throw new CloudRuntimeException("Non-Routing host gets in deleteRoutingHost, id is " + host.getId()); } @@ -2040,28 +2038,28 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (forceDestroyStorage) { // put local storage into mainenance mode, will set all the VMs on // this local storage into stopped state - StoragePoolVO storagePool = _storageMgr.findLocalStorageOnHost(host.getId()); + final StoragePoolVO storagePool = _storageMgr.findLocalStorageOnHost(host.getId()); if (storagePool != null) { if (storagePool.getStatus() == StoragePoolStatus.Up || storagePool.getStatus() == StoragePoolStatus.ErrorInMaintenance) { try { - StoragePool pool = _storageSvr.preparePrimaryStorageForMaintenance(storagePool.getId()); + final StoragePool pool = _storageSvr.preparePrimaryStorageForMaintenance(storagePool.getId()); if (pool == null) { s_logger.debug("Failed to set primary storage into maintenance mode"); throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode"); } - } catch (Exception e) { + } catch (final Exception e) { s_logger.debug("Failed to set primary storage into maintenance mode, due to: " + e.toString()); throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode, due to: " + e.toString()); } } - List vmsOnLocalStorage = _storageMgr.listByStoragePool(storagePool.getId()); - for (VMInstanceVO vm : vmsOnLocalStorage) { + final List vmsOnLocalStorage = _storageMgr.listByStoragePool(storagePool.getId()); + for (final VMInstanceVO vm : vmsOnLocalStorage) { try { _vmMgr.destroy(vm.getUuid()); - } catch (Exception e) { - String errorMsg = "There was an error Destory the vm: " + vm + " as a part of hostDelete id=" + host.getId(); + } catch (final Exception e) { + final String errorMsg = "There was an error Destory the vm: " + vm + " as a part of hostDelete id=" + host.getId(); s_logger.debug(errorMsg, e); throw new UnableDeleteHostException(errorMsg + "," + e.getMessage()); } @@ -2069,18 +2067,18 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } else { // Check if there are vms running/starting/stopping on this host - List vms = _vmDao.listByHostId(host.getId()); + final List vms = _vmDao.listByHostId(host.getId()); if (!vms.isEmpty()) { if (isForced) { // Stop HA disabled vms and HA enabled vms in Stopping state // Restart HA enabled vms - for (VMInstanceVO vm : vms) { + for (final VMInstanceVO vm : vms) { if (!vm.isHaEnabled() || vm.getState() == State.Stopping) { s_logger.debug("Stopping vm: " + vm + " as a part of deleteHost id=" + host.getId()); try { _vmMgr.advanceStop(vm.getUuid(), false); - } catch (Exception e) { - String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId(); + } catch (final Exception e) { + final String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId(); s_logger.debug(errorMsg, e); throw new UnableDeleteHostException(errorMsg + "," + e.getMessage()); } @@ -2091,13 +2089,13 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } else { throw new UnableDeleteHostException("Unable to delete the host as there are vms in " + vms.get(0).getState() + - " state using this host and isForced=false specified"); + " state using this host and isForced=false specified"); } } } } - private boolean doCancelMaintenance(long hostId) { + private boolean doCancelMaintenance(final long hostId) { HostVO host; host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { @@ -2110,14 +2108,14 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, * really prefer to exception that always exposes bugs */ if (host.getResourceState() != ResourceState.PrepareForMaintenance && host.getResourceState() != ResourceState.Maintenance && - host.getResourceState() != ResourceState.ErrorInMaintenance) { + host.getResourceState() != ResourceState.ErrorInMaintenance) { throw new CloudRuntimeException("Cannot perform cancelMaintenance when resource state is " + host.getResourceState() + ", hostId = " + hostId); } /* TODO: move to listener */ _haMgr.cancelScheduledMigrations(host); - List vms = _haMgr.findTakenMigrationWork(); - for (VMInstanceVO vm : vms) { + final List vms = _haMgr.findTakenMigrationWork(); + for (final VMInstanceVO vm : vms) { if (vm != null && vm.getHostId() != null && vm.getHostId() == hostId) { s_logger.info("Unable to cancel migration because the vm is being migrated: " + vm); return false; @@ -2131,20 +2129,20 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, // for kvm, need to log into kvm host, restart cloudstack-agent if (host.getHypervisorType() == HypervisorType.KVM || host.getHypervisorType() == HypervisorType.LXC) { - boolean sshToAgent = Boolean.parseBoolean(_configDao.getValue(Config.KvmSshToAgentEnabled.key())); + final boolean sshToAgent = Boolean.parseBoolean(_configDao.getValue(Config.KvmSshToAgentEnabled.key())); if (!sshToAgent) { s_logger.info("Configuration tells us not to SSH into Agents. Please restart the Agent (" + hostId + ") manually"); return true; } _hostDao.loadDetails(host); - String password = host.getDetail("password"); - String username = host.getDetail("username"); + final String password = host.getDetail("password"); + final String username = host.getDetail("username"); if (password == null || username == null) { s_logger.debug("Can't find password/username"); return false; } - com.trilead.ssh2.Connection connection = SSHCmdHelper.acquireAuthorizedConnection(host.getPrivateIpAddress(), 22, username, password); + final com.trilead.ssh2.Connection connection = SSHCmdHelper.acquireAuthorizedConnection(host.getPrivateIpAddress(), 22, username, password); if (connection == null) { s_logger.debug("Failed to connect to host: " + host.getPrivateIpAddress()); return false; @@ -2152,26 +2150,26 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, try { SSHCmdHelper.sshExecuteCmdOneShot(connection, "service cloudstack-agent restart"); - } catch (SshException e) { + } catch (final SshException e) { return false; } } return true; - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.debug("Cannot transmit host " + host.getId() + "to Enabled state", e); return false; } } - private boolean cancelMaintenance(long hostId) { + private boolean cancelMaintenance(final long hostId) { try { - Boolean result = propagateResourceEvent(hostId, ResourceState.Event.AdminCancelMaintenance); + final Boolean result = propagateResourceEvent(hostId, ResourceState.Event.AdminCancelMaintenance); if (result != null) { return result; } - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { return false; } @@ -2179,7 +2177,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public boolean executeUserRequest(long hostId, ResourceState.Event event) throws AgentUnavailableException { + public boolean executeUserRequest(final long hostId, final ResourceState.Event event) throws AgentUnavailableException { if (event == ResourceState.Event.AdminAskMaintenace) { return doMaintain(hostId); } else if (event == ResourceState.Event.AdminCancelMaintenance) { @@ -2196,15 +2194,15 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } - private boolean doUmanageHost(long hostId) { - HostVO host = _hostDao.findById(hostId); + private boolean doUmanageHost(final long hostId) { + final HostVO host = _hostDao.findById(hostId); if (host == null) { s_logger.debug("Cannot find host " + hostId + ", assuming it has been deleted, skip umanage"); return true; } if (host.getHypervisorType() == HypervisorType.KVM || host.getHypervisorType() == HypervisorType.LXC) { - MaintainAnswer answer = (MaintainAnswer)_agentMgr.easySend(hostId, new MaintainCommand()); + final MaintainAnswer answer = (MaintainAnswer)_agentMgr.easySend(hostId, new MaintainCommand()); } _agentMgr.disconnectWithoutInvestigation(hostId, Event.ShutdownRequested); @@ -2212,63 +2210,63 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public boolean umanageHost(long hostId) { + public boolean umanageHost(final long hostId) { try { - Boolean result = propagateResourceEvent(hostId, ResourceState.Event.Unmanaged); + final Boolean result = propagateResourceEvent(hostId, ResourceState.Event.Unmanaged); if (result != null) { return result; } - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { return false; } return doUmanageHost(hostId); } - private boolean doUpdateHostPassword(long hostId) { + private boolean doUpdateHostPassword(final long hostId) { if (_agentMgr.isAgentAttached(hostId)) { return false; } DetailVO nv = _hostDetailsDao.findDetail(hostId, ApiConstants.USERNAME); - String username = nv.getValue(); + final String username = nv.getValue(); nv = _hostDetailsDao.findDetail(hostId, ApiConstants.PASSWORD); - String password = nv.getValue(); - UpdateHostPasswordCommand cmd = new UpdateHostPasswordCommand(username, password); + final String password = nv.getValue(); + final UpdateHostPasswordCommand cmd = new UpdateHostPasswordCommand(username, password); _agentMgr.easySend(hostId, cmd); return true; } @Override - public boolean updateHostPassword(UpdateHostPasswordCmd cmd) { + public boolean updateHostPassword(final UpdateHostPasswordCmd cmd) { if (cmd.getClusterId() == null) { // update agent attache password try { - Boolean result = propagateResourceEvent(cmd.getHostId(), ResourceState.Event.UpdatePassword); + final Boolean result = propagateResourceEvent(cmd.getHostId(), ResourceState.Event.UpdatePassword); if (result != null) { return result; } - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { } return doUpdateHostPassword(cmd.getHostId()); } else { // get agents for the cluster - List hosts = listAllHostsInCluster(cmd.getClusterId()); - for (HostVO h : hosts) { + final List hosts = listAllHostsInCluster(cmd.getClusterId()); + for (final HostVO h : hosts) { try { /* * FIXME: this is a buggy logic, check with alex. Shouldn't * return if propagation return non null */ - Boolean result = propagateResourceEvent(h.getId(), ResourceState.Event.UpdatePassword); + final Boolean result = propagateResourceEvent(h.getId(), ResourceState.Event.UpdatePassword); if (result != null) { return result; } doUpdateHostPassword(h.getId()); - } catch (AgentUnavailableException e) { + } catch (final AgentUnavailableException e) { } } @@ -2276,9 +2274,9 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } - public String getPeerName(long agentHostId) { + public String getPeerName(final long agentHostId) { - HostVO host = _hostDao.findById(agentHostId); + final HostVO host = _hostDao.findById(agentHostId); if (host != null && host.getManagementServerId() != null) { if (_clusterMgr.getSelfPeerName().equals(Long.toString(host.getManagementServerId()))) { return null; @@ -2289,7 +2287,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, return null; } - public Boolean propagateResourceEvent(long agentId, ResourceState.Event event) throws AgentUnavailableException { + public Boolean propagateResourceEvent(final long agentId, final ResourceState.Event event) throws AgentUnavailableException { final String msPeer = getPeerName(agentId); if (msPeer == null) { return null; @@ -2298,15 +2296,15 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (s_logger.isDebugEnabled()) { s_logger.debug("Propagating agent change request event:" + event.toString() + " to agent:" + agentId); } - Command[] cmds = new Command[1]; + final Command[] cmds = new Command[1]; cmds[0] = new PropagateResourceEventCommand(agentId, event); - String AnsStr = _clusterMgr.execute(msPeer, agentId, _gson.toJson(cmds), true); + final String AnsStr = _clusterMgr.execute(msPeer, agentId, _gson.toJson(cmds), true); if (AnsStr == null) { throw new AgentUnavailableException(agentId); } - Answer[] answers = _gson.fromJson(AnsStr, Answer[].class); + final Answer[] answers = _gson.fromJson(AnsStr, Answer[].class); if (s_logger.isDebugEnabled()) { s_logger.debug("Result for agent change is " + answers[0].getResult()); @@ -2316,8 +2314,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public boolean maintenanceFailed(long hostId) { - HostVO host = _hostDao.findById(hostId); + public boolean maintenanceFailed(final long hostId) { + final HostVO host = _hostDao.findById(hostId); if (host == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Cant not find host " + hostId); @@ -2326,9 +2324,9 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } else { try { return resourceStateTransitTo(host, ResourceState.Event.UnableToMigrate, _nodeId); - } catch (NoTransitionException e) { + } catch (final NoTransitionException e) { s_logger.debug("No next resource state for host " + host.getId() + " while current state is " + host.getResourceState() + " with event " + - ResourceState.Event.UnableToMigrate, e); + ResourceState.Event.UnableToMigrate, e); return false; } } @@ -2337,15 +2335,15 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List findDirectlyConnectedHosts() { /* The resource column is not null for direct connected resource */ - QueryBuilder sc = QueryBuilder.create(HostVO.class); + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getResource(), Op.NNULL); sc.and(sc.entity().getResourceState(), Op.NIN, ResourceState.Disabled); return sc.list(); } @Override - public List listAllUpAndEnabledHosts(Type type, Long clusterId, Long podId, long dcId) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllUpAndEnabledHosts(final Type type, final Long clusterId, final Long podId, final long dcId) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); if (type != null) { sc.and(sc.entity().getType(), Op.EQ, type); } @@ -2362,37 +2360,37 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId) { - String haTag = _haMgr.getHaTag(); + public List listAllUpAndEnabledNonHAHosts(final Type type, final Long clusterId, final Long podId, final long dcId) { + final String haTag = _haMgr.getHaTag(); return _hostDao.listAllUpAndEnabledNonHAHosts(type, clusterId, podId, dcId, haTag); } @Override - public List findHostByGuid(long dcId, String guid) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List findHostByGuid(final long dcId, final String guid) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); sc.and(sc.entity().getGuid(), Op.EQ, guid); return sc.list(); } @Override - public List listAllHostsInCluster(long clusterId) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllHostsInCluster(final long clusterId) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getClusterId(), Op.EQ, clusterId); return sc.list(); } @Override - public List listHostsInClusterByStatus(long clusterId, Status status) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listHostsInClusterByStatus(final long clusterId, final Status status) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getClusterId(), Op.EQ, clusterId); sc.and(sc.entity().getStatus(), Op.EQ, status); return sc.list(); } @Override - public List listAllUpAndEnabledHostsInOneZoneByType(Type type, long dcId) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllUpAndEnabledHostsInOneZoneByType(final Type type, final long dcId) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getType(), Op.EQ, type); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); @@ -2401,35 +2399,35 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List listAllNotInMaintenanceHostsInOneZone(Type type, Long dcId) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllNotInMaintenanceHostsInOneZone(final Type type, final Long dcId) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); if (dcId != null) { sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); } sc.and(sc.entity().getType(), Op.EQ, type); sc.and(sc.entity().getResourceState(), Op.NIN, ResourceState.Maintenance, ResourceState.ErrorInMaintenance, ResourceState.PrepareForMaintenance, - ResourceState.Error); + ResourceState.Error); return sc.list(); } @Override - public List listAllHostsInOneZoneByType(Type type, long dcId) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllHostsInOneZoneByType(final Type type, final long dcId) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getType(), Op.EQ, type); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); return sc.list(); } @Override - public List listAllHostsInAllZonesByType(Type type) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllHostsInAllZonesByType(final Type type) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getType(), Op.EQ, type); return sc.list(); } @Override - public List listAvailHypervisorInZone(Long hostId, Long zoneId) { - SearchCriteria sc = _hypervisorsInDC.create(); + public List listAvailHypervisorInZone(final Long hostId, final Long zoneId) { + final SearchCriteria sc = _hypervisorsInDC.create(); if (zoneId != null) { sc.setParameters("dataCenter", zoneId); } @@ -2442,38 +2440,38 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, // The search is not able to return list of enums, so getting // list of hypervisors as strings and then converting them to enum - List hvs = _hostDao.customSearch(sc, null); - List hypervisors = new ArrayList(); - for (String hv : hvs) { + final List hvs = _hostDao.customSearch(sc, null); + final List hypervisors = new ArrayList(); + for (final String hv : hvs) { hypervisors.add(HypervisorType.getType(hv)); } return hypervisors; } @Override - public HostVO findHostByGuid(String guid) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public HostVO findHostByGuid(final String guid) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getGuid(), Op.EQ, guid); return sc.find(); } @Override - public HostVO findHostByName(String name) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public HostVO findHostByName(final String name) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getName(), Op.EQ, name); return sc.find(); } @Override - public HostStats getHostStatistics(long hostId) { - Answer answer = _agentMgr.easySend(hostId, new GetHostStatsCommand(_hostDao.findById(hostId).getGuid(), _hostDao.findById(hostId).getName(), hostId)); + public HostStats getHostStatistics(final long hostId) { + final Answer answer = _agentMgr.easySend(hostId, new GetHostStatsCommand(_hostDao.findById(hostId).getGuid(), _hostDao.findById(hostId).getName(), hostId)); - if (answer != null && (answer instanceof UnsupportedAnswer)) { + if (answer != null && answer instanceof UnsupportedAnswer) { return null; } if (answer == null || !answer.getResult()) { - String msg = "Unable to obtain host " + hostId + " statistics. "; + final String msg = "Unable to obtain host " + hostId + " statistics. "; s_logger.warn(msg); return null; } else { @@ -2487,13 +2485,13 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public Long getGuestOSCategoryId(long hostId) { - HostVO host = _hostDao.findById(hostId); + public Long getGuestOSCategoryId(final long hostId) { + final HostVO host = _hostDao.findById(hostId); if (host == null) { return null; } else { _hostDao.loadDetails(host); - DetailVO detail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id"); + final DetailVO detail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id"); if (detail == null) { return null; } else { @@ -2503,8 +2501,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public String getHostTags(long hostId) { - List hostTags = _hostTagsDao.gethostTags(hostId); + public String getHostTags(final long hostId) { + final List hostTags = _hostTagsDao.gethostTags(hostId); if (hostTags == null) { return null; } else { @@ -2513,15 +2511,15 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List listByDataCenter(long dcId) { - List pods = _podDao.listByDataCenterId(dcId); - ArrayList pcs = new ArrayList(); - for (HostPodVO pod : pods) { - List clusters = _clusterDao.listByPodId(pod.getId()); + public List listByDataCenter(final long dcId) { + final List pods = _podDao.listByDataCenterId(dcId); + final ArrayList pcs = new ArrayList(); + for (final HostPodVO pod : pods) { + final List clusters = _clusterDao.listByPodId(pod.getId()); if (clusters.size() == 0) { pcs.add(new PodCluster(pod, null)); } else { - for (ClusterVO cluster : clusters) { + for (final ClusterVO cluster : clusters) { pcs.add(new PodCluster(pod, cluster)); } } @@ -2530,8 +2528,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType type, long dcId) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllUpAndEnabledHostsInOneZoneByHypervisor(final HypervisorType type, final long dcId) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getHypervisorType(), Op.EQ, type); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); @@ -2540,8 +2538,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public List listAllUpAndEnabledHostsInOneZone(long dcId) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); + public List listAllUpAndEnabledHostsInOneZone(final long dcId) { + final QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); @@ -2551,16 +2549,16 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public boolean isHostGpuEnabled(long hostId) { - SearchCriteria sc = _gpuAvailability.create(); + public boolean isHostGpuEnabled(final long hostId) { + final SearchCriteria sc = _gpuAvailability.create(); sc.setParameters("hostId", hostId); return _hostGpuGroupsDao.customSearch(sc, null).size() > 0 ? true : false; } @Override - public List listAvailableGPUDevice(long hostId, String groupName, String vgpuType) { - Filter searchFilter = new Filter(VGPUTypesVO.class, "remainingCapacity", false, null, null); - SearchCriteria sc = _gpuAvailability.create(); + public List listAvailableGPUDevice(final long hostId, final String groupName, final String vgpuType) { + final Filter searchFilter = new Filter(VGPUTypesVO.class, "remainingCapacity", false, null, null); + final SearchCriteria sc = _gpuAvailability.create(); sc.setParameters("hostId", hostId); sc.setParameters("groupName", groupName); sc.setJoinParameters("groupId", "vgpuType", vgpuType); @@ -2569,7 +2567,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public boolean isGPUDeviceAvailable(long hostId, String groupName, String vgpuType) { + public boolean isGPUDeviceAvailable(final long hostId, final String groupName, final String vgpuType) { if(!listAvailableGPUDevice(hostId, groupName, vgpuType).isEmpty()) { return true; } else { @@ -2581,15 +2579,15 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public GPUDeviceTO getGPUDevice(long hostId, String groupName, String vgpuType) { - HostGpuGroupsVO gpuDevice = listAvailableGPUDevice(hostId, groupName, vgpuType).get(0); + public GPUDeviceTO getGPUDevice(final long hostId, final String groupName, final String vgpuType) { + final HostGpuGroupsVO gpuDevice = listAvailableGPUDevice(hostId, groupName, vgpuType).get(0); return new GPUDeviceTO(gpuDevice.getGroupName(), vgpuType, null); } @Override - public void updateGPUDetails(long hostId, HashMap> groupDetails) { + public void updateGPUDetails(final long hostId, final HashMap> groupDetails) { // Update GPU group capacity - TransactionLegacy txn = TransactionLegacy.currentTxn(); + final TransactionLegacy txn = TransactionLegacy.currentTxn(); txn.start(); _hostGpuGroupsDao.persist(hostId, new ArrayList(groupDetails.keySet())); _vgpuTypesDao.persist(hostId, groupDetails); @@ -2597,13 +2595,13 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } @Override - public HashMap> getGPUStatistics(HostVO host) { - Answer answer = _agentMgr.easySend(host.getId(), new GetGPUStatsCommand(host.getGuid(), host.getName())); - if (answer != null && (answer instanceof UnsupportedAnswer)) { + public HashMap> getGPUStatistics(final HostVO host) { + final Answer answer = _agentMgr.easySend(host.getId(), new GetGPUStatsCommand(host.getGuid(), host.getName())); + if (answer != null && answer instanceof UnsupportedAnswer) { return null; } if (answer == null || !answer.getResult()) { - String msg = "Unable to obtain GPU stats for host " + host.getName(); + final String msg = "Unable to obtain GPU stats for host " + host.getName(); s_logger.warn(msg); return null; } else { @@ -2622,32 +2620,32 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, try { return Transaction.execute(new TransactionCallback() { @Override - public Boolean doInTransaction(TransactionStatus status) { - PlannerHostReservationVO reservationEntry = _plannerHostReserveDao.findByHostId(hostId); - if (reservationEntry != null) { - long id = reservationEntry.getId(); - PlannerHostReservationVO hostReservation = _plannerHostReserveDao.lockRow(id, true); - if (hostReservation == null) { + public Boolean doInTransaction(final TransactionStatus status) { + final PlannerHostReservationVO reservationEntry = _plannerHostReserveDao.findByHostId(hostId); + if (reservationEntry != null) { + final long id = reservationEntry.getId(); + final PlannerHostReservationVO hostReservation = _plannerHostReserveDao.lockRow(id, true); + if (hostReservation == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Host reservation for host: " + hostId + " does not even exist. Release reservartion call is ignored."); + } + return false; + } + hostReservation.setResourceUsage(null); + _plannerHostReserveDao.persist(hostReservation); + return true; + } + if (s_logger.isDebugEnabled()) { s_logger.debug("Host reservation for host: " + hostId + " does not even exist. Release reservartion call is ignored."); } + return false; } - hostReservation.setResourceUsage(null); - _plannerHostReserveDao.persist(hostReservation); - return true; - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Host reservation for host: " + hostId + " does not even exist. Release reservartion call is ignored."); - } - - return false; - } }); - } catch (CloudRuntimeException e) { + } catch (final CloudRuntimeException e) { throw e; - } catch (Throwable t) { + } catch (final Throwable t) { s_logger.error("Unable to release host reservation for host: " + hostId, t); return false; }