You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ke...@apache.org on 2013/02/02 00:27:31 UTC

[46/50] [abbrv] Merge javelin into master

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/296c2033/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/resource/ResourceManagerImpl.java
index 9e9b687,8b74ee1..f4fa13b
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@@ -27,20 -26,27 +26,26 @@@ import java.util.List
  import java.util.Map;
  import java.util.Set;
  
 -import javax.annotation.PostConstruct;
  import javax.ejb.Local;
+ import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
+ import org.apache.cloudstack.api.ApiConstants;
  import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd;
+ import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd;
+ import org.apache.cloudstack.api.command.admin.host.AddHostCmd;
+ import org.apache.cloudstack.api.command.admin.host.AddSecondaryStorageCmd;
+ import org.apache.cloudstack.api.command.admin.host.CancelMaintenanceCmd;
+ import org.apache.cloudstack.api.command.admin.host.PrepareForMaintenanceCmd;
+ import org.apache.cloudstack.api.command.admin.host.ReconnectHostCmd;
+ import org.apache.cloudstack.api.command.admin.host.UpdateHostCmd;
+ import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd;
+ import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd;
  import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd;
  import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd;
- import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd;
- import org.apache.cloudstack.api.command.admin.host.*;
  import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd;
- import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd;
- import com.cloud.storage.S3;
- import com.cloud.storage.S3VO;
- import com.cloud.storage.s3.S3Manager;
  import org.apache.log4j.Logger;
+ import org.springframework.stereotype.Component;
  
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.AgentManager.TapAgentsAction;
@@@ -54,15 -60,9 +59,10 @@@ import com.cloud.agent.api.StartupRouti
  import com.cloud.agent.api.UnsupportedAnswer;
  import com.cloud.agent.api.UpdateHostPasswordCommand;
  import com.cloud.agent.manager.AgentAttache;
 +import com.cloud.agent.manager.ClusteredAgentManagerImpl;
  import com.cloud.agent.manager.allocator.PodAllocator;
  import com.cloud.agent.transport.Request;
- import org.apache.cloudstack.api.ApiConstants;
  import com.cloud.api.ApiDBUtils;
- import org.apache.cloudstack.api.command.admin.host.AddHostCmd;
- import org.apache.cloudstack.api.command.admin.host.CancelMaintenanceCmd;
- import org.apache.cloudstack.api.command.admin.host.PrepareForMaintenanceCmd;
- import org.apache.cloudstack.api.command.admin.host.UpdateHostCmd;
  import com.cloud.capacity.Capacity;
  import com.cloud.capacity.CapacityVO;
  import com.cloud.capacity.dao.CapacityDao;
@@@ -133,12 -136,9 +136,11 @@@ import com.cloud.user.UserContext
  import com.cloud.utils.Pair;
  import com.cloud.utils.StringUtils;
  import com.cloud.utils.UriUtils;
- import com.cloud.utils.component.Adapters;
- import com.cloud.utils.component.Inject;
  import com.cloud.utils.component.Manager;
+ import com.cloud.utils.component.ManagerBase;
  import com.cloud.utils.db.DB;
 +import com.cloud.utils.db.GlobalLock;
 +import com.cloud.utils.db.SearchBuilder;
  import com.cloud.utils.db.SearchCriteria;
  import com.cloud.utils.db.SearchCriteria.Op;
  import com.cloud.utils.db.SearchCriteria2;
@@@ -155,2250 -155,2509 +157,2645 @@@ import com.cloud.vm.VirtualMachine.Stat
  import com.cloud.vm.VirtualMachineManager;
  import com.cloud.vm.dao.VMInstanceDao;
  
+ @Component
  @Local({ ResourceManager.class, ResourceService.class })
- public class ResourceManagerImpl implements ResourceManager, ResourceService, Manager {
-     private static final Logger s_logger = Logger.getLogger(ResourceManagerImpl.class);
- 
-     private String                           _name;
+ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, ResourceService,
+ 		Manager {
+ 	private static final Logger s_logger = Logger
+ 			.getLogger(ResourceManagerImpl.class);
  
 -	@Inject
 -	AccountManager _accountMgr;
 -	@Inject
 -	AgentManager _agentMgr;
 -	@Inject
 -	StorageManager _storageMgr;
 -	@Inject
 -	protected SecondaryStorageVmManager _secondaryStorageMgr;
 -
 -	@Inject
 -	protected DataCenterDao _dcDao;
 -	@Inject
 -	protected HostPodDao _podDao;
 -	@Inject
 -	protected ClusterDetailsDao _clusterDetailsDao;
 -	@Inject
 -	protected ClusterDao _clusterDao;
 -	@Inject
 -	protected CapacityDao _capacityDao;
 -	@Inject
 -	protected HostDao _hostDao;
 -	@Inject
 -	protected SwiftManager _swiftMgr;
 -	@Inject
 -	protected S3Manager _s3Mgr;
 -	@Inject
 -	protected HostDetailsDao _hostDetailsDao;
 -	@Inject
 -	protected ConfigurationDao _configDao;
 -	@Inject
 -	protected HostTagsDao _hostTagsDao;
 -	@Inject
 -	protected GuestOSCategoryDao _guestOSCategoryDao;
 -	@Inject
 -	protected StoragePoolDao _storagePoolDao;
 -	@Inject
 -	protected DataCenterIpAddressDao _privateIPAddressDao;
 -	@Inject
 -	protected IPAddressDao _publicIPAddressDao;
 -	@Inject
 -	protected VirtualMachineManager _vmMgr;
 -	@Inject
 -	protected VMInstanceDao _vmDao;
 -	@Inject
 -	protected HighAvailabilityManager _haMgr;
 -	@Inject
 -	protected StorageService _storageSvr;
 +    @Inject
 +    AccountManager                           _accountMgr;
 +    @Inject
 +    AgentManager                             _agentMgr;
 +    @Inject
 +    StorageManager                           _storageMgr;
 +    @Inject
 +    protected SecondaryStorageVmManager      _secondaryStorageMgr;
 +
 +    @Inject
 +    protected DataCenterDao                  _dcDao;
 +    @Inject
 +    protected HostPodDao                     _podDao;
 +    @Inject
 +    protected ClusterDetailsDao              _clusterDetailsDao;
 +    @Inject
 +    protected ClusterDao                     _clusterDao;
 +    @Inject
 +    protected CapacityDao 					 _capacityDao;
 +    @Inject
 +    protected HostDao                        _hostDao;
 +    @Inject
 +    protected SwiftManager _swiftMgr;
 +    @Inject
 +    protected S3Manager                      _s3Mgr;
 +    @Inject
 +    protected HostDetailsDao                 _hostDetailsDao;
 +    @Inject
 +    protected ConfigurationDao _configDao;
 +    @Inject
 +    protected HostTagsDao                    _hostTagsDao;
 +    @Inject
 +    protected GuestOSCategoryDao             _guestOSCategoryDao;
 +    @Inject
 +    protected StoragePoolDao                _storagePoolDao;
 +    @Inject
 +    protected DataCenterIpAddressDao         _privateIPAddressDao;
 +    @Inject
 +    protected IPAddressDao                   _publicIPAddressDao;
 +    @Inject
 +    protected VirtualMachineManager          _vmMgr;
 +    @Inject
 +    protected VMInstanceDao                  _vmDao;
 +    @Inject
 +    protected HighAvailabilityManager        _haMgr;
 +    @Inject
 +    protected StorageService                 _storageSvr;
-     @Inject(adapter = Discoverer.class)
-     protected Adapters<? extends Discoverer> _discoverers;
+ 	// @com.cloud.utils.component.Inject(adapter = Discoverer.class)
+ 	@Inject
+ 	protected List<? extends Discoverer> _discoverers;
 -	@Inject
 -	protected ClusterManager _clusterMgr;
 -	@Inject
 -	protected StoragePoolHostDao _storagePoolHostDao;
 +    @Inject
 +    protected ClusterManager                 _clusterMgr;
 +    @Inject
 +    protected StoragePoolHostDao             _storagePoolHostDao;
-     @Inject(adapter = PodAllocator.class)
-     protected Adapters<PodAllocator> _podAllocators = null;
+ 
+ 	// @com.cloud.utils.component.Inject(adapter = PodAllocator.class)
+ 	@Inject
+ 	protected List<PodAllocator> _podAllocators = null;
+ 
 -	@Inject
 -	protected VMTemplateDao _templateDao;
 -	@Inject
 -	protected ConfigurationManager _configMgr;
 -	@Inject
 -	protected ClusterVSMMapDao _clusterVSMMapDao;
 +    @Inject
 +    protected VMTemplateDao  _templateDao;
 +    @Inject
 +    protected ConfigurationManager 			 _configMgr;
 +    @Inject
 +    protected ClusterVSMMapDao				 _clusterVSMMapDao;
 +
 +    protected long                           _nodeId  = ManagementServerNode.getManagementServerId();
  
 -	protected long _nodeId = ManagementServerNode.getManagementServerId();
 +    protected HashMap<String, ResourceStateAdapter> _resourceStateAdapters = new HashMap<String, ResourceStateAdapter>();
  
 -	protected HashMap<String, ResourceStateAdapter> _resourceStateAdapters = new HashMap<String, ResourceStateAdapter>();
 +    protected HashMap<Integer, List<ResourceListener>> _lifeCycleListeners = new HashMap<Integer, List<ResourceListener>>();
 +    private HypervisorType _defaultSystemVMHypervisor;
  
 -	protected HashMap<Integer, List<ResourceListener>> _lifeCycleListeners = new HashMap<Integer, List<ResourceListener>>();
 -	private HypervisorType _defaultSystemVMHypervisor;
 -	
 -	@PostConstruct
 -	public void init() {
 -		// TODO initialize pod allocators here instead
 -	}
 +    private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 30; // seconds
  
 -	private void insertListener(Integer event, ResourceListener listener) {
 -		List<ResourceListener> lst = _lifeCycleListeners.get(event);
 -		if (lst == null) {
 -			lst = new ArrayList<ResourceListener>();
 -			_lifeCycleListeners.put(event, lst);
 -		}
 +    private void insertListener(Integer event, ResourceListener listener) {
 +        List<ResourceListener> lst = _lifeCycleListeners.get(event);
 +        if (lst == null) {
 +            lst = new ArrayList<ResourceListener>();
 +            _lifeCycleListeners.put(event, lst);
 +        }
  
 -		if (lst.contains(listener)) {
 +        if (lst.contains(listener)) {
-             throw new CloudRuntimeException("Duplicate resource lisener:" + listener.getClass().getSimpleName());
+ 			throw new CloudRuntimeException("Duplicate resource lisener:"
+ 					+ listener.getClass().getSimpleName());
 -		}
 -
 -		lst.add(listener);
 -	}
 -
 -	@Override
 -	public void registerResourceEvent(Integer event, ResourceListener listener) {
 -		synchronized (_lifeCycleListeners) {
 -			if ((event & ResourceListener.EVENT_DISCOVER_BEFORE) != 0) {
 -				insertListener(ResourceListener.EVENT_DISCOVER_BEFORE, listener);
 -			}
 -			if ((event & ResourceListener.EVENT_DISCOVER_AFTER) != 0) {
 -				insertListener(ResourceListener.EVENT_DISCOVER_AFTER, listener);
 -			}
 -			if ((event & ResourceListener.EVENT_DELETE_HOST_BEFORE) != 0) {
 +        }
 +
 +        lst.add(listener);
 +    }
 +
 +    @Override
 +    public void registerResourceEvent(Integer event, ResourceListener listener) {
 +        synchronized (_lifeCycleListeners) {
 +            if ((event & ResourceListener.EVENT_DISCOVER_BEFORE) != 0) {
 +                insertListener(ResourceListener.EVENT_DISCOVER_BEFORE, listener);
 +            }
 +            if ((event & ResourceListener.EVENT_DISCOVER_AFTER) != 0) {
 +                insertListener(ResourceListener.EVENT_DISCOVER_AFTER, listener);
 +            }
 +            if ((event & ResourceListener.EVENT_DELETE_HOST_BEFORE) != 0) {
-                 insertListener(ResourceListener.EVENT_DELETE_HOST_BEFORE, listener);
+ 				insertListener(ResourceListener.EVENT_DELETE_HOST_BEFORE,
+ 						listener);
 -			}
 -			if ((event & ResourceListener.EVENT_DELETE_HOST_AFTER) != 0) {
 +            }
 +            if ((event & ResourceListener.EVENT_DELETE_HOST_AFTER) != 0) {
-                 insertListener(ResourceListener.EVENT_DELETE_HOST_AFTER, listener);
+ 				insertListener(ResourceListener.EVENT_DELETE_HOST_AFTER,
+ 						listener);
 -			}
 -			if ((event & ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE) != 0) {
 +            }
 +            if ((event & ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE) != 0) {
-                 insertListener(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE, listener);
+ 				insertListener(
+ 						ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE,
+ 						listener);
 -			}
 -			if ((event & ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER) != 0) {
 +            }
 +            if ((event & ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER) != 0) {
-                 insertListener(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER, listener);
+ 				insertListener(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER,
+ 						listener);
 -			}
 -			if ((event & ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE) != 0) {
 +            }
 +            if ((event & ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE) != 0) {
-                 insertListener(ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE, listener);
+ 				insertListener(
+ 						ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE,
+ 						listener);
 -			}
 -			if ((event & ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER) != 0) {
 +            }
 +            if ((event & ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER) != 0) {
-                 insertListener(ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER, listener);
+ 				insertListener(
+ 						ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER,
+ 						listener);
 -			}
 -		}
 -	}
 -
 -	@Override
 -	public void unregisterResourceEvent(ResourceListener listener) {
 -		synchronized (_lifeCycleListeners) {
 -			Iterator it = _lifeCycleListeners.entrySet().iterator();
 -			while (it.hasNext()) {
 +            }
 +        }
 +    }
 +
 +    @Override
 +    public void unregisterResourceEvent(ResourceListener listener) {
 +        synchronized (_lifeCycleListeners) {
 +            Iterator it = _lifeCycleListeners.entrySet().iterator();
 +            while (it.hasNext()) {
-                 Map.Entry<Integer, List<ResourceListener>> items = (Map.Entry<Integer, List<ResourceListener>>)it.next();
+ 				Map.Entry<Integer, List<ResourceListener>> items = (Map.Entry<Integer, List<ResourceListener>>) it
+ 						.next();
 -				List<ResourceListener> lst = items.getValue();
 -				lst.remove(listener);
 -			}
 -		}
 -	}
 +                List<ResourceListener> lst = items.getValue();
 +                lst.remove(listener);
 +            }
 +        }
 +    }
  
-     protected void processResourceEvent(Integer event, Object...params) {
+ 	protected void processResourceEvent(Integer event, Object... params) {
 -		List<ResourceListener> lst = _lifeCycleListeners.get(event);
 -		if (lst == null || lst.size() == 0) {
 -			return;
 -		}
 -
 -		String eventName;
 -		for (ResourceListener l : lst) {
 -			if (event == ResourceListener.EVENT_DISCOVER_BEFORE) {
 +        List<ResourceListener> lst = _lifeCycleListeners.get(event);
 +        if (lst == null || lst.size() == 0) {
 +            return;
 +        }
 +
 +        String eventName;
 +        for (ResourceListener l : lst) {
 +            if (event == ResourceListener.EVENT_DISCOVER_BEFORE) {
-                 l.processDiscoverEventBefore((Long) params[0], (Long) params[1], (Long) params[2], (URI) params[3], (String) params[4], (String) params[5],
+ 				l.processDiscoverEventBefore((Long) params[0],
+ 						(Long) params[1], (Long) params[2], (URI) params[3],
+ 						(String) params[4], (String) params[5],
 -						(List<String>) params[6]);
 -				eventName = "EVENT_DISCOVER_BEFORE";
 -			} else if (event == ResourceListener.EVENT_DISCOVER_AFTER) {
 -				l.processDiscoverEventAfter((Map<? extends ServerResource, Map<String, String>>) params[0]);
 -				eventName = "EVENT_DISCOVER_AFTER";
 -			} else if (event == ResourceListener.EVENT_DELETE_HOST_BEFORE) {
 -				l.processDeleteHostEventBefore((HostVO) params[0]);
 -				eventName = "EVENT_DELETE_HOST_BEFORE";
 -			} else if (event == ResourceListener.EVENT_DELETE_HOST_AFTER) {
 -				l.processDeletHostEventAfter((HostVO) params[0]);
 -				eventName = "EVENT_DELETE_HOST_AFTER";
 -			} else if (event == ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE) {
 -				l.processCancelMaintenaceEventBefore((Long) params[0]);
 -				eventName = "EVENT_CANCEL_MAINTENANCE_BEFORE";
 -			} else if (event == ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER) {
 -				l.processCancelMaintenaceEventAfter((Long) params[0]);
 -				eventName = "EVENT_CANCEL_MAINTENANCE_AFTER";
 -			} else if (event == ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE) {
 -				l.processPrepareMaintenaceEventBefore((Long) params[0]);
 -				eventName = "EVENT_PREPARE_MAINTENANCE_BEFORE";
 -			} else if (event == ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER) {
 -				l.processPrepareMaintenaceEventAfter((Long) params[0]);
 -				eventName = "EVENT_PREPARE_MAINTENANCE_AFTER";
 -			} else {
 +                        (List<String>) params[6]);
 +                eventName = "EVENT_DISCOVER_BEFORE";
 +            } else if (event == ResourceListener.EVENT_DISCOVER_AFTER) {
 +                l.processDiscoverEventAfter((Map<? extends ServerResource, Map<String, String>>) params[0]);
 +                eventName = "EVENT_DISCOVER_AFTER";
 +            } else if (event == ResourceListener.EVENT_DELETE_HOST_BEFORE) {
 +                l.processDeleteHostEventBefore((HostVO) params[0]);
 +                eventName = "EVENT_DELETE_HOST_BEFORE";
 +            } else if (event == ResourceListener.EVENT_DELETE_HOST_AFTER) {
 +                l.processDeletHostEventAfter((HostVO) params[0]);
 +                eventName = "EVENT_DELETE_HOST_AFTER";
 +            } else if (event == ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE) {
 +                l.processCancelMaintenaceEventBefore((Long) params[0]);
 +                eventName = "EVENT_CANCEL_MAINTENANCE_BEFORE";
 +            } else if (event == ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER) {
 +                l.processCancelMaintenaceEventAfter((Long) params[0]);
 +                eventName = "EVENT_CANCEL_MAINTENANCE_AFTER";
 +            } else if (event == ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE) {
 +                l.processPrepareMaintenaceEventBefore((Long) params[0]);
 +                eventName = "EVENT_PREPARE_MAINTENANCE_BEFORE";
 +            } else if (event == ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER) {
 +                l.processPrepareMaintenaceEventAfter((Long) params[0]);
 +                eventName = "EVENT_PREPARE_MAINTENANCE_AFTER";
 +            } else {
-                 throw new CloudRuntimeException("Unknown resource event:" + event);
+ 				throw new CloudRuntimeException("Unknown resource event:"
+ 						+ event);
 -			}
 +            }
-             s_logger.debug("Sent resource event " + eventName + " to listener " + l.getClass().getSimpleName());
+ 			s_logger.debug("Sent resource event " + eventName + " to listener "
+ 					+ l.getClass().getSimpleName());
 -		}
 +        }
  
 -	}
 +    }
  
 -	@DB
 -	@Override
 +    @DB
 +    @Override
-     public List<? extends Cluster> discoverCluster(AddClusterCmd cmd) throws IllegalArgumentException, DiscoveryException, ResourceInUseException {
+ 	public List<? extends Cluster> discoverCluster(AddClusterCmd cmd)
+ 			throws IllegalArgumentException, DiscoveryException,
+ 			ResourceInUseException {
 -		long dcId = cmd.getZoneId();
 -		long podId = cmd.getPodId();
 -		String clusterName = cmd.getClusterName();
 -		String url = cmd.getUrl();
 -		String username = cmd.getUsername();
 -		String password = cmd.getPassword();
 -
 -		if (url != null) {
 -			url = URLDecoder.decode(url);
 -		}
 -
 -		URI uri = null;
 -
 -		// Check if the zone exists in the system
 -		DataCenterVO zone = _dcDao.findById(dcId);
 -		if (zone == null) {
 +        long dcId = cmd.getZoneId();
 +        long podId = cmd.getPodId();
 +        String clusterName = cmd.getClusterName();
 +        String url = cmd.getUrl();
 +        String username = cmd.getUsername();
 +        String password = cmd.getPassword();
 +
 +        if (url != null) {
 +            url = URLDecoder.decode(url);
 +        }
 +
 +        URI uri = null;
 +
 +        // Check if the zone exists in the system
 +        DataCenterVO zone = _dcDao.findById(dcId);
 +        if (zone == null) {
-             InvalidParameterValueException ex = new InvalidParameterValueException("Can't find zone by the id specified");
+ 			InvalidParameterValueException ex = new InvalidParameterValueException(
+ 					"Can't find zone by the id specified");
 -			ex.addProxyObject(zone, dcId, "dcId");
 -			throw ex;
 -		}
 +            ex.addProxyObject(zone, dcId, "dcId");
 +            throw ex;
 +        }
  
 -		Account account = UserContext.current().getCaller();
 +        Account account = UserContext.current().getCaller();
-         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) {
-             PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled");
+ 		if (Grouping.AllocationState.Disabled == zone.getAllocationState()
+ 				&& !_accountMgr.isRootAdmin(account.getType())) {
+ 			PermissionDeniedException ex = new PermissionDeniedException(
+ 					"Cannot perform this operation, Zone with specified id is currently disabled");
 -			ex.addProxyObject(zone, dcId, "dcId");
 -			throw ex;
 -		}
 +            ex.addProxyObject(zone, dcId, "dcId");
 +            throw ex;
 +        }
  
 -		HostPodVO pod = _podDao.findById(podId);
 -		if (pod == null) {
 +        HostPodVO pod = _podDao.findById(podId);
 +        if (pod == null) {
-             throw new InvalidParameterValueException("Can't find pod with specified podId " + podId);
+ 			throw new InvalidParameterValueException(
+ 					"Can't find pod with specified podId " + podId);
 -		}
 +        }
  
 -		// Check if the pod exists in the system
 -		if (_podDao.findById(podId) == null) {
 +        // Check if the pod exists in the system
 +        if (_podDao.findById(podId) == null) {
-             throw new InvalidParameterValueException("Can't find pod by id " + podId);
+ 			throw new InvalidParameterValueException("Can't find pod by id "
+ 					+ podId);
 -		}
 -		// check if pod belongs to the zone
 -		if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) {
 +        }
 +        // 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);
+ 			InvalidParameterValueException ex = new InvalidParameterValueException(
+ 					"Pod with specified id doesn't belong to the zone " + dcId);
 -			ex.addProxyObject(pod, podId, "podId");
 -			ex.addProxyObject(zone, dcId, "dcId");
 -			throw ex;
 -		}
 +            ex.addProxyObject(pod, podId, "podId");
 +            ex.addProxyObject(zone, dcId, "dcId");
 +            throw ex;
 +        }
  
- 
 -		// Verify cluster information and create a new cluster if needed
 -		if (clusterName == null || clusterName.isEmpty()) {
 +        // Verify cluster information and create a new cluster if needed
 +        if (clusterName == null || clusterName.isEmpty()) {
-             throw new InvalidParameterValueException("Please specify cluster name");
+ 			throw new InvalidParameterValueException(
+ 					"Please specify cluster name");
 -		}
 +        }
  
 -		if (cmd.getHypervisor() == null || cmd.getHypervisor().isEmpty()) {
 +        if (cmd.getHypervisor() == null || cmd.getHypervisor().isEmpty()) {
-             throw new InvalidParameterValueException("Please specify a hypervisor");
+ 			throw new InvalidParameterValueException(
+ 					"Please specify a hypervisor");
 -		}
 +        }
  
-         Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(cmd.getHypervisor());
+ 		Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType
+ 				.getType(cmd.getHypervisor());
 -		if (hypervisorType == null) {
 +        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 ");
+ 			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 ");
 -		}
 +        }
  
 -		Cluster.ClusterType clusterType = null;
 -		if (cmd.getClusterType() != null && !cmd.getClusterType().isEmpty()) {
 -			clusterType = Cluster.ClusterType.valueOf(cmd.getClusterType());
 -		}
 -		if (clusterType == null) {
 -			clusterType = Cluster.ClusterType.CloudManaged;
 -		}
 +        Cluster.ClusterType clusterType = null;
 +        if (cmd.getClusterType() != null && !cmd.getClusterType().isEmpty()) {
 +            clusterType = Cluster.ClusterType.valueOf(cmd.getClusterType());
 +        }
 +        if (clusterType == null) {
 +            clusterType = Cluster.ClusterType.CloudManaged;
 +        }
  
 -		Grouping.AllocationState allocationState = null;
 +        Grouping.AllocationState allocationState = null;
-         if (cmd.getAllocationState() != null && !cmd.getAllocationState().isEmpty()) {
+ 		if (cmd.getAllocationState() != null
+ 				&& !cmd.getAllocationState().isEmpty()) {
 -			try {
 +            try {
-                 allocationState = Grouping.AllocationState.valueOf(cmd.getAllocationState());
+ 				allocationState = Grouping.AllocationState.valueOf(cmd
+ 						.getAllocationState());
 -			} catch (IllegalArgumentException ex) {
 +            } catch (IllegalArgumentException ex) {
-                 throw new InvalidParameterValueException("Unable to resolve Allocation State '" + cmd.getAllocationState() + "' to a supported state");
+ 				throw new InvalidParameterValueException(
+ 						"Unable to resolve Allocation State '"
+ 								+ cmd.getAllocationState()
+ 								+ "' to a supported state");
 -			}
 -		}
 -		if (allocationState == null) {
 -			allocationState = Grouping.AllocationState.Enabled;
 -		}
 +            }
 +        }
 +        if (allocationState == null) {
 +            allocationState = Grouping.AllocationState.Enabled;
 +        }
  
 -		Discoverer discoverer = getMatchingDiscover(hypervisorType);
 -		if (discoverer == null) {
 +        Discoverer discoverer = getMatchingDiscover(hypervisorType);
 +        if (discoverer == null) {
  
-             throw new InvalidParameterValueException("Could not find corresponding resource manager for " + cmd.getHypervisor());
+ 			throw new InvalidParameterValueException(
+ 					"Could not find corresponding resource manager for "
+ 							+ cmd.getHypervisor());
 -		}
 +        }
  
 -		List<ClusterVO> result = new ArrayList<ClusterVO>();
 +        List<ClusterVO> result = new ArrayList<ClusterVO>();
  
 -		long clusterId = 0;
 -		ClusterVO cluster = new ClusterVO(dcId, podId, clusterName);
 -		cluster.setHypervisorType(cmd.getHypervisor());
 +        long clusterId = 0;
 +        ClusterVO cluster = new ClusterVO(dcId, podId, clusterName);
 +        cluster.setHypervisorType(cmd.getHypervisor());
  
 -		cluster.setClusterType(clusterType);
 -		cluster.setAllocationState(allocationState);
 -		try {
 -			cluster = _clusterDao.persist(cluster);
 -		} catch (Exception e) {
 -			// no longer tolerate exception during the cluster creation phase
 +        cluster.setClusterType(clusterType);
 +        cluster.setAllocationState(allocationState);
 +        try {
 +            cluster = _clusterDao.persist(cluster);
 +        } catch (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);
+ 			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, podId, "podId");
 -			ex.addProxyObject(zone, dcId, "dcId");
 -			throw ex;
 -		}
 -		clusterId = cluster.getId();
 -		result.add(cluster);
 -
 -		if (clusterType == Cluster.ClusterType.CloudManaged) {
 -			return result;
 -		}
 -
 -		// save cluster details for later cluster/host cross-checking
 -		Map<String, String> details = new HashMap<String, String>();
 -		details.put("url", url);
 -		details.put("username", username);
 -		details.put("password", password);
 -		_clusterDetailsDao.persist(cluster.getId(), details);
 -
 -		boolean success = false;
 -		try {
 -			try {
 -				uri = new URI(UriUtils.encodeURIComponent(url));
 -				if (uri.getScheme() == null) {
 +            // Get the pod VO object's table name.
 +            ex.addProxyObject(pod, podId, "podId");
 +            ex.addProxyObject(zone, dcId, "dcId");
 +            throw ex;
 +        }
 +        clusterId = cluster.getId();
 +        result.add(cluster);
 +
 +        if (clusterType == Cluster.ClusterType.CloudManaged) {
 +            return result;
 +        }
 +
 +        // save cluster details for later cluster/host cross-checking
 +        Map<String, String> details = new HashMap<String, String>();
 +        details.put("url", url);
 +        details.put("username", username);
 +        details.put("password", password);
 +        _clusterDetailsDao.persist(cluster.getId(), details);
 +
- 
 +        boolean success = false;
 +        try {
 +            try {
 +                uri = new URI(UriUtils.encodeURIComponent(url));
 +                if (uri.getScheme() == null) {
-                     throw new InvalidParameterValueException("uri.scheme is null " + url + ", add http:// as a prefix");
+ 					throw new InvalidParameterValueException(
+ 							"uri.scheme is null " + url
+ 									+ ", add http:// as a prefix");
 -				} else if (uri.getScheme().equalsIgnoreCase("http")) {
 +                } else if (uri.getScheme().equalsIgnoreCase("http")) {
-                     if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) {
-                         throw new InvalidParameterValueException("Your host and/or path is wrong.  Make sure it's of the format http://hostname/path");
+ 					if (uri.getHost() == null
+ 							|| uri.getHost().equalsIgnoreCase("")
+ 							|| uri.getPath() == null
+ 							|| uri.getPath().equalsIgnoreCase("")) {
+ 						throw new InvalidParameterValueException(
+ 								"Your host and/or path is wrong.  Make sure it's of the format http://hostname/path");
 -					}
 -				}
 -			} catch (URISyntaxException e) {
 +                    }
 +                }
 +            } catch (URISyntaxException e) {
-                 throw new InvalidParameterValueException(url + " is not a valid uri");
+ 				throw new InvalidParameterValueException(url
+ 						+ " is not a valid uri");
 -			}
 +            }
  
 -			List<HostVO> hosts = new ArrayList<HostVO>();
 -			Map<? extends ServerResource, Map<String, String>> resources = null;
 +            List<HostVO> hosts = new ArrayList<HostVO>();
 +            Map<? extends ServerResource, Map<String, String>> resources = null;
-             resources = discoverer.find(dcId, podId, clusterId, uri, username, password, null);
+ 			resources = discoverer.find(dcId, podId, clusterId, uri, username,
+ 					password, null);
  
 -			if (resources != null) {
 +            if (resources != null) {
-                 for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources.entrySet()) {
+ 				for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources
+ 						.entrySet()) {
 -					ServerResource resource = entry.getKey();
 +                    ServerResource resource = entry.getKey();
  
-                     // For Hyper-V, we are here means agent have already started and connected to management server
+ 					// For Hyper-V, we are here means agent have already started
+ 					// and connected to management server
 -					if (hypervisorType == Hypervisor.HypervisorType.Hyperv) {
 -						break;
 -					}
 +                    if (hypervisorType == Hypervisor.HypervisorType.Hyperv) {
 +                        break;
 +                    }
  
-                     HostVO host = (HostVO)createHostAndAgent(resource, entry.getValue(), true, null, false);
+ 					HostVO host = (HostVO) createHostAndAgent(resource,
+ 							entry.getValue(), true, null, false);
 -					if (host != null) {
 -						hosts.add(host);
 -					}
 -					discoverer.postDiscovery(hosts, _nodeId);
 -				}
 +                    if (host != null) {
 +                        hosts.add(host);
 +                    }
 +                    discoverer.postDiscovery(hosts, _nodeId);
 +                }
-                 s_logger.info("External cluster has been successfully discovered by " + discoverer.getName());
+ 				s_logger.info("External cluster has been successfully discovered by "
+ 						+ discoverer.getName());
 -				success = true;
 -				return result;
 -			}
 -
 -			s_logger.warn("Unable to find the server resources at " + url);
 -			throw new DiscoveryException("Unable to add the external cluster");
 -		} finally {
 -			if (!success) {
 -				_clusterDetailsDao.deleteDetails(clusterId);
 -				_clusterDao.remove(clusterId);
 -			}
 -		}
 -	}
 -
 -	@Override
 +                success = true;
 +                return result;
 +            }
 +
 +            s_logger.warn("Unable to find the server resources at " + url);
 +            throw new DiscoveryException("Unable to add the external cluster");
 +        } finally {
 +            if (!success) {
 +                _clusterDetailsDao.deleteDetails(clusterId);
 +                _clusterDao.remove(clusterId);
 +            }
 +        }
 +    }
 +
 +    @Override
-     public Discoverer getMatchingDiscover(Hypervisor.HypervisorType hypervisorType) {
-         Enumeration<? extends Discoverer> en = _discoverers.enumeration();
-         while (en.hasMoreElements()) {
-             Discoverer discoverer = en.nextElement();
-             if (discoverer.getHypervisorType() == hypervisorType) {
+ 	public Discoverer getMatchingDiscover(
+ 			Hypervisor.HypervisorType hypervisorType) {
+ 		for (Discoverer discoverer : _discoverers) {
+ 			if (discoverer.getHypervisorType() == hypervisorType)
 -				return discoverer;
 -		}
 -		return null;
 -	}
 +                return discoverer;
 +            }
-         }
 +        return null;
 +    }
  
 -	@Override
 +    @Override
-     public List<? extends Host> discoverHosts(AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException {
+ 	public List<? extends Host> discoverHosts(AddHostCmd cmd)
+ 			throws IllegalArgumentException, DiscoveryException,
+ 			InvalidParameterValueException {
 -		Long dcId = cmd.getZoneId();
 -		Long podId = cmd.getPodId();
 -		Long clusterId = cmd.getClusterId();
 -		String clusterName = cmd.getClusterName();
 -		String url = cmd.getUrl();
 -		String username = cmd.getUsername();
 -		String password = cmd.getPassword();
 -		List<String> hostTags = cmd.getHostTags();
 +        Long dcId = cmd.getZoneId();
 +        Long podId = cmd.getPodId();
 +        Long clusterId = cmd.getClusterId();
 +        String clusterName = cmd.getClusterName();
 +        String url = cmd.getUrl();
 +        String username = cmd.getUsername();
 +        String password = cmd.getPassword();
 +        List<String> hostTags = cmd.getHostTags();
  
-         dcId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), dcId);
+ 		dcId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current()
+ 				.getCaller(), dcId);
  
 -		// this is for standalone option
 -		if (clusterName == null && clusterId == null) {
 -			clusterName = "Standalone-" + url;
 -		}
 +        // this is for standalone option
 +        if (clusterName == null && clusterId == null) {
 +            clusterName = "Standalone-" + url;
 +        }
  
 -		if (clusterId != null) {
 -			ClusterVO cluster = _clusterDao.findById(clusterId);
 -			if (cluster == null) {
 +        if (clusterId != null) {
 +            ClusterVO cluster = _clusterDao.findById(clusterId);
 +            if (cluster == null) {
-                 InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId");
+ 				InvalidParameterValueException ex = new InvalidParameterValueException(
+ 						"can not find cluster for specified clusterId");
 -				ex.addProxyObject(cluster, clusterId, "clusterId");
 -				throw ex;
 -			} else {
 -				if (cluster.getGuid() == null) {
 -					List<HostVO> hosts = listAllHostsInCluster(clusterId);
 -					if (!hosts.isEmpty()) {
 +                ex.addProxyObject(cluster, clusterId, "clusterId");
 +                throw ex;
 +            } else {
 +                if (cluster.getGuid() == null) {
 +                    List<HostVO> 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");
+ 						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, clusterId, "clusterId");
 -						throw ex;
 -					}
 -				}
 -			}
 -		}
 +                        ex.addProxyObject(cluster, clusterId, "clusterId");
 +                        throw ex;
 +                    }
 +                }
 +            }
 +        }
  
 -		return discoverHostsFull(dcId, podId, clusterId, clusterName, url,
 -				username, password, cmd.getHypervisor(), hostTags,
 -				cmd.getFullUrlParams());
 -	}
 +        return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), true);
 +    }
  
 -	@Override
 +    @Override
-     public List<? extends Host> discoverHosts(AddSecondaryStorageCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException {
+ 	public List<? extends Host> discoverHosts(AddSecondaryStorageCmd cmd)
+ 			throws IllegalArgumentException, DiscoveryException,
+ 			InvalidParameterValueException {
 -		Long dcId = cmd.getZoneId();
 -		String url = cmd.getUrl();
 -		return discoverHostsFull(dcId, null, null, null, url, null, null,
 -				"SecondaryStorage", null, null);
 -	}
 -
 -	@Override
 -	public Swift discoverSwift(AddSwiftCmd cmd) throws DiscoveryException {
 -		return _swiftMgr.addSwift(cmd);
 -	}
 -
 -	@Override
 +        Long dcId = cmd.getZoneId();
 +        String url = cmd.getUrl();
 +        return discoverHostsFull(dcId, null, null, null, url, null, null, "SecondaryStorage", null, null, false);
 +    }
 +
 +    @Override
 +    public Swift discoverSwift(AddSwiftCmd cmd) throws DiscoveryException {
 +        return _swiftMgr.addSwift(cmd);
 +    }
 +
 +    @Override
      public Pair<List<? extends Swift>, Integer> listSwifts(ListSwiftsCmd cmd) {
          Pair<List<SwiftVO>, Integer> swifts =  _swiftMgr.listSwifts(cmd);
          return new Pair<List<? extends Swift>, Integer>(swifts.first(), swifts.second());
 -	}
 -
 -	@Override
 -	public S3 discoverS3(final AddS3Cmd cmd) throws DiscoveryException {
 -		return this._s3Mgr.addS3(cmd);
 -	}
 -
 -	@Override
 -	public List<S3VO> listS3s(final ListS3sCmd cmd) {
 -		return this._s3Mgr.listS3s(cmd);
 -	}
 -
 -	private List<HostVO> discoverHostsFull(Long dcId, Long podId,
 -			Long clusterId, String clusterName, String url, String username,
 -			String password, String hypervisorType, List<String> hostTags,
 -			Map<String, String> params) throws IllegalArgumentException,
 -			DiscoveryException, InvalidParameterValueException {
 -		URI uri = null;
 -
 -		// Check if the zone exists in the system
 -		DataCenterVO zone = _dcDao.findById(dcId);
 -		if (zone == null) {
 +    }
 +
 +    @Override
 +    public S3 discoverS3(final AddS3Cmd cmd) throws DiscoveryException {
 +        return this._s3Mgr.addS3(cmd);
 +    }
 +
 +    @Override
 +    public List<S3VO> listS3s(final ListS3sCmd cmd) {
 +        return this._s3Mgr.listS3s(cmd);
 +    }
 +
 +    private List<HostVO> discoverHostsFull(Long dcId, Long podId, Long clusterId, String clusterName, String url, String username, String password, String hypervisorType, List<String> hostTags,
 +            Map<String, String> params, boolean deferAgentCreation) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException {
 +        URI uri = null;
 +
 +        // Check if the zone exists in the system
 +        DataCenterVO zone = _dcDao.findById(dcId);
 +        if (zone == null) {
-             throw new InvalidParameterValueException("Can't find zone by id " + dcId);
+ 			throw new InvalidParameterValueException("Can't find zone by id "
+ 					+ dcId);
 -		}
 +        }
  
 -		Account account = UserContext.current().getCaller();
 +        Account account = UserContext.current().getCaller();
-         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) {
-             PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled");
+ 		if (Grouping.AllocationState.Disabled == zone.getAllocationState()
+ 				&& !_accountMgr.isRootAdmin(account.getType())) {
+ 			PermissionDeniedException ex = new PermissionDeniedException(
+ 					"Cannot perform this operation, Zone with specified id is currently disabled");
 -			ex.addProxyObject(zone, dcId, "dcId");
 -			throw ex;
 -		}
 -
 -		// Check if the pod exists in the system
 -		if (podId != null) {
 -			HostPodVO pod = _podDao.findById(podId);
 -			if (pod == null) {
 +            ex.addProxyObject(zone, dcId, "dcId");
 +            throw ex;
 +        }
 +
- 
 +        // Check if the pod exists in the system
 +        if (podId != null) {
 +            HostPodVO pod = _podDao.findById(podId);
 +            if (pod == null) {
-                 throw new InvalidParameterValueException("Can't find pod by id " + podId);
+ 				throw new InvalidParameterValueException(
+ 						"Can't find pod by id " + podId);
 -			}
 -			// check if pod belongs to the zone
 -			if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) {
 +            }
 +            // 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);
+ 				InvalidParameterValueException ex = new InvalidParameterValueException(
+ 						"Pod with specified podId"
+ 								+ podId
+ 								+ " doesn't belong to the zone with specified zoneId"
+ 								+ dcId);
 -				ex.addProxyObject(pod, podId, "podId");
 -				ex.addProxyObject(zone, dcId, "dcId");
 -				throw ex;
 -			}
 -		}
 -
 -		// Verify cluster information and create a new cluster if needed
 -		if (clusterName != null && clusterId != null) {
 +                ex.addProxyObject(pod, podId, "podId");
 +                ex.addProxyObject(zone, dcId, "dcId");
 +                throw ex;
 +            }
 +        }
 +
 +        // Verify cluster information and create a new cluster if needed
 +        if (clusterName != null && clusterId != null) {
-             throw new InvalidParameterValueException("Can't specify cluster by both id and name");
+ 			throw new InvalidParameterValueException(
+ 					"Can't specify cluster by both id and name");
 -		}
 +        }
  
 -		if (hypervisorType == null || hypervisorType.isEmpty()) {
 +        if (hypervisorType == null || hypervisorType.isEmpty()) {
-             throw new InvalidParameterValueException("Need to specify Hypervisor Type");
+ 			throw new InvalidParameterValueException(
+ 					"Need to specify Hypervisor Type");
 -		}
 +        }
  
 -		if ((clusterName != null || clusterId != null) && podId == null) {
 +        if ((clusterName != null || clusterId != null) && podId == null) {
-             throw new InvalidParameterValueException("Can't specify cluster without specifying the pod");
+ 			throw new InvalidParameterValueException(
+ 					"Can't specify cluster without specifying the pod");
 -		}
 +        }
  
 -		if (clusterId != null) {
 -			if (_clusterDao.findById(clusterId) == null) {
 +        if (clusterId != null) {
 +            if (_clusterDao.findById(clusterId) == null) {
-                 throw new InvalidParameterValueException("Can't find cluster by id " + clusterId);
-             }
- 
-             if(hypervisorType.equalsIgnoreCase(HypervisorType.VMware.toString())) {
-                 // VMware only allows adding host to an existing cluster, as we already have a lot of information
-                 // in cluster object, to simplify user input, we will construct neccessary information here
-                 Map<String, String> clusterDetails = this._clusterDetailsDao.findDetails(clusterId);
+ 				throw new InvalidParameterValueException(
+ 						"Can't find cluster by id " + clusterId);
+ 			}
+ 
+ 			if (hypervisorType.equalsIgnoreCase(HypervisorType.VMware
+ 					.toString())) {
+ 				// VMware only allows adding host to an existing cluster, as we
+ 				// already have a lot of information
+ 				// in cluster object, to simplify user input, we will construct
+ 				// neccessary information here
+ 				Map<String, String> clusterDetails = this._clusterDetailsDao
+ 						.findDetails(clusterId);
 -				username = clusterDetails.get("username");
 +                username = clusterDetails.get("username");
-                 assert(username != null);
+ 				assert (username != null);
  
 -				password = clusterDetails.get("password");
 +                password = clusterDetails.get("password");
-                 assert(password != null);
+ 				assert (password != null);
  
 -				try {
 -					uri = new URI(UriUtils.encodeURIComponent(url));
 +                try {
 +                    uri = new URI(UriUtils.encodeURIComponent(url));
  
 -					url = clusterDetails.get("url") + "/" + uri.getHost();
 -				} catch (URISyntaxException e) {
 +                    url = clusterDetails.get("url") + "/" + uri.getHost();
 +                } catch (URISyntaxException e) {
-                     throw new InvalidParameterValueException(url + " is not a valid uri");
+ 					throw new InvalidParameterValueException(url
+ 							+ " is not a valid uri");
 -				}
 -			}
 -		}
 +                }
 +            }
 +        }
  
 -		if (clusterName != null) {
 -			HostPodVO pod = _podDao.findById(podId);
 -			if (pod == null) {
 +        if (clusterName != null) {
 +            HostPodVO pod = _podDao.findById(podId);
 +            if (pod == null) {
-                 throw new InvalidParameterValueException("Can't find pod by id " + podId);
+ 				throw new InvalidParameterValueException(
+ 						"Can't find pod by id " + podId);
 -			}
 -			ClusterVO cluster = new ClusterVO(dcId, podId, clusterName);
 -			cluster.setHypervisorType(hypervisorType);
 -			try {
 -				cluster = _clusterDao.persist(cluster);
 -			} catch (Exception e) {
 -				cluster = _clusterDao.findBy(clusterName, podId);
 -				if (cluster == null) {
 +            }
 +            ClusterVO cluster = new ClusterVO(dcId, podId, clusterName);
 +            cluster.setHypervisorType(hypervisorType);
 +            try {
 +                cluster = _clusterDao.persist(cluster);
 +            } catch (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);
+ 					CloudRuntimeException ex = new CloudRuntimeException(
+ 							"Unable to create cluster "
+ 									+ clusterName
+ 									+ " in pod with specified podId and data center with specified dcID",
+ 							e);
 -					ex.addProxyObject(pod, podId, "podId");
 -					ex.addProxyObject(zone, dcId, "dcId");
 -					throw ex;
 -				}
 -			}
 -			clusterId = cluster.getId();
 -		}
 -
 -		try {
 -			uri = new URI(UriUtils.encodeURIComponent(url));
 -			if (uri.getScheme() == null) {
 +                    ex.addProxyObject(pod, podId, "podId");
 +                    ex.addProxyObject(zone, dcId, "dcId");
 +                    throw ex;
 +                }
 +            }
 +            clusterId = cluster.getId();
 +        }
 +
 +        try {
 +            uri = new URI(UriUtils.encodeURIComponent(url));
 +            if (uri.getScheme() == null) {
-                 throw new InvalidParameterValueException("uri.scheme is null " + url + ", add nfs:// as a prefix");
+ 				throw new InvalidParameterValueException("uri.scheme is null "
+ 						+ url + ", add nfs:// as a prefix");
 -			} else if (uri.getScheme().equalsIgnoreCase("nfs")) {
 +            } else if (uri.getScheme().equalsIgnoreCase("nfs")) {
-                 if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) {
-                     throw new InvalidParameterValueException("Your host and/or path is wrong.  Make sure it's of the format nfs://hostname/path");
+ 				if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("")
+ 						|| uri.getPath() == null
+ 						|| uri.getPath().equalsIgnoreCase("")) {
+ 					throw new InvalidParameterValueException(
+ 							"Your host and/or path is wrong.  Make sure it's of the format nfs://hostname/path");
 -				}
 -			}
 -		} catch (URISyntaxException e) {
 +                }
 +            }
 +        } catch (URISyntaxException e) {
-             throw new InvalidParameterValueException(url + " is not a valid uri");
+ 			throw new InvalidParameterValueException(url
+ 					+ " is not a valid uri");
 -		}
 +        }
  
 -		List<HostVO> hosts = new ArrayList<HostVO>();
 +        List<HostVO> hosts = new ArrayList<HostVO>();
-         s_logger.info("Trying to add a new host at " + url + " in data center " + dcId);
-         Enumeration<? extends Discoverer> en = _discoverers.enumeration();
+ 		s_logger.info("Trying to add a new host at " + url + " in data center "
+ 				+ dcId);
 -		boolean isHypervisorTypeSupported = false;
 +        boolean isHypervisorTypeSupported = false;
-         while (en.hasMoreElements()) {
-             Discoverer discoverer = en.nextElement();
+ 		for (Discoverer discoverer : _discoverers) {
 -			if (params != null) {
 -				discoverer.putParam(params);
 -			}
 +            if (params != null) {
 +                discoverer.putParam(params);
 +            }
  
 -			if (!discoverer.matchHypervisor(hypervisorType)) {
 -				continue;
 -			}
 -			isHypervisorTypeSupported = true;
 -			Map<? extends ServerResource, Map<String, String>> resources = null;
 +            if (!discoverer.matchHypervisor(hypervisorType)) {
 +                continue;
 +            }
 +            isHypervisorTypeSupported = true;
 +            Map<? extends ServerResource, Map<String, String>> resources = null;
  
-             processResourceEvent(ResourceListener.EVENT_DISCOVER_BEFORE, dcId, podId, clusterId, uri, username, password, hostTags);
+ 			processResourceEvent(ResourceListener.EVENT_DISCOVER_BEFORE, dcId,
+ 					podId, clusterId, uri, username, password, hostTags);
 -			try {
 +            try {
-                 resources = discoverer.find(dcId, podId, clusterId, uri, username, password, hostTags);
-             } catch(DiscoveryException e) {
+ 				resources = discoverer.find(dcId, podId, clusterId, uri,
+ 						username, password, hostTags);
+ 			} catch (DiscoveryException e) {
 -				throw e;
 -			} catch (Exception e) {
 +                throw e;
 +            } catch (Exception e) {
-                 s_logger.info("Exception in host discovery process with discoverer: " + discoverer.getName() + ", skip to another discoverer if there is any");
+ 				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);
+ 			processResourceEvent(ResourceListener.EVENT_DISCOVER_AFTER,
+ 					resources);
  
 -			if (resources != null) {
 +            if (resources != null) {
-                 for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources.entrySet()) {
+ 				for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources
+ 						.entrySet()) {
 -					ServerResource resource = entry.getKey();
 -					/*
 +                    ServerResource resource = entry.getKey();
 +                    /*
-                      * For KVM, if we go to here, that means kvm agent is already connected to mgt svr.
+ 					 * For KVM, if we go to here, that means kvm agent is
+ 					 * already connected to mgt svr.
 -					 */
 -					if (resource instanceof KvmDummyResourceBase) {
 -						Map<String, String> details = entry.getValue();
 -						String guid = details.get("guid");
 +                     */
 +                    if (resource instanceof KvmDummyResourceBase) {
 +                        Map<String, String> details = entry.getValue();
 +                        String guid = details.get("guid");
-                         List<HostVO> kvmHosts = listAllUpAndEnabledHosts(Host.Type.Routing, clusterId, podId, dcId);
+ 						List<HostVO> kvmHosts = listAllUpAndEnabledHosts(
+ 								Host.Type.Routing, clusterId, podId, dcId);
 -						for (HostVO host : kvmHosts) {
 -							if (host.getGuid().equalsIgnoreCase(guid)) {
 +                        for (HostVO host : kvmHosts) {
 +                            if (host.getGuid().equalsIgnoreCase(guid)) {
-                                 if(hostTags != null){
-                                     if(s_logger.isTraceEnabled()){
-                                         s_logger.trace("Adding Host Tags for KVM host, tags:  :"+hostTags);
+ 								if (hostTags != null) {
+ 									if (s_logger.isTraceEnabled()) {
+ 										s_logger.trace("Adding Host Tags for KVM host, tags:  :"
+ 												+ hostTags);
 -									}
 +                                    }
-                                     _hostTagsDao.persist(host.getId(), hostTags);
+ 									_hostTagsDao
+ 											.persist(host.getId(), hostTags);
 -								}
 -								hosts.add(host);
 -								return hosts;
 -							}
 -						}
 -						return null;
 -					}
 -
 -					HostVO host = (HostVO) createHostAndAgent(resource,
 -							entry.getValue(), true, hostTags, false);
 -					if (host != null) {
 -						hosts.add(host);
 -					}
 -					discoverer.postDiscovery(hosts, _nodeId);
 -
 -				}
 +                                }
 +                                hosts.add(host);
 +                                return hosts;
 +                            }
 +                        }
 +                        return null;
 +                    }
 +
 +                    HostVO host = null;
 +                    if (deferAgentCreation) {
 +                        host = (HostVO)createHostAndAgentDeferred(resource, entry.getValue(), true, hostTags, false);
 +                    } else {
 +                        host = (HostVO)createHostAndAgent(resource, entry.getValue(), true, hostTags, false);
 +                    }
 +                    if (host != null) {
 +                        hosts.add(host);
 +                    }
 +                    discoverer.postDiscovery(hosts, _nodeId);
 +
 +                }
-                 s_logger.info("server resources successfully discovered by " + discoverer.getName());
+ 				s_logger.info("server resources successfully discovered by "
+ 						+ discoverer.getName());
 -				return hosts;
 -			}
 -		}
 -		if (!isHypervisorTypeSupported) {
 +                return hosts;
 +            }
 +        }
 +        if (!isHypervisorTypeSupported) {
-             String msg = "Do not support HypervisorType " + hypervisorType + " for " + url;
+ 			String msg = "Do not support HypervisorType " + hypervisorType
+ 					+ " for " + url;
 -			s_logger.warn(msg);
 -			throw new DiscoveryException(msg);
 -		}
 -		s_logger.warn("Unable to find the server resources at " + url);
 -		throw new DiscoveryException("Unable to add the host");
 -	}
 -
 -	@Override
 -	public Host getHost(long hostId) {
 -		return _hostDao.findById(hostId);
 -	}
 -
 -	@DB
 +            s_logger.warn(msg);
 +            throw new DiscoveryException(msg);
 +        }
 +        s_logger.warn("Unable to find the server resources at " + url);
 +        throw new DiscoveryException("Unable to add the host");
 +    }
 +
 +    @Override
 +    public Host getHost(long hostId) {
 +        return _hostDao.findById(hostId);
 +    }
 +
 +    @DB
-     protected boolean doDeleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage) {
-         User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId());
+ 	protected boolean doDeleteHost(long hostId, boolean isForced,
+ 			boolean isForceDeleteStorage) {
+ 		User caller = _accountMgr.getActiveUser(UserContext.current()
+ 				.getCallerUserId());
 -		// Verify that host exists
 -		HostVO host = _hostDao.findById(hostId);
 -		if (host == null) {
 +        // Verify that host exists
 +        HostVO host = _hostDao.findById(hostId);
 +        if (host == null) {
-             throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist");
+ 			throw new InvalidParameterValueException("Host with id " + hostId
+ 					+ " doesn't exist");
 -		}
 +        }
-         _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), host.getDataCenterId());
+ 		_accountMgr.checkAccessAndSpecifyAuthority(UserContext.current()
+ 				.getCaller(), host.getDataCenterId());
  
 -		/*
 +        /*
-          * TODO: check current agent status and updateAgentStatus to removed. If it was already removed, that means
-          * someone is deleting host concurrently, return. And consider the situation of CloudStack shutdown during delete.
-          * A global lock?
-          *
+ 		 * TODO: check current agent status and updateAgentStatus to removed. If
+ 		 * it was already removed, that means someone is deleting host
+ 		 * concurrently, return. And consider the situation of CloudStack
+ 		 * shutdown during delete. A global lock?
 -		 */
 -		AgentAttache attache = _agentMgr.findAttache(hostId);
 +         */
 +        AgentAttache attache = _agentMgr.findAttache(hostId);
-         // 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!
-         List<StoragePoolHostVO> pools = _storagePoolHostDao.listByHostIdIncludingRemoved(hostId);
+ 		// 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!
+ 		List<StoragePoolHostVO> pools = _storagePoolHostDao
+ 				.listByHostIdIncludingRemoved(hostId);
  
-         ResourceStateAdapter.DeleteHostAnswer answer = (ResourceStateAdapter.DeleteHostAnswer) dispatchToStateAdapters(ResourceStateAdapter.Event.DELETE_HOST, false, host, new Boolean(isForced), new Boolean(isForceDeleteStorage));
+ 		ResourceStateAdapter.DeleteHostAnswer answer = (ResourceStateAdapter.DeleteHostAnswer) dispatchToStateAdapters(
+ 				ResourceStateAdapter.Event.DELETE_HOST, false, host,
+ 				new Boolean(isForced), new Boolean(isForceDeleteStorage));
  
 -		if (answer == null) {
 +        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());
+ 			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());
 -		}
 +        }
  
 -		if (answer.getIsException()) {
 -			return false;
 -		}
 +        if (answer.getIsException()) {
 +            return false;
 +        }
  
 -		if (!answer.getIsContinue()) {
 -			return true;
 -		}
 +        if (!answer.getIsContinue()) {
 +            return true;
 +        }
  
 -		Transaction txn = Transaction.currentTxn();
 -		txn.start();
 +        Transaction txn = Transaction.currentTxn();
 +        txn.start();
  
-         _dcDao.releasePrivateIpAddress(host.getPrivateIpAddress(), host.getDataCenterId(), null);
+ 		_dcDao.releasePrivateIpAddress(host.getPrivateIpAddress(),
+ 				host.getDataCenterId(), null);
 -		_agentMgr.disconnectWithoutInvestigation(hostId, Status.Event.Remove);
 -
 -		// delete host details
 -		_hostDetailsDao.deleteDetails(hostId);
 -
 -		host.setGuid(null);
 -		Long clusterId = host.getClusterId();
 -		host.setClusterId(null);
 -		_hostDao.update(host.getId(), host);
 -
 -		_hostDao.remove(hostId);
 -		if (clusterId != null) {
 -			List<HostVO> hosts = listAllHostsInCluster(clusterId);
 -			if (hosts.size() == 0) {
 -				ClusterVO cluster = _clusterDao.findById(clusterId);
 -				cluster.setGuid(null);
 -				_clusterDao.update(clusterId, cluster);
 -			}
 -		}
 -
 -		try {
 +        _agentMgr.disconnectWithoutInvestigation(hostId, Status.Event.Remove);
 +
 +        // delete host details
 +        _hostDetailsDao.deleteDetails(hostId);
 +
 +        host.setGuid(null);
 +        Long clusterId = host.getClusterId();
 +        host.setClusterId(null);
 +        _hostDao.update(host.getId(), host);
 +
 +        _hostDao.remove(hostId);
 +        if (clusterId != null) {
 +            List<HostVO> hosts = listAllHostsInCluster(clusterId);
 +            if (hosts.size() == 0) {
 +                ClusterVO cluster = _clusterDao.findById(clusterId);
 +                cluster.setGuid(null);
 +                _clusterDao.update(clusterId, cluster);
 +            }
 +        }
 +
 +        try {
-             resourceStateTransitTo(host, ResourceState.Event.DeleteHost, _nodeId);
+ 			resourceStateTransitTo(host, ResourceState.Event.DeleteHost,
+ 					_nodeId);
 -		} catch (NoTransitionException e) {
 +        } catch (NoTransitionException e) {
-             s_logger.debug("Cannot transmit host " + host.getId() + "to Enabled state", 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);
  
-         // For pool ids you got, delete local storage host entries in pool table where
+ 		// 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);
 +        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);
+ 				s_logger.debug("Local storage id=" + poolId
+ 						+ " is removed as a part of host removal id=" + hostId);
 -			}
 -		}
 +            }
 +        }
  
 -		// delete the op_host_capacity entry
 +        // delete the op_host_capacity entry
-         Object[] capacityTypes = { Capacity.CAPACITY_TYPE_CPU, Capacity.CAPACITY_TYPE_MEMORY };
-         SearchCriteria<CapacityVO> hostCapacitySC = _capacityDao.createSearchCriteria();
+ 		Object[] capacityTypes = { Capacity.CAPACITY_TYPE_CPU,
+ 				Capacity.CAPACITY_TYPE_MEMORY };
+ 		SearchCriteria<CapacityVO> hostCapacitySC = _capacityDao
+ 				.createSearchCriteria();
 -		hostCapacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, hostId);
 +        hostCapacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, hostId);
-         hostCapacitySC.addAnd("capacityType", SearchCriteria.Op.IN, capacityTypes);
+ 		hostCapacitySC.addAnd("capacityType", SearchCriteria.Op.IN,
+ 				capacityTypes);
 -		_capacityDao.remove(hostCapacitySC);
 -		txn.commit();
 -		return true;
 -	}
 +        _capacityDao.remove(hostCapacitySC);
 +        txn.commit();
 +        return true;
 +    }
  
 -	@Override
 +    @Override
-     public boolean deleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage) {
+ 	public boolean deleteHost(long hostId, boolean isForced,
+ 			boolean isForceDeleteStorage) {
 -		try {
 +        try {
-             Boolean result = _clusterMgr.propagateResourceEvent(hostId, ResourceState.Event.DeleteHost);
+ 			Boolean result = _clusterMgr.propagateResourceEvent(hostId,
+ 					ResourceState.Event.DeleteHost);
 -			if (result != null) {
 -				return result;
 -			}
 -		} catch (AgentUnavailableException e) {
 -			return false;
 -		}
 -
 -		return doDeleteHost(hostId, isForced, isForceDeleteStorage);
 -	}
 -
 -	@Override
 -	@DB
 -	public boolean deleteCluster(DeleteClusterCmd cmd) {
 -		Transaction txn = Transaction.currentTxn();
 -		try {
 -			txn.start();
 -			ClusterVO cluster = _clusterDao.lockRow(cmd.getId(), true);
 -			if (cluster == null) {
 -				if (s_logger.isDebugEnabled()) {
 +            if (result != null) {
 +                return result;
 +            }
 +        } catch (AgentUnavailableException e) {
 +            return false;
 +        }
 +
 +        return doDeleteHost(hostId, isForced, isForceDeleteStorage);
 +    }
 +
 +    @Override
 +    @DB
 +    public boolean deleteCluster(DeleteClusterCmd cmd) {
 +        Transaction txn = Transaction.currentTxn();
 +        try {
 +            txn.start();
 +            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.");
+ 					s_logger.debug("Cluster: " + cmd.getId()
+ 							+ " does not even exist.  Delete call is ignored.");
 -				}
 -				txn.rollback();
 +                }
 +                txn.rollback();
-                 throw new CloudRuntimeException("Cluster: " + cmd.getId() + " does not exist");
+ 				throw new CloudRuntimeException("Cluster: " + cmd.getId()
+ 						+ " does not exist");
 -			}
 +            }
  
-             Hypervisor.HypervisorType hypervisorType = cluster.getHypervisorType();
+ 			Hypervisor.HypervisorType hypervisorType = cluster
+ 					.getHypervisorType();
  
 -			List<HostVO> hosts = listAllHostsInCluster(cmd.getId());
 -			if (hosts.size() > 0) {
 -				if (s_logger.isDebugEnabled()) {
 +            List<HostVO> hosts = listAllHostsInCluster(cmd.getId());
 +            if (hosts.size() > 0) {
 +                if (s_logger.isDebugEnabled()) {
-                     s_logger.debug("Cluster: " + cmd.getId() + " still has hosts, can't remove");
+ 					s_logger.debug("Cluster: " + cmd.getId()
+ 							+ " still has hosts, can't remove");
 -				}
 -				txn.rollback();
 +                }
 +                txn.rollback();
-                 throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has hosts");
+ 				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<StoragePoolVO> storagePools = _storagePoolDao.listPoolsByCluster(cmd.getId());
+ 			// don't allow to remove the cluster if it has non-removed storage
+ 			// pools
+ 			List<StoragePoolVO> storagePools = _storagePoolDao
+ 					.listPoolsByCluster(cmd.getId());
 -			if (storagePools.size() > 0) {
 -				if (s_logger.isDebugEnabled()) {
 +            if (storagePools.size() > 0) {
 +                if (s_logger.isDebugEnabled()) {
-                     s_logger.debug("Cluster: " + cmd.getId() + " still has storage pools, can't remove");
+ 					s_logger.debug("Cluster: " + cmd.getId()
+ 							+ " still has storage pools, can't remove");
 -				}
 -				txn.rollback();
 +                }
 +                txn.rollback();
-                 throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has storage pools");
+ 				throw new CloudRuntimeException("Cluster: " + cmd.getId()
+ 						+ " cannot be removed. Cluster still has storage pools");
 -			}
 +            }
  
-             if (_clusterDao.remove(cmd.getId())){
+ 			if (_clusterDao.remove(cmd.getId())) {
 -				_capacityDao.removeBy(null, null, null, cluster.getId(), null);
 +                _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
+ 				// 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.
 +                // on, remove the row in cluster_vsm_map for this cluster id.
-                 if (hypervisorType == HypervisorType.VMware &&
-                         Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) {
+ 				if (hypervisorType == HypervisorType.VMware
+ 						&& Boolean.parseBoolean(_configDao
+ 								.getValue(Config.VmwareUseNexusVSwitch
+ 										.toString()))) {
 -					_clusterVSMMapDao.removeByClusterId(cmd.getId());
 -				}
 -			}
 +                    _clusterVSMMapDao.removeByClusterId(cmd.getId());
 +                }
 +            }
  
 -			txn.commit();
 -			return true;
 +            txn.commit();
 +            return true;
-         } catch(CloudRuntimeException e){
+ 		} catch (CloudRuntimeException e) {
 -			throw e;
 -		} catch (Throwable t) {
 -			s_logger.error("Unable to delete cluster: " + cmd.getId(), t);
 -			txn.rollback();
 -			return false;
 -		}
 -	}
 -
 -	@Override
 -	@DB
 +            throw e;
 +        } catch (Throwable t) {
 +            s_logger.error("Unable to delete cluster: " + cmd.getId(), t);
 +            txn.rollback();
 +            return false;
 +        }
 +    }
 +
 +    @Override
 +    @DB
-     public Cluster updateCluster(Cluster clusterToUpdate, String clusterType, String hypervisor, String allocationState, String managedstate) {
+ 	public Cluster updateCluster(Cluster clusterToUpdate, String clusterType,
+ 			String hypervisor, String allocationState, String managedstate) {
  
 -		ClusterVO cluster = (ClusterVO) clusterToUpdate;
 -		// Verify cluster information and update the cluster if needed
 -		boolean doUpdate = false;
 +        ClusterVO cluster = (ClusterVO) clusterToUpdate;
 +        // Verify cluster information and update the cluster if needed
 +        boolean doUpdate = false;
  
 -		if (hypervisor != null && !hypervisor.isEmpty()) {
 +        if (hypervisor != null && !hypervisor.isEmpty()) {
-             Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(hypervisor);
+ 			Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType
+ 					.getType(hypervisor);
 -			if (hypervisorType == null) {
 +            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");
+ 				s_logger.error("Unable to resolve " + hypervisor
+ 						+ " to a valid supported hypervisor type");
+ 				throw new InvalidParameterValueException("Unable to resolve "
+ 						+ hypervisor + " to a supported type");
 -			} else {
 -				cluster.setHypervisorType(hypervisor);
 -				doUpdate = true;
 -			}
 -		}
 -
 -		Cluster.ClusterType newClusterType = null;
 -		if (clusterType != null && !clusterType.isEmpty()) {
 -			try {
 -				newClusterType = Cluster.ClusterType.valueOf(clusterType);
 -			} catch (IllegalArgumentException ex) {
 +            } else {
 +                cluster.setHypervisorType(hypervisor);
 +                doUpdate = true;
 +            }
 +        }
 +
 +        Cluster.ClusterType newClusterType = null;
 +        if (clusterType != null && !clusterType.isEmpty()) {
 +            try {
 +                newClusterType = Cluster.ClusterType.valueOf(clusterType);
 +            } catch (IllegalArgumentException ex) {
-                 throw new InvalidParameterValueException("Unable to resolve " + clusterType + " to a supported type");
+ 				throw new InvalidParameterValueException("Unable to resolve "
+ 						+ clusterType + " to a supported type");
 -			}
 -			if (newClusterType == null) {
 +            }
 +            if (newClusterType == null) {
-                 s_logger.error("Unable to resolve " + clusterType + " to a valid supported cluster type");
-                 throw new InvalidParameterValueException("Unable to resolve " + clusterType + " to a supported type");
+ 				s_logger.error("Unable to resolve " + clusterType
+ 						+ " to a valid supported cluster type");
+ 				throw new InvalidParameterValueException("Unable to resolve "
+ 						+ clusterType + " to a supported type");
 -			} else {
 -				cluster.setClusterType(newClusterType);
 -				doUpdate = true;
 -			}
 -		}
 -
 -		Grouping.AllocationState newAllocationState = null;
 -		if (allocationState != null && !allocationState.isEmpty()) {
 -			try {
 +            } else {
 +                cluster.setClusterType(newClusterType);
 +                doUpdate = true;
 +            }
 +        }
 +
 +        Grouping.AllocationState newAllocationState = null;
 +        if (allocationState != null && !allocationState.isEmpty()) {
 +            try {
-                 newAllocationState = Grouping.AllocationState.valueOf(allocationState);
+ 				newAllocationState = Grouping.AllocationState
+ 						.valueOf(allocationState);
 -			} catch (IllegalArgumentException ex) {
 +            } catch (IllegalArgumentException ex) {
-                 throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationState + "' to a supported state");
+ 				throw new InvalidParameterValueException(
+ 						"Unable to resolve Allocation State '"
+ 								+ allocationState + "' to a supported state");
 -			}
 -			if (newAllocationState == null) {
 +            }
 +            if (newAllocationState == null) {
-                 s_logger.error("Unable to resolve " + allocationState + " to a valid supported allocation State");
-                 throw new InvalidParameterValueException("Unable to resolve " + allocationState + " to a supported state");
+ 				s_logger.error("Unable to resolve " + allocationState
+ 						+ " to a valid supported allocation State");
+ 				throw new InvalidParameterValueException("Unable to resolve "
+ 						+ allocationState + " to a supported state");
 -			} else {
 +            } else {
-                 _capacityDao.updateCapacityState(null, null, cluster.getId(), null, allocationState);
+ 				_capacityDao.updateCapacityState(null, null, cluster.getId(),
+ 						null, allocationState);
 -				cluster.setAllocationState(newAllocationState);
 -				doUpdate = true;
 -			}
 -		}
 -
 -		Managed.ManagedState newManagedState = null;
 -		Managed.ManagedState oldManagedState = cluster.getManagedState();
 -		if (managedstate != null && !managedstate.isEmpty()) {
 -			try {
 -				newManagedState = Managed.ManagedState.valueOf(managedstate);
 -			} catch (IllegalArgumentException ex) {
 +                cluster.setAllocationState(newAllocationState);
 +                doUpdate = true;
 +            }
 +        }
 +
 +        Managed.ManagedState newManagedState = null;
 +        Managed.ManagedState oldManagedState = cluster.getManagedState();
 +        if (managedstate != null && !managedstate.isEmpty()) {
 +            try {
 +                newManagedState = Managed.ManagedState.valueOf(managedstate);
 +            } catch (IllegalArgumentException ex) {
-                 throw new InvalidParameterValueException("Unable to resolve Managed State '" + managedstate + "' to a supported state");
+ 				throw new InvalidParameterValueException(
+ 						"Unable to resolve Managed State '" + managedstate
+ 								+ "' to a supported state");
 -			}
 -			if (newManagedState == null) {
 +            }
 +            if (newManagedState == null) {
-                 s_logger.error("Unable to resolve Managed State '" + managedstate + "' to a supported state");
-                 throw new InvalidParameterValueException("Unable to resolve Managed State '" + managedstate + "' to a supported state");
+ 				s_logger.error("Unable to resolve Managed State '"
+ 						+ managedstate + "' to a supported state");
+ 				throw new InvalidParameterValueException(
+ 						"Unable to resolve Managed State '" + managedstate
+ 								+ "' to a supported state");
 -			} else {
 -				doUpdate = true;
 -			}
 -		}
 -
 -		if (doUpdate) {
 -			Transaction txn = Transaction.currentTxn();
 -			try {
 -				txn.start();
 -				_clusterDao.update(cluster.getId(), cluster);
 -				txn.commit();
 -			} catch (Exception e) {
 +            } else {
 +                doUpdate = true;
 +            }
 +        }
 +
 +        if (doUpdate) {
 +            Transaction txn = Transaction.currentTxn();
 +            try {
 +                txn.start();
 +                _clusterDao.update(cluster.getId(), cluster);
 +                txn.commit();
 +            } catch (Exception e) {
-                 s_logger.error("Unable to update cluster due to " + e.getMessage(), e);
-                 throw new CloudRuntimeException("Failed to update cluster. Please contact Cloud Support.");
+ 				s_logger.error(
+ 						"Unable to update cluster due to " + e.getMessage(), e);
+ 				throw new CloudRuntimeException(
+ 						"Failed to update cluster. Please contact Cloud Support.");
 -			}
 -		}
 +            }
 +        }
  
-         if( newManagedState != null && !newManagedState.equals(oldManagedState)) {
+ 		if (newManagedState != null && !newManagedState.equals(oldManagedState)) {
 -			Transaction txn = Transaction.currentTxn();
 +            Transaction txn = Transaction.currentTxn();
-             if( newManagedState.equals(Managed.ManagedState.Unmanaged) ) {
+ 			if (newManagedState.equals(Managed.ManagedState.Unmanaged)) {
 -				boolean success = false;
 -				try {
 -					txn.start();
 -					cluster.setManagedState(Managed.ManagedState.PrepareUnmanaged);
 -					_clusterDao.update(cluster.getId(), cluster);
 -					txn.commit();
 +                boolean success = false;
 +                try {
 +                    txn.start();
 +                    cluster.setManagedState(Managed.ManagedState.PrepareUnmanaged);
 +                    _clusterDao.update(cluster.getId(), cluster);
 +                    txn.commit();
-                     List<HostVO>  hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId());
-                     for( 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";
-                             throw new CloudRuntimeException("PrepareUnmanaged Failed due to " + msg);
+ 					List<HostVO> hosts = listAllUpAndEnabledHosts(
+ 							Host.Type.Routing, cluster.getId(),
+ 							cluster.getPodId(), cluster.getDataCenterId());
+ 					for (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";
+ 							throw new CloudRuntimeException(
+ 									"PrepareUnmanaged Failed due to " + msg);
 -						}
 -					}
 +                        }
 +                    }
  
-                     for( HostVO host : hosts ) {
-                         if ( host.getStatus().equals(Status.Up )) {
+ 					for (HostVO host : hosts) {
+ 						if (host.getStatus().equals(Status.Up)) {
 -							umanageHost(host.getId());
 -						}
 -					}
 -					int retry = 40;
 -					boolean lsuccess = true;
 +                            umanageHost(host.getId());
 +                        }
 +                    }
 +                    int retry = 40;
 +                    boolean lsuccess = true;
-                     for ( int i = 0; i < retry; i++) {
+ 					for (int i = 0; i < retry; i++) {
 -						lsuccess = true;
 -						try {
 -							Thread.sleep(5 * 1000);
 -						} catch (Exception e) {
 -						}
 +                        lsuccess = true;
 +                        try {
 +                            Thread.sleep(5 * 1000);
 +                        } catch (Exception e) {
 +                        }
-                         hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId());
-                         for( HostVO host : hosts ) {
-                             if ( !host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected)
+ 						hosts = listAllUpAndEnabledHosts(Host.Type.Routing,
+ 								cluster.getId(), cluster.getPodId(),
+ 								cluster.getDataCenterId());
+ 						for (HostVO host : hosts) {
+ 							if (!host.getStatus().equals(Status.Down)
+ 									&& !host.getStatus().equals(
+ 											Status.Disconnected)
 -									&& !host.getStatus().equals(Status.Alert)) {
 -								lsuccess = false;
 -								break;
 -							}
 -						}
 +                                    && !host.getStatus().equals(Status.Alert)) {
 +                                lsuccess = false;
 +                                break;
 +                            }
 +                        }
-                         if( lsuccess == true ) {
+ 						if (lsuccess == true) {
 -							success = true;
 -							break;
 -						}
 -					}
 +                            success = true;
 +                            break;
 +                        }
 +                    }
-                     if ( success == false ) {
-                         throw new CloudRuntimeException("PrepareUnmanaged Failed due to some hosts are still in UP status after 5 Minutes, please try later ");
+ 					if (success == false) {
+ 						throw new CloudRuntimeException(
+ 								"PrepareUnmanaged Failed due to some hosts are still in UP status after 5 Minutes, please try later ");
 -					}
 -				} finally {
 -					txn.start();
 +                    }
 +                } finally {
 +                    txn.start();
-                     cluster.setManagedState(success? Managed.ManagedState.Unmanaged : Managed.ManagedState.PrepareUnmanagedError);
+ 					cluster.setManagedState(success ? Managed.ManagedState.Unmanaged
+ 							: Managed.ManagedState.PrepareUnmanagedError);
 -					_clusterDao.update(cluster.getId(), cluster);
 -					txn.commit();
 -				}
 +                    _clusterDao.update(cluster.getId(), cluster);
 +                    txn.commit();
 +                }
-             } else if( newManagedState.equals(Managed.ManagedState.Managed)) {
+ 			} else if (newManagedState.equals(Managed.ManagedState.Managed)) {
 -				txn.start();
 -				cluster.setManagedState(Managed.ManagedState.Managed);
 -				_clusterDao.update(cluster.getId(), cluster);
 -				txn.commit();
 -			}
 +                txn.start();
 +                cluster.setManagedState(Managed.ManagedState.Managed);
 +                _clusterDao.update(cluster.getId(), cluster);
 +                txn.commit();
 +            }
  
 -		}
 +        }
  
 -		return cluster;
 -	}
 +        return cluster;
 +    }
  
 -	@Override
 -	public Host cancelMaintenance(CancelMaintenanceCmd cmd) {
 -		Long hostId = cmd.getId();
 +    @Override
 +    public Host cancelMaintenance(CancelMaintenanceCmd cmd) {
 +        Long hostId = cmd.getId();
  
 -		// verify input parameters
 -		HostVO host = _hostDao.findById(hostId);
 -		if (host == null || host.getRemoved() != null) {
 +        // verify input parameters
 +        HostVO host = _hostDao.findById(hostId);
 +        if (host == null || host.getRemoved() != null) {
-             throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist");
+ 			throw new InvalidParameterValueException("Host with id "
+ 					+ hostId.toString() + " doesn't exist");
 -		}
 +        }
  
-         processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE, hostId);
+ 		processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE,
+ 				hostId);
 -		boolean success = cancelMaintenance(hostId);
 +        boolean success = cancelMaintenance(hostId);
-         processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER, hostId);
+ 		processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER,
+ 				hostId);
 -		if (!success) {
 +        if (!success) {
-             throw new CloudRuntimeException("Internal error cancelling maintenance.");
+ 			throw new CloudRuntimeException(
+ 					"Internal error cancelling maintenance.");
 -		}
 -		return host;
 -	}
 +        }
 +        return host;
 +    }
  
 -	@Override
 -	public Host reconnectHost(ReconnectHostCmd cmd) {
 -		Long hostId = cmd.getId();
 +    @Override
 +    public Host reconnectHost(ReconnectHostCmd cmd) {
 +        Long hostId = cmd.getId();
  
 -		HostVO host = _hostDao.findById(hostId);
 -		if (host == null) {
 +        HostVO host = _hostDao.findById(hostId);
 +        if (host == null) {
-             throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist");
+ 			throw new InvalidParameterValueException("Host with id "
+ 					+ hostId.toString() + " doesn't exist");
 -		}
 +        }
  
 -		return (_agentMgr.reconnect(hostId) ? host : null);
 -	}
 +        return (_agentMgr.reconnect(hostId) ? host : null);
 +    }
  
 -	@Override
 +    @Override
-     public boolean resourceStateTransitTo(Host host, ResourceState.Event event, long msId) throws NoTransitionException {
+ 	public boolean resourceStateTransitTo(Host host, ResourceState.Event event,
+ 			long msId) throws NoTransitionException {
 -		ResourceState currentState = host.getResourceState();
 -		ResourceState nextState = currentState.getNextState(event);
 -		if (nextState == null) {
 +        ResourceState currentState = host.getResourceState();
 +        ResourceState nextState = currentState.getNextState(event);
 +        if (nextState == null) {
-             throw new NoTransitionException("No next resource state found for current state =" + currentState + " event =" + event);
+ 			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
+ 		// TO DO - Make it more granular and have better conversion into
+ 		// capacity type
  
-         if(host.getType() == Type.Routing && host.getClusterId() != null){
-             AllocationState capacityState =  _configMgr.findClusterAllocationState(ApiDBUtils.findClusterById(host.getClusterId()));
-             if (capacityState == AllocationState.Enabled && nextState != ResourceState.Enabled){
+ 		if (host.getType() == Type.Routing && host.getClusterId() != null) {
+ 			AllocationState capacityState = _configMgr
+ 					.findClusterAllocationState(ApiDBUtils.findClusterById(host
+ 							.getClusterId()));
+ 			if (capaci

<TRUNCATED>