You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by re...@apache.org on 2013/10/23 11:00:18 UTC

[3/4] git commit: adding changes for STRATOS-104

adding changes for STRATOS-104


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

Branch: refs/heads/master
Commit: f94b4b518411befecfe0c96d6f7148afbbe6898b
Parents: dcf9ad4
Author: rekathiru <rt...@gmail.com>
Authored: Wed Oct 23 14:29:08 2013 +0530
Committer: rekathiru <rt...@gmail.com>
Committed: Wed Oct 23 14:29:08 2013 +0530

----------------------------------------------------------------------
 .../client/CloudControllerServiceClient.java    |  29 +-
 .../SingleTenantCartridgeSubscription.java      |   6 +-
 .../mgt/utils/ApplicationManagementUtil.java    |   4 +-
 .../org.apache.stratos.cloud.controller/pom.xml |  11 +-
 .../controller/axiom/AxiomXpathParser.java      |  71 +-
 .../controller/consumers/TopologyBuilder.java   | 212 ------
 .../controller/deployers/CartridgeDeployer.java |  24 +-
 .../controller/deployers/ServiceDeployer.java   |  30 +-
 .../impl/CloudControllerServiceImpl.java        | 656 +++++++++----------
 .../interfaces/CloudControllerService.java      |  91 ++-
 .../internal/CloudControllerDSComponent.java    |  23 +-
 .../jcloud/ComputeServiceBuilderUtil.java       |  30 +-
 .../CartridgeInstanceDataPublisherTask.java     |  35 +-
 .../controller/registry/RegistryManager.java    |   3 +-
 .../runtime/FasterLookUpDataHolder.java         | 102 ++-
 .../topic/TopologySynchronizerTask.java         |  35 +-
 .../controller/topology/TopologyBuilder.java    | 261 ++++++++
 .../topology/TopologyEventMessageDelegator.java |  65 ++
 .../topology/TopologyEventSender.java           | 112 ++++
 .../controller/topology/TopologyListener.java   |  43 ++
 .../controller/topology/TopologyManager.java    | 112 ++++
 .../util/CloudControllerConstants.java          |   6 +-
 .../controller/util/CloudControllerUtil.java    |  21 +-
 .../cloud/controller/util/IaasProvider.java     |  26 +-
 .../cloud/controller/util/LocationScope.java    |  70 ++
 .../cloud/controller/util/ServiceContext.java   | 119 +---
 .../controller/util/ServiceReferenceHolder.java |   1 -
 .../src/main/resources/service.xsd              |   1 -
 .../src/main/resources/services.xsd             |   1 -
 .../service/axiom/AxiomXpathParserTest.java     |   8 +-
 .../service/util/ServiceContextTest.java        |  12 +-
 .../src/test/resources/cloud-controller.xml     |   3 -
 components/pom.xml                              |   3 -
 .../main/resources/conf/cloud-controller.xml    |   2 -
 .../main/resources/CloudControllerService.wsdl  | 144 +---
 35 files changed, 1278 insertions(+), 1094 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
index cfd29c7..d62ecda 100644
--- a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
@@ -68,32 +68,25 @@ public class CloudControllerServiceClient {
         return serviceClient;
     }
 
-	public boolean register(String domainName, String subDomain, String cartridgeType,
-	                        DataHandler payload, String tenantRange, String hostName, Properties properties) throws RemoteException, CloudControllerServiceUnregisteredCartridgeExceptionException
+	public boolean register(String clusterId, String cartridgeType,
+	                        DataHandler payload, String tenantRange,
+                            String hostName, Properties properties,
+                            String autoscalorPolicyName) throws RemoteException, CloudControllerServiceUnregisteredCartridgeExceptionException
 	                                                                                  {		
-		return stub.registerService(domainName, subDomain, tenantRange, cartridgeType, hostName,
-		                            properties, payload);
+		return stub.registerService(clusterId, tenantRange, cartridgeType, hostName,
+		                            properties, payload, autoscalorPolicyName);
 
 	}
 
-	public String startInstance(String domain, String subDomain) throws Exception {
-		return stub.startInstance(domain, subDomain);
-	}
-
-	public boolean terminateAllInstances(String domain, String subDomain) throws Exception {
-		return stub.terminateAllInstances(domain, subDomain);
+    public boolean terminateAllInstances(String clusterId) throws Exception {
+		return stub.terminateAllInstances(clusterId);
 	}
 
 	public String[] getRegisteredCartridges() throws Exception {
 		return stub.getRegisteredCartridges();
 	}
 
-	public boolean createKeyPair(String cartridge, String keyPairName, String publicKey)
-	                                                                                    throws Exception {
-		return stub.createKeyPairFromPublicKey(cartridge, keyPairName, publicKey);
-	}
-
-	public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException, Exception {
+    public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException, Exception {
 		try {
 			return stub.getCartridgeInfo(cartridgeType);
 		} catch (RemoteException e) {
@@ -103,8 +96,8 @@ public class CloudControllerServiceClient {
 		}
 	}
 	
-	public boolean unregisterService(String domain, String subDomain) throws Exception {
-	    return stub.unregisterService(domain, subDomain);
+	public boolean unregisterService(String clusterId) throws Exception {
+	    return stub.unregisterService(clusterId);
 	}
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/subscription/SingleTenantCartridgeSubscription.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/subscription/SingleTenantCartridgeSubscription.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/subscription/SingleTenantCartridgeSubscription.java
index 5e7e5af..4ed9bc5 100644
--- a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/subscription/SingleTenantCartridgeSubscription.java
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/subscription/SingleTenantCartridgeSubscription.java
@@ -80,8 +80,7 @@ public class SingleTenantCartridgeSubscription extends CartridgeSubscription {
     public void removeSubscription() throws ADCException, NotSubscribedException {
 
         try {
-            CloudControllerServiceClient.getServiceClient().terminateAllInstances(getClusterDomain(),
-                    getClusterSubDomain());
+            CloudControllerServiceClient.getServiceClient().terminateAllInstances(getClusterDomain());
 
         } catch (AxisFault e) {
             String errorMsg = "Error in terminating cartridge subscription, alias " + getAlias();
@@ -97,8 +96,7 @@ public class SingleTenantCartridgeSubscription extends CartridgeSubscription {
         log.info("Terminated all instances of " + getClusterDomain() + " " + getClusterSubDomain());
 
         try {
-            CloudControllerServiceClient.getServiceClient().unregisterService(getClusterDomain(),
-                    getClusterSubDomain());
+            CloudControllerServiceClient.getServiceClient().unregisterService(getClusterDomain());
 
         } catch (Exception e) {
             String errorMsg = "Error in unregistering service cluster with domain " + getClusterDomain() +

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
index 1ab0982..ed3b353 100644
--- a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
@@ -932,8 +932,8 @@ public class ApplicationManagementUtil {
             throws ADCException, UnregisteredCartridgeException {
         log.info("Register service..");
         try {
-            CloudControllerServiceClient.getServiceClient().register(domain, subDomain, cartridgeType, payload, tenantRange,
-                    hostName, properties);
+            CloudControllerServiceClient.getServiceClient().register(domain, cartridgeType, payload, tenantRange,
+                    hostName, properties, "economy");
         } catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
             String msg = "Exception is occurred in register service operation. Reason :" + e.getMessage();
             log.error(msg, e);

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/pom.xml b/components/org.apache.stratos.cloud.controller/pom.xml
index 92c9ede..83a4d7d 100644
--- a/components/org.apache.stratos.cloud.controller/pom.xml
+++ b/components/org.apache.stratos.cloud.controller/pom.xml
@@ -98,20 +98,14 @@
             <groupId>org.wso2.carbon</groupId>
             <artifactId>org.wso2.carbon.utils</artifactId>
 	    </dependency>
-
         <dependency>
             <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <artifactId>org.apache.stratos.messaging</artifactId>
             <version>${project.version}</version>
-		    <exclusions>
-		        <exclusion>
-		            <groupId>com.google.guava.wso2</groupId>
-		            <artifactId>guava</artifactId>
-		        </exclusion>
-		    </exclusions>
         </dependency>
 
 
+
 <dependency>
     <groupId>org.wso2.carbon</groupId>
     <artifactId>org.wso2.carbon.securevault</artifactId>
@@ -264,6 +258,7 @@
            <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
            <version>2.1.1</version>
          </dependency>
+
          <dependency>
             <groupId>org.wso2.carbon</groupId>
             <artifactId>org.wso2.carbon.databridge.agent.thrift</artifactId>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java
index 30bf0d6..ec7c615 100644
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/axiom/AxiomXpathParser.java
@@ -18,22 +18,6 @@
  */
 package org.apache.stratos.cloud.controller.axiom;
 
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.XMLConstants;
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.Source;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-import javax.xml.validation.Validator;
-
 import org.apache.axiom.om.OMElement;
 import org.apache.axiom.om.OMFactory;
 import org.apache.axiom.om.OMNode;
@@ -41,24 +25,32 @@ import org.apache.axiom.om.impl.builder.StAXOMBuilder;
 import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
 import org.apache.axiom.om.impl.dom.ElementImpl;
 import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.cloud.controller.exception.CloudControllerException;
 import org.apache.stratos.cloud.controller.exception.MalformedConfigurationFileException;
 import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.apache.stratos.cloud.controller.util.AppType;
-import org.apache.stratos.cloud.controller.util.Cartridge;
-import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
-import org.apache.stratos.cloud.controller.util.PortMapping;
-import org.apache.stratos.cloud.controller.util.TopologyConfig;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cloud.controller.util.*;
 import org.jaxen.JaxenException;
 import org.w3c.dom.Element;
-import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
-import org.apache.stratos.cloud.controller.util.IaasProvider;
-import org.apache.stratos.cloud.controller.util.ServiceContext;
 import org.wso2.securevault.SecretResolver;
 import org.wso2.securevault.SecretResolverFactory;
 
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
 /**
  * This class is parsing configuration files using Axiom Xpath.
  */
@@ -73,7 +65,7 @@ public class AxiomXpathParser {
 	}
 
 	/**
-     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param cartridgeElementString Cartridges section as a {@link String}
      * @param aCartridge {@link org.apache.stratos.cloud.controller.util.Cartridge} instance.
      * @param appTypesNodes nodes of App types.
      */
@@ -409,10 +401,10 @@ public class AxiomXpathParser {
 
 			// load other elements
 			loadClassName(iaas, iaasElt);
-			loadMaxInstanceLimit(iaas, iaasElt);
+//			loadMaxInstanceLimit(iaas, iaasElt);
 			loadProperties(iaasElt, iaas.getProperties());
 			loadTemplate(iaas, iaasElt);
-			loadScalingOrders(iaas, iaasElt);
+//			loadScalingOrders(iaas, iaasElt);
 			loadProvider(iaas, iaasElt);
 			loadIdentity(iaas, iaasElt);
 			loadCredentials(iaas, iaasElt, xpath);
@@ -470,7 +462,7 @@ public class AxiomXpathParser {
 	}
 
 	/**
-     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param cartridgeElementString Cartridges section as a {@link String}
      * @param aCartridge {@link Cartridge} instance.
      * @param portMappingNodes nodes of port mapping elements
      */
@@ -581,16 +573,10 @@ public class AxiomXpathParser {
 					}
 
 					// set domain name
-					serviceCtxt.setDomainName(node.getAttribute(new QName(
-					                                                      CloudControllerConstants.SERVICE_DOMAIN_ATTR))
-					                              .getAttributeValue());
-
-					// set sub domain
-					serviceCtxt.setSubDomainName(node.getAttribute(new QName(
-					                                                         CloudControllerConstants.SERVICE_SUB_DOMAIN_ATTR))
-					                                 .getAttributeValue());
-
-					// set tenant range
+					serviceCtxt.setClusterId(node.getAttribute(new QName(
+                            CloudControllerConstants.SERVICE_DOMAIN_ATTR))
+                            .getAttributeValue());
+					                              // set tenant range
 					serviceCtxt.setTenantRange(node.getAttribute(new QName(
 					                                                       CloudControllerConstants.SERVICE_TENANT_RANGE_ATTR))
 					                               .getAttributeValue());
@@ -908,6 +894,7 @@ public class AxiomXpathParser {
 
 	}
 
+	/* Have to handle at the autoscaler level...
 	private void loadScalingOrders(final IaasProvider iaas, final OMElement iaasElt) {
 		// set scale up order
 		Iterator<?> it =
@@ -971,7 +958,7 @@ public class AxiomXpathParser {
 			handleException(msg);
 		}
 
-	}
+	}*/
 
 	private void loadTemplate(final IaasProvider iaas, final OMElement iaasElt) {
 
@@ -1127,7 +1114,7 @@ public class AxiomXpathParser {
 	}
 
 	/**
-     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param cartridgeElementString Cartridges section as a {@link String}
      * @param aCartridge {@link Cartridge} instance.
      * @param deploymentNodes list of deployment directory nodes
      */

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java
deleted file mode 100644
index ed28d68..0000000
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/consumers/TopologyBuilder.java
+++ /dev/null
@@ -1,212 +0,0 @@
-package org.apache.stratos.cloud.controller.consumers;
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.concurrent.BlockingQueue;
-
-import org.apache.stratos.cloud.controller.exception.CloudControllerException;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.conf.structure.Node;
-import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
-import org.apache.stratos.lb.common.conf.util.Constants;
-import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
-import org.apache.stratos.cloud.controller.util.ServiceReferenceHolder;
-import org.apache.stratos.cloud.controller.util.ServiceContext;
-
-/**
- * This class is responsible for generating the service topology and
- * publishing it to a topic.
- */
-public class TopologyBuilder implements Runnable {
-
-    private BlockingQueue<List<ServiceContext>> sharedQueue;
-	private static File topologyFile, backup;
-	private static final Log log = LogFactory.getLog(TopologyBuilder.class);
-	private static FasterLookUpDataHolder data = FasterLookUpDataHolder.getInstance();
-	private static String topic;
-	
-	public TopologyBuilder(BlockingQueue<List<ServiceContext>> queue){
-		
-		sharedQueue = queue;
-		topologyFile = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH);
-		backup = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH+".back");
-		topic = CloudControllerConstants.TOPOLOGY_TOPIC_NAME;
-		
-	}
-	
-	@Override
-	public void run() {
-
-		while(true){
-            try {
-            	Object obj = sharedQueue.take();
-            	boolean isAdded = false;
-            	
-            	if(obj instanceof List<?>){
-            		@SuppressWarnings("unchecked")
-                    List<ServiceContext> ctxts = (List<ServiceContext>) obj;
-            		
-            		for (ServiceContext serviceContext : ctxts) {
-
-            			Node newNode = serviceContext.toNode();
-            			
-            			if(!topologyFile.exists()){
-            				FileUtils.writeStringToFile(topologyFile, "services {\n}");
-            			}
-            			
-            			String currentContent = FileUtils.readFileToString(topologyFile);
-            			Node currentNode = NodeBuilder.buildNode(currentContent);
-                   			
-            			for (Node aNode : currentNode.getChildNodes()) {
-            				// similar service element is present
-	                        if(aNode.getName().equals(newNode.getName())){
-	                        	// hence, we should not override, but append
-	                        	Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
-	                        	
-	                        	if(domainsNode == null){
-	                        		// existing node is useless
-	                        		currentNode.removeChildNode(aNode.getName());
-	                        		currentNode.appendChild(newNode);
-	                        		break;
-	                        	}
-	                        	
-	                        	// append the new node/s
-	                        	for (Node serNode : newNode.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
-	                                
-	                        		for (Node currentSerNode : domainsNode.getChildNodes()) {
-	                                    String prop = Constants.SUB_DOMAIN_ELEMENT;
-	                        			if(serNode.getName().equals(currentSerNode.getName()) &&
-	                        					serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
-	                        				// if domain and sub domain, are not unique, we shouldn't append, but override
-	                        				domainsNode.removeChildNode(currentSerNode.getName());
-	                        				break;
-	                        			}
-                                    }
-	                        		
-	                        		domainsNode.appendChild(serNode);
-                                }
-	                        	isAdded = true;
-	                        	break;
-	                        }
-                        }
-            			
-						if (!isAdded) {
-							currentNode.appendChild(newNode);
-						}
-						
-            			if (topologyFile.exists()) {
-            				backup.delete();
-            				topologyFile.renameTo(backup);
-            			}
-            			
-            			// overwrite the topology file
-            			FileUtils.writeStringToFile(topologyFile, currentNode.toString());
-            			
-            			// publish to the topic - to sync immediately
-            	        data.getTopicPublisher(topic).publish(currentNode.toString());
-
-                    }
-            	}
-                
-            } catch (InterruptedException ignore) {
-            } catch (IOException e) {
-            	log.error(e.getMessage(), e);
-            	throw new CloudControllerException(e.getMessage(), e);
-            }
-        }
-
-	}
-	
-	public static void removeTopologyAndPublish(ServiceContext serviceContext){
-	    
-	    Node currentNodeToBeRemoved = null;
-	    Node nodeToBeRemoved = serviceContext.toNode();
-        
-        if(!topologyFile.exists()){
-            return;
-        }
-        try{
-        String currentContent = FileUtils.readFileToString(topologyFile);
-        Node currentNode = NodeBuilder.buildNode(currentContent);
-            
-        for (Node aNode : currentNode.getChildNodes()) {
-            // similar service element is present
-            if(aNode.getName().equals(nodeToBeRemoved.getName())){
-                // let's check whether the domain node exists
-                
-                Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
-                
-                if(domainsNode == null){
-                    continue;
-                }
-                
-                for (Node serNode : nodeToBeRemoved.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
-                    
-                    for (Node currentSerNode : domainsNode.getChildNodes()) {
-                        String prop = Constants.SUB_DOMAIN_ELEMENT;
-                        if(serNode.getName().equals(currentSerNode.getName()) &&
-                                serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
-                            // if domain and sub domain, are matching, we should remove the node.
-                            domainsNode.removeChildNode(currentSerNode.getName());
-                            if(domainsNode.getChildNodes().size() == 0){
-                                // if no cluster definitions remain, we shouldn't keep the node
-                                currentNodeToBeRemoved = aNode;
-                            }
-                            break;
-                        }
-                    }
-                    
-                }
-                
-            }
-        }
-        
-        if(currentNodeToBeRemoved != null){
-            // remove the node with empty clusters
-            currentNode.removeChildNode(currentNodeToBeRemoved);
-        }
-        
-        if (topologyFile.exists()) {
-            backup.delete();
-            topologyFile.renameTo(backup);
-        }
-        
-        // overwrite the topology file
-        FileUtils.writeStringToFile(topologyFile, currentNode.toString());
-        
-        // publish to the topic - to sync immediately
-        data.getTopicPublisher(topic).publish(currentNode.toString());
-        
-        } catch (IOException e) {
-            log.error(e.getMessage(), e);
-            throw new CloudControllerException(e.getMessage(), e);
-        }
-
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java
index 310ebd7..39c3300 100644
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/CartridgeDeployer.java
@@ -18,27 +18,28 @@
  */
 package org.apache.stratos.cloud.controller.deployers;
 
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
 import org.apache.axis2.context.ConfigurationContext;
 import org.apache.axis2.deployment.AbstractDeployer;
 import org.apache.axis2.deployment.DeploymentException;
 import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.cloud.controller.axiom.AxiomXpathParser;
 import org.apache.stratos.cloud.controller.concurrent.ThreadExecutor;
+import org.apache.stratos.cloud.controller.topology.TopologyBuilder;
 import org.apache.stratos.cloud.controller.exception.CloudControllerException;
 import org.apache.stratos.cloud.controller.interfaces.Iaas;
 import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
 import org.apache.stratos.cloud.controller.util.Cartridge;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.cloud.controller.util.IaasProvider;
 import org.wso2.carbon.utils.CarbonUtils;
 
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
 /**
  * All the {@link org.apache.stratos.cloud.controller.util.Cartridge}s will get deployed / undeployed / updated via this class.
  */
@@ -90,9 +91,9 @@ public class CartridgeDeployer extends AbstractDeployer{
 			fileToCartridgeListMap.put(deploymentFileData.getAbsolutePath(),
 			                           new ArrayList<Cartridge>(cartridges));
 
-			log.info("Successfully deployed the Cartridge definition specified at "+deploymentFileData.getAbsolutePath());
-			
-		} catch (Exception e) {
+			log.info("Successfully deployed the Cartridge definition specified at " + deploymentFileData.getAbsolutePath());
+            TopologyBuilder.handleServiceCreated(cartridges);
+        } catch (Exception e) {
 			String msg = "Invalid deployment artefact at "+deploymentFileData.getAbsolutePath();
             // back up the file
             File f = deploymentFileData.getFile();
@@ -141,6 +142,7 @@ public class CartridgeDeployer extends AbstractDeployer{
         // grab the entry from Map
         if(fileToCartridgeListMap.containsKey(file)){
             // remove 'em
+            TopologyBuilder.handleServiceRemoved(fileToCartridgeListMap.get(file));
             serviceContextLookUpStructure.removeCartridges(fileToCartridgeListMap.get(file));
             
             log.info("Successfully undeployed the Cartridge definition specified at "+file);

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java
index f325949..d435dd4 100644
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/deployers/ServiceDeployer.java
@@ -18,24 +18,24 @@
  */
 package org.apache.stratos.cloud.controller.deployers;
 
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
 import org.apache.axis2.context.ConfigurationContext;
 import org.apache.axis2.deployment.AbstractDeployer;
 import org.apache.axis2.deployment.DeploymentException;
 import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.cloud.controller.axiom.AxiomXpathParser;
-import org.apache.stratos.cloud.controller.consumers.TopologyBuilder;
+import org.apache.stratos.cloud.controller.topology.TopologyBuilder;
 import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
 import org.apache.stratos.cloud.controller.util.ServiceContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.wso2.carbon.utils.CarbonUtils;
 
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
 /**
  * All the {@link org.apache.stratos.cloud.controller.util.Cartridge}s will get deployed / undeployed / updated via this class.
  */
@@ -89,12 +89,9 @@ public class ServiceDeployer extends AbstractDeployer{
         // deploy
         List<ServiceContext> services = parser.getServiceContexts();
         
-        // notify consumer by adding the diff
-        try {
-	        serviceContextLookUpStructure.getSharedTopologyDiffQueue().put(services);
-        } catch (InterruptedException ignore) {
-        }
-        
+        // notify consumer by adding services
+        TopologyBuilder.handleClusterCreated(services);
+
         // update map
         fileToServiceContextListMap.put(deploymentFileData.getAbsolutePath(), new ArrayList<ServiceContext>(services));
         
@@ -141,10 +138,9 @@ public class ServiceDeployer extends AbstractDeployer{
             // remove 'em all
             for (ServiceContext ctxt : fileToServiceContextListMap.get(file)) {
                 serviceContextLookUpStructure.removeServiceContext(ctxt);
+                TopologyBuilder.handleClusterRemoved(ctxt);
                 // remove from the topology
-                TopologyBuilder.removeTopologyAndPublish(ctxt);
             }
-            
             log.info("Successfully undeployed the Service definition specified at "+file);
         }
         

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
index 832180a..b2395e0 100644
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
@@ -18,57 +18,41 @@
  */
 package org.apache.stratos.cloud.controller.impl;
 
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.apache.stratos.cloud.controller.consumers.TopologyBuilder;
+import com.google.common.collect.Lists;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.exception.UnregisteredCartridgeException;
 import org.apache.stratos.cloud.controller.exception.UnregisteredServiceException;
+import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.apache.stratos.cloud.controller.persist.Deserializer;
 import org.apache.stratos.cloud.controller.publisher.CartridgeInstanceDataPublisherTask;
+import org.apache.stratos.cloud.controller.registry.RegistryManager;
 import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.apache.stratos.cloud.controller.util.Cartridge;
-import org.apache.stratos.cloud.controller.util.CartridgeInfo;
+import org.apache.stratos.cloud.controller.topic.TopologySynchronizerTask;
+import org.apache.stratos.cloud.controller.topology.TopologyBuilder;
+import org.apache.stratos.cloud.controller.topology.TopologyEventMessageDelegator;
+import org.apache.stratos.cloud.controller.util.*;
 import org.apache.stratos.cloud.controller.util.Properties;
-import org.apache.stratos.cloud.controller.util.Property;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.jclouds.compute.ComputeService;
 import org.jclouds.compute.domain.ComputeMetadata;
 import org.jclouds.compute.domain.NodeMetadata;
 import org.jclouds.compute.domain.NodeMetadata.Status;
 import org.jclouds.compute.domain.Template;
 import org.jclouds.compute.domain.internal.NodeMetadataImpl;
-import org.apache.stratos.lb.common.conf.util.Constants;
 import org.wso2.carbon.ntask.common.TaskException;
 import org.wso2.carbon.ntask.core.TaskInfo;
 import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo;
 import org.wso2.carbon.ntask.core.TaskManager;
 import org.wso2.carbon.ntask.core.service.TaskService;
 import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.apache.stratos.cloud.controller.exception.UnregisteredCartridgeException;
-import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
-import org.apache.stratos.cloud.controller.persist.Deserializer;
-import org.apache.stratos.cloud.controller.registry.RegistryManager;
-import org.apache.stratos.cloud.controller.topic.TopologySynchronizerTask;
-import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
-import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
-import org.apache.stratos.cloud.controller.util.IaasContext;
-import org.apache.stratos.cloud.controller.util.IaasProvider;
-import org.apache.stratos.cloud.controller.util.ServiceContext;
-import org.apache.stratos.cloud.controller.util.ServiceReferenceHolder;
 
-import com.google.common.collect.Lists;
+import java.io.File;
+import java.io.IOException;
+import java.util.*;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 
 /**
  * Cloud Controller Service is responsible for starting up new server instances,
@@ -150,9 +134,8 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 	}
 
 	private void startTopologyBuilder() {
-		// initialize TopologyBuilder Consumer
-		Thread topologyBuilder = new Thread(new TopologyBuilder(
-				dataHolder.getSharedTopologyDiffQueue()));
+		// initialize TopologyEventMessageProcessor Consumer
+		Thread topologyBuilder = new Thread(new TopologyEventMessageDelegator());
 		// start consumer
 		topologyBuilder.start();
 	}
@@ -283,27 +266,25 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		}
 	}
 
-	@Override
-	public String startInstance(String domainName, String subDomainName) {
+    @Override
+	public String startInstance(String clusterId, LocationScope locationScope) {
 
 		ComputeService computeService;
 		Template template;
-		String ip = "";
+		String ip;
+        String cloud = locationScope.getCloud();
+        String region = locationScope.getRegion();
 		final Lock lock = new ReentrantLock();
 
-		// check for sub domain
-		subDomainName = checkSubDomain(subDomainName);
 
-		log.info("Starting new instance of domain : " + domainName
-				+ " and sub domain : " + subDomainName);
+		log.info("Starting new instance of domain : " + clusterId);
 
 		// get the subjected ServiceContext
 		ServiceContext serviceCtxt = dataHolder
-				.getServiceContext(domainName, subDomainName);
+				.getServiceContextFromDomain(clusterId);
 
 		if (serviceCtxt == null) {
-			String msg = "Not a registered service: domain - " + domainName
-					+ ", sub domain - " + subDomainName;
+			String msg = "Not a registered service: domain - " + clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
@@ -315,7 +296,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 		if (serviceCtxt.getCartridge() == null) {
 			String msg = "There's no registered Cartridge found. Domain - "
-					+ domainName + ", sub domain - " + subDomainName;
+					+ clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
@@ -327,171 +308,173 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 			throw new CloudControllerException(msg);
 		}
 
-		// sort the IaasProviders according to scale up order
-		Collections.sort(serviceCtxt.getCartridge().getIaases(),
-				IaasProviderComparator.ascending(IaasProviderComparator
-						.getComparator(IaasProviderComparator.SCALE_UP_SORT)));
 
 		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
 
-			IaasContext ctxt = null;
-			if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
-				ctxt = serviceCtxt.addIaasContext(iaas.getType());
-			}
-
-			if (iaas.getMaxInstanceLimit() > dataHolder.getActiveInstanceCount(iaas.getType())) {
-				try {
-
-					iaas.getIaas().setDynamicPayload(iaas);
-
-					// get the ComputeService
-					computeService = iaas.getComputeService();
-
-					// corresponding Template
-					template = iaas.getTemplate();
-
-					if (template == null) {
-						String msg = "Failed to start an instance in "
-								+ iaas.getType()
-								+ ". Reason : Template is null. You have not specify a matching service "
-								+ "element in the configuration file of Autoscaler.\n Hence, will try to "
-								+ "start in another IaaS if available.";
-						log.error(msg);
-						continue;
-					}
-
-					// set instance name as the host name
-					// template.getOptions().userMetadata("Name",
-					// serviceCtxt.getHostName());
-					// template.getOptions().as(TemplateOptions.class).userMetadata("Name",
-					// serviceCtxt.getHostName());
-
-					// generate the group id from domain name and sub domain
-					// name.
-					// Should have lower-case ASCII letters, numbers, or dashes.
-					// Should have a length between 3-15
-					String str = domainName.concat("-" + subDomainName)
-							.substring(0, 10);
-					String group = str.replaceAll("[^a-z0-9-]", "");
-
-					NodeMetadata node;
-
-					// create and start a node
-					Set<? extends NodeMetadata> nodes = computeService
-							.createNodesInGroup(group, 1, template);
-
-					node = nodes.iterator().next();
-
-					String autoAssignIpProp = iaas
-							.getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
-
-					// acquire the lock
-					lock.lock();
-
-					try {
-						// reset ip
-						ip = "";
-						// default behavior is autoIpAssign=false
-						if (autoAssignIpProp == null
-								|| (autoAssignIpProp != null && autoAssignIpProp
-										.equals("false"))) {
-							// allocate an IP address - manual IP assigning mode
-							ip = iaas.getIaas().associateAddress(iaas, node);
-						}
-
-						if (ip.isEmpty()
-								&& node.getPublicAddresses() != null
-								&& node.getPublicAddresses().iterator()
-										.hasNext()) {
-							ip = node.getPublicAddresses().iterator().next();
-						}
-
-						// if not public IP is assigned, we're using private IP
-						if (ip.isEmpty()
-								&& node.getPrivateAddresses() != null
-								&& node.getPrivateAddresses().iterator()
-										.hasNext()) {
-							ip = node.getPrivateAddresses().iterator().next();
-						}
-
-						if (node.getId() == null) {
-							String msg = "Node id of the starting instance is null.\n"
-									+ node.toString();
-							log.fatal(msg);
-							throw new CloudControllerException(msg);
-						}
-
-						// add node ID
-						ctxt.addNodeId(node.getId());
-						ctxt.addNodeToPublicIp(node.getId(), ip);
-
-						// to faster look up
-						dataHolder.addNodeId(
-								node.getId(), serviceCtxt);
-
-						serviceCtxt.getCartridge().setLastlyUsedIaas(iaas);
-
-						// add this ip to the topology
-						appendToPublicIpProperty(ip, serviceCtxt);
-
-						dataHolder.updateActiveInstanceCount(iaas.getType(), 1);
-
-						// persist in registry
-						persist();
-
-						// trigger topology consumers
-						List<ServiceContext> list = new ArrayList<ServiceContext>();
-						list.add(serviceCtxt);
-						try {
-							dataHolder.getSharedTopologyDiffQueue().put(list);
-
-							// publish data
-							CartridgeInstanceDataPublisherTask.publish();
-						} catch (InterruptedException ignore) {
-						}
-
-						if (log.isDebugEnabled()) {
-							log.debug("Node details: \n" + node.toString()
-									+ "\n***************\n");
-						}
-
-						log.info("Instance is successfully starting up in IaaS "
-								+ iaas.getType()
-								+ ".\tIP Address(public/private): "
-								+ ip
-								+ "\tNode Id: " + node.getId());
-
-						return ip;
-
-					} finally {
-						// release the lock
-						lock.unlock();
-					}
-
-				} catch (Exception e) {
-					log.warn(
-							"Failed to start an instance in "
-									+ iaas.getType()
-									+ ". Hence, will try to start in another IaaS if available.",
-							e);
-					continue;
-				}
-			} else {
-				log.warn("Max instance limit is reached in the IaaS "
-						+ iaas.getType() + " : Max instance limit: "
-						+ iaas.getMaxInstanceLimit());
-			}
-
-		}
-
-		log.error("Failed to start an instance, in any available IaaS: "
-				+ domainName + " and sub domain : " + subDomainName);
-
-		return null;
+            if(cloud == null) {
+                String msg = "There's no IaaS provided for the cluster: "
+					+ clusterId + " to start an instance";
+                log.fatal(msg);
+                throw new CloudControllerException(msg);
+            }
+
+            if(region == null) {
+                log.info("Region is not provided. Hence the default region is taken into the spawning a new instance");
+            }
+            //checking for the cloud and the region
+            //TODO adding more locations and retrieve it from the request received
+            if(iaas.getName().equals(cloud) && (region == null || iaas.getRegion().equals(region))) {
+                IaasContext ctxt;
+                if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
+                    ctxt = serviceCtxt.addIaasContext(iaas.getType());
+                }
+                try {
+                    //generating the Unique member ID...
+                    String memberID = generateMemberId(clusterId);
+                    //have to add memberID to the payload
+                    iaas.getIaas().setDynamicPayload(iaas);
+
+                    // get the ComputeService
+                    computeService = iaas.getComputeService();
+
+                    // corresponding Template
+                    template = iaas.getTemplate();
+
+                    if (template == null) {
+                        String msg = "Failed to start an instance in "
+                                + iaas.getType()
+                                + ". Reason : Template is null. You have not specify a matching service "
+                                + "element in the configuration file of Autoscaler.\n Hence, will try to "
+                                + "start in another IaaS if available.";
+                        log.error(msg);
+                        continue;
+                    }
+
+                    // set instance name as the host name
+                    // template.getOptions().userMetadata("Name",
+                    // serviceCtxt.getHostName());
+                    // template.getOptions().as(TemplateOptions.class).userMetadata("Name",
+                    // serviceCtxt.getHostName());
+
+                    // generate the group id from domain name and sub domain
+                    // name.
+                    // Should have lower-case ASCII letters, numbers, or dashes.
+                    // Should have a length between 3-15
+                    String str = clusterId.substring(0, 10);
+                    String group = str.replaceAll("[^a-z0-9-]", "");
+
+                    NodeMetadata node;
+
+                    // create and start a node
+                    Set<? extends NodeMetadata> nodes = computeService
+                            .createNodesInGroup(group, 1, template);
+
+                    node = nodes.iterator().next();
+
+                    String autoAssignIpProp = iaas
+                            .getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
+
+                    // acquire the lock
+                    lock.lock();
+
+                    try {
+                        // reset ip
+                        ip = "";
+                        // default behavior is autoIpAssign=false
+                        if (autoAssignIpProp == null
+                                || (autoAssignIpProp != null && autoAssignIpProp
+                                        .equals("false"))) {
+                            // allocate an IP address - manual IP assigning mode
+                            ip = iaas.getIaas().associateAddress(iaas, node);
+                        }
+
+                        if (ip.isEmpty()
+                                && node.getPublicAddresses() != null
+                                && node.getPublicAddresses().iterator()
+                                        .hasNext()) {
+                            ip = node.getPublicAddresses().iterator().next();
+                        }
+
+                        // if not public IP is assigned, we're using private IP
+                        if (ip.isEmpty()
+                                && node.getPrivateAddresses() != null
+                                && node.getPrivateAddresses().iterator()
+                                        .hasNext()) {
+                            ip = node.getPrivateAddresses().iterator().next();
+                        }
+
+                        if (node.getId() == null) {
+                            String msg = "Node id of the starting instance is null.\n"
+                                    + node.toString();
+                            log.fatal(msg);
+                            throw new CloudControllerException(msg);
+                        }
+
+                        // add node ID
+                        ctxt.addNodeId(node.getId());
+                        ctxt.addNodeToPublicIp(node.getId(), ip);
+
+                        // to faster look up
+                        dataHolder.addNodeId(
+                                node.getId(), serviceCtxt);
+
+                        serviceCtxt.getCartridge().setLastlyUsedIaas(iaas);
+
+                        // add this ip to the topology
+                        appendToPublicIpProperty(ip, serviceCtxt);
+
+                        dataHolder.updateActiveInstanceCount(iaas.getType(), 1);
+
+                        // persist in registry
+                        persist();
+
+                        // trigger topology
+                        TopologyBuilder.handleMemberSpawned(memberID, serviceCtxt.getCartridgeType(), clusterId,
+                                 node.getId(), locationScope);
+
+                        //update the topology with the newly spawned member
+                        // publish data
+                        CartridgeInstanceDataPublisherTask.publish();
+                        if (log.isDebugEnabled()) {
+                            log.debug("Node details: \n" + node.toString()
+                                    + "\n***************\n");
+                        }
+
+                        log.info("Instance is successfully starting up in IaaS "
+                                + iaas.getType()
+                                + ".\tIP Address(public/private): "
+                                + ip
+                                + "\tNode Id: " + node.getId());
+
+                        return ip;
+
+                    } finally {
+                        // release the lock
+                        lock.unlock();
+                    }
+
+                    } catch (Exception e) {
+                        log.warn(
+                                "Failed to start an instance in "
+                                        + iaas.getType()
+                                        + ". Hence, will try to start in another IaaS if available.",
+                                e);
+                    }
+            }
+            else {
+                if(region != null) {
+                   log.error("Failed to start an instance, in any IaaS: " + cloud +
+                           " of the region: " + region +  "for the cluster: "
+				            + clusterId);
+                }
+            }
+        }
+        return null;
 
 	}
 
-	/**
+
+    /**
 	 * Appends this ip to the Service Context's
 	 * {@link CloudControllerConstants#PUBLIC_IP_PROPERTY}
 	 * 
@@ -525,6 +508,11 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		}
 	}
 
+    private String generateMemberId(String clusterId) {
+        UUID memberId = UUID.randomUUID();
+         return clusterId + memberId.toString();
+    }
+
 	private Cartridge loadCartridge(String cartridgeType, byte[] payload,
 			List<Cartridge> cartridges) {
 
@@ -541,19 +529,17 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 	}
 
 	@Override
-	public boolean terminateInstance(String domainName, String subDomainName) {
-
-		subDomainName = checkSubDomain(subDomainName);
+	public boolean terminateInstance(String clusterId, LocationScope locationScope) {
 
-		log.info("Starting to terminate an instance of domain : " + domainName
-				+ " and sub domain : " + subDomainName);
+         String cloud = locationScope.getCloud();
+        String region = locationScope.getRegion();
+		log.info("Starting to terminate an instance of domain : " + clusterId);
 
 		ServiceContext serviceCtxt = dataHolder
-				.getServiceContext(domainName, subDomainName);
+				.getServiceContextFromDomain(clusterId);
 
 		if (serviceCtxt == null) {
-			String msg = "Not a registered service: domain - " + domainName
-					+ ", sub domain - " + subDomainName;
+			String msg = "Not a registered service: domain - " + clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
@@ -568,58 +554,55 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		// if still, Cartridge is null
 		if (serviceCtxt.getCartridge() == null) {
 			String msg = "There's no registered Cartridge found. Domain - "
-					+ domainName + ", sub domain - " + subDomainName;
+					+ clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
 
-		// sort the IaasProviders according to scale down order
-		Collections
-				.sort(serviceCtxt.getCartridge().getIaases(),
-						IaasProviderComparator.ascending(IaasProviderComparator
-								.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
-
-		// traverse in scale down order
-		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+        for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
 
 			String msg = "Failed to terminate an instance in "
 					+ iaas.getType()
 					+ ". Hence, will try to terminate an instance in another IaaS if possible.";
+            //TODO adding more locations and retrieve it from the request received
+            if(iaas.getName().equals(cloud) && (region == null || iaas.getRegion().equals(region))) {
+                String nodeId = null;
 
-			String nodeId = null;
+                IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
 
-			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
+                // terminate the last instance first
+                for (String id : Lists.reverse(ctxt.getNodeIds())) {
+                    if (id != null) {
+                        nodeId = id;
+                        break;
+                    }
+                }
 
-			// terminate the last instance first
-			for (String id : Lists.reverse(ctxt.getNodeIds())) {
-				if (id != null) {
-					nodeId = id;
-					break;
-				}
-			}
+                // if no matching node id can be found.
+                if (nodeId == null) {
 
-			// if no matching node id can be found.
-			if (nodeId == null) {
+                    log.warn(msg
+                            + " : Reason- No matching instance found for domain: "
+                            + clusterId
+                            + ".");
+                    continue;
+                }
 
-				log.warn(msg
-						+ " : Reason- No matching instance found for domain: "
-						+ domainName + " and sub domain: " + subDomainName
-						+ ".");
-				continue;
-			}
+                // terminate it!
+                terminate(iaas, ctxt, nodeId);
+
+                // log information
+                logTermination(nodeId, ctxt, serviceCtxt);
+            }
 
-			// terminate it!
-			terminate(iaas, ctxt, nodeId);
 
-			// log information
-			logTermination(nodeId, ctxt, serviceCtxt);
 
 			return true;
 
 		}
 
 		log.info("Termination of an instance which is belong to domain '"
-				+ domainName + "' and sub domain '" + subDomainName
+				+ clusterId
 				+ "' , failed! Reason: No matching "
 				+ "running instance found in any available IaaS.");
 
@@ -627,21 +610,22 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 	}
 
-	@Override
-	public boolean terminateLastlySpawnedInstance(String domainName,
-			String subDomainName) {
+    @Override
+    public boolean terminateInstance(String instanceId) {
+        //TODO
+        return false;
+    }
 
-		subDomainName = checkSubDomain(subDomainName);
-
-		log.info("Starting to terminate the last instance spawned, of domain : "
-				+ domainName + " and sub domain : " + subDomainName);
+    @Override
+	public boolean terminateLastlySpawnedInstance(String clusterId) {
+        log.info("Starting to terminate the last instance spawned, of domain : "
+				+ clusterId);
 
 		ServiceContext serviceCtxt = dataHolder
-				.getServiceContext(domainName, subDomainName);
+				.getServiceContextFromDomain(clusterId);
 
 		if (serviceCtxt == null) {
-			String msg = "Not a registered service: domain - " + domainName
-					+ ", sub domain - " + subDomainName;
+			String msg = "Not a registered service: domain - " + clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
@@ -655,7 +639,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 		if (serviceCtxt.getCartridge() == null) {
 			String msg = "There's no registered Cartridge found. Domain - "
-					+ domainName + ", sub domain - " + subDomainName;
+					+ clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
@@ -671,7 +655,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 			String nodeId = null;
 			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
 
-			int i = 0;
+			int i;
 			for (i = ctxt.getNodeIds().size() - 1; i >= 0; i--) {
 				String id = ctxt.getNodeIds().get(i);
 				if (id != null) {
@@ -694,8 +678,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		}
 
 		log.info("Termination of an instance which is belong to domain '"
-				+ domainName + "' and sub domain '" + subDomainName
-				+ "' , failed! Reason: No matching "
+				+ clusterId + ", failed! Reason: No matching "
 				+ "running instance found in lastly used IaaS.");
 
 		return false;
@@ -703,21 +686,19 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 	}
 
 	@Override
-	public boolean terminateAllInstances(String domainName, String subDomainName) {
+	public boolean terminateAllInstances(String clusterId) {
 
 		boolean isAtLeastOneTerminated = false;
 
-		subDomainName = checkSubDomain(subDomainName);
 
 		log.info("Starting to terminate all instances of domain : "
-				+ domainName + " and sub domain : " + subDomainName);
+				+ clusterId);
 
 		ServiceContext serviceCtxt = dataHolder
-				.getServiceContext(domainName, subDomainName);
+				.getServiceContextFromDomain(clusterId);
 
 		if (serviceCtxt == null) {
-			String msg = "Not a registered service: domain - " + domainName
-					+ ", sub domain - " + subDomainName;
+			String msg = "Not a registered service: domain - " + clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
@@ -731,19 +712,12 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 		if (serviceCtxt.getCartridge() == null) {
 			String msg = "There's no registered Cartridge found. Domain - "
-					+ domainName + ", sub domain - " + subDomainName;
+					+ clusterId;
 			log.fatal(msg);
 			throw new CloudControllerException(msg);
 		}
 
-		// sort the IaasProviders according to scale down order
-		Collections
-				.sort(serviceCtxt.getCartridge().getIaases(),
-						IaasProviderComparator.ascending(IaasProviderComparator
-								.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
-
-		// traverse in scale down order
-		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+        for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
 
 			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
 
@@ -772,22 +746,18 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		}
 
 		log.info("Termination of an instance which is belong to domain '"
-				+ domainName + "' and sub domain '" + subDomainName
-				+ "' , failed! Reason: No matching "
+				+ clusterId + "', failed! Reason: No matching "
 				+ "running instance found in lastly used IaaS.");
 
 		return false;
 
 	}
 
-	public int getPendingInstanceCount(String domainName, String subDomainName) {
-
-		subDomainName = checkSubDomain(subDomainName);
-
-		int pendingInstanceCount = 0;
+	public int getPendingInstanceCount(String clusterId) {
+        int pendingInstanceCount = 0;
 
 		ServiceContext subjectedSerCtxt = dataHolder
-				.getServiceContext(domainName, subDomainName);
+				.getServiceContextFromDomain(clusterId);
 
 		if (subjectedSerCtxt != null
 				&& subjectedSerCtxt.getCartridgeType() != null) {
@@ -808,7 +778,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 				ComputeService computeService = iaas.getComputeService();
 
-				IaasContext ctxt = null;
+				IaasContext ctxt;
 				if ((ctxt = subjectedSerCtxt.getIaasContext(iaas.getType())) == null) {
 					ctxt = subjectedSerCtxt.addIaasContext(iaas.getType());
 				}
@@ -819,39 +789,35 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 				if (nodeIds.isEmpty()) {
 					log.debug("Zero nodes spawned in the IaaS "
-							+ iaas.getType() + " of domain: " + domainName
-							+ " and sub domain: " + subDomainName);
+							+ iaas.getType() + " of domain: " + clusterId);
 					continue;
 				}
 
 				// get all the nodes spawned by this IaasContext
 				Set<? extends ComputeMetadata> set = computeService.listNodes();
 
-				Iterator<? extends ComputeMetadata> iterator = set.iterator();
+                // traverse through all nodes of this ComputeService object
+                for (ComputeMetadata aSet : set) {
+                    NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) aSet;
 
-				// traverse through all nodes of this ComputeService object
-				while (iterator.hasNext()) {
-					NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator
-							.next();
+                    // if this node belongs to the requested domain
+                    if (nodeIds.contains(nodeMetadata.getId())) {
 
-					// if this node belongs to the requested domain
-					if (nodeIds.contains(nodeMetadata.getId())) {
+                        // get the status of the node
+                        Status nodeStatus = nodeMetadata.getStatus();
 
-						// get the status of the node
-						Status nodeStatus = nodeMetadata.getStatus();
-
-						// count nodes that are in pending state
-						if (nodeStatus.equals(Status.PENDING)) {
-							pendingInstanceCount++;
-						}
-					}
+                        // count nodes that are in pending state
+                        if (nodeStatus.equals(Status.PENDING)) {
+                            pendingInstanceCount++;
+                        }
+                    }
 
-				}
+                }
 			}
 		}
 
-		log.debug("Pending instance count of domain '" + domainName
-				+ "' and sub domain '" + subDomainName + "' is "
+		log.debug("Pending instance count of domain '" + clusterId
+				+ " is "
 				+ pendingInstanceCount);
 
 		return pendingInstanceCount;
@@ -860,7 +826,11 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 	/**
 	 * A helper method to terminate an instance.
-	 */
+     * @param iaasTemp
+     * @param ctxt
+     * @param nodeId
+     * @return will return the IaaSProvider
+     */
 	private IaasProvider terminate(IaasProvider iaasTemp, IaasContext ctxt,
 			String nodeId) {
 
@@ -879,7 +849,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 		// release allocated IP address
 		if (autoAssignIpProp == null
-				|| (autoAssignIpProp != null && autoAssignIpProp
+				|| (autoAssignIpProp
 						.equals("false"))) {
 			// allocate an IP address - manual IP assigning mode
 			iaasTemp.getIaas().releaseAddress(iaasTemp,
@@ -916,6 +886,8 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		// add this ip to the topology
 		serviceCtxt.setProperty(ipProp, newIpStr.length() == 0 ? "" : newIpStr
 				.substring(0, newIpStr.length() - 1).toString());
+        //updating the topology
+        TopologyBuilder.handleMemberTerminated(serviceCtxt.getCartridgeType(), serviceCtxt.getClusterId(), nodeId);
 
 		// remove the reference
 		ctxt.removeNodeIdToPublicIp(nodeId);
@@ -923,13 +895,8 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		// persist
 		persist();
 
-		// trigger topology consumers
-		List<ServiceContext> list = new ArrayList<ServiceContext>();
-		list.add(serviceCtxt);
-		try {
-			dataHolder.getSharedTopologyDiffQueue().put(list);
-		} catch (InterruptedException ignore) {
-		}
+		//handle the termination event
+
 
 	}
 
@@ -976,17 +943,18 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 	}
 
 	@Override
-	public boolean registerService(String domain, String subDomain,
+	public boolean registerService(String clusterId,
 			String tenantRange, String cartridgeType, String hostName,
-			Properties properties, byte[] payload)
+			Properties properties, byte[] payload, String autoScalerPolicyName)
 			throws UnregisteredCartridgeException {
 
 		// create a ServiceContext dynamically
 		ServiceContext newServiceCtxt = new ServiceContext();
-		newServiceCtxt.setDomainName(domain);
-		newServiceCtxt.setSubDomainName(subDomain);
+		newServiceCtxt.setClusterId(clusterId);
+		//newServiceCtxt.setSubDomainName(subDomain);
 		newServiceCtxt.setTenantRange(tenantRange);
 		newServiceCtxt.setHostName(hostName);
+        newServiceCtxt.setAutoScalerPolicyName(autoScalerPolicyName);
 
 		if (properties != null && properties.getProperties() != null) {
 			// add properties
@@ -1019,7 +987,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 
 			// write payload file
 			try {
-				String uniqueName = domain + "-" + subDomain + ".txt";
+				String uniqueName = clusterId + ".txt";
 				FileUtils.forceMkdir(new File(
 						CloudControllerConstants.PAYLOAD_DIR));
 				File payloadFile = new File(
@@ -1028,40 +996,29 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 				newServiceCtxt.setPayloadFile(payloadFile.getPath());
 
 			} catch (IOException e) {
-				String msg = "Failed while persisting the payload of domain : "
-						+ domain + ", sub domain : " + subDomain;
+				String msg = "Failed while persisting the payload of clusterId : "
+						+ clusterId;
 				log.error(msg, e);
 				throw new CloudControllerException(msg, e);
 			}
 
 		} else {
 			log.debug("Payload is null or empty for :\n "
-					+ newServiceCtxt.toNode().toString());
+					+ newServiceCtxt);
 		}
 
 		// persist
-		try {
-			String uniqueName = domain + "-" + subDomain + "-"
-					+ UUID.randomUUID() + ".xml";
-			FileUtils.writeStringToFile(new File(
-					CloudControllerConstants.SERVICES_DIR + uniqueName),
-					newServiceCtxt.toXml());
-		} catch (IOException e) {
-			String msg = "Failed while persisting the service configuration - domain : "
-					+ domain
-					+ ", sub domain : "
-					+ subDomain
-					+ ", tenant range: "
-					+ tenantRange
-					+ ", cartridge type: "
-					+ cartridgeType;
-			log.error(msg, e);
-			throw new CloudControllerException(msg, e);
-		}
-
-		log.info("Service successfully registered! Domain - " + domain
-				+ ", Sub domain - " + newServiceCtxt.getSubDomainName()
-				+ ", Cartridge type - " + cartridgeType);
+        String uniqueName = clusterId + "-"
+                + UUID.randomUUID() + ".xml";
+        try {
+            FileUtils.writeStringToFile(new File(CloudControllerConstants.SERVICES_DIR + uniqueName),
+                                            newServiceCtxt.toXml());
+        } catch (IOException e) {
+            //TODO
+        }
+
+        log.info("Service successfully registered! Domain - " + clusterId
+                + ", Cartridge type - " + cartridgeType);
 
 		return true;
 	}
@@ -1087,7 +1044,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		return cartridgeTypes;
 	}
 
-	private String checkSubDomain(String subDomainName) {
+	/*private String checkSubDomain(String subDomainName) {
 		// if sub domain is null, we assume it as default one.
 		if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
 			subDomainName = Constants.DEFAULT_SUB_DOMAIN;
@@ -1096,7 +1053,7 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		}
 
 		return subDomainName;
-	}
+	}*/
 
 	@Override
 	public CartridgeInfo getCartridgeInfo(String cartridgeType)
@@ -1116,20 +1073,19 @@ public class CloudControllerServiceImpl implements CloudControllerService {
 		throw new UnregisteredCartridgeException(msg);
 	}
 
-	@Override
-	public boolean unregisterService(String domain, String subDomain)
+    @Override
+	public boolean unregisterService(String clusterId)
 			throws UnregisteredServiceException {
 
-		subDomain = checkSubDomain(subDomain);
+		//subDomain = checkSubDomain(subDomain);
 
 		// find the service context
 		ServiceContext subjectedSerCtxt = dataHolder
-				.getServiceContext(domain, subDomain);
+				.getServiceContextFromDomain(clusterId);
 
 		if (subjectedSerCtxt == null) {
 			throw new UnregisteredServiceException(
-					"No registered service found for domain: " + domain
-							+ " - sub domain: " + subDomain);
+					"No registered service found for domain: " + clusterId);
 		}
 
 		// get the service definition file.

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java
index d444644..4f35100 100644
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/interfaces/CloudControllerService.java
@@ -18,11 +18,11 @@
  */
 package org.apache.stratos.cloud.controller.interfaces;
 
+import org.apache.stratos.cloud.controller.exception.UnregisteredCartridgeException;
 import org.apache.stratos.cloud.controller.exception.UnregisteredServiceException;
 import org.apache.stratos.cloud.controller.util.CartridgeInfo;
+import org.apache.stratos.cloud.controller.util.LocationScope;
 import org.apache.stratos.cloud.controller.util.Properties;
-import org.apache.stratos.lb.common.conf.util.Constants;
-import org.apache.stratos.cloud.controller.exception.UnregisteredCartridgeException;
 
 /**
  * This Interface provides a way to communicate with underline
@@ -38,11 +38,9 @@ public interface CloudControllerService {
      * present service cluster, if there is any. A service cluster is uniquely identified by its
      * domain and sub domain combination.
      * </p>
-     * @param domain
+     * @param clusterId
      *            service cluster domain
-     * @param subDomain
-     *            service cluster sub domain
-     * @param tenantRange 
+     * @param tenantRange
      * 			  tenant range eg: '1-10' or '2'
      * @param cartridgeType
      *            cartridge type of the new service. This should be an already registered cartridge
@@ -60,76 +58,75 @@ public interface CloudControllerService {
      *             when the cartridge type requested by this service is
      *             not a registered one.
      */
-    public boolean registerService(String domain, String subDomain, String tenantRange, String cartridgeType,
-        String hostName, Properties properties, byte[] payload) throws UnregisteredCartridgeException;
+    public boolean registerService(String clusterId, String tenantRange, String cartridgeType,
+        String hostName, Properties properties, byte[] payload, String autoScalerPolicyName) throws UnregisteredCartridgeException;
 
     /**
      * Calling this method will result in an instance startup, which is belong
-     * to the provided service domain. Also note that the instance that is starting up
-     * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
+     * to the provided Cluster ID. Also note that the instance that is starting up
+     * belongs to the group whose name is derived from its Cluster ID, replacing <i>.</i>
      * by a hyphen (<i>-</i>).
      * 
-     * @param domainName
-     *            service clustering domain of the instance to be started up.
-     * @param subDomainName
-     *            service clustering sub domain of the instance to be started up.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @param clusterId
+     *            cluster ID of the instance to be started up.
+     * @param locationScope
+     *            It contains the region, zone, network and host of a IaaS where
+     *            an instance need to be started.
      * @return public IP which is associated with the newly started instance.
      */
-    public String startInstance(String domainName, String subDomainName);
+    public String startInstance(String clusterId, LocationScope locationScope);
     
     /**
      * Calling this method will result in termination of an instance which is belong
-     * to the provided service domain and sub domain.
+     * to the provided cluster Id and the location scope..
      * 
-     * @param domainName
-     *            service domain of the instance to be terminated.
-     * @param sudDomainName
-     *            service clustering sub domain of the instance to be terminated.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @param clusterId
+     *            cluster ID of the instance to be terminated.
+     * @param locationScope
+     *            It contains the region, zone, network and host of a IaaS where
+     *            an instance need to be terminated..
+     * @return whether an instance terminated successfully or not.
+     */
+    public boolean terminateInstance(String clusterId, LocationScope locationScope);
+
+     /**
+     * Calling this method will result in termination of an instance which is belong
+     * to the provided instance Id.
+     *
+     * @param instanceId
+     *            instance Id of the instance to be terminated.
      * @return whether an instance terminated successfully or not.
      */
-    public boolean terminateInstance(String domainName, String subDomainName);
+    public boolean terminateInstance(String instanceId);
 
     /**
      * Calling this method will result in termination of all instances belong
-     * to the provided service domain and sub domain.
+     * to the provided cluster ID.
      * 
-     * @param domainName
-     *            service domain of the instance to be terminated.
-     * @param sudDomainName
-     *            service clustering sub domain of the instances to be terminated.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @param clusterId
+     *            cluster ID of the instance to be terminated.
      * @return whether an instance terminated successfully or not.
      */
-    public boolean terminateAllInstances(String domainName, String subDomainName);
+    public boolean terminateAllInstances(String clusterId);
 
     
     /**
      * Calling this method will result in termination of the lastly spawned instance which is
-     * belong to the provided service domain and sub domain.
+     * belong to the provided clusterID.
      * 
-     * @param domainName
+     * @param clusterId
      *            service domain of the instance to be terminated.
-     * @param sudDomainName
-     *            service clustering sub domain of the instance to be terminated.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
      * @return whether the termination is successful or not.
      */
-    public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
+    public boolean terminateLastlySpawnedInstance(String clusterId);
 
     /**
      * Unregister the service cluster which represents by this domain and sub domain.
-     * @param domain service cluster domain
-     * @param subDomain service cluster sub domain
+     * @param clusterId service cluster domain
      * @return whether the unregistration was successful or not.
      * @throws org.apache.stratos.cloud.controller.exception.UnregisteredServiceException if the service cluster requested is not a registered one.
      */
-    public boolean unregisterService(String domain, String subDomain) throws UnregisteredServiceException;
+    public boolean unregisterService(String clusterId) throws UnregisteredServiceException;
     
     /**
      * This method will return the information regarding the given cartridge, if present.
@@ -146,16 +143,12 @@ public interface CloudControllerService {
      * Calling this method will result in returning the pending instances
      * count of a particular domain.
      * 
-     * @param domainName
+     * @param clusterId
      *            service cluster domain
-     * @param sudDomainName
-     *            service clustering sub domain of the instance to be started up.
-     *            If this is null, the default value will be used. Default value is
-     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
      * @return number of pending instances for this domain. If no instances of this
      *         domain is present, this will return zero.
      */
-    public int getPendingInstanceCount(String domainName, String subDomainName);
+    public int getPendingInstanceCount(String clusterId);
 
     /**
      * Calling this method will result in returning the types of {@link org.apache.stratos.cloud.controller.util.Cartridge}s

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java
index 9fd1e64..45f3c0c 100644
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/internal/CloudControllerDSComponent.java
@@ -21,22 +21,23 @@ package org.apache.stratos.cloud.controller.internal;
 */
 
 
-import java.util.List;
-
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.cloud.controller.exception.CloudControllerException;
 import org.apache.stratos.cloud.controller.impl.CloudControllerServiceImpl;
 import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.ServiceReferenceHolder;
+import org.apache.stratos.messaging.broker.publish.EventPublisher;
+import org.apache.stratos.messaging.broker.publish.EventPublisher;
 import org.osgi.framework.BundleContext;
 import org.osgi.service.component.ComponentContext;
 import org.wso2.carbon.ntask.core.service.TaskService;
 import org.wso2.carbon.registry.core.exceptions.RegistryException;
 import org.wso2.carbon.registry.core.service.RegistryService;
-import org.apache.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
-import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
-import org.apache.stratos.cloud.controller.util.ServiceReferenceHolder;
-import org.apache.stratos.lb.common.mb.publish.TopicPublisher;
+
+import java.util.List;
 
 /**
  * Registering Cloud Controller Service.
@@ -70,7 +71,7 @@ public class CloudControllerDSComponent {
         	// initialize the topic publishers
         	for (String topic : topics) {
 				
-        		dataHolder.addTopicPublisher(new TopicPublisher(topic));
+        		dataHolder.addEventPublisher(new EventPublisher(topic), topic);
 			}
             
             BundleContext bundleContext = context.getBundleContext();
@@ -121,8 +122,8 @@ public class CloudControllerDSComponent {
 	
 	protected void deactivate(ComponentContext ctx) {
 
-		List<TopicPublisher> publishers = dataHolder.getAllTopicPublishers();
-		for (TopicPublisher topicPublisher : publishers) {
+		List<EventPublisher> publishers = dataHolder.getAllEventPublishers();
+		for (EventPublisher topicPublisher : publishers) {
 			topicPublisher.close();
 		}
 	}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/f94b4b51/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
index f82edae..7b27f9a 100644
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
@@ -18,26 +18,25 @@
  */
 package org.apache.stratos.cloud.controller.jcloud;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import com.google.common.collect.ImmutableSet;
+import com.google.inject.Module;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
+import org.apache.stratos.cloud.controller.exception.CloudControllerException;
+import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
+import org.apache.stratos.cloud.controller.util.IaasProvider;
 import org.jclouds.ContextBuilder;
 import org.jclouds.compute.ComputeServiceContext;
 import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
 import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
 import org.jclouds.sshj.config.SshjSshClientModule;
-import org.apache.stratos.cloud.controller.util.IaasProvider;
 
-import com.google.common.collect.ImmutableSet;
-import com.google.inject.Module;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Properties;
 
 /**
  * This class is responsible for creating a JClouds specific ComputeService object.
@@ -163,7 +162,7 @@ public class ComputeServiceBuilderUtil {
      */
     private static void handleException(String msg) {
         log.error(msg);
-        throw new SynapseException(msg);
+        throw new CloudControllerException(msg);
     }
 
     /**
@@ -176,8 +175,9 @@ public class ComputeServiceBuilderUtil {
      */
     private static void handleException(String msg, Exception e) {
         log.error(msg, e);
-        throw new SynapseException(msg, e);
+        throw new CloudControllerException(msg, e);
+
     }
     
     
-}
+}
\ No newline at end of file