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/05 12:33:08 UTC

[31/34] committing refactoered adc components and top level pom in components

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
new file mode 100644
index 0000000..fc1569b
--- /dev/null
+++ b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
@@ -0,0 +1,84 @@
+/**
+ *  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.autoscaler.service.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+/**
+ * We keep details under a service element of jcoluds configuration file,
+ * in this object.
+ */
+public class ServiceTemplate implements Cloneable {
+
+    private String domainName;
+    private String subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    public String getDomainName() {
+        return domainName;
+    }
+    
+    public boolean setDomainName(String domainName) {
+        if (!"".equals(domainName)) {
+            this.domainName = domainName;
+            return true;
+        }
+        
+        return false;
+    }
+    
+    public void setProperty(String key, String value) {
+        properties.put(key, value);
+    }
+    
+    public String getProperty(String key) {
+        
+        if(properties.containsKey(key)){
+            return properties.get(key);
+        }
+        
+        return "";
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+    
+    public String getSubDomainName() {
+        return subDomainName;
+    }
+
+    public void setSubDomainName(String subDomainName) {
+        if(subDomainName == null || "".equals(subDomainName)){
+            return;
+        }
+        this.subDomainName = subDomainName;
+    }
+    
+    public Object clone() throws CloneNotSupportedException {
+        return super.clone();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
new file mode 100644
index 0000000..a40cf41
--- /dev/null
+++ b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
@@ -0,0 +1,557 @@
+/**
+ *  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.autoscaler.service.xml;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.apache.stratos.autoscaler.service.exception.MalformedConfigurationFileException;
+import org.apache.stratos.autoscaler.service.util.AutoscalerConstant;
+import org.apache.stratos.autoscaler.service.util.IaasProvider;
+import org.apache.stratos.autoscaler.service.util.ServiceTemplate;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * Responsible for reading the Elastic scaler configuration file.
+ * Following is a sample XML.
+ *
+ * &lt;elasticScalerConfig&gt;
+ *      &lt;iaasProviders&gt;
+ *          &lt;iaasProvider name="ec2"&gt;
+ *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
+ *              &lt;identity&gt;aaa&lt;/identity&gt;
+ *              &lt;credential&gt;aaaa&lt;/credential&gt;
+ *              &lt;scaleUpOrder&gt;1&lt;/scaleUpOrder&gt;
+ *              &lt;scaleDownOrder&gt;2&lt;/scaleDownOrder&gt;
+ *              &lt;property name="A" value="a"/&gt;
+ *              &lt;property name="B" value="b"/&gt;
+ *              &lt;template&gt;temp1&lt;/template&gt;
+ *          &lt;/iaasProvider&gt;
+ *          
+ *          &lt;iaasProvider name="lxc"&gt;
+ *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
+ *              &lt;identity&gt;aaa&lt;/identity&gt;
+ *              &lt;credential&gt;aaaa&lt;/credential&gt;
+ *              &lt;scaleUpOrder&gt;2&lt;/scaleUpOrder&gt;
+ *              &lt;scaleDownOrder&gt;1&lt;/scaleDownOrder&gt;
+ *              &lt;property name="X" value="x"/&gt;
+ *              &lt;property name="Y" value="y"/&gt;
+ *              &lt;template&gt;temp2&lt;/template&gt;
+ *          &lt;/iaasProvider&gt;
+ *      &lt;/iaasProviders&gt;
+ *      $lt;services&gt;
+ *          $lt;default&gt;
+ *              $lt;property name="availabilityZone" value="us-east-1c"/&gt;
+ *              $lt;property name="securityGroups" value="manager,cep,mb,default"/&gt;
+ *              $lt;property name="instanceType" value="m1.large"/&gt;
+ *              $lt;property name="keyPair" value="aa"/&gt;
+ *          $lt;/default&gt;
+ *          $lt;service domain="wso2.as.domain"&gt;
+ *              $lt;property name="securityGroups" value="manager,default"/&gt;
+ *              $lt;property name="payload" value="resources/as.zip"/&gt;
+ *          $lt;/service&gt;
+ *      $lt;/services&gt;
+ *  &lt;/elasticScalerConfig&gt;
+ */
+public class ElasticScalerConfigFileReader {
+	
+	private static final Log log = LogFactory.getLog(ElasticScalerConfigFileReader.class);
+
+	//get the factory
+	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+	private Document dom;
+	private Element docEle;
+
+	/**
+	 * Path to elastic-scaler-config XML file, which specifies the Iaas specific details and 
+	 * services related details.
+	 */
+	private String elasticScalerConfigFile;
+	
+	
+	public ElasticScalerConfigFileReader(){
+	    
+	    elasticScalerConfigFile = CarbonUtils.getCarbonConfigDirPath() +
+	            File.separator + "elastic-scaler-config.xml";
+	    
+		/**
+		 * Parse the configuration file.
+		 */
+		try {
+			//Using factory, get an instance of document builder
+			DocumentBuilder db = dbf.newDocumentBuilder();
+
+			//parse using builder to get DOM representation of the XML file
+			dom = db.parse(elasticScalerConfigFile);
+			
+
+		}catch(Exception ex) {
+			String msg = "Error occurred while parsing the "+elasticScalerConfigFile+".";
+			handleException(msg, ex);
+		}
+	}
+	
+	/**
+	 * Constructor to be used in the test cases.
+	 * @param file path to elastic-scaler-config xml file.
+	 */
+	public ElasticScalerConfigFileReader(String file) {
+        
+        /**
+         * Parse the configuration file.
+         */
+        try {
+            //Using factory, get an instance of document builder
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            
+            //parse using builder to get DOM representation of the XML file
+            dom = db.parse(file);
+            
+
+        }catch(Exception ex) {
+            String msg = "Error occurred when parsing the "+file+".";
+            handleException(msg, ex);
+        }
+    }
+	
+	/**
+	 * Returns the serialization directory specified in the configuration file.
+	 * @return the path to the directory or an empty string if element cannot be found.
+	 */
+	public String getSerializationDir() {
+        
+	    docEle = dom.getDocumentElement();
+	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.SERIALIZATION_DIR_ELEMENT);
+
+        // there should be only one serializationDir element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                return prop.getTextContent();
+
+            }
+        }
+        
+        return "";
+    }
+	
+	/**
+	 * Load all IaasProviders from the configuration file and returns a list.
+	 * @return a list of IaasProvider instances.
+	 */
+	public List<IaasProvider> getIaasProvidersList() {
+	    List<IaasProvider> iaasProviders = new ArrayList<IaasProvider>();
+	    
+	    docEle = dom.getDocumentElement();
+	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.IAAS_PROVIDER_ELEMENT);
+	    
+	    if (nl != null && nl.getLength() > 0) {
+	        
+	        for(int i=0; i< nl.getLength() ; i++){
+	            iaasProviders.add(getIaasProvider(nl.item(i)));
+	        }
+	        
+	    }
+	    else{
+	        String msg = "Essential '"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element cannot" +
+	        		" be found in "+elasticScalerConfigFile;
+	        handleException(msg);
+	    }
+	    
+	    return iaasProviders;
+	    
+    }
+
+    private IaasProvider getIaasProvider(Node item) {
+
+        IaasProvider iaas = new IaasProvider();
+        
+        if (item.getNodeType() == Node.ELEMENT_NODE) {
+            Element iaasElt = (Element) item;
+            iaas.setType(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR));
+            
+            if("".equals(iaas.getType())){
+                String msg = "'"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element's '"+
+            AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR+"' attribute should be specified!";
+                
+                handleException(msg);
+
+            }
+            
+            // this is not mandatory
+            iaas.setName(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_NAME_ATTR));
+            
+            iaas.setProperties(loadProperties(iaasElt));
+            loadTemplate(iaas, iaasElt);
+            loadScalingOrders(iaas, iaasElt);
+            loadProvider(iaas, iaasElt);
+            loadIdentity(iaas, iaasElt);
+            loadCredentials(iaas, iaasElt);
+        }
+        
+        
+        return iaas;
+    }
+    
+    /**
+     * Load all ServiceTemplates from the configuration file and returns a list.
+     * @return a list of ServiceTemplate instances.
+     */
+    public List<ServiceTemplate> getTemplates() {
+        
+        List<ServiceTemplate> templates = new ArrayList<ServiceTemplate>();
+        
+        // build default template object
+        ServiceTemplate template = new ServiceTemplate();
+        
+        Element docEle = dom.getDocumentElement();
+        NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.DEFAULT_SERVICE_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+
+            Node item = nl.item(0);
+
+            if (item.getNodeType() == Node.ELEMENT_NODE) {
+                Element defaultElt = (Element) item;
+                template.setProperties(loadProperties(defaultElt));
+            }
+
+        }
+        
+        // append / overwrite the default template object with values in each domain
+        nl = docEle.getElementsByTagName(AutoscalerConstant.SERVICE_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+
+            for (int i = 0; i < nl.getLength(); i++) {
+                Node item = nl.item(i);
+
+                // clone the default template to an independent object
+                try {
+                    ServiceTemplate temp = (ServiceTemplate) template.clone();
+
+                    if (item.getNodeType() == Node.ELEMENT_NODE) {
+                        Element imageElt = (Element) item;
+
+                        if ("".equals(imageElt.getAttribute(
+                                             AutoscalerConstant.SERVICE_DOMAIN_ATTR))) {
+                            String msg =
+                                "Essential '"+AutoscalerConstant.SERVICE_DOMAIN_ATTR+"' " +
+                                		"attribute of '"+AutoscalerConstant.SERVICE_ELEMENT+
+                                		"' element cannot be found in " + elasticScalerConfigFile;
+
+                            handleException(msg);
+                        }
+
+                        // set domain name
+                        temp.setDomainName(imageElt.getAttribute(AutoscalerConstant.SERVICE_DOMAIN_ATTR));
+                        
+                        // set sub domain
+                        temp.setSubDomainName(imageElt.getAttribute(
+                                              AutoscalerConstant.SERVICE_SUB_DOMAIN_ATTR));
+                        
+                        // load custom properties
+                        Map<String, String> customProperties = loadProperties(imageElt);
+                        
+                        // add custom properties (overwrite default properties where necessary)
+                        for (Entry<String, String> pair : customProperties.entrySet()) {
+                            temp.setProperty(pair.getKey(), pair.getValue());
+                        }
+
+                    }
+                    
+                    // add each domain specific template to list
+                    templates.add(temp);
+
+                } catch (CloneNotSupportedException e) {
+                    String msg = "This is extraordinary!! ";
+                    handleException(msg, e);
+                }
+            }
+        }
+        
+        return templates;
+    }
+    
+    private void loadCredentials(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.CREDENTIAL_ELEMENT);
+
+        // there should be only one credential element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                         AutoscalerConstant.CREDENTIAL_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+
+                // retrieve the value using secure vault
+                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
+                String alias;
+
+                // FIXME following is a hack to find the correct alias.
+                if (iaas.getProvider().contains("ec2")) {
+                    alias = AutoscalerConstant.EC2_CREDENTIAL_ALIAS;
+                } else {
+                    alias = AutoscalerConstant.OPENSTACK_CREDENTIAL_ALIAS;
+                }
+
+                // retrieve the secured password
+                if (secretResolver != null && secretResolver.isInitialized() && 
+                        secretResolver.isTokenProtected(alias)) {
+
+                    iaas.setCredential(secretResolver.resolve(alias));
+
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.CREDENTIAL_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadIdentity(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IDENTITY_ELEMENT);
+
+        // there should be only one identity element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.IDENTITY_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+
+                // retrieve the value using secure vault
+                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
+                String alias;
+                
+                //FIXME following is a hack to find the correct alias.
+                if(iaas.getProvider().contains("ec2")){
+                    alias = AutoscalerConstant.EC2_IDENTITY_ALIAS;
+                }
+                else{
+                    alias = AutoscalerConstant.OPENSTACK_IDENTITY_ALIAS;
+                }
+
+                // retrieve the secured password
+                if (secretResolver != null && secretResolver.isInitialized() && 
+                        secretResolver.isTokenProtected(alias)) {
+
+                    iaas.setIdentity(secretResolver.resolve(alias));
+
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.IDENTITY_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadProvider(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROVIDER_ELEMENT);
+
+        // there should be only one provider element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.PROVIDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                iaas.setProvider(prop.getTextContent());
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.PROVIDER_ELEMENT+"' element " +
+            		"has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadScalingOrders(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_UP_ORDER_ELEMENT);
+
+        // there should be only one scaleUpOrder element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                try {
+                    iaas.setScaleUpOrder(Integer.parseInt(prop.getTextContent()));
+                }catch (NumberFormatException e) {
+                    String msg = AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" element contained" +
+                    		" in "+elasticScalerConfigFile +"" +
+                    		" has a value which is not an Integer value.";
+                    handleException(msg, e);
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+        
+        
+        nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT);
+
+        // there should be only one scaleDownOrder element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                try {
+                    iaas.setScaleDownOrder(Integer.parseInt(prop.getTextContent()));
+                }catch (NumberFormatException e) {
+                    String msg = AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" element contained" +
+                            " in "+elasticScalerConfigFile +"" +
+                            " has a value which is not an Integer value.";
+                    handleException(msg, e);
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+"' element" +
+                    " has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadTemplate(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IMAGE_ID_ELEMENT);
+
+        // there should be only one imageId element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.IMAGE_ID_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                iaas.setTemplate(prop.getTextContent());
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.IMAGE_ID_ELEMENT+"' element" +
+                    " has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private Map<String, String> loadProperties(Element iaasElt) {
+
+        Map<String, String> propertyMap = new HashMap<String, String>();
+        
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROPERTY_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+            for(int i=0; i< nl.getLength() ; i++){
+                
+                if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
+                    Element prop = (Element) nl.item(i);
+                    
+                    if("".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR)) ||
+                            "".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR))){
+                        
+                        String msg ="Property element's, name and value attributes should be specified " +
+                        		"in "+elasticScalerConfigFile;
+
+                        handleException(msg);
+                    }
+                    propertyMap.put(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR), 
+                                    prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR));
+                    
+                }
+            }
+        }
+        
+        return propertyMap;
+    }
+    
+    private void handleException(String msg){
+        log.error(msg);
+        throw new MalformedConfigurationFileException(msg);
+    }
+    
+    private void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new MalformedConfigurationFileException(msg, e);
+    }
+	
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..04dd8d8
--- /dev/null
+++ b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="AutoscalerService" scope="application">
+        <parameter name="ServiceClass">org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImplpl</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/ca25b1f7/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
new file mode 100644
index 0000000..9a742ee
--- /dev/null
+++ b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
@@ -0,0 +1,98 @@
+/**
+ *  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.autoscaler.service.util;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.IaasContextComparator;
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
+
+import junit.framework.TestCase;
+
+public class IaasContextComparatorTest extends TestCase {
+    
+    List<IaasContext> iaasContexts = new ArrayList<IaasContext>();
+    
+    @Override
+    protected void setUp() throws Exception {
+        IaasContext a = new IaasContext(Iaases.ec2, null);
+        a.setScaleUpOrder(1);
+        a.setScaleDownOrder(5);
+        
+        IaasContext b = new IaasContext(Iaases.openstack, null);
+        b.setScaleUpOrder(3);
+        b.setScaleDownOrder(0);
+        
+        iaasContexts.add(a);
+        iaasContexts.add(b);
+        
+        super.setUp();
+    }
+
+    public void testSort() {
+        
+        // scale up order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_UP_SORT)));
+        
+        assertEquals("ec2", iaasContexts.get(0).getName().toString());
+        assertEquals("openstack", iaasContexts.get(1).getName().toString());
+        
+        // scale down order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_DOWN_SORT)));
+        
+        assertEquals("openstack", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        
+        IaasContext c = new IaasContext(Iaases.ec2, null);
+        c.setScaleUpOrder(0);
+        c.setScaleDownOrder(4);
+        
+        iaasContexts.add(c);
+        
+        // scale up order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_UP_SORT)));
+        
+        assertEquals("ec2", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        // scale down order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_DOWN_SORT)));
+        
+        assertEquals("openstack", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
new file mode 100644
index 0000000..2297a6f
--- /dev/null
+++ b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
@@ -0,0 +1,113 @@
+/**
+ *  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.autoscaler.service.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadataBuilder;
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+import junit.framework.TestCase;
+
+public class IaasContextTest extends TestCase {
+
+    IaasContext ctx;
+    NodeMetadata node1, node2, node3, node4;
+    
+    String[] domains = {"wso2.a", "wso2.b", "wso2.c"};
+    String[] subDomains = {"mgt", "worker"};
+    String[] nodeIds = {"1", "2", "3", "4", "5"};
+    String[] ips = {"192.168.1.2", "192.168.1.3", "192.168.1.4"};
+
+    public IaasContextTest(String name) {
+        super(name);
+    }
+
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        node1 = new NodeMetadataBuilder().id("1")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .publicAddresses(new ArrayList<String>(Arrays.asList("192.168.1.2")))
+                                         .build();
+        node2 = new NodeMetadataBuilder().id("2")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+        node3 = new NodeMetadataBuilder().id("3")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+        node4 = new NodeMetadataBuilder().id("4")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+
+        ctx = new IaasContext(Iaases.ec2, null);
+        
+        
+        ctx.addInstanceContext(new InstanceContext(domains[0], subDomains[0], null));
+        ctx.addInstanceContext(new InstanceContext(domains[1], subDomains[1], null));
+        ctx.addInstanceContext(new InstanceContext(domains[2], subDomains[0], null));
+        ctx.addInstanceContext(new InstanceContext(domains[2], Constants.DEFAULT_SUB_DOMAIN, null));
+        
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[0], "");
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
+        ctx.addNodeDetails(domains[1], subDomains[1], nodeIds[2], ips[1]);
+        ctx.addNodeDetails(domains[2], subDomains[0], nodeIds[3], ips[2]);
+        ctx.addNodeDetails(domains[2], Constants.DEFAULT_SUB_DOMAIN, nodeIds[4], "");
+        
+        
+//        ctx.addNodeIdToDomainMap(node1.getId(), "wso2.a");
+//        ctx.addPublicIpToDomainMap("192.168.1.2", "wso2.a");
+//        ctx.addPublicIpToNodeIdMap("192.168.1.2", node1.getId());
+//        ctx.addNodeIdToDomainMap(node2.getId(), "wso2.b");
+//        ctx.addNodeIdToDomainMap(node3.getId(), "wso2.a");
+//        ctx.addPublicIpToDomainMap("192.168.1.3", "wso2.a");
+//        ctx.addPublicIpToNodeIdMap("192.168.1.3", node3.getId());
+//        ctx.addNodeIdToDomainMap(node4.getId(), "wso2.c");
+    }
+
+    public final void testGetLastMatchingNode() {
+
+        assertEquals(nodeIds[1], ctx.getLastMatchingNode(domains[0], subDomains[0]));
+        ctx.removeNodeId(nodeIds[1]);
+        assertEquals(nodeIds[0], ctx.getLastMatchingNode(domains[0], subDomains[0]));
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
+    }
+
+    public final void testGetFirstMatchingNode() {
+        assertEquals(nodeIds[0], ctx.getFirstMatchingNode(domains[0], subDomains[0]));
+    }
+    
+    public final void testGetLastMatchingPublicIp() {
+        assertEquals(ips[0], ctx.getLastMatchingPublicIp(domains[0], subDomains[0]));
+        assertEquals(null, ctx.getLastMatchingPublicIp(domains[2], Constants.DEFAULT_SUB_DOMAIN));
+    }
+
+    public final void testGetNodeWithPublicIp() {
+        assertEquals(nodeIds[3], ctx.getNodeWithPublicIp(ips[2]));
+    }
+
+    public final void testGetNodeIds() {
+        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[0], nodeIds[1])), ctx.getNodeIds(domains[0], subDomains[0]));
+        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[2])), ctx.getNodeIds(domains[1], subDomains[1]));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
new file mode 100644
index 0000000..54502b7
--- /dev/null
+++ b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.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.autoscaler.service.xml;
+
+import java.util.List;
+import org.apache.stratos.autoscaler.service.util.IaasProvider;
+import junit.framework.TestCase;
+
+public class ElasticScalerConfigFileReaderTest extends TestCase {
+
+    public void testGetIaasProvidersListy() throws Exception {
+        
+        String file = "src/test/resources/elastic-scaler-config.xml";
+        ElasticScalerConfigFileReader reader = new ElasticScalerConfigFileReader(file);
+        
+        List<IaasProvider> list =reader.getIaasProvidersList();
+        
+        assertEquals(2, list.size());
+        
+        assertEquals("ec2", list.get(0).getType());
+        //assertEquals("cdcd", list.get(0).getIdentity());
+        assertEquals(2, list.get(0).getScaleDownOrder());
+        assertEquals(1, list.get(0).getScaleUpOrder());
+        assertEquals("a", list.get(0).getProperties().get("A.x"));
+        assertEquals("b", list.get(0).getProperties().get("B"));
+        assertEquals(null, list.get(0).getProperties().get("AA"));
+        
+        assertEquals("openstack", list.get(1).getType());
+        //assertEquals("bebbe", list.get(1).getIdentity());
+        assertEquals(1, list.get(1).getScaleDownOrder());
+        assertEquals(2, list.get(1).getScaleUpOrder());
+        assertEquals("x", list.get(1).getProperties().get("X"));
+        assertEquals("y", list.get(1).getProperties().get("Y"));
+        assertEquals(null, list.get(1).getProperties().get("x"));
+        
+        
+        List<org.apache.stratos.autoscaler.service.util.ServiceTemplate> temps =reader.getTemplates();
+      
+        assertEquals("wso2.as.domain", temps.get(0).getDomainName());
+        assertEquals("manager,default", temps.get(0).getProperty("securityGroups"));
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
new file mode 100644
index 0000000..d05bb14
--- /dev/null
+++ b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<!--
+/**
+ *  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.
+ */
+  -->
+
+<elasticScalerConfig xmlns:svns="http://org.wso2.securevault/configuration">
+
+<svns:secureVault provider="org.wso2.securevault.secret.handler.SecretManagerSecretCallbackHandler"/>
+	<iaasProviders>
+		<iaasProvider type="ec2" name="EC2 specific details">
+			<provider>aws-ec2</provider>
+			<identity svns:secretAlias="elastic.scaler.ec2.identity">cdcd</identity>
+			<credential svns:secretAlias="elastic.scaler.ec2.credential">cdccdc</credential>
+			<scaleUpOrder>1</scaleUpOrder>
+			<scaleDownOrder>2</scaleDownOrder>
+			<property name="A.x" value="a"/>
+			<property name="B" value="b"/>
+			<imageId>tempEC2</imageId>
+		</iaasProvider>
+		<iaasProvider type="openstack" >
+			<provider>lxc</provider>
+			<identity svns:secretAlias="elastic.scaler.openstack.identity">bebbe</identity>
+			<credential svns:secretAlias="elastic.scaler.openstack.credential">bebebe</credential>
+			<scaleUpOrder>2</scaleUpOrder>
+			<scaleDownOrder>1</scaleDownOrder>
+			<property name="X" value="x"/>
+			<property name="Y" value="y"/>
+			<imageId>tempLXC</imageId>
+		</iaasProvider>
+	</iaasProviders>
+	
+	<services>
+		<default>
+			<property name="availabilityZone" value="us-east-1c"/>
+			<property name="securityGroups" value="manager,cep,mb,default"/>
+            <property name="instanceType.ec2" value="m1.large"/>
+            <property name="instanceType.openstack" value="1"/>
+            <property name="minAppInstances" value="1"/>
+            <property name="maxAppInstances" value="5"/>
+            <property name="queueLengthPerNode" value="50"/>
+            <property name="roundsToAverage" value="100"/>
+            <property name="instancesPerScaleUp" value="1"/>
+            <property name="messageExpiryTime" value="60000"/>
+            <property name="keyPair" value="aa"/>
+		</default>
+		<service domain="wso2.as.domain" subDomain="mgt">
+			<property name="securityGroups" value="manager,default"/>
+            <property name="availabilityZone" value="us-east-1c"/>
+            <property name="payload" value="resources/as.zip"/>
+		</service>
+	</services>
+
+</elasticScalerConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
new file mode 100644
index 0000000..98acbcb
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
@@ -0,0 +1,138 @@
+<?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.
+ */
+-->
+
+
+<!--
+We need to modify this file since this copied from branch
+-->
+<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>2.0.0</version>
+        <relativePath>../../../pom.xml</relativePath>
+    </parent>
+
+    <version>4.1.3</version>
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.mediator.autoscale</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Autoscale Mediator BE</name>
+    <url>http://apache.org</url>
+
+    <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>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            !org.org.apache.stratos.mediator.autoscale.lbautoscale.internal,
+                            org.apache.stratos.mediator.autoscale.*
+                        </Export-Package>
+                        <Private-Package>org.apache.stratos.mediator.autoscale.lbautoscale.internal</Private-Package>
+                        <Import-Package>
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            org.apache.axis2.*,
+                            org.apache.synapse.*,
+                            org.wso2.carbon.task.*; version=0.0.0,
+                            org.wso2.carbon.core.*,
+                            org.apache.stratos.lb.common.*,
+                            org.wso2.carbon.load.balance.cartridge.autoscaler.service.stub.*; version=0.0.0,
+                            org.wso2.carbon.utils.*,
+                            org.apache.axiom.om; version="${axiom.osgi.version.range}",
+                            org.wso2.carbon.stratos.cloud.controller.*,
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+          <groupId>org.apache.axis2.wso2</groupId>
+          <artifactId>axis2</artifactId>
+          <version>1.6.1.wso2v9</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.load.balance.cartridge.autoscaler.service.stub</artifactId>
+            <version>4.1.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <version>4.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.cloud.controller</artifactId>
+            <version>2.1.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.task</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-tasks</artifactId>
+            <version>2.1.1-wso2v4</version>
+        </dependency>
+
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
new file mode 100644
index 0000000..c535489
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
@@ -0,0 +1,86 @@
+/**
+ *  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.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+import java.util.concurrent.Callable;
+
+/** Performing sanity checks for each service domain, sub domain combination **/
+public class AppNodeSanityCheckCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(AppNodeSanityCheckCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appDomainContext;
+    private ServiceConfiguration serviceConfig;
+    
+    public AppNodeSanityCheckCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appDomainContext = appCtxt;
+        serviceConfig =
+                AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig().getServiceConfig(this.domain,
+                    this.subDomain);
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+
+        if (appDomainContext != null) {
+            int currentInstances = 0;
+            // we're considering both running and pending instance count
+            currentInstances = appDomainContext.getInstances();
+
+            int requiredInstances = serviceConfig.getMinAppInstances();
+
+            // we try to maintain the minimum number of instances required
+            if (currentInstances < requiredInstances) {
+                log.debug("App domain Sanity check failed for " +
+                    AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                        " . Current instances: " +
+                        currentInstances +
+                        ". Required instances: " +
+                        requiredInstances);
+
+                int diff = requiredInstances - currentInstances;
+
+                // Launch diff number of App instances
+                log.debug("Launching " +
+                    diff +
+                    " App instances for " +AutoscaleUtil.domainSubDomainString(domain, subDomain));
+
+                // FIXME: should we need to consider serviceConfig.getInstancesPerScaleUp()?
+                AutoscaleUtil.runInstances(client, appDomainContext, this.domain, this.subDomain, diff);
+            }
+        }
+
+        return true;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
new file mode 100644
index 0000000..84705bb
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
@@ -0,0 +1,241 @@
+/**
+ *  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.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.state.check.TerminatingInstancesStateChecker;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+import java.util.concurrent.Callable;
+
+/** Take auto-scaling decisions for each service domain, sub domain combination **/
+public class AutoscaleDeciderCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(AutoscaleDeciderCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appDomainContext;
+    private ServiceConfiguration serviceConfig;
+    private String clusterStr;
+    
+    public AutoscaleDeciderCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appDomainContext = appCtxt;
+        clusterStr = AutoscaleUtil.domainSubDomainString(domain, subDomain);
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+
+        // expire tokens
+        if (appDomainContext != null) {
+            appDomainContext.expireRequestTokens();
+
+            serviceConfig = appDomainContext.getServiceConfig();
+
+            appDomainContext.recordRequestTokenListLength();
+            if (!appDomainContext.canMakeScalingDecision()) {
+                return true;
+            }
+
+            long average = appDomainContext.getAverageRequestsInFlight();
+            int runningAppInstances = appDomainContext.getRunningInstanceCount();
+            int terminatingAppInstances = appDomainContext.getTerminatingInstanceCount();
+
+            int maxRPS = serviceConfig.getMaxRequestsPerSecond();
+            double taskInterval =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getWholeLoadBalancerConfig()
+                    .getLoadBalancerConfig()
+                    .getAutoscalerTaskInterval() / (double)1000;
+            double aur = serviceConfig.getAlarmingUpperRate();
+            double alr = serviceConfig.getAlarmingLowerRate();
+            double scaleDownFactor = serviceConfig.getScaleDownFactor();
+
+            // scale up early
+            double maxhandleableReqs = maxRPS * taskInterval * aur;
+            // scale down slowly
+            double minhandleableReqs = maxRPS * taskInterval * alr * scaleDownFactor;
+
+            if (log.isDebugEnabled()) {
+                log.debug(clusterStr +": Average requests in flight: " + average + " **** Handleable requests: " +
+                    (runningAppInstances * maxhandleableReqs));
+            }
+            if (average > (runningAppInstances * maxhandleableReqs) && maxhandleableReqs > 0) {
+                
+                // estimate number of instances we might want to spawn
+                int requiredInstances = (int) Math.ceil(average/maxhandleableReqs);
+                
+                log.debug(clusterStr+" : Required instance count: "+requiredInstances);
+                
+                // current average is higher than that can be handled by current nodes.
+                scaleUp(requiredInstances - runningAppInstances);
+            } else if (terminatingAppInstances == 0 && average < ((runningAppInstances - 1) * minhandleableReqs)) {
+                // current average is less than that can be handled by (current nodes - 1).
+                scaleDown();
+            }
+        }
+
+        return true;
+    }
+
+    private void scaleDown() {
+
+        int runningInstances = appDomainContext.getRunningInstanceCount();
+//        int pendingInstances = appDomainContext.getPendingInstanceCount();
+        int terminatingInstances = appDomainContext.getTerminatingInstanceCount();
+        int minAppInstances = serviceConfig.getMinAppInstances();
+//        int serverStartupDelay = AutoscalerTaskDSHolder
+//                                            .getInstance()
+//                                            .getWholeLoadBalancerConfig()
+//                                            .getLoadBalancerConfig()
+//                                            .getServerStartupDelay();
+
+        if ( (runningInstances - terminatingInstances) > minAppInstances) {
+
+            if (log.isDebugEnabled()) {
+                log.debug("Scale Down - " +
+                    clusterStr +
+                        ". Running instances:" +
+                        runningInstances +
+                        ". Terminating instances: " +
+                        terminatingInstances +
+                        ". Min instances:" +
+                        minAppInstances);
+            }
+            // ask to scale down
+            try {
+                if (client.terminateInstance(domain, subDomain)) {
+                    
+                    Thread th = new Thread(new TerminatingInstancesStateChecker(appDomainContext, domain, subDomain));
+                    th.start();
+                    
+//                        log.debug(clusterStr +": There's an instance who's in shutting down state " +
+//                            "(but still not left ELB), hence we should wait till " +
+//                            "it leaves the cluster.");
+//
+//                        int totalWaitedTime = 0;
+//
+//                        log.debug(clusterStr +": Task will wait maximum of (milliseconds) : " +
+//                            serverStartupDelay +
+//                                ", to let the member leave the cluster.");
+//                        
+//                        // for each sub domain, get the clustering group management agent
+//                        GroupManagementAgent agent =
+//                            AutoscalerTaskDSHolder.getInstance().getAgent()
+//                                .getGroupManagementAgent(domain,
+//                                    subDomain);
+//
+//                        // we give some time for the server to be terminated, we'll check time to time
+//                        // whether the instance has actually left the cluster.
+//                        while (agent.getMembers().size() == runningInstances &&
+//                            totalWaitedTime < serverStartupDelay) {
+//
+//                            try {
+//                                Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+//                            } catch (InterruptedException ignore) {
+//                            }
+//
+//                            totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+//                        }
+//
+//                        log.debug(clusterStr+ " : task waited for (milliseconds) : " + totalWaitedTime);
+//
+//                        // we recalculate number of alive instances
+//                        runningInstances = agent.getMembers().size();
+//                        
+//                        appDomainContext.setRunningInstanceCount(runningInstances);
+//
+//                        log.debug(clusterStr+" : New running instance count: " + runningInstances);
+                }
+
+            } catch (Exception e) {
+                log.error("Instance termination failed for " + clusterStr, e);
+            }
+        }
+
+    }
+
+    private void scaleUp(int requiredInstanceCount) {
+
+        int maxAppInstances = serviceConfig.getMaxAppInstances();
+//        int instancesPerScaleUp = serviceConfig.getInstancesPerScaleUp();
+//        int runningInstances = appDomainContext.getRunningInstanceCount();
+//        int pendingInstances = appDomainContext.getPendingInstanceCount();
+        int totalInstanceCount = appDomainContext.getInstances();
+        
+        log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Total Running/Pending instance count: "+totalInstanceCount);
+        
+        if(maxAppInstances > totalInstanceCount){
+            
+            int availableQuotaOfInstances = maxAppInstances - totalInstanceCount;
+            
+            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Available Quota of Instances: "+availableQuotaOfInstances);
+            
+            requiredInstanceCount = requiredInstanceCount <= availableQuotaOfInstances ? requiredInstanceCount : availableQuotaOfInstances;
+            
+            log.debug(clusterStr + " - Going to start " +
+                    requiredInstanceCount + " instance/s.");
+
+                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
+                    requiredInstanceCount);
+                
+        } else if (totalInstanceCount > maxAppInstances) {
+            log.fatal("Number of running instances has over reached the maximum limit of " +
+                maxAppInstances + " of " + clusterStr);
+        }
+
+//        int failedInstances = 0;
+//        if (runningInstances < maxAppInstances && pendingInstances == 0) {
+//
+//            log.debug(clusterStr + " - Going to start " +
+//                    requiredInstanceCount + " instance/s. Running instances:" + runningInstances);
+//
+//                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
+//                    requiredInstanceCount);
+
+//            if (successfullyStarted != instancesPerScaleUp) {
+//                failedInstances = instancesPerScaleUp - successfullyStarted;
+//                if (log.isDebugEnabled()) {
+//                    log.debug(successfullyStarted +
+//                        " instances successfully started and\n" + failedInstances +
+//                        " instances failed to start for " + clusterStr);
+//                }
+//            }
+//
+//            // we increment the pending instance count
+//            // appDomainContext.incrementPendingInstances(instancesPerScaleUp);
+//            else {
+//                log.debug("Successfully started " + successfullyStarted +
+//                    " instances of " + clusterStr);
+//            }
+
+       
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
new file mode 100644
index 0000000..90c2c3a
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
@@ -0,0 +1,78 @@
+/**
+ *  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.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/** Calculate instances of each service domain, sub domain combination **/
+public class InstanceCountCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(InstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appCtxt;
+    private ExecutorService executor = Executors.newFixedThreadPool(10);
+    
+    public InstanceCountCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appCtxt = appCtxt;
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+        log.debug("Computation of instance counts started for domain: " + this.domain +
+            " and sub domain: " + this.subDomain);
+
+        Callable<Integer> worker = new RunningInstanceCountCallable(this.domain, this.subDomain);
+        Future<Integer> runningInstanceCount = executor.submit(worker);
+
+//        worker = new PendingInstanceCountCallable(this.domain, this.subDomain, client);
+//        Future<Integer> pendingInstanceCount = executor.submit(worker);
+
+        int runningInstances = 0, pendingInstances = 0;
+        if (appCtxt != null) {
+
+            try {
+                // get the values of Callables
+                runningInstances = runningInstanceCount.get();
+                pendingInstances = appCtxt.getPendingInstanceCount();
+            } catch (Exception e) {
+                // no need to throw
+                log.error(e.getMessage(), e);
+            }
+
+            appCtxt.setRunningInstanceCount(runningInstances);
+            appCtxt.setPendingInstanceCount(pendingInstances);
+            
+        }
+        return true;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
new file mode 100644
index 0000000..27cf50e
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
@@ -0,0 +1,65 @@
+/**
+ *  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.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+
+import java.util.concurrent.Callable;
+
+/** Calculate pending instances of each service domain, sub domain combination **/
+public class PendingInstanceCountCallable implements Callable<Integer> {
+
+    private static final Log log = LogFactory.getLog(PendingInstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    
+    public PendingInstanceCountCallable(String domain, String subDomain, CloudControllerClient client){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+    }
+    
+    @Override
+    public Integer call() throws Exception {
+        int pendingInstanceCount = 0;
+
+        try {
+            pendingInstanceCount =
+                client.getPendingInstanceCount(this.domain,
+                    this.subDomain);
+
+        } catch (Exception e) {
+            log.error("Failed to retrieve pending instance count for domain: " +
+                this.domain + " and sub domain: " + this.subDomain, e);
+        }
+
+        log.debug("Pending instance count for domain: " +
+            this.domain +
+            ", sub domain: " +
+            this.subDomain +
+            " is " +
+            pendingInstanceCount);
+
+        return pendingInstanceCount;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
new file mode 100644
index 0000000..3bc3db5
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
@@ -0,0 +1,68 @@
+/**
+ *  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.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+import java.util.concurrent.Callable;
+
+/** Calculate running instances of each service domain, sub domain combination **/
+public class RunningInstanceCountCallable implements Callable<Integer> {
+
+    private static final Log log = LogFactory.getLog(RunningInstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    
+    public RunningInstanceCountCallable(String domain, String subDomain){
+        this.domain = domain;
+        this.subDomain = subDomain;
+    }
+    
+    @Override
+    public Integer call() throws Exception {
+        int runningInstances;
+        // for each sub domain, get the clustering group management agent
+        GroupManagementAgent agent =
+            AutoscalerTaskDSHolder.getInstance().getAgent()
+                .getGroupManagementAgent(this.domain,
+                    this.subDomain);
+
+        // if it isn't null
+        if (agent != null) {
+            // we calculate running instance count for this service domain
+            runningInstances = agent.getMembers().size();
+        } else {
+            // if agent is null, we assume no service instances are running
+            runningInstances = 0;
+        }
+
+        log.debug("Running instance count for domain: " +
+            this.domain +
+                ", sub domain: " +
+                this.subDomain +
+                " is " +
+                runningInstances);
+        
+        return runningInstances;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
new file mode 100644
index 0000000..ec9e1bb
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
@@ -0,0 +1,66 @@
+/**
+ *  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.mediator.autoscale.lbautoscale.clients;
+
+/**
+ * Each Implementation which provides access to Cloud Controller, should implement this interface.
+ */
+public abstract class CloudControllerClient {
+
+    /**
+     * Initializes the client.
+     */
+    public abstract void init();
+    
+    /**
+     * Should start an instance.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return Public IP of the spawned instance.
+     * @throws Exception 
+     */
+    public abstract String startInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Terminates an instance belongs to the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return whether the termination is successful or not.
+     * @throws Exception
+     */
+    public abstract boolean terminateInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Terminates lastly spawned instance of the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return whether the termination is successful or not.
+     * @throws Exception
+     */
+    public abstract boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Return pending instance count of the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return pending instance count.
+     * @throws Exception
+     */
+    public abstract int getPendingInstanceCount(String domainName, String subDomainName) throws Exception;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ca25b1f7/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
new file mode 100644
index 0000000..ad95a89
--- /dev/null
+++ b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
@@ -0,0 +1,82 @@
+/**
+ *  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.mediator.autoscale.lbautoscale.clients;
+
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+
+/**
+ * This is the client class this calls Autoscaler service.
+ */
+public class CloudControllerOsgiClient extends CloudControllerClient {
+
+    private CloudControllerService cloudControllerService;
+
+    private static final Log log = LogFactory.getLog(CloudControllerOsgiClient.class);
+
+    // public CloudControllerStubClient(String epr) throws AxisFault {
+    //
+    // try {
+    //
+    // stub = new CloudControllerServiceStub(epr);
+    // stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(90000);
+    //
+    // } catch (AxisFault axisFault) {
+    // String msg =
+    // "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+    // log.error(msg, axisFault);
+    // throw new AxisFault(msg, axisFault);
+    // }
+    // }
+
+    // public boolean init(boolean isSpi) throws Exception {
+    //
+    // return stub.initAutoscaler(isSpi);
+    // }
+
+    public String startInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.startInstance(domainName, subDomainName);
+    }
+
+    public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.terminateInstance(domainName, subDomainName);
+    }
+
+    public boolean
+        terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.terminateLastlySpawnedInstance(domainName, subDomainName);
+    }
+
+    public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.getPendingInstanceCount(domainName, subDomainName);
+    }
+
+    @Override
+    public void init() {
+
+        cloudControllerService = AutoscalerTaskDSHolder.getInstance().getCloudControllerService();
+    }
+
+}