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

[12/45] fixing component version issues and adding currently refactored components to the parent pom

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
new file mode 100644
index 0000000..5d26a2c
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
@@ -0,0 +1,73 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.common.replication;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.ClusteringMessage;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.Map;
+
+/**
+ * This is the notification message a primary load balancer will send to all other load balancers
+ * in the cluster, to replicate its state. When the other load balancers received this message, 
+ * they will set their states to the state of primary load balancer.
+ */
+public class RequestTokenReplicationCommand extends ClusteringMessage {
+
+    private static final long serialVersionUID = -7897961078018830555L;
+    private static final Log log = LogFactory.getLog(RequestTokenReplicationCommand.class);
+    private Map<String, Map<String, ?>> appDomainContexts;
+
+    public Map<String, Map<String, ?>> getAppDomainContexts() {
+        return appDomainContexts;
+    }
+
+    public void setAppDomainContexts(Map<String, Map<String, ?>> appDomainContexts) {
+        this.appDomainContexts = appDomainContexts;
+    }
+
+    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+        // set the appDomainContexts map
+        configurationContext.setNonReplicableProperty("autoscale.app.domain.contexts",
+                                          getAppDomainContexts());
+        
+        log.info("Request Tokens Replicated! ");
+    }
+
+    public String toString() {
+        return "Replication message sent!";
+    }
+
+    @Override
+    public ClusteringCommand getResponse() {
+        return new ClusteringCommand() {
+            
+            private static final long serialVersionUID = -8271265673996681347L;
+
+            @Override
+            public void execute(ConfigurationContext arg0) throws ClusteringFault {
+                // do nothing
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
new file mode 100644
index 0000000..5958ad9
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
@@ -0,0 +1,79 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.common.service;
+
+import org.apache.stratos.lb.common.conf.util.HostContext;
+
+import java.util.Map;
+
+/**
+ * This service provides a way to consume details in loadbalancer.conf file.
+ * Also to update the runtime object model of loadbalancer conf.
+ */
+public interface LoadBalancerConfigurationService {
+
+    /**
+     * Provides a reference to the runtime object model of loadbalancer.conf
+     * @return {@link Object} which is an instance of {@link org.apache.stratos.lb.common.conf.LoadBalancerConfiguration}
+     */
+    public Object getLoadBalancerConfig();
+    
+//    /**
+//     * Return a {@link Map} of {@link HostContext} objects, built using the given config.
+//     * @param config service configuration.
+//     * @return {@link Map} {@link Object}
+//     */
+//    public Object getHostContext(String config);
+    
+    /**
+     * Return a {@link Map} of {@link HostContext} objects, built using the given configuration.
+     * @param config service configuration diff. This can be in following format.
+     * 
+     * <p/>
+     * appserver {
+     * hosts                   appserver.cloud-test.wso2.com;
+     * domains   {
+     * 		wso2.as1.domain {
+     * 			tenant_range    1-100;
+     * 		}
+     *		wso2.as2.domain {
+     * 			tenant_range    101-200;
+     * 		}
+     * 		wso2.as3.domain {
+     *	 		tenant_range    *;
+     * 		}
+     * 	}
+     * } 
+     * <p/>
+     * esb {
+     * hosts                   esb.cloud-test.wso2.com;
+     * domains   {
+     * 		wso2.esb.domain {
+     *	 		tenant_range    *;
+     * 		}
+     * 	}
+     * }
+     * <p/>
+     * @return a {@link Map} of {@link HostContext} objects.
+     * key - host name
+     * Value - {@link HostContext}
+     */
+    public Object getHostContexts(String config) ;
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
new file mode 100644
index 0000000..99c2ced
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
@@ -0,0 +1,60 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.common.service.impl;
+
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+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.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+
+import java.util.Map;
+
+public class LoadBalancerConfigurationServiceImpl implements LoadBalancerConfigurationService {
+
+    @Override
+    public Object getLoadBalancerConfig() {
+        return LoadBalancerConfiguration.getInstance();
+    }
+
+	@Override
+    public Object getHostContexts(String config) {
+
+		// build a Node object for whole loadbalancer.conf
+        Node rootNode = new Node();
+        rootNode.setName(Constants.SERVICES_ELEMENT);
+        rootNode = NodeBuilder.buildNode(rootNode, config);
+		
+        Map<String, HostContext> oldMap = LoadBalancerConfiguration.getInstance().getHostContextMap();
+        LoadBalancerConfiguration.getInstance().createServicesConfig(rootNode);
+        
+//        MapDifference<String, HostContext> diff = Maps.difference(LoadBalancerConfiguration.getInstance().getHostContextMap(),
+//                                                             oldMap );
+//		
+//		return diff.entriesOnlyOnLeft();
+        return LoadBalancerConfiguration.getInstance().getHostContextMap();
+    }
+
+//	@Override
+//    public Object getHostContext(String config) {
+//	    return null;
+//    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
new file mode 100644
index 0000000..7355833
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
@@ -0,0 +1,40 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.common.util;
+
+/**
+ *
+ */
+public class DomainMapping {
+    private String mapping;
+    private String actualHost;
+
+    public DomainMapping(String mapping) {
+        this.mapping = mapping;
+    }
+
+    public String getActualHost() {
+        return actualHost;
+    }
+
+    public void setActualHost(String actualHost) {
+        this.actualHost = actualHost;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..6d1f398
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="LoadBalancerConfigurationService" scope="application">
+        <parameter name="ServiceClass">org.wso2.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpll</parameter>
+        <messageReceivers>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
+    </messageReceivers>
+    </service>
+</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
new file mode 100644
index 0000000..4efbbd2
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
@@ -0,0 +1,169 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.common.test;
+
+import java.io.File;
+
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+
+import junit.framework.TestCase;
+
+public class LoadBalancerConfigurationTest extends TestCase {
+    
+    private LoadBalancerConfiguration lbConfig ;
+    private LoadBalancerConfiguration lbConfig1;
+    
+    
+    @Override
+    protected void setUp() throws Exception {
+
+        LoadBalancerConfiguration.setInstance(null);
+        File f = new File("src/test/resources/loadbalancer.conf");
+        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
+        lbConfig = LoadBalancerConfiguration.getInstance();
+    }
+    
+    public final void testCreateLoadBalancerConfig() {
+
+        LoadBalancerConfiguration.LBConfiguration loadBalancerConfig =
+            lbConfig.getLoadBalancerConfig();
+        
+        assertEquals(1, loadBalancerConfig.getInstances());
+        assertEquals(5000, loadBalancerConfig.getAutoscalerTaskInterval());
+        assertEquals(15000, loadBalancerConfig.getServerStartupDelay());
+    }
+
+    public final void testCreateServicesConfig() {
+
+        /* Tests relavant to loadbalancer.conf file */
+        
+        ServiceConfiguration asServiceConfig =
+                                               lbConfig.getServiceConfig("wso2.as1.domain",
+                                                                         "worker");
+
+        assertEquals(1, asServiceConfig.getInstancesPerScaleUp());
+        assertEquals(5, asServiceConfig.getMaxAppInstances());
+        assertEquals(0, asServiceConfig.getMinAppInstances());
+        assertEquals(60000, asServiceConfig.getMessageExpiryTime());
+        assertEquals(400, asServiceConfig.getMaxRequestsPerSecond());
+        assertEquals(0.65, asServiceConfig.getAlarmingUpperRate());
+        assertEquals(10, asServiceConfig.getRoundsToAverage());
+        assertEquals("worker", asServiceConfig.getSubDomain());
+
+        asServiceConfig = lbConfig.getServiceConfig("wso2.as2.domain", "worker1");
+        assertEquals("worker1", asServiceConfig.getSubDomain());
+
+        asServiceConfig = lbConfig.getServiceConfig("wso2.esb.domain", "mgt");
+        assertEquals("mgt", asServiceConfig.getSubDomain());
+
+        assertEquals(2, lbConfig.getHostNamesTracker().keySet().size());
+        assertEquals(3, lbConfig.getHostNamesTracker().get("appserver").size());
+        assertEquals(2, lbConfig.getHostNamesTracker().get("esb").size());
+
+        for (HostContext ctx : lbConfig.getHostContextMap().values()) {
+
+            if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
+
+                assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
+                assertEquals(18, ctx.getTenantDomainContexts().size());
+            } else if (ctx.getHostName().equals("as2.cloud-test.wso2.com")) {
+                assertEquals("worker", ctx.getSubDomainFromTenantId(2));
+            } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
+                assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
+            }
+        }
+        
+        /* tests relevant to loadbalancer1.conf file */
+        
+        File f = new File("src/test/resources/loadbalancer2.conf");
+        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
+        
+        LoadBalancerConfiguration.setInstance(null);
+        lbConfig1 = LoadBalancerConfiguration.getInstance();
+        
+        for (HostContext ctx : lbConfig1.getHostContextMap().values()) {
+
+            if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
+
+                assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
+                assertEquals("wso2.as1.domain", ctx.getDomainFromTenantId(5));
+                assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(8));
+                assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(2));
+                assertEquals(4, ctx.getTenantDomainContexts().size());
+                
+            } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
+                
+                assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
+            }
+        }
+
+    }
+
+    public final void testGetServiceDomains() throws Exception {
+
+        setUp();
+        String[] serviceDomains = lbConfig.getServiceDomains();
+        assertEquals(4, serviceDomains.length);
+        
+        assertTrue("wso2.as1.domain".equals(serviceDomains[0]) ||
+            "wso2.as1.domain".equals(serviceDomains[1]) ||
+            "wso2.as1.domain".equals(serviceDomains[2]) ||
+            "wso2.as1.domain".equals(serviceDomains[3]));
+        
+        assertTrue("wso2.as2.domain".equals(serviceDomains[0]) ||
+            "wso2.as2.domain".equals(serviceDomains[1]) ||
+            "wso2.as2.domain".equals(serviceDomains[2]) ||
+            "wso2.as2.domain".equals(serviceDomains[3]));
+        
+        assertTrue("wso2.as3.domain".equals(serviceDomains[0]) ||
+            "wso2.as3.domain".equals(serviceDomains[1]) ||
+            "wso2.as3.domain".equals(serviceDomains[2]) ||
+            "wso2.as3.domain".equals(serviceDomains[3]));
+        
+        assertTrue("wso2.esb.domain".equals(serviceDomains[0]) ||
+                   "wso2.esb.domain".equals(serviceDomains[1]) ||
+                   "wso2.esb.domain".equals(serviceDomains[2]) ||
+                   "wso2.esb.domain".equals(serviceDomains[3]));
+        
+    }
+    
+    public final void testGetServiceSubDomains() throws Exception {
+
+        setUp();
+        String[] serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as3.domain");
+        assertEquals(2, serviceSubDomains.length);
+        
+        assertTrue("nirmal".equals(serviceSubDomains[0]) ||
+            "nirmal".equals(serviceSubDomains[1]));
+        
+        assertTrue("nirmal2".equals(serviceSubDomains[0]) ||
+            "nirmal2".equals(serviceSubDomains[1]));
+        
+        serviceSubDomains = lbConfig.getServiceSubDomains("wso2.esb.domain");
+        assertEquals(2, serviceSubDomains.length);
+        
+        serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as1.domain");
+        assertEquals(1, serviceSubDomains.length);
+        
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
new file mode 100644
index 0000000..e3b2f5e
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
@@ -0,0 +1,124 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.common.test;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+
+public class NodeBuilderTest extends TestCase {
+
+    String content;
+
+    public void setUp() throws Exception {
+    }
+
+    public final void testBuildNode() {
+
+        // Testing a node only has properties
+        Node a = new Node();
+        a.setName("loadbalancer");
+
+        content =
+            "securityGroups      stratos-appserver-lb;\ninstanceType        m1.large;\n"
+                + "instances           1;\nelasticIP           ${ELASTIC_IP};\n"
+                + "availabilityZone    us-east-1c;\npayload             /mnt/payload.zip;";
+
+        a = NodeBuilder.buildNode(a, content);
+
+        Assert.assertEquals("loadbalancer", a.getName());
+        Assert.assertEquals("stratos-appserver-lb", a.getProperty("securityGroups"));
+        Assert.assertEquals("${ELASTIC_IP}", a.getProperty("elasticIP"));
+        Assert.assertEquals("/mnt/payload.zip", a.getProperty("payload"));
+        Assert.assertNull(a.getProperty("payloader"));
+
+        // Testing a node has sub nodes and properties
+        a = new Node();
+        a.setName("appserver");
+
+        content =
+            "hosts                   appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n"
+                + "domains   {\n" + "wso2.as1.domain {\n" + "tenant_range    1-100;\n" + "}\n"
+                + "wso2.as2.domain {\n" + "tenant_range    101-200;\n" + "}\n"
+                + "wso2.as3.domain { # domain\n" + "tenant_range    *;\n" + "}\n" + "}\n"
+                + "# line comment \n"
+                + "payload                 resources/cluster_node.zip;# payload\n"
+                + "availability_zone       us-east-1c;\n";
+
+        a = NodeBuilder.buildNode(a, content);
+
+        Assert.assertEquals("appserver", a.getName());
+        Assert.assertEquals(1, a.getChildNodes().size());
+        Assert.assertEquals("domains", a.getChildNodes().get(0).getName());
+        Assert.assertEquals("appserver.cloud-test.wso2.com,as.cloud-test.wso2.com",
+                            a.getProperty("hosts"));
+        Assert.assertEquals("resources/cluster_node.zip", a.getProperty("payload"));
+        Assert.assertEquals(null, a.getProperty("payloader"));
+
+        Node b = a.getChildNodes().get(0);
+
+        Assert.assertEquals(3, b.getChildNodes().size());
+        Assert.assertEquals(null, b.getProperty("payload"));
+
+        Node c = b.getChildNodes().get(0);
+
+        Assert.assertEquals(0, c.getChildNodes().size());
+        Assert.assertEquals("1-100", c.getProperty("tenant_range"));
+
+        c = b.getChildNodes().get(2);
+
+        Assert.assertEquals(0, c.getChildNodes().size());
+        Assert.assertEquals("*", c.getProperty("tenant_range"));
+        
+        String nodeStr = "appserver {\n" +
+                "\thosts\tappserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n" +
+                "\tpayload\tresources/cluster_node.zip;\n" +
+        		"\tavailability_zone\tus-east-1c;\n" +
+        		"\tdomains {\n" +
+        		"\t\twso2.as1.domain {\n" +
+        		"\t\t\ttenant_range\t1-100;\n" +
+        		"\t\t}\n" +
+        		"\t\twso2.as2.domain {\n" +
+        		"\t\t\ttenant_range\t101-200;\n" +
+        		"\t\t}\n" +
+        		"\t\twso2.as3.domain {\n" +
+        		"\t\t\ttenant_range\t*;\n" +
+        		"\t\t}\n" +
+        		"\t}\n" +
+        		"}";
+        
+        assertEquals(nodeStr, a.toString());
+        
+        // test equals method
+        assertEquals(true, a.equals(a));
+        assertEquals(false, a.equals(b));
+        assertEquals(false, c.equals(b));
+        
+        // test buildNode(String)
+        c = NodeBuilder.buildNode(nodeStr);
+        
+        assertEquals(c.getName(), "appserver");
+        assertEquals(c.getChildNodes().size(), 1);
+        assertEquals(c.getProperty("availability_zone"), "us-east-1c");
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
new file mode 100644
index 0000000..b2fd44f
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
@@ -0,0 +1,64 @@
+loadbalancer {
+    instances	1;
+    enable_autoscaler	true;
+    # interval between two task executions in milliseconds
+    autoscaler_task_interval	5000;
+    # after an instance booted up, task will wait till this much of time and let the server started up
+    server_startup_delay		15000; #default will be 60000ms
+}
+
+services {
+    defaults {
+        min_app_instances 1;
+        max_app_instances       5;
+        max_requests_per_second   400;
+        alarming_upper_rate 0.65;
+        alarming_lower_rate 0.2;
+        scale_down_factor 0.25;
+        rounds_to_average       10;
+        instances_per_scale_up  1;
+        message_expiry_time     60000;
+    }
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            wso2.as1.domain {
+            	hosts as2.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      worker;
+                tenant_range    1-5;
+            }
+            wso2.as2.domain {
+                tenant_range    7;
+            }
+            wso2.as3.domain {
+                sub_domain nirmal;
+                tenant_range    10-20;
+            }
+            
+            wso2.as3.domain {
+                sub_domain nirmal2;
+                tenant_range    21-25;
+            }
+            
+            wso2.esb.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com,mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
new file mode 100644
index 0000000..8b87a32
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
@@ -0,0 +1,39 @@
+loadbalancer {
+    instances	1;
+    enable_autoscaler	true;
+    # interval between two task executions in milliseconds
+    autoscaler_task_interval	5000;
+    # after an instance booted up, task will wait till this much of time and let the server started up
+    server_startup_delay		15000; #default will be 60000ms
+}
+
+services {
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            
+            wso2.as.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+            wso2.as1.domain {
+            	sub_domain nirmal;
+                tenant_range    5-7;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
new file mode 100644
index 0000000..718d881
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
@@ -0,0 +1,30 @@
+services {
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            
+            wso2.as.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+            wso2.as1.domain {
+            	sub_domain nirmal;
+                tenant_range    5-7;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/testng.xml b/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
new file mode 100644
index 0000000..44b9822
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
+<suite name="Default suite">
+  <test verbose="2" name="Default test">
+    <classes>
+      <!--class name="org.wso2.carbon.lb.common.test.AgentPersistenceManagerTest">
+          <methods>
+            <include name="addZone" />
+              <include name="addHostMachine" />
+              <include name="deleteHostMachine" />
+          </methods>
+      </class-->
+    </classes>
+  </test>
+</suite>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/pom.xml b/components/org.apache.stratos.lb.endpoint/pom.xml
new file mode 100644
index 0000000..35da614
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/pom.xml
@@ -0,0 +1,114 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     ~  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.
+     ~
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.lb.endpoint</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Tenant Aware LoadBalance Endpoint</name>
+    <url>http://apache.org</url>
+    
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.mediation.initializer</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.mediation.dependency.mgt</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>${synapse.core.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.logging</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+	<dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+            <version>${axis2.wso2.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2</groupId>
+            <artifactId>axis2-kernel</artifactId>
+            <version>1.6.1-wso2v9</version>
+        </dependency>
+        <dependency>
+           <groupId>org.apache.stratos</groupId>
+           <artifactId>org.apache.stratos.cartridge.messages</artifactId>
+           <version>${apache.stratos.version}</version>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.apache.stratos.lb.endpoint.endpoint,
+                            org.apache.stratos.lb.endpoint,
+                            org.apache.stratos.lb.endpoint.util,
+                        </Export-Package>
+                        <Import-Package>
+                            !org.apache.stratos.lb.endpoint.endpoint,
+                            !org.apache.stratos.lb.endpoint,
+                            org.apache.stratos.lb.common.*; version=${project.version},
+                            org.apache.stratos.registry.core.service; version=1.0.1,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
new file mode 100644
index 0000000..60efed5
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
@@ -0,0 +1,31 @@
+/**
+ *  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.
+ */
+
+package org.apache.stratos.lb.endpoint;
+
+/**
+ * The <code>EndpointConstants</code> class defined the endpoint constants.
+ */
+public class EndpointConstants {
+
+    public static final String ADDRESS_ENDPOINT = "Address Endpoint";
+    public static final String WSDL_ENDPOINT = "WSDL Endpoint";
+    public static final String FAILOVER_ENDPOINT = "Failover Group";
+    public static final String LOADBALANCE_ENDPOINT = "Loadbalance Endpoint";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
new file mode 100644
index 0000000..e4274f5
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
@@ -0,0 +1,71 @@
+/**
+ *  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.
+ */
+
+package org.apache.stratos.lb.endpoint;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
+import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
+import org.wso2.carbon.mediation.initializer.persistence.MediationPersistenceManager;
+
+import java.util.Properties;
+
+/**
+ * Responsible for deploying Synapse artifacts.
+ */
+public class EndpointDeployer extends org.apache.synapse.deployers.EndpointDeployer {
+
+    MediationPersistenceManager mpm;
+
+    @Override
+    public void init(ConfigurationContext configCtx) {
+        super.init(configCtx);
+        this.mpm = ServiceBusUtils.getMediationPersistenceManager(configCtx.getAxisConfiguration());
+    }
+
+    @Override
+    public String deploySynapseArtifact(OMElement artifactConfig, String fileName,
+                                        Properties properties) {
+        String epName = super.deploySynapseArtifact(artifactConfig, fileName, properties);
+        mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+        return epName;
+    }
+
+    @Override
+    public String updateSynapseArtifact(OMElement artifactConfig, String fileName,
+                                        String existingArtifactName, Properties properties) {
+        String epName = super.updateSynapseArtifact(
+                artifactConfig, fileName, existingArtifactName, properties);
+        mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+        return epName;
+    }
+
+    @Override
+    public void undeploySynapseArtifact(String artifactName) {
+        super.undeploySynapseArtifact(artifactName);
+        mpm.deleteItemFromRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+    }
+
+    @Override
+    public void restoreSynapseArtifact(String artifactName) {
+        super.restoreSynapseArtifact(artifactName);
+        mpm.saveItemToRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
new file mode 100644
index 0000000..ac78fdd
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
@@ -0,0 +1,39 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.endpoint;
+
+/**
+ * Exception to be thrown from this component.
+ */
+public class TenantAwareLoadBalanceEndpointException extends RuntimeException {
+
+    private static final long serialVersionUID = -663839410798538370L;
+
+    public TenantAwareLoadBalanceEndpointException(String msg) {
+        super(msg);
+    }
+
+    public TenantAwareLoadBalanceEndpointException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+    public TenantAwareLoadBalanceEndpointException(Throwable cause) {
+        super(cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
new file mode 100644
index 0000000..07208cb
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
@@ -0,0 +1,208 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.endpoint;
+
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.LoadBalanceMembershipHandler;
+import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
+import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.wso2.carbon.user.api.UserStoreException;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Bridge between Axis2 membership notification and Synapse load balancing
+ */
+public class TenantLoadBalanceMembershipHandler implements LoadBalanceMembershipHandler {
+    private static final Log log = LogFactory.getLog(TenantLoadBalanceMembershipHandler.class);
+
+    private ConfigurationContext configCtx;
+
+    private LoadbalanceAlgorithm lbAlgo;
+    
+    /**
+     * Key - Host, Value - HostContext
+     */
+    private static Map<String, HostContext> hostContextsMap =
+            new HashMap<String, HostContext>();
+    
+    private ClusteringAgent clusteringAgent;
+    
+    private boolean isClusteringEnabled;
+    private String endpointName;
+
+    public TenantLoadBalanceMembershipHandler(Map<String, HostContext> hostContexts,
+                                              LoadbalanceAlgorithm algorithm,
+                                              ConfigurationContext configCtx,
+                                              boolean isClusteringEnabled,
+                                              String endpointName) {
+
+        lbAlgo = algorithm;
+        this.isClusteringEnabled = isClusteringEnabled;
+        this.endpointName = endpointName;
+        this.configCtx = configCtx;
+        
+        for (HostContext host : hostContexts.values()) {
+            
+            addHostContext(host);
+
+        }
+    }
+    
+    /**
+     * This will be used to add new {@link HostContext}s.
+     * @param host {@link HostContext}
+     */
+    public void addHostContext(HostContext host){
+        
+        String hostName = host.getHostName();
+
+        AlgorithmContext algorithmContext =
+                                            new AlgorithmContext(isClusteringEnabled,
+                                                                 configCtx, endpointName + "." +
+                                                                            hostName);
+
+        host.setAlgorithm(lbAlgo.clone());
+        host.setAlgorithmContext(algorithmContext);
+
+        hostContextsMap.put(hostName, host);
+        
+    }
+    
+    /**
+     * This will be used to remove an existing {@link HostContext}s.
+     * @param host {@link HostContext}
+     */
+    public void removeHostContext(String host){
+
+        hostContextsMap.remove(host);
+        
+    }
+
+    public void init(Properties props, LoadbalanceAlgorithm algorithm) {
+        // Nothing to do
+    }
+
+    public void setConfigurationContext(ConfigurationContext configCtx) {
+        this.configCtx = configCtx;
+
+        // The following code does the bridging between Axis2 and Synapse load balancing
+        clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
+        if (clusteringAgent == null) {
+            String msg = "In order to enable load balancing across an Axis2 cluster, " +
+                         "the cluster entry should be enabled in the axis2.xml file";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+    }
+
+    public ConfigurationContext getConfigurationContext() {
+        return configCtx;
+    }
+
+    /**
+     * Getting the next member to which the request has to be sent in a round-robin fashion
+     *
+     * @param context The AlgorithmContext
+     * @return The current member
+     * @deprecated Use {@link #getNextApplicationMember(String, int)}
+     */
+    public Member getNextApplicationMember(AlgorithmContext context) {
+        throw new UnsupportedOperationException("This operation is invalid. " +
+                                                "Call getNextApplicationMember(String host)");
+    }
+
+    public boolean isAValidHostName(String host){
+        if(getHostContext(host) != null){
+            return true;
+        }
+        return false;
+    }
+
+    public Member getNextApplicationMember(String host, int tenantId) {
+        HostContext hostContext = getHostContext(host);
+
+        if(hostContext == null){
+            String msg = "Invalid host name : " + host;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        // here we have to pass tenant id to get domain from hostContext
+        String domain = hostContext.getDomainFromTenantId(tenantId);
+        String subDomain = hostContext.getSubDomainFromTenantId(tenantId);
+
+        LoadbalanceAlgorithm algorithm = hostContext.getAlgorithm();
+        GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
+        
+        if (groupMgtAgent == null) {
+        	String tenantDomain;
+            try {
+	            tenantDomain = ConfigHolder.getInstance().getRealmService().getTenantManager().getDomain(tenantId);
+            } catch (UserStoreException ignore) {
+            	tenantDomain = ""+tenantId;
+            }
+        	
+            String msg =
+                    "No Group Management Agent found for the domain: " + domain + ", subDomain: "
+                    		+ subDomain + ", host: " + host+ " and for tenant: "
+                    		+  tenantDomain;
+            log.error(msg); 
+            throw new SynapseException(msg);
+        }
+        algorithm.setApplicationMembers(groupMgtAgent.getMembers());
+        AlgorithmContext context = hostContext.getAlgorithmContext();
+        return algorithm.getNextApplicationMember(context);
+    }
+
+    public HostContext getHostContext(String host) {
+        HostContext hostContext = hostContextsMap.get(host);
+        if (hostContext == null) {
+            int indexOfDot;
+            if ((indexOfDot = host.indexOf(".")) != -1) {
+                hostContext = getHostContext(host.substring(indexOfDot + 1));
+            } 
+        }
+        return hostContext;
+    }
+
+    public LoadbalanceAlgorithm getLoadbalanceAlgorithm() {
+        return lbAlgo;
+    }
+
+    public Properties getProperties() {
+        return null;
+    }
+    
+    public ClusteringAgent getClusteringAgent() {
+        return clusteringAgent;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
new file mode 100644
index 0000000..478790e
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
@@ -0,0 +1,159 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.endpoint.builder;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+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.HostContext;
+import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
+import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
+import org.apache.stratos.lb.endpoint.group.mgt.GroupMgtAgentBuilder;
+
+/**
+ * A Thread, which is responsible for making a sense out of a message received for
+ * ELB via topology synchronization.
+ */
+public class TopologySyncher implements Runnable {
+
+    private static final Log log = LogFactory.getLog(TopologySyncher.class);
+
+    /*
+     * This is a reference to sharedTopologyQueue ConfigHolder.
+     */
+    private BlockingQueue<String> sharedQueue;
+
+    public TopologySyncher(BlockingQueue<String> queue) {
+
+        sharedQueue = queue;
+
+    }
+
+    @Override
+    public void run() {
+        // grab the lb configuration instance
+        LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
+
+        // FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer
+        // conf
+        // in order to proper initialization of TribesClusteringAgent.
+        generateGroupMgtAgents(lbconfig);
+
+        // this thread should run for ever, untill terminated.
+        while (true) {
+            try {
+
+                // grabs a message or waits till the queue is non-empty
+                String message = sharedQueue.take();
+//                ConfigHolder data = ConfigHolder.getInstance();
+
+                // this message needs attention only if it's not same as the previous message and
+                // not null of course.
+//                if (data.getPreviousMsg() == null || !data.getPreviousMsg().equals(message)) {
+
+                    // reset the previous message
+//                    data.setPreviousMsg(message);
+
+                    // build the nginx format of this message, and get the Node object
+                    Node topologyNode = NodeBuilder.buildNode(message);
+
+                    // reset service configurations
+//                    lbconfig.resetData();
+                    // create new service configurations
+                    List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
+                    
+                    generateGroupMgtAgents(lbconfig);
+                    
+                    removeGroupMgtAgents(lbconfig, currentServiceConfigs);
+
+//                }
+
+            } catch (InterruptedException ignore) {
+            }
+        }
+
+    }
+
+    private void removeGroupMgtAgents(LoadBalancerConfiguration lbConfig, List<ServiceConfiguration> currentServiceConfigs) {
+
+        for (Iterator iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
+            Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
+            
+            for (Iterator iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
+                ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
+                
+                if(!currentServiceConfigs.contains(oldServiceConfig)){
+                    // if the ServiceConfiguration is not there any more in the latest topology
+                    lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                    GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                }
+            }
+        }
+    }
+
+    /**
+     * @param lbconfig
+     */
+    private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
+        TenantLoadBalanceMembershipHandler handler =
+            ConfigHolder.getInstance()
+                .getTenantLoadBalanceMembershipHandler();
+
+        if (handler == null) {
+            String msg =
+                "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        Map<String, HostContext> hostContexts = lbconfig.getHostContextMap();
+
+        // Add the Axis2 GroupManagement agents
+        if (hostContexts != null) {
+            // iterate through each host context
+            for (HostContext hostCtxt : hostContexts.values()) {
+                // each host can has multiple Tenant Contexts, iterate through them
+                for (TenantDomainContext tenantCtxt : hostCtxt
+                    .getTenantDomainContexts()) {
+
+                    String domain = tenantCtxt.getDomain();
+                    String subDomain = tenantCtxt.getSubDomain();
+
+                    // creates the group management agent
+                    GroupMgtAgentBuilder.createGroupMgtAgent(domain,
+                        subDomain);
+                }
+
+                // add to the handler
+                handler.addHostContext(hostCtxt);
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
new file mode 100644
index 0000000..a0e1022
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
@@ -0,0 +1,228 @@
+/**
+ *  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.
+ */
+package org.apache.stratos.lb.endpoint.cluster.manager;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.stratos.cartridge.messages.ClusterDomainManager;
+import org.apache.stratos.cartridge.messages.ClusterDomain;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
+import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
+
+/**
+ * Bridge between the ELB and the Stratos2 Agent.
+ */
+public class ClusterDomainManagerImpl implements ClusterDomainManager {
+
+    private static final Log log = LogFactory.getLog(ClusterDomainManagerImpl.class);
+
+    @Override
+    public void addClusterDomain(ClusterDomain cluster) {
+
+        // create group management agent, if one doesn't exist already.
+        HostContext hostCtxt = createGroupMgtAgentIfNotExists(cluster);
+
+        // we should only update if the above step is successful.
+        if (hostCtxt != null) {
+            // create / update Service Configuration
+            createOrUpdateServiceConfig(cluster, hostCtxt);
+        }
+        
+    }
+
+    @Override
+	public void removeClusterDomain(String domain, String subDomain, String hostName) {
+
+		TenantLoadBalanceMembershipHandler handler =
+		                                             ConfigHolder.getInstance()
+		                                                         .getTenantLoadBalanceMembershipHandler();
+
+		if (handler == null) {
+			String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+			log.error(msg);
+			throw new SynapseException(msg);
+		}
+
+		handler.removeHostContext(hostName);
+		
+		LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
+		
+		lbConfig.removeServiceConfiguration(domain, subDomain);
+		
+	}
+    
+    private void createOrUpdateServiceConfig(ClusterDomain cluster, HostContext ctxt) {
+        LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
+        
+        String domain = cluster.getDomain();
+        String subDomain = cluster.getSubDomain();
+        
+        if (subDomain == null || subDomain.isEmpty()) {
+            // uses default sub domain
+            subDomain = Constants.DEFAULT_SUB_DOMAIN;
+        }
+        
+        String hostName = cluster.getHostName();
+        String tenantRange = cluster.getTenantRange();
+        int minInstances = cluster.getMinInstances();
+        int maxInstances = cluster.getMaxInstances();
+        String service = cluster.getServiceName();
+        int maxRequestsPerSecond = cluster.getMaxRequestsPerSecond();
+    	int roundsToAverage = cluster.getRoundsToAverage(); 
+    	double alarmingUpperRate = cluster.getAlarmingUpperRate();
+    	double alarmingLowerRate = cluster.getAlarmingLowerRate();
+    	double scaleDownFactor = cluster.getScaleDownFactor();
+        
+        ServiceConfiguration serviceConfig ;
+        
+        if((serviceConfig = lbConfig.getServiceConfig(domain, subDomain)) == null){
+            serviceConfig = lbConfig.new ServiceConfiguration();
+        }
+        
+        // we simply override the attributes with new values
+        serviceConfig.setDomain(domain);
+        serviceConfig.setSub_domain(subDomain);
+        serviceConfig.setTenant_range(tenantRange);
+        serviceConfig.setHosts(hostName);
+        serviceConfig.setMin_app_instances(minInstances);
+        serviceConfig.setMax_app_instances(maxInstances);
+        serviceConfig.setMax_requests_per_second(maxRequestsPerSecond);
+        serviceConfig.setRounds_to_average(roundsToAverage);
+        serviceConfig.setAlarming_upper_rate(alarmingUpperRate);
+        serviceConfig.setAlarming_lower_rate(alarmingLowerRate);
+        serviceConfig.setScale_down_factor(scaleDownFactor);
+        
+        // add to host name tracker
+        lbConfig.addToHostNameTrackerMap(service, serviceConfig.getHosts());
+        
+        // add to host contexts
+        lbConfig.addToHostContextMap(hostName, ctxt);
+        
+        // finally add this service config
+        lbConfig.addServiceConfiguration(serviceConfig);
+    }
+
+    protected HostContext createGroupMgtAgentIfNotExists(ClusterDomain cluster) {
+        
+        String domain = cluster.getDomain();
+        String subDomain = cluster.getSubDomain();
+        String hostName = cluster.getHostName();
+        String tenantRange = cluster.getTenantRange();
+
+        // sub domain can be null, but others can't
+        if (domain == null || hostName == null || tenantRange == null) {
+            String msg =
+                         "Invalid value/s detected - domain: " + domain + "\n host name: " +
+                                 hostName + "\n tenant range: " + tenantRange;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        if (subDomain == null || subDomain.isEmpty()) {
+            // uses default sub domain
+            subDomain = Constants.DEFAULT_SUB_DOMAIN;
+        }
+
+        ClusteringAgent clusteringAgent = null;
+
+        try {
+            clusteringAgent =
+                              ConfigHolder.getInstance().getAxisConfiguration()
+                                          .getClusteringAgent();
+
+        } catch (Exception e) {
+            String msg = "Failed to retrieve Clustering Agent.";
+            log.error(msg, e);
+            throw new SynapseException(msg, e);
+
+        }
+
+        if (clusteringAgent == null) {
+            String msg = "Clustering Agent is null.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        /*
+         * Add Group Management Agent if one is not already present for this domain and sub
+         * domain
+         */
+
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
+                                                    domain, subDomain,-1);
+
+            if (log.isDebugEnabled()) {
+                log.debug("Group management agent added to cluster domain: " + domain +
+                          " and sub domain: " + subDomain);
+            }
+
+        } else {
+            if (log.isDebugEnabled()) {
+                log.debug("Group management agent is already available for cluster domain: " +
+                          domain + " and sub domain: " + subDomain);
+            }
+        }
+
+        TenantLoadBalanceMembershipHandler handler =
+                                                     ConfigHolder.getInstance()
+                                                                 .getTenantLoadBalanceMembershipHandler();
+
+        if (handler == null) {
+            String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        HostContext hostCtxt;
+
+        // if there's an already registered HostContext use it
+        if((hostCtxt = handler.getHostContext(hostName)) == null){
+            hostCtxt = new HostContext(hostName);
+        }
+        
+        List<TenantDomainContext> ctxts;
+        ctxts = new ArrayList<TenantDomainContext>(hostCtxt.getTenantDomainContexts());
+
+        // default value is super tenant mode - which is defined by tenant id 0, in this context
+        int tenantId = 0;
+        if(!"*".equals(tenantRange)){
+        	tenantId = Integer.parseInt(tenantRange);
+        }
+                
+        ctxts.add(new TenantDomainContext(tenantId, domain, subDomain));
+
+        hostCtxt.addTenantDomainContexts(ctxts);
+
+        handler.addHostContext(hostCtxt);
+
+        return hostCtxt;
+    }
+
+}