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:51 UTC
[01/10] committing org.apache.stratos.mediator.autoscale
Updated Branches:
refs/heads/master 3b2cf6c20 -> 290c63075
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java
deleted file mode 100644
index cdde5e6..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.conf.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-//public class TenantDomainRangeContext {
-//
-// private static final Log log = LogFactory.getLog(TenantDomainRangeContext.class);
-//
-// /**
-// * Map is used instead of using a list, in order to minimize the lookup time.
-// * key - host name
-// * Value - A map with tenant id as key and TenantDomainContext object as value
-// */
-// private Map<String, Map<Integer, TenantDomainContext>> tenantDomainContextMap = new HashMap<String, Map<Integer, TenantDomainContext>>();
-//
-// /**
-// * This method will populate the {@link #tenantDomainContextMap} with <code>TenantDomainContext</code>
-// * objects created for all the tenants covered by the given range.
-// */
-// public void addTenantDomain(String domain, String subDomain, String tenantRange) {
-//
-// String msg = "Invalid tenant range is specified for domain " + domain+" - sub domain "+subDomain;
-//
-// String[] parsedLine = tenantRange.trim().split("-");
-//
-// if (parsedLine[0].equalsIgnoreCase("*")) {
-//
-// tenantDomainContextMap.put(0, new TenantDomainContext(0, domain, subDomain));
-//
-// } else if (parsedLine.length == 1) {
-//
-// try {
-//
-// int tenantId = Integer.parseInt(tenantRange);
-//
-// tenantDomainContextMap.put(tenantId, new TenantDomainContext(tenantId, domain, subDomain));
-//
-// } catch (NumberFormatException e) {
-//
-// log.error(msg, e);
-// throw new RuntimeException(msg, e);
-// }
-//
-// } else if (parsedLine.length == 2) {
-//
-// try {
-// int startIndex = Integer.parseInt(parsedLine[0]);
-// int endIndex = Integer.parseInt(parsedLine[1]);
-//
-// for (int tenantId = startIndex; tenantId <= endIndex; tenantId++) {
-//
-// tenantDomainContextMap.put(tenantId, new TenantDomainContext(tenantId, domain, subDomain));
-//
-// }
-// } catch (NumberFormatException e) {
-// log.error(msg, e);
-// throw new RuntimeException(msg, e);
-// }
-//
-// } else {
-// log.error(msg);
-// throw new RuntimeException(msg);
-// }
-//
-// }
-//
-//// private void addToTenantDomainRangeContextMap(
-//// String domain, String subDomain,
-//// String tenantRange) {
-////
-//// Map<String, String> map ;
-////
-//// if(tenantDomainRangeContextMap.containsKey(domain)){
-//// map = tenantDomainRangeContextMap.get(domain);
-//// }
-//// else{
-//// map = new HashMap<String, String>();
-//// }
-//// // put this tenant range
-//// map.put(subDomain, tenantRange);
-////
-//// // update the parent map
-//// tenantDomainRangeContextMap.put(domain, map);
-//// }
-////
-//// public Map<Integer, String> getTenantIDClusterDomainMap() {
-//// return this.tenantIDClusterDomainMap;
-//// }
-////
-//// public Map<Integer, String> getTenantIDClusterSubDomainMap() {
-//// return this.tenantIDClusterSubDomainMap;
-//// }
-//
-// /**
-// * Given a tenant id, this will return its domain.
-// * @param id tenant id
-// * @return domain which this tenant belongs to.
-// */
-// public String getClusterDomainFromTenantId(int id) {
-//
-// if(tenantDomainContextMap.get(id) == null){
-// // if there's no specific domain for this tenant, we will redirect it to the default cluster
-// return tenantDomainContextMap.get(0).getDomain();
-// }
-//
-// return tenantDomainContextMap.get(id).getDomain();
-//
-// }
-//
-// /**
-// * Given a tenant id, this will return its sub domain.
-// * @param id tenant id
-// * @return sub domain which this tenant belongs to.
-// */
-// public String getClusterSubDomainFromTenantId(int id) {
-//
-// if(tenantDomainContextMap.get(id) == null){
-// // if there's no specific domain for this tenant, we will redirect it to the default cluster
-// return tenantDomainContextMap.get(0).getSubDomain();
-// }
-//
-// return tenantDomainContextMap.get(id).getSubDomain();
-// }
-//
-// public Map<Integer, TenantDomainContext> getTenantDomainContextMap() {
-// return tenantDomainContextMap;
-// }
-//}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
deleted file mode 100644
index 570a5d7..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.group.mgt;
-
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.DefaultGroupManagementAgent;
-import org.apache.synapse.endpoints.dispatch.SALSessions;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-
-/**
- * This GroupManagementAgent can handle group membership based on cluster sub-domains.
- */
-public class SubDomainAwareGroupManagementAgent extends DefaultGroupManagementAgent {
-
- private String subDomain;
-
- public SubDomainAwareGroupManagementAgent(String subDomain) {
- this.subDomain = subDomain;
- }
-
- @Override
- public void applicationMemberAdded(Member member) {
- String subDomain = member.getProperties().getProperty("subDomain");
- if ((subDomain == null && Constants.DEFAULT_SUB_DOMAIN.equals(this.subDomain)) ||
- subDomain.equals(this.subDomain)) {
- super.applicationMemberAdded(member);
- }
- }
-
- @Override
- public void applicationMemberRemoved(Member member) {
-
- // remove the sessions bound with this member
- SALSessions.getInstance().removeSessionsOfMember(member);
-
- String subDomain = member.getProperties().getProperty("subDomain");
- if ((subDomain == null && Constants.DEFAULT_SUB_DOMAIN.equals(this.subDomain)) ||
- subDomain.equals(this.subDomain)) {
- super.applicationMemberRemoved(member);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java
deleted file mode 100644
index 24562f5..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.wso2.carbon.lb.common.replication;
-
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.clustering.ClusteringMessage;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.util.Map;
-
-/**
- * This is the notification message a primary load balancer will send to all other load balancers
- * in the cluster, to replicate its state. When the other load balancers received this message,
- * they will set their states to the state of primary load balancer.
- */
-public class RequestTokenReplicationCommand extends ClusteringMessage {
-
- private static final long serialVersionUID = -7897961078018830555L;
- private static final Log log = LogFactory.getLog(RequestTokenReplicationCommand.class);
- private Map<String, Map<String, ?>> appDomainContexts;
-
- public Map<String, Map<String, ?>> getAppDomainContexts() {
- return appDomainContexts;
- }
-
- public void setAppDomainContexts(Map<String, Map<String, ?>> appDomainContexts) {
- this.appDomainContexts = appDomainContexts;
- }
-
- public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
- // set the appDomainContexts map
- configurationContext.setNonReplicableProperty("autoscale.app.domain.contexts",
- getAppDomainContexts());
-
- log.info("Request Tokens Replicated! ");
- }
-
- public String toString() {
- return "Replication message sent!";
- }
-
- @Override
- public ClusteringCommand getResponse() {
- return new ClusteringCommand() {
-
- private static final long serialVersionUID = -8271265673996681347L;
-
- @Override
- public void execute(ConfigurationContext arg0) throws ClusteringFault {
- // do nothing
- }
- };
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java
deleted file mode 100644
index 9499b20..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.service;
-
-import java.util.Map;
-
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-
-/**
- * This service provides a way to consume details in loadbalancer.conf file.
- * Also to update the runtime object model of loadbalancer conf.
- */
-public interface LoadBalancerConfigurationService {
-
- /**
- * Provides a reference to the runtime object model of loadbalancer.conf
- * @return {@link Object} which is an instance of {@link LoadBalancerConfiguration}
- */
- public Object getLoadBalancerConfig();
-
-// /**
-// * Return a {@link Map} of {@link HostContext} objects, built using the given config.
-// * @param config service configuration.
-// * @return {@link Map} {@link Object}
-// */
-// public Object getHostContext(String config);
-
- /**
- * Return a {@link Map} of {@link HostContext} objects, built using the given configuration.
- * @param config service configuration diff. This can be in following format.
- *
- * <p/>
- * appserver {
- * hosts appserver.cloud-test.wso2.com;
- * domains {
- * wso2.as1.domain {
- * tenant_range 1-100;
- * }
- * wso2.as2.domain {
- * tenant_range 101-200;
- * }
- * wso2.as3.domain {
- * tenant_range *;
- * }
- * }
- * }
- * <p/>
- * esb {
- * hosts esb.cloud-test.wso2.com;
- * domains {
- * wso2.esb.domain {
- * tenant_range *;
- * }
- * }
- * }
- * <p/>
- * @return a {@link Map} of {@link HostContext} objects.
- * key - host name
- * Value - {@link HostContext}
- */
- public Object getHostContexts(String config) ;
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
deleted file mode 100644
index 532c94d..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.service.impl;
-
-import java.util.Map;
-
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.structure.Node;
-import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
-import com.google.common.collect.MapDifference;
-import com.google.common.collect.Maps;
-
-public class LoadBalancerConfigurationServiceImpl implements LoadBalancerConfigurationService {
-
- @Override
- public Object getLoadBalancerConfig() {
- return LoadBalancerConfiguration.getInstance();
- }
-
- @Override
- public Object getHostContexts(String config) {
-
- // build a Node object for whole loadbalancer.conf
- Node rootNode = new Node();
- rootNode.setName(Constants.SERVICES_ELEMENT);
- rootNode = NodeBuilder.buildNode(rootNode, config);
-
- Map<String, HostContext> oldMap = LoadBalancerConfiguration.getInstance().getHostContextMap();
- LoadBalancerConfiguration.getInstance().createServicesConfig(rootNode);
-
-// MapDifference<String, HostContext> diff = Maps.difference(LoadBalancerConfiguration.getInstance().getHostContextMap(),
-// oldMap );
-//
-// return diff.entriesOnlyOnLeft();
- return LoadBalancerConfiguration.getInstance().getHostContextMap();
- }
-
-// @Override
-// public Object getHostContext(String config) {
-// return null;
-// }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java
deleted file mode 100644
index d543b05..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.wso2.carbon.lb.common.util;
-
-/**
- *
- */
-public class DomainMapping {
- private String mapping;
- private String actualHost;
-
- public DomainMapping(String mapping) {
- this.mapping = mapping;
- }
-
- public String getActualHost() {
- return actualHost;
- }
-
- public void setActualHost(String actualHost) {
- this.actualHost = actualHost;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml
deleted file mode 100644
index b50b721..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<serviceGroup>
- <service name="LoadBalancerConfigurationService" scope="application">
- <parameter name="ServiceClass">org.wso2.carbon.lb.common.service.impl.LoadBalancerConfigurationServiceImpl</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/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java
deleted file mode 100644
index c49cf37..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java
+++ /dev/null
@@ -1,267 +0,0 @@
-//package org.wso2.carbon.lb.common.test;
-//
-//import java.sql.SQLException;
-//
-//import org.testng.Assert;
-//import org.testng.annotations.Test;
-//import org.testng.annotations.BeforeMethod;
-//import org.testng.annotations.AfterMethod;
-//import org.testng.annotations.DataProvider;
-//import org.testng.annotations.BeforeClass;
-//import org.testng.annotations.AfterClass;
-//import org.testng.annotations.BeforeTest;
-//import org.testng.annotations.AfterTest;
-//import org.testng.annotations.BeforeSuite;
-//import org.testng.annotations.AfterSuite;
-//import org.wso2.carbon.lb.common.dto.Bridge;
-//import org.wso2.carbon.lb.common.dto.HostMachine;
-//import org.wso2.carbon.lb.common.dto.Zone;
-//
-//import org.apache.commons.logging.Log;
-//import org.apache.commons.logging.LogFactory;
-//import org.wso2.carbon.lb.common.persistence.AgentPersistenceManager;
-//
-///**
-// * This test class is there to test the database access methods. There is a testng.xml to run these
-// * tests as a suit. It's located at test/resources. Currently it is disabled by commenting the class
-// * element at the xml file. Mysql driver dependancy at pom.xml is also disabled and it should be
-// * uncommented to support database activities.
-// */
-//public class AgentPersistenceManagerTest {
-//
-// private static final Log log = LogFactory.getLog(AgentPersistenceManagerTest.class);;
-//
-//// @Test(dataProvider = "dp")
-//// public void f(Integer n, String s) {
-//// }
-// @BeforeMethod
-// public void beforeMethod() {
-// }
-//
-// @AfterMethod
-// public void afterMethod() {
-// }
-//
-//
-// @DataProvider
-// public Object[][] dataProviderForDAO() {
-//
-// String epr = "epr4";
-// String zoneName = "zone1";
-// Bridge[] bridges = new Bridge[3];
-// bridges[0] = new Bridge();
-// bridges[1] = new Bridge();
-// bridges[2] = new Bridge();
-//
-// bridges[0].setBridgeIp("168.192.1.0");
-// bridges[0].setAvailable(true);
-// bridges[0].setCurrentCountIps(0);
-// bridges[0].setMaximumCountIps(100);
-// bridges[0].setNetGateway("net_gateway");
-// bridges[0].setNetMask("net_mask");
-// bridges[0].setHostMachine(epr);
-//
-// bridges[1].setBridgeIp("168.192.2.0");
-// bridges[1].setAvailable(true);
-// bridges[1].setCurrentCountIps(0);
-// bridges[1].setMaximumCountIps(100);
-// bridges[1].setNetGateway("net_gateway");
-// bridges[1].setNetMask("net_mask");
-// bridges[1].setHostMachine(epr);
-//
-// bridges[2].setBridgeIp("168.192.3.0");
-// bridges[2].setAvailable(true);
-// bridges[2].setCurrentCountIps(0);
-// bridges[2].setMaximumCountIps(100);
-// bridges[2].setNetGateway("net_gateway");
-// bridges[2].setNetMask("net_mask");
-// bridges[2].setHostMachine(epr);
-//
-//
-// HostMachine hostMachine = new HostMachine();
-// hostMachine.setAvailable(true);
-// hostMachine.setContainerRoot("ContainerRoot");
-// hostMachine.setIp("ip");
-// hostMachine.setZone(zoneName);
-// hostMachine.setBridges(bridges);
-// hostMachine.setEpr(epr);
-//
-// String[] domains = new String[2];
-// domains[0] = "domian1";
-// domains[1] = "domain2";
-//
-//
-// return new Object[][] {
-// new Object[] { hostMachine, domains },
-// };
-// }
-// @BeforeClass
-// public void beforeClass() {
-// }
-//
-// @AfterClass
-// public void afterClass() {
-// }
-//
-// @BeforeTest
-// public void beforeTest() {
-// }
-//
-// @AfterTest
-// public void afterTest() {
-// }
-//
-// @BeforeSuite
-// public void beforeSuite() {
-// }
-//
-// @AfterSuite
-// public void afterSuite() {
-// }
-//
-//
-//// @Test
-//// public void addContainer() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-//
-// @Test(dataProvider="dataProviderForDAO")
-// public void addZone(HostMachine hostMachine, String[] domains) {
-// AgentPersistenceManager agentPersistenceManager = AgentPersistenceManager.getPersistenceManager();
-// boolean isAdded = false;
-// boolean zoneExists = false;
-// try {
-// zoneExists = agentPersistenceManager.isZoneExist(hostMachine.getZone());
-// if (!zoneExists) {
-// String msg = "Zone does not exists ";
-// System.out.println(msg);
-// Zone zone = new Zone();
-// zone.setName(hostMachine.getZone());
-// zone.setAvailable(true);
-// isAdded = agentPersistenceManager.addZone(zone, domains);
-// } else {
-// String msg = "Zone exist";
-// System.out.println(msg);
-// }
-// } catch (SQLException e) {
-// String msg = "Test failure while adding zone";
-// log.error(msg);
-// }
-// System.out.println("zone added " + isAdded);
-// if(!zoneExists){
-// Assert.assertEquals(isAdded, true);
-// }else{
-// Assert.assertEquals(isAdded, false );
-// }
-// }
-//
-// @Test(dataProvider="dataProviderForDAO")
-// public void addHostMachine(HostMachine hostMachine, String[] domains) {
-//
-//
-//
-// AgentPersistenceManager agentPersistenceManager = AgentPersistenceManager.getPersistenceManager();
-// boolean isAdded = false;
-// try {
-// isAdded = agentPersistenceManager.addHostMachine(hostMachine, domains);
-// } catch (SQLException e) {
-// String msg = "Test failure while adding host machine";
-// log.error(msg);
-// }
-// System.out.println(" HM added " + isAdded);
-// Assert.assertEquals(isAdded, true);
-//
-// }
-//
-// @Test(dataProvider="dataProviderForDAO")
-// public void deleteHostMachine(HostMachine hostMachine) {
-// AgentPersistenceManager agentPersistenceManager = AgentPersistenceManager.getPersistenceManager();
-// boolean isDeleted = false;
-//
-// try {
-// isDeleted = agentPersistenceManager.deleteHostMachine(hostMachine.getEpr());
-// } catch (SQLException e) {
-// String msg = "Test failure while deleting host machine";
-// log.error(msg);
-// }
-//
-// }
-////
-//// @Test
-//// public void addInstance() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//
-////
-//// @Test
-//// public void changeContainerState() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void changeHostMachineAvailability() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void deleteContainer() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-//
-////
-//// @Test
-//// public void getPersistenceManager() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void isDomainExist() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void isHostMachineExist() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void isHostMachinesAvailableInDomain() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void isZoneExist() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void retrieveAgentToContainerRootMap() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void retrieveAvailableContainerInformation() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void retrieveContainerIdToAgentMap() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void retrieveDomainToInstanceIdsMap() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void retrieveInstanceIdToAdapterMap() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-////
-//// @Test
-//// public void updateDomainConfigs() {
-//// throw new RuntimeException("Test not implemented");
-//// }
-//}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java
deleted file mode 100644
index 124d552..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * 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.wso2.carbon.lb.common.test;
-
-import java.io.File;
-import java.util.List;
-
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-
-import junit.framework.TestCase;
-
-public class LoadBalancerConfigurationTest extends TestCase {
-
- private LoadBalancerConfiguration lbConfig ;
- private LoadBalancerConfiguration lbConfig1;
-
-
- @Override
- protected void setUp() throws Exception {
-
- LoadBalancerConfiguration.setInstance(null);
- File f = new File("src/test/resources/loadbalancer.conf");
- System.setProperty("loadbalancer.conf", f.getAbsolutePath());
- lbConfig = LoadBalancerConfiguration.getInstance();
- }
-
- public final void testCreateLoadBalancerConfig() {
-
- LoadBalancerConfiguration.LBConfiguration loadBalancerConfig =
- lbConfig.getLoadBalancerConfig();
-
- assertEquals(1, loadBalancerConfig.getInstances());
- assertEquals(5000, loadBalancerConfig.getAutoscalerTaskInterval());
- assertEquals(15000, loadBalancerConfig.getServerStartupDelay());
- }
-
- public final void testCreateServicesConfig() {
-
- /* Tests relavant to loadbalancer.conf file */
-
- ServiceConfiguration asServiceConfig =
- lbConfig.getServiceConfig("wso2.as1.domain",
- "worker");
-
- assertEquals(1, asServiceConfig.getInstancesPerScaleUp());
- assertEquals(5, asServiceConfig.getMaxAppInstances());
- assertEquals(0, asServiceConfig.getMinAppInstances());
- assertEquals(60000, asServiceConfig.getMessageExpiryTime());
- assertEquals(400, asServiceConfig.getMaxRequestsPerSecond());
- assertEquals(0.65, asServiceConfig.getAlarmingUpperRate());
- assertEquals(10, asServiceConfig.getRoundsToAverage());
- assertEquals("worker", asServiceConfig.getSubDomain());
-
- asServiceConfig = lbConfig.getServiceConfig("wso2.as2.domain", "worker1");
- assertEquals("worker1", asServiceConfig.getSubDomain());
-
- asServiceConfig = lbConfig.getServiceConfig("wso2.esb.domain", "mgt");
- assertEquals("mgt", asServiceConfig.getSubDomain());
-
- assertEquals(2, lbConfig.getHostNamesTracker().keySet().size());
- assertEquals(3, lbConfig.getHostNamesTracker().get("appserver").size());
- assertEquals(2, lbConfig.getHostNamesTracker().get("esb").size());
-
- for (HostContext ctx : lbConfig.getHostContextMap().values()) {
-
- if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
-
- assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
- assertEquals(18, ctx.getTenantDomainContexts().size());
- } else if (ctx.getHostName().equals("as2.cloud-test.wso2.com")) {
- assertEquals("worker", ctx.getSubDomainFromTenantId(2));
- } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
- assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
- }
- }
-
- /* tests relevant to loadbalancer1.conf file */
-
- File f = new File("src/test/resources/loadbalancer2.conf");
- System.setProperty("loadbalancer.conf", f.getAbsolutePath());
-
- LoadBalancerConfiguration.setInstance(null);
- lbConfig1 = LoadBalancerConfiguration.getInstance();
-
- for (HostContext ctx : lbConfig1.getHostContextMap().values()) {
-
- if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
-
- assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
- assertEquals("wso2.as1.domain", ctx.getDomainFromTenantId(5));
- assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(8));
- assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(2));
- assertEquals(4, ctx.getTenantDomainContexts().size());
-
- } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
-
- assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
- }
- }
-
- }
-
- public final void testGetServiceDomains() throws Exception {
-
- setUp();
- String[] serviceDomains = lbConfig.getServiceDomains();
- assertEquals(4, serviceDomains.length);
-
- assertTrue("wso2.as1.domain".equals(serviceDomains[0]) ||
- "wso2.as1.domain".equals(serviceDomains[1]) ||
- "wso2.as1.domain".equals(serviceDomains[2]) ||
- "wso2.as1.domain".equals(serviceDomains[3]));
-
- assertTrue("wso2.as2.domain".equals(serviceDomains[0]) ||
- "wso2.as2.domain".equals(serviceDomains[1]) ||
- "wso2.as2.domain".equals(serviceDomains[2]) ||
- "wso2.as2.domain".equals(serviceDomains[3]));
-
- assertTrue("wso2.as3.domain".equals(serviceDomains[0]) ||
- "wso2.as3.domain".equals(serviceDomains[1]) ||
- "wso2.as3.domain".equals(serviceDomains[2]) ||
- "wso2.as3.domain".equals(serviceDomains[3]));
-
- assertTrue("wso2.esb.domain".equals(serviceDomains[0]) ||
- "wso2.esb.domain".equals(serviceDomains[1]) ||
- "wso2.esb.domain".equals(serviceDomains[2]) ||
- "wso2.esb.domain".equals(serviceDomains[3]));
-
- }
-
- public final void testGetServiceSubDomains() throws Exception {
-
- setUp();
- String[] serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as3.domain");
- assertEquals(2, serviceSubDomains.length);
-
- assertTrue("nirmal".equals(serviceSubDomains[0]) ||
- "nirmal".equals(serviceSubDomains[1]));
-
- assertTrue("nirmal2".equals(serviceSubDomains[0]) ||
- "nirmal2".equals(serviceSubDomains[1]));
-
- serviceSubDomains = lbConfig.getServiceSubDomains("wso2.esb.domain");
- assertEquals(2, serviceSubDomains.length);
-
- serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as1.domain");
- assertEquals(1, serviceSubDomains.length);
-
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java
deleted file mode 100644
index a75484b..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * 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.wso2.carbon.lb.common.test;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import org.wso2.carbon.lb.common.conf.structure.Node;
-import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
-
-public class NodeBuilderTest extends TestCase {
-
- String content;
-
- public void setUp() throws Exception {
- }
-
- public final void testBuildNode() {
-
- // Testing a node only has properties
- Node a = new Node();
- a.setName("loadbalancer");
-
- content =
- "securityGroups stratos-appserver-lb;\ninstanceType m1.large;\n"
- + "instances 1;\nelasticIP ${ELASTIC_IP};\n"
- + "availabilityZone us-east-1c;\npayload /mnt/payload.zip;";
-
- a = NodeBuilder.buildNode(a, content);
-
- Assert.assertEquals("loadbalancer", a.getName());
- Assert.assertEquals("stratos-appserver-lb", a.getProperty("securityGroups"));
- Assert.assertEquals("${ELASTIC_IP}", a.getProperty("elasticIP"));
- Assert.assertEquals("/mnt/payload.zip", a.getProperty("payload"));
- Assert.assertNull(a.getProperty("payloader"));
-
- // Testing a node has sub nodes and properties
- a = new Node();
- a.setName("appserver");
-
- content =
- "hosts appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n"
- + "domains {\n" + "wso2.as1.domain {\n" + "tenant_range 1-100;\n" + "}\n"
- + "wso2.as2.domain {\n" + "tenant_range 101-200;\n" + "}\n"
- + "wso2.as3.domain { # domain\n" + "tenant_range *;\n" + "}\n" + "}\n"
- + "# line comment \n"
- + "payload resources/cluster_node.zip;# payload\n"
- + "availability_zone us-east-1c;\n";
-
- a = NodeBuilder.buildNode(a, content);
-
- Assert.assertEquals("appserver", a.getName());
- Assert.assertEquals(1, a.getChildNodes().size());
- Assert.assertEquals("domains", a.getChildNodes().get(0).getName());
- Assert.assertEquals("appserver.cloud-test.wso2.com,as.cloud-test.wso2.com",
- a.getProperty("hosts"));
- Assert.assertEquals("resources/cluster_node.zip", a.getProperty("payload"));
- Assert.assertEquals(null, a.getProperty("payloader"));
-
- Node b = a.getChildNodes().get(0);
-
- Assert.assertEquals(3, b.getChildNodes().size());
- Assert.assertEquals(null, b.getProperty("payload"));
-
- Node c = b.getChildNodes().get(0);
-
- Assert.assertEquals(0, c.getChildNodes().size());
- Assert.assertEquals("1-100", c.getProperty("tenant_range"));
-
- c = b.getChildNodes().get(2);
-
- Assert.assertEquals(0, c.getChildNodes().size());
- Assert.assertEquals("*", c.getProperty("tenant_range"));
-
- String nodeStr = "appserver {\n" +
- "\thosts\tappserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n" +
- "\tpayload\tresources/cluster_node.zip;\n" +
- "\tavailability_zone\tus-east-1c;\n" +
- "\tdomains {\n" +
- "\t\twso2.as1.domain {\n" +
- "\t\t\ttenant_range\t1-100;\n" +
- "\t\t}\n" +
- "\t\twso2.as2.domain {\n" +
- "\t\t\ttenant_range\t101-200;\n" +
- "\t\t}\n" +
- "\t\twso2.as3.domain {\n" +
- "\t\t\ttenant_range\t*;\n" +
- "\t\t}\n" +
- "\t}\n" +
- "}";
-
- assertEquals(nodeStr, a.toString());
-
- // test equals method
- assertEquals(true, a.equals(a));
- assertEquals(false, a.equals(b));
- assertEquals(false, c.equals(b));
-
- // test buildNode(String)
- c = NodeBuilder.buildNode(nodeStr);
-
- assertEquals(c.getName(), "appserver");
- assertEquals(c.getChildNodes().size(), 1);
- assertEquals(c.getProperty("availability_zone"), "us-east-1c");
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf
deleted file mode 100644
index b2fd44f..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf
+++ /dev/null
@@ -1,64 +0,0 @@
-loadbalancer {
- instances 1;
- enable_autoscaler true;
- # interval between two task executions in milliseconds
- autoscaler_task_interval 5000;
- # after an instance booted up, task will wait till this much of time and let the server started up
- server_startup_delay 15000; #default will be 60000ms
-}
-
-services {
- defaults {
- min_app_instances 1;
- max_app_instances 5;
- max_requests_per_second 400;
- alarming_upper_rate 0.65;
- alarming_lower_rate 0.2;
- scale_down_factor 0.25;
- rounds_to_average 10;
- instances_per_scale_up 1;
- message_expiry_time 60000;
- }
-
- appserver {
- hosts appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
- sub_domain worker1;
- domains {
- wso2.as1.domain {
- hosts as2.cloud-test.wso2.com;
- min_app_instances 0;
- sub_domain worker;
- tenant_range 1-5;
- }
- wso2.as2.domain {
- tenant_range 7;
- }
- wso2.as3.domain {
- sub_domain nirmal;
- tenant_range 10-20;
- }
-
- wso2.as3.domain {
- sub_domain nirmal2;
- tenant_range 21-25;
- }
-
- wso2.esb.domain {
- sub_domain nirmal;
- tenant_range *;
- }
- }
- }
-
- esb {
- hosts esb.cloud-test.wso2.com,mgt.as.cloud-test.wso2.com;
- domains {
- wso2.esb.domain {
- sub_domain mgt;
- tenant_range *;
- }
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
deleted file mode 100644
index 8b87a32..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
+++ /dev/null
@@ -1,39 +0,0 @@
-loadbalancer {
- instances 1;
- enable_autoscaler true;
- # interval between two task executions in milliseconds
- autoscaler_task_interval 5000;
- # after an instance booted up, task will wait till this much of time and let the server started up
- server_startup_delay 15000; #default will be 60000ms
-}
-
-services {
-
- appserver {
- hosts appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
- sub_domain worker1;
- domains {
-
- wso2.as.domain {
- sub_domain nirmal;
- tenant_range *;
- }
- wso2.as1.domain {
- sub_domain nirmal;
- tenant_range 5-7;
- }
- }
- }
-
- esb {
- hosts esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
- domains {
- wso2.esb.domain {
- sub_domain mgt;
- tenant_range *;
- }
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
deleted file mode 100644
index 718d881..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
+++ /dev/null
@@ -1,30 +0,0 @@
-services {
-
- appserver {
- hosts appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
- sub_domain worker1;
- domains {
-
- wso2.as.domain {
- sub_domain nirmal;
- tenant_range *;
- }
- wso2.as1.domain {
- sub_domain nirmal;
- tenant_range 5-7;
- }
- }
- }
-
- esb {
- hosts esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
- domains {
- wso2.esb.domain {
- sub_domain mgt;
- tenant_range *;
- }
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml
deleted file mode 100644
index 44b9822..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Default suite">
- <test verbose="2" name="Default test">
- <classes>
- <!--class name="org.wso2.carbon.lb.common.test.AgentPersistenceManagerTest">
- <methods>
- <include name="addZone" />
- <include name="addHostMachine" />
- <include name="deleteHostMachine" />
- </methods>
- </class-->
- </classes>
- </test>
-</suite>
[09/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java
deleted file mode 100644
index 5c0110e..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.wso2.carbon.autoscaler.service.io;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Deserializer {
-
- private static final Log log = LogFactory.getLog(Deserializer.class);
-
- /**
- * We deserialize only if the path to the serialized object file is exists.
- * @param filePath path to the serialized object file
- * @return the object obtained after deserialization or null if file isn't valid.
- * @throws Exception
- */
- public static Object deserialize(String filePath) throws Exception {
-
- ObjectInputStream objIn = null;
- Object obj = null;
-
- if(!new File(filePath).isFile()){
- return obj;
- }
-
- try {
-
- objIn = new ObjectInputStream(new FileInputStream(filePath));
- obj = objIn.readObject();
-
- } catch (IOException e) {
- log.error("Failed to deserialize the file at "+filePath , e);
- throw e;
-
- } catch (ClassNotFoundException e) {
- log.error("Failed to deserialize the file at "+filePath , e);
- throw e;
-
- } finally{
- objIn.close();
- }
-
- return obj;
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java
deleted file mode 100644
index 31dd1eb..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.wso2.carbon.autoscaler.service.io;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Serializer {
-
- private static final Log log = LogFactory.getLog(Serializer.class);
-
- public static void serialize(Object serializableObj, String filePath) throws IOException {
-
- File outFile = new File(filePath);
- ObjectOutput ObjOut = null;
-
- try {
-
- if(outFile.createNewFile()){
- log.debug("Serialization file is created at "+filePath);
- } else{
- log.debug("Serialization file is already existing at "+filePath);
- }
-
- ObjOut = new ObjectOutputStream(new FileOutputStream(outFile));
- ObjOut.writeObject(serializableObj);
-
- } catch (IOException e) {
- log.error("Failed to serialize the object "+serializableObj.toString()
- + " to file "+filePath , e);
- throw e;
-
- } finally{
- ObjOut.close();
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java
deleted file mode 100644
index 5818ca1..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.jcloud;
-
-import java.util.Map;
-import java.util.Properties;
-
-import org.jclouds.ContextBuilder;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.ComputeServiceContext;
-import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
-import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
-import org.jclouds.sshj.config.SshjSshClientModule;
-import org.wso2.carbon.autoscaler.service.util.IaasProvider;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.inject.Module;
-
-/**
- * This class is responsible for creating a JClouds specific ComputeService object instances.
- */
-public class ComputeServiceBuilder {
-
- public static ComputeService buildComputeService(IaasProvider iaas) {
-
- Properties properties = new Properties();
-
- // load properties
- for (Map.Entry<String, String> entry : iaas.getProperties().entrySet()) {
- properties.put(entry.getKey(), entry.getValue());
- }
-
- // set modules
- Iterable<Module> modules =
- ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
- new EnterpriseConfigurationModule());
-
- // build context
- ContextBuilder builder =
- ContextBuilder.newBuilder(iaas.getProvider())
- .credentials(iaas.getIdentity(), iaas.getCredential()).modules(modules)
- .overrides(properties);
-
- // return the compute service object
- return builder.buildView(ComputeServiceContext.class).getComputeService();
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java
deleted file mode 100644
index 7373902..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.util;
-
-public final class AutoscalerConstant {
-
- /**
- * elastic-scaler-config XML file's elements
- */
- public static final String SERIALIZATION_DIR_ELEMENT = "serializationDir";
- public static final String IAAS_PROVIDER_ELEMENT = "iaasProvider";
- public static final String IAAS_PROVIDER_TYPE_ATTR = "type";
- public static final String IAAS_PROVIDER_NAME_ATTR = "name";
- public static final String PROPERTY_ELEMENT = "property";
- public static final String PROPERTY_NAME_ATTR= "name";
- public static final String PROPERTY_VALUE_ATTR = "value";
- public static final String IMAGE_ID_ELEMENT = "imageId";
- public static final String SCALE_DOWN_ORDER_ELEMENT = "scaleDownOrder";
- public static final String SCALE_UP_ORDER_ELEMENT = "scaleUpOrder";
- public static final String PROVIDER_ELEMENT = "provider";
- public static final String IDENTITY_ELEMENT = "identity";
- public static final String CREDENTIAL_ELEMENT = "credential";
- public static final String DEFAULT_SERVICE_ELEMENT = "default";
- public static final String SERVICE_ELEMENT = "service";
- public static final String SERVICE_DOMAIN_ATTR = "domain";
- public static final String SERVICE_SUB_DOMAIN_ATTR = "subDomain";
-
- /**
- * Secret Manager related aliases.
- */
- public static final String EC2_IDENTITY_ALIAS = "elastic.scaler.ec2.identity";
- public static final String EC2_CREDENTIAL_ALIAS = "elastic.scaler.ec2.credential";
- public static final String OPENSTACK_IDENTITY_ALIAS = "elastic.scaler.openstack.identity";
- public static final String OPENSTACK_CREDENTIAL_ALIAS = "elastic.scaler.openstack.credential";
-
- /**
- * Serializer related constants
- */
- public static final String IAAS_CONTEXT_LIST_SERIALIZING_FILE = "iaas-context-list.txt";
- public static final String LASTLY_USED_IAAS_MAP_SERIALIZING_FILE = "lastly-used-iaas.txt";
-
- /**
- * Payload related constants
- */
- public static final String PAYLOAD_DIR = "payload";
- public static final String PARAMS_FILE_NAME = "launch-params";
- public static final String RESOURCES_DIR = "resources";
- public static final String VALUE_SEPARATOR = "=";
- public static final String ENTRY_SEPARATOR = ",";
- public static final String APP_PATH_KEY = "APP_PATH";
- public static final String TENANT_KEY = "TENANT";
-
- /**
- * Super tenant id
- */
- public static final String SUPER_TENANT_ID = "-1234";
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java
deleted file mode 100644
index c2affa5..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.util;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.domain.Template;
-import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
-
-/**
- * This object holds all IaaS related runtime data.
- */
-public class IaasContext implements Serializable{
-
- private static final long serialVersionUID = -922284976926131383L;
-
- // name of the IaaS
- private Enum<Iaases> name;
-
- /* We keep following maps in order to make the look up time, low.*/
-
- /**
- * Key - domain
- * Value - is another map
- * key - sub domain
- * value - <code>InstanceContext</code>
- */
- private Map<String, Map<String, InstanceContext>> instanceCtxts;
-
- /**
- * Key - public IP
- * Value - <code>InstanceContext</code>
- */
- private Map<String, InstanceContext> publicIpToInstanceCtxt;
-
- /**
- * Key - node id
- * Value - <code>InstanceContext</code>
- */
- private Map<String, InstanceContext> nodeIdToInstanceCtxt;
-
-
-// private transient Map<String, Template> domainToTemplateMap;
- private transient ComputeService computeService;
-
- // Since Jclouds' NodeMetadata object contains unserializable objects, I had to use 3 maps.
-// private Map<String, String> nodeIdToDomainMap = new LinkedHashMap<String, String>();
-// private Map<String, String> publicIpToDomainMap = new LinkedHashMap<String, String>();
-// private Map<String, String> publicIpToNodeIdMap = new LinkedHashMap<String, String>();
-
- private int scaleUpOrder, scaleDownOrder;
-
- public IaasContext(Enum<Iaases> name, ComputeService computeService) {
- this.name = name;
- this.computeService = computeService;
- instanceCtxts = new LinkedHashMap<String, Map<String,InstanceContext>>();
- publicIpToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
- nodeIdToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
- }
-
- public Enum<Iaases> getName() {
- return name;
- }
-
- public void addInstanceContext(InstanceContext ctx) {
-
- if(ctx == null){
- return;
- }
-
- String domain = ctx.getDomain();
- String subDomain = ctx.getSubDomain();
-
- if(domain != null && subDomain != null){
- addToInstanceCtxts(domain, subDomain, ctx);
- }
-
- }
-
- public void addNodeDetails(String domain, String subDomain, String nodeId, String ip) {
-
- if(getInstanceContext(domain, subDomain) != null){
- getInstanceContext(domain, subDomain).addNode(nodeId, ip);
-
- nodeIdToInstanceCtxt.put(nodeId, getInstanceContext(domain, subDomain));
- publicIpToInstanceCtxt.put(ip, getInstanceContext(domain, subDomain));
- }
- }
-
- private void addToInstanceCtxts(String domainName, String subDomainName, InstanceContext ctx) {
-
- Map<String, InstanceContext> map;
-
- if(instanceCtxts.get(domainName) == null){
- map = new HashMap<String, InstanceContext>();
-
- } else{
- map = instanceCtxts.get(domainName);
- }
-
- map.put(subDomainName, ctx);
- instanceCtxts.put(domainName, map);
-
- }
-
-// public void addToDomainToTemplateMap(String key, Template value) {
-// domainToTemplateMap.put(key, value);
-// }
-
- public Template getTemplate(String domain, String subDomain) {
- if(getInstanceContext(domain, subDomain) == null){
- return null;
- }
- return getInstanceContext(domain, subDomain).getTemplate();
- }
-
- public InstanceContext getInstanceContext(String domain, String subDomain) {
- if (instanceCtxts.get(domain) != null) {
- return instanceCtxts.get(domain).get(subDomain);
- }
- return null;
- }
-
- public ComputeService getComputeService() {
- return computeService;
- }
-
- public void setComputeService(ComputeService computeService) {
- this.computeService = computeService;
- }
-
-// public void addNodeIdToDomainMap(String nodeId, String domain) {
-// nodeIdToDomainMap.put(nodeId, domain);
-// }
-//
-// public void addPublicIpToDomainMap(String ip, String domain) {
-// publicIpToDomainMap.put(ip, domain);
-// }
-//
-// public void addPublicIpToNodeIdMap(String ip, String nodeId) {
-// publicIpToNodeIdMap.put(ip, nodeId);
-// }
-
- /**
- * This will return the node id of the node which is belong to the
- * requesting domain, sub domain and which is the most recently created. If it cannot find a
- * matching node id, this will return <code>null</code>.
- * @param domain service domain.
- * @param subDomain service sub domain.
- * @return the node Id of the node
- */
- public String getLastMatchingNode(String domain, String subDomain) {
-
- InstanceContext ctx = getInstanceContext(domain, subDomain);
-
- if(ctx == null){
- return null;
- }
-
- // iterate in reverse order
- ListIterator<String> iter =
- new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
- listIterator(ctx.getNodeIdToIpMap().size());
-
- if (iter.hasPrevious()) {
- return iter.previous();
- }
-
- return null;
- }
-
- /**
- * This will return the public IP of the node which is belong to the
- * requesting domain, sub domain and which is the most recently created. If it cannot find a
- * matching public IP, this will return <code>null</code>.
- * @param domain service domain.
- * @param subDomain service sub domain.
- * @return the public IP of the node
- */
- public String getLastMatchingPublicIp(String domain, String subDomain) {
-
- InstanceContext ctx = getInstanceContext(domain, subDomain);
-
- if(ctx == null){
- return null;
- }
-
- // iterate in reverse order
- ListIterator<String> iter =
- new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
- listIterator(ctx.getNodeIdToIpMap().size());
-
- while (iter.hasPrevious()) {
- return ctx.getNodeIdToIpMap().get(iter.previous());
- }
-
- return null;
-
-// // traverse from the last entry of the map
-// ListIterator<Map.Entry<String, String>> iter =
-// new ArrayList<Entry<String, String>>(publicIpToDomainMap.entrySet()).
-// listIterator(publicIpToDomainMap.size());
-//
-// while (iter.hasPrevious()) {
-// Map.Entry<String, String> entry = iter.previous();
-// if (entry.getValue().equals(domain)) {
-// return entry.getKey();
-// }
-// }
-//
-// return null;
- }
-
- /**
- * This will return the node id of the node which is belong to the
- * requesting domain, sub domain and which is created at first. If it cannot find a
- * matching node id, this will return <code>null</code>.
- * @param domain service domain.
- * @param subDomain service sub domain.
- * @return node id of the node
- */
- public String getFirstMatchingNode(String domain, String subDomain) {
-
- InstanceContext ctx = getInstanceContext(domain, subDomain);
-
- if(ctx == null){
- return null;
- }
-
- // iterate in added order
- ListIterator<String> iter =
- new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
- listIterator(0);
-
- while (iter.hasNext()) {
- return iter.next();
- }
-
- return null;
-
-// for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
-// if (entry.getValue().equals(domain)) {
-// return entry.getKey();
-// }
-// }
-// return null;
- }
-
- /**
- * This will return the node id of the node which has the given public IP.
- * If it cannot find a matching node id, this will return
- * <code>null</code>.
- * @param publicIp public IP of a node.
- * @return node id of the matching node.
- */
- public String getNodeWithPublicIp(String publicIp) {
-
- InstanceContext ctx;
-
- for (String ip : publicIpToInstanceCtxt.keySet()) {
-
- if (ip.equals(publicIp)) {
-
- ctx = publicIpToInstanceCtxt.get(ip);
-
- for (String nodeId : nodeIdToInstanceCtxt.keySet()) {
- if (ctx.equals(nodeIdToInstanceCtxt.get(nodeId))) {
- return nodeId;
- }
- }
- }
- }
-
- return null;
- }
-
- /**
- * This will return a list of node Ids that are started in this IaaS and that are
- * belong to the given domain, sub domain.
- * @param domain service domain.
- * @param subDomain service sub domain.
- * @return List of node Ids.
- */
- public List<String> getNodeIds(String domain, String subDomain) {
-
- InstanceContext ctx = getInstanceContext(domain, subDomain);
-
- if(ctx == null){
- return new ArrayList<String>();
- }
-
- return new ArrayList<String>(ctx.getNodeIdToIpMap().keySet());
-
-
-// List<String> nodeIds = new ArrayList<String>();
-//
-// for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
-// if (entry.getValue().equals(domain)) {
-// nodeIds.add(entry.getKey());
-// }
-// }
-//
-// return nodeIds;
- }
-
- /**
- * Removes a specific node id and related entries.
- * @param node id of the node to be removed.
- */
- public void removeNodeId(String nodeId) {
-
- InstanceContext ctx;
-
- if(nodeIdToInstanceCtxt.containsKey(nodeId)){
- // remove from node id map
- ctx = nodeIdToInstanceCtxt.remove(nodeId);
-
- // remove from public ip map
- publicIpToInstanceCtxt.remove(ctx.getNodeIdToIpMap().get(nodeId));
-
- // remove from main map
- instanceCtxts.get(ctx.getDomain()).get(ctx.getSubDomain()).removeNode(nodeId);
-
- }
- }
-
- public boolean equals(Object obj) {
-
- if (obj instanceof IaasContext) {
- return new EqualsBuilder().append(getName(), ((IaasContext) obj).getName()).isEquals();
- }
- return false;
-
- }
-
- public int hashCode() {
- return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
- append(name).
- toHashCode();
- }
-
- public int getScaleDownOrder() {
- return scaleDownOrder;
- }
-
- public void setScaleDownOrder(int scaleDownOrder) {
- this.scaleDownOrder = scaleDownOrder;
- }
-
- public int getScaleUpOrder() {
- return scaleUpOrder;
- }
-
- public void setScaleUpOrder(int scaleUpOrder) {
- this.scaleUpOrder = scaleUpOrder;
- }
-
-// public void setDomainToTemplateMap(Map<String, Template> map) {
-// domainToTemplateMap = map;
-// }
-//
-// public Map<String, Template> getDomainToTemplateMap() {
-// return domainToTemplateMap;
-// }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java
deleted file mode 100644
index 84bb307..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * This is the basic data structure which holds an IaaS specific details.
- */
-public class IaasProvider {
-
- /**
- * Unique id to identify this IaaS provider.
- */
- private String type;
-
- /**
- * human description of this IaaS provider
- */
- private String name;
-
- /**
- * Property map for this IaaS provider.
- */
- private Map<String, String> properties = new HashMap<String, String>();
-
- /**
- * Image identifier.
- */
- private String template;
-
- /**
- * Scale up order and scale down order of the IaaS.
- */
- private int scaleUpOrder, scaleDownOrder;
-
- private String provider, identity, credential;
-
-// public enum SortParameter {
-// SCALE_UP, SCALE_DOWN
-// }
-
-
- public String getType() {
- return type;
- }
-
- public void setType(String id) {
- this.type = id;
- }
-
- public Map<String, String> getProperties() {
- return properties;
- }
-
- public void setProperty(String key, String value) {
-
- if(key != null && value != null){
- properties.put(key, value);
- }
- }
-
- public void setProperties(Map<String, String> properties) {
- this.properties = properties;
- }
-
- public String getTemplate() {
- return template;
- }
-
- public void setTemplate(String template) {
- this.template = template;
- }
-
- public int getScaleUpOrder() {
- return scaleUpOrder;
- }
-
- public void setScaleUpOrder(int scaleUpOrder) {
- this.scaleUpOrder = scaleUpOrder;
- }
-
- public int getScaleDownOrder() {
- return scaleDownOrder;
- }
-
- public void setScaleDownOrder(int scaleDownOrder) {
- this.scaleDownOrder = scaleDownOrder;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getProvider() {
- return provider;
- }
-
- public void setProvider(String provider) {
- this.provider = provider;
- }
-
- public String getIdentity() {
- return identity;
- }
-
- public void setIdentity(String identity) {
- this.identity = identity;
- }
-
- public String getCredential() {
- return credential;
- }
-
- public void setCredential(String credential) {
- this.credential = credential;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java
deleted file mode 100644
index 80f3883..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.util;
-
-import java.io.Serializable;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import org.jclouds.compute.domain.Template;
-
-/**
- * This will hold the run-time data related to an instance.
- * Instance can be an EC2 one, Openstack one etc.
- */
-public class InstanceContext implements Serializable {
-
- private static final long serialVersionUID = -2604902942512629140L;
- private String domain;
- private String subDomain;
- private transient Template template;
-
- /**
- * Key - node Id
- * Value - IP
- */
- private Map<String, String> nodeIdToIpMap;
-
- public InstanceContext(String domain, String subDomain, Template temp) {
- this.domain = domain;
- this.subDomain = subDomain;
- this.template = temp;
- nodeIdToIpMap = new LinkedHashMap<String, String>();
- }
-//
-// public InstanceContext(String domain, String subDomain, Template temp, String nodeId, String publicIp) {
-// this.domain = domain;
-// this.subDomain = subDomain;
-// this.template = temp;
-// this.nodeId = nodeId;
-// this.publicIp = publicIp;
-// }
-
-
- public String getDomain() {
- return domain;
- }
-
- public String getSubDomain() {
- return subDomain;
- }
-
- public Template getTemplate() {
- return template;
- }
-
- public void setTemplate(Template temp) {
- this.template = temp;
- }
-
- public void addNode(String nodeId, String ip) {
- if("".equals(ip)){
- ip = null;
- }
- nodeIdToIpMap.put(nodeId, ip);
- }
-
- public void removeNode(String nodeId) {
- nodeIdToIpMap.remove(nodeId);
- }
-
-
- public Map<String, String> getNodeIdToIpMap() {
- return nodeIdToIpMap;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java
deleted file mode 100644
index 0dbd6a0..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.wso2.carbon.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/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java
deleted file mode 100644
index 325da96..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java
+++ /dev/null
@@ -1,556 +0,0 @@
-/*
- * 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.wso2.carbon.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.wso2.carbon.autoscaler.service.exception.MalformedConfigurationFileException;
-import org.wso2.carbon.autoscaler.service.util.AutoscalerConstant;
-import org.wso2.carbon.autoscaler.service.util.IaasProvider;
-import org.wso2.carbon.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.
- *
- * <elasticScalerConfig>
- * <iaasProviders>
- * <iaasProvider name="ec2">
- * <provider>aws-ec2</provider>
- * <identity>aaa</identity>
- * <credential>aaaa</credential>
- * <scaleUpOrder>1</scaleUpOrder>
- * <scaleDownOrder>2</scaleDownOrder>
- * <property name="A" value="a"/>
- * <property name="B" value="b"/>
- * <template>temp1</template>
- * </iaasProvider>
- *
- * <iaasProvider name="lxc">
- * <provider>aws-ec2</provider>
- * <identity>aaa</identity>
- * <credential>aaaa</credential>
- * <scaleUpOrder>2</scaleUpOrder>
- * <scaleDownOrder>1</scaleDownOrder>
- * <property name="X" value="x"/>
- * <property name="Y" value="y"/>
- * <template>temp2</template>
- * </iaasProvider>
- * </iaasProviders>
- * $lt;services>
- * $lt;default>
- * $lt;property name="availabilityZone" value="us-east-1c"/>
- * $lt;property name="securityGroups" value="manager,cep,mb,default"/>
- * $lt;property name="instanceType" value="m1.large"/>
- * $lt;property name="keyPair" value="aa"/>
- * $lt;/default>
- * $lt;service domain="wso2.as.domain">
- * $lt;property name="securityGroups" value="manager,default"/>
- * $lt;property name="payload" value="resources/as.zip"/>
- * $lt;/service>
- * $lt;/services>
- * </elasticScalerConfig>
- */
-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/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
deleted file mode 100644
index ae20622..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<serviceGroup>
- <service name="AutoscalerService" scope="application">
- <parameter name="ServiceClass">org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl</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/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java
deleted file mode 100644
index 946efb6..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.util;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl.IaasContextComparator;
-import org.wso2.carbon.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/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java
deleted file mode 100644
index 2805d64..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
-* 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.wso2.carbon.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.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
-import org.wso2.carbon.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/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
deleted file mode 100644
index 4a3eb74..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.xml;
-
-import java.util.List;
-import org.wso2.carbon.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.wso2.carbon.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/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
deleted file mode 100644
index 3ef215e..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
+++ /dev/null
@@ -1,66 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<!--
- ~ Copyright 2005-2011 WSO2, Inc. (http://wso2.com)
- ~
- ~ 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.
- -->
-
-<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/290c6307/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
new file mode 100644
index 0000000..7b0bbbe
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, 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.
+-->
+
+
+<!--
+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>loadbalancer-components</artifactId>
+ <version>4.1.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/290c6307/components/load-balancer/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/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java b/components/load-balancer/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..804823f
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
@@ -0,0 +1,84 @@
+/*
+* 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.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+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.context.AppDomainContext;
+
+/** 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;
+ }
+
+}
[04/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
deleted file mode 100644
index c3131af..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * 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.wso2.carbon.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.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.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.wso2.carbon.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.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
deleted file mode 100644
index f097e2e..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.util;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.LBConfiguration;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.wso2.carbon.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.wso2.carbon.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.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
deleted file mode 100644
index 399d502..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
+++ /dev/null
@@ -1,2 +0,0 @@
-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.wso2.carbon.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.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
deleted file mode 100644
index 05fce78..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
+++ /dev/null
@@ -1,2 +0,0 @@
-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.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
deleted file mode 100644
index f8ecf6f..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
+++ /dev/null
@@ -1,138 +0,0 @@
-<?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.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
deleted file mode 100644
index 3e66066..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
+++ /dev/null
@@ -1,135 +0,0 @@
-<?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>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
deleted file mode 100644
index 7332d38..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
+++ /dev/null
@@ -1,108 +0,0 @@
-<?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.autoscale.lbautoscale.ServiceRequestsInFlightAutoscaler"
- name="LoadAnalyzer">
-
- <!--
- The private key for ec2
- -->
- <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
-
- <!--
- The certificate for ec2
- -->
- <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
- <!--
- The key pair
- -->
- <property name="sshKey" value="stratos-1.0.0-keypair"/>
-
- <property name="loadBalancer">
- <loadBalancer>
- <property name="securityGroup" value="stratos-appserver-lb"/>
- <property name="instanceType" value="m1.large"/>
- <property name="instances" value="1"/>
- <property name="elasticIP" value="${ELASTIC_IP}"/>
- <property name="availabilityZone" value="us-east-1c"/>
- <property name="payload" value="/mnt/payload.zip"/>
- </loadBalancer>
- </property>
-
- <property name="services">
- <services>
- <defaults>
- <property name="payload" value="resources/cluster_node.zip"/>
- <property name="availabilityZone" value="us-east-1c"/>
- <property name="securityGroup" value="as-2011-02-23"/>
- <property name="instanceType" value="m1.large"/>
- <property name="minAppInstances" value="1"/>
- <property name="maxAppInstances" value="5"/>
- <property name="queueLengthPerNode" value="400"/>
- <property name="roundsToAverage" value="10"/>
- <property name="instancesPerScaleUp" value="1"/>
- <property name="messageExpiryTime" value="60000"/>
- </defaults>
- <service domain="wso2.as.domain">
- <property name="payload" value="resources/cluster_node.zip"/>
- <property name="availabilityZone" value="us-east-1c"/>
- </service>
- <service domain="wso2.ds.domain">
- <property name="payload" value="resources/cluster_node.zip"/>
- <property name="minAppInstances" value="1"/>
- <property name="maxAppInstances" value="5"/>
- <property name="queueLengthPerNode" value="400"/>
- <property name="roundsToAverage" value="10"/>
- <property name="instancesPerScaleUp" value="1"/>
- <property name="availabilityZone" value="us-east-1c"/>
- <property name="securityGroup" value="ds-2011-02-23"/>
- </service>
- <service domain="wso2.bps.domain">
- <property name="payload" value="resources/cluster_node.zip"/>
- <property name="minAppInstances" value="1"/>
- <property name="maxAppInstances" value="5"/>
- <property name="queueLengthPerNode" value="400"/>
- <property name="roundsToAverage" value="10"/>
- <property name="instancesPerScaleUp" value="1"/>
- <property name="availabilityZone" value="us-east-1c"/>
- <property name="securityGroup" value="bps-2011-02-23"/>
- </service>
- </services>
- </property>
-
- <!--
- 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.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
deleted file mode 100644
index 1d017a3..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale;
-
-import java.io.File;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.context.ConfigurationContextFactory;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.wso2.carbon.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-public class AppDomainContextsTest extends TestCase {
-
- private static Map<String, Map<String, ?>> map;
- private LoadBalancerConfiguration lbConfig;
- ConfigurationContext configCtx;
- ClusteringAgent clusteringAgent;
-
- protected void setUp() throws Exception {
- super.setUp();
- configCtx = ConfigurationContextFactory.createEmptyConfigurationContext();
- clusteringAgent = new TribesClusteringAgent();
- clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
- "worker"),
- "wso2.as1.domain", "worker", -1);
- clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
- "mgt"),
- "wso2.as1.domain", "mgt", -1);
- clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
- "mgt"),
- "wso2.as2.domain", "mgt", -1);
- configCtx.getAxisConfiguration().setClusteringAgent(clusteringAgent);
-
- File f = new File("src/test/resources/loadbalancer.conf");
- System.setProperty("loadbalancer.conf", f.getAbsolutePath());
- lbConfig = LoadBalancerConfiguration.getInstance();
-
- map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-
- }
-
-
- public void testRemoval(){
- // removing a cluster domain with only 1 sub domain
- lbConfig.removeServiceConfiguration("wso2.as2.domain", "mgt");
- map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-
- Assert.assertEquals(true, !map.containsKey("wso2.as2.domain"));
-
- // removing a cluster domain with more than 1 sub domain
- lbConfig.removeServiceConfiguration("wso2.as1.domain", "mgt");
- map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-
- Assert.assertEquals(true, map.containsKey("wso2.as1.domain"));
- Assert.assertEquals(true, map.get("wso2.as1.domain").get("mgt") == null);
- Assert.assertEquals(true, map.get("wso2.as1.domain").get("worker") != null);
- }
-
- public void testAddition(){
- ServiceConfiguration config1 = lbConfig.new ServiceConfiguration();
- config1.setDomain("wso2.as3.domain");
- config1.setSub_domain("mgt");
- lbConfig.addServiceConfiguration(config1);
- clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
- "mgt"),
- "wso2.as3.domain", "mgt", -1);
- map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-
- Assert.assertEquals(true, map.containsKey("wso2.as3.domain"));
- Assert.assertEquals(true, map.get("wso2.as3.domain").get("mgt") != null);
- }
-
- @Deprecated // use only for writing test cases
- void printKeys(Map<?,?> map){
- for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
- Object type = iterator.next();
- System.out.println(type);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java
deleted file mode 100644
index 1f1a084..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale;
-
-/**
- * Test for ServiceRequestsInFlightAutoscaler
- */
-//public class ServiceRequestsInFlightAutoscalerTest extends TestCase {
-//
-// public void testInit() {
-//
-// //new ServiceRequestsInFlightAutoscaler().init(new Axis2SynapseEnvironment());
-// }
-//}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
deleted file mode 100644
index 7b2a80a..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
+++ /dev/null
@@ -1,50 +0,0 @@
-loadbalancer {
- instances 1;
- enable_autoscaler true;
- # interval between two task executions in milliseconds
- autoscaler_task_interval 5000;
- # after an instance booted up, task will wait till this much of time and let the server started up
- server_startup_delay 15000; #default will be 60000ms
-}
-
-services {
- defaults {
- min_app_instances 1;
- max_app_instances 5;
- max_requests_per_second 400;
- alarming_upper_rate 0.65;
- alarming_lower_rate 0.2;
- scale_down_factor 0.25;
- rounds_to_average 10;
- instances_per_scale_up 1;
- message_expiry_time 60000;
- }
-
- appserver {
- hosts appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
- sub_domain worker1;
- domains {
- wso2.as1.domain {
- hosts as1.cloud-test.wso2.com;
- min_app_instances 0;
- sub_domain worker;
- tenant_range 1-5;
- }
- wso2.as1.domain {
- hosts mgt.as1.cloud-test.wso2.com;
- min_app_instances 0;
- sub_domain mgt;
- tenant_range 1-5;
- }
- wso2.as2.domain {
- hosts mgt.as2.cloud-test.wso2.com;
- min_app_instances 0;
- sub_domain mgt;
- tenant_range 1-5;
- }
-
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml b/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml
index 4f52100..c77ab0b 100644
--- a/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml
+++ b/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml
@@ -18,7 +18,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
- <groupId>org.wso2.carbon</groupId>
+ <groupId>org.apache.stratos</groupId>
<artifactId>loadbalancer-components</artifactId>
<version>4.1.0</version>
<relativePath>../../../pom.xml</relativePath>
@@ -36,25 +36,22 @@
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.mediation.initializer</artifactId>
- <version>4.1.0</version>
- <!--version>${wso2carbon.version}</version-->
+ <version>${wso2carbon.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.mediation.dependency.mgt</artifactId>
- <version>4.1.0</version>
- <!--version>${wso2carbon.version}</version-->
+ <version>${wso2carbon.version}</version>
</dependency>
<dependency>
<groupId>org.apache.synapse</groupId>
<artifactId>synapse-core</artifactId>
- <version>2.1.1-wso2v4</version>
+ <version>${synapse.core.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
- <version>4.1.0</version>
- <!--version>${wso2carbon.version}</version-->
+ <version>${wso2carbon.version}</version>
</dependency>
<dependency>
<groupId>org.apache.stratos</groupId>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/Main.iml
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/Main.iml b/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/Main.iml
index 54e5e3d..8bf5197 100644
--- a/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/Main.iml
+++ b/components/load-balancer/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/Main.iml
@@ -3,7 +3,7 @@
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/../../../../org.wso2.carbon.lb.endpoint/4.1.3/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml
deleted file mode 100644
index 49f4624..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml
+++ /dev/null
@@ -1,107 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (c) 2009-2010, 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.
--->
-<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.wso2.carbon</groupId>
- <artifactId>loadbalancer-components</artifactId>
- <version>4.1.0</version>
- <relativePath>../../../pom.xml</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.lb.endpoint</artifactId>
- <packaging>bundle</packaging>
- <version>4.1.3</version>
- <name>WSO2 Carbon - Tenant Aware LoadBalance Endpoint</name>
- <url>http://wso2.org</url>
-
- <dependencies>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.mediation.initializer</artifactId>
- <version>${wso2carbon.version}</version>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.mediation.dependency.mgt</artifactId>
- <version>${wso2carbon.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.synapse</groupId>
- <artifactId>synapse-core</artifactId>
- <version>2.1.1-wso2v4</version>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.logging</artifactId>
- <version>${wso2carbon.version}</version>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.lb.common</artifactId>
- <version>4.1.3</version>
- </dependency>
- <dependency>
- <groupId>org.apache.axis2</groupId>
- <artifactId>axis2-kernel</artifactId>
- <version>1.6.1-wso2v9</version>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
- <version>2.1.1</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
-
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-scr-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
-
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
- <Bundle-Name>${project.artifactId}</Bundle-Name>
- <Export-Package>
- org.wso2.carbon.lb.endpoint.endpoint,
- org.wso2.carbon.lb.endpoint,
- org.wso2.carbon.lb.endpoint.util,
- </Export-Package>
- <Import-Package>
- !org.wso2.carbon.lb.endpoint.endpoint,
- !org.wso2.carbon.lb.endpoint,
- org.wso2.carbon.lb.common.*; version=${wso2carbon.version},
- org.wso2.carbon.registry.core.service; version=1.0.1,
- *;resolution:=optional
- </Import-Package>
- <DynamicImport-Package>*</DynamicImport-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java
deleted file mode 100644
index cf31ef0..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * 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.wso2.carbon.lb.endpoint;
-
-/**
- * The <code>EndpointConstants</code> class defined the endpoint constants.
- */
-public class EndpointConstants {
-
- public static final String ADDRESS_ENDPOINT = "Address Endpoint";
- public static final String WSDL_ENDPOINT = "WSDL Endpoint";
- public static final String FAILOVER_ENDPOINT = "Failover Group";
- public static final String LOADBALANCE_ENDPOINT = "Loadbalance Endpoint";
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java
deleted file mode 100644
index d9366b8..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * 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.wso2.carbon.lb.endpoint;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axis2.context.ConfigurationContext;
-import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
-import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
-import org.wso2.carbon.mediation.initializer.persistence.MediationPersistenceManager;
-
-import java.util.Properties;
-
-/**
- * Responsible for deploying Synapse artifacts.
- */
-public class EndpointDeployer extends org.apache.synapse.deployers.EndpointDeployer {
-
- MediationPersistenceManager mpm;
-
- @Override
- public void init(ConfigurationContext configCtx) {
- super.init(configCtx);
- this.mpm = ServiceBusUtils.getMediationPersistenceManager(configCtx.getAxisConfiguration());
- }
-
- @Override
- public String deploySynapseArtifact(OMElement artifactConfig, String fileName,
- Properties properties) {
- String epName = super.deploySynapseArtifact(artifactConfig, fileName, properties);
- mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
- return epName;
- }
-
- @Override
- public String updateSynapseArtifact(OMElement artifactConfig, String fileName,
- String existingArtifactName, Properties properties) {
- String epName = super.updateSynapseArtifact(
- artifactConfig, fileName, existingArtifactName, properties);
- mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
- return epName;
- }
-
- @Override
- public void undeploySynapseArtifact(String artifactName) {
- super.undeploySynapseArtifact(artifactName);
- mpm.deleteItemFromRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
- }
-
- @Override
- public void restoreSynapseArtifact(String artifactName) {
- super.restoreSynapseArtifact(artifactName);
- mpm.saveItemToRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
deleted file mode 100644
index d49758a..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 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.wso2.carbon.lb.endpoint;
-
-/**
- * Exception to be thrown from this component.
- */
-public class TenantAwareLoadBalanceEndpointException extends RuntimeException {
-
- private static final long serialVersionUID = -663839410798538370L;
-
- public TenantAwareLoadBalanceEndpointException(String msg) {
- super(msg);
- }
-
- public TenantAwareLoadBalanceEndpointException(String msg, Throwable cause) {
- super(msg, cause);
- }
-
- public TenantAwareLoadBalanceEndpointException(Throwable cause) {
- super(cause);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java
deleted file mode 100644
index dec45b4..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java
+++ /dev/null
@@ -1,190 +0,0 @@
-package org.wso2.carbon.lb.endpoint;
-
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.core.LoadBalanceMembershipHandler;
-import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
-import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-import org.wso2.carbon.user.api.UserStoreException;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * Bridge between Axis2 membership notification and Synapse load balancing
- */
-public class TenantLoadBalanceMembershipHandler implements LoadBalanceMembershipHandler {
- private static final Log log = LogFactory.getLog(TenantLoadBalanceMembershipHandler.class);
-
- private ConfigurationContext configCtx;
-
- private LoadbalanceAlgorithm lbAlgo;
-
- /**
- * Key - Host, Value - HostContext
- */
- private static Map<String, HostContext> hostContextsMap =
- new HashMap<String, HostContext>();
-
- private ClusteringAgent clusteringAgent;
-
- private boolean isClusteringEnabled;
- private String endpointName;
-
- public TenantLoadBalanceMembershipHandler(Map<String, HostContext> hostContexts,
- LoadbalanceAlgorithm algorithm,
- ConfigurationContext configCtx,
- boolean isClusteringEnabled,
- String endpointName) {
-
- lbAlgo = algorithm;
- this.isClusteringEnabled = isClusteringEnabled;
- this.endpointName = endpointName;
- this.configCtx = configCtx;
-
- for (HostContext host : hostContexts.values()) {
-
- addHostContext(host);
-
- }
- }
-
- /**
- * This will be used to add new {@link HostContext}s.
- * @param host {@link HostContext}
- */
- public void addHostContext(HostContext host){
-
- String hostName = host.getHostName();
-
- AlgorithmContext algorithmContext =
- new AlgorithmContext(isClusteringEnabled,
- configCtx, endpointName + "." +
- hostName);
-
- host.setAlgorithm(lbAlgo.clone());
- host.setAlgorithmContext(algorithmContext);
-
- hostContextsMap.put(hostName, host);
-
- }
-
- /**
- * This will be used to remove an existing {@link HostContext}s.
- * @param host {@link HostContext}
- */
- public void removeHostContext(String host){
-
- hostContextsMap.remove(host);
-
- }
-
- public void init(Properties props, LoadbalanceAlgorithm algorithm) {
- // Nothing to do
- }
-
- public void setConfigurationContext(ConfigurationContext configCtx) {
- this.configCtx = configCtx;
-
- // The following code does the bridging between Axis2 and Synapse load balancing
- clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
- if (clusteringAgent == null) {
- String msg = "In order to enable load balancing across an Axis2 cluster, " +
- "the cluster entry should be enabled in the axis2.xml file";
- log.error(msg);
- throw new SynapseException(msg);
- }
- }
-
- public ConfigurationContext getConfigurationContext() {
- return configCtx;
- }
-
- /**
- * Getting the next member to which the request has to be sent in a round-robin fashion
- *
- * @param context The AlgorithmContext
- * @return The current member
- * @deprecated Use {@link #getNextApplicationMember(String, int)}
- */
- public Member getNextApplicationMember(AlgorithmContext context) {
- throw new UnsupportedOperationException("This operation is invalid. " +
- "Call getNextApplicationMember(String host)");
- }
-
- public boolean isAValidHostName(String host){
- if(getHostContext(host) != null){
- return true;
- }
- return false;
- }
-
- public Member getNextApplicationMember(String host, int tenantId) {
- HostContext hostContext = getHostContext(host);
-
- if(hostContext == null){
- String msg = "Invalid host name : " + host;
- log.error(msg);
- throw new SynapseException(msg);
- }
-
- // here we have to pass tenant id to get domain from hostContext
- String domain = hostContext.getDomainFromTenantId(tenantId);
- String subDomain = hostContext.getSubDomainFromTenantId(tenantId);
-
- LoadbalanceAlgorithm algorithm = hostContext.getAlgorithm();
- GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
-
- if (groupMgtAgent == null) {
- String tenantDomain;
- try {
- tenantDomain = ConfigHolder.getInstance().getRealmService().getTenantManager().getDomain(tenantId);
- } catch (UserStoreException ignore) {
- tenantDomain = ""+tenantId;
- }
-
- String msg =
- "No Group Management Agent found for the domain: " + domain + ", subDomain: "
- + subDomain + ", host: " + host+ " and for tenant: "
- + tenantDomain;
- log.error(msg);
- throw new SynapseException(msg);
- }
- algorithm.setApplicationMembers(groupMgtAgent.getMembers());
- AlgorithmContext context = hostContext.getAlgorithmContext();
- return algorithm.getNextApplicationMember(context);
- }
-
- public HostContext getHostContext(String host) {
- HostContext hostContext = hostContextsMap.get(host);
- if (hostContext == null) {
- int indexOfDot;
- if ((indexOfDot = host.indexOf(".")) != -1) {
- hostContext = getHostContext(host.substring(indexOfDot + 1));
- }
- }
- return hostContext;
- }
-
- public LoadbalanceAlgorithm getLoadbalanceAlgorithm() {
- return lbAlgo;
- }
-
- public Properties getProperties() {
- return null;
- }
-
- public ClusteringAgent getClusteringAgent() {
- return clusteringAgent;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java
deleted file mode 100644
index 31e9f67..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java
+++ /dev/null
@@ -1,142 +0,0 @@
-package org.wso2.carbon.lb.endpoint.builder;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.wso2.carbon.lb.common.conf.structure.Node;
-import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
-import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
-import org.wso2.carbon.lb.endpoint.group.mgt.GroupMgtAgentBuilder;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-
-/**
- * A Thread, which is responsible for making a sense out of a message received for
- * ELB via topology synchronization.
- */
-public class TopologySyncher implements Runnable {
-
- private static final Log log = LogFactory.getLog(TopologySyncher.class);
-
- /*
- * This is a reference to sharedTopologyQueue ConfigHolder.
- */
- private BlockingQueue<String> sharedQueue;
-
- public TopologySyncher(BlockingQueue<String> queue) {
-
- sharedQueue = queue;
-
- }
-
- @Override
- public void run() {
- // grab the lb configuration instance
- LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
-
- // FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer
- // conf
- // in order to proper initialization of TribesClusteringAgent.
- generateGroupMgtAgents(lbconfig);
-
- // this thread should run for ever, untill terminated.
- while (true) {
- try {
-
- // grabs a message or waits till the queue is non-empty
- String message = sharedQueue.take();
-// ConfigHolder data = ConfigHolder.getInstance();
-
- // this message needs attention only if it's not same as the previous message and
- // not null of course.
-// if (data.getPreviousMsg() == null || !data.getPreviousMsg().equals(message)) {
-
- // reset the previous message
-// data.setPreviousMsg(message);
-
- // build the nginx format of this message, and get the Node object
- Node topologyNode = NodeBuilder.buildNode(message);
-
- // reset service configurations
-// lbconfig.resetData();
- // create new service configurations
- List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
-
- generateGroupMgtAgents(lbconfig);
-
- removeGroupMgtAgents(lbconfig, currentServiceConfigs);
-
-// }
-
- } catch (InterruptedException ignore) {
- }
- }
-
- }
-
- private void removeGroupMgtAgents(LoadBalancerConfiguration lbConfig, List<ServiceConfiguration> currentServiceConfigs) {
-
- for (Iterator iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
- Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
-
- for (Iterator iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
- ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
-
- if(!currentServiceConfigs.contains(oldServiceConfig)){
- // if the ServiceConfiguration is not there any more in the latest topology
- lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
- GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
- }
- }
- }
- }
-
- /**
- * @param lbconfig
- */
- private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
- TenantLoadBalanceMembershipHandler handler =
- ConfigHolder.getInstance()
- .getTenantLoadBalanceMembershipHandler();
-
- if (handler == null) {
- String msg =
- "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
- log.error(msg);
- throw new SynapseException(msg);
- }
-
- Map<String, HostContext> hostContexts = lbconfig.getHostContextMap();
-
- // Add the Axis2 GroupManagement agents
- if (hostContexts != null) {
- // iterate through each host context
- for (HostContext hostCtxt : hostContexts.values()) {
- // each host can has multiple Tenant Contexts, iterate through them
- for (TenantDomainContext tenantCtxt : hostCtxt
- .getTenantDomainContexts()) {
-
- String domain = tenantCtxt.getDomain();
- String subDomain = tenantCtxt.getSubDomain();
-
- // creates the group management agent
- GroupMgtAgentBuilder.createGroupMgtAgent(domain,
- subDomain);
- }
-
- // add to the handler
- handler.addHostContext(hostCtxt);
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
deleted file mode 100644
index 1032fc9..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * 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.wso2.carbon.lb.endpoint.cluster.manager;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.wso2.carbon.cartridge.messages.ClusterDomainManager;
-import org.wso2.carbon.cartridge.messages.ClusterDomain;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
-import org.wso2.carbon.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
-import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-
-/**
- * Bridge between the ELB and the Stratos2 Agent.
- */
-public class ClusterDomainManagerImpl implements ClusterDomainManager {
-
- private static final Log log = LogFactory.getLog(ClusterDomainManagerImpl.class);
-
- @Override
- public void addClusterDomain(ClusterDomain cluster) {
-
- // create group management agent, if one doesn't exist already.
- HostContext hostCtxt = createGroupMgtAgentIfNotExists(cluster);
-
- // we should only update if the above step is successful.
- if (hostCtxt != null) {
- // create / update Service Configuration
- createOrUpdateServiceConfig(cluster, hostCtxt);
- }
-
- }
-
- @Override
- public void removeClusterDomain(String domain, String subDomain, String hostName) {
-
- TenantLoadBalanceMembershipHandler handler =
- ConfigHolder.getInstance()
- .getTenantLoadBalanceMembershipHandler();
-
- if (handler == null) {
- String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
- log.error(msg);
- throw new SynapseException(msg);
- }
-
- handler.removeHostContext(hostName);
-
- LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
-
- lbConfig.removeServiceConfiguration(domain, subDomain);
-
- }
-
- private void createOrUpdateServiceConfig(ClusterDomain cluster, HostContext ctxt) {
- LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
-
- String domain = cluster.getDomain();
- String subDomain = cluster.getSubDomain();
-
- if (subDomain == null || subDomain.isEmpty()) {
- // uses default sub domain
- subDomain = Constants.DEFAULT_SUB_DOMAIN;
- }
-
- String hostName = cluster.getHostName();
- String tenantRange = cluster.getTenantRange();
- int minInstances = cluster.getMinInstances();
- int maxInstances = cluster.getMaxInstances();
- String service = cluster.getServiceName();
- int maxRequestsPerSecond = cluster.getMaxRequestsPerSecond();
- int roundsToAverage = cluster.getRoundsToAverage();
- double alarmingUpperRate = cluster.getAlarmingUpperRate();
- double alarmingLowerRate = cluster.getAlarmingLowerRate();
- double scaleDownFactor = cluster.getScaleDownFactor();
-
- ServiceConfiguration serviceConfig ;
-
- if((serviceConfig = lbConfig.getServiceConfig(domain, subDomain)) == null){
- serviceConfig = lbConfig.new ServiceConfiguration();
- }
-
- // we simply override the attributes with new values
- serviceConfig.setDomain(domain);
- serviceConfig.setSub_domain(subDomain);
- serviceConfig.setTenant_range(tenantRange);
- serviceConfig.setHosts(hostName);
- serviceConfig.setMin_app_instances(minInstances);
- serviceConfig.setMax_app_instances(maxInstances);
- serviceConfig.setMax_requests_per_second(maxRequestsPerSecond);
- serviceConfig.setRounds_to_average(roundsToAverage);
- serviceConfig.setAlarming_upper_rate(alarmingUpperRate);
- serviceConfig.setAlarming_lower_rate(alarmingLowerRate);
- serviceConfig.setScale_down_factor(scaleDownFactor);
-
- // add to host name tracker
- lbConfig.addToHostNameTrackerMap(service, serviceConfig.getHosts());
-
- // add to host contexts
- lbConfig.addToHostContextMap(hostName, ctxt);
-
- // finally add this service config
- lbConfig.addServiceConfiguration(serviceConfig);
- }
-
- protected HostContext createGroupMgtAgentIfNotExists(ClusterDomain cluster) {
-
- String domain = cluster.getDomain();
- String subDomain = cluster.getSubDomain();
- String hostName = cluster.getHostName();
- String tenantRange = cluster.getTenantRange();
-
- // sub domain can be null, but others can't
- if (domain == null || hostName == null || tenantRange == null) {
- String msg =
- "Invalid value/s detected - domain: " + domain + "\n host name: " +
- hostName + "\n tenant range: " + tenantRange;
- log.error(msg);
- throw new SynapseException(msg);
- }
-
- if (subDomain == null || subDomain.isEmpty()) {
- // uses default sub domain
- subDomain = Constants.DEFAULT_SUB_DOMAIN;
- }
-
- ClusteringAgent clusteringAgent = null;
-
- try {
- clusteringAgent =
- ConfigHolder.getInstance().getAxisConfiguration()
- .getClusteringAgent();
-
- } catch (Exception e) {
- String msg = "Failed to retrieve Clustering Agent.";
- log.error(msg, e);
- throw new SynapseException(msg, e);
-
- }
-
- if (clusteringAgent == null) {
- String msg = "Clustering Agent is null.";
- log.error(msg);
- throw new SynapseException(msg);
- }
-
- /*
- * Add Group Management Agent if one is not already present for this domain and sub
- * domain
- */
-
- if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
- clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
- domain, subDomain,-1);
-
- if (log.isDebugEnabled()) {
- log.debug("Group management agent added to cluster domain: " + domain +
- " and sub domain: " + subDomain);
- }
-
- } else {
- if (log.isDebugEnabled()) {
- log.debug("Group management agent is already available for cluster domain: " +
- domain + " and sub domain: " + subDomain);
- }
- }
-
- TenantLoadBalanceMembershipHandler handler =
- ConfigHolder.getInstance()
- .getTenantLoadBalanceMembershipHandler();
-
- if (handler == null) {
- String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
- log.error(msg);
- throw new SynapseException(msg);
- }
-
- HostContext hostCtxt;
-
- // if there's an already registered HostContext use it
- if((hostCtxt = handler.getHostContext(hostName)) == null){
- hostCtxt = new HostContext(hostName);
- }
-
- List<TenantDomainContext> ctxts;
- ctxts = new ArrayList<TenantDomainContext>(hostCtxt.getTenantDomainContexts());
-
- // default value is super tenant mode - which is defined by tenant id 0, in this context
- int tenantId = 0;
- if(!"*".equals(tenantRange)){
- tenantId = Integer.parseInt(tenantRange);
- }
-
- ctxts.add(new TenantDomainContext(tenantId, domain, subDomain));
-
- hostCtxt.addTenantDomainContexts(ctxts);
-
- handler.addHostContext(hostCtxt);
-
- return hostCtxt;
- }
-
-}
[03/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
deleted file mode 100644
index 16f392a..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
+++ /dev/null
@@ -1,513 +0,0 @@
-package org.wso2.carbon.lb.endpoint.endpoint;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.util.AXIOMUtil;
-import org.apache.axis2.addressing.EndpointReference;
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.http.protocol.HTTP;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.SynapseConstants;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.config.xml.endpoints.utils.LoadbalanceAlgorithmFactory;
-import org.apache.synapse.core.LoadBalanceMembershipHandler;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
-import org.apache.synapse.endpoints.DynamicLoadbalanceFaultHandler;
-import org.apache.synapse.endpoints.Endpoint;
-import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
-import org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher;
-import org.apache.synapse.endpoints.dispatch.SALSessions;
-import org.apache.synapse.endpoints.dispatch.SessionInformation;
-import org.apache.synapse.transport.nhttp.NhttpConstants;
-import org.wso2.carbon.base.MultitenantConstants;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
-import org.wso2.carbon.lb.common.util.DomainMapping;
-import org.wso2.carbon.lb.common.group.mgt.*;
-import org.wso2.carbon.lb.common.cache.URLMappingCache;
-import org.wso2.carbon.lb.endpoint.TenantAwareLoadBalanceEndpointException;
-import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
-import org.wso2.carbon.lb.endpoint.internal.RegistryManager;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-
-public class TenantAwareLoadBalanceEndpoint extends org.apache.synapse.endpoints.DynamicLoadbalanceEndpoint implements Serializable {
-
- private static final long serialVersionUID = 1577351815951789938L;
- private static final Log log = LogFactory.getLog(TenantAwareLoadBalanceEndpoint.class);
- /**
- * Axis2 based membership handler which handles members in multiple clustering domains
- */
- private TenantLoadBalanceMembershipHandler tlbMembershipHandler;
-
- /**
- * Key - host name
- * Value - {@link HostContext}
- */
- private Map<String, HostContext> hostContexts = new HashMap<String, HostContext>();
-
- private LoadBalancerConfiguration lbConfig;
-
- /**
- * keep the size of cache which used to keep hostNames of url mapping.
- */
- private URLMappingCache mappingCache;
- private RegistryManager registryManager;
- private int sizeOfCache;
-
- private boolean initialized;
-
- private String algorithm;
- private String configuration;
- private String failOver;
-
- @Override
- public void init(SynapseEnvironment synapseEnvironment) {
- try {
-
- lbConfig = ConfigHolder.getInstance().getLbConfig();
- hostContexts = lbConfig.getHostContextMap();
- sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
- mappingCache = URLMappingCache.getInstance(sizeOfCache);
- setSessionTimeout(lbConfig.getLoadBalancerConfig().getSessionTimeOut());
- setFailover(lbConfig.getLoadBalancerConfig().getFailOver());
-
- } catch (Exception e) {
- String msg = "Failed while reading Load Balancer configuration";
- log.error(msg, e);
- throw new TenantAwareLoadBalanceEndpointException(msg, e);
- }
-
-
- LoadbalanceAlgorithm algorithm = null;
- try {
- OMElement payload = AXIOMUtil.stringToOM(generatePayLoad());
- algorithm =
- LoadbalanceAlgorithmFactory.
- createLoadbalanceAlgorithm(payload, null);
-
- } catch (Exception e) {
- String msg = "Error While creating Load balance algorithm";
- log.error(msg, e);
- throw new SynapseException(msg, e);
- }
-
- if (!initialized) {
- super.init(synapseEnvironment);
- ConfigurationContext cfgCtx =
- ((Axis2SynapseEnvironment) synapseEnvironment).getAxis2ConfigurationContext();
- ClusteringAgent clusteringAgent = cfgCtx.getAxisConfiguration().getClusteringAgent();
- if (clusteringAgent == null) {
- throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
- }
-
- // Add the Axis2 GroupManagement agents
- if (hostContexts != null) {
- // iterate through each host context
- for (HostContext hostCtxt : hostContexts.values()) {
- // each host can has multiple Tenant Contexts, iterate through them
- for (TenantDomainContext tenantCtxt : hostCtxt.getTenantDomainContexts()) {
-
- String domain = tenantCtxt.getDomain();
- String subDomain = tenantCtxt.getSubDomain();
-
- if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
- String gmAgentClass = lbConfig.getLoadBalancerConfig().getGroupManagementAgentClass();
- GroupManagementAgent groupManagementAgent;
- if (gmAgentClass != null) {
- try {
- groupManagementAgent = (GroupManagementAgent) Class.forName(gmAgentClass).newInstance();
- } catch (Exception e) {
- String msg = "Cannot instantiate GroupManagementAgent. Class: " + gmAgentClass;
- log.error(msg, e);
- throw new TenantAwareLoadBalanceEndpointException(msg, e);
- }
- } else {
- groupManagementAgent = new SubDomainAwareGroupManagementAgent(subDomain);
- }
- clusteringAgent.addGroupManagementAgent(groupManagementAgent,
- domain, subDomain,-1);
- if (log.isDebugEnabled()) {
- log.debug("Group management agent added to cluster domain: " +
- domain + " and sub domain: " + subDomain);
- }
- }
- }
- }
-
- tlbMembershipHandler =
- new TenantLoadBalanceMembershipHandler(hostContexts,
- algorithm, cfgCtx,
- isClusteringEnabled,
- getName());
-
- // set TenantLoadBalanceMembershipHandler for future reference
- ConfigHolder.getInstance().setTenantLoadBalanceMembershipHandler(tlbMembershipHandler);
- }
-
- // Initialize the SAL Sessions if already has not been initialized.
- SALSessions salSessions = SALSessions.getInstance();
- if (!salSessions.isInitialized()) {
- salSessions.initialize(isClusteringEnabled, cfgCtx);
- }
- setSessionAffinity(true);
- setDispatcher(new HttpSessionDispatcher());
- initialized = true;
- log.info("Tenant Aware Load Balance Endpoint is initialized.");
- }
-
- }
-
- public void setConfiguration(String paramEle) {
- configuration = paramEle;
- }
-
- public void setAlgorithm(String paramEle) {
- this.algorithm = paramEle;
- }
-
- public void setFailOver(String paramEle) {
- this.failOver = paramEle;
- }
-
-
- public String getName() {
- return "tlbEndpoint";
- }
-
- //TODO remove following hard coded element
- private String generatePayLoad() {
- return " <serviceDynamicLoadbalance failover=\"true\"\n" +
- " algorithm=\"org.apache.synapse.endpoints.algorithms.RoundRobin\"" +
- //" configuration=\"$system:loadbalancer.xml\"" +
- "/>";
- }
-
- public LoadBalanceMembershipHandler getLbMembershipHandler() {
- return tlbMembershipHandler;
- }
-
-
- public void send(MessageContext synCtx) {
- /* setCookieHeader(synCtx); */
- Member currentMember = null;
- SessionInformation sessionInformation = null;
- String actualHost = null;
-
- //Gathering required information for domain mapping
- org.apache.axis2.context.MessageContext axis2MessageContext =
- ((Axis2MessageContext) synCtx).getAxis2MessageContext();
- Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
- getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
- String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
-
- String port = "";
- boolean containsPort = false;
- if (targetHost.contains(":")) {
- containsPort = true;
- port = targetHost.substring(targetHost.indexOf(':') + 1, targetHost.length());
- targetHost = targetHost.substring(0, targetHost.indexOf(':'));
- }
- //Gathering required information for domain mapping done
-
- boolean isValidHost = tlbMembershipHandler.isAValidHostName(targetHost);
- DomainMapping domainMapping = null;
- if(!isValidHost){
- //check if the host is valid, if not valid, execute following code to check whether it is a mapped domain
- domainMapping = mappingCache.getMapping(targetHost);
- if(domainMapping == null){
- registryManager = new RegistryManager();
- domainMapping = registryManager.getMapping(targetHost);
- mappingCache.addValidMapping(targetHost, domainMapping);
- }
- if (domainMapping != null) {
- actualHost = domainMapping.getActualHost();
-
- if(containsPort){
- transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
- } else {
- transportHeaders.put(HTTP.TARGET_HOST, actualHost);
- }
- ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
-
- } else {
- String msg = "Invalid host name : " + targetHost;
- log.error(msg);
- throw new SynapseException(msg);
- }
- }
-
- if (isSessionAffinityBasedLB()) {
- // first check if this session is associated with a session. if so, get the endpoint
- // associated for that session.
- sessionInformation =
- (SessionInformation) synCtx.getProperty(
- SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
-
- currentMember = (Member) synCtx.getProperty(
- SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER);
-
- if (sessionInformation == null && currentMember == null) {
- sessionInformation = dispatcher.getSession(synCtx);
- if (sessionInformation != null) {
-
- if (log.isDebugEnabled()) {
- log.debug("Current session id : " + sessionInformation.getId());
- }
-
- currentMember = sessionInformation.getMember();
- synCtx.setProperty(
- SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
- // This is for reliably recovery any session information if while response is getting ,
- // session information has been removed by cleaner.
- // This will not be a cost as session information a not heavy data structure
- synCtx.setProperty(
- SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
- }
- }
-
- }
-
- // Dispatch request the relevant member
-// String targetHost = getTargetHost(synCtx);
- ConfigurationContext configCtx =
- ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
-
- if (tlbMembershipHandler.getConfigurationContext() == null) {
- tlbMembershipHandler.setConfigurationContext(configCtx);
- }
-
- if(tlbMembershipHandler.getClusteringAgent() == null) {
- tlbMembershipHandler.setConfigurationContext(configCtx);
- }
-
- TenantDynamicLoadBalanceFaultHandlerImpl faultHandler = new TenantDynamicLoadBalanceFaultHandlerImpl();
- log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
- faultHandler.setHost(actualHost != null ? actualHost : targetHost);
-
- if (sessionInformation != null && currentMember != null) {
- //send message on current session
- sessionInformation.updateExpiryTime();
- sendToApplicationMember(synCtx, currentMember, faultHandler, false);
- } else {
-// prepare for a new session
- int tenantId = getTenantId(synCtx);
- //check if this is a valid host name registered in ELB
- if(tlbMembershipHandler.isAValidHostName(targetHost)){
- currentMember = tlbMembershipHandler.getNextApplicationMember(targetHost, tenantId);
- if (currentMember == null) {
- String msg = "No application members available";
- log.error(msg);
- throw new SynapseException(msg);
- }
- sendToApplicationMember(synCtx, currentMember, faultHandler, true);
- } else {
- if(domainMapping == null){
- registryManager = new RegistryManager();
- domainMapping = registryManager.getMapping(targetHost);
- mappingCache.addValidMapping(targetHost, domainMapping);
- }
- if(domainMapping != null) {
-
- actualHost = domainMapping.getActualHost();
-
- log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
- faultHandler.setHost(actualHost != null ? actualHost : targetHost);
-
- if(containsPort){
- transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
- } else {
- transportHeaders.put(HTTP.TARGET_HOST, actualHost);
- }
- ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
-
- currentMember = tlbMembershipHandler.getNextApplicationMember(actualHost,tenantId);
- sendToApplicationMember(synCtx,currentMember,faultHandler,true);
- }else {
- String msg = "Invalid host name : " + targetHost;
- log.error(msg);
- throw new SynapseException(msg);
- }
- }
- }
- }
-
-
-// public List<HostContext> getHostContexts() {
-// return Collections.unmodifiableList(hostContexts);
-// }
-
- /**
- * This FaultHandler will try to resend the message to another member if an error occurs
- * while sending to some member. This is a failover mechanism
- */
-
- /**
- * @param url to url for target
- * @return tenantID if tenant id available else 0
- */
- private int getTenantId(String url) {
- String servicesPrefix = "/t/";
- if (url != null && url.contains(servicesPrefix)) {
- int domainNameStartIndex =
- url.indexOf(servicesPrefix) + servicesPrefix.length();
- int domainNameEndIndex = url.indexOf('/', domainNameStartIndex);
- String domainName = url.substring(domainNameStartIndex,
- domainNameEndIndex == -1 ? url.length() : domainNameEndIndex);
-
- // return tenant id if domain name is not null
- if (domainName != null) {
- try {
- return ConfigHolder.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;
- }
-
- private int getTenantId(MessageContext synCtx){
- String url = synCtx.getTo().toString();
- int tenantId = getTenantId(url);
- // tenantId = 0 because domain name was null. May be this is the SSO response
- if(tenantId == 0 && url.contains(MultitenantConstants.TENANT_DOMAIN+"=")){
- // OK,this is the SAML SSO response from the IS
- // e.g url = https://localhost:9444/acs?teantDomain=domain
- String domainName = url.split("=").clone()[1];
- // return tenant id if domain name is not null
- if (domainName != null) {
- try {
- return ConfigHolder.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 tenantId;
- }
-
-
- /**
- * This FaultHandler will try to resend the message to another member if an error occurs
- * while sending to some member. This is a failover mechanism
- */
- private class TenantDynamicLoadBalanceFaultHandlerImpl extends DynamicLoadbalanceFaultHandler {
-
- private EndpointReference to;
- private Member currentMember;
- private Endpoint currentEp;
- private String host;
-
- private static final int MAX_RETRY_COUNT = 5;
-
- // ThreadLocal variable to keep track of how many times this fault handler has been
- // called
- private ThreadLocal<Integer> callCount = new ThreadLocal<Integer>() {
- protected Integer initialValue() {
- return 0;
- }
- };
-
- public void setHost(String host) {
- log.debug("Setting host name: "+host);
- this.host = host;
- }
-
- public void setCurrentMember(Member currentMember) {
- this.currentMember = currentMember;
- }
-
- public void setTo(EndpointReference to) {
- this.to = to;
- }
-
- private TenantDynamicLoadBalanceFaultHandlerImpl() {
- }
-
- public void onFault(MessageContext synCtx) {
- if (currentMember == null || to == null) {
- return;
- }
-
- // Prevent infinite retrying to failed members
- callCount.set(callCount.get() + 1);
- if (callCount.get() >= MAX_RETRY_COUNT) {
- log.debug("Retrying to a failed member has stopped.");
- return;
- }
-
- //cleanup endpoint if exists
- if (currentEp != null) {
- currentEp.destroy();
- }
- Integer errorCode = (Integer) synCtx.getProperty(SynapseConstants.ERROR_CODE);
- if (errorCode != null) {
- if (errorCode.equals(NhttpConstants.CONNECTION_FAILED)) {
- currentMember.suspend(10000); // TODO: Make this configurable.
- log.info("Suspended member " + currentMember + " for 10s due to connection failure to that member");
- }
- if (errorCode.equals(NhttpConstants.CONNECTION_FAILED) ||
- errorCode.equals(NhttpConstants.CONNECT_CANCEL) ||
- errorCode.equals(NhttpConstants.CONNECT_TIMEOUT)) {
-
- if (!synCtx.getFaultStack().isEmpty()) {
- synCtx.getFaultStack().pop();
- }
- // Try to resend to another member
- Member newMember = tlbMembershipHandler.getNextApplicationMember(host, getTenantId(synCtx.toString()));
- if (newMember == null || newMember.isSuspended()) {
- String msg = "No application members available having host name : "+host+
- " and tenant id : "+getTenantId(synCtx.toString()+" and which is not suspended.");
- log.error(msg);
- throw new SynapseException(msg);
- }
- synCtx.setTo(to);
- if (isSessionAffinityBasedLB()) {
- // We are sending this message on a new session,
- // hence we need to remove previous session information
- Set pros = synCtx.getPropertyKeySet();
- if (pros != null) {
- pros.remove(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
- }
- }
- try {
- Thread.sleep(1000); // Sleep for sometime before retrying
- } catch (InterruptedException ignored) {
- }
-
- if(synCtx == null || to == null) {
- return;
- }
- log.info("Failed over to " + newMember);
- sendToApplicationMember(synCtx, newMember, this, true);
- } else if (errorCode.equals(NhttpConstants.SND_IO_ERROR_SENDING) ||
- errorCode.equals(NhttpConstants.CONNECTION_CLOSED)) {
- // TODO: Envelope is consumed
- String msg = "Error sending request! Connection to host "+host+
- " might be closed. Error code: "+errorCode;
- log.error(msg);
- throw new SynapseException(msg);
- }
- }
- // We cannot failover since we are using binary relay
- }
-
- public void setCurrentEp(Endpoint currentEp) {
- this.currentEp = currentEp;
- }
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
deleted file mode 100644
index da25156..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package org.wso2.carbon.lb.endpoint.group.mgt;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.wso2.carbon.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-
-/**
- * Responsible for building {@link GroupManagementAgent}s.
- */
-public class GroupMgtAgentBuilder {
-
- private static final Log log = LogFactory.getLog(GroupMgtAgentBuilder.class);
-
- /**
- * Creates a {@link SubDomainAwareGroupManagementAgent} corresponds to the given
- * parameters, if and only if there's no existing agent.
- * @param domain clustering domain.
- * @param subDomain clustering sub domain.
- */
- public static void createGroupMgtAgent(String domain, String subDomain) {
-
- ClusteringAgent clusteringAgent =
- ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
-
- if (clusteringAgent == null) {
- throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
- }
-
- // checks the existence.
- if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
-
- clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
- domain, subDomain,-1);
-
- log.info("Group management agent added to cluster domain: " +
- domain + " and sub domain: " + subDomain);
- }
- }
-
- public static void resetGroupMgtAgent(String domain, String subDomain) {
-
- ClusteringAgent clusteringAgent =
- ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
-
- if (clusteringAgent == null) {
- throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
- }
-
- // checks the existence.
- if (clusteringAgent.getGroupManagementAgent(domain, subDomain) != null) {
-
- clusteringAgent.resetGroupManagementAgent(domain, subDomain);
-
- log.info("Group management agent of cluster domain: " +
- domain + " and sub domain: " + subDomain+" is removed.");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
deleted file mode 100644
index 7cdd8c8..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * 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.wso2.carbon.lb.endpoint.internal;
-
-import org.apache.axis2.deployment.DeploymentEngine;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.Mediator;
-import org.apache.synapse.config.SynapseConfiguration;
-import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.deployers.SynapseArtifactDeploymentStore;
-import org.apache.synapse.endpoints.Endpoint;
-import org.apache.synapse.mediators.base.SequenceMediator;
-import org.apache.synapse.mediators.builtin.SendMediator;
-import org.apache.synapse.mediators.filters.InMediator;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.cartridge.messages.CreateClusterDomainMessage;
-import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
-import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
-import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
-import org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService;
-import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
-import org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
-import org.wso2.carbon.lb.endpoint.EndpointDeployer;
-import org.wso2.carbon.lb.endpoint.TenantAwareLoadBalanceEndpointException;
-import org.wso2.carbon.lb.endpoint.builder.TopologySyncher;
-import org.wso2.carbon.lb.endpoint.cluster.manager.ClusterDomainManagerImpl;
-import org.wso2.carbon.lb.endpoint.endpoint.TenantAwareLoadBalanceEndpoint;
-import org.wso2.carbon.lb.endpoint.subscriber.TopologySubscriber;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-import org.wso2.carbon.lb.endpoint.util.TopologyConstants;
-
-import java.io.File;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @scr.component name="org.wso2.carbon.load.balancer.endpoint" immediate="true"
- * @scr.reference name="configuration.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
- * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
- * @scr.reference name="synapse.config.service"
- * interface="org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService"
- * cardinality="1..1" policy="dynamic" bind="setSynapseConfigurationService"
- * unbind="unsetSynapseConfigurationService"
- * @scr.reference name="synapse.env.service"
- * interface="org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService"
- * cardinality="1..n" policy="dynamic" bind="setSynapseEnvironmentService"
- * unbind="unsetSynapseEnvironmentService"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService"
- * cardinality="1..1" policy="dynamic"
- * bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="dependency.mgt.service"
- * interface="org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService"
- * cardinality="0..1" policy="dynamic"
- * bind="setDependencyManager" unbind="unsetDependencyManager"
- * @scr.reference name="synapse.registrations.service"
- * interface="org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService"
- * cardinality="1..n" policy="dynamic" bind="setSynapseRegistrationsService"
- * unbind="unsetSynapseRegistrationsService"
- * @scr.reference name="user.realmservice.default"
- * interface="org.wso2.carbon.user.core.service.RealmService"
- * cardinality="1..1" policy="dynamic" bind="setRealmService"
- * unbind="unsetRealmService"
- * @scr.reference name="org.wso2.carbon.lb.common"
- * interface="org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService"
- * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
- * unbind="unsetLoadBalancerConfigurationService"
- */
-@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
-public class LoadBalanceEndpointServiceComponent {
-
- private static final Log log = LogFactory.getLog(LoadBalanceEndpointServiceComponent.class);
-
- private boolean activated = false;
-
- protected void activate(ComponentContext ctxt) {
- try {
- SynapseEnvironmentService synEnvService =
- ConfigHolder.getInstance()
- .getSynapseEnvironmentService(MultitenantConstants.SUPER_TENANT_ID);
-
- registerDeployer(ConfigHolder.getInstance().getAxisConfiguration(),
- synEnvService.getSynapseEnvironment());
-
- if (ConfigHolder.getInstance().getConfigCtxt() != null) {
- ConfigHolder
- .getInstance()
- .getConfigCtxt()
- .setNonReplicableProperty(
- CreateClusterDomainMessage.CLUSTER_DOMAIN_MANAGER,
- new ClusterDomainManagerImpl());
- log.debug("Setting property Cluster Domain MANAGER ... ");
-
- }
-
- SynapseEnvironment synapseEnv = synEnvService.getSynapseEnvironment();
-
- /* Registering Tenant Aware Load Balance Endpoint */
-
- // get the main sequence mediator
- SequenceMediator mainSequence =
- (SequenceMediator) synapseEnv.getSynapseConfiguration()
- .getSequence("main");
-
- boolean successfullyRegistered = false;
-
- // iterate through its child mediators
- for (Mediator child : mainSequence.getList()) {
-
- // find the InMediator
- if (child instanceof InMediator) {
-
- for(Mediator inChild : ((InMediator)child).getList()){
-
- // find the SendMediator
- if (inChild instanceof SendMediator) {
-
- SendMediator sendMediator = (SendMediator) inChild;
-
- /* add Tenant Aware LB endpoint */
-
- TenantAwareLoadBalanceEndpoint tenantAwareEp = new TenantAwareLoadBalanceEndpoint();
-
- tenantAwareEp.init(synapseEnv);
-
- sendMediator.setEndpoint(tenantAwareEp);
-
- successfullyRegistered = true;
-
- if (log.isDebugEnabled()) {
- log.debug("Added Tenant Aware Endpoint: " +
- sendMediator.getEndpoint().getName() + "" +
- " to Send Mediator.");
- }
- }
- }
- }
- }
-
- if(!successfullyRegistered){
- String msg = "Failed to register Tenant Aware Load Balance Endpoint in Send Mediator.";
- log.fatal(msg);
- throw new TenantAwareLoadBalanceEndpointException(msg);
- }
-
- if (log.isDebugEnabled()) {
- log.debug("Endpoint Admin bundle is activated ");
- }
-
- if (ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl() != null) {
-
- // start consumer
- // initialize TopologyBuilder Consumer
- Thread topologyConsumer =
- new Thread(new TopologySyncher(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
- // start consumer
- topologyConsumer.start();
-
- TopologySubscriber.subscribe(TopologyConstants.TOPIC_NAME);
-
- }
- activated = true;
- } catch (Throwable e) {
- log.error("Failed to activate Endpoint Admin bundle ", e);
- }
- }
-
- protected void deactivate(ComponentContext context) {
- try {
- Set<Map.Entry<Integer, SynapseEnvironmentService>> entrySet =
- ConfigHolder.getInstance().getSynapseEnvironmentServices().entrySet();
- for (Map.Entry<Integer, SynapseEnvironmentService> entry : entrySet) {
- unregisterDeployer(
- entry.getValue().getConfigurationContext().getAxisConfiguration(),
- entry.getValue().getSynapseEnvironment());
- }
- } catch (Exception e) {
- log.warn("Couldn't remove the EndpointDeployer");
- }
- }
-
- /**
- * Un-registers the Endpoint deployer.
- *
- * @param axisConfig AxisConfiguration to which this deployer belongs
- * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
- */
- private void unregisterDeployer(AxisConfiguration axisConfig, SynapseEnvironment synapseEnvironment)
- throws TenantAwareLoadBalanceEndpointException {
- if (axisConfig != null) {
- DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig.getConfigurator();
- String synapseConfigPath = ServiceBusUtils.getSynapseConfigAbsPath(
- synapseEnvironment.getServerContextInformation());
- String endpointDirPath = synapseConfigPath
- + File.separator + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
- deploymentEngine.removeDeployer(
- endpointDirPath, ServiceBusConstants.ARTIFACT_EXTENSION);
- }
- }
-
- /**
- * Registers the Endpoint deployer.
- *
- * @param axisConfig AxisConfiguration to which this deployer belongs
- * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
- */
- private void registerDeployer(AxisConfiguration axisConfig, SynapseEnvironment synapseEnvironment)
- throws TenantAwareLoadBalanceEndpointException {
- SynapseConfiguration synCfg = synapseEnvironment.getSynapseConfiguration();
- DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig.getConfigurator();
- SynapseArtifactDeploymentStore deploymentStore = synCfg.getArtifactDeploymentStore();
-
- String synapseConfigPath = ServiceBusUtils.getSynapseConfigAbsPath(
- synapseEnvironment.getServerContextInformation());
- String endpointDirPath = synapseConfigPath
- + File.separator + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
-
- for (Endpoint ep : synCfg.getDefinedEndpoints().values()) {
- if (ep.getFileName() != null) {
- deploymentStore.addRestoredArtifact(
- endpointDirPath + File.separator + ep.getFileName());
- }
- }
- deploymentEngine.addDeployer(
- new EndpointDeployer(), endpointDirPath, ServiceBusConstants.ARTIFACT_EXTENSION);
- }
-
- protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
- ConfigHolder.getInstance().setAxisConfiguration(
- cfgCtxService.getServerConfigContext().getAxisConfiguration());
- ConfigHolder.getInstance().setConfigCtxt(cfgCtxService.getServerConfigContext());
- }
-
- protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
- ConfigHolder.getInstance().setAxisConfiguration(null);
- ConfigHolder.getInstance().setConfigCtxt(null);
- }
-
- protected void setSynapseConfigurationService(
- SynapseConfigurationService synapseConfigurationService) {
-
- ConfigHolder.getInstance().setSynapseConfiguration(
- synapseConfigurationService.getSynapseConfiguration());
- }
-
- protected void unsetSynapseConfigurationService(
- SynapseConfigurationService synapseConfigurationService) {
-
- ConfigHolder.getInstance().setSynapseConfiguration(null);
- }
-
- /**
- * Here we receive an event about the creation of a SynapseEnvironment. If this is
- * SuperTenant we have to wait until all the other constraints are met and actual
- * initialization is done in the activate method. Otherwise we have to do the activation here.
- *
- * @param synapseEnvironmentService SynapseEnvironmentService which contains information
- * about the new Synapse Instance
- */
- protected void setSynapseEnvironmentService(
- SynapseEnvironmentService synapseEnvironmentService) {
- boolean alreadyCreated = ConfigHolder.getInstance().getSynapseEnvironmentServices().
- containsKey(synapseEnvironmentService.getTenantId());
-
- ConfigHolder.getInstance().addSynapseEnvironmentService(
- synapseEnvironmentService.getTenantId(),
- synapseEnvironmentService);
- if (activated) {
- if (!alreadyCreated) {
- try {
- registerDeployer(synapseEnvironmentService.getConfigurationContext().getAxisConfiguration(),
- synapseEnvironmentService.getSynapseEnvironment());
- if (log.isDebugEnabled()) {
- log.debug("Endpoint Admin bundle is activated ");
- }
- } catch (Throwable e) {
- log.error("Failed to activate Endpoint Admin bundle ", e);
- }
- }
- }
- }
-
- /**
- * Here we receive an event about Destroying a SynapseEnvironment. This can be the super tenant
- * destruction or a tenant destruction.
- *
- * @param synapseEnvironmentService synapseEnvironment
- */
- protected void unsetSynapseEnvironmentService(
- SynapseEnvironmentService synapseEnvironmentService) {
- ConfigHolder.getInstance().removeSynapseEnvironmentService(
- synapseEnvironmentService.getTenantId());
- }
-
- protected void setRegistryService(RegistryService regService) {
- if (log.isDebugEnabled()) {
- log.debug("RegistryService bound to the endpoint component");
- }
- try {
- ConfigHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
- ConfigHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
- } catch (RegistryException e) {
- log.error("Couldn't retrieve the registry from the registry service");
- }
- }
-
- protected void unsetRegistryService(RegistryService regService) {
- if (log.isDebugEnabled()) {
- log.debug("RegistryService unbound from the endpoint component");
- }
- ConfigHolder.getInstance().setConfigRegistry(null);
- }
-
- protected void setDependencyManager(DependencyManagementService dependencyMgr) {
- if (log.isDebugEnabled()) {
- log.debug("Dependency management service bound to the endpoint component");
- }
- ConfigHolder.getInstance().setDependencyManager(dependencyMgr);
- }
-
- protected void unsetDependencyManager(DependencyManagementService dependencyMgr) {
- if (log.isDebugEnabled()) {
- log.debug("Dependency management service unbound from the endpoint component");
- }
- ConfigHolder.getInstance().setDependencyManager(null);
- }
-
- protected void setSynapseRegistrationsService(
- SynapseRegistrationsService synapseRegistrationsService) {
-
- }
-
- protected void unsetSynapseRegistrationsService(
- SynapseRegistrationsService synapseRegistrationsService) {
- int tenantId = synapseRegistrationsService.getTenantId();
- if (ConfigHolder.getInstance().getSynapseEnvironmentServices().containsKey(tenantId)) {
- SynapseEnvironment env = ConfigHolder.getInstance().
- getSynapseEnvironmentService(tenantId).getSynapseEnvironment();
-
- ConfigHolder.getInstance().removeSynapseEnvironmentService(
- synapseRegistrationsService.getTenantId());
-
- AxisConfiguration axisConfig = synapseRegistrationsService.getConfigurationContext().
- getAxisConfiguration();
- if (axisConfig != null) {
- try {
- unregisterDeployer(axisConfig, env);
- } catch (Exception e) {
- log.warn("Couldn't remove the EndpointDeployer");
- }
- }
- }
- }
-
- protected void setRealmService(RealmService realmService) {
- ConfigHolder.getInstance().setRealmService(realmService);
- }
-
- protected void unsetRealmService(RealmService realmService) {
- ConfigHolder.getInstance().setRealmService(null);
- }
-
- protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
- ConfigHolder.getInstance().setLbConfigService(lbConfigSer);
- }
-
- protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
- ConfigHolder.getInstance().setLbConfigService(null);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java
deleted file mode 100644
index 0f42aad..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright WSO2 Inc.
- *
- * 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.wso2.carbon.lb.endpoint.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-import org.wso2.carbon.lb.common.util.DomainMapping;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-
-public class RegistryManager {
- UserRegistry governanceRegistry = ConfigHolder.getInstance().getGovernanceRegistry();
- private static final Log log = LogFactory.getLog(RegistryManager.class);
- /**
- *
- */
- private Resource resource = null;
- public static final String HOST_INFO = "hostinfo/";
- public static final String ACTUAL_HOST = "actual.host";
-
- public DomainMapping getMapping(String hostName) {
- DomainMapping domainMapping;
- try {
- if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
- resource = governanceRegistry.get(HOST_INFO + hostName);
- domainMapping = new DomainMapping(hostName);
- domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
- return domainMapping;
- }
- } catch (RegistryException e) {
- log.info("Error while getting registry resource");
- throw new RuntimeException(e);
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java
deleted file mode 100644
index dd05f83..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-* 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.wso2.carbon.lb.endpoint.subscriber;
-
-import javax.jms.TopicSubscriber;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * This health checker runs forever, and is responsible for re-establishing a connection
- * between ELB and CC.
- */
-public class TopicHealthChecker implements Runnable{
-
- private static final Log log = LogFactory.getLog(TopicHealthChecker.class);
- private String topicName;
- private TopicSubscriber subscriber;
-
- public TopicHealthChecker(String topicName, TopicSubscriber subscriber) {
- this.topicName = topicName;
- this.subscriber = subscriber;
- }
-
- @Override
- public void run() {
- log.info("Topic Health Checker is running... ");
-
- while (true) {
- try {
- subscriber.getTopic();
-
- // health checker runs in every 30s
- Thread.sleep(30000);
-
- } catch (Exception e) {
- // implies connection is not established
- // sleep for 5s and retry
- try {
- log.info("Health checker failed and will retry to establish a connection after a 5s.");
- Thread.sleep(5000);
- break;
- } catch (InterruptedException ignore) {
- }
- }
-
- }
-
- TopologySubscriber.subscribe(topicName);
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java
deleted file mode 100644
index ed30069..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package org.wso2.carbon.lb.endpoint.subscriber;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.TextMessage;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-
-public class TopologyListener implements MessageListener {
-
- private static final Log log = LogFactory.getLog(TopologyListener.class);
-
- @Override
- public void onMessage(Message message) {
- TextMessage receivedMessage = (TextMessage) message;
- try {
-
- ConfigHolder.getInstance().getSharedTopologyDiffQueue().add(receivedMessage.getText());
-
- } catch (JMSException e) {
- log.error(e.getMessage(), e);
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java
deleted file mode 100644
index a36445a..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package org.wso2.carbon.lb.endpoint.subscriber;
-
-import java.util.Properties;
-
-import javax.jms.*;
-import javax.naming.InitialContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
-import org.wso2.carbon.lb.endpoint.util.TopologyConstants;
-
-public class TopologySubscriber {
-
- private static final Log log = LogFactory.getLog(TopologySubscriber.class);
-
- public static void subscribe(String topicName) {
- Properties initialContextProperties = new Properties();
- TopicSubscriber topicSubscriber = null;
- TopicSession topicSession = null;
- TopicConnection topicConnection = null;
- InitialContext initialContext = null;
-
- initialContextProperties.put("java.naming.factory.initial",
- "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
-
- String mbServerUrl = null;
- if (ConfigHolder.getInstance().getLbConfig() != null) {
- mbServerUrl = ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl();
- }
- String connectionString =
- "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" +
- (mbServerUrl == null ? TopologyConstants.DEFAULT_MB_SERVER_URL : mbServerUrl) + "'&reconnect='true'";
- initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
-
- try {
- initialContext = new InitialContext(initialContextProperties);
- TopicConnectionFactory topicConnectionFactory =
- (TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
- topicConnection = topicConnectionFactory.createTopicConnection();
- topicConnection.start();
- topicSession =
- topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Topic topic = topicSession.createTopic(topicName);
- topicSubscriber =
- topicSession.createSubscriber(topic);
-
- topicSubscriber.setMessageListener(new TopologyListener());
-
- } catch (Exception e) {
- log.error(e.getMessage(), e);
-
- try {
- if (topicSubscriber != null) {
- topicSubscriber.close();
- }
-
- if (topicSession != null) {
- topicSession.close();
- }
-
- if (topicConnection != null) {
- topicConnection.close();
- }
- } catch (JMSException e1) {
- // ignore
- }
-
- }
- finally {
- // start the health checker
- Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
- healthChecker.start();
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java
deleted file mode 100644
index 59f68ae..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/**
- * 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.wso2.carbon.lb.endpoint.util;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.config.SynapseConfiguration;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
-import org.wso2.carbon.lb.endpoint.TenantAwareLoadBalanceEndpointException;
-import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
-import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
-import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.service.RealmService;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-/**
- *
- */
-public class ConfigHolder {
-
- private static ConfigHolder instance;
- private static final Log log = LogFactory.getLog(ConfigHolder.class);
-
- private SynapseConfiguration synapseConfiguration;
- private ConfigurationContext configCtxt;
- private AxisConfiguration axisConfiguration;
- private UserRegistry configRegistry;
- private UserRegistry governanceRegistry;
- private DependencyManagementService dependencyManager;
- private TenantLoadBalanceMembershipHandler tenantMembershipHandler;
- private LoadBalancerConfigurationService lbConfigService;
- private BlockingQueue<String> sharedTopologyQueue = new LinkedBlockingQueue<String>();
- private String previousMsg;
-
-
- private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices =
- new HashMap<Integer, SynapseEnvironmentService>();
-
- public RealmService getRealmService() {
- return realmService;
- }
-
- public void setRealmService(RealmService realmService) {
- this.realmService = realmService;
- }
-
- private RealmService realmService;
-
- private ConfigHolder() {
- }
-
- public static ConfigHolder getInstance() {
- if (instance == null) {
- instance = new ConfigHolder();
- }
- return instance;
- }
-
- public SynapseConfiguration getSynapseConfiguration() throws TenantAwareLoadBalanceEndpointException{
- assertNull("SynapseConfiguration", synapseConfiguration);
- return synapseConfiguration;
- }
-
- public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
- this.synapseConfiguration = synapseConfiguration;
- }
-
- public AxisConfiguration getAxisConfiguration() throws TenantAwareLoadBalanceEndpointException {
- assertNull("AxisConfiguration", axisConfiguration);
- return axisConfiguration;
- }
-
- public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
- this.axisConfiguration = axisConfiguration;
- }
-
- public UserRegistry getConfigRegistry() throws TenantAwareLoadBalanceEndpointException {
- assertNull("Registry", configRegistry);
- return configRegistry;
- }
-
- public void setConfigRegistry(UserRegistry configRegistry) {
- this.configRegistry = configRegistry;
- }
-
- public DependencyManagementService getDependencyManager() {
- return dependencyManager;
- }
-
- public void setDependencyManager(DependencyManagementService dependencyManager) {
- this.dependencyManager = dependencyManager;
- }
-
- private void assertNull(String name, Object object) throws TenantAwareLoadBalanceEndpointException {
- if (object == null) {
- String message = name + " reference in the proxy admin config holder is null";
- log.error(message);
- throw new TenantAwareLoadBalanceEndpointException(message);
- }
- }
-
- public UserRegistry getGovernanceRegistry() {
- return governanceRegistry;
- }
-
- public void setGovernanceRegistry(UserRegistry governanceRegistry) {
- this.governanceRegistry = governanceRegistry;
- }
-
- public SynapseEnvironmentService getSynapseEnvironmentService(int id) {
- return synapseEnvironmentServices.get(id);
- }
-
- public void addSynapseEnvironmentService(int id,
- SynapseEnvironmentService synapseEnvironmentService) {
- synapseEnvironmentServices.put(id, synapseEnvironmentService);
- }
-
- public void removeSynapseEnvironmentService(int id) {
- synapseEnvironmentServices.remove(id);
- }
-
- public Map<Integer, SynapseEnvironmentService> getSynapseEnvironmentServices() {
- return synapseEnvironmentServices;
- }
-
- public void setTenantLoadBalanceMembershipHandler(TenantLoadBalanceMembershipHandler handler) {
- tenantMembershipHandler = handler;
- }
-
- public TenantLoadBalanceMembershipHandler getTenantLoadBalanceMembershipHandler() {
- return tenantMembershipHandler;
- }
-
- public ConfigurationContext getConfigCtxt() {
- return configCtxt;
- }
-
- public void setConfigCtxt(ConfigurationContext configCtxt) {
- this.configCtxt = configCtxt;
- }
-
- public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
- this.lbConfigService = lbConfigSer;
- }
-
- public LoadBalancerConfiguration getLbConfig() {
- return (LoadBalancerConfiguration) lbConfigService.getLoadBalancerConfig();
- }
-
- public BlockingQueue<String> getSharedTopologyDiffQueue() {
- return sharedTopologyQueue;
- }
-
- public void setSharedTopologyDiffQueue(BlockingQueue<String> sharedTopologyDiffQueue) {
- this.sharedTopologyQueue = sharedTopologyDiffQueue;
- }
-
- public String getPreviousMsg() {
- return previousMsg;
- }
-
- public void setPreviousMsg(String previousMsg) {
- this.previousMsg = previousMsg;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java
deleted file mode 100644
index 7e2fb79..0000000
--- a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package org.wso2.carbon.lb.endpoint.util;
-
-public class TopologyConstants {
-
- public static final String TOPIC_NAME = "cloud-controller-topology";
- public static final String MB_SERVER_URL = "mb.server.ip";
- public static final String DEFAULT_MB_SERVER_URL = "localhost:5672";
-
- public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
- public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySubscriberTaskOfADC";
- public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SUBSCRIBER_TASK";
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.apache.stratos.lb.common/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.apache.stratos.lb.common/4.1.3/pom.xml b/components/load-balancer/org.apache.stratos.lb.common/4.1.3/pom.xml
index 717385e..3caecf5 100644
--- a/components/load-balancer/org.apache.stratos.lb.common/4.1.3/pom.xml
+++ b/components/load-balancer/org.apache.stratos.lb.common/4.1.3/pom.xml
@@ -20,12 +20,12 @@
<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.wso2.carbon</groupId>
+ <parent>
+ <groupId>org.apache.stratos</groupId>
<artifactId>loadbalancer-components</artifactId>
<version>4.1.0</version>
<relativePath>../../pom.xml</relativePath>
- </parent-->
+ </parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.stratos</groupId>
@@ -39,23 +39,22 @@
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
- <version>4.1.0</version>
+ <version>${wso2carbon.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava.wso2</groupId>
<artifactId>guava</artifactId>
- <version>12.0.0.wso2v1</version>
- <!--version>${google.guava.wso2.version}</version-->
+ <version>${google.guava.wso2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.synapse</groupId>
<artifactId>synapse-core</artifactId>
- <version>2.1.1-wso2v4</version>
+ <version>${synapse.core.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>3.8.2</version>
+ <version>${junit.version}</version>
</dependency>
<!--dependency>
<groupId>org.testng</groupId>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/main/Main1.iml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/main/Main1.iml b/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/main/Main1.iml
index 7c21d05..76c5866 100644
--- a/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/main/Main1.iml
+++ b/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/main/Main1.iml
@@ -3,7 +3,7 @@
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/../../../../org.wso2.carbon.lb.common/4.1.3/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/test/Test.iml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/test/Test.iml b/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/test/Test.iml
index 26aaeb1..0eb6e7a 100644
--- a/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/test/Test.iml
+++ b/components/load-balancer/org.apache.stratos.lb.common/4.1.3/src/test/Test.iml
@@ -3,7 +3,7 @@
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
- <sourceFolder url="file://$MODULE_DIR$/../../../../org.wso2.carbon.lb.common/4.1.3/src/test/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml
deleted file mode 100644
index 92dae9d..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml
+++ /dev/null
@@ -1,115 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (c) 2009-2010, 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.
--->
-<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.wso2.carbon</groupId>
- <artifactId>loadbalancer-components</artifactId>
- <version>4.1.0</version>
- <relativePath>../../pom.xml</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.lb.common</artifactId>
- <packaging>bundle</packaging>
- <version>4.1.3</version>
- <name>WSO2 Loadbalancer - Common</name>
- <url>http://wso2.org</url>
-
- <dependencies>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.core</artifactId>
- <version>4.1.0</version>
- </dependency>
- <dependency>
- <groupId>com.google.guava.wso2</groupId>
- <artifactId>guava</artifactId>
- <version>${google.guava.wso2.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.synapse</groupId>
- <artifactId>synapse-core</artifactId>
- <version>2.1.1-wso2v4</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </dependency>
- <!--dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.3.1</version>
- <scope>test</scope>
- </dependency-->
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.logging</artifactId>
- </dependency>
- <!--dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.6</version>
- </dependency-->
- <!-- This mysql dependency is required for tests-->
- </dependencies>
-
- <build>
- <plugins>
- <!--plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.12</version>
- <configuration>
- <suiteXmlFiles>
- <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
- </suiteXmlFiles>
- </configuration>
- </plugin-->
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-scr-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
-
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
- <Bundle-Name>${project.artifactId}</Bundle-Name>
- <Export-Package>
- org.wso2.carbon.lb.common.*,
- </Export-Package>
- <Private-Package>
- org.wso2.carbon.lb.common.conf.internal;
- </Private-Package>
- <Import-Package>
- !org.apache.commons.logging,
- org.apache.commons.logging; version=0.0.0,
- *;resolution:=optional
- </Import-Package>
- <DynamicImport-Package>*</DynamicImport-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java
deleted file mode 100644
index 54503ab..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright WSO2 Inc.
- *
- * 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.wso2.carbon.lb.common.cache;
-
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-/**
- * A simple, thread-safe LRU cache implementation. This cache allows concurrent reads.
- * Concurrent write attempts are synchronized using an exclusive lock.
- */
-public class LRUCache<K,V> extends LinkedHashMap<K,V> {
-
- private static final long serialVersionUID = 5901026458782787628L;
- private int maxEntries;
- private ReadWriteLock lock;
-
- public LRUCache(int maxEntries) {
- super(maxEntries + 1, 1, false);
- this.maxEntries = maxEntries;
- this.lock = new ReentrantReadWriteLock();
- }
-
- @Override
- public V get(Object key) {
- lock.readLock().lock();
- try {
- return super.get(key);
- } finally {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public V put(K key, V value) {
- lock.writeLock().lock();
- try {
- return super.put(key, value);
- } finally {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public V remove(Object key) {
- lock.writeLock().lock();
- try {
- return super.remove(key);
- } finally {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public void clear() {
- lock.writeLock().lock();
- try {
- super.clear();
- } finally {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
- boolean remove = size() > maxEntries;
- if (remove) {
- handleRemovableEntry(eldest);
- }
- return remove;
- }
-
- protected void handleRemovableEntry(Map.Entry<K,V> entry) {
-
- }
-
- public void exclusiveLock() {
- lock.writeLock().lock();
- }
-
- public void release() {
- lock.writeLock().unlock();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java
deleted file mode 100644
index b2cfcc2..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright WSO2 Inc.
- *
- * 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.wso2.carbon.lb.common.cache;
-
-import org.wso2.carbon.lb.common.util.DomainMapping;
-import java.util.Map;
-
-public class URLMappingCache {
- private Map<String,DomainMapping> validMappings;
-
- private static URLMappingCache instance = null;
- protected URLMappingCache(int maxValidKeys) {
- validMappings = new LRUCache<String, DomainMapping>(maxValidKeys);
- }
-
- public void addValidMapping(String hostName, DomainMapping mapping) {
- validMappings.put(hostName, mapping);
- }
-
- public DomainMapping getMapping(String hostName) {
- return validMappings.get(hostName);
- }
-
- public static URLMappingCache getInstance(int maxValidKeys) {
- if(instance == null) {
-
- instance = new URLMappingCache(maxValidKeys);
- }
- return instance;
- }
-}
[10/10] git commit: committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
committing org.apache.stratos.mediator.autoscale
Project: http://git-wip-us.apache.org/repos/asf/incubator-stratos/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-stratos/commit/290c6307
Tree: http://git-wip-us.apache.org/repos/asf/incubator-stratos/tree/290c6307
Diff: http://git-wip-us.apache.org/repos/asf/incubator-stratos/diff/290c6307
Branch: refs/heads/master
Commit: 290c63075f6c0eaea83d96b10b524ee919842b87
Parents: 3b2cf6c
Author: Isuru <is...@wso2.com>
Authored: Tue Jul 2 12:09:44 2013 +0530
Committer: Isuru <is...@wso2.com>
Committed: Tue Jul 2 12:09:44 2013 +0530
----------------------------------------------------------------------
.../4.1.0/pom.xml | 200 ---
.../autoscaler/service/IAutoscalerService.java | 111 --
.../exception/AutoscalerServiceException.java | 32 -
.../exception/DeserializationException.java | 32 -
.../MalformedConfigurationFileException.java | 32 -
.../exception/NoInstanceFoundException.java | 38 -
.../exception/SerializationException.java | 32 -
.../service/impl/AutoscalerServiceImpl.java | 1388 ------------------
.../internal/AutoscalerServiceDSComponent.java | 29 -
.../autoscaler/service/io/Deserializer.java | 67 -
.../autoscaler/service/io/Serializer.java | 60 -
.../service/jcloud/ComputeServiceBuilder.java | 64 -
.../service/util/AutoscalerConstant.java | 72 -
.../autoscaler/service/util/IaasContext.java | 389 -----
.../autoscaler/service/util/IaasProvider.java | 140 --
.../service/util/InstanceContext.java | 92 --
.../service/util/ServiceTemplate.java | 83 --
.../xml/ElasticScalerConfigFileReader.java | 556 -------
.../src/main/resources/META-INF/services.xml | 9 -
.../service/util/IaasContextComparatorTest.java | 97 --
.../service/util/IaasContextTest.java | 112 --
.../xml/ElasticScalerConfigFileReaderTest.java | 59 -
.../test/resources/elastic-scaler-config.xml | 66 -
.../4.1.3/pom.xml | 133 ++
.../callables/AppNodeSanityCheckCallable.java | 84 ++
.../callables/AutoscaleDeciderCallable.java | 241 +++
.../callables/InstanceCountCallable.java | 77 +
.../callables/PendingInstanceCountCallable.java | 64 +
.../callables/RunningInstanceCountCallable.java | 67 +
.../clients/CloudControllerClient.java | 65 +
.../clients/CloudControllerOsgiClient.java | 81 +
.../clients/CloudControllerStubClient.java | 92 ++
.../lbautoscale/context/AppDomainContext.java | 169 +++
.../context/LoadBalancerContext.java | 103 ++
.../AutoscalerTaskServiceComponent.java | 328 +++++
.../lbautoscale/internal/RegistryManager.java | 51 +
.../mediators/AutoscaleInMediator.java | 173 +++
.../mediators/AutoscaleOutMediator.java | 77 +
.../check/PendingInstancesStateChecker.java | 147 ++
.../check/TerminatingInstancesStateChecker.java | 88 ++
.../task/AutoscalerTaskInitializer.java | 47 +
.../task/AutoscalerTaskMgmtAdminService.java | 345 +++++
.../lbautoscale/task/AutoscalingJob.java | 65 +
.../task/ServiceRequestsInFlightAutoscaler.java | 524 +++++++
.../lbautoscale/task/TaskSchedulingManager.java | 185 +++
.../lbautoscale/util/AutoscaleConstants.java | 65 +
.../lbautoscale/util/AutoscaleUtil.java | 356 +++++
.../util/AutoscalerTaskDSHolder.java | 128 ++
...rg.apache.synapse.config.xml.MediatorFactory | 2 +
...apache.synapse.config.xml.MediatorSerializer | 2 +
.../src/main/resources/synapse-load-average.xml | 138 ++
.../resources/synapse-messages-in-flight.xml | 135 ++
.../synapse-service-messages-in-flight.xml | 108 ++
.../lbautoscale/AppDomainContextsTest.java | 104 ++
.../4.1.3/src/test/resources/loadbalancer.conf | 50 +
.../4.1.3/pom.xml | 133 --
.../callables/AppNodeSanityCheckCallable.java | 84 --
.../callables/AutoscaleDeciderCallable.java | 242 ---
.../callables/InstanceCountCallable.java | 77 -
.../callables/PendingInstanceCountCallable.java | 64 -
.../callables/RunningInstanceCountCallable.java | 67 -
.../clients/CloudControllerClient.java | 65 -
.../clients/CloudControllerOsgiClient.java | 81 -
.../clients/CloudControllerStubClient.java | 92 --
.../lbautoscale/context/AppDomainContext.java | 169 ---
.../context/LoadBalancerContext.java | 103 --
.../AutoscalerTaskServiceComponent.java | 328 -----
.../lbautoscale/internal/RegistryManager.java | 51 -
.../mediators/AutoscaleInMediator.java | 173 ---
.../mediators/AutoscaleOutMediator.java | 77 -
.../check/PendingInstancesStateChecker.java | 147 --
.../check/TerminatingInstancesStateChecker.java | 88 --
.../task/AutoscalerTaskInitializer.java | 47 -
.../task/AutoscalerTaskMgmtAdminService.java | 345 -----
.../lbautoscale/task/AutoscalingJob.java | 65 -
.../task/ServiceRequestsInFlightAutoscaler.java | 525 -------
.../lbautoscale/task/TaskSchedulingManager.java | 185 ---
.../lbautoscale/util/AutoscaleConstants.java | 65 -
.../lbautoscale/util/AutoscaleUtil.java | 356 -----
.../util/AutoscalerTaskDSHolder.java | 129 --
...rg.apache.synapse.config.xml.MediatorFactory | 2 -
...apache.synapse.config.xml.MediatorSerializer | 2 -
.../src/main/resources/synapse-load-average.xml | 138 --
.../resources/synapse-messages-in-flight.xml | 135 --
.../synapse-service-messages-in-flight.xml | 108 --
.../lbautoscale/AppDomainContextsTest.java | 105 --
.../ServiceRequestsInFlightAutoscalerTest.java | 29 -
.../4.1.3/src/test/resources/loadbalancer.conf | 50 -
.../4.1.3/pom.xml | 13 +-
.../4.1.3/src/main/Main.iml | 2 +-
.../org.wso2.carbon.lb.endpoint/4.1.3/pom.xml | 107 --
.../carbon/lb/endpoint/EndpointConstants.java | 28 -
.../carbon/lb/endpoint/EndpointDeployer.java | 68 -
...TenantAwareLoadBalanceEndpointException.java | 36 -
.../TenantLoadBalanceMembershipHandler.java | 190 ---
.../lb/endpoint/builder/TopologySyncher.java | 142 --
.../manager/ClusterDomainManagerImpl.java | 227 ---
.../TenantAwareLoadBalanceEndpoint.java | 513 -------
.../group/mgt/GroupMgtAgentBuilder.java | 62 -
.../LoadBalanceEndpointServiceComponent.java | 394 -----
.../lb/endpoint/internal/RegistryManager.java | 51 -
.../endpoint/subscriber/TopicHealthChecker.java | 67 -
.../endpoint/subscriber/TopologyListener.java | 28 -
.../endpoint/subscriber/TopologySubscriber.java | 77 -
.../carbon/lb/endpoint/util/ConfigHolder.java | 189 ---
.../lb/endpoint/util/TopologyConstants.java | 13 -
.../org.apache.stratos.lb.common/4.1.3/pom.xml | 15 +-
.../4.1.3/src/main/Main1.iml | 2 +-
.../4.1.3/src/test/Test.iml | 2 +-
.../org.wso2.carbon.lb.common/4.1.3/pom.xml | 115 --
.../wso2/carbon/lb/common/cache/LRUCache.java | 100 --
.../carbon/lb/common/cache/URLMappingCache.java | 44 -
.../common/conf/LoadBalancerConfiguration.java | 1205 ---------------
.../LoadBalancerConfigurationDSComponent.java | 46 -
.../carbon/lb/common/conf/structure/Node.java | 355 -----
.../lb/common/conf/structure/NodeBuilder.java | 139 --
.../carbon/lb/common/conf/util/Constants.java | 49 -
.../carbon/lb/common/conf/util/HostContext.java | 160 --
.../conf/util/LoadBalancerConfigUtil.java | 288 ----
.../common/conf/util/TenantDomainContext.java | 79 -
.../conf/util/TenantDomainRangeContext.java | 149 --
.../mgt/SubDomainAwareGroupManagementAgent.java | 57 -
.../RequestTokenReplicationCommand.java | 72 -
.../LoadBalancerConfigurationService.java | 79 -
.../LoadBalancerConfigurationServiceImpl.java | 61 -
.../carbon/lb/common/util/DomainMapping.java | 22 -
.../src/main/resources/META-INF/services.xml | 9 -
.../test/AgentPersistenceManagerTest.java | 267 ----
.../test/LoadBalancerConfigurationTest.java | 169 ---
.../carbon/lb/common/test/NodeBuilderTest.java | 123 --
.../4.1.3/src/test/resources/loadbalancer.conf | 64 -
.../4.1.3/src/test/resources/loadbalancer1.conf | 39 -
.../4.1.3/src/test/resources/loadbalancer2.conf | 30 -
.../4.1.3/src/test/resources/testng.xml | 15 -
134 files changed, 4309 insertions(+), 14034 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml
deleted file mode 100644
index 5c3a54e..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml
+++ /dev/null
@@ -1,200 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (c) 2009-2010, 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.
--->
-<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.wso2.carbon</groupId>
- <artifactId>loadbalancer-components</artifactId>
- <version>4.1.0</version>
- <relativePath>../../../pom.xml</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.autoscaler.service</artifactId>
- <packaging>aar</packaging>
- <name>WSO2 Carbon - Autoscaler Service</name>
- <url>http://wso2.org</url>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-shade-plugin</artifactId>
- <version>1.7.1</version>
- <executions>
- <execution>
- <phase>package</phase>
- <goals>
- <goal>shade</goal>
- </goals>
- <configuration>
- <artifactSet>
- <includes>
- <include>org.jclouds:*</include>
- <include>org.jclouds.*:*</include>
- </includes>
- </artifactSet>
- <filtering>true</filtering>
- <filters>
- <filter>
- <artifact>org.jclouds*:*</artifact>
- <includes>
- <include>META-INF/services/org.jclouds.apis.ApiMetadata</include>
- <include>META-INF/services/org.jclouds.providers.ProviderMetadata</include>
- </includes>
- </filter>
- </filters>
- <transformers>
- <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
- </transformer>
- </transformers>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.axis2</groupId>
- <artifactId>axis2-aar-maven-plugin</artifactId>
- <version>1.4</version>
- <extensions>true</extensions>
- </plugin>
- <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.wso2.carbon.autoscaler.service
- </Export-Package>
- <Private-Package>
- org.wso2.carbon.autoscaler.service.*, !org.wso2.carbon.autoscaler.service
- </Private-Package>
- <Import-Package>
- !org.apache.commons.logging,
- org.apache.commons.logging; version=0.0.0,
- org.wso2.carbon.utils.*,
- org.jclouds.compute*;version="${jclouds.version}";resolution:=optional,
- org.jclouds*;version="${jclouds.version}",
- *; resolution:=optional
- </Import-Package>
- <DynamicImport-Package>*</DynamicImport-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <dependencies>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.utils</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.lb.common</artifactId>
- <version>${wso2carbon.version}</version>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.securevault</artifactId>
- <version>${wso2carbon.version}</version>
- </dependency>
- <!--dependency>
- <groupId>org.apache.synapse</groupId>
- <artifactId>synapse-core</artifactId>
- <version>${synapse.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.synapse</groupId>
- <artifactId>synapse-commons</artifactId>
- <version>${synapse.version}</version>
- </dependency-->
-
- <!-- Jclouds dependencies -->
- <dependency>
- <groupId>org.jclouds</groupId>
- <artifactId>jclouds-allcompute</artifactId>
- <version>${jclouds.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jclouds</groupId>
- <artifactId>jclouds-compute</artifactId>
- <version>${jclouds.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jclouds.driver</groupId>
- <artifactId>jclouds-bouncycastle</artifactId>
- <version>${jclouds.version}</version>
- <exclusions>
- <exclusion>
- <groupId>org.bouncycastle</groupId>
- <artifactId>bcprov-jdk16</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.jclouds.driver</groupId>
- <artifactId>jclouds-sshj</artifactId>
- <version>${jclouds.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jclouds.driver</groupId>
- <artifactId>jclouds-log4j</artifactId>
- <version>${jclouds.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jclouds.driver</groupId>
- <artifactId>jclouds-enterprise</artifactId>
- <version>${jclouds.version}</version>
- </dependency>
- <!--dependency>
- <groupId>org.jclouds.api</groupId>
- <artifactId>ec2</artifactId>
- <version>${jclouds.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jclouds.provider</groupId>
- <artifactId>aws-ec2</artifactId>
- <version>${jclouds.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jclouds.api</groupId>
- <artifactId>openstack-nova</artifactId>
- <version>${jclouds.version}</version>
- </dependency-->
-
- </dependencies>
-
-
-</project>
-
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java
deleted file mode 100644
index 05269d6..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service;
-
-import org.wso2.carbon.lb.common.conf.util.Constants;
-
-/**
- * This Interface provides a way for a component, to communicate with an underline
- * Infrastructure which are supported by <i>JClouds</i>.
- *
- */
-public interface IAutoscalerService {
-
- /**
- * Initialize the service.
- * @param isSpi if this service is to be used by SPI, this parameter should be set to
- * true. When this is true, you should specify an image id, each time you
- * are starting an instance i.e. you should use {@link #startSpiInstance(String, String)}
- * method, instead of using {@link #startInstance(String)}.
- * @return
- */
- public boolean initAutoscaler(boolean isSpi);
-
-
- /**
- * Calling this method will result in an instance startup, which is belong
- * to the provided service domain. This method is non-blocking, means we do not
- * wait till the instance is started up. Also note that the instance that is starting up
- * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
- * by a hyphen (<i>-</i>).
- * @param domainName service clustering domain of the instance to be started up.
- * @param sudDomainName service clustering sub domain of the instance to be started up.
- * If this is null, the default value will be used. Default value is
- * {@link Constants}.DEFAULT_SUB_DOMAIN.
- * @return whether the starting up is successful or not.
- */
- public boolean startInstance(String domainName, String sudDomainName);
-
- /**
- * Calling this method will result in an instance startup, which is belong
- * to the provided service domain. This method will return the public IP address of
- * the instance that is started. Thus, this method is blocking, since we need to
- * return the IP Address and for that we have to wait till the instance started up.
- * @param domainName should be in following format.
- * <code>${service-domain}\t\${tenant-id}</code>.
- * @param imageId starting instance will be an instance of this image. Image id should
- * be a valid one.
- * @param sudDomainName service clustering sub domain of the instance to be started up.
- * If this is null, the default value will be used. Default value is
- * {@link Constants}.DEFAULT_SUB_DOMAIN.
- * @return public IP address of the instance in String format. If instance failed to
- * start, this will return an empty String.
- */
- public String startSpiInstance(String domainName, String subDomainName, String imageId);
-
-
- /**
- * Calling this method will result in termination of an instance which is belong
- * to the provided service domain.
- * @param domainName service domain of the instance to be terminated.
- * @param sudDomainName service clustering sub domain of the instance to be started up.
- * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
- * @return whether an instance terminated successfully or not.
- */
- public boolean terminateInstance(String domainName, String subDomainName);
-
- /**
- * Calling this method will result in termination of the lastly spawned instance which is
- * belong to the provided service domain.
- * @param domainName service domain of the instance to be terminated.
- * @param sudDomainName service clustering sub domain of the instance to be started up.
- * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
- * @return whether the termination is successful or not.
- */
- public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
-
- /**
- * Calling this method will result in termination of an instance which has the
- * provided public IP address.
- * @param publicIp public IP address of the instance to be terminated.
- * @return whether the instance terminated successfully or not.
- */
- public boolean terminateSpiInstance(String publicIp);
-
- /**
- * Calling this method will result in returning the pending instances
- * count of a particular domain.
- * @param domainName service domain
- * @param sudDomainName service clustering sub domain of the instance to be started up.
- * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
- * @return number of pending instances for this domain. If no instances of this
- * domain is present, this will return zero.
- */
- public int getPendingInstanceCount(String domainName, String subDomainName);
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java
deleted file mode 100644
index 4b6818a..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.exception;
-
-public class AutoscalerServiceException extends RuntimeException {
-
- private static final long serialVersionUID = -6326227079367867222L;
-
- public AutoscalerServiceException(String msg) {
- super(msg);
- }
-
- public AutoscalerServiceException(String msg, Exception ex) {
- super(msg, ex);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java
deleted file mode 100644
index 377a641..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.exception;
-
-public class DeserializationException extends RuntimeException {
-
- private static final long serialVersionUID = -2426068347954381831L;
-
- public DeserializationException(String msg) {
- super(msg);
- }
-
- public DeserializationException(String msg, Exception ex) {
- super(msg, ex);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java
deleted file mode 100644
index 4065417..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.exception;
-
-public class MalformedConfigurationFileException extends RuntimeException {
-
- private static final long serialVersionUID = -1662095377704279326L;
-
- public MalformedConfigurationFileException(String msg) {
- super(msg);
- }
-
- public MalformedConfigurationFileException(String msg, Exception ex) {
- super(msg, ex);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java
deleted file mode 100644
index 0888a3c..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.wso2.carbon.autoscaler.service.exception;
-
-/**
- * This will throw when no instance is found
- */
-public class NoInstanceFoundException extends Exception {
-
- /**
- * For serializing requirement
- */
- private static final long serialVersionUID = -435060299292679892L;
-
-
- public NoInstanceFoundException(String msg) {
- super(msg);
- }
-
- public NoInstanceFoundException(String msg, Exception ex) {
- super(msg, ex);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java
deleted file mode 100644
index 06ff6d2..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-* 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.wso2.carbon.autoscaler.service.exception;
-
-public class SerializationException extends RuntimeException {
-
- private static final long serialVersionUID = -3701458642228072331L;
-
- public SerializationException(String msg) {
- super(msg);
- }
-
- public SerializationException(String msg, Exception ex) {
- super(msg, ex);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java
deleted file mode 100644
index f77eb52..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java
+++ /dev/null
@@ -1,1388 +0,0 @@
-/*
- * 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.wso2.carbon.autoscaler.service.impl;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.RunNodesException;
-import org.jclouds.compute.domain.ComputeMetadata;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.NodeMetadata.Status;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.TemplateBuilder;
-import org.jclouds.compute.domain.internal.NodeMetadataImpl;
-import org.jclouds.compute.options.TemplateOptions;
-import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
-import org.wso2.carbon.autoscaler.service.IAutoscalerService;
-import org.wso2.carbon.autoscaler.service.exception.AutoscalerServiceException;
-import org.wso2.carbon.autoscaler.service.exception.DeserializationException;
-import org.wso2.carbon.autoscaler.service.exception.SerializationException;
-import org.wso2.carbon.autoscaler.service.io.Deserializer;
-import org.wso2.carbon.autoscaler.service.io.Serializer;
-import org.wso2.carbon.autoscaler.service.jcloud.ComputeServiceBuilder;
-import org.wso2.carbon.autoscaler.service.util.AutoscalerConstant;
-import org.wso2.carbon.autoscaler.service.util.IaasContext;
-import org.wso2.carbon.autoscaler.service.util.IaasProvider;
-import org.wso2.carbon.autoscaler.service.util.InstanceContext;
-import org.wso2.carbon.autoscaler.service.util.ServiceTemplate;
-import org.wso2.carbon.autoscaler.service.xml.ElasticScalerConfigFileReader;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * Autoscaler Service is responsible for starting up new server instances, terminating already
- * started instances, providing pending instance count.
- *
- */
-public class AutoscalerServiceImpl implements IAutoscalerService {
-
-
- private static final Log log = LogFactory.getLog(AutoscalerServiceImpl.class);
-
- /**
- * pointer to Carbon Home directory.
- */
- private static final String CARBON_HOME = CarbonUtils.getCarbonHome();
-
- /**
- * pointer to Carbon Temp directory.
- */
- private static final String CARBON_TEMP = CarbonUtils.getTmpDir();
-
- /**
- * Tenant id Delimiter
- */
- private static final String TENANT_ID_DELIMITER = "/t/";
-
- /**
- * This directory will be used to store serialized objects.
- */
- private String serializationDir;
-
- /**
- * List of all <code>IaaSProviders</code> specified in the config file.
- */
- private List<IaasProvider> iaasProviders;
-
- /**
- * List of all <code>ServiceTemplate</code> objects.
- */
- private List<ServiceTemplate> serviceTemps;
-
- /**
- * We keep an enum which contains all supported IaaSes.
- */
- public enum Iaases {
- ec2, openstack
- };
-
- /**
- * List which keeps <code>IaasContext</code> objects.
- */
- private List<IaasContext> iaasContextList = new ArrayList<IaasContext>();
-
- /**
- * We keep track of the IaaS where the last instance of a domain and a sub domain combination is spawned.
- * This is required when there are multiple <code>IaasProvider</code>s defined.
- * Key - domain
- * Value - a map which has a Key - sub domain and Value - name of the {@link IaasProvider}.
- */
- private Map<String, Map<String, String>> lastlyUsedIaasMap = new HashMap<String, Map<String, String>>();
-
- /**
- * To track whether the {@link #initAutoscaler(boolean)} method has been called.
- */
- boolean isInitialized = false;
-
- @Override
- public boolean initAutoscaler(boolean isSpi) {
-
- if (!isInitialized) {
-
- log.debug("InitAutoscaler has started ... IsSPI : " + isSpi);
-
- // load configuration file
- ElasticScalerConfigFileReader configReader = new ElasticScalerConfigFileReader();
-
- // read serialization directory from config file if specified, else will use the
- // default.
- if ("".equals(serializationDir = configReader.getSerializationDir())) {
- serializationDir = CARBON_TEMP;
-
- log.debug("Directory to be used to serialize objects: " + serializationDir);
- }
-
- // let's deserialize and load the serialized objects.
- deserialize();
-
- // from config file, we grab the details unique to IaaS providers.
- iaasProviders = configReader.getIaasProvidersList();
-
- // from config file, we grab the details related to each service domain.
- serviceTemps = configReader.getTemplates();
-
- // we iterate through each IaaSProvider which is loaded from the config file.
- for (IaasProvider iaas : iaasProviders) {
-
- // build the JClouds specific ComputeService object
- ComputeService computeService = ComputeServiceBuilder.buildComputeService(iaas);
- IaasContext entity;
-
- // let's see whether there's a serialized entity
- entity = findIaasContext(iaas.getType());
-
- if (entity != null) {
-
- log.debug("Serializable object is loaded for IaaS " + iaas.getType());
-
- // ComputeService isn't serializable, hence we need to set it in the
- // deserialized
- // object.
- entity.setComputeService(computeService);
- }
-
- // build JClouds Template objects according to different IaaSes
- if (iaas.getType().equalsIgnoreCase(Iaases.ec2.toString())) {
-
- // initiate the IaasContext object, if it is null.
- entity =
- (entity == null) ? (entity =
- new IaasContext(Iaases.ec2,
- computeService)) : entity;
-
- // we should build the templates only if this is not SPI stuff
- if (!isSpi) {
- // Build the Template
- buildEC2Templates(entity, iaas.getTemplate(), isSpi);
-
- } else {
- // add to data structure
- iaasContextList.add(entity);
- }
-
- } else if (iaas.getType().equalsIgnoreCase(Iaases.openstack.toString())) {
-
- // initiate the IaasContext object, if it is null.
- entity =
- (entity == null) ? (entity =
- new IaasContext(Iaases.openstack,
- computeService)) : entity;
-
- // we should build the templates only if this is not SPI stuff
- if (!isSpi) {
- // Build the Template
- buildLXCTemplates(entity, iaas.getTemplate(), isSpi, null);
-
- } else {
- // add to data structure
- iaasContextList.add(entity);
- }
-
- } else {
- // unsupported IaaS detected. We only complain, since there could be other
- // IaaSes.
- String msg =
- "Unsupported IaasProvider is specified in the config file: " +
- iaas.getType() + ". Supported IaasProviders are " +
- print(Iaases.values());
- log.warn(msg);
- continue;
- }
-
- // populate scale up order
- fillInScaleUpOrder();
-
- // populate scale down order
- fillInScaleDownOrder();
-
- // serialize the objects
- serialize();
- }
-
- // we couldn't locate any valid IaaS providers from config file, thus shouldn't proceed.
- if (iaasContextList.size() == 0) {
- String msg = "No valid IaaS provider specified in the config file!";
- log.error(msg);
- throw new AutoscalerServiceException(msg);
- }
-
- // initialization completed.
- isInitialized = true;
-
- log.info("Autoscaler service initialized successfully!!");
-
- return true;
- }
-
- log.debug("Autoscaler Service is already initialized!");
- return false;
- }
-
-
- @Override
- public boolean startInstance(String domainName, String subDomainName) {
-
- // initialize the service, if it's not already initialized.
- initAutoscaler(false);
-
- ComputeService computeService;
- Template template;
-
- subDomainName = checkSubDomain(subDomainName);
-
- log.info("Starting new instance of domain : " + domainName+" and sub domain : "+subDomainName);
-
- // sort the IaasContext entities according to scale up order
- Collections.sort(iaasContextList,
- IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_UP_SORT)));
-
- // traverse through IaasContext object instances in scale up order
- for (IaasContext iaasCtxt : iaasContextList) {
-
- // get the ComputeService
- computeService = iaasCtxt.getComputeService();
-
- // from the list grab the Template corresponds to this domain
- template = iaasCtxt.getTemplate(domainName, subDomainName);
-
- if(template == null){
- String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
- ". Reason : Template is null. You have not specify a matching service " +
- "element in the configuration file of Autoscaler.\n Hence, will try to " +
- "start in another IaaS if available.";
- log.error(msg);
- continue;
- }
-
- // generate the group id from domain name and sub domain name.
- // Should have lower-case ASCII letters, numbers, or dashes.
- String str = domainName.concat("-"+subDomainName);
- String group = str.replaceAll("[^a-z0-9-]", "");
-
- try {
- // create and start a node
- Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(group,
- 1,
- template);
-
- NodeMetadata node = nodes.iterator().next();
-
-// // add the details of the started node to maps
-// iaasCtxt.addNodeIdToDomainMap(node.getId(), domainName);
-
- String ip="";
-
- // set public Ip, if it's available
- if (node.getPublicAddresses().size() > 0) {
- ip = node.getPublicAddresses().iterator().next();
-// iaasCtxt.addPublicIpToDomainMap(publicIp, domainName);
-// iaasCtxt.addPublicIpToNodeIdMap(publicIp, node.getId());
- } else if(node.getPrivateAddresses().size() > 0) { // set private IPs if no public IP s are returned
- ip = node.getPrivateAddresses().iterator().next();
-// iaasCtxt.addPublicIpToDomainMap(privateIp, domainName);
-// iaasCtxt.addPublicIpToNodeIdMap(privateIp, node.getId());
- } else{
- log.debug("Public IP of the node : "+node.getId()+" cannot be found.");
- }
-
-
- if (iaasCtxt.getInstanceContext(domainName, subDomainName) == null) {
- String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
- ". Reason : InstanceContext is null. Hence, will try to start in another IaaS if available.";
- log.error(msg);
- continue;
- }
-
- if(node.getId() == null){
- String msg = "Node id of the starting instance is null.\n"+ node.toString();
- log.fatal(msg);
- throw new AutoscalerServiceException(msg);
- }
-
- // add run time data to InstanceContext
- iaasCtxt.addNodeDetails(domainName, subDomainName, node.getId(), ip);
-
- // since we modified the IaasContext instance, let's replace it.
- replaceIaasContext(iaasCtxt);
-
- // update the lastlyUsedIaasMap
- addToLastlyUsedIaasMap(domainName, subDomainName, iaasCtxt.getName().toString());
-// lastlyUsedIaasMap.put(domainName, iaasCtxt.getName().toString());
-
- if (log.isDebugEnabled()) {
- log.debug("Node details: \n" + node.toString() +
- "\n***************\n");
- }
-
- } catch (RunNodesException e) {
- log.warn("Failed to start an instance in " + iaasCtxt.getName().toString() +
- ". Hence, will try to start in another IaaS if available.", e);
- continue;
- }
-
- log.info("Instance is successfully starting up in IaaS " + iaasCtxt.getName()
- .toString() + " ...");
-
- // serialize the objects
- serialize();
-
- return true;
- }
-
- log.info("Failed to start instance, in any available IaaS.");
-
- return false;
-
- }
-
- private String checkSubDomain(String subDomainName) {
- // if sub domain is null, we assume it as default one.
- if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
- subDomainName = Constants.DEFAULT_SUB_DOMAIN;
- log.debug("Sub domain is null, hence using the default value : " + subDomainName);
- }
-
- return subDomainName;
- }
-
-
- private void addToLastlyUsedIaasMap(String domainName, String subDomainName, String iaasName) {
-
- Map<String, String> map;
-
- if(lastlyUsedIaasMap.get(domainName) == null){
- map = new HashMap<String, String>();
-
- } else{
- map = lastlyUsedIaasMap.get(domainName);
- }
-
- map.put(subDomainName, iaasName);
- lastlyUsedIaasMap.put(domainName, map);
-
- }
-
-
- @Override
- public String startSpiInstance(String domainName, String subDomainName, String imageId) {
-
- log.debug("Starting an SPI instance ... | domain: " + domainName + " | sub domain: " +
- subDomainName + " | ImageId: " + imageId);
-
- // initialize the service, if it's not already initialized.
- initAutoscaler(true);
-
- String tenantId = null;
- String spiDomainName = null;
-
- if(domainName != null) {
- // domainName will have the pattern <domainName>/t/<tenantId>
- String[] arr = domainName.split(TENANT_ID_DELIMITER);
- if(arr.length != 2) {
- String msg = "Domain name does not match with the expected pattern. Expected " +
- "pattern is <domainName>/t/<tenantId>";
- log.error(msg);
- throw new AutoscalerServiceException(msg);
- }
- spiDomainName = arr[0];
- tenantId = arr[1];
- }
-
- IaasContext entry;
-
- // FIXME: Build the Templates, for now we're doing a hack here. I don't know whether
- // there's a proper fix.
- // handle openstack case
- if (imageId.startsWith("nova") && ((entry = findIaasContext(Iaases.openstack)) != null)) {
-
- buildLXCTemplates(entry, imageId, true, tenantId);
-
- } else if (((entry = findIaasContext(Iaases.ec2)) != null)) {
-
- buildEC2Templates(entry, imageId, true);
-
- } else {
- String msg = "Invalid image id: " + imageId;
- log.error(msg);
- throw new AutoscalerServiceException(msg);
- }
-
- // let's start the instance
- if (startInstance(spiDomainName, subDomainName)) {
-
- // if it's successful, get the public IP of the started instance.
- // FIXME remove --> String publicIP =
- // findIaasContext(iaas).getLastMatchingPublicIp(domainName);
- String publicIP = entry.getLastMatchingPublicIp(spiDomainName, subDomainName);
-
- // if public IP is null, return an empty string, else return public IP.
- return (publicIP == null) ? "" : publicIP;
-
- }
-
- return "";
-
- }
-
- @Override
- public boolean terminateInstance(String domainName, String subDomainName) {
-
- // initialize the service, if it's not already initialized.
- initAutoscaler(false);
-
- subDomainName = checkSubDomain(subDomainName);
-
- log.info("Starting to terminate an instance of domain : " + domainName + " and sub domain : "+subDomainName);
-
- // sort the IaasContext entities according to scale down order.
- Collections.sort(iaasContextList,
- IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
-
- // traverse in scale down order
- for (IaasContext iaasTemp : iaasContextList) {
-
- String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
- ". Hence, will try to terminate an instance in another IaaS if possible.";
-
- String nodeId = null;
-
- // grab the node ids related to the given domain and traverse
- for (String id : iaasTemp.getNodeIds(domainName, subDomainName)) {
- if (id != null) {
- nodeId = id;
- break;
- }
- }
-
- // if no matching node id can be found.
- if (nodeId == null) {
-
- log.warn(msg + " : Reason- No matching instance found for domain: " +
- domainName + " and sub domain: "+subDomainName+
- ".");
- continue;
- }
-
- // terminate it!
- terminate(iaasTemp, nodeId);
-
- return true;
-
- }
-
- log.info("Termination of an instance which is belong to domain '" + domainName +
- "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching " +
- "running instance found in any available IaaS.");
-
- return false;
-
- }
-
- @Override
- public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) {
-
- // initialize the service, if it's not already initialized.
- initAutoscaler(false);
-
- subDomainName = checkSubDomain(subDomainName);
-
- // see whether there is a matching IaaS, where we spawn an instance belongs to given domain.
- if (lastlyUsedIaasMap.containsKey(domainName)) {
-
- // grab the name of the IaaS
- String iaas = lastlyUsedIaasMap.get(domainName).get(subDomainName);
-
- // find the corresponding IaasContext
- IaasContext iaasTemp = findIaasContext(iaas);
-
- String msg = "Failed to terminate the lastly spawned instance of '" + domainName +
- "' service domain.";
-
- if (iaasTemp == null) {
- log.error(msg + " : Reason- Iaas' data cannot be located!");
- return false;
- }
-
- // find the instance spawned at last of this IaasContext
- String nodeId = iaasTemp.getLastMatchingNode(domainName, subDomainName);
-
- if (nodeId == null) {
- log.error(msg + " : Reason- No matching instance found for domain: " +
- domainName + " and sub domain: "+subDomainName+
- ".");
- return false;
- }
-
- // terminate it!
- terminate(iaasTemp, nodeId);
-
- return true;
-
- }
-
- log.info("Termination of an instance which is belong to domain '" + domainName +
- "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching instance found.");
-
- return false;
- }
-
- @Override
- public boolean terminateSpiInstance(String publicIp) {
-
- // initialize the service, if it's not already initialized.
- initAutoscaler(true);
-
- // sort the IaasContext entities according to scale down order.
- Collections.sort(iaasContextList,
- IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
-
- // traverse in scale down order
- for (IaasContext iaasTemp : iaasContextList) {
-
- String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
- "" +
- ". Hence, will try to terminate an instance in another IaaS if possible.";
-
- // grab the node maps with the given public IP address
- String nodeId = iaasTemp.getNodeWithPublicIp(publicIp);
-
- if (nodeId == null) {
- log.warn(msg + " : Reason- No matching instance found for public ip '" +
- publicIp +
- "'.");
- continue;
- }
-
- // terminate it!
- terminate(iaasTemp, nodeId);
-
- return true;
- }
-
- log.info("Termination of an instance which has the public IP '" + publicIp + "', failed!");
-
- return false;
- }
-
- @Override
- public int getPendingInstanceCount(String domainName, String subDomain) {
-
- // initialize the service, if it's not already initialized.
- initAutoscaler(false);
-
- subDomain = checkSubDomain(subDomain);
-
- int pendingInstanceCount = 0;
-
- // traverse through IaasContexts
- for (IaasContext entry : iaasContextList) {
-
- ComputeService computeService = entry.getComputeService();
-
- // get list of node Ids which are belong to the requested domain
- List<String> nodeIds = entry.getNodeIds(domainName, subDomain);
-
- if(nodeIds.isEmpty()){
- log.debug("Zero nodes spawned in the IaaS "+entry.getName()+
- " of domain: "+domainName+" and sub domain: "+subDomain);
- continue;
- }
-
- // get all the nodes spawned by this IaasContext
- Set<? extends ComputeMetadata> set = computeService.listNodes();
-
- Iterator<? extends ComputeMetadata> iterator = set.iterator();
-
- // traverse through all nodes of this ComputeService object
- while (iterator.hasNext()) {
- NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator.next();
-
- // if this node belongs to the requested domain
- if (nodeIds.contains(nodeMetadata.getId())) {
-
- // get the status of the node
- Status nodeStatus = nodeMetadata.getStatus();
-
- // count nodes that are in pending state
- if (nodeStatus.toString().equalsIgnoreCase("PENDING")) {
- pendingInstanceCount++;
- }
- }
-
- }
- }
-
- log.info("Pending instance count of domain '" + domainName + "' and sub domain '"+
- subDomain+"' is " + pendingInstanceCount);
-
- return pendingInstanceCount;
-
- }
-
- /**
- * Returns matching IaasContext for the given {@link Iaases} entry.
- */
- private IaasContext findIaasContext(Enum<Iaases> iaas) {
-
- for (IaasContext entry : iaasContextList) {
- if (entry.getName().equals(iaas)) {
- return entry;
- }
- }
-
- return null;
- }
-
- /**
- * Returns matching IaasContext for the given iaas type.
- */
- private IaasContext findIaasContext(String iaasType) {
-
- for (IaasContext entry : iaasContextList) {
- if (entry.getName().toString().equals(iaasType)) {
- return entry;
- }
- }
-
- return null;
- }
-
- private void fillInScaleDownOrder() {
-
- for (IaasProvider iaas : iaasProviders) {
- if (findIaasContext(iaas.getType()) != null) {
- findIaasContext(iaas.getType()).setScaleDownOrder(iaas.getScaleDownOrder());
- }
- }
-
- }
-
- private void fillInScaleUpOrder() {
-
- for (IaasProvider iaas : iaasProviders) {
- if (findIaasContext(iaas.getType()) != null) {
- findIaasContext(iaas.getType()).setScaleUpOrder(iaas.getScaleUpOrder());
- }
- }
-
- }
-
- private byte[] getUserData(String payloadFileName, String tenantId) {
-
- byte[] bytes = null;
- File outputFile = null;
- String tempfilename = UUID.randomUUID().toString();
- 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");
- }
- if(tenantId != null) {
- // Tenant Id is available. This is an spi scenario. Edit the payload content
- editPayload(tenantId,file,tempfilename);
- outputFile = new File(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfilename+".zip");
- } else {
- outputFile = file;
- }
- bytes = getBytesFromFile(outputFile);
-
- } catch (IOException e) {
- handleException("Cannot read data from payload file " + payloadFileName, e);
- }
-
- // Remove temporary payload file
- if (tenantId != null) {
- outputFile.delete();
- }
-
- return bytes;
- }
-
-
- private void editPayload(String tenantName, File file, String tempfileName) {
-
- unzipFile(file, tempfileName);
- editContent(tenantName, file, tempfileName);
- zipPayloadFile(tempfileName);
- }
-
-
- /**
- * unzips the payload file
- *
- * @param file
- * @param tempfileName
- */
- private void unzipFile(File file, String tempfileName) {
-
- int buffer = 2048;
- BufferedOutputStream dest = null;
- ZipInputStream zis = null;
-
- try {
- FileInputStream fis = new FileInputStream(file);
- zis = new ZipInputStream(new BufferedInputStream(fis));
- ZipEntry entry;
-
- while ((entry = zis.getNextEntry()) != null) {
-
- log.debug("Extracting: " + entry);
-
- int count;
- byte data[] = new byte[buffer];
- String outputFilename = tempfileName + File.separator + entry.getName();
- createDirIfNeeded(tempfileName, entry);
-
- // write the files to the disk
- if (!entry.isDirectory()) {
- FileOutputStream fos = new FileOutputStream(outputFilename);
- dest = new BufferedOutputStream(fos, buffer);
- while ((count = zis.read(data, 0, buffer)) != -1) {
- dest.write(data, 0, count);
- }
- dest.flush();
- dest.close();
- }
- }
-
- } catch (Exception e) {
- log.error("Exception is occurred in unzipping payload file. Reason:" + e.getMessage());
- throw new AutoscalerServiceException(e.getMessage(), e);
- } finally {
- closeStream(zis);
- closeStream(dest);
- }
- }
-
-
- private void closeStream(Closeable stream) {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- log.error(" Exception is occurred when closing stream. Reason :" + e.getMessage());
- }
- }
- }
-
- /**
- *
- * Modify contents (tenantName) of the debian_cron_script.sh file
- *
- * @param tenantName
- * @param file
- */
- private void editContent(String tenantName, File file, String tempfileName) {
-
- File f = new File(CARBON_HOME + File.separator + tempfileName
- + File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator
- + AutoscalerConstant.PARAMS_FILE_NAME);
-
- FileInputStream fs = null;
- InputStreamReader in = null;
- BufferedReader br = null;
-
- StringBuffer sb = new StringBuffer();
-
- String textinLine;
-
- try {
- fs = new FileInputStream(f);
- in = new InputStreamReader(fs);
- br = new BufferedReader(in);
-
- while (true) {
-
- textinLine=br.readLine();
- if(textinLine==null)
- break;
- sb.append(editLine(textinLine, tenantName));
- }
- } catch (Exception e) {
- log.error("Exception is occurred in editing payload content. Reason: "+e.getMessage());
- throw new AutoscalerServiceException(e.getMessage(), e);
- } finally {
- closeStream(fs);
- closeStream(in);
- closeStream(br);
- }
-
- writeChangesBackToFile(f, sb);
- }
-
-
- private String editLine(String textinLine, String tenantName) {
-
- // Format of the line will be <IP>=<IPvalue>,<Path>=<PathValue>..
-
- StringBuffer outputBuffer = new StringBuffer();
- Map<String, String> paramMap = new HashMap<String, String>();
- String[] params = textinLine.split(AutoscalerConstant.ENTRY_SEPARATOR);
-
- for (int i = 0; i < params.length; i++) {
-
- // split the params one by one
- String param = params[i];
- String[] values = param.split(AutoscalerConstant.VALUE_SEPARATOR);
-
- if(values.length != 2) {
- throw new AutoscalerServiceException("Incorrect format in parameters file");
- }
-
- String key = values[0];
- String value = values[1];
-
- String updatedValue = value;
-
- if (AutoscalerConstant.TENANT_KEY.equals(key)) {
- updatedValue = tenantName;
- } else if (AutoscalerConstant.APP_PATH_KEY.equals(key)) {
- updatedValue = getAppPathForTenant(tenantName,value);
- }
- paramMap.put(key, updatedValue);
- }
-
- // Loop through the map and put values into a string
- reOrganizeContent(outputBuffer, paramMap);
-
- // cleanup output buffer
- if (outputBuffer.substring(0, 1).equals(AutoscalerConstant.ENTRY_SEPARATOR)) {
- outputBuffer.delete(0, 1);
- }
-
- return outputBuffer.toString();
- }
-
-
- private void reOrganizeContent(StringBuffer outputBuffer, Map<String, String> paramMap) {
-
- for (Map.Entry<String, String> entry : paramMap.entrySet()) {
- outputBuffer.append(AutoscalerConstant.ENTRY_SEPARATOR).append(entry.getKey()).append(AutoscalerConstant.VALUE_SEPARATOR)
- .append(entry.getValue());
- }
- }
-
-
- private String getAppPathForTenant(String tenantName, String appPath) {
- // Assumes app path is /opt/wso2-app/repository/
- StringBuffer updatedAppPath = new StringBuffer();
- if(tenantName.equals(AutoscalerConstant.SUPER_TENANT_ID)){
- updatedAppPath.append(appPath).append("deployment").append(File.separator).append("server")
- .append(File.separator).append("phpapps");
- }else{
- updatedAppPath.append(appPath).append(tenantName).append(File.separator).append("phpapps");
- }
- return updatedAppPath.toString();
- }
-
-
- private void writeChangesBackToFile(File f, StringBuffer sb) {
- FileWriter fstream = null;
- BufferedWriter outobj = null;
-
- try {
- fstream = new FileWriter(f);
- outobj = new BufferedWriter(fstream);
- outobj.write(sb.toString());
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- closeStream(outobj);
- }
- }
-
- /**
- *
- * Compress the modified files back into payload.zip
- * @param tempfileName
- *
- */
- private void zipPayloadFile(String tempfileName) {
-
- int buffer = 2048;
- BufferedInputStream origin = null;
- ZipOutputStream out = null;
-
- try {
-
- FileOutputStream dest = new
- FileOutputStream(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfileName+".zip");
- out = new ZipOutputStream(new BufferedOutputStream(dest));
- byte data[] = new byte[buffer];
-
- File f = new File(CARBON_HOME + File.separator + tempfileName + File.separator + AutoscalerConstant.PAYLOAD_DIR);
- String files[] = f.list();
-
- for (int i=0; i<files.length; i++) {
- FileInputStream fi = new FileInputStream(CARBON_HOME + File.separator + tempfileName
- + File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
- origin = new BufferedInputStream(fi, buffer);
- ZipEntry entry = new ZipEntry(AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
- out.putNextEntry(entry);
-
- int count;
- while((count = origin.read(data, 0, buffer)) != -1) {
- out.write(data, 0, count);
- }
- origin.close();
- }
-
- // delete temp files
- deleteDir(f);
- File fl = new File(CARBON_HOME + File.separator + tempfileName);
- fl.delete();
-
- } catch(Exception e) {
- log.error("Exception is occurred in zipping payload file after modification. Reason:" + e.getMessage());
- throw new AutoscalerServiceException(e.getMessage(),e);
- } finally {
- closeStream(origin);
- closeStream(out);
- }
- }
-
- private static boolean deleteDir(File dir) {
- if (dir.isDirectory()) {
- String[] children = dir.list();
- for (int i=0; i<children.length; i++) {
- boolean success = deleteDir(new File(dir, children[i]));
- if (!success) {
- return false;
- }
- }
- }
-
- // The directory is now empty so delete it
- return dir.delete();
- }
-
- private void createDirIfNeeded(String destDirectory, ZipEntry entry) {
-
- String name = entry.getName();
-
- if(name.contains("/"))
- {
- log.debug("directory will need to be created");
-
- int index = name.lastIndexOf("/");
- String dirSequence = name.substring(0, index);
-
- File newDirs = new File(destDirectory + File.separator + dirSequence);
-
- //create the directory
- newDirs.mkdirs();
- }
-
- }
-
-
- /**
- * 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.
- */
- private 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;
- }
-
- /**
- * handles the exception
- *
- * @param msg
- * exception message
- */
- private void handleException(String msg) {
- log.error(msg);
- throw new SynapseException(msg);
- }
-
- /**
- * handles the exception
- *
- * @param msg
- * exception message
- * @param e
- * exception
- */
- private static void handleException(String msg, Exception e) {
- log.error(msg, e);
- throw new SynapseException(msg, e);
- }
-
-
- /**
- * This will replace an existing entry in iaasEntities list, if there's such.
- * If not this will add the replacement value to the list.
- *
- * @param replacement
- * IaasContext entry to be added.
- */
- private void replaceIaasContext(IaasContext replacement) {
- for (IaasContext entry : iaasContextList) {
- if (entry.equals(replacement)) {
- int idx = iaasContextList.indexOf(entry);
- iaasContextList.remove(idx);
- iaasContextList.add(idx, replacement);
- return;
- }
- }
- iaasContextList.add(replacement);
-
- }
-
- /**
- * Builds the LXC Template object.
- */
- private void buildLXCTemplates(IaasContext entity, String imageId, boolean blockUntilRunning, String tenantId) {
-
- if (entity.getComputeService() == null) {
- throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
- }
-
-// // if domain to template map is null
-// if (entity.getDomainToTemplateMap() == null) {
-// // we initialize it
-// entity.setDomainToTemplateMap(new HashMap<String, Template>());
-// }
-
- TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
- templateBuilder.imageId(imageId);
-
- // to avoid creation of template objects in each and every time, we create all
- // at once!
- for (org.wso2.carbon.autoscaler.service.util.ServiceTemplate temp : serviceTemps) {
-
- String instanceType;
-
- // set instance type
- if (((instanceType = temp.getProperty("instanceType." + Iaases.openstack.toString())) != null) ) {
-
- templateBuilder.hardwareId(instanceType);
- }
-
- Template template = templateBuilder.build();
-
- template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
-
- template.getOptions()
- .as(NovaTemplateOptions.class)
- .securityGroupNames(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
-
- if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
- template.getOptions()
- .as(NovaTemplateOptions.class)
- .userData(getUserData(CARBON_HOME + File.separator +
- temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), tenantId));
- }
-
- template.getOptions()
- .as(NovaTemplateOptions.class)
- .keyPairName(temp.getProperty("keyPair"));
-
- // add to the data structure
- if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
- entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
- temp.getSubDomainName(), template));
- }
- else{
- entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
- }
-
- }
-
- // since we modified the Context, we need to replace
- replaceIaasContext(entity);
- }
-
- /**
- * Builds EC2 Template object
- *
- */
- private void buildEC2Templates(IaasContext entity, String imageId, boolean blockUntilRunning) {
-
- if (entity.getComputeService() == null) {
- throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
- }
-
-// // if domain to template map is null
-// if (entity.getDomainToTemplateMap() == null) {
-// // we initialize it
-// entity.setDomainToTemplateMap(new HashMap<String, Template>());
-// }
-
- TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
-
- // set image id specified
- templateBuilder.imageId(imageId);
-
- // to avoid creation of template objects in each and every time, we create all
- // at once! FIXME we could use caching and lazy loading
- for (org.wso2.carbon.autoscaler.service.util.ServiceTemplate temp : serviceTemps) {
-
- if (temp.getProperty("instanceType." + Iaases.ec2.toString()) != null) {
- // set instance type eg: m1.large
- templateBuilder.hardwareId(temp.getProperty("instanceType." + Iaases.ec2.toString()));
- }
-
- // build the Template
- Template template = templateBuilder.build();
-
- // make it non blocking
- template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
-
- // set EC2 specific options
- template.getOptions()
- .as(AWSEC2TemplateOptions.class)
- .placementGroup(temp.getProperty("availabilityZone"));
-
- template.getOptions()
- .as(AWSEC2TemplateOptions.class)
- .securityGroups(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
-
- if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
- template.getOptions()
- .as(AWSEC2TemplateOptions.class)
- .userData(getUserData(CARBON_HOME + File.separator +
- temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), null));
- }
-
- template.getOptions()
- .as(AWSEC2TemplateOptions.class)
- .keyPair(temp.getProperty("keyPair"));
-
- // add to the data structure
- if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
- entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
- temp.getSubDomainName(), template));
- }
- else{
- entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
- }
-
- }
-
- // since we modified the Context, we need to replace
- replaceIaasContext(entity);
-
- }
-
- private String print(Iaases[] values) {
- String str = "";
- for (Iaases iaases : values) {
- str = iaases.name() + ", ";
- }
- str = str.trim();
- return str.endsWith(AutoscalerConstant.ENTRY_SEPARATOR) ? str.substring(0, str.length() - 1) : str;
- }
-
- @SuppressWarnings("unchecked")
- private void deserialize() {
-
- String path;
-
- try {
- path = serializationDir + File.separator +
- AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE;
-
- Object obj = Deserializer.deserialize(path);
- if (obj != null) {
- iaasContextList = (List<IaasContext>) obj;
- log.debug("Deserialization was successful from file: " + path);
- }
-
- path = serializationDir + File.separator +
- AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE;
-
- obj = Deserializer.deserialize(path);
-
- if (obj != null) {
- lastlyUsedIaasMap = (Map<String, Map<String, String>>) obj;
- log.debug("Deserialization was successful from file: " + path);
- }
-
- } catch (Exception e) {
- String msg = "Deserialization of objects failed!";
- log.fatal(msg, e);
- throw new DeserializationException(msg, e);
- }
-
- }
-
- /**
- * Does all the serialization stuff!
- */
- private void serialize() {
-
- try {
- Serializer.serialize(iaasContextList,
- serializationDir + File.separator +
- AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE);
-
- Serializer.serialize(lastlyUsedIaasMap,
- serializationDir + File.separator +
- AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE);
-
- } catch (IOException e) {
- String msg = "Serialization of objects failed!";
- log.fatal(msg, e);
- throw new SerializationException(msg, e);
- }
- }
-
- /**
- * A helper method to terminate an instance.
- */
- private void terminate(IaasContext iaasTemp, String nodeId) {
-
- // this is just to be safe
- if (iaasTemp.getComputeService() == null) {
- String msg = "Unexpeced error occured! IaasContext's ComputeService is null!";
- log.error(msg);
- throw new AutoscalerServiceException(msg);
- }
-
- // destroy the node
- iaasTemp.getComputeService().destroyNode(nodeId);
-
- // remove the node id from the Context
- iaasTemp.removeNodeId(nodeId);
-
- // replace this IaasContext instance, as it reflects the new changes.
- replaceIaasContext(iaasTemp);
-
- // serialize the objects
- serialize();
-
- log.info("Node with Id: '" + nodeId + "' is terminated!");
- }
-
- /**
- * Comparator to compare IaasContexts on different attributes.
- */
- public enum IaasContextComparator implements Comparator<IaasContext> {
- SCALE_UP_SORT {
- public int compare(IaasContext o1, IaasContext o2) {
- return Integer.valueOf(o1.getScaleUpOrder()).compareTo(o2.getScaleUpOrder());
- }
- },
- SCALE_DOWN_SORT {
- public int compare(IaasContext o1, IaasContext o2) {
- return Integer.valueOf(o1.getScaleDownOrder()).compareTo(o2.getScaleDownOrder());
- }
- };
-
- public static Comparator<IaasContext> ascending(final Comparator<IaasContext> other) {
- return new Comparator<IaasContext>() {
- public int compare(IaasContext o1, IaasContext o2) {
- return other.compare(o1, o2);
- }
- };
- }
-
- public static Comparator<IaasContext>
- getComparator(final IaasContextComparator... multipleOptions) {
- return new Comparator<IaasContext>() {
- public int compare(IaasContext o1, IaasContext o2) {
- for (IaasContextComparator option : multipleOptions) {
- int result = option.compare(o1, o2);
- if (result != 0) {
- return result;
- }
- }
- return 0;
- }
- };
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java
deleted file mode 100644
index 5053e30..0000000
--- a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.wso2.carbon.autoscaler.service.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.autoscaler.service.IAutoscalerService;
-import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl;
-
-/**
- * Registering Autoscaler Service.
- * @scr.component name="org.wso2.carbon.autoscaler.service" immediate="true"
- */
-public class AutoscalerServiceDSComponent {
-
- private static final Log log = LogFactory.getLog(AutoscalerServiceDSComponent.class);
-
- protected void activate(ComponentContext context) {
- try {
- BundleContext bundleContext = context.getBundleContext();
- bundleContext.registerService(IAutoscalerService.class.getName(),
- new AutoscalerServiceImpl(), null);
-
- log.debug("******* Autoscaler Service bundle is activated ******* ");
- } catch (Exception e) {
- log.error("******* Autoscaler Service bundle is failed to activate ****", e);
- }
- }
-}
\ No newline at end of file
[07/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
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>
[02/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java
deleted file mode 100644
index f5aae03..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java
+++ /dev/null
@@ -1,1205 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.conf;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.commons.util.PropertyHelper;
-import org.wso2.carbon.lb.common.conf.structure.Node;
-import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-import org.wso2.carbon.lb.common.conf.util.LoadBalancerConfigUtil;
-import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
-import java.io.*;
-import java.net.URL;
-import java.util.*;
-
-/**
- * Data object which hold configuration data of the load analyzer task
- */
-@SuppressWarnings("unused")
-public class LoadBalancerConfiguration implements Serializable {
-
- protected static final long serialVersionUID = -5553545217542808233L;
-
- private static final Log log = LogFactory.getLog(LoadBalancerConfiguration.class);
-
- /**
- * This map is there to speed up the lookup time.
- * Key: domain
- * <p/>
- * Value: A map whose key is sub domain and value is ServiceConfiguration
- */
- private Map<String, Map<String, ServiceConfiguration>> serviceConfigurations =
- new HashMap<String, Map<String, ServiceConfiguration>>();
-
- /**
- * Key - host name
- * Value - {@link HostContext}
- */
- private transient Map<String, HostContext> hostCtxt = new HashMap<String, HostContext>();
-
- /**
- * This map is there to speed up the lookup time.
- * Key: service name/cartridge type (Stratos2). NOTE: that this is not the service cluster domain.
- * Value: list of {@link ServiceConfiguration} - corresponding objects under a service name.
- */
- private Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations =
- new HashMap<String, List<ServiceConfiguration>>();
-
- /**
- * This list will be used to identify host name duplications among different services.
- * Within a service there can be duplications, but among different services you can't have duplications.
- * Key - service name
- * Value - hosts under the respective service.
- */
- private Map<String, Set<String>> hostNamesTracker = new HashMap<String, Set<String>>();
-
- protected ServiceConfiguration defaultServiceConfig;
- protected LBConfiguration lbConfig;
-
- /**
- * LBConfig file as a String
- */
- protected String lbConfigString;
-
- /**
- * Root node object for loadbalancer.conf
- */
- protected Node rootNode;
-
- private LoadBalancerConfiguration(){
- init(System.getProperty("loadbalancer.conf"));
- }
-
- private static LoadBalancerConfiguration instance ;
-
- public static LoadBalancerConfiguration getInstance(){
- if(instance == null){
- instance = new LoadBalancerConfiguration();
- }
- return instance;
- }
-
- /**
- * Sample loadbalancer.conf:
- * <p/>
- * loadbalancer {
- * # minimum number of load balancer instances
- * instances 1;
- * # whether autoscaling enable or not
- * enable_autoscaler true;
- * # End point reference of the Autoscaler Service
- * autoscaler_service_epr https://10.100.3.81:9443/services/AutoscalerService/;
- * # interval between two task executions in milliseconds
- * autoscaler_task_interval 1000;
- * # after an instance booted up, task will wait till this much of time and let the server started up
- * server_startup_delay 15000;
- * }
- * <p/>
- * services {
- * defaults {
- * min_app_instances 1;
- * max_app_instances 5;
- * queue_length_per_node 400;
- * rounds_to_average 10;
- * instances_per_scale_up 1;
- * message_expiry_time 60000;
- * }
- * <p/>
- * appserver {
- * hosts appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;
- * domains {
- * wso2.as1.domain {
- * tenant_range 1-100;
- * }
- * wso2.as2.domain {
- * tenant_range 101-200;
- * }
- * wso2.as3.domain {
- * tenant_range *;
- * }
- * }
- * }
- * }
- *
- * @param configURL URL of the load balancer config
- */
- public void init(String configURL) {
-
- if(configURL == null){
- String msg = "Cannot locate the location of the loadbalancer.conf file." +
- " You need to set the 'loadbalancer.conf' system property.";
- log.error(msg);
- throw new RuntimeException(msg);
- }
-
- if (configURL.startsWith("$system:")) {
- configURL = System.getProperty(configURL.substring("$system:".length()));
- }
-
- try {
-
- // get loadbalancer.conf file as a String
- if (configURL.startsWith(File.separator)) {
- lbConfigString = createLBConfigString(configURL);
- } else {
- lbConfigString = createLBConfigString(new URL(configURL).openStream());
- }
-
- } catch (Exception e) {
- String msg = "Cannot read configuration file from " + configURL;
- log.error(msg, e);
- throw new RuntimeException(msg, e);
- }
-
- // build a Node object for whole loadbalancer.conf
- rootNode = new Node();
- rootNode.setName("root");
- rootNode = NodeBuilder.buildNode(rootNode, lbConfigString);
-
- // load 'loadbalancer' node
- Node lbConfigNode = rootNode.findChildNodeByName(Constants.LOAD_BALANCER_ELEMENT);
-
- if(lbConfigNode != null){
- createConfiguration(lbConfig = new LBConfiguration(), lbConfigNode);
- }
-
- // load services node
- Node servicesConfigNode = rootNode.findChildNodeByName(Constants.SERVICES_ELEMENT);
-
- if (servicesConfigNode == null) {
- String msg = "Mandatory " + Constants.SERVICES_ELEMENT +
- " element can not be found in the configuration file.";
- log.error(msg);
- throw new RuntimeException(msg);
- }
-
- // Set services configuration
- createServicesConfig(servicesConfigNode);
-
- }
-
-
- /**
- * Process the content of the following 'services' element
- * <p/>
- * services {
- * defaults {
- * min_app_instances 1;
- * max_app_instances 5;
- * queue_length_per_node 400;
- * rounds_to_average 10;
- * instances_per_scale_up 1;
- * message_expiry_time 60000;
- * }
- * <p/>
- * appserver {
- * hosts appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;
- * domains {
- * wso2.as1.domain {
- * tenant_range 1-100;
- * }
- * wso2.as2.domain {
- * tenant_range 101-200;
- * }
- * wso2.as3.domain {
- * tenant_range *;
- * }
- * }
- * }
- * }
- *
- * @param servicesConfigNode services element's Node
- */
- public List<ServiceConfiguration> createServicesConfig(Node servicesConfigNode) {
-
- // current list of service configs
- List<ServiceConfiguration> currentServiceConfigs = new ArrayList<ServiceConfiguration>();
-
- // Building default configuration
- Node defaultNode = servicesConfigNode.findChildNodeByName(Constants.DEFAULTS_ELEMENT);
-
- if (defaultNode != null) {
-
- createConfiguration(defaultServiceConfig = new ServiceConfiguration(), defaultNode);
- }
-
- // Building custom services configuration
- for (Node serviceNode : servicesConfigNode.getChildNodes()) {
- //skip default node
- if (serviceNode != defaultNode) {
-
- String serviceName = serviceNode.getName();
-
- // reading domains
-
- Node domainsNode;
-
- if (serviceNode.getChildNodes().isEmpty() ||
- !(domainsNode = serviceNode.getChildNodes().get(0)).getName().equals(
- Constants.DOMAIN_ELEMENT)) {
-
- String msg = "The mandatory domains element, child of the " + serviceName +
- " element is not specified in the configuration file. \n"+
- serviceNode.toString();
- log.error(msg);
- throw new RuntimeException(msg);
- }
-
- if (domainsNode.getChildNodes().isEmpty()) {
- // this is probably a mistake, so we don't proceed
- String msg = "No domain is specified under " + Constants.DOMAIN_ELEMENT +
- " of " + serviceName + " element.";
- log.error(msg);
- throw new RuntimeException(msg);
- }
-
- ServiceConfiguration serviceConfig;
-
- // iterates through all the service domain specified in this service element.
- for (Node domain : domainsNode.getChildNodes()) {
-
- // create a new service configuration
- serviceConfig = new ServiceConfiguration();
-
- // set service name
- serviceConfig.setServiceName(serviceName);
-
- // set domain name
- serviceConfig.setDomain(domain.getName());
-
- // let's set properties common to all domains specified in this service element.
- createConfiguration(serviceConfig, serviceNode);
-
- // load properties specified under this service domain element.
- createConfiguration(serviceConfig, domain);
-
- // check host name duplication
- if(isDuplicatedHost(serviceNode.getName(), serviceConfig)){
- // this is probably a mistake, so we don't proceed
- String msg = "Duplicated host names detected for different service domains.\n" +
- "Element: \n"+serviceNode.toString();
- log.error(msg);
- throw new RuntimeException(msg);
- }
-
- currentServiceConfigs.add(serviceConfig);
-
- }
- }
- }
-
- for (ServiceConfiguration serviceConfiguration : currentServiceConfigs) {
-
- // add the built ServiceConfiguration, to the map
- addServiceConfiguration(serviceConfiguration);
-
- }
-
- return currentServiceConfigs;
-
- }
-
-
- public boolean addServiceConfiguration(ServiceConfiguration serviceConfig) {
-
- Map<String, ServiceConfiguration> map;
- String domain = serviceConfig.getDomain();
-
- if(domain == null){
- String msg = "Domain of a Service Configuration cannot be null. Hence this " +
- "Configuration will be neglected.";
- log.error(msg);
- return false;
- }
-
- String subDomain = serviceConfig.getSubDomain();
-
- if (serviceConfigurations.containsKey(domain)) {
- map = serviceConfigurations.get(domain);
- } else {
- map = new HashMap<String, ServiceConfiguration>();
- }
- // put this serviceConfig
- map.put(subDomain, serviceConfig);
-
- // update the parent map
- serviceConfigurations.put(domain, map);
-
- // add to serviceNameToServiceConfiguration map
- List<ServiceConfiguration> configs;
- if(serviceNameToServiceConfigurations.get(serviceConfig.getServiceName()) == null){
- configs = new ArrayList<ServiceConfiguration>();
-
- }else{
- configs = serviceNameToServiceConfigurations.get(serviceConfig.getServiceName());
- }
-
- if(!configs.contains(serviceConfig)){
- configs.add(serviceConfig);
- }
- serviceNameToServiceConfigurations.put(serviceConfig.getServiceName(), configs);
-
- return true;
- }
-
- public ServiceConfiguration removeServiceConfiguration(String domain, String subDomain) {
-
- Map<String, ServiceConfiguration> map;
- ServiceConfiguration serviceConfig = null;
-
- if(domain == null){
- String msg = "Domain of a Service Configuration cannot be null. Hence this " +
- "Configuration will be neglected.";
- log.error(msg);
- return null;
- }
-
- if (serviceConfigurations.containsKey(domain)) {
- map = serviceConfigurations.get(domain);
-
- if(map != null){
- serviceConfig = map.remove(subDomain);
- }
- }
-
- if(serviceConfig == null){
- String msg = "No matching service configuration found for domain: "+domain+
- ", sub domain: "+subDomain;
- log.error(msg);
- return null;
- }
-
- String serviceName = serviceConfig.getServiceName();
-
- if (serviceName != null && serviceNameToServiceConfigurations.containsKey(serviceName)) {
- if(serviceConfig != null){
- List<ServiceConfiguration> list = serviceNameToServiceConfigurations.get(serviceName);
-
- list.remove(serviceConfig);
-
- serviceNameToServiceConfigurations.put(serviceName, list);
- }
- }
-
- Set<String> allHosts;
-
- if (hostNamesTracker.containsKey(serviceName)) {
- allHosts = hostNamesTracker.get(serviceName);
-
- for (String hostName : serviceConfig.getHosts()) {
-
- if (hostName != null) {
-
- allHosts.remove(hostName);
-
- hostCtxt.remove(hostName);
- }
- }
- }
-
- return serviceConfig;
- }
-
- public void resetData(){
- serviceConfigurations =
- new HashMap<String, Map<String, ServiceConfiguration>>();
-
- serviceNameToServiceConfigurations =
- new HashMap<String, List<ServiceConfiguration>>();
-
- }
-
-
- /**
- * Duplications can only be seen, when you traverse down the configuration file.
- *
- */
- public boolean isDuplicatedHost(String name, ServiceConfiguration serviceConfig) {
-
- /**
- * This will be populated with host names of all other services other than the
- * service subjected to the test.
- */
- List<String> hostsOtherThanMine = new ArrayList<String>(hostNamesTracker.values().size());
-
- for (Map.Entry<String, Set<String>> entry : hostNamesTracker.entrySet()) {
- if (!entry.getKey().equals(name)) {
- hostsOtherThanMine.addAll(entry.getValue());
- }
- }
-
- for (String host : serviceConfig.getHosts()) {
- if (!hostsOtherThanMine.isEmpty() && hostsOtherThanMine.contains(host)) {
- return true;
- }
- }
-
- addToHostNameTrackerMap(name, serviceConfig.getHosts());
-
- return false;
- }
-
-
- public void addToHostNameTrackerMap(String name, List<String> hosts) {
-
- Set<String> allHosts;
-
- if (hostNamesTracker.containsKey(name)) {
- allHosts = hostNamesTracker.get(name);
- allHosts.addAll(hosts);
- } else {
- allHosts = new HashSet<String>(hosts);
- }
- hostNamesTracker.put(name, allHosts);
- }
-
- public void addToHostContextMap(String hostName, HostContext ctxt) {
-
- if (hostName != null && ctxt != null) {
- hostCtxt.put(hostName, ctxt);
- }
- }
-
- /**
- * Return a map of {@link HostContext}.
- * @return
- */
- public Map<String, HostContext> getHostContextMap() {
-
- List<Integer> tenantIds;
- Map<String, String> URLSuffixes;
-
- // FIXME if possible! I couldn't think of any other way to do this, at this moment.
- // Note: some of these for-loops are pretty small, thus no considerable performance overhead.
- // iterate through each service
- for (Iterator<Set<String>> it = hostNamesTracker.values().iterator(); it.hasNext();) {
-
- // iterate through host names of this service
- for (String hostName : ((Set<String>) it.next())) {
-
- // building HostContext
- HostContext ctxt = new HostContext(hostName);
-
- // iterate through domains of this host
- for (Map.Entry<String, Map<String, ServiceConfiguration>> parentMap : serviceConfigurations.entrySet()) {
-
- // iterate through sub domain of this domain
- for (Map.Entry<String, ServiceConfiguration> childMap : parentMap.getValue()
- .entrySet()) {
- // iterate through hosts of this
- for (String host : childMap.getValue().getHosts()) {
- // if a matching Service configuration is found.
- if (host.equals(hostName)) {
-
- String tenantRange = childMap.getValue().getTenantRange();
- String domain = parentMap.getKey();
- String subDomain = childMap.getKey();
-
- ctxt.addTenantDomainContexts(LoadBalancerConfigUtil.getTenantDomainContexts(tenantRange, domain, subDomain));
-
- break;
- }
- }
-
- //iterate through URL suffixes
- for(Map.Entry<String, String> entry : childMap.getValue().getUrl_suffix().entrySet()) {
- if(entry.getKey().equals(hostName)) {
-
- ctxt.setUrlSuffix(entry.getValue());
-
- break;
- }
-
- }
- }
- }
-
- // add this hostCtxt
- hostCtxt.put(hostName, ctxt);
- }
-
- }
-
- return hostCtxt;
-
- }
-
- protected void createConfiguration(Configuration config, Node node) {
-
- if (node == null) {
- String msg = "The configuration element for " +
- config.getClass().getName() + " is null.";
- throw new RuntimeException(msg);
- }
-
- try {
- // load properties
- for (Map.Entry<String, String> entry : node.getProperties().entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue();
-
- PropertyHelper.setInstanceProperty(key, value, config);
- }
-
- } catch (Exception e) {
- String msg = "Error setting values to " + config.getClass().getName();
- log.error(msg, e);
- throw new RuntimeException(msg, e);
- }
- }
-
- public LBConfiguration getLoadBalancerConfig() {
- return lbConfig;
- }
-
- public String[] getServiceDomains() {
-
- Object[] objs = serviceConfigurations.keySet().toArray();
-
- return Arrays.copyOf(objs, objs.length, String[].class);
-
- }
-
- public String[] getServiceSubDomains(String domain) {
-
- if (serviceConfigurations.get(domain) != null) {
- Object[] objs = serviceConfigurations.get(domain).keySet().toArray();
- return Arrays.copyOf(objs, objs.length, String[].class);
- }
-
- return new String[0];
- }
-
- public ServiceConfiguration getServiceConfig(String domain, String subDomain) {
- if (serviceConfigurations.get(domain) != null) {
- return serviceConfigurations.get(domain).get(subDomain);
- }
- return null;
- }
-
-
- public List<ServiceConfiguration> getServiceConfigs(String serviceName) {
- return serviceNameToServiceConfigurations.get(serviceName);
- }
-
- /**
- * Convert given configuration file to a single String
- *
- * @param configFileName - file name to convert
- * @return String with complete lb configuration
- * @throws FileNotFoundException
- */
- public String createLBConfigString(String configFileName) throws FileNotFoundException {
- StringBuilder lbConfigString = new StringBuilder("");
-
- File configFile = new File(configFileName);
- Scanner scanner;
-
- scanner = new Scanner(configFile);
-
- while (scanner.hasNextLine()) {
- lbConfigString.append(scanner.nextLine().trim() + "\n");
- }
-
- return lbConfigString.toString().trim();
- }
-
- public String createLBConfigString(InputStream configFileName) throws IOException {
-
- // read the stream with BufferedReader
- BufferedReader br = new BufferedReader(new InputStreamReader(configFileName));
-
- StringBuilder sb = new StringBuilder();
-
- String line;
- while ((line = br.readLine()) != null) {
- sb.append(line.trim() + "\n");
- }
-
- return sb.toString().trim();
- }
-
- public abstract class Configuration implements Serializable {
-
- private static final long serialVersionUID = -5433889427746551250L;
- protected String imageId = System.getenv("ami_id");
- protected String payload;
- protected boolean payloadSet;
-
- protected String availability_zone = "us-east-1c";
- protected boolean availabilityZoneSet;
-
- protected String[] security_groups = new String[]{"default"};
- protected boolean securityGroupsSet;
-
- protected String instance_type = "m1.large";
- protected boolean instanceTypeSet;
-
- protected String additional_info;
-
- public String getImageId() {
- return imageId;
- }
-
- public String getAdditionalInfo() {
- return additional_info;
- }
-
- public String getAvailability_zone() {
- if (this instanceof LBConfiguration) {
- return availability_zone;
- }
- if (availabilityZoneSet) {
- return availability_zone;
- } else if (defaultServiceConfig != null && defaultServiceConfig.availabilityZoneSet) {
- return defaultServiceConfig.availability_zone;
- }
- return availability_zone;
- }
-
- public String[] getSecurityGroups() {
- if (this instanceof LBConfiguration) {
- return security_groups;
- }
- if (securityGroupsSet) {
- return security_groups;
- } else if (defaultServiceConfig != null && defaultServiceConfig.securityGroupsSet) {
- return defaultServiceConfig.security_groups;
- }
- return security_groups;
- }
-
- public String getInstanceType() {
- if (this instanceof LBConfiguration) {
- return instance_type;
- }
- if (instanceTypeSet) {
- return instance_type;
- } else if (defaultServiceConfig != null && defaultServiceConfig.instanceTypeSet) {
- return defaultServiceConfig.instance_type;
- }
- return instance_type;
- }
-
-
- public String getUserData() {
- if (payload == null) {
- payload = LoadBalancerConfigUtil.getUserData("resources/cluster_node.zip");
- }
- if (this instanceof LBConfiguration) {
- return payload;
- }
- if (payloadSet) {
- return payload;
- } else if (defaultServiceConfig != null && defaultServiceConfig.payloadSet) {
- return defaultServiceConfig.payload;
- }
- return payload;
- }
-
- public void setPayload(String payload) {
- this.payload = LoadBalancerConfigUtil.getUserData(LoadBalancerConfigUtil.replaceVariables(payload));
- this.payloadSet = true;
- }
-
- public void setAvailability_zone(String availabilityZone) {
- this.availability_zone = LoadBalancerConfigUtil.replaceVariables(availabilityZone);
- this.availabilityZoneSet = true;
- }
-
- public void setSecurity_groups(String securityGroups) {
- this.security_groups = LoadBalancerConfigUtil.replaceVariables(securityGroups).split(",");
- this.securityGroupsSet = true;
- }
-
- public void setInstance_type(String instanceType) {
- this.instance_type = LoadBalancerConfigUtil.replaceVariables(instanceType);
- this.instanceTypeSet = true;
- }
-
- }
-
- public class LBConfiguration extends Configuration implements Serializable {
-
- private static final long serialVersionUID = 1357143883932816418L;
- private String elasticIP;//= LoadBalancerConfigUtil.replaceVariables("${ELASTIC_IP}");
- private int instances = 1;
- private boolean isAutoscaleEnabled;
- private int autoscalerTaskInterval = 30000;
- private String autoscalerServiceEpr;
- private int serverStartupDelay = 60000;
- private int sizeOfCache = 0 ;
- private boolean failOver;
- private int sessionTimeOut = -1;
- private String groupManagementAgentClass;
- private String autoscalerTaskClass;
- private String mbServerUrl;
- private boolean useEmbeddedAutoscaler = true;
- private String algorithm = "org.apache.synapse.endpoints.algorithms.RoundRobin";
-
- public String getElasticIP() {
- return elasticIP;
- }
-
- public int getInstances() {
- return instances;
- }
-
- public boolean isAutoscaleEnabled() {
- return isAutoscaleEnabled;
- }
-
- public boolean useEmbeddedAutoscaler() {
- return useEmbeddedAutoscaler;
- }
-
- public boolean getFailOver() {
- return failOver;
- }
-
- public String getAutoscalerServiceEpr() {
- return autoscalerServiceEpr;
- }
-
- public int getAutoscalerTaskInterval() {
- return autoscalerTaskInterval;
- }
-
- public int getServerStartupDelay() {
- return serverStartupDelay;
- }
-
- public int getSessionTimeOut() {
- return sessionTimeOut;
- }
-
- public void setElasticIP(String elasticIP) {
- this.elasticIP = LoadBalancerConfigUtil.replaceVariables(elasticIP);
- }
-
- public void setInstances(int instances) {
- this.instances = instances;
- }
-
- public void setEnable_autoscaler(String isEnabled) {
- this.isAutoscaleEnabled = Boolean.parseBoolean(isEnabled);
- }
-
- public void setUse_embedded_autoscaler(String use) {
- this.useEmbeddedAutoscaler = Boolean.parseBoolean(use);
- }
-
- public void setFail_over(String isEnabled) {
- this.failOver = Boolean.parseBoolean(isEnabled);
- }
-
- public void setAutoscaler_service_epr(String epr) {
- this.autoscalerServiceEpr = epr;
- }
-
- public void setMb_server_url(String url) {
- this.mbServerUrl = url;
- }
-
- public String getMbServerUrl() {
- return mbServerUrl;
- }
-
- public void setAutoscaler_task_interval(String interval) {
- this.autoscalerTaskInterval = Integer.parseInt(interval);
- }
-
- public void setServer_startup_delay(String delay) {
- this.serverStartupDelay = Integer.parseInt(delay);
- }
-
- public void setSession_timeout(String timeout) {
- this.sessionTimeOut = Integer.parseInt(timeout);
- }
-
- public String getAlgorithm() {
- return algorithm;
- }
-
- public void setAlgorithm(String algorithm) {
- if (algorithm != null) {
- this.algorithm = algorithm;
- }
- }
-
- public int getSizeOfCache() {
- return sizeOfCache;
- }
-
- public void setSize_of_cache(int sizeOfCache) {
- this.sizeOfCache = sizeOfCache;
- }
-
- public String getGroupManagementAgentClass() {
- return groupManagementAgentClass;
- }
-
- public String getAutoscalerTaskClass() {
- return autoscalerTaskClass;
- }
-
- public void setGroup_mgt_agent(String groupManagementAgentClass){
- this.groupManagementAgentClass = groupManagementAgentClass;
- }
-
- public void setAutoscaler_task(String autoscalerTaskClass){
- this.autoscalerTaskClass = autoscalerTaskClass;
- }
- }
-
- public class ServiceConfiguration extends Configuration implements Serializable {
-
- private String serviceName;
-
- public String getServiceName() {
- return serviceName;
- }
-
- public void setServiceName(String name) {
- this.serviceName = name;
- }
-
- public String getPublicIp() {
- return publicIp;
- }
-
- public void setPublic_ip(String publicIp) {
- this.publicIp = publicIp;
- }
-
- private String publicIp;
-
- private static final long serialVersionUID = 8707314702788040116L;
- private int minAppInstances = 1;
- private boolean minAppInstancesSet;
-
- private int maxAppInstances = 3;
- private boolean maxAppInstancesSet;
-
- private int maxRequestsPerSecond = 100;
- private boolean maxRequestsPerSecondSet;
-
- private double alarmingUpperRate = 0.7;
- private boolean alarmingUpperRateSet;
-
- private double alarmingLowerRate = 0.2;
- private boolean alarmingLowerRateSet;
-
- private double scaleDownFactor = 0.25;
- private boolean scaleDownFactorSet;
-
- private int roundsToAverage = 10;
- private boolean roundsToAverageSet;
-
- private int instancesPerScaleUp = 1;
- private boolean instancesPerScaleUpSet;
-
- private int messageExpiryTime = 60000; // milliseconds
- private boolean messageExpiryTimeSet;
-
- private List<String> hosts = new ArrayList<String>();
- private Map<String, String> urlSuffixes = new HashMap<String, String>();
- private boolean hostsSet;
-
- private String domain;
-
- private String tenantRange;
- private boolean tenantRangeSet;
-
- private String subDomain = Constants.DEFAULT_SUB_DOMAIN;
- private boolean subDomainSet;
-
- public String getTenantRange() {
- if (tenantRangeSet) {
- return tenantRange;
- } else if (defaultServiceConfig != null && defaultServiceConfig.tenantRangeSet) {
- return defaultServiceConfig.tenantRange;
- }
- return tenantRange;
- }
-
- public String getDomain() {
- return domain;
- }
-
- public List<String> getHosts() {
- if (hostsSet) {
- return hosts;
- } else if (defaultServiceConfig != null && defaultServiceConfig.hostsSet) {
- return defaultServiceConfig.hosts;
- }
- return hosts;
- }
-
- public int getMinAppInstances() {
- if (minAppInstancesSet) {
- return minAppInstances;
- } else if (defaultServiceConfig != null && defaultServiceConfig.minAppInstancesSet) {
- return defaultServiceConfig.minAppInstances;
- }
- return minAppInstances;
- }
-
- public int getMaxAppInstances() {
- if (maxAppInstancesSet) {
- return maxAppInstances;
- } else if (defaultServiceConfig != null && defaultServiceConfig.maxAppInstancesSet) {
- return defaultServiceConfig.maxAppInstances;
- }
- return maxAppInstances;
- }
-
- public int getMaxRequestsPerSecond() {
- if (maxRequestsPerSecondSet) {
- return maxRequestsPerSecond;
- } else if (defaultServiceConfig != null && defaultServiceConfig.maxRequestsPerSecondSet) {
- return defaultServiceConfig.maxRequestsPerSecond;
- }
- return maxRequestsPerSecond;
- }
-
- public int getRoundsToAverage() {
- if (roundsToAverageSet) {
- return roundsToAverage;
- } else if (defaultServiceConfig != null && defaultServiceConfig.roundsToAverageSet) {
- return defaultServiceConfig.roundsToAverage;
- }
- return roundsToAverage;
- }
-
- public int getInstancesPerScaleUp() {
- if (instancesPerScaleUpSet) {
- return instancesPerScaleUp;
- } else if (defaultServiceConfig != null && defaultServiceConfig.instancesPerScaleUpSet) {
- return defaultServiceConfig.instancesPerScaleUp;
- }
- return instancesPerScaleUp;
- }
-
- public int getMessageExpiryTime() {
- if (messageExpiryTimeSet) {
- return messageExpiryTime;
- } else if (defaultServiceConfig != null && defaultServiceConfig.messageExpiryTimeSet) {
- return defaultServiceConfig.messageExpiryTime;
- }
- return messageExpiryTime;
- }
-
- public String getSubDomain() {
- if (subDomainSet) {
- return subDomain;
- } else if (defaultServiceConfig != null && defaultServiceConfig.subDomainSet) {
- return defaultServiceConfig.subDomain;
- }
- return subDomain;
- }
-
- public void setMin_app_instances(int minAppInstances) {
-// if (minAppInstances < 1) {
-// LoadBalancerConfigUtil.handleException("minAppInstances in the autoscaler task configuration " +
-// "should be at least 1");
-// }
- this.minAppInstances = minAppInstances;
- this.minAppInstancesSet = true;
- }
-
- public void setMax_app_instances(int maxAppInstances) {
- if (maxAppInstances < 1) {
- LoadBalancerConfigUtil.handleException("maxAppInstances in the autoscaler task configuration " +
- "should be at least 1");
- }
- this.maxAppInstances = maxAppInstances;
- this.maxAppInstancesSet = true;
- }
-
- public void setAlarming_upper_rate(double rate) {
- if (rate > 0 && rate <= 1) {
- this.alarmingUpperRate = rate;
- this.alarmingUpperRateSet = true;
- }
- }
-
- public void setAlarming_lower_rate(double rate) {
- if (rate > 0 && rate <= 1) {
- this.alarmingLowerRate = rate;
- this.alarmingLowerRateSet = true;
- }
- }
-
- public void setScale_down_factor(double factor) {
- if (factor > 0 && factor <= 1) {
- this.scaleDownFactor = factor;
- this.scaleDownFactorSet = true;
- }
- }
-
- public void setMax_requests_per_second(int rps) {
- this.maxRequestsPerSecond = rps;
- this.maxRequestsPerSecondSet = true;
- }
-
- public void setRounds_to_average(int roundsToAverage) {
- this.roundsToAverage = roundsToAverage;
- this.roundsToAverageSet = true;
- }
-
- public void setInstances_per_scale_up(int instancesPerScaleUp) {
- if (instancesPerScaleUp < 1) {
- LoadBalancerConfigUtil.handleException("instancesPerScaleUp in the autoscaler task configuration " +
- "should be at least 1");
- }
- this.instancesPerScaleUp = instancesPerScaleUp;
- this.instancesPerScaleUpSet = true;
- }
-
- public void setMessage_expiry_time(int messageExpiryTime) {
- if (messageExpiryTime < 1) {
- LoadBalancerConfigUtil.handleException("messageExpiryTime in the autoscaler task configuration " +
- "should be at least 1");
- }
- this.messageExpiryTime = messageExpiryTime;
- this.messageExpiryTimeSet = true;
- }
-
- public void setHosts(String hostsStr) {
- // clear all unnecessary values --> property will get overwritten
- hosts = new ArrayList<String>();
- // there can be multiple hosts, let's find out.
- String[] host = hostsStr.split(Constants.HOSTS_DELIMITER);
-
- for (String string : host) {
- if (!string.isEmpty()) {
- this.hosts.add(string);
- }
- }
-
- }
-
- public void setUrl_suffix(String suffix) {
- // clear all unnecessary values --> property will get overwritten
- //hosts = new ArrayList<String>();
- // there can be multiple hosts, let's find out.
- String[] suffixes = suffix.split(Constants.HOSTS_DELIMITER);
- int count = 0;
- if(suffixes.length == this.hosts.size()) {
- for (String string : suffixes) {
- if (!string.isEmpty()) {
- this.urlSuffixes.put(this.hosts.get(count), string);
- count++;
- }
- }
-
- } else {
- //Error
- }
- }
-
- public Map<String, String> getUrl_suffix() {
- return this.urlSuffixes;
- }
-
- public void setTenant_range(String range) {
- this.tenantRange = range;
- }
-
- public void setSub_domain(String subDomain) {
- this.subDomain = subDomain;
- this.subDomainSet = true;
- }
-
- public void setDomain(String domain) {
- this.domain = domain;
- }
-
- public boolean equals(ServiceConfiguration config) {
- return this.domain.equals(config.getDomain()) &&
- this.subDomain.equals(config.getSubDomain());
- }
-
- public int hashCode() {
- return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
- append(domain).
- append(subDomain).
- toHashCode();
- }
-
- public double getAlarmingUpperRate() {
- if (alarmingUpperRateSet) {
- return alarmingUpperRate;
- } else if (defaultServiceConfig != null && defaultServiceConfig.alarmingUpperRateSet) {
- return defaultServiceConfig.alarmingUpperRate;
- }
- return alarmingUpperRate;
- }
-
- public double getAlarmingLowerRate() {
- if (alarmingLowerRateSet) {
- return alarmingLowerRate;
- } else if (defaultServiceConfig != null && defaultServiceConfig.alarmingLowerRateSet) {
- return defaultServiceConfig.alarmingLowerRate;
- }
- return alarmingLowerRate;
- }
-
- public double getScaleDownFactor() {
- if (scaleDownFactorSet) {
- return scaleDownFactor;
- } else if (defaultServiceConfig != null && defaultServiceConfig.scaleDownFactorSet) {
- return defaultServiceConfig.scaleDownFactor;
- }
- return scaleDownFactor;
- }
- }
-
- public Map<String, Set<String>> getHostNamesTracker() {
- return hostNamesTracker;
- }
-
-
- public Map<String, Map<String, ServiceConfiguration>> getServiceConfigurations() {
- return serviceConfigurations;
- }
-
-
- public Node getRootNode() {
- return rootNode;
- }
-
-
- public void setRootNode(Node rootNode) {
- this.rootNode = rootNode;
- }
-
- public static void setInstance(LoadBalancerConfiguration instance) {
- LoadBalancerConfiguration.instance = instance;
- }
-
- public Map<String, List<ServiceConfiguration>> getServiceNameToServiceConfigurations() {
- return serviceNameToServiceConfigurations;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
deleted file mode 100644
index b488bf3..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.conf.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
-import org.wso2.carbon.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
-
-/**
- * Registering {@link LoadBalancerConfigurationService} .
- * @scr.component name="org.wso2.carbon.lb.common" immediate="true"
- */
-public class LoadBalancerConfigurationDSComponent {
-
- private static final Log log = LogFactory.getLog(LoadBalancerConfigurationDSComponent.class);
-
- protected void activate(ComponentContext context) {
- try {
- BundleContext bundleContext = context.getBundleContext();
- bundleContext.registerService(LoadBalancerConfigurationService.class.getName(),
- new LoadBalancerConfigurationServiceImpl(), null);
-
- log.debug("******* Load Balancer Configuration Service bundle is activated ******* ");
- } catch (Exception e) {
- log.error("******* Load Balancer Configuration Service bundle is failed to activate ****", e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java
deleted file mode 100644
index a1ccc60..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * 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.wso2.carbon.lb.common.conf.structure;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-
-/**
- * This is the basic data structure which holds a <i>Nginx</i> formatted configuration file.
- *
- */
-public class Node implements Serializable{
-
- private static final long serialVersionUID = 4071569903421115370L;
-
- /**
- * Name of this Node element
- */
- private String name;
-
- /**
- * Every node can have 0..n child nodes.
- * They are kept in a List.
- */
- private List<Node> childNodes = new ArrayList<Node>();
-
- /**
- * Every node can have 0..n properties.
- * They are kept in a Map, in the order they appear.
- * Key: property name
- * Value: property value
- */
- private Map<String, String> properties = new LinkedHashMap<String, String>();
-
- public void setChildNodes(List<Node> childNodes) {
- this.childNodes = childNodes;
- }
-
- public void setProperties(Map<String, String> properties) {
- this.properties = properties;
- }
-
- /**
- * This will convert each child Node of this Node to a String.
- * @return a string which represents child nodes of this node.
- */
- public String childNodesToString(int indentation) {
- StringBuilder childNodesString = new StringBuilder();
- indentation++;
-
- for (Node node : childNodes) {
- childNodesString.append(node.toString(indentation)+"\n");
- }
-
- return childNodesString.toString();
- }
-
- /**
- * This will try to find a child Node of this Node, which has the given name.
- * @param name name of the child node to find.
- * @return child Node object if found or else <code>null</code>.
- */
- public Node findChildNodeByName(String name) {
- for (Node aNode : childNodes) {
- if (aNode.getName().equals(name)) {
- return aNode;
- }
- }
-
- return null;
- }
-
- /**
- * Returns the name of this Node.
- * @return name of the node.
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns child nodes List of this Node.
- * @return List of Node
- */
- public List<Node> getChildNodes() {
- return childNodes;
- }
-
- /**
- * Returns properties Map of this Node.
- * @return Map whose keys and values are String.
- */
- public Map<String, String> getProperties() {
- return properties;
- }
-
- /**
- * Returns the value of a given property.
- * @param key name of a property.
- * @return trimmed value if the property is found in this Node, or else <code>null</code>.
- */
- public String getProperty(String key) {
- if (properties.get(key) == null) {
- return null;
- }
- return properties.get(key).trim();
- }
-
- /**
- * Returns all the properties of this Node as a String.
- * Key and value of the property is separated by a tab (\t) character and
- * each property is separated by a new line character.
- * @param indentation relative number of tabs
- * @return properties of this node as a String.
- */
- public String propertiesToString(int indentation) {
-
- String indent = getIndentation(indentation);
-
- StringBuilder sb = new StringBuilder();
- for (Map.Entry<String, String> entry : properties.entrySet()) {
- // hack to get a quick fix in.
- if (!"tenant_id".equals(entry.getKey()) && !"alias".equals(entry.getKey())) {
- sb.append(indent + entry.getKey() + "\t" + entry.getValue() + ";\n");
- }
- }
- return sb.toString();
- }
-
- /**
- * Removes the first occurrence of a node having the given name
- * and returns the removed {@link Node}.
- * @param name name of the child node to be removed.
- * @return removed {@link Node} or else <code>null</code>.
- */
- public Node removeChildNode(String name) {
- Node aNode = findChildNodeByName(name);
-
- if(aNode != null){
- if(childNodes.remove(aNode)){
- return aNode;
- }
- }
-
- return null;
- }
-
- /**
- * Removes the first occurrence of a node equals to the given node.
- * @param node {@link Node} to be removed.
- * @return whether the removal is successful or not.
- */
- public boolean removeChildNode(Node node){
-
- return childNodes.remove(node);
- }
-
- /**
- * Sets the name of this Node.
- * @param name String to be set as the name.
- */
- public void setName(String name) {
- this.name = name;
- }
-
- /**
- * Appends a child node at the end of the List of child nodes of this Node, if
- * a similar node is not already present as a child node.
- * @param aNode child Node to be appended.
- */
- public void appendChild(Node aNode) {
- if (aNode != null && !nodeAlreadyPresent(aNode)) {
- childNodes.add(aNode);
- }
- }
-
- /**
- * Adds a new property to properties Map of this Node if and only if
- * key is not <code>null</code>.
- * @param key name of the property to be added.
- * @param value value of the property to be added.
- */
- public void addProperty(String key, String value) {
- if (key != null) {
- properties.put(key, value);
- }
- }
-
- /**
- * Convert this Node to a String which is in <i>Nginx</i> format.
- * <br/>
- * Sample:
- * <br></br>
- * <code>
- * ij {
- * <br/>
- * klm n;
- * <br/>
- * pq {
- * <br/>
- * rst u;
- * <br/>
- * }
- * <br/>
- * }
- * <br/>
- * </code>
- */
- public String toString() {
-
- String nodeString =
- getName()+" {\n" +
- (propertiesToString(1)) +
- (childNodesToString(1)) +
- "}";
-
- return nodeString;
- }
-
- public boolean equals(Object node) {
-
- if(node instanceof Node){
- return this.getName().equals(((Node) node).getName()) &&
- isIdenticalProperties(this.getProperties(), ((Node) node).getProperties()) &&
- isIdenticalChildren(this.getChildNodes(), ((Node) node).getChildNodes());
- }
-
- return false;
-
- }
-
- public int hashCode() {
- return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
- append(name).
- append(properties).
- append(childNodes).
- toHashCode();
- }
-
- private boolean isIdenticalChildren(List<Node> childNodes1, List<Node> childNodes2) {
-
- if(childNodes1.size() != childNodes2.size()){
- return false;
- }
-
- for (Node node1 : childNodes1) {
- int i=0;
- for (Node node2 : childNodes2) {
-
- i++;
- if(node1.equals(node2)){
- break;
- }
-
- if(i == childNodes1.size()){
- return false;
- }
-
- }
- }
-
- return true;
- }
-
- private boolean nodeAlreadyPresent(Node aNode){
-
- for(Node node : this.childNodes){
- if(node.equals(aNode)){
- return true;
- }
- }
-
- return false;
- }
-
- private boolean isIdenticalProperties(Map<String, String> map1,
- Map<String, String> map2) {
-
- if(map1.size() != map2.size()){
- return false;
- }
-
- for (Iterator<Entry<String, String>> iterator1 = map1.entrySet().iterator(); iterator1.hasNext();) {
- Map.Entry<String, String> entry1 = (Map.Entry<String, String>) iterator1.next();
-
- int i=0;
-
- for(Iterator<Entry<String, String>> iterator2 = map2.entrySet().iterator(); iterator2.hasNext();) {
- Map.Entry<String, String> entry2 = (Map.Entry<String, String>) iterator2.next();
-
- i++;
-
- if((entry1.getKey().equals(entry2.getKey()) &&
- entry1.getValue().equals(entry2.getValue()))){
-
- break;
- }
-
- if(i == map1.size()){
- return false;
- }
-
- }
- }
-
- return true;
- }
-
- private String toString(int indentation){
-
- String indent = getIndentation(indentation-1);
-
- String nodeString =
- indent + getName()+" {\n" +
- (propertiesToString(indentation)) +
- (childNodesToString(indentation)) +
- indent + "}";
-
- return nodeString;
- }
-
- private String getIndentation(int tabs){
-
- StringBuilder indent = new StringBuilder("");
-
- for (int i = 0; i < tabs; i++) {
- indent.append("\t");
- }
-
- return indent.toString();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java
deleted file mode 100644
index f7bfe2f..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.wso2.carbon.lb.common.conf.structure;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.common.conf.util.Constants;
-
-/**
- * This responsible for build up a Node object from a given content.
- * Every closing brace should be in a new line.
- */
-public class NodeBuilder {
-
- private static final Log log = LogFactory.getLog(NodeBuilder.class);
-
- /**
- * This method is useful when you do not have a root node in your content.
- * @param aNode
- * Node object whose name set.
- * @param content
- * should be something similar to following.
- *
- * abc d;
- * efg h;
- * # comment
- * ij { # comment
- * klm n;
- *
- * pq {
- * rst u;
- * }
- * }
- *
- * @return fully constructed Node
- */
- public static Node buildNode(Node aNode, String content) {
-
- if(content == null || content.isEmpty()){
- return aNode;
- }
-
- String[] lines = content.split("\n");
-
- for (int i = 0; i < lines.length; i++) {
- String line = lines[i].trim();
-
- // avoid line comments
- if (!line.startsWith(Constants.NGINX_COMMENT)) {
-
- // skip comments in-line
- if(line.contains(Constants.NGINX_COMMENT)){
- line = line.substring(0, line.indexOf(Constants.NGINX_COMMENT));
- }
-
- // another node is detected and it is not a variable starting from $
- if (line.contains(Constants.NGINX_NODE_START_BRACE) &&
- !line.contains(Constants.NGINX_VARIABLE)) {
-
- try {
- Node childNode = new Node();
- childNode.setName(line.substring(0, line.indexOf(Constants.NGINX_NODE_START_BRACE)).trim());
-
- StringBuilder sb = new StringBuilder();
-
- int matchingBraceTracker = 1;
-
- while (!line.contains(Constants.NGINX_NODE_END_BRACE) || matchingBraceTracker != 0) {
- i++;
- if (i == lines.length) {
- break;
- }
- line = lines[i];
- if (line.contains(Constants.NGINX_NODE_START_BRACE)) {
- matchingBraceTracker++;
- }
- if (line.contains(Constants.NGINX_NODE_END_BRACE)) {
- matchingBraceTracker--;
- }
- sb.append(line + "\n");
- }
-
- childNode = buildNode(childNode, sb.toString());
- if (aNode == null) {
- aNode = childNode;
- } else {
- aNode.appendChild(childNode);
- }
-
- } catch (Exception e) {
- String msg = "Malformatted element is defined in the configuration file. [" +
- i + "] \n";
- log.error(msg , e);
- throw new RuntimeException(msg + line, e);
- }
-
- }
- // this is a property
- else {
- if (!line.isEmpty() && !Constants.NGINX_NODE_END_BRACE.equals(line)) {
- String[] prop = line.split(Constants.NGINX_SPACE_REGEX);
- String value = line.substring(prop[0].length(), line.indexOf(Constants.NGINX_LINE_DELIMITER)).trim();
- try {
- aNode.addProperty(prop[0], value);
- } catch (Exception e) {
- String msg = "Malformatted property is defined in the configuration file. [" +
- i + "] \n";
- log.error(msg, e);
- throw new RuntimeException(msg + line, e);
- }
- }
- }
-
- }
- }
-
- return aNode;
-
- }
-
- public static Node buildNode(String content) {
- return buildNode(null, content);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java
deleted file mode 100644
index bc83ca9..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.conf.util;
-
-/**
- * This keeps the element names used in loadbalancer.conf file
- */
-public class Constants {
-
- public static final String LOAD_BALANCER_ELEMENT = "loadbalancer";
- public static final String SERVICES_ELEMENT = "services";
- public static final String DEFAULTS_ELEMENT = "defaults";
- public static final String HOSTS_ELEMENT = "hosts";
- public static final String HOSTS_DELIMITER = ",";
- public static final String DOMAIN_ELEMENT = "domains";
- public static final String TENANT_RANGE_ELEMENT = "tenant_range";
- public static final String SUB_DOMAIN_ELEMENT = "sub_domain";
- public static final String TENANT_RANGE_DELIMITER = "-";
- public static final String UNLIMITED_TENANT_RANGE = "*";
- public static final String AUTOSCALER_ENABLE_ELEMENT = "enable_autoscaler";
- public static final String SUB_DOMAIN_DELIMITER = "#";
- public static final String DEFAULT_SUB_DOMAIN = "__$default";
-
- /* Nginx format related constants */
-
- public static final String NGINX_COMMENT = "#";
- public static final String NGINX_NODE_START_BRACE = "{";
- public static final String NGINX_NODE_END_BRACE = "}";
- public static final String NGINX_VARIABLE = "${";
- public static final String NGINX_LINE_DELIMITER = ";";
- public static final String NGINX_SPACE_REGEX = "[\\s]+";
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java
deleted file mode 100644
index 1845017..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.conf.util;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
-import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
-
-/**
- * For each unique host name defined in loadbalancer configuration, we'll generate
- * this object.
- */
-public class HostContext {
-
- /**
- * A unique identifier to identify this {@link #HostContext()}
- */
- private String hostName;
-
- /**
- * Key - tenant id
- * Value - <code>TenantDomainContext</code> of the corresponding tenant
- */
- private Map<Integer, TenantDomainContext> tenantIdToTenantDomainContextMap = new HashMap<Integer, TenantDomainContext>();
-
- /**
- * AlgorithmContext of this host
- */
- private AlgorithmContext algorithmContext;
-
- /**
- * Load balance algorithm of this host
- */
- private LoadbalanceAlgorithm algorithm;
-
- private String urlSuffix;
-
- public HostContext(String hostName) {
- this.hostName = hostName;
- }
-
- public void addTenantDomainContexts(List<TenantDomainContext> ctxts) {
-
- for (TenantDomainContext tenantDomainContext : ctxts) {
- tenantIdToTenantDomainContextMap.put(tenantDomainContext.getTenantId(), tenantDomainContext);
- }
- }
-
- @Deprecated
- public void addTenantDomainContext(TenantDomainContext ctxt) {
- tenantIdToTenantDomainContextMap.put(ctxt.getTenantId(), ctxt);
- }
-
- public TenantDomainContext getTenantDomainContext(int tenantId) {
- return tenantIdToTenantDomainContextMap.get(tenantId);
- }
-
- /**
- * Returns all the {@link TenantDomainContext} entries.
- */
- public Collection<TenantDomainContext> getTenantDomainContexts() {
- return tenantIdToTenantDomainContextMap.values();
- }
-
- /**
- * Given a tenant id, this will return its domain.
- * @param tenantId
- * @return domain if this tenant has a dedicated one, it will be returned.
- * If not, and there's a default (*) domain, it will be returned.
- * If neither of the above is defined, null will be returned.
- */
- public String getDomainFromTenantId(int tenantId) {
- if (tenantIdToTenantDomainContextMap.get(tenantId) == null) {
- // if there's no specific domain for this tenant, we will redirect it to the default
- // cluster
-
- if(tenantIdToTenantDomainContextMap.get(0) == null){
- return null;
- }
-
- return tenantIdToTenantDomainContextMap.get(0).getDomain();
- }
-
- return tenantIdToTenantDomainContextMap.get(tenantId).getDomain();
- }
-
- /**
- * Given a tenant id, this will return its sub domain.
- * @param tenantId
- * @return sub_domain if this tenant has a dedicated one, it will be returned.
- * If not, and there's a default (*) sub domain, it will be returned.
- * If neither of the above is defined, null will be returned.
- */
- public String getSubDomainFromTenantId(int tenantId) {
- if (tenantIdToTenantDomainContextMap.get(tenantId) == null) {
- // if there's no specific domain for this tenant, we will redirect it to the default
- // cluster
-
- if(tenantIdToTenantDomainContextMap.get(0) == null){
- return null;
- }
-
- return tenantIdToTenantDomainContextMap.get(0).getSubDomain();
- }
-
- return tenantIdToTenantDomainContextMap.get(tenantId).getSubDomain();
- }
-
- public String getHostName() {
- return hostName;
- }
-
- public LoadbalanceAlgorithm getAlgorithm() {
- return algorithm;
- }
-
- public AlgorithmContext getAlgorithmContext() {
- return algorithmContext;
- }
-
- public void setAlgorithmContext(AlgorithmContext algorithmContext) {
- this.algorithmContext = algorithmContext;
- }
-
- public void setAlgorithm(LoadbalanceAlgorithm algorithm) {
- this.algorithm = algorithm;
- }
-
- public Map<Integer, TenantDomainContext> getTenantIdToTenantDomainContextMap() {
- return tenantIdToTenantDomainContextMap;
- }
-
- public void setUrlSuffix(String suffix) {
- this.urlSuffix = suffix;
- }
-
- public String getUrlSuffix() {
- return this.urlSuffix;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java
deleted file mode 100644
index 404849b..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * 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.wso2.carbon.lb.common.conf.util;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import sun.misc.BASE64Encoder;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Utility methods for Autoscale mediator
- */
-public final class LoadBalancerConfigUtil {
-
- private static final Log log = LogFactory.getLog(LoadBalancerConfigUtil.class);
-
- private LoadBalancerConfigUtil() {
- }
-
- /**
- * handles the exception
- *
- * @param msg
- * exception message
- */
- public static void handleException(String msg) {
- log.error(msg);
- throw new RuntimeException(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);
- }
-
- /**
- * 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 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 = LoadBalancerConfigUtil.getBytesFromFile(file);
- if (bytes != null) {
- BASE64Encoder encoder = new BASE64Encoder();
- userData = encoder.encode(bytes);
- }
- } catch (Exception e) {
- LoadBalancerConfigUtil.handleException("Cannot read data from payload file " +
- payloadFileName, e);
-
- }
- return userData;
- }
-
- /**
- * 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;
- }
-
- /**
- * @deprecated
- * Extract the domain part given a string which is in
- * <sub_domain>#<domain> format.
- * @param str
- * in <sub_domain>#<domain> format.
- * @return the domain part. If # is not present this will return the trimmed
- * input string.
- */
- public static String getDomain(String str) {
- str = str.trim();
- if (!str.contains(Constants.SUB_DOMAIN_DELIMITER)) {
- return str;
- }
- return str.substring(str.indexOf(Constants.SUB_DOMAIN_DELIMITER) + 1);
- }
-
- /**
- * @deprecated
- * Extract the sub_domain part given a string which is in
- * <sub_domain>#<domain> format.
- * @param str
- * in <sub_domain>#<domain> format.
- * @return the sub_domain part. If # is not present this will return <code>null</code>.
- */
- public static String getSubDomain(String str) {
- str = str.trim();
- if (!str.contains(Constants.SUB_DOMAIN_DELIMITER)) {
- return null;
- }
- return str.substring(0, str.indexOf(Constants.SUB_DOMAIN_DELIMITER));
- }
-
- // public static EC2InstanceManager createEC2InstanceManager(String accessKey,
- // String secretKey,
- // String instanceMgtEPR) {
- // AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
- // AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
- // ec2Client.setEndpoint(instanceMgtEPR);
- // return new EC2InstanceManager(ec2Client);
- // }
-
- public static List<TenantDomainContext> getTenantDomainContexts(String tenantRange, String domain, String subDomain) {
-
- List<TenantDomainContext> ctxts = new ArrayList<TenantDomainContext>();
- List<Integer> tenantIds = getTenantIds(tenantRange);
-
- // iterate through all tenant ids under this host
- for (Integer tId : tenantIds) {
-
- // create a new TenantDomainContext
- TenantDomainContext tenantCtxt =
- new TenantDomainContext(
- tId,
- domain,
- subDomain);
- // add it to the list
- ctxts.add(tenantCtxt);
- }
-
- return ctxts;
-
- }
-
- /**
- * This method will read the tenant range string and return a list of tenant ids
- * which is derived from tenant range string.
- *
- * @param tenantRange
- * @return list of tenant ids.
- */
- public static List<Integer> getTenantIds(String tenantRange) {
-
- List<Integer> tenantIds = new ArrayList<Integer>();
-
- String[] parsedLine = tenantRange.trim().split("-");
-
- if (parsedLine[0].equalsIgnoreCase("*")) {
- tenantIds.add(0);
-
- } else if (parsedLine.length == 1) {
- try {
- int tenantId = Integer.parseInt(tenantRange);
- tenantIds.add(tenantId);
-
- } catch (NumberFormatException e) {
- String msg = "Invalid tenant range is specified : " + tenantRange;
- log.error(msg, e);
- throw new RuntimeException(msg, e);
- }
- } else if (parsedLine.length == 2) {
- try {
-
- int startIndex = Integer.parseInt(parsedLine[0]);
- int endIndex = Integer.parseInt(parsedLine[1]);
-
- for (int tenantId = startIndex; tenantId <= endIndex; tenantId++) {
-
- tenantIds.add(tenantId);
- }
-
- } catch (NumberFormatException e) {
- String msg = "Invalid tenant range is specified : " + tenantRange;
- log.error(msg, e);
- throw new RuntimeException(msg, e);
- }
-
- } else {
- String msg = "Invalid tenant range is specified : " + tenantRange;
- log.error(msg);
- throw new RuntimeException(msg);
- }
-
- return tenantIds;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java
deleted file mode 100644
index fdb893e..0000000
--- a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
-* 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.wso2.carbon.lb.common.conf.util;
-
-/**
- * This object will hold all the data related to a tenant.
- */
-public class TenantDomainContext {
-
- /**
- * this is the unique identifier for this object
- */
- private int tenantId;
-
- /**
- * Domain, which this tenant belongs to.
- */
- private String domain;
-
- /**
- * Sub domain, which this tenant belongs to.
- */
- private String subDomain;
-
- public TenantDomainContext(int tenantId, String domain, String subDomain) {
- this.tenantId = tenantId;
- this.domain = domain;
- this.subDomain = subDomain;
- }
-
-
- /** Getters and Setters **/
-
- public int getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(int tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getDomain() {
- return domain;
- }
-
- public void setDomain(String domain) {
- this.domain = domain;
- }
-
- public String getSubDomain() {
- return subDomain;
- }
-
- public void setSubDomain(String subDomain) {
- this.subDomain = subDomain;
- }
-
-
- /** End of Getters and Setters **/
-
-
-
-
-}
[08/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
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/callables/AutoscaleDeciderCallable.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/callables/AutoscaleDeciderCallable.java b/components/load-balancer/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..544e026
--- /dev/null
+++ b/components/load-balancer/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 @@
+/*
+* 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.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+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 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.context.AppDomainContext;
+
+/** 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/290c6307/components/load-balancer/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/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java b/components/load-balancer/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..b3b1070
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
@@ -0,0 +1,77 @@
+/*
+* 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.callables;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+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;
+
+/** 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/290c6307/components/load-balancer/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/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java b/components/load-balancer/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..fcd3271
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
@@ -0,0 +1,64 @@
+/*
+* 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.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+
+/** 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/290c6307/components/load-balancer/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/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java b/components/load-balancer/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..c49e77b
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
@@ -0,0 +1,67 @@
+/*
+* 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.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/** 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/290c6307/components/load-balancer/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/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java b/components/load-balancer/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..640f4c6
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
@@ -0,0 +1,65 @@
+/*
+* 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.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/290c6307/components/load-balancer/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/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java b/components/load-balancer/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..a4c75ca
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
@@ -0,0 +1,81 @@
+/*
+ * 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.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();
+ }
+
+}
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/clients/CloudControllerStubClient.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/clients/CloudControllerStubClient.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
new file mode 100644
index 0000000..6159dc6
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
@@ -0,0 +1,92 @@
+/*
+ * 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.clients;
+
+import org.apache.axis2.AxisFault;
+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.stub.CloudControllerServiceStub;
+
+/**
+ * This is the client class this calls Autoscaler service.
+ */
+public class CloudControllerStubClient extends CloudControllerClient {
+
+ private CloudControllerServiceStub stub;
+ private static final String CLOUD_CONTROLLER_EPR = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerServiceEpr();
+
+ private static final Log log = LogFactory.getLog(CloudControllerStubClient.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 stub.startInstance(domainName, subDomainName);
+ }
+
+ public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
+
+ return stub.terminateInstance(domainName, subDomainName);
+ }
+
+ public boolean
+ terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
+
+ return stub.terminateLastlySpawnedInstance(domainName, subDomainName);
+ }
+
+ public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
+
+ return stub.getPendingInstanceCount(domainName, subDomainName);
+ }
+
+ @Override
+ public void init() {
+
+ try {
+
+ stub = new CloudControllerServiceStub(CLOUD_CONTROLLER_EPR);
+ stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
+
+ } catch (AxisFault axisFault) {
+ String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+ log.error(msg, axisFault);
+ throw new RuntimeException(msg, axisFault);
+ }
+ }
+
+}
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/context/AppDomainContext.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/context/AppDomainContext.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
new file mode 100644
index 0000000..c9f2a13
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
@@ -0,0 +1,169 @@
+/*
+* 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.context;
+
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+
+
+/**
+ * Contextual information related to autoscaling for a particular clustering domain
+ */
+public class AppDomainContext extends LoadBalancerContext{
+
+ private static final long serialVersionUID = 6582721801663800609L;
+
+ private static final Log log = LogFactory.getLog(AppDomainContext.class);
+
+ /**
+ * Request tokens of requests in flight
+ * <p/>
+ * Key - request token ID, Value - message received time
+ */
+ private Map<String, Long> requestTokens = new ConcurrentHashMap<String, Long>();
+ private List<Integer> requestTokenListLengths;
+ private LoadBalancerConfiguration.ServiceConfiguration serviceConfig;
+
+ public AppDomainContext(LoadBalancerConfiguration.ServiceConfiguration serviceConfig) {
+ this.serviceConfig = serviceConfig;
+ requestTokenListLengths = new Vector<Integer>(serviceConfig.getRoundsToAverage());
+ }
+
+ public LoadBalancerConfiguration.ServiceConfiguration getServiceConfig() {
+ return serviceConfig;
+ }
+
+ /**
+ * If there is insufficient number of messages we cannot make a scaling decision.
+ *
+ * @return true - if a scaling decision can be made
+ */
+ public boolean canMakeScalingDecision() {
+ return requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage();
+ }
+
+ public void addRequestToken(String tokenId) {
+ requestTokens.put(tokenId, System.currentTimeMillis());
+ if (log.isDebugEnabled()) {
+ log.debug("Request Tokens Added : "+requestTokens.size());
+ }
+ }
+
+ public void removeRequestToken(String tokenId) {
+ requestTokens.remove(tokenId);
+ }
+
+// public int getRunningInstanceCount() {
+// return super.getRunningInstanceCount();
+// }
+
+ /**
+ * This will set the running instance count for this app domain
+ * and also will return the difference of current running instance count and previous count.
+ * @param runningInstanceCount current running instance count
+ * @return difference of current running instance count and previous count.
+ */
+// public int setRunningInstanceCount(int runningInstanceCount) {
+// int diff = 0;
+//
+// if(this.runningInstanceCount < runningInstanceCount){
+// diff = runningInstanceCount - this.runningInstanceCount;
+// }
+//
+// this.runningInstanceCount = runningInstanceCount;
+//
+// return diff;
+// }
+
+ public void expireRequestTokens() {
+ for (Map.Entry<String, Long> entry : requestTokens.entrySet()) {
+ if (System.currentTimeMillis() - entry.getValue() >= serviceConfig.getMessageExpiryTime()) {
+ requestTokens.remove(entry.getKey());
+ if (log.isDebugEnabled()) {
+ log.debug("Request Tokens Expired : " + requestTokens.get(entry.getKey()));
+ }
+ }
+ }
+ }
+
+ public void recordRequestTokenListLength() {
+ if (requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage()) {
+ int count = requestTokenListLengths.remove(0);
+ if (log.isDebugEnabled()) {
+ log.debug("Request Tokens Removed : " + count);
+ }
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("Request Tokens Added : " + requestTokens.size());
+ }
+ requestTokenListLengths.add(requestTokens.size());
+ }
+
+
+// public synchronized int getPendingInstances() {
+// return pendingInstances;
+// }
+
+// public synchronized void incrementPendingInstances() {
+// this.pendingInstances++;
+// }
+
+// public synchronized void decrementPendingInstancesIfNotZero(int diff) {
+//
+// while (diff > 0 && this.pendingInstances > 0 ){
+// this.pendingInstances--;
+// diff--;
+// }
+//
+// }
+
+// public synchronized int getInstances() {
+// return runningInstanceCount + pendingInstances;
+// }
+
+ /**
+ * Get the average requests in flight, averaged over the number of of observations rounds
+ *
+ * @return number of average requests in flight. -1 if there no requests were received
+ */
+ public long getAverageRequestsInFlight() {
+ long total = 0;
+ for (Integer messageQueueLength : requestTokenListLengths) {
+ total += messageQueueLength;
+ }
+ int size = requestTokenListLengths.size();
+ if (size == 0) {
+ return -1; // -1 means that no requests have been received
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("Total Tokens : "+total+ " : Size: "+size);
+ }
+ return (long) total / size;
+ }
+
+
+// public synchronized void resetRunningPendingInstances() {
+// pendingInstances = 0;
+// runningInstanceCount = 0;
+// }
+}
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/context/LoadBalancerContext.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/context/LoadBalancerContext.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
new file mode 100644
index 0000000..7b58393
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
@@ -0,0 +1,103 @@
+/*
+* 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.context;
+
+import java.io.Serializable;
+
+/**
+ * Contextual information related to autoscaling for a particular domain
+ */
+public class LoadBalancerContext implements Serializable{
+
+ private static final long serialVersionUID = -2022110665957598060L;
+ private int runningInstances;
+ private int pendingInstances;
+ private int terminatingInstances;
+
+ public synchronized int getTerminatingInstanceCount() {
+ return terminatingInstances;
+ }
+
+ public synchronized int getRunningInstanceCount() {
+ return runningInstances;
+ }
+
+ public synchronized int getPendingInstanceCount() {
+ return pendingInstances;
+ }
+
+ /**
+ * This will set the running instance count for a domain
+ * and also will return the difference of current running instance count and previous count.
+ * @param runningInstanceCount current running instance count
+ * @return difference of current running instance count and previous count.
+ */
+ public synchronized int setRunningInstanceCount(int count) {
+ int diff = 0;
+
+ if (this.runningInstances < count) {
+ diff = count - this.runningInstances;
+ }
+
+ this.runningInstances = count;
+
+ return diff;
+ }
+
+ public synchronized int getInstances() {
+ return runningInstances + pendingInstances;
+ }
+
+ public synchronized void setPendingInstanceCount(int count) {
+
+ this.pendingInstances = count;
+ }
+
+ public synchronized void setTerminatingInstanceCount(int count) {
+
+ this.terminatingInstances = count;
+ }
+
+ public synchronized void incrementPendingInstances(int diff) {
+
+ this.pendingInstances += diff;
+ }
+
+ public synchronized void incrementTerminatingInstances(int diff) {
+
+ this.terminatingInstances += diff;
+ }
+
+ public synchronized void decrementPendingInstancesIfNotZero(int diff) {
+
+ while (diff > 0 && this.pendingInstances > 0) {
+ this.pendingInstances--;
+ diff--;
+ }
+
+ }
+
+ public synchronized void decrementTerminatingInstancesIfNotZero(int diff) {
+
+ while (diff > 0 && this.terminatingInstances > 0) {
+ this.terminatingInstances--;
+ diff--;
+ }
+
+ }
+}
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/internal/AutoscalerTaskServiceComponent.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/internal/AutoscalerTaskServiceComponent.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
new file mode 100644
index 0000000..ebde723
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
@@ -0,0 +1,328 @@
+/*
+ * 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.internal;
+
+import java.util.Date;
+import java.util.Map;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.stratos.mediator.autoscale.lbautoscale.task.AutoscalerTaskInitializer;
+import org.apache.stratos.mediator.autoscale.lbautoscale.task.AutoscalingJob;
+import org.apache.stratos.mediator.autoscale.lbautoscale.task.ServiceRequestsInFlightAutoscaler;
+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.Mediator;
+import org.apache.synapse.SynapseConstants;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.mediators.base.SequenceMediator;
+import org.apache.synapse.mediators.filters.InMediator;
+import org.apache.synapse.mediators.filters.OutMediator;
+import org.apache.synapse.task.Task;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskScheduler;
+import org.apache.synapse.task.service.TaskManagementService;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.quartz.JobBuilder;
+import org.quartz.JobDetail;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.apache.stratos.mediator.autoscale.lbautoscale.mediators.AutoscaleInMediator;
+import org.apache.stratos.mediator.autoscale.lbautoscale.mediators.AutoscaleOutMediator;
+import org.apache.stratos.mediator.autoscale.lbautoscale.task.AutoscalerTaskMgmtAdminService;
+import org.apache.stratos.mediator.autoscale.lbautoscale.task.TaskSchedulingManager;
+import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name="autoscaler.task.component" immediate="true"
+ * @scr.reference name="carbon.core.configurationContextService"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ * @scr.reference name="org.wso2.carbon.lb.common"
+ * interface="org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
+ * unbind="unsetLoadBalancerConfigurationService"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="org.wso2.carbon.stratos.cloud.controller"
+ * interface="org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService"
+ * cardinality="1..1" policy="dynamic" bind="setCloudControllerService"
+ * unbind="unsetCloudControllerService"
+ */
+public class AutoscalerTaskServiceComponent {
+
+ private static final Log log = LogFactory.getLog(AutoscalerTaskServiceComponent.class);
+ private ConfigurationContext configurationContext = null;
+
+ protected void activate(ComponentContext context) {
+
+ try{
+
+ // read config file
+// String configURL = System.getProperty(AutoscaleConstants.LOAD_BALANCER_CONFIG);
+// LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration();
+// lbConfig.init(configURL);
+
+ if(configurationContext == null){
+ String msg = "Configuration context is null. Autoscaler task activation failed.";
+ log.fatal(msg);
+ throw new RuntimeException(msg);
+ }
+
+ // load synapse environment
+ Parameter synEnv =
+ configurationContext.getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
+
+ if (synEnv == null || synEnv.getValue() == null ||
+ !(synEnv.getValue() instanceof SynapseEnvironment)) {
+
+ String message = "Unable to initialize the Synapse Configuration : Can not find the ";
+ log.fatal(message + "Synapse Environment");
+ throw new SynapseException(message + "Synapse Environment");
+ }
+
+ SynapseEnvironment synapseEnv = (SynapseEnvironment) synEnv.getValue();
+
+ /** Initializing autoscaleIn and autoscaleOut Mediators.**/
+
+ LoadBalancerConfiguration lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+ // check whether autoscaling is enabled
+ if (lbConfig.getLoadBalancerConfig().isAutoscaleEnabled()) {
+
+ // get the main sequence mediator
+ SequenceMediator mainSequence =
+ (SequenceMediator) synapseEnv.getSynapseConfiguration().getSequence("main");
+
+ // iterate through its child mediators
+ for (Mediator child : mainSequence.getList()) {
+
+ // find the InMediator
+ if (child instanceof InMediator) {
+ InMediator inSequence = (InMediator) child;
+
+ // if the first child of InMediator isn't an AutoscaleInMediator
+ if (!(inSequence.getList().get(0) instanceof AutoscaleInMediator)) {
+
+ // we gonna add it!
+ inSequence.getList().add(0, new AutoscaleInMediator());
+ if (log.isDebugEnabled()) {
+ log.debug("Added Mediator: " + inSequence.getChild(0) + "" +
+ " to InMediator. Number of child mediators in InMediator" + " is " +
+ inSequence.getList().size() + ".");
+ }
+ }
+
+ }
+
+ // find the OutMediator
+ if (child instanceof OutMediator) {
+
+ OutMediator outSequence = (OutMediator) child;
+
+ // if the first child of OutMediator isn't an AutoscaleOutMediator
+ if (!(outSequence.getList().get(0) instanceof AutoscaleOutMediator)) {
+
+ // we gonna add it!
+ outSequence.getList().add(0, new AutoscaleOutMediator());
+
+ if (log.isDebugEnabled()) {
+ log.debug("Added Mediator: " + outSequence.getChild(0) + "" +
+ " to OutMediator. Number of child mediators in OutMediator" +
+ " is " + outSequence.getList().size() + ".");
+ }
+
+ }
+ }
+ }
+
+ /** Initializing Autoscaler Task **/
+
+ BundleContext bundleContext = context.getBundleContext();
+ if (log.isDebugEnabled()) {
+ log.debug("Initiating Autoscaler task service component");
+ }
+
+ if (bundleContext.getServiceReference(TaskManagementService.class.getName()) != null) {
+ bundleContext.registerService(TaskManagementService.class.getName(),
+ new AutoscalerTaskMgmtAdminService(), null);
+ }
+
+
+ AutoscalerTaskInitializer listener = new AutoscalerTaskInitializer();
+
+ if (bundleContext.getServiceReference(Axis2ConfigurationContextObserver.class.getName()) != null) {
+ bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
+ listener, null);
+ }
+
+ if (configurationContext != null) {
+ TaskScheduler scheduler =
+ (TaskScheduler) configurationContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
+ if (scheduler == null) {
+ scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
+ scheduler.init(null);
+ configurationContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER,
+ scheduler);
+ } else if (!scheduler.isInitialized()) {
+ scheduler.init(null);
+ }
+ }
+
+ String autoscalerClass = lbConfig.getLoadBalancerConfig().getAutoscalerTaskClass();
+ Task task;
+ if (autoscalerClass != null) {
+ try {
+ task = (Task) Class.forName(autoscalerClass).newInstance();
+ } catch (Exception e) {
+ String msg = "Cannot instantiate Autoscaling Task. Class: " + autoscalerClass
+ +". It should implement 'org.apache.synapse.task.Task' and "
+ +"'org.apache.synapse.ManagedLifecycle' interfaces.";
+ log.error(msg, e);
+ throw new RuntimeException(msg, e);
+ }
+ } else {
+ task = new ServiceRequestsInFlightAutoscaler();
+ }
+
+// ServiceRequestsInFlightAutoscaler autoscalerTask =
+// new ServiceRequestsInFlightAutoscaler();
+
+ ((ManagedLifecycle) task).init(synapseEnv);
+
+ // specify scheduler task details
+ JobBuilder jobBuilder = JobBuilder.newJob(AutoscalingJob.class)
+ .withIdentity("autoscalerJob");
+ JobDetail job = jobBuilder.build();
+
+ Map<String, Object> dataMap = job.getJobDataMap();
+ dataMap.put(AutoscalingJob.AUTOSCALER_TASK, task);
+ dataMap.put(AutoscalingJob.SYNAPSE_ENVI, synapseEnv);
+
+ final TaskDescription taskDescription = new TaskDescription();
+ taskDescription.setTaskClass(ServiceRequestsInFlightAutoscaler.class.getName());
+ taskDescription.setName("autoscaler");
+ //taskDescription.setCount(SimpleTrigger.REPEAT_INDEFINITELY);
+
+ int interval = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerTaskInterval();
+ taskDescription.setInterval(interval);
+ taskDescription.setStartTime(new Date(System.currentTimeMillis() + (interval*2)));
+
+ TaskSchedulingManager scheduler = new TaskSchedulingManager();
+ scheduler.scheduleTask(taskDescription, dataMap, configurationContext);
+
+
+ } else {
+
+ log.info("Autoscaling is disabled.");
+ }
+ } catch (Throwable e) {
+ log.error("Failed to activate Autoscaler Task Service Component. ", e);
+ }
+ }
+
+
+ protected void deactivate(ComponentContext ctx) {
+ AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
+ if (log.isDebugEnabled()) {
+ log.debug("Autoscaler task bundle is deactivated");
+ }
+ }
+
+ protected void setCloudControllerService(CloudControllerService cc) {
+ AutoscalerTaskDSHolder.getInstance().setCloudControllerService(cc);
+ }
+
+ protected void unsetCloudControllerService(CloudControllerService cc) {
+ AutoscalerTaskDSHolder.getInstance().setCloudControllerService(null);
+ }
+
+ protected void setConfigurationContextService(ConfigurationContextService context) {
+ if (log.isDebugEnabled()) {
+ log.debug("ConfigurationContextService bound to the Autoscaler task initialization process");
+ }
+ this.configurationContext = context.getServerConfigContext();
+ AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(context);
+ }
+
+ protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
+ if (log.isDebugEnabled()) {
+ log.debug("ConfigurationContextService unbound from the Autoscaler task");
+ }
+ this.configurationContext = null;
+ AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
+ }
+
+ protected void setRealmService(RealmService realmService) {
+ if (log.isDebugEnabled()) {
+ log.debug("Bound realm service from the Autoscaler task");
+ }
+ AutoscalerTaskDSHolder.getInstance().setRealmService(realmService);
+ }
+
+ protected void unsetRealmService(RealmService realmService) {
+ if (log.isDebugEnabled()) {
+ log.debug("Unbound realm service from the Autoscaler task");
+ }
+ AutoscalerTaskDSHolder.getInstance().setRealmService(null);
+ }
+
+ protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+ AutoscalerTaskDSHolder.getInstance().setLbConfigService(lbConfigSer);
+ }
+
+ protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+ AutoscalerTaskDSHolder.getInstance().setLbConfigService(null);
+ }
+
+ protected void setRegistryService(RegistryService regService) {
+ if (log.isDebugEnabled()) {
+ log.debug("RegistryService bound to the endpoint component");
+ }
+ try {
+ AutoscalerTaskDSHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
+ AutoscalerTaskDSHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
+ } catch (RegistryException e) {
+ log.error("Couldn't retrieve the registry from the registry service");
+ }
+ }
+
+ protected void unsetRegistryService(RegistryService regService) {
+ if (log.isDebugEnabled()) {
+ log.debug("RegistryService unbound from the endpoint component");
+ }
+ AutoscalerTaskDSHolder.getInstance().setConfigRegistry(null);
+ }
+
+}
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/internal/RegistryManager.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/internal/RegistryManager.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
new file mode 100644
index 0000000..d29faae
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright WSO2 Inc.
+ *
+ * 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.internal;
+
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.util.DomainMapping;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+
+public class RegistryManager {
+ UserRegistry governanceRegistry = AutoscalerTaskDSHolder.getInstance().getGovernanceRegistry();
+ private static final Log log = LogFactory.getLog(RegistryManager.class);
+ /**
+ *
+ */
+ private Resource resource = null;
+ public static final String HOST_INFO = "hostinfo/";
+ public static final String ACTUAL_HOST = "actual.host";
+
+ public DomainMapping getMapping(String hostName) {
+ DomainMapping domainMapping;
+ try {
+ if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
+ resource = governanceRegistry.get(HOST_INFO + hostName);
+ domainMapping = new DomainMapping(hostName);
+ domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
+ return domainMapping;
+ }
+ } catch (RegistryException e) {
+ log.info("Error while getting registry resource");
+ throw new RuntimeException(e);
+ }
+ return null;
+ }
+}
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/mediators/AutoscaleInMediator.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/mediators/AutoscaleInMediator.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
new file mode 100644
index 0000000..153c2d3
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
@@ -0,0 +1,173 @@
+/*
+ * 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.mediators;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.internal.RegistryManager;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.http.protocol.HTTP;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.mediators.AbstractMediator;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.cache.URLMappingCache;
+import org.apache.stratos.lb.common.util.DomainMapping;
+
+import java.util.Map;
+
+/**
+ * This Synapse mediator generates a token per request received. These tokens are used for tracking
+ * the number of requests in flight. Once a response is received, the relevant token will be removed
+ * by the {@link AutoscaleOutMediator}
+ *
+ * @see AutoscaleOutMediator
+ */
+public class AutoscaleInMediator extends AbstractMediator implements ManagedLifecycle {
+
+ private LoadBalancerConfiguration lbConfig;
+ private Map<String, HostContext> hostCtxts;
+ /**
+ * keep the size of cache which used to keep hostNames of url mapping.
+ */
+ private URLMappingCache mappingCache;
+ private RegistryManager registryManager;
+ private int sizeOfCache;
+
+ public AutoscaleInMediator() {
+
+ this.lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+ hostCtxts = lbConfig.getHostContextMap();
+ sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
+ mappingCache = URLMappingCache.getInstance(sizeOfCache);
+ }
+
+ public boolean mediate(MessageContext synCtx) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Mediation started .......... " + AutoscaleInMediator.class.getName());
+
+ }
+
+ ConfigurationContext configCtx =
+ ((Axis2MessageContext) synCtx).getAxis2MessageContext()
+ .getConfigurationContext();
+ String uuid = org.apache.axiom.util.UIDGenerator.generateUID();
+ synCtx.setProperty(AutoscaleConstants.REQUEST_ID, uuid);
+
+ Map<String, Map<String, ?>> appDomainContexts =
+ AutoscaleUtil.getAppDomainContexts(configCtx,
+ lbConfig);
+ org.apache.axis2.context.MessageContext axis2MessageContext =
+ ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+ Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
+ getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+ String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
+
+ String toAddress = synCtx.getTo().getAddress();
+ if (targetHost.contains(":")) {
+ targetHost = targetHost.substring(0, targetHost.indexOf(':'));
+ }
+
+ int tenantId = AutoscaleUtil.getTenantId(synCtx.getTo().toString());
+
+ String domain = null, subDomain = null;
+
+ log.debug("************ Target Host: "+targetHost + " -- Tenant id : "+tenantId);
+
+ HostContext ctxt = hostCtxts.get(targetHost);
+
+ if (ctxt == null) {
+
+ DomainMapping domainMapping = mappingCache.getMapping(targetHost);
+ if (domainMapping == null) {
+ registryManager = new RegistryManager();
+ domainMapping = registryManager.getMapping(targetHost);
+ mappingCache.addValidMapping(targetHost, domainMapping);
+ }
+ if (domainMapping != null) {
+
+ String actualHost = domainMapping.getActualHost();
+
+ // get the HostContext from the actual host name in the case of domain
+ // mapping.
+ ctxt = hostCtxts.get(actualHost);
+
+ }
+ }
+
+ if (ctxt == null) {
+ log.debug("Host Context is null.");
+ // we don't need to do anything
+ return true;
+ }
+
+
+ // gets the corresponding domain
+ domain = ctxt.getDomainFromTenantId(tenantId);
+ synCtx.setProperty(AutoscaleConstants.TARGET_DOMAIN, domain);
+
+ // gets the corresponding sub domain
+ subDomain = ctxt.getSubDomainFromTenantId(tenantId);
+ synCtx.setProperty(AutoscaleConstants.TARGET_SUB_DOMAIN, subDomain);
+
+ if (appDomainContexts.get(domain) == null) {
+ // if we do not find a correct context, we just ignore
+ log.debug("AppDomainContext not found for domain " + domain);
+
+ } else {
+ AppDomainContext appDomainContext = (AppDomainContext) appDomainContexts.get(domain).get(subDomain);
+
+ if (appDomainContext != null) {
+ appDomainContext.addRequestToken(uuid);
+ System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
+
+ } else {
+ // if we do not find a correct context, we just ignore
+ log.debug("AppDomainContext not found for sub domain: " + subDomain +
+ " of domain: " + domain);
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void destroy() {
+
+ log.info("Mediator destroyed! " + AutoscaleInMediator.class.getName());
+ }
+
+ @Override
+ public void init(SynapseEnvironment arg0) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Mediator initialized! " + AutoscaleInMediator.class.getName());
+ }
+ }
+
+ private void throwException(String msg){
+ log.error(msg);
+ throw new RuntimeException(msg);
+ }
+}
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/mediators/AutoscaleOutMediator.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/mediators/AutoscaleOutMediator.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
new file mode 100644
index 0000000..8751af2
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
@@ -0,0 +1,77 @@
+/*
+ * 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.mediators;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.mediators.AbstractMediator;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+
+import java.util.Map;
+
+/**
+ * This Synapse mediator removes the request token generated by the {@link AutoscaleInMediator}
+ *
+ * @see AutoscaleInMediator
+ */
+public class AutoscaleOutMediator extends AbstractMediator implements ManagedLifecycle {
+
+ public boolean mediate(MessageContext synCtx) {
+
+ log.debug("Mediation started ....... " + AutoscaleOutMediator.class.getName());
+
+ ConfigurationContext configCtx =
+ ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
+
+ String domain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_DOMAIN);
+ // gets the corresponding sub domain
+ String subDomain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_SUB_DOMAIN);
+
+ String tokenId = (String) synCtx.getProperty(AutoscaleConstants.REQUEST_ID);
+ @SuppressWarnings("unchecked")
+ Map<String, Map<String, AppDomainContext>> appDomainContexts =
+ (Map<String, Map<String, AppDomainContext>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
+ AppDomainContext appDomainContext = null ;
+
+ if(appDomainContexts.get(domain) != null){
+ appDomainContext = appDomainContexts.get(domain).get(subDomain);
+ }
+
+ if (appDomainContext != null) {
+ appDomainContext.removeRequestToken(tokenId);
+ System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
+ } else {
+ log.debug("AppDomainContext not found for domain " + domain+" and sub domain : "+subDomain);
+ }
+ return true;
+ }
+
+ @Override
+ public void destroy() {
+ log.debug("Autoscale out mediator destroyed...");
+ }
+
+ @Override
+ public void init(SynapseEnvironment arg0) {
+ log.debug("Autoscale out mediator started...");
+ }
+}
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/state/check/PendingInstancesStateChecker.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/state/check/PendingInstancesStateChecker.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
new file mode 100644
index 0000000..7aea18c
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
@@ -0,0 +1,147 @@
+/*
+* 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.state.check;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class PendingInstancesStateChecker implements Runnable {
+
+ private static final Log log = LogFactory.getLog(PendingInstancesStateChecker.class);
+ private LoadBalancerContext groupCtxt = null;
+ private String domain;
+ private String subDomain;
+ private int expectedIncrementOfinstanceCount, originalRunningInstanceCount;
+ private CloudControllerClient ccClient;
+
+ public PendingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain,
+ int anexpectedInstanceCount, int currentCount, CloudControllerClient client) {
+ groupCtxt = ctxt;
+ domain = aDomain;
+ subDomain = aSubDomain;
+ expectedIncrementOfinstanceCount = anexpectedInstanceCount;
+ originalRunningInstanceCount = currentCount;
+ ccClient = client;
+ }
+
+ @Override
+ public void run() {
+
+ if (groupCtxt != null) {
+
+ int totalWaitedTime = 0;
+ int serverStartupDelay = AutoscalerTaskDSHolder
+ .getInstance()
+ .getWholeLoadBalancerConfig()
+ .getLoadBalancerConfig()
+ .getServerStartupDelay();
+
+ log.debug("Pending Instances State Checker has started for: " +
+ AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
+
+ // for each sub domain, get the clustering group management agent
+ GroupManagementAgent agent =
+ AutoscalerTaskDSHolder.getInstance().getAgent()
+ .getGroupManagementAgent(domain,
+ subDomain);
+ int startingRunningInstanceCount = agent.getMembers().size();
+
+ // we give some time for the server to get joined, we'll check time to time
+ // whether the instance has actually joined the ELB.
+ while ((agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) &&
+ totalWaitedTime < serverStartupDelay) {
+ int upToDateRunningInstanceCount = agent.getMembers().size();
+
+ log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+ " - Number of current running instances " +
+ upToDateRunningInstanceCount);
+
+ if (upToDateRunningInstanceCount > startingRunningInstanceCount) {
+ int newlyJoinedInstanceCount = upToDateRunningInstanceCount - startingRunningInstanceCount;
+ // set new running instance count
+ groupCtxt.setRunningInstanceCount(upToDateRunningInstanceCount);
+ // decrement the pending instance count
+ groupCtxt.decrementPendingInstancesIfNotZero(newlyJoinedInstanceCount);
+ // update the starting running instance count
+ startingRunningInstanceCount = upToDateRunningInstanceCount;
+
+ log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+ " - Instances newly joined: " +
+ newlyJoinedInstanceCount);
+ }
+
+ try {
+ Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+ } catch (InterruptedException ignore) {
+ }
+
+ totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+ }
+
+ log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
+ totalWaitedTime +
+ " (milliseconds) till pending members get joined.");
+
+ if (agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) {
+
+ int instanceCountFailedToJoin =
+ originalRunningInstanceCount + expectedIncrementOfinstanceCount - agent.getMembers().size();
+ log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+ "Instances that are failed to join: " +
+ instanceCountFailedToJoin);
+
+ // to avoid an infinite loop
+ int retries = instanceCountFailedToJoin + 2;
+
+ while (instanceCountFailedToJoin > 0 && retries > 0) {
+ // instances spawned haven't joined ELB, so we assume that instance is
+ // corrupted.
+ // hence, we ask CC to terminate it.
+ try {
+ log.debug("Terminating lastly spwaned instance of " +
+ AutoscaleUtil.domainSubDomainString(domain, subDomain));
+ ccClient.terminateLastlySpawnedInstance(domain, subDomain);
+ instanceCountFailedToJoin--;
+ // decrement pending count
+ groupCtxt.decrementPendingInstancesIfNotZero(1);
+ } catch (Exception e) {
+ log
+ .error(
+ "Instance termination failed for " +
+ AutoscaleUtil.domainSubDomainString(domain, subDomain),
+ e);
+ } finally {
+ retries--;
+ }
+ }
+
+ // decrement pending count
+ groupCtxt.decrementPendingInstancesIfNotZero(instanceCountFailedToJoin);
+ }
+
+ }
+
+ }
+
+}
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/state/check/TerminatingInstancesStateChecker.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/state/check/TerminatingInstancesStateChecker.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
new file mode 100644
index 0000000..ce2fc29
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
@@ -0,0 +1,88 @@
+/*
+* 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.state.check;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class TerminatingInstancesStateChecker implements Runnable {
+
+ private static final Log log = LogFactory.getLog(TerminatingInstancesStateChecker.class);
+ private LoadBalancerContext groupCtxt = null;
+ private String domain;
+ private String subDomain;
+
+ public TerminatingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain) {
+ groupCtxt = ctxt;
+ domain = aDomain;
+ subDomain = aSubDomain;
+ }
+
+ @Override
+ public void run() {
+
+ if (groupCtxt != null) {
+
+ groupCtxt.incrementTerminatingInstances(1);
+
+ int totalWaitedTime = 0;
+ int serverStartupDelay = AutoscalerTaskDSHolder
+ .getInstance()
+ .getWholeLoadBalancerConfig()
+ .getLoadBalancerConfig()
+ .getServerStartupDelay();
+ log.info("Terminating Instances State Checker has started for: " +
+ AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
+
+ // for each sub domain, get the clustering group management agent
+ GroupManagementAgent agent =
+ AutoscalerTaskDSHolder.getInstance().getAgent()
+ .getGroupManagementAgent(domain,
+ subDomain);
+
+ int startingRunningInstanceCount = agent.getMembers().size();
+
+ // 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() == startingRunningInstanceCount &&
+ totalWaitedTime < serverStartupDelay) {
+
+ try {
+ Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+ } catch (InterruptedException ignore) {
+ }
+
+ totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+ }
+
+ log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
+ totalWaitedTime +
+ " (milliseconds) till terminating member left the cluster.");
+
+ // we recalculate number of alive instances
+ groupCtxt.decrementTerminatingInstancesIfNotZero(1);
+ }
+
+ }
+
+}
[06/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
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-service-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
new file mode 100644
index 0000000..7332d38
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
@@ -0,0 +1,108 @@
+<?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.autoscale.lbautoscale.ServiceRequestsInFlightAutoscaler"
+ name="LoadAnalyzer">
+
+ <!--
+ The private key for ec2
+ -->
+ <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+ <!--
+ The certificate for ec2
+ -->
+ <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+ <!--
+ The key pair
+ -->
+ <property name="sshKey" value="stratos-1.0.0-keypair"/>
+
+ <property name="loadBalancer">
+ <loadBalancer>
+ <property name="securityGroup" value="stratos-appserver-lb"/>
+ <property name="instanceType" value="m1.large"/>
+ <property name="instances" value="1"/>
+ <property name="elasticIP" value="${ELASTIC_IP}"/>
+ <property name="availabilityZone" value="us-east-1c"/>
+ <property name="payload" value="/mnt/payload.zip"/>
+ </loadBalancer>
+ </property>
+
+ <property name="services">
+ <services>
+ <defaults>
+ <property name="payload" value="resources/cluster_node.zip"/>
+ <property name="availabilityZone" value="us-east-1c"/>
+ <property name="securityGroup" value="as-2011-02-23"/>
+ <property name="instanceType" value="m1.large"/>
+ <property name="minAppInstances" value="1"/>
+ <property name="maxAppInstances" value="5"/>
+ <property name="queueLengthPerNode" value="400"/>
+ <property name="roundsToAverage" value="10"/>
+ <property name="instancesPerScaleUp" value="1"/>
+ <property name="messageExpiryTime" value="60000"/>
+ </defaults>
+ <service domain="wso2.as.domain">
+ <property name="payload" value="resources/cluster_node.zip"/>
+ <property name="availabilityZone" value="us-east-1c"/>
+ </service>
+ <service domain="wso2.ds.domain">
+ <property name="payload" value="resources/cluster_node.zip"/>
+ <property name="minAppInstances" value="1"/>
+ <property name="maxAppInstances" value="5"/>
+ <property name="queueLengthPerNode" value="400"/>
+ <property name="roundsToAverage" value="10"/>
+ <property name="instancesPerScaleUp" value="1"/>
+ <property name="availabilityZone" value="us-east-1c"/>
+ <property name="securityGroup" value="ds-2011-02-23"/>
+ </service>
+ <service domain="wso2.bps.domain">
+ <property name="payload" value="resources/cluster_node.zip"/>
+ <property name="minAppInstances" value="1"/>
+ <property name="maxAppInstances" value="5"/>
+ <property name="queueLengthPerNode" value="400"/>
+ <property name="roundsToAverage" value="10"/>
+ <property name="instancesPerScaleUp" value="1"/>
+ <property name="availabilityZone" value="us-east-1c"/>
+ <property name="securityGroup" value="bps-2011-02-23"/>
+ </service>
+ </services>
+ </property>
+
+ <!--
+ 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/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
new file mode 100644
index 0000000..2e6cb4a
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
@@ -0,0 +1,104 @@
+/*
+* 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;
+
+import java.io.File;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+public class AppDomainContextsTest extends TestCase {
+
+ private static Map<String, Map<String, ?>> map;
+ private LoadBalancerConfiguration lbConfig;
+ ConfigurationContext configCtx;
+ ClusteringAgent clusteringAgent;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ configCtx = ConfigurationContextFactory.createEmptyConfigurationContext();
+ clusteringAgent = new TribesClusteringAgent();
+ clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+ "worker"),
+ "wso2.as1.domain", "worker", -1);
+ clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+ "mgt"),
+ "wso2.as1.domain", "mgt", -1);
+ clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+ "mgt"),
+ "wso2.as2.domain", "mgt", -1);
+ configCtx.getAxisConfiguration().setClusteringAgent(clusteringAgent);
+
+ File f = new File("src/test/resources/loadbalancer.conf");
+ System.setProperty("loadbalancer.conf", f.getAbsolutePath());
+ lbConfig = LoadBalancerConfiguration.getInstance();
+
+ map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+
+ }
+
+
+ public void testRemoval(){
+ // removing a cluster domain with only 1 sub domain
+ lbConfig.removeServiceConfiguration("wso2.as2.domain", "mgt");
+ map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+
+ Assert.assertEquals(true, !map.containsKey("wso2.as2.domain"));
+
+ // removing a cluster domain with more than 1 sub domain
+ lbConfig.removeServiceConfiguration("wso2.as1.domain", "mgt");
+ map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+
+ Assert.assertEquals(true, map.containsKey("wso2.as1.domain"));
+ Assert.assertEquals(true, map.get("wso2.as1.domain").get("mgt") == null);
+ Assert.assertEquals(true, map.get("wso2.as1.domain").get("worker") != null);
+ }
+
+ public void testAddition(){
+ ServiceConfiguration config1 = lbConfig.new ServiceConfiguration();
+ config1.setDomain("wso2.as3.domain");
+ config1.setSub_domain("mgt");
+ lbConfig.addServiceConfiguration(config1);
+ clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+ "mgt"),
+ "wso2.as3.domain", "mgt", -1);
+ map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+
+ Assert.assertEquals(true, map.containsKey("wso2.as3.domain"));
+ Assert.assertEquals(true, map.get("wso2.as3.domain").get("mgt") != null);
+ }
+
+ @Deprecated // use only for writing test cases
+ void printKeys(Map<?,?> map){
+ for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
+ Object type = iterator.next();
+ System.out.println(type);
+ }
+ }
+}
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/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
new file mode 100644
index 0000000..7b2a80a
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
@@ -0,0 +1,50 @@
+loadbalancer {
+ instances 1;
+ enable_autoscaler true;
+ # interval between two task executions in milliseconds
+ autoscaler_task_interval 5000;
+ # after an instance booted up, task will wait till this much of time and let the server started up
+ server_startup_delay 15000; #default will be 60000ms
+}
+
+services {
+ defaults {
+ min_app_instances 1;
+ max_app_instances 5;
+ max_requests_per_second 400;
+ alarming_upper_rate 0.65;
+ alarming_lower_rate 0.2;
+ scale_down_factor 0.25;
+ rounds_to_average 10;
+ instances_per_scale_up 1;
+ message_expiry_time 60000;
+ }
+
+ appserver {
+ hosts appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+ sub_domain worker1;
+ domains {
+ wso2.as1.domain {
+ hosts as1.cloud-test.wso2.com;
+ min_app_instances 0;
+ sub_domain worker;
+ tenant_range 1-5;
+ }
+ wso2.as1.domain {
+ hosts mgt.as1.cloud-test.wso2.com;
+ min_app_instances 0;
+ sub_domain mgt;
+ tenant_range 1-5;
+ }
+ wso2.as2.domain {
+ hosts mgt.as2.cloud-test.wso2.com;
+ min_app_instances 0;
+ sub_domain mgt;
+ tenant_range 1-5;
+ }
+
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml
deleted file mode 100644
index 842f4cf..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml
+++ /dev/null
@@ -1,133 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (c) 2009-2010, 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.
--->
-
-
-<!--
-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.wso2.carbon</groupId>
- <artifactId>loadbalancer-components</artifactId>
- <version>4.1.0</version>
- <relativePath>../../../pom.xml</relativePath>
- </parent>
-
- <version>4.1.3</version>
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.mediator.autoscale</artifactId>
- <packaging>bundle</packaging>
- <name>WSO2 Carbon - Autoscale Mediator BE</name>
- <url>http://wso2.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.wso2.carbon.mediator.autoscale.lbautoscale.internal,
- org.wso2.carbon.mediator.autoscale.*
- </Export-Package>
- <Private-Package>org.wso2.carbon.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.wso2.carbon.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>2.1.1-wso2v4</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.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.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/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
deleted file mode 100644
index 4f21a85..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.callables;
-
-import java.util.concurrent.Callable;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-/** 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/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
deleted file mode 100644
index f30ab9a..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.callables;
-
-import java.util.concurrent.Callable;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.state.check.TerminatingInstancesStateChecker;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-/** 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/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
deleted file mode 100644
index 580db58..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.callables;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-
-/** 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/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
deleted file mode 100644
index bf3f336..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.callables;
-
-import java.util.concurrent.Callable;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-
-/** 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/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
deleted file mode 100644
index 7f151fb..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.callables;
-
-import java.util.concurrent.Callable;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-/** 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/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
deleted file mode 100644
index 8ca9764..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
-* 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.wso2.carbon.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/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
deleted file mode 100644
index e05c809..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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.wso2.carbon.mediator.autoscale.lbautoscale.clients;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-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();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
deleted file mode 100644
index 09feb78..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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.wso2.carbon.mediator.autoscale.lbautoscale.clients;
-
-import org.apache.axis2.AxisFault;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.wso2.carbon.stratos.cloud.controller.stub.CloudControllerServiceStub;
-
-/**
- * This is the client class this calls Autoscaler service.
- */
-public class CloudControllerStubClient extends CloudControllerClient {
-
- private CloudControllerServiceStub stub;
- private static final String CLOUD_CONTROLLER_EPR = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerServiceEpr();
-
- private static final Log log = LogFactory.getLog(CloudControllerStubClient.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 stub.startInstance(domainName, subDomainName);
- }
-
- public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
-
- return stub.terminateInstance(domainName, subDomainName);
- }
-
- public boolean
- terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
-
- return stub.terminateLastlySpawnedInstance(domainName, subDomainName);
- }
-
- public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
-
- return stub.getPendingInstanceCount(domainName, subDomainName);
- }
-
- @Override
- public void init() {
-
- try {
-
- stub = new CloudControllerServiceStub(CLOUD_CONTROLLER_EPR);
- stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
-
- } catch (AxisFault axisFault) {
- String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
- log.error(msg, axisFault);
- throw new RuntimeException(msg, axisFault);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java
deleted file mode 100644
index add198e..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.context;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-
-
-/**
- * Contextual information related to autoscaling for a particular clustering domain
- */
-public class AppDomainContext extends LoadBalancerContext{
-
- private static final long serialVersionUID = 6582721801663800609L;
-
- private static final Log log = LogFactory.getLog(AppDomainContext.class);
-
- /**
- * Request tokens of requests in flight
- * <p/>
- * Key - request token ID, Value - message received time
- */
- private Map<String, Long> requestTokens = new ConcurrentHashMap<String, Long>();
- private List<Integer> requestTokenListLengths;
- private LoadBalancerConfiguration.ServiceConfiguration serviceConfig;
-
- public AppDomainContext(LoadBalancerConfiguration.ServiceConfiguration serviceConfig) {
- this.serviceConfig = serviceConfig;
- requestTokenListLengths = new Vector<Integer>(serviceConfig.getRoundsToAverage());
- }
-
- public LoadBalancerConfiguration.ServiceConfiguration getServiceConfig() {
- return serviceConfig;
- }
-
- /**
- * If there is insufficient number of messages we cannot make a scaling decision.
- *
- * @return true - if a scaling decision can be made
- */
- public boolean canMakeScalingDecision() {
- return requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage();
- }
-
- public void addRequestToken(String tokenId) {
- requestTokens.put(tokenId, System.currentTimeMillis());
- if (log.isDebugEnabled()) {
- log.debug("Request Tokens Added : "+requestTokens.size());
- }
- }
-
- public void removeRequestToken(String tokenId) {
- requestTokens.remove(tokenId);
- }
-
-// public int getRunningInstanceCount() {
-// return super.getRunningInstanceCount();
-// }
-
- /**
- * This will set the running instance count for this app domain
- * and also will return the difference of current running instance count and previous count.
- * @param runningInstanceCount current running instance count
- * @return difference of current running instance count and previous count.
- */
-// public int setRunningInstanceCount(int runningInstanceCount) {
-// int diff = 0;
-//
-// if(this.runningInstanceCount < runningInstanceCount){
-// diff = runningInstanceCount - this.runningInstanceCount;
-// }
-//
-// this.runningInstanceCount = runningInstanceCount;
-//
-// return diff;
-// }
-
- public void expireRequestTokens() {
- for (Map.Entry<String, Long> entry : requestTokens.entrySet()) {
- if (System.currentTimeMillis() - entry.getValue() >= serviceConfig.getMessageExpiryTime()) {
- requestTokens.remove(entry.getKey());
- if (log.isDebugEnabled()) {
- log.debug("Request Tokens Expired : " + requestTokens.get(entry.getKey()));
- }
- }
- }
- }
-
- public void recordRequestTokenListLength() {
- if (requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage()) {
- int count = requestTokenListLengths.remove(0);
- if (log.isDebugEnabled()) {
- log.debug("Request Tokens Removed : " + count);
- }
- }
- if (log.isDebugEnabled()) {
- log.debug("Request Tokens Added : " + requestTokens.size());
- }
- requestTokenListLengths.add(requestTokens.size());
- }
-
-
-// public synchronized int getPendingInstances() {
-// return pendingInstances;
-// }
-
-// public synchronized void incrementPendingInstances() {
-// this.pendingInstances++;
-// }
-
-// public synchronized void decrementPendingInstancesIfNotZero(int diff) {
-//
-// while (diff > 0 && this.pendingInstances > 0 ){
-// this.pendingInstances--;
-// diff--;
-// }
-//
-// }
-
-// public synchronized int getInstances() {
-// return runningInstanceCount + pendingInstances;
-// }
-
- /**
- * Get the average requests in flight, averaged over the number of of observations rounds
- *
- * @return number of average requests in flight. -1 if there no requests were received
- */
- public long getAverageRequestsInFlight() {
- long total = 0;
- for (Integer messageQueueLength : requestTokenListLengths) {
- total += messageQueueLength;
- }
- int size = requestTokenListLengths.size();
- if (size == 0) {
- return -1; // -1 means that no requests have been received
- }
-
- if (log.isDebugEnabled()) {
- log.debug("Total Tokens : "+total+ " : Size: "+size);
- }
- return (long) total / size;
- }
-
-
-// public synchronized void resetRunningPendingInstances() {
-// pendingInstances = 0;
-// runningInstanceCount = 0;
-// }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
deleted file mode 100644
index d7f7993..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.context;
-
-import java.io.Serializable;
-
-/**
- * Contextual information related to autoscaling for a particular domain
- */
-public class LoadBalancerContext implements Serializable{
-
- private static final long serialVersionUID = -2022110665957598060L;
- private int runningInstances;
- private int pendingInstances;
- private int terminatingInstances;
-
- public synchronized int getTerminatingInstanceCount() {
- return terminatingInstances;
- }
-
- public synchronized int getRunningInstanceCount() {
- return runningInstances;
- }
-
- public synchronized int getPendingInstanceCount() {
- return pendingInstances;
- }
-
- /**
- * This will set the running instance count for a domain
- * and also will return the difference of current running instance count and previous count.
- * @param runningInstanceCount current running instance count
- * @return difference of current running instance count and previous count.
- */
- public synchronized int setRunningInstanceCount(int count) {
- int diff = 0;
-
- if (this.runningInstances < count) {
- diff = count - this.runningInstances;
- }
-
- this.runningInstances = count;
-
- return diff;
- }
-
- public synchronized int getInstances() {
- return runningInstances + pendingInstances;
- }
-
- public synchronized void setPendingInstanceCount(int count) {
-
- this.pendingInstances = count;
- }
-
- public synchronized void setTerminatingInstanceCount(int count) {
-
- this.terminatingInstances = count;
- }
-
- public synchronized void incrementPendingInstances(int diff) {
-
- this.pendingInstances += diff;
- }
-
- public synchronized void incrementTerminatingInstances(int diff) {
-
- this.terminatingInstances += diff;
- }
-
- public synchronized void decrementPendingInstancesIfNotZero(int diff) {
-
- while (diff > 0 && this.pendingInstances > 0) {
- this.pendingInstances--;
- diff--;
- }
-
- }
-
- public synchronized void decrementTerminatingInstancesIfNotZero(int diff) {
-
- while (diff > 0 && this.terminatingInstances > 0) {
- this.terminatingInstances--;
- diff--;
- }
-
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
deleted file mode 100644
index eec09fa..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
+++ /dev/null
@@ -1,328 +0,0 @@
-/*
- * 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.wso2.carbon.mediator.autoscale.lbautoscale.internal;
-
-import java.util.Date;
-import java.util.Map;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.description.Parameter;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.Mediator;
-import org.apache.synapse.SynapseConstants;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.mediators.base.SequenceMediator;
-import org.apache.synapse.mediators.filters.InMediator;
-import org.apache.synapse.mediators.filters.OutMediator;
-import org.apache.synapse.task.Task;
-import org.apache.synapse.task.TaskConstants;
-import org.apache.synapse.task.TaskDescription;
-import org.apache.synapse.task.TaskScheduler;
-import org.apache.synapse.task.service.TaskManagementService;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.quartz.JobBuilder;
-import org.quartz.JobDetail;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.mediators.AutoscaleInMediator;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.mediators.AutoscaleOutMediator;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.task.AutoscalerTaskInitializer;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.task.AutoscalerTaskMgmtAdminService;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.task.AutoscalingJob;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.task.ServiceRequestsInFlightAutoscaler;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.task.TaskSchedulingManager;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-/**
- * @scr.component name="autoscaler.task.component" immediate="true"
- * @scr.reference name="carbon.core.configurationContextService"
- * interface="org.wso2.carbon.utils.ConfigurationContextService"
- * cardinality="1..1" policy="dynamic"
- * bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
- * @scr.reference name="user.realmservice.default"
- * interface="org.wso2.carbon.user.core.service.RealmService"
- * cardinality="1..1" policy="dynamic" bind="setRealmService"
- * unbind="unsetRealmService"
- * @scr.reference name="org.wso2.carbon.lb.common"
- * interface="org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService"
- * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
- * unbind="unsetLoadBalancerConfigurationService"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService"
- * cardinality="1..1" policy="dynamic"
- * bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="org.wso2.carbon.stratos.cloud.controller"
- * interface="org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService"
- * cardinality="1..1" policy="dynamic" bind="setCloudControllerService"
- * unbind="unsetCloudControllerService"
- */
-public class AutoscalerTaskServiceComponent {
-
- private static final Log log = LogFactory.getLog(AutoscalerTaskServiceComponent.class);
- private ConfigurationContext configurationContext = null;
-
- protected void activate(ComponentContext context) {
-
- try{
-
- // read config file
-// String configURL = System.getProperty(AutoscaleConstants.LOAD_BALANCER_CONFIG);
-// LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration();
-// lbConfig.init(configURL);
-
- if(configurationContext == null){
- String msg = "Configuration context is null. Autoscaler task activation failed.";
- log.fatal(msg);
- throw new RuntimeException(msg);
- }
-
- // load synapse environment
- Parameter synEnv =
- configurationContext.getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
-
- if (synEnv == null || synEnv.getValue() == null ||
- !(synEnv.getValue() instanceof SynapseEnvironment)) {
-
- String message = "Unable to initialize the Synapse Configuration : Can not find the ";
- log.fatal(message + "Synapse Environment");
- throw new SynapseException(message + "Synapse Environment");
- }
-
- SynapseEnvironment synapseEnv = (SynapseEnvironment) synEnv.getValue();
-
- /** Initializing autoscaleIn and autoscaleOut Mediators.**/
-
- LoadBalancerConfiguration lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
- // check whether autoscaling is enabled
- if (lbConfig.getLoadBalancerConfig().isAutoscaleEnabled()) {
-
- // get the main sequence mediator
- SequenceMediator mainSequence =
- (SequenceMediator) synapseEnv.getSynapseConfiguration().getSequence("main");
-
- // iterate through its child mediators
- for (Mediator child : mainSequence.getList()) {
-
- // find the InMediator
- if (child instanceof InMediator) {
- InMediator inSequence = (InMediator) child;
-
- // if the first child of InMediator isn't an AutoscaleInMediator
- if (!(inSequence.getList().get(0) instanceof AutoscaleInMediator)) {
-
- // we gonna add it!
- inSequence.getList().add(0, new AutoscaleInMediator());
- if (log.isDebugEnabled()) {
- log.debug("Added Mediator: " + inSequence.getChild(0) + "" +
- " to InMediator. Number of child mediators in InMediator" + " is " +
- inSequence.getList().size() + ".");
- }
- }
-
- }
-
- // find the OutMediator
- if (child instanceof OutMediator) {
-
- OutMediator outSequence = (OutMediator) child;
-
- // if the first child of OutMediator isn't an AutoscaleOutMediator
- if (!(outSequence.getList().get(0) instanceof AutoscaleOutMediator)) {
-
- // we gonna add it!
- outSequence.getList().add(0, new AutoscaleOutMediator());
-
- if (log.isDebugEnabled()) {
- log.debug("Added Mediator: " + outSequence.getChild(0) + "" +
- " to OutMediator. Number of child mediators in OutMediator" +
- " is " + outSequence.getList().size() + ".");
- }
-
- }
- }
- }
-
- /** Initializing Autoscaler Task **/
-
- BundleContext bundleContext = context.getBundleContext();
- if (log.isDebugEnabled()) {
- log.debug("Initiating Autoscaler task service component");
- }
-
- if (bundleContext.getServiceReference(TaskManagementService.class.getName()) != null) {
- bundleContext.registerService(TaskManagementService.class.getName(),
- new AutoscalerTaskMgmtAdminService(), null);
- }
-
-
- AutoscalerTaskInitializer listener = new AutoscalerTaskInitializer();
-
- if (bundleContext.getServiceReference(Axis2ConfigurationContextObserver.class.getName()) != null) {
- bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
- listener, null);
- }
-
- if (configurationContext != null) {
- TaskScheduler scheduler =
- (TaskScheduler) configurationContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
- if (scheduler == null) {
- scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
- scheduler.init(null);
- configurationContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER,
- scheduler);
- } else if (!scheduler.isInitialized()) {
- scheduler.init(null);
- }
- }
-
- String autoscalerClass = lbConfig.getLoadBalancerConfig().getAutoscalerTaskClass();
- Task task;
- if (autoscalerClass != null) {
- try {
- task = (Task) Class.forName(autoscalerClass).newInstance();
- } catch (Exception e) {
- String msg = "Cannot instantiate Autoscaling Task. Class: " + autoscalerClass
- +". It should implement 'org.apache.synapse.task.Task' and "
- +"'org.apache.synapse.ManagedLifecycle' interfaces.";
- log.error(msg, e);
- throw new RuntimeException(msg, e);
- }
- } else {
- task = new ServiceRequestsInFlightAutoscaler();
- }
-
-// ServiceRequestsInFlightAutoscaler autoscalerTask =
-// new ServiceRequestsInFlightAutoscaler();
-
- ((ManagedLifecycle) task).init(synapseEnv);
-
- // specify scheduler task details
- JobBuilder jobBuilder = JobBuilder.newJob(AutoscalingJob.class)
- .withIdentity("autoscalerJob");
- JobDetail job = jobBuilder.build();
-
- Map<String, Object> dataMap = job.getJobDataMap();
- dataMap.put(AutoscalingJob.AUTOSCALER_TASK, task);
- dataMap.put(AutoscalingJob.SYNAPSE_ENVI, synapseEnv);
-
- final TaskDescription taskDescription = new TaskDescription();
- taskDescription.setTaskClass(ServiceRequestsInFlightAutoscaler.class.getName());
- taskDescription.setName("autoscaler");
- //taskDescription.setCount(SimpleTrigger.REPEAT_INDEFINITELY);
-
- int interval = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerTaskInterval();
- taskDescription.setInterval(interval);
- taskDescription.setStartTime(new Date(System.currentTimeMillis() + (interval*2)));
-
- TaskSchedulingManager scheduler = new TaskSchedulingManager();
- scheduler.scheduleTask(taskDescription, dataMap, configurationContext);
-
-
- } else {
-
- log.info("Autoscaling is disabled.");
- }
- } catch (Throwable e) {
- log.error("Failed to activate Autoscaler Task Service Component. ", e);
- }
- }
-
-
- protected void deactivate(ComponentContext ctx) {
- AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
- if (log.isDebugEnabled()) {
- log.debug("Autoscaler task bundle is deactivated");
- }
- }
-
- protected void setCloudControllerService(CloudControllerService cc) {
- AutoscalerTaskDSHolder.getInstance().setCloudControllerService(cc);
- }
-
- protected void unsetCloudControllerService(CloudControllerService cc) {
- AutoscalerTaskDSHolder.getInstance().setCloudControllerService(null);
- }
-
- protected void setConfigurationContextService(ConfigurationContextService context) {
- if (log.isDebugEnabled()) {
- log.debug("ConfigurationContextService bound to the Autoscaler task initialization process");
- }
- this.configurationContext = context.getServerConfigContext();
- AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(context);
- }
-
- protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
- if (log.isDebugEnabled()) {
- log.debug("ConfigurationContextService unbound from the Autoscaler task");
- }
- this.configurationContext = null;
- AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
- }
-
- protected void setRealmService(RealmService realmService) {
- if (log.isDebugEnabled()) {
- log.debug("Bound realm service from the Autoscaler task");
- }
- AutoscalerTaskDSHolder.getInstance().setRealmService(realmService);
- }
-
- protected void unsetRealmService(RealmService realmService) {
- if (log.isDebugEnabled()) {
- log.debug("Unbound realm service from the Autoscaler task");
- }
- AutoscalerTaskDSHolder.getInstance().setRealmService(null);
- }
-
- protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
- AutoscalerTaskDSHolder.getInstance().setLbConfigService(lbConfigSer);
- }
-
- protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
- AutoscalerTaskDSHolder.getInstance().setLbConfigService(null);
- }
-
- protected void setRegistryService(RegistryService regService) {
- if (log.isDebugEnabled()) {
- log.debug("RegistryService bound to the endpoint component");
- }
- try {
- AutoscalerTaskDSHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
- AutoscalerTaskDSHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
- } catch (RegistryException e) {
- log.error("Couldn't retrieve the registry from the registry service");
- }
- }
-
- protected void unsetRegistryService(RegistryService regService) {
- if (log.isDebugEnabled()) {
- log.debug("RegistryService unbound from the endpoint component");
- }
- AutoscalerTaskDSHolder.getInstance().setConfigRegistry(null);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java
deleted file mode 100644
index 8442bcc..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright WSO2 Inc.
- *
- * 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.wso2.carbon.mediator.autoscale.lbautoscale.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.wso2.carbon.lb.common.util.DomainMapping;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-
-public class RegistryManager {
- UserRegistry governanceRegistry = AutoscalerTaskDSHolder.getInstance().getGovernanceRegistry();
- private static final Log log = LogFactory.getLog(RegistryManager.class);
- /**
- *
- */
- private Resource resource = null;
- public static final String HOST_INFO = "hostinfo/";
- public static final String ACTUAL_HOST = "actual.host";
-
- public DomainMapping getMapping(String hostName) {
- DomainMapping domainMapping;
- try {
- if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
- resource = governanceRegistry.get(HOST_INFO + hostName);
- domainMapping = new DomainMapping(hostName);
- domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
- return domainMapping;
- }
- } catch (RegistryException e) {
- log.info("Error while getting registry resource");
- throw new RuntimeException(e);
- }
- return null;
- }
-}
[05/10] committing org.apache.stratos.mediator.autoscale
Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
deleted file mode 100644
index ea0138a..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * 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.wso2.carbon.mediator.autoscale.lbautoscale.mediators;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.http.protocol.HTTP;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.mediators.AbstractMediator;
-import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.lb.common.conf.util.HostContext;
-import org.wso2.carbon.lb.common.cache.URLMappingCache;
-import org.wso2.carbon.lb.common.util.DomainMapping;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.internal.RegistryManager;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-import java.util.Map;
-
-/**
- * This Synapse mediator generates a token per request received. These tokens are used for tracking
- * the number of requests in flight. Once a response is received, the relevant token will be removed
- * by the {@link AutoscaleOutMediator}
- *
- * @see AutoscaleOutMediator
- */
-public class AutoscaleInMediator extends AbstractMediator implements ManagedLifecycle {
-
- private LoadBalancerConfiguration lbConfig;
- private Map<String, HostContext> hostCtxts;
- /**
- * keep the size of cache which used to keep hostNames of url mapping.
- */
- private URLMappingCache mappingCache;
- private RegistryManager registryManager;
- private int sizeOfCache;
-
- public AutoscaleInMediator() {
-
- this.lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
- hostCtxts = lbConfig.getHostContextMap();
- sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
- mappingCache = URLMappingCache.getInstance(sizeOfCache);
- }
-
- public boolean mediate(MessageContext synCtx) {
-
- if (log.isDebugEnabled()) {
- log.debug("Mediation started .......... " + AutoscaleInMediator.class.getName());
-
- }
-
- ConfigurationContext configCtx =
- ((Axis2MessageContext) synCtx).getAxis2MessageContext()
- .getConfigurationContext();
- String uuid = org.apache.axiom.util.UIDGenerator.generateUID();
- synCtx.setProperty(AutoscaleConstants.REQUEST_ID, uuid);
-
- Map<String, Map<String, ?>> appDomainContexts =
- AutoscaleUtil.getAppDomainContexts(configCtx,
- lbConfig);
- org.apache.axis2.context.MessageContext axis2MessageContext =
- ((Axis2MessageContext) synCtx).getAxis2MessageContext();
- Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
- getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
- String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
-
- String toAddress = synCtx.getTo().getAddress();
- if (targetHost.contains(":")) {
- targetHost = targetHost.substring(0, targetHost.indexOf(':'));
- }
-
- int tenantId = AutoscaleUtil.getTenantId(synCtx.getTo().toString());
-
- String domain = null, subDomain = null;
-
- log.debug("************ Target Host: "+targetHost + " -- Tenant id : "+tenantId);
-
- HostContext ctxt = hostCtxts.get(targetHost);
-
- if (ctxt == null) {
-
- DomainMapping domainMapping = mappingCache.getMapping(targetHost);
- if (domainMapping == null) {
- registryManager = new RegistryManager();
- domainMapping = registryManager.getMapping(targetHost);
- mappingCache.addValidMapping(targetHost, domainMapping);
- }
- if (domainMapping != null) {
-
- String actualHost = domainMapping.getActualHost();
-
- // get the HostContext from the actual host name in the case of domain
- // mapping.
- ctxt = hostCtxts.get(actualHost);
-
- }
- }
-
- if (ctxt == null) {
- log.debug("Host Context is null.");
- // we don't need to do anything
- return true;
- }
-
-
- // gets the corresponding domain
- domain = ctxt.getDomainFromTenantId(tenantId);
- synCtx.setProperty(AutoscaleConstants.TARGET_DOMAIN, domain);
-
- // gets the corresponding sub domain
- subDomain = ctxt.getSubDomainFromTenantId(tenantId);
- synCtx.setProperty(AutoscaleConstants.TARGET_SUB_DOMAIN, subDomain);
-
- if (appDomainContexts.get(domain) == null) {
- // if we do not find a correct context, we just ignore
- log.debug("AppDomainContext not found for domain " + domain);
-
- } else {
- AppDomainContext appDomainContext = (AppDomainContext) appDomainContexts.get(domain).get(subDomain);
-
- if (appDomainContext != null) {
- appDomainContext.addRequestToken(uuid);
- System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
-
- } else {
- // if we do not find a correct context, we just ignore
- log.debug("AppDomainContext not found for sub domain: " + subDomain +
- " of domain: " + domain);
- }
- }
-
- return true;
- }
-
- @Override
- public void destroy() {
-
- log.info("Mediator destroyed! " + AutoscaleInMediator.class.getName());
- }
-
- @Override
- public void init(SynapseEnvironment arg0) {
-
- if (log.isDebugEnabled()) {
- log.debug("Mediator initialized! " + AutoscaleInMediator.class.getName());
- }
- }
-
- private void throwException(String msg){
- log.error(msg);
- throw new RuntimeException(msg);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
deleted file mode 100644
index c6f41ab..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.wso2.carbon.mediator.autoscale.lbautoscale.mediators;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.mediators.AbstractMediator;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-
-import java.util.Map;
-
-/**
- * This Synapse mediator removes the request token generated by the {@link AutoscaleInMediator}
- *
- * @see AutoscaleInMediator
- */
-public class AutoscaleOutMediator extends AbstractMediator implements ManagedLifecycle {
-
- public boolean mediate(MessageContext synCtx) {
-
- log.debug("Mediation started ....... " + AutoscaleOutMediator.class.getName());
-
- ConfigurationContext configCtx =
- ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
-
- String domain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_DOMAIN);
- // gets the corresponding sub domain
- String subDomain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_SUB_DOMAIN);
-
- String tokenId = (String) synCtx.getProperty(AutoscaleConstants.REQUEST_ID);
- @SuppressWarnings("unchecked")
- Map<String, Map<String, AppDomainContext>> appDomainContexts =
- (Map<String, Map<String, AppDomainContext>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
- AppDomainContext appDomainContext = null ;
-
- if(appDomainContexts.get(domain) != null){
- appDomainContext = appDomainContexts.get(domain).get(subDomain);
- }
-
- if (appDomainContext != null) {
- appDomainContext.removeRequestToken(tokenId);
- System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
- } else {
- log.debug("AppDomainContext not found for domain " + domain+" and sub domain : "+subDomain);
- }
- return true;
- }
-
- @Override
- public void destroy() {
- log.debug("Autoscale out mediator destroyed...");
- }
-
- @Override
- public void init(SynapseEnvironment arg0) {
- log.debug("Autoscale out mediator started...");
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
deleted file mode 100644
index 0e84608..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.state.check;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-public class PendingInstancesStateChecker implements Runnable {
-
- private static final Log log = LogFactory.getLog(PendingInstancesStateChecker.class);
- private LoadBalancerContext groupCtxt = null;
- private String domain;
- private String subDomain;
- private int expectedIncrementOfinstanceCount, originalRunningInstanceCount;
- private CloudControllerClient ccClient;
-
- public PendingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain,
- int anexpectedInstanceCount, int currentCount, CloudControllerClient client) {
- groupCtxt = ctxt;
- domain = aDomain;
- subDomain = aSubDomain;
- expectedIncrementOfinstanceCount = anexpectedInstanceCount;
- originalRunningInstanceCount = currentCount;
- ccClient = client;
- }
-
- @Override
- public void run() {
-
- if (groupCtxt != null) {
-
- int totalWaitedTime = 0;
- int serverStartupDelay = AutoscalerTaskDSHolder
- .getInstance()
- .getWholeLoadBalancerConfig()
- .getLoadBalancerConfig()
- .getServerStartupDelay();
-
- log.debug("Pending Instances State Checker has started for: " +
- AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
-
- // for each sub domain, get the clustering group management agent
- GroupManagementAgent agent =
- AutoscalerTaskDSHolder.getInstance().getAgent()
- .getGroupManagementAgent(domain,
- subDomain);
- int startingRunningInstanceCount = agent.getMembers().size();
-
- // we give some time for the server to get joined, we'll check time to time
- // whether the instance has actually joined the ELB.
- while ((agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) &&
- totalWaitedTime < serverStartupDelay) {
- int upToDateRunningInstanceCount = agent.getMembers().size();
-
- log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
- " - Number of current running instances " +
- upToDateRunningInstanceCount);
-
- if (upToDateRunningInstanceCount > startingRunningInstanceCount) {
- int newlyJoinedInstanceCount = upToDateRunningInstanceCount - startingRunningInstanceCount;
- // set new running instance count
- groupCtxt.setRunningInstanceCount(upToDateRunningInstanceCount);
- // decrement the pending instance count
- groupCtxt.decrementPendingInstancesIfNotZero(newlyJoinedInstanceCount);
- // update the starting running instance count
- startingRunningInstanceCount = upToDateRunningInstanceCount;
-
- log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
- " - Instances newly joined: " +
- newlyJoinedInstanceCount);
- }
-
- try {
- Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
- } catch (InterruptedException ignore) {
- }
-
- totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
- }
-
- log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
- totalWaitedTime +
- " (milliseconds) till pending members get joined.");
-
- if (agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) {
-
- int instanceCountFailedToJoin =
- originalRunningInstanceCount + expectedIncrementOfinstanceCount - agent.getMembers().size();
- log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
- "Instances that are failed to join: " +
- instanceCountFailedToJoin);
-
- // to avoid an infinite loop
- int retries = instanceCountFailedToJoin + 2;
-
- while (instanceCountFailedToJoin > 0 && retries > 0) {
- // instances spawned haven't joined ELB, so we assume that instance is
- // corrupted.
- // hence, we ask CC to terminate it.
- try {
- log.debug("Terminating lastly spwaned instance of " +
- AutoscaleUtil.domainSubDomainString(domain, subDomain));
- ccClient.terminateLastlySpawnedInstance(domain, subDomain);
- instanceCountFailedToJoin--;
- // decrement pending count
- groupCtxt.decrementPendingInstancesIfNotZero(1);
- } catch (Exception e) {
- log
- .error(
- "Instance termination failed for " +
- AutoscaleUtil.domainSubDomainString(domain, subDomain),
- e);
- } finally {
- retries--;
- }
- }
-
- // decrement pending count
- groupCtxt.decrementPendingInstancesIfNotZero(instanceCountFailedToJoin);
- }
-
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
deleted file mode 100644
index 3807f7b..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
-* 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.wso2.carbon.mediator.autoscale.lbautoscale.state.check;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-public class TerminatingInstancesStateChecker implements Runnable {
-
- private static final Log log = LogFactory.getLog(TerminatingInstancesStateChecker.class);
- private LoadBalancerContext groupCtxt = null;
- private String domain;
- private String subDomain;
-
- public TerminatingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain) {
- groupCtxt = ctxt;
- domain = aDomain;
- subDomain = aSubDomain;
- }
-
- @Override
- public void run() {
-
- if (groupCtxt != null) {
-
- groupCtxt.incrementTerminatingInstances(1);
-
- int totalWaitedTime = 0;
- int serverStartupDelay = AutoscalerTaskDSHolder
- .getInstance()
- .getWholeLoadBalancerConfig()
- .getLoadBalancerConfig()
- .getServerStartupDelay();
- log.info("Terminating Instances State Checker has started for: " +
- AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
-
- // for each sub domain, get the clustering group management agent
- GroupManagementAgent agent =
- AutoscalerTaskDSHolder.getInstance().getAgent()
- .getGroupManagementAgent(domain,
- subDomain);
-
- int startingRunningInstanceCount = agent.getMembers().size();
-
- // 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() == startingRunningInstanceCount &&
- totalWaitedTime < serverStartupDelay) {
-
- try {
- Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
- } catch (InterruptedException ignore) {
- }
-
- totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
- }
-
- log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
- totalWaitedTime +
- " (milliseconds) till terminating member left the cluster.");
-
- // we recalculate number of alive instances
- groupCtxt.decrementTerminatingInstancesIfNotZero(1);
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/290c6307/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
deleted file mode 100644
index 5696643..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * 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.wso2.carbon.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.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
deleted file mode 100644
index b1650d6..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
+++ /dev/null
@@ -1,345 +0,0 @@
-/**
- * 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.wso2.carbon.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.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
deleted file mode 100644
index 2edbd3a..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * 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.wso2.carbon.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.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
deleted file mode 100644
index 712ceb3..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
+++ /dev/null
@@ -1,525 +0,0 @@
-/*
- * 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.wso2.carbon.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.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.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.AppNodeSanityCheckCallable;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.AutoscaleDeciderCallable;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.InstanceCountCallable;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.PendingInstanceCountCallable;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerOsgiClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerStubClient;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.wso2.carbon.lb.common.replication.RequestTokenReplicationCommand;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-/**
- * 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.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
deleted file mode 100644
index 9c5ca8b..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * 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.wso2.carbon.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.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
deleted file mode 100644
index d4ae9ef..0000000
--- a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.wso2.carbon.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;
- }
- }
-
-}