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 2012/12/18 05:38:01 UTC

git commit: Modify Async callback setup convention

Updated Branches:
  refs/heads/javelin aefb657c4 -> c1ed9a901


Modify Async callback setup convention


Project: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/commit/c1ed9a90
Tree: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/tree/c1ed9a90
Diff: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/diff/c1ed9a90

Branch: refs/heads/javelin
Commit: c1ed9a901069e48231f0f5ff64f47e49cfe99b8f
Parents: aefb657
Author: Kelven Yang <ke...@gmail.com>
Authored: Mon Dec 17 20:34:13 2012 -0800
Committer: Kelven Yang <ke...@gmail.com>
Committed: Mon Dec 17 20:37:19 2012 -0800

----------------------------------------------------------------------
 .../framework/async/AsyncCallbackDispatcher.java   |  116 +--
 .../AsyncSampleEventDrivenStyleCaller.java         |   21 +-
 .../hypervisor/vmware/VmwareServerDiscoverer.java  |  547 ++++++++-------
 3 files changed, 353 insertions(+), 331 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/c1ed9a90/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
----------------------------------------------------------------------
diff --git a/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java b/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
index a02e130..7cb44df 100644
--- a/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
+++ b/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
@@ -24,36 +24,23 @@ import java.lang.reflect.Method;
 import java.util.HashMap;
 import java.util.Map;
 
+import net.sf.cglib.proxy.Enhancer;
+import net.sf.cglib.proxy.MethodInterceptor;
+import net.sf.cglib.proxy.MethodProxy;
 
 @SuppressWarnings("rawtypes")
-public class AsyncCallbackDispatcher implements AsyncCompletionCallback {
-	private static Map<Class<?>, Map<String, Method>> s_handlerCache = new HashMap<Class<?>, Map<String, Method>>();
-	private final String parentCallbackKey = "parentCallback";
-	private Map<String, Object> _contextMap = new HashMap<String, Object>();
-	private String _operationName;
-	private Object _targetObject;
+public class AsyncCallbackDispatcher<T> implements AsyncCompletionCallback {
+	private Method _callbackMethod;
+	private T _targetObject;
+	private Object _contextObject;
 	private Object _resultObject;
 	private AsyncCallbackDriver _driver = new InplaceAsyncCallbackDriver(); 
 	
-	public AsyncCallbackDispatcher(Object target) {
+	public AsyncCallbackDispatcher(T target) {
 		assert(target != null);
 		_targetObject = target;
 	}
 	
-	public AsyncCallbackDispatcher setContextParam(String key, Object param) {
-		_contextMap.put(key, param);
-		return this;
-	}
-	
-	public <T> AsyncCallbackDispatcher setParentCallback(AsyncCompletionCallback<T> parentCallback) {
-	    _contextMap.put(parentCallbackKey, parentCallback);
-	    return this;
-	}
-	
-	public AsyncCallbackDispatcher getParentCallback() {
-	   return (AsyncCallbackDispatcher)_contextMap.get(parentCallbackKey);
-	}
-	
 	public AsyncCallbackDispatcher attachDriver(AsyncCallbackDriver driver) {
 		assert(driver != null);
 		_driver = driver;
@@ -61,22 +48,34 @@ public class AsyncCallbackDispatcher implements AsyncCompletionCallback {
 		return this;
 	}
 	
-	public AsyncCallbackDispatcher setOperationName(String name) {
-		_operationName = name;
-		return this;
+	public Method getCallbackMethod() {
+		return _callbackMethod;
 	}
 	
-	public String getOperationName() {
-		return _operationName;
+	@SuppressWarnings("unchecked")
+	public T getTarget() {
+		return (T)Enhancer.create(_targetObject.getClass(), new MethodInterceptor() {
+			@Override
+			public Object intercept(Object arg0, Method arg1, Object[] arg2,
+				MethodProxy arg3) throws Throwable {
+				_callbackMethod = arg1;
+				return null;
+			}
+		});
+	}
+
+	public AsyncCallbackDispatcher setCallback(Object useless) {
+		return this;
 	}
 	
-	public Object getTargetObject() {
-		return _targetObject;
+	public AsyncCallbackDispatcher setContext(Object context) {
+		_contextObject = context;
+		return this;
 	}
 	
 	@SuppressWarnings("unchecked")
-	public <T> T getContextParam(String key) {
-		return (T)_contextMap.get(key);
+	public <P> P getContext() {
+		return (P)_contextObject;
 	}
 	
 	public void complete(Object resultObject) {
@@ -85,65 +84,28 @@ public class AsyncCallbackDispatcher implements AsyncCompletionCallback {
 	}
 	
 	@SuppressWarnings("unchecked")
-	public <T> T getResult() {
-		return (T)_resultObject;
+	public <R> R getResult() {
+		return (R)_resultObject;
+	}
+	
+	public Object getTargetObject() {
+		return _targetObject;
 	}
 	
 	public static boolean dispatch(Object target, AsyncCallbackDispatcher callback) {
 		assert(callback != null);
 		assert(target != null);
 		
-		Method handler = resolveHandler(target.getClass(), callback.getOperationName());
-		if(handler == null)
-			return false;
-		
 		try {
-			handler.invoke(target, callback);
+			callback.getCallbackMethod().invoke(target, callback, callback.getContext());
 		} catch (IllegalArgumentException e) {
-			throw new RuntimeException("IllegalArgumentException when invoking RPC callback for command: " + callback.getOperationName());
+			throw new RuntimeException("IllegalArgumentException when invoking RPC callback for command: " + callback.getCallbackMethod().getName());
 		} catch (IllegalAccessException e) {
-			throw new RuntimeException("IllegalAccessException when invoking RPC callback for command: " + callback.getOperationName());
+			throw new RuntimeException("IllegalAccessException when invoking RPC callback for command: " + callback.getCallbackMethod().getName());
 		} catch (InvocationTargetException e) {
-			throw new RuntimeException("InvocationTargetException when invoking RPC callback for command: " + callback.getOperationName(), e);
+			throw new RuntimeException("InvocationTargetException when invoking RPC callback for command: " + callback.getCallbackMethod().getName());
 		}
 		
 		return true;
 	}
-	
-	public static Method resolveHandler(Class<?> handlerClz, String command) {
-		synchronized(s_handlerCache) {
-			Map<String, Method> handlerMap = getAndSetHandlerMap(handlerClz);
-				
-			Method handler = handlerMap.get(command);
-			if(handler != null)
-				return handler;
-			
-			for(Method method : handlerClz.getDeclaredMethods()) {
-				AsyncCallbackHandler annotation = method.getAnnotation(AsyncCallbackHandler.class);
-				if(annotation != null) {
-					if(annotation.operationName().equals(command)) {
-						handlerMap.put(command, method);
-						method.setAccessible(true);
-						return method;
-					}
-				}
-			}
-		}
-		
-		return null;
-	}
-	
-	private static Map<String, Method> getAndSetHandlerMap(Class<?> handlerClz) {
-		Map<String, Method> handlerMap;
-		synchronized(s_handlerCache) {
-			handlerMap = s_handlerCache.get(handlerClz);
-			
-			if(handlerMap == null) {
-				handlerMap = new HashMap<String, Method>();
-				s_handlerCache.put(handlerClz, handlerMap);
-			}
-		}
-		
-		return handlerMap;
-	}
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/c1ed9a90/framework/ipc/test/org/apache/cloudstack/framework/codestyle/AsyncSampleEventDrivenStyleCaller.java
----------------------------------------------------------------------
diff --git a/framework/ipc/test/org/apache/cloudstack/framework/codestyle/AsyncSampleEventDrivenStyleCaller.java b/framework/ipc/test/org/apache/cloudstack/framework/codestyle/AsyncSampleEventDrivenStyleCaller.java
index 4ce86c6..852e352 100644
--- a/framework/ipc/test/org/apache/cloudstack/framework/codestyle/AsyncSampleEventDrivenStyleCaller.java
+++ b/framework/ipc/test/org/apache/cloudstack/framework/codestyle/AsyncSampleEventDrivenStyleCaller.java
@@ -20,26 +20,25 @@ package org.apache.cloudstack.framework.codestyle;
 
 import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher;
 import org.apache.cloudstack.framework.async.AsyncCallbackDriver;
-import org.apache.cloudstack.framework.async.AsyncCallbackHandler;
 
 public class AsyncSampleEventDrivenStyleCaller {
 	AsyncSampleCallee _ds = new AsyncSampleCallee();
 	AsyncCallbackDriver _callbackDriver;
 	
+	@SuppressWarnings("unchecked")
 	public void MethodThatWillCallAsyncMethod() {
-		Object vol = new Object();
-		_ds.createVolume(vol,
-			new AsyncCallbackDispatcher(this)
-				.setOperationName("volume.create")
-				.setContextParam("origVolume", vol)
-				);
+		String vol = new String("Hello");
+		AsyncCallbackDispatcher<AsyncSampleEventDrivenStyleCaller> caller = new AsyncCallbackDispatcher<AsyncSampleEventDrivenStyleCaller>(this);
+		_ds.createVolume(vol, caller
+			.setCallback(caller.getTarget().HandleVolumeCreateAsyncCallback(null, null))
+			.setContext(vol)
+		);
 	}
 
-	@AsyncCallbackHandler(operationName="volume.create")
-	public void HandleVolumeCreateAsyncCallback(AsyncCallbackDispatcher callback) {
-		Object origVol = callback.getContextParam("origVolume");
-		
+	public Void HandleVolumeCreateAsyncCallback(AsyncCallbackDispatcher<AsyncSampleEventDrivenStyleCaller> callback, String context) {
 		Object resultVol = callback.getResult();
+		
+		return null;
 	}
 	
 	public static void main(String[] args) {

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/c1ed9a90/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
index 42a29f7..91ead4d 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
@@ -71,273 +71,331 @@ import com.vmware.vim25.ClusterDasConfigInfo;
 import com.vmware.vim25.ManagedObjectReference;
 
 @Component
-@Local(value=Discoverer.class)
-public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter {
-	private static final Logger s_logger = Logger.getLogger(VmwareServerDiscoverer.class);
-	
-	@Inject ClusterDao _clusterDao;
-	@Inject VmwareManager _vmwareMgr;
-    @Inject AlertManager _alertMgr;
-    @Inject VMTemplateDao _tmpltDao;
-    @Inject ClusterDetailsDao _clusterDetailsDao;
-    @Inject HostDao _hostDao;
-    @Inject
-    DataCenterDao _dcDao;
-    @Inject ResourceManager _resourceMgr;
-    @Inject CiscoNexusVSMDeviceDao _nexusDao;
-    @Inject
-    NetworkManager _netmgr;
-    
-    @Override
-    public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url, 
-    	String username, String password, List<String> hostTags) throws DiscoveryException {
-    	
-    	if(s_logger.isInfoEnabled())
-    		s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost());
-    	
-    	if(podId == null) {
-        	if(s_logger.isInfoEnabled())
-        		s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer"); 
-    		return null;
-    	}
-    	
-        ClusterVO cluster = _clusterDao.findById(clusterId);
-        if(cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) {
-        	if(s_logger.isInfoEnabled())
-        		s_logger.info("invalid cluster id or cluster is not for VMware hypervisors"); 
-    		return null;
-        }
-        
-        List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
-        if(hosts.size() >= _vmwareMgr.getMaxHostsPerCluster()) {
-        	String msg = "VMware cluster " + cluster.getName() + " is too big to add new host now. (current configured cluster size: " + _vmwareMgr.getMaxHostsPerCluster() + ")";
-        	s_logger.error(msg);
-        	throw new DiscoveredWithErrorException(msg);
-        }
-
-        String privateTrafficLabel = null;
-        String publicTrafficLabel = null;
-        String guestTrafficLabel = null;
-        Map<String, String> vsmCredentials = null;
-        
-        privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.VMware);
-        if (privateTrafficLabel != null) {
-            s_logger.info("Detected private network label : " + privateTrafficLabel);
-        }
-        
-        if (_vmwareMgr.getNexusVSwitchGlobalParameter()) {
-            DataCenterVO zone = _dcDao.findById(dcId);
-            NetworkType zoneType = zone.getNetworkType();
-            if (zoneType != NetworkType.Basic) {
-                publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);
-                if (publicTrafficLabel != null) {
-                    s_logger.info("Detected public network label : " + publicTrafficLabel);
-                }
-            }
-            // Get physical network label
-            guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);
-            if (guestTrafficLabel != null) {
-                s_logger.info("Detected guest network label : " + guestTrafficLabel);
-            }
-            vsmCredentials = _vmwareMgr.getNexusVSMCredentialsByClusterId(clusterId);
-        }
+@Local(value = Discoverer.class)
+public class VmwareServerDiscoverer extends DiscovererBase implements
+		Discoverer, ResourceStateAdapter {
+	private static final Logger s_logger = Logger
+			.getLogger(VmwareServerDiscoverer.class);
+
+	@Inject
+	ClusterDao _clusterDao;
+	@Inject
+	VmwareManager _vmwareMgr;
+	@Inject
+	AlertManager _alertMgr;
+	@Inject
+	VMTemplateDao _tmpltDao;
+	@Inject
+	ClusterDetailsDao _clusterDetailsDao;
+	@Inject
+	HostDao _hostDao;
+	@Inject
+	DataCenterDao _dcDao;
+	@Inject
+	ResourceManager _resourceMgr;
+	@Inject
+	CiscoNexusVSMDeviceDao _nexusDao;
+	@Inject
+	NetworkManager _netmgr;
+
+	@Override
+	public Map<? extends ServerResource, Map<String, String>> find(long dcId,
+			Long podId, Long clusterId, URI url, String username,
+			String password, List<String> hostTags) throws DiscoveryException {
+
+		if (s_logger.isInfoEnabled())
+			s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId
+					+ ", cluster: " + clusterId + ", uri host: "
+					+ url.getHost());
+
+		if (podId == null) {
+			if (s_logger.isInfoEnabled())
+				s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
+			return null;
+		}
+
+		ClusterVO cluster = _clusterDao.findById(clusterId);
+		if (cluster == null
+				|| cluster.getHypervisorType() != HypervisorType.VMware) {
+			if (s_logger.isInfoEnabled())
+				s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
+			return null;
+		}
+
+		List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
+		if (hosts.size() >= _vmwareMgr.getMaxHostsPerCluster()) {
+			String msg = "VMware cluster "
+					+ cluster.getName()
+					+ " is too big to add new host now. (current configured cluster size: "
+					+ _vmwareMgr.getMaxHostsPerCluster() + ")";
+			s_logger.error(msg);
+			throw new DiscoveredWithErrorException(msg);
+		}
+
+		String privateTrafficLabel = null;
+		String publicTrafficLabel = null;
+		String guestTrafficLabel = null;
+		Map<String, String> vsmCredentials = null;
+
+		privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId,
+				HypervisorType.VMware);
+		if (privateTrafficLabel != null) {
+			s_logger.info("Detected private network label : "
+					+ privateTrafficLabel);
+		}
+
+		if (_vmwareMgr.getNexusVSwitchGlobalParameter()) {
+			DataCenterVO zone = _dcDao.findById(dcId);
+			NetworkType zoneType = zone.getNetworkType();
+			if (zoneType != NetworkType.Basic) {
+				publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId,
+						HypervisorType.VMware);
+				if (publicTrafficLabel != null) {
+					s_logger.info("Detected public network label : "
+							+ publicTrafficLabel);
+				}
+			}
+			// Get physical network label
+			guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId,
+					HypervisorType.VMware);
+			if (guestTrafficLabel != null) {
+				s_logger.info("Detected guest network label : "
+						+ guestTrafficLabel);
+			}
+			vsmCredentials = _vmwareMgr
+					.getNexusVSMCredentialsByClusterId(clusterId);
+		}
 
 		VmwareContext context = null;
 		try {
-			context = VmwareContextFactory.create(url.getHost(), username, password);
-            if (privateTrafficLabel != null)
-                context.registerStockObject("privateTrafficLabel", privateTrafficLabel);
-			
-            if (_vmwareMgr.getNexusVSwitchGlobalParameter()) {
-                if (vsmCredentials != null) {
-                    s_logger.info("Stocking credentials of Nexus VSM");
-                    context.registerStockObject("vsmcredentials", vsmCredentials);
-                }
-            }
-			List<ManagedObjectReference> morHosts = _vmwareMgr.addHostToPodCluster(context, dcId, podId, clusterId,
-				URLDecoder.decode(url.getPath()));
-            if (morHosts == null)
-                s_logger.info("Found 0 hosts.");
-            if (privateTrafficLabel != null)
-                context.uregisterStockObject("privateTrafficLabel");
-
-			if(morHosts == null) {
-				s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath()));
+			context = VmwareContextFactory.create(url.getHost(), username,
+					password);
+			if (privateTrafficLabel != null)
+				context.registerStockObject("privateTrafficLabel",
+						privateTrafficLabel);
+
+			if (_vmwareMgr.getNexusVSwitchGlobalParameter()) {
+				if (vsmCredentials != null) {
+					s_logger.info("Stocking credentials of Nexus VSM");
+					context.registerStockObject("vsmcredentials",
+							vsmCredentials);
+				}
+			}
+			List<ManagedObjectReference> morHosts = _vmwareMgr
+					.addHostToPodCluster(context, dcId, podId, clusterId,
+							URLDecoder.decode(url.getPath()));
+			if (morHosts == null)
+				s_logger.info("Found 0 hosts.");
+			if (privateTrafficLabel != null)
+				context.uregisterStockObject("privateTrafficLabel");
+
+			if (morHosts == null) {
+				s_logger.error("Unable to find host or cluster based on url: "
+						+ URLDecoder.decode(url.getPath()));
 				return null;
 			}
-			
+
 			ManagedObjectReference morCluster = null;
-			Map<String, String> clusterDetails = _clusterDetailsDao.findDetails(clusterId);
-			if(clusterDetails.get("url") != null) {
-				URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url")));
-				morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath()));
-				
-				if(morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) {
-					s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url"));
+			Map<String, String> clusterDetails = _clusterDetailsDao
+					.findDetails(clusterId);
+			if (clusterDetails.get("url") != null) {
+				URI uriFromCluster = new URI(
+						UriUtils.encodeURIComponent(clusterDetails.get("url")));
+				morCluster = context.getHostMorByPath(URLDecoder
+						.decode(uriFromCluster.getPath()));
+
+				if (morCluster == null
+						|| !morCluster.getType().equalsIgnoreCase(
+								"ClusterComputeResource")) {
+					s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: "
+							+ clusterDetails.get("url"));
 					return null;
 				} else {
 					ClusterMO clusterMo = new ClusterMO(context, morCluster);
 					ClusterDasConfigInfo dasConfig = clusterMo.getDasConfig();
-					if(dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) {
+					if (dasConfig != null && dasConfig.getEnabled() != null
+							&& dasConfig.getEnabled().booleanValue()) {
 						clusterDetails.put("NativeHA", "true");
 						_clusterDetailsDao.persist(clusterId, clusterDetails);
 					}
 				}
 			}
-			
-			if(!validateDiscoveredHosts(context, morCluster, morHosts)) {
-				if(morCluster == null)
+
+			if (!validateDiscoveredHosts(context, morCluster, morHosts)) {
+				if (morCluster == null)
 					s_logger.warn("The discovered host is not standalone host, can not be added to a standalone cluster");
 				else
 					s_logger.warn("The discovered host does not belong to the cluster");
 				return null;
 			}
 
-            Map<VmwareResource, Map<String, String>> resources = new HashMap<VmwareResource, Map<String, String>>();
-			for(ManagedObjectReference morHost : morHosts) {
-	            Map<String, String> details = new HashMap<String, String>();
-	            Map<String, Object> params = new HashMap<String, Object>();
-	            
-	            HostMO hostMo = new HostMO(context, morHost);
-	            details.put("url", hostMo.getHostName());
-	            details.put("username", username);
-	            details.put("password", password);
-	            String guid = morHost.getType() + ":" + morHost.get_value() + "@"+ url.getHost();
-	            details.put("guid", guid);
-	            
-	            params.put("url", hostMo.getHostName());
-	            params.put("username", username);
-	            params.put("password", password);
-	            params.put("zone", Long.toString(dcId));
-	            params.put("pod", Long.toString(podId));
-	            params.put("cluster", Long.toString(clusterId));
-	            params.put("guid", guid);
-                if (privateTrafficLabel != null) {
-                    params.put("private.network.vswitch.name", privateTrafficLabel);
-                }
-                if (publicTrafficLabel != null) {
-                    params.put("public.network.vswitch.name", publicTrafficLabel);
-                }
-                if (guestTrafficLabel != null) {
-                    params.put("guest.network.vswitch.name", guestTrafficLabel);
-                }
-	            
-	            VmwareResource resource = new VmwareResource(); 
-	            try {
-	                resource.configure("VMware", params);
-	            } catch (ConfigurationException e) {
-	                _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + url.getHost(), "Error is " + e.getMessage());
-	                s_logger.warn("Unable to instantiate " + url.getHost(), e);
-	            }
-	            resource.start();
-	            
-	            resources.put(resource, details);
+			Map<VmwareResource, Map<String, String>> resources = new HashMap<VmwareResource, Map<String, String>>();
+			for (ManagedObjectReference morHost : morHosts) {
+				Map<String, String> details = new HashMap<String, String>();
+				Map<String, Object> params = new HashMap<String, Object>();
+
+				HostMO hostMo = new HostMO(context, morHost);
+				details.put("url", hostMo.getHostName());
+				details.put("username", username);
+				details.put("password", password);
+				String guid = morHost.getType() + ":" + morHost.get_value()
+						+ "@" + url.getHost();
+				details.put("guid", guid);
+
+				params.put("url", hostMo.getHostName());
+				params.put("username", username);
+				params.put("password", password);
+				params.put("zone", Long.toString(dcId));
+				params.put("pod", Long.toString(podId));
+				params.put("cluster", Long.toString(clusterId));
+				params.put("guid", guid);
+				if (privateTrafficLabel != null) {
+					params.put("private.network.vswitch.name",
+							privateTrafficLabel);
+				}
+				if (publicTrafficLabel != null) {
+					params.put("public.network.vswitch.name",
+							publicTrafficLabel);
+				}
+				if (guestTrafficLabel != null) {
+					params.put("guest.network.vswitch.name", guestTrafficLabel);
+				}
+
+				VmwareResource resource = new VmwareResource();
+				try {
+					resource.configure("VMware", params);
+				} catch (ConfigurationException e) {
+					_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId,
+							podId, "Unable to add " + url.getHost(),
+							"Error is " + e.getMessage());
+					s_logger.warn("Unable to instantiate " + url.getHost(), e);
+				}
+				resource.start();
+
+				resources.put(resource, details);
 			}
-            
-            // place a place holder guid derived from cluster ID
-            cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString());
-            _clusterDao.update(clusterId, cluster);
-            
-            return resources;
+
+			// place a place holder guid derived from cluster ID
+			cluster.setGuid(UUID.nameUUIDFromBytes(
+					String.valueOf(clusterId).getBytes()).toString());
+			_clusterDao.update(clusterId, cluster);
+
+			return resources;
 		} catch (DiscoveredWithErrorException e) {
 			throw e;
 		} catch (Exception e) {
-			s_logger.warn("Unable to connect to Vmware vSphere server. service address: " + url.getHost());
+			s_logger.warn("Unable to connect to Vmware vSphere server. service address: "
+					+ url.getHost());
 			return null;
 		} finally {
-			if(context != null)
+			if (context != null)
 				context.close();
 		}
-    }
-    
-    private boolean validateDiscoveredHosts(VmwareContext context, ManagedObjectReference morCluster, List<ManagedObjectReference> morHosts) throws Exception {
-    	if(morCluster == null) {
-    		for(ManagedObjectReference morHost : morHosts) {
-    			ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent");
-    			if(morParent.getType().equalsIgnoreCase("ClusterComputeResource"))
-    				return false;
-    		}
-    	} else {
-    		for(ManagedObjectReference morHost : morHosts) {
-    			ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent");
-    			if(!morParent.getType().equalsIgnoreCase("ClusterComputeResource"))
-    				return false;
-    			
-    			if(!morParent.get_value().equals(morCluster.get_value()))
-    				return false;
-    		}
-    	}
-    	
-    	return true;
-    }
-    
-    @Override
-    public void postDiscovery(List<HostVO> hosts, long msId) {
-        // do nothing
-    }
-    
-    @Override
+	}
+
+	private boolean validateDiscoveredHosts(VmwareContext context,
+			ManagedObjectReference morCluster,
+			List<ManagedObjectReference> morHosts) throws Exception {
+		if (morCluster == null) {
+			for (ManagedObjectReference morHost : morHosts) {
+				ManagedObjectReference morParent = (ManagedObjectReference) context
+						.getServiceUtil().getDynamicProperty(morHost, "parent");
+				if (morParent.getType().equalsIgnoreCase(
+						"ClusterComputeResource"))
+					return false;
+			}
+		} else {
+			for (ManagedObjectReference morHost : morHosts) {
+				ManagedObjectReference morParent = (ManagedObjectReference) context
+						.getServiceUtil().getDynamicProperty(morHost, "parent");
+				if (!morParent.getType().equalsIgnoreCase(
+						"ClusterComputeResource"))
+					return false;
+
+				if (!morParent.get_value().equals(morCluster.get_value()))
+					return false;
+			}
+		}
+
+		return true;
+	}
+
+	@Override
+	public void postDiscovery(List<HostVO> hosts, long msId) {
+		// do nothing
+	}
+
+	@Override
 	public boolean matchHypervisor(String hypervisor) {
-    	if(hypervisor == null)
-    		return true;
-    	
-    	return Hypervisor.HypervisorType.VMware.toString().equalsIgnoreCase(hypervisor);
-    }
-    
-    @Override
+		if (hypervisor == null)
+			return true;
+
+		return Hypervisor.HypervisorType.VMware.toString().equalsIgnoreCase(
+				hypervisor);
+	}
+
+	@Override
 	public Hypervisor.HypervisorType getHypervisorType() {
-    	return Hypervisor.HypervisorType.VMware;
-    }
-    
-    @Override
-    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
-        if(s_logger.isInfoEnabled())
-        	s_logger.info("Configure VmwareServerDiscoverer, discover name: " + name);
-        
-        super.configure(name, params);
-        
-        ComponentLocator locator = ComponentLocator.getCurrentLocator();
-        ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
-        if (configDao == null) {
-            throw new ConfigurationException("Unable to get the configuration dao.");
-        }
-        
-        createVmwareToolsIso();
-
-		if(s_logger.isInfoEnabled()) {
+		return Hypervisor.HypervisorType.VMware;
+	}
+
+	@Override
+	public boolean configure(String name, Map<String, Object> params)
+			throws ConfigurationException {
+		if (s_logger.isInfoEnabled())
+			s_logger.info("Configure VmwareServerDiscoverer, discover name: "
+					+ name);
+
+		super.configure(name, params);
+
+		ComponentLocator locator = ComponentLocator.getCurrentLocator();
+		ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
+		if (configDao == null) {
+			throw new ConfigurationException(
+					"Unable to get the configuration dao.");
+		}
+
+		createVmwareToolsIso();
+
+		if (s_logger.isInfoEnabled()) {
 			s_logger.info("VmwareServerDiscoverer has been successfully configured");
 		}
-		_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
-        return true;
-    }
-    
-    private void createVmwareToolsIso() {
-        String isoName = "vmware-tools.iso";
-        VMTemplateVO tmplt = _tmpltDao.findByTemplateName(isoName);
-        Long id;
-        if (tmplt == null) {
-            id = _tmpltDao.getNextInSequence(Long.class, "id");
-            VMTemplateVO template = new VMTemplateVO(id, isoName, isoName, ImageFormat.ISO, true, true,
-                    TemplateType.PERHOST, null, null, true, 64,
-                    Account.ACCOUNT_ID_SYSTEM, null, "VMware Tools Installer ISO", false, 1, false, HypervisorType.VMware);
-            _tmpltDao.persist(template);
-        } else {
-            id = tmplt.getId();
-            tmplt.setTemplateType(TemplateType.PERHOST);
-            tmplt.setUrl(null);
-            _tmpltDao.update(id, tmplt);
-        }
-    }
+		_resourceMgr.registerResourceStateAdapter(this.getClass()
+				.getSimpleName(), this);
+		return true;
+	}
+
+	private void createVmwareToolsIso() {
+		String isoName = "vmware-tools.iso";
+		VMTemplateVO tmplt = _tmpltDao.findByTemplateName(isoName);
+		Long id;
+		if (tmplt == null) {
+			id = _tmpltDao.getNextInSequence(Long.class, "id");
+			VMTemplateVO template = new VMTemplateVO(id, isoName, isoName,
+					ImageFormat.ISO, true, true, TemplateType.PERHOST, null,
+					null, true, 64, Account.ACCOUNT_ID_SYSTEM, null,
+					"VMware Tools Installer ISO", false, 1, false,
+					HypervisorType.VMware);
+			_tmpltDao.persist(template);
+		} else {
+			id = tmplt.getId();
+			tmplt.setTemplateType(TemplateType.PERHOST);
+			tmplt.setUrl(null);
+			_tmpltDao.update(id, tmplt);
+		}
+	}
 
 	@Override
-    public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
-	    // TODO Auto-generated method stub
-	    return null;
-    }
+	public HostVO createHostVOForConnectedAgent(HostVO host,
+			StartupCommand[] cmd) {
+		// TODO Auto-generated method stub
+		return null;
+	}
 
 	@Override
-    public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details,
-            List<String> hostTags) {
+	public HostVO createHostVOForDirectConnectAgent(HostVO host,
+			StartupCommand[] startup, ServerResource resource,
+			Map<String, String> details, List<String> hostTags) {
 		StartupCommand firstCmd = startup[0];
 		if (!(firstCmd instanceof StartupRoutingCommand)) {
 			return null;
@@ -348,23 +406,26 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
 			return null;
 		}
 
-		return _resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.VMware, details, hostTags);
-    }
+		return _resourceMgr.fillRoutingHostVO(host, ssCmd,
+				HypervisorType.VMware, details, hostTags);
+	}
 
 	@Override
-    public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
-		if (host.getType() != com.cloud.host.Host.Type.Routing || host.getHypervisorType() != HypervisorType.VMware) {
+	public DeleteHostAnswer deleteHost(HostVO host, boolean isForced,
+			boolean isForceDeleteStorage) throws UnableDeleteHostException {
+		if (host.getType() != com.cloud.host.Host.Type.Routing
+				|| host.getHypervisorType() != HypervisorType.VMware) {
 			return null;
 		}
-		
+
 		_resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
 		return new DeleteHostAnswer(true);
-    }
-	
-    @Override
-    public boolean stop() {
-    	_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
-        return super.stop();
-    }
-}
+	}
 
+	@Override
+	public boolean stop() {
+		_resourceMgr.unregisterResourceStateAdapter(this.getClass()
+				.getSimpleName());
+		return super.stop();
+	}
+}