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/02 08:40:57 UTC

[07/10] committing org.apache.stratos.mediator.autoscale

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
new file mode 100644
index 0000000..99c96ca
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
@@ -0,0 +1,47 @@
+/**
+ *  Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed 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.task;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescriptionRepository;
+import org.apache.synapse.task.TaskScheduler;
+import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
+
+public class AutoscalerTaskInitializer extends AbstractAxis2ConfigurationContextObserver {
+
+    public static final java.lang.String CARBON_TASK_SCHEDULER = "CARBON_TASK_SCHEDULER";
+    public static final java.lang.String CARBON_TASK_REPOSITORY = "CARBON_TASK_REPOSITORY";
+
+    public void createdConfigurationContext(ConfigurationContext configContext) {
+        TaskScheduler scheduler = (TaskScheduler)configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
+        if (scheduler == null) {
+            scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
+            scheduler.init(null);
+            configContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER, scheduler);
+        } else if(!scheduler.isInitialized()) {
+            scheduler.init(null);
+        }
+
+        if (configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY) == null) {
+            TaskDescriptionRepository repository = new TaskDescriptionRepository();
+            configContext.setProperty(
+                    AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY, repository);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
new file mode 100644
index 0000000..f9e5e32
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
@@ -0,0 +1,345 @@
+/**
+ * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed 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.task;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskDescriptionFactory;
+import org.apache.synapse.task.TaskDescriptionSerializer;
+import org.apache.synapse.task.service.TaskManagementService;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.task.TaskManagementException;
+import org.wso2.carbon.task.TaskManager;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import java.util.*;
+
+public class AutoscalerTaskMgmtAdminService extends AbstractAdmin implements TaskManagementService{
+
+    private static final Log log = LogFactory.getLog(AutoscalerTaskMgmtAdminService.class);
+
+    private TaskSchedulingManager schedulingManager;
+
+
+    private static final String TASK_EXTENSION_NS =
+            "http://www.wso2.org/tasks";
+
+    private static final OMFactory FACTORY = OMAbstractFactory.getOMFactory();
+
+    private static final OMNamespace TASK_OM_NAMESPACE = FACTORY.createOMNamespace(
+            TASK_EXTENSION_NS, "task");
+
+    public AutoscalerTaskMgmtAdminService(){}
+    
+    public AutoscalerTaskMgmtAdminService(ConfigurationContext configurationContext) {
+        this.schedulingManager = TaskSchedulingManager.getInstance();
+        this.configurationContext = configurationContext;
+    }
+
+    public void shutdown() {
+        schedulingManager.shutDown(getConfigContext());
+    }
+
+    public void addTaskDescription(TaskDescription taskDescription, Map<String, Object> resources)
+            throws Exception {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding the Task " + taskDescription.getName());
+        }
+        try {
+            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
+        } catch (Exception e) {
+            String msg = "Cannot add the task " + taskDescription.getName() + "..";
+            log.error(msg, e);  
+            throw e;
+        }
+    }
+
+    /**
+     * Passing the Task Description to scheduling manager to actually add it to the Task
+     * Description Repository.
+     *
+     * @param taskDescription TaskDescription
+     */
+    public void addTaskDescription(TaskDescription taskDescription) {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding the Task " + taskDescription.getName());
+        }
+        try {
+            Map<String, Object> resources = new HashMap<String, Object>();
+            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
+        } catch (Exception e) {
+            String msg = "Cannot add the task";
+            log.error(msg, e);
+        }
+    }
+
+    public void addTaskDescriptionInAnOmElement(String taskElementString) throws
+                                                                          TaskManagementException,
+                                                                          XMLStreamException {
+        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
+        if (log.isDebugEnabled()) {
+            log.debug("Add TaskDescription - Get a Task configuration  :" + taskElement);
+        }
+        TaskDescription taskDescription = validateAndCreate(taskElement);
+
+        try {
+            addTaskDescription(taskDescription);
+        } catch (Exception e) {
+            try {
+                getTaskManager().deleteTaskDescription(taskDescription.getName(),
+                        taskDescription.getGroup());
+            } catch (Exception ignored) {
+            }
+            handleException("Error creating a task : " + e.getMessage(), e);
+        }
+    }
+
+
+
+    public void deleteTaskDescription(TaskDescription taskDescription) {
+        String taskName = taskDescription.getName();
+        if (log.isDebugEnabled()) {
+            log.debug("Deleting the task " + taskName);
+        }
+        try {
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+        } catch (Exception e) {
+            log.error("Cannot delete the task " + taskName, e);
+        }
+    }
+
+    /**
+     * Indicating Task Scheduling manager to delete the task with the given task Name.
+     *
+     * @param taskName taskName
+     */
+    public void deleteTaskDescription(String taskName) {
+        if (log.isDebugEnabled()) {
+            log.debug("Deleting the task " + taskName);
+        }
+        try {
+            TaskDescription taskDescription = new TaskDescription();
+            taskDescription.setName(taskName);
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+        } catch (Exception e) {
+            log.error("Cannot delete the task " + taskName, e);
+        }
+    }
+
+    /**
+     * Notifying the Task Scheduling Manager to delete the previous Task Description from the
+     * Task Description Repository and add the edited task.
+     *
+     * @param taskDescription TaskDescription
+     */
+    public void editTaskDescription(TaskDescription taskDescription) {
+        if (log.isDebugEnabled()) {
+            log.debug("Editing the task " + taskDescription.getName());
+        }
+        if (schedulingManager.isContains(taskDescription.getName(), getConfigContext())) {
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+            schedulingManager.scheduleTask(taskDescription, null, getConfigContext());
+        } else {
+            log.error("Task " + taskDescription.getName() + "does not exist");
+        }
+    }
+
+    public void editTaskDescriptionInOmElement(
+            String taskElementString) throws TaskManagementException, XMLStreamException {
+        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
+        if (log.isDebugEnabled()) {
+            log.debug("Edit TaskDescription - Get a Task configuration  :" + taskElement);
+        }
+        try {
+            editTaskDescription(validateAndCreate(taskElement));
+        } catch (Exception e) {
+            String msg = "Error editing Task";
+            throw new TaskManagementException(msg, e);
+        }
+    }
+
+    /**
+     * Returns the list of Task Descriptions that have been already added to the Task Description
+     * Repository.
+     *
+     * @return A list of Task Descriptions
+     */
+    public List<TaskDescription> getAllTaskDescriptions() {
+        List<TaskDescription> taskDescriptions = new ArrayList<TaskDescription>();
+        Iterator<TaskDescription> iterator = schedulingManager.getAllTaskDescriptions(
+                getConfigContext());
+
+        while (iterator.hasNext()) {
+            TaskDescription taskDescription = iterator.next();
+            if (taskDescription != null) {
+                taskDescriptions.add(taskDescription);
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("All available Task based Scheduled Functions " + taskDescriptions);
+        }
+        return taskDescriptions;
+    }
+
+    public String getAllTaskDescriptionsInAnOMElement() throws AxisFault {
+        OMElement rootElement =
+                OMAbstractFactory.getOMFactory().createOMElement(new QName(TASK_EXTENSION_NS,
+                        "taskExtension", "task"));
+        try {
+            List<TaskDescription> descriptions = getAllTaskDescriptions();
+            for (TaskDescription taskDescription : descriptions) {
+                if (taskDescription != null) {
+                    OMElement taskElement =
+                            TaskDescriptionSerializer.serializeTaskDescription(TASK_OM_NAMESPACE,
+                                                                               taskDescription);
+                    validateTaskElement(taskElement);
+                    rootElement.addChild(taskElement);
+                }
+            }
+        } catch (TaskManagementException e) {
+            String msg = "Error loading all tasks";
+            log.error(msg, e);
+            throw new AxisFault(msg, e);
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Returning all TaskDescriptions as  :" + rootElement);
+        }
+        return rootElement.toString();
+    }
+
+    /**
+     * Returns the names of job groups that are being executed.
+     *
+     * @return An array of strings
+     */
+    public String[] getAllJobGroups() {
+        List<String> strings = getTaskManager().getAllJobGroups();
+        return strings.toArray(new String[strings.size()]);
+    }
+
+    /**
+     * Returns the TaskDescription associates with a particular task name
+     *
+     * @param taskName Task Name
+     * @return TaskDescription
+     */
+    public TaskDescription getTaskDescription(String taskName) {
+        return schedulingManager.getTaskDescription(taskName, getConfigContext());
+    }
+
+    public boolean isContains(String taskName) {
+        return schedulingManager.isContains(taskName, getConfigContext());
+    }
+
+    /**
+     * @param taskClass taskClass
+     * @return list of strings containing properties of the task class
+     */
+    public List<String> getPropertyNames(String taskClass) {
+        return null;
+    }
+
+    /**
+     * Returns the TaskManager instance currently being used
+     *
+     * @return TaskManager
+     */
+    private synchronized TaskManager getTaskManager() {
+        return (TaskManager) getConfigContext().getProperty(
+                TaskManager.CARBON_TASK_MANAGER);
+    }
+
+    /**
+     * Validates the OMElement which has a particular TaskDescription
+     * serialized into it.
+     *
+     * @param taskElement taskElement
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void validateTaskElement(
+            OMElement taskElement) throws TaskManagementException {
+        if (taskElement == null) {
+            handleException("Task Description OMElement can not be found.");
+        }
+    }
+
+    /**
+     * Handles the exception thrown and logs it.
+     *
+     * @param msg message to be logged
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void handleException(String msg) throws TaskManagementException {
+        log.error(msg);
+        throw new TaskManagementException(msg);
+    }
+
+    /**
+     * Handles the exception thrown and logs it.
+     *
+     * @param msg message to be logged
+     * @param e   exception thrown
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void handleException(String msg, Exception e) throws TaskManagementException {
+        log.error(msg, e);
+        throw new TaskManagementException(msg, e);
+    }
+
+    /**
+     * Validates an OMElement which has a TaskDescription serialized into it
+     * and returns the corresponding TaskDescription
+     *
+     * @param taskElement OMElement containing the TaskDescription
+     * @return TaskDescription
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static TaskDescription validateAndCreate(
+            OMElement taskElement) throws TaskManagementException {
+
+        validateTaskElement(taskElement);
+        TaskDescription taskDescription =
+                TaskDescriptionFactory.createTaskDescription(taskElement, TASK_OM_NAMESPACE);
+        validateTaskDescription(taskDescription);
+        if (log.isDebugEnabled()) {
+            log.debug("Task Description : " + taskDescription);
+        }
+        return taskDescription;
+    }
+
+    /**
+     * Validates TaskDescriptions
+     *
+     * @param description TaskDescription
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void validateTaskDescription(
+            TaskDescription description) throws TaskManagementException {
+        if (description == null) {
+            handleException("Task Description can not be found.");
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
new file mode 100644
index 0000000..e091455
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
@@ -0,0 +1,65 @@
+/**
+ * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed 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.task;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.task.Task;
+import org.quartz.Job;
+import org.quartz.JobDetail;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import java.util.Map;
+
+public class AutoscalingJob implements Job {
+
+    public static final String AUTOSCALER_TASK = "autoscalerTask";
+
+    public static final String SYNAPSE_ENVI = "synapseEnv";
+
+    private static final Log log = LogFactory.getLog(AutoscalingJob.class);
+
+    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+
+        try {
+
+            Task task = null;
+
+            JobDetail jobDetail = jobExecutionContext.getJobDetail();
+
+            if (log.isDebugEnabled()) {
+                log.debug("Executing Autoscaler task : " + jobDetail.getKey().getName());
+            }
+
+            @SuppressWarnings("rawtypes")
+            Map mjdm = jobExecutionContext.getMergedJobDataMap();
+
+            task = (Task) mjdm.get(AUTOSCALER_TASK);
+
+            if (task instanceof ManagedLifecycle) {
+                // Execute Autoscaler task
+                ((ServiceRequestsInFlightAutoscaler) task).execute();
+            }
+
+        } catch (Exception e) {
+            throw new JobExecutionException(e);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
new file mode 100644
index 0000000..05f987d
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
@@ -0,0 +1,524 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. 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.task;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.callables.InstanceCountCallable;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
+import org.apache.synapse.task.Task;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.mediator.autoscale.lbautoscale.callables.AppNodeSanityCheckCallable;
+import org.apache.stratos.mediator.autoscale.lbautoscale.callables.AutoscaleDeciderCallable;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerOsgiClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerStubClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.stratos.lb.common.replication.RequestTokenReplicationCommand;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+
+/**
+ * Service request in flight autoscaler task for Stratos service level auto-scaling
+ */
+public class ServiceRequestsInFlightAutoscaler implements Task, ManagedLifecycle {
+
+    private static final Log log = LogFactory.getLog(ServiceRequestsInFlightAutoscaler.class);
+
+    /**
+     * This instance holds the loadbalancer configuration
+     */
+    private LoadBalancerConfiguration loadBalancerConfig;
+
+    /**
+     * Autoscaler service client instance
+     */
+    private CloudControllerClient autoscalerService;
+
+    /**
+     * AppDomainContexts for each domain
+     * Key - domain
+     * Value - Map of key - sub domain
+     * value - {@link AppDomainContext}
+     */
+    private Map<String, Map<String, ?>> appDomainContexts =
+        new HashMap<String, Map<String, ?>>();
+
+    /**
+     * LB Context for LB cluster
+     */
+    private final LoadBalancerContext lbContext = new LoadBalancerContext();
+
+    /**
+     * Attribute to keep track whether this instance is the primary load balancer.
+     */
+    private boolean isPrimaryLoadBalancer;
+
+    /**
+     * Keeps track whether this task is still running
+     */
+    private boolean isTaskRunning;
+    
+    /**
+     * Thread pool used in this task to execute parallel tasks.
+     */
+    private ExecutorService executor = Executors.newFixedThreadPool(100);
+
+    /**
+     * Check that all app nodes in all clusters meet the minimum configuration
+     */
+    private void appNodesSanityCheck() {
+        
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+        
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+            
+            String msg =
+                    "Sanity check is failed to run. No Appdomain context is generated for the" +
+                        " domain " + serviceDomain;
+            
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+                log.debug("Sanity check has started for: "+AutoscaleUtil.domainSubDomainString(serviceDomain, serviceSubDomain));
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+                    
+                    if (appCtxt != null) {
+                        // Concurrently perform the application node sanity check.
+                        Callable<Boolean> worker =
+                            new AppNodeSanityCheckCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> appNodeSanityCheck = executor.submit(worker);
+                        jobList.add(appNodeSanityCheck);
+
+                    } else{
+                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
+                    }
+                } else{
+                    log.error(msg);
+                }
+            }
+        }
+        
+        // Retrieve the results of the concurrently performed sanity checks.
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            } 
+        }
+
+    }
+
+    /**
+     * Autoscale the entire system, analyzing the requests in flight of each domain - sub domain
+     */
+    private void autoscale() {
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+
+            String msg =
+                "Autoscaler check is failed to run. No Appdomain context is generated for the" +
+                    " domain " + serviceDomain;
+
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+
+                log.debug("Autoscaling analysis is starting to run for domain: " + serviceDomain +
+                    " and sub domain: " + serviceSubDomain);
+
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+
+                    if (appCtxt != null) {
+
+                        // Concurrently make the auto-scaling decisions
+                        Callable<Boolean> worker =
+                            new AutoscaleDeciderCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> autoscalerDeciderCheck = executor.submit(worker);
+                        jobList.add(autoscalerDeciderCheck);
+
+                    } else {
+                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
+                    }
+                } else {
+                    log.error(msg);
+                }
+            }
+        }
+
+        // Retrieve the results of the concurrently performed sanity checks.
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            }
+        }
+    }
+
+    /**
+     * We compute the number of running instances of a particular domain using clustering agent.
+     */
+    private void computeRunningAndPendingInstances() {
+
+        int runningInstances = 0, pendingInstances = 0;
+
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+                    
+                    log.debug("Values in App domain context: " +
+                        appCtxt.getPendingInstanceCount() +
+                            " - " +
+                            appCtxt.getRunningInstanceCount() +
+                            " - Ctxt: " +
+                            appCtxt.hashCode());
+
+                    if (appCtxt != null) {
+                        Callable<Boolean> worker =
+                            new InstanceCountCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> countInstancesJob = executor.submit(worker);
+                        jobList.add(countInstancesJob);
+                    }
+                }
+            }
+        }
+
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            }
+        }
+
+        /* Calculate running load balancer instances */
+
+        // count this LB instance in.
+        runningInstances = 1;
+
+        runningInstances += AutoscalerTaskDSHolder.getInstance().getAgent().getAliveMemberCount();
+
+        lbContext.setRunningInstanceCount(runningInstances);
+
+        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain") == null) {
+            String msg = "Clustering Agent's domain parameter is null. Please specify a domain" +
+                " name in axis2.xml of Elastic Load Balancer.";
+            log.error(msg);
+            throw new RuntimeException(msg);
+        }
+
+        String lbDomain = AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain").getValue().toString();
+
+        String lbSubDomain = null;
+
+        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain") != null) {
+            lbSubDomain =
+                AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain").getValue().toString();
+        }
+
+        // reset
+        pendingInstances = 0;
+        try {
+            pendingInstances = lbContext.getPendingInstanceCount();
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            // no need to throw
+        }
+
+        lbContext.setPendingInstanceCount(pendingInstances);
+
+        log.debug("Load Balancer members of domain: " +
+            lbDomain +
+            " and sub domain: " +
+            lbSubDomain +
+            " running instances (including this): " +
+            runningInstances +
+            " - pending instances: "
+            +
+            pendingInstances);
+
+    }
+
+    @Override
+    public void destroy() {
+        appDomainContexts.clear();
+        log.debug("Cleared AppDomainContext Map.");
+    }
+
+    /**
+     * This is method that gets called periodically when the task runs.
+     * <p/>
+     * The exact sequence of execution is shown in this method.
+     */
+    @Override
+    public void execute() {
+
+        appDomainContexts =
+            AutoscaleUtil.getAppDomainContexts(
+                AutoscalerTaskDSHolder.getInstance().getConfigCtxt(),
+                loadBalancerConfig);
+
+        if (isTaskRunning) {
+            log.debug("Task is already running!");
+            return;
+        }
+        try {
+            isTaskRunning = true;
+            setIsPrimaryLB();
+            if (!isPrimaryLoadBalancer) {
+                log.debug("This is not the primary load balancer, hence will not " +
+                        "perform any sanity check.");
+                return;
+            }
+            sanityCheck();
+            autoscale();
+        } finally {
+            // if there are any changes in the request length
+            if (Boolean.parseBoolean(System.getProperty(AutoscaleConstants.IS_TOUCHED))) {
+                // primary LB will send out replication message to all load balancers
+                sendReplicationMessage();
+            }
+            isTaskRunning = false;
+            log.debug("Task finished a cycle.");
+        }
+    }
+
+    @Override
+    public void init(final SynapseEnvironment synEnv) {
+
+        String msg = "Autoscaler Service initialization failed and cannot proceed.";
+
+        loadBalancerConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+
+        if (loadBalancerConfig == null) {
+            log.error(msg + "Reason: Load balancer configuration is null.");
+            throw new RuntimeException(msg);
+        }
+
+        ConfigurationContext configCtx = ((Axis2SynapseEnvironment) synEnv).getAxis2ConfigurationContext();
+        AutoscalerTaskDSHolder.getInstance().setConfigCtxt(configCtx);
+
+        appDomainContexts = AutoscaleUtil.getAppDomainContexts(configCtx, loadBalancerConfig);
+        
+        AutoscalerTaskDSHolder.getInstance().setAgent(configCtx.getAxisConfiguration().getClusteringAgent());
+
+        boolean useEmbeddedAutoscaler = loadBalancerConfig.getLoadBalancerConfig().useEmbeddedAutoscaler();
+        
+        try {
+
+            if(useEmbeddedAutoscaler){
+                autoscalerService = new CloudControllerOsgiClient();
+            } else{
+                autoscalerService = new CloudControllerStubClient();
+            }
+            // let's initialize the auto-scaler service
+            autoscalerService.init();
+
+        }catch (Exception e) {
+            log.error(msg, e);
+            throw new RuntimeException(msg, e);
+        }
+
+        if (log.isDebugEnabled()) {
+
+            log.debug("Autoscaler task is initialized.");
+
+        }
+    }
+
+    /**
+     * Sanity check to see whether the number of LBs is the number specified in the LB config
+     */
+    private void loadBalancerSanityCheck() {
+
+        log.debug("Load balancer sanity check has started.");
+
+        // get current LB instance count
+        int currentLBInstances = lbContext.getInstances();
+
+        LoadBalancerConfiguration.LBConfiguration lbConfig =
+            loadBalancerConfig.getLoadBalancerConfig();
+
+        // get minimum requirement of LB instances
+        int requiredInstances = lbConfig.getInstances();
+
+        if (currentLBInstances < requiredInstances) {
+            log.debug("LB Sanity check failed. Running/Pending LB instances: " + currentLBInstances +
+                ". Required LB instances: " + requiredInstances);
+            int diff = requiredInstances - currentLBInstances;
+
+            // gets the domain of the LB
+            String lbDomain =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getAgent()
+                    .getParameter("domain")
+                    .getValue()
+                    .toString();
+            String lbSubDomain =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getAgent()
+                    .getParameter("subDomain")
+                    .getValue()
+                    .toString();
+
+            // Launch diff number of LB instances
+            log.debug("Launching " + diff + " LB instances.");
+
+            runInstances(lbContext, lbDomain, lbSubDomain, diff);
+        }
+    }
+
+    private int runInstances(final LoadBalancerContext context, final String domain,
+        final String subDomain,
+        int diff) {
+
+        int successfullyStartedInstanceCount = diff;
+
+        while (diff > 0) {
+            // call autoscaler service and ask to spawn an instance
+            // and increment pending instance count only if autoscaler service returns
+            // true.
+            try {
+                String ip = autoscalerService.startInstance(domain, subDomain);
+
+                if (ip == null || ip.isEmpty()) {
+                    log.debug("Instance start up failed. domain: " +
+                        domain +
+                            ", sub domain: " +
+                            subDomain);
+                    successfullyStartedInstanceCount--;
+                } else {
+                    log.debug("An instance of domain: " +
+                        domain +
+                            " and sub domain: " +
+                            subDomain +
+                            " is started up.");
+                    if (context != null) {
+                        context.incrementPendingInstances(1);
+                    }
+                }
+            } catch (Exception e) {
+                log.error("Failed to start an instance of sub domain: " + subDomain +
+                    " of domain : " + domain + ".\n", e);
+                successfullyStartedInstanceCount--;
+            }
+
+            diff--;
+        }
+
+        return successfullyStartedInstanceCount;
+    }
+
+    /**
+     * This method makes sure that the minimum configuration of the clusters in the system is
+     * maintained
+     */
+    private void sanityCheck() {
+
+        if (!isPrimaryLoadBalancer) {
+            log.debug("This is not the primary load balancer, hence will not " +
+                "perform any sanity check.");
+            return;
+        }
+
+        log.debug("This is the primary load balancer, starting to perform sanity checks.");
+
+        computeRunningAndPendingInstances();
+        loadBalancerSanityCheck();
+        appNodesSanityCheck();
+    }
+
+    /**
+     * Replicate information needed to take autoscaling decision for other ELBs
+     * in the cluster.
+     */
+    private void sendReplicationMessage() {
+
+        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
+        if (clusteringAgent != null) {
+            RequestTokenReplicationCommand msg = new RequestTokenReplicationCommand();
+            msg.setAppDomainContexts(appDomainContexts);
+            try {
+                clusteringAgent.sendMessage(msg, true);
+                System.setProperty(AutoscaleConstants.IS_TOUCHED, "false");
+                log.debug("Request token replication messages sent out successfully!!");
+
+            } catch (ClusteringFault e) {
+                log.error("Failed to send the request token replication message.", e);
+            }
+        }
+        else {
+            log
+                .debug("Clustering Agent is null. Hence, unable to send out the replication message.");
+        }
+    }
+
+    /**
+     * This method will check whether this LB is the primary LB or not and set
+     * attribute accordingly.
+     */
+    private void setIsPrimaryLB() {
+
+        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
+        if (clusteringAgent != null) {
+
+            isPrimaryLoadBalancer = clusteringAgent.isCoordinator();
+
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
new file mode 100644
index 0000000..273be34
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
@@ -0,0 +1,185 @@
+/**
+ * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed 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.task;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskDescriptionRepository;
+import org.apache.synapse.task.TaskScheduler;
+import org.wso2.carbon.task.TaskManager;
+
+import java.util.Iterator;
+import java.util.Map;
+
+public class TaskSchedulingManager {
+
+    private static final Log log = LogFactory.getLog(TaskSchedulingManager.class);
+
+    private static TaskSchedulingManager thisInstance = new TaskSchedulingManager();
+
+    public static TaskSchedulingManager getInstance() {
+        return thisInstance;
+    }
+
+    /**
+     * This method adds a particular Task to the Task Description Repository and schedule it
+     * for the execution.
+     *
+     * @param taskDescription      TaskDescription
+     * @param resources            Map containing require meta data for the task execution.
+     * @param configurationContext ConfigurationContext
+     */
+    public void scheduleTask(TaskDescription taskDescription, Map<String, Object> resources,
+                             ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding a Task Description to the Task Description Repository");
+        }
+
+        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
+        getTaskScheduler(configurationContext).scheduleTask(
+                taskDescription, resources, AutoscalingJob.class);
+
+        if (log.isDebugEnabled()) {
+            log.debug("Task Description " + taskDescription.getName() +
+                    " added to the Task Description Repository");
+        }
+    }
+
+    /**
+     * Returns a Task Description with a given name from the Task Description Repository.
+     *
+     * @param taskName             taskName
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescription
+     */
+    public TaskDescription getTaskDescription(
+            String taskName, ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Returning a Start up : " + taskName + " from the configuration");
+        }
+
+        TaskDescription taskDescription = getTaskDescriptionRepository(
+                configurationContext).getTaskDescription(taskName);
+
+        if (taskDescription != null) {
+            if (log.isDebugEnabled()) {
+                log.debug("Returning a Task Description : " + taskDescription);
+
+            }
+            return taskDescription;
+        } else {
+            if (log.isDebugEnabled()) {
+                log.debug("No Task Description can be found with name :" + taskName);
+            }
+            return null;
+        }
+    }
+
+    /**
+     * This method search for a given Task which has already been added to the Task Description
+     * Repository and removes it.
+     *
+     * @param taskDescription             TaskDescription
+     * @param configurationContext ConfigurationContext
+     */
+    public void deleteTaskDescription(TaskDescription taskDescription, ConfigurationContext configurationContext) {
+        String taskName = null;
+        if (taskDescription != null) {
+            taskName = taskDescription.getName();
+            getTaskDescriptionRepository(configurationContext).removeTaskDescription(taskName);
+            getTaskScheduler(configurationContext).deleteTask(taskName, taskDescription.getGroup());
+
+            if (log.isDebugEnabled()) {
+                log.debug("Deleted TaskDescription : " + taskName + " from the configuration");
+            }
+        } else {
+            log.warn("Unable to delete the Task " + taskName
+                    + ",as it doesn't exist in the Repository");
+        }
+    }
+
+    /**
+     * Retrieves all Task Descriptions added to the Task Description Repository at a given instance.
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescription Iterator
+     */
+    public Iterator<TaskDescription> getAllTaskDescriptions(
+            ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Returning a All TaskDescription from the configuration");
+        }
+        return getTaskDescriptionRepository(configurationContext).getAllTaskDescriptions();
+    }
+
+    /**
+     * This method checks whether a particular Task has already been added to the Task Description
+     * Repository associated with the context of this execution and returns a flag indicating the
+     * existence.
+     *
+     * @param taskName             Name of the task to be searched
+     * @param configurationContext ConfigurationContext
+     * @return a boolean depending on the existence of a task
+     */
+    public boolean isContains(String taskName, ConfigurationContext configurationContext) {
+        return !getTaskDescriptionRepository(configurationContext).isUnique(taskName);
+    }
+
+    /**
+     * Returns the Carbon TaskDescriptionRepository instance that carries details of the added
+     * tasks for execution.
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescriptionRepository
+     */
+    private synchronized TaskDescriptionRepository getTaskDescriptionRepository(
+            ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Retrieving access to Task Description Repository");
+        }
+        return (TaskDescriptionRepository) configurationContext.getProperty(
+                TaskManager.CARBON_TASK_REPOSITORY);
+    }
+
+    /**
+     * Returns the carbon TaskScheduler associated with the context of scheduling the task execution
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskScheduler
+     */
+    private synchronized TaskScheduler getTaskScheduler(ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Retrieving access to Task Scheduler");
+        }
+        return (TaskScheduler) configurationContext.getProperty(
+                TaskManager.CARBON_TASK_SCHEDULER);
+    }
+
+    public void shutDown(ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Starting to shut down tasks");
+        }
+
+//        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
+        getTaskScheduler(configurationContext).shutDown();
+
+        if (log.isDebugEnabled()) {
+            log.debug("All tasks shut down");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
new file mode 100644
index 0000000..9c21b0f
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
@@ -0,0 +1,65 @@
+/*                                                                             
+ * Copyright 2004,2005 The Apache Software Foundation.                         
+ *                                                                             
+ * Licensed 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.util;
+
+/**
+ * Constants
+ */
+public final class AutoscaleConstants {
+    public static final String REQUEST_ID = "request.id";
+    public static final String APP_DOMAIN_CONTEXTS = "autoscale.app.domain.contexts";
+    public static final String TARGET_DOMAIN = "autoscale.target.domain";
+    public static final String TARGET_SUB_DOMAIN = "autoscale.target.sub.domain";
+    public static final String LOAD_BALANCER_CONFIG = "loadbalancer.conf";
+    
+    /**
+     * we use this to track the changes happen to request token list lengths.
+     */
+    public static final String IS_TOUCHED = "is_touched";
+    
+    /**
+     * We'll check whether a server is started up in every this much of time.
+     * (in milliseconds)
+     */
+    public static final int SERVER_START_UP_CHECK_TIME = 30000;
+    
+    /**
+     * We'll check whether an instance is left the cluster in every this much of time.
+     * (in milliseconds)
+     */
+    public static final int INSTANCE_REMOVAL_CHECK_TIME = 5000;
+
+    /**
+     * Name of the EC2 instance tag which if set on an instance, the autoscaler will not
+     * terminate such instance
+     */
+    public static final String AVOID_TERMINATION = "avoidTermination";
+
+    public static enum InstanceState {
+        RUNNING("running"), PENDING("pending"), TERMINATED("terminated"), SHUTTING_DOWN("shutting-down");
+
+        private String state;
+
+        InstanceState(String state) {
+            this.state = state;
+        }
+
+        public String getState() {
+            return state;
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
new file mode 100644
index 0000000..894203d
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
@@ -0,0 +1,356 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.util;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.protocol.HTTP;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+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.PendingInstancesStateChecker;
+import org.apache.axiom.om.util.Base64;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Utility methods for Autoscale mediator
+ */
+public final class AutoscaleUtil {
+
+    private static final Log log = LogFactory.getLog(AutoscaleUtil.class);
+
+    private AutoscaleUtil() {
+    }
+
+    /**
+     * handles the exception
+     *
+     * @param msg exception message
+     */
+    public static void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+    /**
+     * handles the exception
+     *
+     * @param msg exception message
+     * @param e   exception
+     */
+    public static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+    /**
+     * Returns the contents of the file in a byte array
+     *
+     * @param file - Input File
+     * @return Bytes from the file
+     * @throws java.io.IOException, if retrieving the file contents failed.
+     */
+    public static byte[] getBytesFromFile(File file) throws IOException {
+        if (!file.exists()) {
+            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
+            return null;
+        }
+        InputStream is = new FileInputStream(file);
+        byte[] bytes;
+
+        try {
+            // Get the size of the file
+            long length = file.length();
+
+            // You cannot create an array using a long type.
+            // It needs to be an int type.
+            // Before converting to an int type, check
+            // to ensure that file is not larger than Integer.MAX_VALUE.
+            if (length > Integer.MAX_VALUE) {
+                if (log.isDebugEnabled()) {
+                    log.debug("File is too large");
+                }
+            }
+
+            // Create the byte array to hold the data
+            bytes = new byte[(int) length];
+
+            // Read in the bytes
+            int offset = 0;
+            int numRead;
+            while (offset < bytes.length
+                   && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
+                offset += numRead;
+            }
+
+            // Ensure all the bytes have been read in
+            if (offset < bytes.length) {
+                throw new IOException("Could not completely read file " + file.getName());
+            }
+        } finally {
+            // Close the input stream and return bytes
+            is.close();
+        }
+
+        return bytes;
+    }
+
+    /**
+     * Replaces the variables
+     *
+     * @param text input string
+     * @return output String
+     */
+    public static String replaceVariables(String text) {
+        int indexOfStartingChars;
+        int indexOfClosingBrace;
+
+        // The following condition deals with properties.
+        // Properties are specified as ${system.property},
+        // and are assumed to be System properties
+        if ((indexOfStartingChars = text.indexOf("${")) != -1 &&
+            (indexOfClosingBrace = text.indexOf("}")) != -1) { // Is a property used?
+            String var = text.substring(indexOfStartingChars + 2,
+                                        indexOfClosingBrace);
+
+            String propValue = System.getProperty(var);
+            if (propValue == null) {
+                propValue = System.getenv(var);
+            }
+            if (propValue != null) {
+                text = text.substring(0, indexOfStartingChars) + propValue +
+                       text.substring(indexOfClosingBrace + 1);
+            }
+        }
+        return text;
+    }
+
+/*    public static InstanceManager createEC2InstanceManager(String accessKey,
+                                                              String secretKey,
+                                                              String instanceMgtEPR) {
+        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
+        AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
+        ec2Client.setEndpoint(instanceMgtEPR);
+        return new InstanceManager(ec2Client);
+    }*/
+
+    public static String getUserData(String payloadFileName) {
+        String userData = null;
+        try {
+            File file = new File(payloadFileName);
+            if (!file.exists()) {
+                handleException("Payload file " + payloadFileName + " does not exist");
+            }
+            if (!file.canRead()) {
+                handleException("Payload file " + payloadFileName + " does cannot be read");
+            }
+            byte[] bytes = AutoscaleUtil.getBytesFromFile(file);
+            if (bytes != null) {
+//                /BASE64.e encoder = new BASE64Encoder();
+                userData = Base64.encode(bytes);
+            }
+        } catch (IOException e) {
+            AutoscaleUtil.handleException("Cannot read data from payload file " + payloadFileName,
+                                          e);
+        }
+        return userData;
+    }
+
+    /*public static boolean areEqual(List<GroupIdentifier> securityGroups1, String[] sourceGroups2) {
+        for (String sourceGroup : sourceGroups2) {
+            boolean isSourceGroupFound = false;
+            for (GroupIdentifier securityGroup : securityGroups1) {
+                if (securityGroup.getGroupName().equals(sourceGroup)) {
+                    isSourceGroupFound = true;
+                }
+            }
+            if (!isSourceGroupFound) {
+                return false;
+            }
+        }
+        return true;
+    } */
+
+    /**
+     * TODO These methods should use to common place since these are using endpoints and mediators
+     */
+    public static int getTenantId(String url) {
+        String address = url;
+        String servicesPrefix = "/t/";
+        if (address != null && address.contains(servicesPrefix)) {
+            int domainNameStartIndex =
+                    address.indexOf(servicesPrefix) + servicesPrefix.length();
+            int domainNameEndIndex = address.indexOf('/', domainNameStartIndex);
+            String domainName = address.substring(domainNameStartIndex,
+                    domainNameEndIndex == -1 ? address.length() : domainNameEndIndex);
+            // return tenant id if domain name is not null
+            if (domainName != null) {
+                try {
+                    return AutoscalerTaskDSHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
+                } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                    log.error("An error occurred while obtaining the tenant id.", e);
+                }
+            }
+        }
+        // return 0 if the domain name is null
+        return 0;
+    }
+
+    /**
+     * TODO These methods should use to common place since these are using endpoints and mediators
+     */
+    @SuppressWarnings("unchecked")
+    public static String getTargetHost(MessageContext synCtx) {
+        org.apache.axis2.context.MessageContext axis2MessageContext =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        Map<String, String> headers =
+                (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String address = headers.get(HTTP.TARGET_HOST);
+        if (address.contains(":")) {
+            address = address.substring(0, address.indexOf(":"));
+        }
+        return address;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static Map<String, Map<String, ?>> getAppDomainContexts(ConfigurationContext configCtx,
+ LoadBalancerConfiguration lbConfig) {
+        Map<String, Map<String, ?>> oldAppDomainContexts =
+        	(Map<String, Map<String, ?>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
+        Map<String, Map<String, ?>> newAppDomainContexts = new HashMap<String, Map<String, ?>>();
+        
+            ClusteringAgent clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
+
+            for (String domain : lbConfig.getServiceDomains()) {
+
+                for (String subDomain : lbConfig.getServiceSubDomains(domain)) {
+                    if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+                        throw new SynapseException("Axis2 clustering GroupManagementAgent for domain: " + domain +
+                                                   ", sub-domain: " + subDomain +
+                                                   " has not been defined");
+                    }
+
+                    if(oldAppDomainContexts == null || oldAppDomainContexts.get(domain) == null || 
+                    		(oldAppDomainContexts.get(domain) != null && oldAppDomainContexts.get(domain).get(subDomain) == null)){
+                    	
+                    	AppDomainContext appCtxt = new AppDomainContext(lbConfig.getServiceConfig(domain,
+                                subDomain));
+
+                    	addAppDomainContext(newAppDomainContexts, domain, subDomain, appCtxt);
+                    	
+                    } else {
+                        addAppDomainContext(newAppDomainContexts, domain, subDomain, (AppDomainContext) oldAppDomainContexts.get(domain).get(subDomain));
+                    }
+                    
+                }
+
+            }
+//        }
+        configCtx.setNonReplicableProperty(AutoscaleConstants.APP_DOMAIN_CONTEXTS,
+                                           newAppDomainContexts);
+
+        return newAppDomainContexts;
+    }
+    
+    
+    private static void addAppDomainContext(Map<String, Map<String, ?>> appDomainContexts,
+                                     String domain, String subDomain, AppDomainContext appCtxt) {
+
+        Map<String, AppDomainContext> map ;
+        
+        if(appDomainContexts.containsKey(domain)){
+            map = (Map<String, AppDomainContext>) appDomainContexts.get(domain);
+        }
+        else{
+            map = new HashMap<String, AppDomainContext>();
+        }
+        // put this appDomainContext
+        map.put(subDomain, appCtxt);
+        
+        // update the parent map
+        appDomainContexts.put(domain, map);
+        
+    }
+    
+    public static String domainSubDomainString(String domain, String subDomain){
+        return "Domain: "+domain+" - Sub Domain: "+subDomain;
+    }
+    
+    public static int runInstances(final CloudControllerClient client, final LoadBalancerContext context, final String domain,
+        final String subDomain, int diff) {
+
+        int successfullyStartedInstanceCount = diff;
+
+        if(context == null){
+            // can't help
+            return 0;
+        }
+        
+        while (diff > 0) {
+            // call autoscaler service and ask to spawn an instance
+            // and increment pending instance count only if autoscaler service returns
+            // true.
+            try {
+                String ip = client.startInstance(domain, subDomain);
+
+                if (ip == null || ip.isEmpty()) {
+                    log.debug("Instance start up failed for " + domainSubDomainString(domain, subDomain));
+                    successfullyStartedInstanceCount--;
+                    
+                } else {
+                    log.debug("An instance of " + domainSubDomainString(domain, subDomain) +
+                        " is started up.");
+                    if (context != null) {
+                        context.incrementPendingInstances(1);
+                    }
+                }
+            } catch (Exception e) {
+                log.error("Failed to start an instance of " + domainSubDomainString(domain, subDomain) + ".\n", e);
+                successfullyStartedInstanceCount--;
+            }
+
+            diff--;
+        }
+
+        if (successfullyStartedInstanceCount > 0) {
+            
+            Thread stateChecker =
+                new Thread(new PendingInstancesStateChecker(
+                    context,
+                    domain,
+                    subDomain,
+                    successfullyStartedInstanceCount,
+                    context.getRunningInstanceCount(),
+                    client));
+            stateChecker.start();
+        }
+
+        return successfullyStartedInstanceCount;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
new file mode 100644
index 0000000..c896232
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
@@ -0,0 +1,128 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. 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.util;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.LBConfiguration;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * Singleton class to hold Agent Management Service
+ */
+public class AutoscalerTaskDSHolder {
+    
+    private ConfigurationContextService configurationContextService;
+    private LoadBalancerConfiguration wholeLbConfig;
+    private CloudControllerService cloudControllerService;  
+
+    private RealmService realmService;
+    private ClusteringAgent agent;
+    private ConfigurationContext configCtxt;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+
+    private static AutoscalerTaskDSHolder instance = new AutoscalerTaskDSHolder();
+
+    private AutoscalerTaskDSHolder(){
+
+    }
+
+    public static AutoscalerTaskDSHolder getInstance(){
+        return instance;
+    }
+
+    public ConfigurationContextService getConfigurationContextServiceService(){
+        return this.configurationContextService;
+    }
+
+    public void setConfigurationContextService(ConfigurationContextService cCtxService){
+        this.configurationContextService = cCtxService;
+    }
+    
+    public LoadBalancerConfiguration getWholeLoadBalancerConfig() {
+        return wholeLbConfig;
+    }
+    
+    public LBConfiguration getLoadBalancerConfig() {
+        return wholeLbConfig.getLoadBalancerConfig();
+    }
+
+    public ClusteringAgent getAgent() {
+        return agent;
+    }
+
+    public void setAgent(ClusteringAgent agent) {
+        this.agent = agent;
+    }
+
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+    
+    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
+        if (lbConfigSer != null) {
+            this.wholeLbConfig = (LoadBalancerConfiguration) lbConfigSer.getLoadBalancerConfig();
+        } else {
+            this.wholeLbConfig = null;
+        }
+    }
+
+	public void setConfigCtxt(ConfigurationContext configCtxt) {
+		this.configCtxt = configCtxt;
+	}
+
+	public ConfigurationContext getConfigCtxt() {
+		return configCtxt;
+	}
+
+	public void setCloudControllerService(CloudControllerService cc) {
+        this.cloudControllerService = cc;
+    }
+	
+	public CloudControllerService getCloudControllerService() {
+        return cloudControllerService;
+    }
+
+	public UserRegistry getConfigRegistry() {
+        return configRegistry;
+    }
+
+    public void setConfigRegistry(UserRegistry configRegistry) {
+        this.configRegistry = configRegistry;
+    }
+    
+    public UserRegistry getGovernanceRegistry() {
+        return governanceRegistry;
+    }
+
+    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
+        this.governanceRegistry = governanceRegistry;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
new file mode 100644
index 0000000..399d502
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
@@ -0,0 +1,2 @@
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorFactory
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorFactory

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
new file mode 100644
index 0000000..05fce78
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
@@ -0,0 +1,2 @@
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorSerializer
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorSerializer
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
new file mode 100644
index 0000000..f8ecf6f
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
@@ -0,0 +1,138 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. 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.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+
+    <task class="org.wso2.carbon.mediator.autoscale2.LoadAverageBasedEC2LoadAnalyzerTask"
+          name="LoadAnalyzer">
+
+
+        <!--
+            The private key for the ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for the ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+
+        <!--
+            The amazon instance type for the load balanced service instances.
+            Recommended and the default is m1.large.
+        -->
+        <property name="instanceType" value="m1.large"/>
+
+        <!--
+            The amazon instance type for the instances of the load balancer itself.
+            Default is m1.large. Can be changed to m1.small too.
+        -->
+        <property name="loadBalancerInstanceType" value="m1.large"/>
+
+        <!--
+            The group of the service being load balanced.
+        -->
+        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
+
+        <!--
+            The group of the load balancer.
+        -->
+        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
+
+        <!--
+            The Amazon availability zone for the instances. 1-c is given as the default
+        -->
+        <property name="availabilityZone" value="us-east-1c"/>
+
+        <!--
+            Additional information for the amazon instances
+        -->
+        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
+
+        <!--
+            The key pair
+        -->
+        <property name="key" value="stratos-1.0.0-keypair"/>
+
+        <!--
+            The service payload file which should be loaded to the bucket
+        -->
+        <property name="applicationPayload" value="resources/cluster_node.zip"/>
+
+        <!--
+            The load balancer payload file which should be loaded to the bucket
+        -->
+        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
+
+        <!--
+            The elasticIP property can be overriden by the ELASTIC_IP environment var,
+             which is set in the payload
+        -->
+        <property name="elasticIP" value="${ELASTIC_IP}"/>
+
+        <!--
+            The minimum and maximum limits of the load balanced service instances
+        -->
+        <property name="minAppInstances" value="1"/>
+        <property name="maxAppInstances" value="5"/>
+
+        <!--
+            The minimum and maximum limits of the load balancer instances
+        -->
+        <property name="minLoadBalancerInstances" value="1"/>
+
+        <property name="roundsToAverage" value="10"/>
+
+        <!--
+            The instances spawned at once, per scaling up decision.
+	    Default and the recommended value is 1
+        -->
+        <property name="instancesPerScaleUp" value="1"/>
+
+        <!--
+            The low and high limits of the load average
+        -->
+        <property name="loadAverageLowerLimit" value="2"/>
+        <property name="loadAverageHigherLimit" value="5"/>
+
+        <!--
+            The Load Balanced Service Ports
+        -->
+        <property name="serviceHttpPort" value="9763"/>
+        <property name="serviceHttpsPort" value="9443"/>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
new file mode 100644
index 0000000..3e66066
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
@@ -0,0 +1,135 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. 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.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+
+    <task class="org.wso2.carbon.mediator.autoscale2.MessagesInFlightBasedEC2LoadAnalyzerTask"
+          name="LoadAnalyzer">
+
+
+        <!--
+            The private key for the ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for the ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+
+        <!--
+            The amazon instance type for the load balanced service instances.
+            Recommended and the default is m1.large.
+        -->
+        <property name="instanceType" value="m1.large"/>
+
+        <!--
+            The amazon instance type for the instances of the load balancer itself.
+            Default is m1.large. Can be changed to m1.small too.
+        -->
+        <property name="loadBalancerInstanceType" value="m1.large"/>
+
+        <!--
+            The group of the service being load balanced.
+        -->
+        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
+
+        <!--
+            The group of the load balancer.
+        -->
+        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
+
+        <!--
+            The Amazon availability zone for the instances. 1-c is given as the default
+        -->
+        <property name="availabilityZone" value="us-east-1c"/>
+
+        <!--
+            Additional information for the amazon instances
+        -->
+        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
+
+        <!--
+            The key pair
+        -->
+        <property name="key" value="stratos-1.0.0-keypair"/>
+
+        <!--
+            The service payload file which should be loaded to the bucket
+        -->
+        <property name="applicationPayload" value="resources/cluster_node.zip"/>
+
+        <!--
+            The load balancer payload file which should be loaded to the bucket
+        -->
+        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
+
+        <!--
+            The elasticIP property can be overriden by the ELASTIC_IP environment var,
+             which is set in the payload
+        -->
+        <property name="elasticIP" value="${ELASTIC_IP}"/>
+
+        <!--
+            The time in milliseconds which the message takes to expire
+        -->
+        <property name="messageExpiryTime" value="60000"/>
+
+        <!--
+            The minimum and maximum limits of the load balanced service instances
+        -->
+        <property name="minAppInstances" value="1"/>
+        <property name="maxAppInstances" value="5"/>
+
+        <!--
+            The number of load balancer instances
+        -->
+        <property name="loadBalancerInstances" value="1"/>
+
+        <!--
+            The given queue length per node, for the calculation in scaling up
+        -->
+        <property name="queueLengthPerNode" value="400"/>
+        <property name="roundsToAverage" value="10"/>
+
+        <!--
+            The instances spawned at once, per scaling up decision.
+	    Default and the recommended value is 1
+        -->
+        <property name="instancesPerScaleUp" value="1"/>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>