Updated Branches:
  refs/heads/master 68dcc68e0 -> 723f3397e

Refactored autoscaler service component, partition manager, policy manager and 
registry manager - revision 1


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

Branch: refs/heads/master
Commit: 0091a767af458b095f4974f218952c2da2356d77
Parents: 0a4f798
Author: Imesh Gunaratne <[email protected]>
Authored: Sat Dec 14 09:39:19 2013 +0530
Committer: Imesh Gunaratne <[email protected]>
Committed: Sat Dec 14 09:39:19 2013 +0530

----------------------------------------------------------------------
 .../internal/AutoscalerServerComponent.java     | 259 +++++----------
 .../autoscaler/partition/PartitionManager.java  |  46 +--
 .../autoscaler/policy/PolicyManager.java        | 317 +++++++++----------
 .../autoscaler/registry/RegistryManager.java    | 154 ++++++++-
 4 files changed, 378 insertions(+), 398 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/0091a767/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/internal/AutoscalerServerComponent.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/internal/AutoscalerServerComponent.java
 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/internal/AutoscalerServerComponent.java
index cdcee85..e5c7964 100644
--- 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/internal/AutoscalerServerComponent.java
+++ 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/internal/AutoscalerServerComponent.java
@@ -41,208 +41,93 @@ import 
org.wso2.carbon.registry.core.service.RegistryService;
 
 import java.util.ArrayList;
 import java.util.Iterator;
+import java.util.List;
 
 /**
-* @scr.component 
name=org.apache.stratos.autoscaler.internal.AutoscalerServerComponent"
-* immediate="true"
-*
-* @scr.reference name="registry.service"
-*                interface=
-*                "org.wso2.carbon.registry.core.service.RegistryService"
-*                cardinality="1..1" policy="dynamic" bind="setRegistryService"
-*                unbind="unsetRegistryService"
-*/
+ * @scr.component 
name=org.apache.stratos.autoscaler.internal.AutoscalerServerComponent"
+ * immediate="true"
+ * @scr.reference name="registry.service"
+ * interface=
+ * "org.wso2.carbon.registry.core.service.RegistryService"
+ * cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ * unbind="unsetRegistryService"
+ */
 
 public class AutoscalerServerComponent {
 
     private static final Log log = 
LogFactory.getLog(AutoscalerServerComponent.class);
-    private RegistryManager registryManager;
 
     protected void activate(ComponentContext componentContext) throws 
Exception {
-
-        // Subscribe to all topics
-//        TopicSubscriber topologyTopicSubscriber = new 
TopicSubscriber(Constants.TOPOLOGY_TOPIC);
-//        topologyTopicSubscriber.setMessageListener(new 
TopologyEventMessageReceiver());
-//        Thread topologyTopicSubscriberThread = new 
Thread(topologyTopicSubscriber);
-//        topologyTopicSubscriberThread.start();
-//        if (log.isDebugEnabled()) {
-//            log.debug("Topology event message receiver thread started");
-//        }
-//
-//        TopologyEventMessageDelegator tropologyEventMessageDelegator = new 
TopologyEventMessageDelegator();
-//        Thread tropologyDelegatorThread = new 
Thread(tropologyEventMessageDelegator);
-//        tropologyDelegatorThread.start();
-
-        
-        
-        // Adding the registry stored AS policies to the information model.
-        
         try {
-                       Thread topologyTopicSubscriberThread = new Thread(new 
AutoscalerTopologyReceiver());
-                       topologyTopicSubscriberThread.start();
-                       if (log.isDebugEnabled()) {
-                               log.debug("Topology message processor thread 
started");
-                       }
-
-                       TopicSubscriber healthStatTopicSubscriber = new 
TopicSubscriber(
-                                       Constants.HEALTH_STAT_TOPIC);
-                       healthStatTopicSubscriber
-                                       .setMessageListener(new 
HealthEventMessageReceiver());
-                       Thread healthStatTopicSubscriberThread = new Thread(
-                                       healthStatTopicSubscriber);
-                       healthStatTopicSubscriberThread.start();
-                       if (log.isDebugEnabled()) {
-                               log.debug("Health Stat event message receiver 
thread started");
-                       }
-                       HealthEventMessageDelegator healthEventMessageDelegator 
= new HealthEventMessageDelegator();
-                       Thread healthDelegatorThread = new Thread(
-                                       healthEventMessageDelegator);
-                       healthDelegatorThread.start();
-                       if (log.isDebugEnabled()) {
-                               log.debug("Health message processor thread 
started");
-                       }
-                       // Start scheduler for running rules
-//                     ExecutorTaskScheduler executor = new 
ExecutorTaskScheduler();
-//                     Thread executorThread = new Thread(executor);
-//                     executorThread.start();
-//                     if (log.isDebugEnabled()) {
-//                             log.debug("Rules executor thread started");
-//                     }
-                       this.registryManager = RegistryManager.getInstance();
-                       // Adding the registry stored partitions to the 
information model.
-                       ArrayList<Partition> partitions = 
this.retreivePartitions();
-                       Iterator<Partition> it = partitions.iterator();
-                       while (it.hasNext()) {
-                               Partition par = it.next();
-                               
PartitionManager.getInstance().addPartitionToInformationModel(
-                                               par);
-                       }
-                       ArrayList<AutoscalePolicy> asPolicies = 
this.retreiveASPolicies();
-                       Iterator<AutoscalePolicy> asItr = asPolicies.iterator();
-                       while (asItr.hasNext()) {
-                               AutoscalePolicy asPolicy = asItr.next();
-                               
PolicyManager.getInstance().addASPolicyToInformationModel(asPolicy);
-                       }
-                       
-                       ArrayList<DeploymentPolicy> depPolicies = 
this.retreiveDeploymentPolicies();
-                       Iterator<DeploymentPolicy> depItr = 
depPolicies.iterator();
-                       while (depItr.hasNext()) {
-                               DeploymentPolicy depPolicy = depItr.next();
-                               
PolicyManager.getInstance().addDeploymentPolicyToInformationModel(depPolicy);
-                       }
-                       
-                       if (log.isInfoEnabled()) {
-                               log.info("Autoscaler Server Component 
activated");
-                       }
-               } catch (Throwable e) {
-                       log.error("Error in activating the autoscaler component 
", e);
-               }
+            // Start topology receiver
+            Thread topologyTopicSubscriberThread = new Thread(new 
AutoscalerTopologyReceiver());
+            topologyTopicSubscriberThread.start();
+            if (log.isDebugEnabled()) {
+                log.debug("Topology receiver thread started");
+            }
+
+            // Start health stat receiver
+            TopicSubscriber healthStatTopicSubscriber = new 
TopicSubscriber(Constants.HEALTH_STAT_TOPIC);
+            healthStatTopicSubscriber.setMessageListener(new 
HealthEventMessageReceiver());
+            Thread healthStatTopicSubscriberThread = new 
Thread(healthStatTopicSubscriber);
+            healthStatTopicSubscriberThread.start();
+            if (log.isDebugEnabled()) {
+                log.debug("Health event message receiver thread started");
+            }
+
+            HealthEventMessageDelegator healthEventMessageDelegator = new 
HealthEventMessageDelegator();
+            Thread healthDelegatorThread = new 
Thread(healthEventMessageDelegator);
+            healthDelegatorThread.start();
+            if (log.isDebugEnabled()) {
+                log.debug("Health message processor thread started");
+            }
+
+            // Adding the registry stored partitions to the information model
+            List<Partition> partitions = 
RegistryManager.getInstance().retrievePartitions();
+            Iterator<Partition> partitionIterator = partitions.iterator();
+            while (partitionIterator.hasNext()) {
+                Partition partition = partitionIterator.next();
+                
PartitionManager.getInstance().addPartitionToInformationModel(partition);
+            }
+            List<AutoscalePolicy> asPolicies = 
RegistryManager.getInstance().retrieveASPolicies();
+            Iterator<AutoscalePolicy> asPolicyIterator = asPolicies.iterator();
+            while (asPolicyIterator.hasNext()) {
+                AutoscalePolicy asPolicy = asPolicyIterator.next();
+                
PolicyManager.getInstance().addASPolicyToInformationModel(asPolicy);
+            }
+
+            List<DeploymentPolicy> depPolicies = 
RegistryManager.getInstance().retrieveDeploymentPolicies();
+            Iterator<DeploymentPolicy> depPolicyIterator = 
depPolicies.iterator();
+            while (depPolicyIterator.hasNext()) {
+                DeploymentPolicy depPolicy = depPolicyIterator.next();
+                
PolicyManager.getInstance().addDeploymentPolicyToInformationModel(depPolicy);
+            }
+
+            if (log.isInfoEnabled()) {
+                log.info("Autoscaler Server Component activated");
+            }
+        } catch (Throwable e) {
+            log.error("Error in activating the autoscaler component ", e);
+        }
     }
-    
+
     protected void setRegistryService(RegistryService registryService) {
-               if (log.isDebugEnabled()) {
-                       log.debug("Setting the Registry Service");
-               }
-               try {
-               
ServiceReferenceHolder.getInstance().setRegistry(registryService.getGovernanceSystemRegistry());
+        if (log.isDebugEnabled()) {
+            log.debug("Setting the Registry Service");
+        }
+        try {
+            
ServiceReferenceHolder.getInstance().setRegistry(registryService.getGovernanceSystemRegistry());
         } catch (RegistryException e) {
-               String msg = "Failed when retrieving Governance System 
Registry.";
-               log.error(msg, e);
-               throw new AutoScalerException(msg, e);
+            String msg = "Failed when retrieving Governance System Registry.";
+            log.error(msg, e);
+            throw new AutoScalerException(msg, e);
         }
-        }
+    }
 
-       protected void unsetRegistryService(RegistryService registryService) {
-               if (log.isDebugEnabled()) {
+    protected void unsetRegistryService(RegistryService registryService) {
+        if (log.isDebugEnabled()) {
             log.debug("Unsetting the Registry Service");
         }
         ServiceReferenceHolder.getInstance().setRegistry(null);
-       }
-       
-       private ArrayList<Partition> retreivePartitions(){
-               ArrayList<Partition> partitionList = new ArrayList<Partition>();
-                String [] partitionsResourceList = (String 
[])registryManager.retrieve(AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.PARTITION_RESOURCE);
-                
-               if (partitionsResourceList != null) {
-                               for (String resourcePath : 
partitionsResourceList) {
-                                       Object partition = 
registryManager.retrieve(resourcePath);
-
-                                       if (partition != null) {
-                                               try {
-
-                                                       Object dataObj = 
Deserializer
-                                                                       
.deserializeFromByteArray((byte[]) partition);
-                                                       if (dataObj instanceof 
Partition) {
-                                                               
partitionList.add((Partition) dataObj);
-                                                       } else {
-                                                               return null;
-                                                       }
-                                               } catch (Exception e) {
-                                                       String msg = "Unable to 
retrieve data from Registry. Hence, any historical partitions will not get 
reflected.";
-                                                       log.warn(msg, e);
-                                               }
-                                       }
-                               }
-                       }
-                       return partitionList;           
-       }
-       
-       private ArrayList<AutoscalePolicy> retreiveASPolicies(){
-               ArrayList<AutoscalePolicy> asPolicyList = new 
ArrayList<AutoscalePolicy>();
-                String [] partitionsResourceList = (String 
[])registryManager.retrieve(AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.AS_POLICY_RESOURCE);
-                
-               if (partitionsResourceList != null) {
-                               for (String resourcePath : 
partitionsResourceList) {
-                                       Object asPolicy = 
registryManager.retrieve(resourcePath);
-
-                                       if (asPolicy != null) {
-                                               try {
-
-                                                       Object dataObj = 
Deserializer
-                                                                       
.deserializeFromByteArray((byte[]) asPolicy);
-                                                       if (dataObj instanceof 
AutoscalePolicy) {
-                                                               
asPolicyList.add((AutoscalePolicy) dataObj);
-                                                       } else {
-                                                               return null;
-                                                       }
-                                               } catch (Exception e) {
-                                                       String msg = "Unable to 
retrieve data from Registry. Hence, any historical autoscaler policies will not 
get reflected.";
-                                                       log.warn(msg, e);
-                                               }
-                                       }
-                               }
-                       }
-                       return asPolicyList;            
-       }
-       
-       private ArrayList<DeploymentPolicy> retreiveDeploymentPolicies(){
-               ArrayList<DeploymentPolicy> depPolicyList = new 
ArrayList<DeploymentPolicy>();
-                String [] depPolicyResourceList = (String 
[])registryManager.retrieve(AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.DEPLOYMENT_POLICY_RESOURCE);
-                
-               if (depPolicyResourceList != null) {
-                               for (String resourcePath : 
depPolicyResourceList) {
-                                       Object asPolicy = 
registryManager.retrieve(resourcePath);
-
-                                       if (asPolicy != null) {
-                                               try {
-
-                                                       Object dataObj = 
Deserializer
-                                                                       
.deserializeFromByteArray((byte[]) asPolicy);
-                                                       if (dataObj instanceof 
DeploymentPolicy) {
-                                                               
depPolicyList.add((DeploymentPolicy) dataObj);
-                                                       } else {
-                                                               return null;
-                                                       }
-                                               } catch (Exception e) {
-                                                       String msg = "Unable to 
retrieve data from Registry. Hence, any historical deployment policies will not 
get reflected.";
-                                                       log.warn(msg, e);
-                                               }
-                                       }
-                               }
-                       }
-                       return depPolicyList;           
-       }
-       
-       
-       
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/0091a767/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/partition/PartitionManager.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/partition/PartitionManager.java
 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/partition/PartitionManager.java
index a199715..379a055 100644
--- 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/partition/PartitionManager.java
+++ 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/partition/PartitionManager.java
@@ -62,9 +62,6 @@ private static final Log log = 
LogFactory.getLog(PartitionManager.class);
 
        private static PartitionManager instance;
        
-       private String partitionResourcePath = 
AutoScalerConstants.AUTOSCALER_RESOURCE 
-                       + AutoScalerConstants.PARTITION_RESOURCE + "/";
-       
        private PartitionManager(){
         networkPartitionContexts = new HashMap<String, 
NetworkPartitionContext>();
 //         networkPartitions = new ArrayList<NetworkPartitionContext>();
@@ -86,34 +83,21 @@ private static final Log log = 
LogFactory.getLog(PartitionManager.class);
         * Deploy a new partition to Auto Scaler.
         */
        public boolean addNewPartition(Partition partition) throws 
AutoScalerException{
-               String partitionId = partition.getId();
-               if(this.partitionExist(partition.getId()))
-                       throw new AutoScalerException("A parition with the ID " 
+  partitionId + " already exist.");
-                               
-               String resourcePath= this.partitionResourcePath + 
partition.getId();
-               
-        RegistryManager regManager = RegistryManager.getInstance();     
-        
-        try {
-               this.validatePartition(partition);
-
-               regManager.persist(partition, resourcePath);
-                       addPartitionToInformationModel(partition);      
-
-               // register network partition
-//             NetworkPartitionContext nwPartition = 
getOrAddNetworkPartition(partition);
-//             this.partitionIdToNetworkPartition.put(partitionId, 
nwPartition);
-//            
this.networkPartitionIdToNetworkPartition.put(nwPartition.getId(), nwPartition);
-
+               if(this.partitionExist(partition.getId())) {
+                       throw new AutoScalerException(String.format("Partition 
already exist in partition manager: [id] %s", partition.getId()));
+        }
 
-               } catch (RegistryException e) {
-                       throw new AutoScalerException(e);
-               } catch(PartitionValidationException e){
+        try {
+               validatePartition(partition);
+            RegistryManager.getInstance().persistPartition(partition);
+                       addPartitionToInformationModel(partition);
+            if(log.isInfoEnabled()) {
+                log.info(String.format("Partition is deployed successfully: 
[id] %s", partition.getId()));
+            }
+            return true;
+               } catch(Exception e){
                        throw new AutoScalerException(e);
                }
-                
-               log.info("Partition :" + partition.getId() + " is deployed 
successfully.");
-               return true;
        }
        
        
@@ -177,7 +161,10 @@ private static final Log log = 
LogFactory.getLog(PartitionManager.class);
                
        }
        
-       public boolean validatePartition(Partition partition) throws 
PartitionValidationException{                              
+       public boolean validatePartition(Partition partition) throws 
PartitionValidationException {
+        if(log.isDebugEnabled()) {
+            log.debug(String.format("Validating partition via cloud 
controller: [id] %s", partition.getId()));
+        }
                return 
CloudControllerClient.getInstance().validatePartition(partition);
        }
 
@@ -185,7 +172,6 @@ private static final Log log = 
LogFactory.getLog(PartitionManager.class);
         for(PartitionGroup partitionGroup: depPolicy.getPartitionGroups()){
             NetworkPartitionContext networkPartitionContext = new 
NetworkPartitionContext(partitionGroup.getId());
             networkPartitionContexts.put(partitionGroup.getId(), 
networkPartitionContext);
-
         }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/0091a767/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/policy/PolicyManager.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/policy/PolicyManager.java
 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/policy/PolicyManager.java
index 43c8336..49ee34b 100644
--- 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/policy/PolicyManager.java
+++ 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/policy/PolicyManager.java
@@ -19,7 +19,6 @@
 
 package org.apache.stratos.autoscaler.policy;
 
-import java.io.File;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -29,40 +28,35 @@ import java.util.Map;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.autoscaler.deployment.policy.DeploymentPolicy;
-import org.apache.stratos.autoscaler.exception.AutoScalerException;
 import org.apache.stratos.autoscaler.exception.InvalidPartitionException;
 import org.apache.stratos.autoscaler.exception.InvalidPolicyException;
-import org.apache.stratos.autoscaler.exception.PolicyValidationException;
 import org.apache.stratos.autoscaler.partition.PartitionManager;
 import org.apache.stratos.autoscaler.policy.model.AutoscalePolicy;
 import org.apache.stratos.autoscaler.registry.RegistryManager;
 import org.apache.stratos.autoscaler.util.AutoScalerConstants;
 import org.apache.stratos.cloud.controller.deployment.partition.Partition;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
 
 /**
- * 
- *  Manager class for the purpose of managing Autoscale/Deployment policy 
definitions.
+ * Manager class for the purpose of managing Autoscale/Deployment policy 
definitions.
  */
 public class PolicyManager {
-       
-       private static final Log log = LogFactory.getLog(PolicyManager.class);
-
-       private static final String asResourcePath = 
AutoScalerConstants.AUTOSCALER_RESOURCE+ AutoScalerConstants.AS_POLICY_RESOURCE 
+ "/";
-       private static final String deploymentPolicyResourcePath = 
AutoScalerConstants.AUTOSCALER_RESOURCE+ 
AutoScalerConstants.DEPLOYMENT_POLICY_RESOURCE + "/";
-       
-       private static Map<String,AutoscalePolicy> autoscalePolicyListMap = new 
HashMap<String, AutoscalePolicy>();
-       
-       private static Map<String,DeploymentPolicy> deploymentPolicyListMap = 
new HashMap<String, DeploymentPolicy>();
-       
-       private static PolicyManager instance = null;
-        
+
+    private static final Log log = LogFactory.getLog(PolicyManager.class);
+
+    private static final String asResourcePath = 
AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.AS_POLICY_RESOURCE + "/";
+
+    private static Map<String, AutoscalePolicy> autoscalePolicyListMap = new 
HashMap<String, AutoscalePolicy>();
+
+    private static Map<String, DeploymentPolicy> deploymentPolicyListMap = new 
HashMap<String, DeploymentPolicy>();
+
+    private static PolicyManager instance = null;
+
     private PolicyManager() {
     }
 
     public static PolicyManager getInstance() {
         if (instance == null) {
-            synchronized (PolicyManager.class){
+            synchronized (PolicyManager.class) {
                 if (instance == null) {
                     instance = new PolicyManager();
                 }
@@ -70,167 +64,158 @@ public class PolicyManager {
         }
         return instance;
     }
-    
+
     // Add the policy to information model and persist.
-       public boolean deployAutoscalePolicy(AutoscalePolicy policy) throws 
InvalidPolicyException {    
-               this.addASPolicyToInformationModel(policy);
-               this.persitASPolicy(asResourcePath+ policy.getId(), policy);    
-               
-               log.info("AutoScaling policy  :" + policy.getId() + " is 
deployed successfully.");
-               return true;
-       }
-       
-       // Add the deployment policy to information model and persist.
-       public boolean deployDeploymentPolicy(DeploymentPolicy policy) throws 
InvalidPolicyException {  
-           try {
-               Partition[] allPartitions = policy.getAllPartitions();
-            validateExistenceOfPartions(allPartitions);
-            
+    public boolean deployAutoscalePolicy(AutoscalePolicy policy) throws 
InvalidPolicyException {
+        this.addASPolicyToInformationModel(policy);
+        RegistryManager.getInstance().persistAutoscalerPolicy(policy);
+        if (log.isInfoEnabled()) {
+            log.info(String.format("AutoScaling policy is deployed 
successfully: [id] %s", policy.getId()));
+        }
+        return true;
+    }
+
+    // Add the deployment policy to information model and persist.
+    public boolean deployDeploymentPolicy(DeploymentPolicy policy) throws 
InvalidPolicyException {
+        try {
+            if(log.isInfoEnabled()) {
+                log.info(String.format("Deploying deployment policy: [id] %s", 
policy.getId()));
+            }
+            fillPartitions(policy);
         } catch (InvalidPartitionException e) {
-            String msg = "Deployment Policy is invalid. Policy name: " + 
policy.getId();
-            log.error(msg, e);
-            throw new InvalidPolicyException(msg, e);
+            throw new InvalidPolicyException(String.format("Deployment policy 
is invalid: [id] %s", policy.getId()), e);
+        }
+
+        this.addDeploymentPolicyToInformationModel(policy);
+        RegistryManager.getInstance().persistDeploymentPolicy(policy);
+
+        if (log.isInfoEnabled()) {
+            log.info(String.format("Deployment policy is deployed 
successfully: [id] %s", policy.getId()));
         }
-           
-               this.addDeploymentPolicyToInformationModel(policy);
-               this.persitDeploymentPolicy(deploymentPolicyResourcePath+ 
policy.getId(), policy);
-               
-               log.info("Deployment policy  :" + policy.getId() + " is 
deployed successfully.");
-               return true;
-       }
-       
-       private static void validateExistenceOfPartions(Partition[] partitions) 
throws InvalidPartitionException {
+        return true;
+    }
+
+    private void fillPartitions(DeploymentPolicy deploymentPolicy) throws 
InvalidPartitionException {
         PartitionManager partitionMgr = PartitionManager.getInstance();
-        for (Partition partition : partitions) {
+        for (Partition partition : deploymentPolicy.getAllPartitions()) {
             String partitionId = partition.getId();
-            if (partitionId == null || 
!partitionMgr.partitionExist(partitionId)) {
-                String msg =
-                             "Non existing Partition defined. Partition id: " 
+ partitionId + ". " +
-                                     "Please define the partition in the 
partition definition file.";
-                log.error(msg);
+            if ((partitionId == null) || 
(!partitionMgr.partitionExist(partitionId))) {
+                String msg = "Could not find partition: [id] " + partitionId + 
". " +
+                        "Please deploy the partitions before deploying the 
deployment policies.";
                 throw new InvalidPartitionException(msg);
             }
-            fillPartition(partition, 
partitionMgr.getPartitionById(partitionId));
+            fillPartition(partition, 
PartitionManager.getInstance().getPartitionById(deploymentPolicy.getId()));
         }
     }
 
     private static void fillPartition(Partition destPartition, Partition 
srcPartition) {
-       if(log.isDebugEnabled())
-               log.debug("Settting provider for Partition " + 
destPartition.getId() + " provider "+ srcPartition.getProvider());
+        if (log.isDebugEnabled()) {
+            log.debug(String.format("Setting provider for partition: [id] %s 
[provider] %s", destPartition.getId(), srcPartition.getProvider()));
+        }
         destPartition.setProvider(srcPartition.getProvider());
-        
-        if(log.isDebugEnabled())
-               log.info("Settting properties for Partition " + 
destPartition.getId() + " provider "+ srcPartition.getProperties());
+
+        if (log.isDebugEnabled()) {
+            log.debug(String.format("Setting properties for partition: [id] %s 
[properties] %s", destPartition.getId(), srcPartition.getProperties()));
+        }
         destPartition.setProperties(srcPartition.getProperties());
+    }
+
+    public void addASPolicyToInformationModel(AutoscalePolicy asPolicy) throws 
InvalidPolicyException {
+        if (!autoscalePolicyListMap.containsKey(asPolicy.getId())) {
+            if (log.isDebugEnabled()) {
+                log.debug("Adding policy :" + asPolicy.getId());
+            }
+            autoscalePolicyListMap.put(asPolicy.getId(), asPolicy);
+        } else {
+            throw new InvalidPolicyException("Specified policy [" + 
asPolicy.getId()
+                    + "] already exists");
+        }
+    }
+
+    /**
+     * Removes the specified policy
+     *
+     * @param policy
+     * @throws InvalidPolicyException
+     */
+    public void removeAutoscalePolicy(String policy) throws 
InvalidPolicyException {
+        if (autoscalePolicyListMap.containsKey(policy)) {
+            if (log.isDebugEnabled()) {
+                log.debug("Removing policy :" + policy);
+            }
+            autoscalePolicyListMap.remove(policy);
+        } else {
+            throw new InvalidPolicyException("No such policy [" + policy + "] 
exists");
+        }
+    }
+
+    /**
+     * Returns a List of the Autoscale policies contained in this manager.
+     *
+     * @return
+     */
+    public List<AutoscalePolicy> getAutoscalePolicyList() {
+        return Collections.unmodifiableList(new 
ArrayList<AutoscalePolicy>(autoscalePolicyListMap.values()));
+    }
+
+    /**
+     * Returns the autoscale policy to which the specified id is mapped or null
+     *
+     * @param id
+     * @return
+     */
+    public AutoscalePolicy getAutoscalePolicy(String id) {
+        return autoscalePolicyListMap.get(id);
+    }
+
+    // Add the deployment policy to As in memmory information model. Does not 
persist.
+    public void addDeploymentPolicyToInformationModel(DeploymentPolicy policy) 
throws InvalidPolicyException {
+        if (!deploymentPolicyListMap.containsKey(policy.getId())) {
+            if (log.isDebugEnabled()) {
+                log.debug("Adding policy :" + policy.getId());
+            }
+            PartitionManager.getInstance().deployNewNetworkPartitions(policy);
+            deploymentPolicyListMap.put(policy.getId(), policy);
+        } else {
+            throw new InvalidPolicyException("Specified policy [" + 
policy.getId()
+                    + "] already exists");
+        }
+    }
+
+    /**
+     * Removes the specified policy
+     *
+     * @param policy
+     * @throws InvalidPolicyException
+     */
+    public void removeDeploymentPolicy(String policy) throws 
InvalidPolicyException {
+        if (deploymentPolicyListMap.containsKey(policy)) {
+            if (log.isDebugEnabled()) {
+                log.debug("Removing policy :" + policy);
+            }
+            deploymentPolicyListMap.remove(policy);
+        } else {
+            throw new InvalidPolicyException("No such policy [" + policy + "] 
exists");
+        }
+    }
+
+    /**
+     * Returns a List of the Deployment policies contained in this manager.
+     *
+     * @return
+     */
+    public List<DeploymentPolicy> getDeploymentPolicyList() {
+        return Collections.unmodifiableList(new 
ArrayList<DeploymentPolicy>(deploymentPolicyListMap.values()));
+    }
 
+    /**
+     * Returns the deployment policy to which the specified id is mapped or 
null
+     *
+     * @param id
+     * @return
+     */
+    public DeploymentPolicy getDeploymentPolicy(String id) {
+        return deploymentPolicyListMap.get(id);
     }
-               
-       public void addASPolicyToInformationModel(AutoscalePolicy asPolicy) 
throws InvalidPolicyException{
-               if (!autoscalePolicyListMap.containsKey(asPolicy.getId())) {
-                       if(log.isDebugEnabled()){
-                               log.debug("Adding policy :" + asPolicy.getId());
-                       }                       
-                       autoscalePolicyListMap.put(asPolicy.getId(), asPolicy);
-               } else {
-                       throw new InvalidPolicyException("Specified policy [" + 
asPolicy.getId()
-                                       + "] already exists");
-               }
-       }
-       
-       private void persitASPolicy(String asResourcePath, AutoscalePolicy 
policy){             
-               try {
-                       RegistryManager.getInstance().persist(policy, 
asResourcePath);
-               } catch (RegistryException e) {
-                       throw new AutoScalerException(e);
-               }
-       }
-       
-       private void persitDeploymentPolicy(String depResourcePath, 
DeploymentPolicy policy){           
-               try {
-                       RegistryManager.getInstance().persist(policy, 
depResourcePath);
-               } catch (RegistryException e) {
-                       throw new AutoScalerException(e);
-               }
-       }
-       
-       /**
-        * Removes the specified policy
-        * @param policy
-        * @throws InvalidPolicyException
-        */
-       public void removeAutoscalePolicy(String policy) throws 
InvalidPolicyException {
-               if (autoscalePolicyListMap.containsKey(policy)) {
-                       if(log.isDebugEnabled()){
-                               log.debug("Removing policy :" + policy);
-                       }
-                       autoscalePolicyListMap.remove(policy);
-               } else {
-                       throw new InvalidPolicyException("No such policy [" + 
policy + "] exists");
-               }
-       }
-       
-       /**
-        * Returns a List of the Autoscale policies contained in this manager.
-        * @return
-        */
-       public List<AutoscalePolicy> getAutoscalePolicyList() {
-               return Collections.unmodifiableList(new 
ArrayList<AutoscalePolicy>(autoscalePolicyListMap.values()));
-       }
-       
-       /**
-        * Returns the autoscale policy to which the specified id is mapped or 
null
-        * @param id
-        * @return
-        */
-       public AutoscalePolicy getAutoscalePolicy(String id) {
-               return autoscalePolicyListMap.get(id);
-       }
-
-       // Add the deployment policy to As in memmory information model. Does 
not persist.
-       public void addDeploymentPolicyToInformationModel(DeploymentPolicy 
policy) throws InvalidPolicyException {
-               if (!deploymentPolicyListMap.containsKey(policy.getId())) {
-                       if(log.isDebugEnabled()){
-                               log.debug("Adding policy :" + policy.getId());
-                       }
-                       
PartitionManager.getInstance().deployNewNetworkPartitions(policy);
-                       deploymentPolicyListMap.put(policy.getId(), policy);
-               } else {
-                       throw new InvalidPolicyException("Specified policy [" + 
policy.getId()
-                                       + "] already exists");
-               }
-       }
-               
-       /**
-        * Removes the specified policy
-        * @param policy
-        * @throws InvalidPolicyException
-        */
-       public void removeDeploymentPolicy(String policy) throws 
InvalidPolicyException {
-               if (deploymentPolicyListMap.containsKey(policy)) {
-                       if(log.isDebugEnabled()){
-                               log.debug("Removing policy :" + policy);
-                       }
-                       deploymentPolicyListMap.remove(policy);
-               } else {
-                       throw new InvalidPolicyException("No such policy [" + 
policy + "] exists");
-               }
-       }
-       
-       /**
-        * Returns a List of the Deployment policies contained in this manager.
-        * @return
-        */
-       public List<DeploymentPolicy> getDeploymentPolicyList() {
-               return Collections.unmodifiableList(new 
ArrayList<DeploymentPolicy>(deploymentPolicyListMap.values()));
-       }
-       
-       /**
-        * Returns the deployment policy to which the specified id is mapped or 
null
-        * @param id
-        * @return
-        */
-       public DeploymentPolicy getDeploymentPolicy(String id) {
-               return deploymentPolicyListMap.get(id);
-       }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/0091a767/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/registry/RegistryManager.java
----------------------------------------------------------------------
diff --git 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/registry/RegistryManager.java
 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/registry/RegistryManager.java
index 5be5fd4..ba1afdf 100644
--- 
a/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/registry/RegistryManager.java
+++ 
b/components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/registry/RegistryManager.java
@@ -2,6 +2,10 @@ package org.apache.stratos.autoscaler.registry;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.autoscaler.deployment.policy.DeploymentPolicy;
+import org.apache.stratos.autoscaler.policy.model.AutoscalePolicy;
+import org.apache.stratos.autoscaler.util.Deserializer;
+import org.apache.stratos.cloud.controller.deployment.partition.Partition;
 import org.wso2.carbon.registry.core.Registry;
 import org.wso2.carbon.registry.core.Resource;
 import org.wso2.carbon.registry.core.exceptions.RegistryException;
@@ -11,6 +15,9 @@ import org.apache.stratos.autoscaler.util.AutoScalerConstants;
 import org.apache.stratos.autoscaler.util.ServiceReferenceHolder;
 import org.apache.stratos.autoscaler.util.Serializer;
 
+import java.util.ArrayList;
+import java.util.List;
+
 public class RegistryManager {
 
        private final static Log log = LogFactory.getLog(RegistryManager.class);
@@ -54,13 +61,9 @@ public class RegistryManager {
      * @param dataObj object to be persisted.
      * @param resourcePath resource path to be persisted.
      */
-    public void persist(Object dataObj, String resourcePath) throws 
RegistryException {
+    private void persist(Object dataObj, String resourcePath) throws 
AutoScalerException {
        
         try {
-               /*
-               if (registryService.resourceExists(resourcePath)) {
-                throw new AutoScalerException("Resource already exist in the 
registry: " + resourcePath);
-            }*/
             registryService.beginTransaction();
 
             Resource nodeResource = registryService.newResource();
@@ -68,21 +71,46 @@ public class RegistryManager {
             
             registryService.put(resourcePath, nodeResource);
             registryService.commitTransaction();
-            
-            if(log.isDebugEnabled()){
-               
-            }
-        
         } catch (Exception e) {
-            String msg = "Failed to persist the Autoscaler data in registry.";
-            registryService.rollbackTransaction();
-            log.error(msg, e);
-            throw new AutoScalerException(msg, e);
+            try {
+                registryService.rollbackTransaction();
+            } catch (RegistryException e1) {
+                if(log.isErrorEnabled()) {
+                    log.error("Could not rollback transaction", e);
+                }
+            }
+            throw new AutoScalerException("Could not persist data in 
registry", e);
+        }
+    }
 
+    public void persistPartition(Partition partition) {
+        String resourcePath = AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.PARTITION_RESOURCE + "/";
+        persist(partition, resourcePath);
+        if(log.isDebugEnabled()) {
+            log.debug(String.format("Partition written to registry: [id] %s 
[provider] %s [min] %d [max] %d",
+                    partition.getId(), partition.getProvider(), 
partition.getPartitionMin(), partition.getPartitionMax()));
+        }
+    }
+
+    public void persistAutoscalerPolicy(AutoscalePolicy autoscalePolicy) {
+        String resourcePath = AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.AS_POLICY_RESOURCE + "/" + autoscalePolicy.getId();
+        persist(autoscalePolicy, resourcePath);
+        if(log.isDebugEnabled()) {
+            log.debug(String.format("Autoscaler policy written to registry: 
[id] %s [name] %s [description] %s",
+                    autoscalePolicy.getId(), autoscalePolicy.getDisplayName(), 
autoscalePolicy.getDescription()));
+        }
+    }
+
+    public void persistDeploymentPolicy(DeploymentPolicy deploymentPolicy) {
+        String resourcePath = AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.DEPLOYMENT_POLICY_RESOURCE + "/" + deploymentPolicy.getId();
+        persist(deploymentPolicy, resourcePath);
+        if(log.isDebugEnabled()) {
+            log.debug(String.format("Deployment policy written to registry: 
[id] %s [partitions] %s",
+                    deploymentPolicy.getId(), 
deploymentPolicy.getAllPartitions()));
         }
     }
     
-    public Object retrieve(String resourcePath) {
+    private Object retrieve(String resourcePath) {
         try {
             Resource resource = registryService.get(resourcePath);
            
@@ -96,6 +124,102 @@ public class RegistryManager {
             log.error(msg, e);
             throw new AutoScalerException(msg, e);
         }
+    }
+
+    public List<Partition> retrievePartitions() {
+        List<Partition> partitionList = new ArrayList<Partition>();
+        RegistryManager registryManager = RegistryManager.getInstance();
+        String[] partitionsResourceList = (String[]) 
registryManager.retrieve(AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.PARTITION_RESOURCE);
 
+        if (partitionsResourceList != null) {
+            Partition partition;
+            for (String resourcePath : partitionsResourceList) {
+                Object serializedObj = registryManager.retrieve(resourcePath);
+                if (serializedObj != null) {
+                    try {
+
+                        Object dataObj = 
Deserializer.deserializeFromByteArray((byte[]) serializedObj);
+                        if (dataObj instanceof Partition) {
+                            partition = (Partition) dataObj;
+                            if(log.isDebugEnabled()) {
+                                log.debug(String.format("Partition read from 
registry: [id] %s [provider] %s [min] %d [max] %d",
+                                        partition.getId(), 
partition.getProvider(), partition.getPartitionMin(), 
partition.getPartitionMax()));
+                            }
+                            partitionList.add(partition);
+                        } else {
+                            return null;
+                        }
+                    } catch (Exception e) {
+                        String msg = "Unable to retrieve data from Registry. 
Hence, any historical partitions will not get reflected.";
+                        log.warn(msg, e);
+                    }
+                }
+            }
+        }
+        return partitionList;
+    }
+
+    public List<AutoscalePolicy> retrieveASPolicies() {
+        List<AutoscalePolicy> asPolicyList = new ArrayList<AutoscalePolicy>();
+        RegistryManager registryManager = RegistryManager.getInstance();
+        String[] partitionsResourceList = (String[]) 
registryManager.retrieve(AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.AS_POLICY_RESOURCE);
+
+        if (partitionsResourceList != null) {
+            AutoscalePolicy asPolicy;
+            for (String resourcePath : partitionsResourceList) {
+                Object serializedObj = registryManager.retrieve(resourcePath);
+                if (serializedObj != null) {
+                    try {
+                        Object dataObj = 
Deserializer.deserializeFromByteArray((byte[]) serializedObj);
+                        if (dataObj instanceof AutoscalePolicy) {
+                            asPolicy = (AutoscalePolicy) dataObj;
+                            if(log.isDebugEnabled()) {
+                                log.debug(String.format("Autoscaler policy 
read from registry: [id] %s [name] %s [description] %s",
+                                        asPolicy.getId(), 
asPolicy.getDisplayName(), asPolicy.getDescription()));
+                            }
+                            asPolicyList.add(asPolicy);
+                        } else {
+                            return null;
+                        }
+                    } catch (Exception e) {
+                        String msg = "Unable to retrieve data from Registry. 
Hence, any historical autoscaler policies will not get reflected.";
+                        log.warn(msg, e);
+                    }
+                }
+            }
+        }
+        return asPolicyList;
+    }
+
+    public List<DeploymentPolicy> retrieveDeploymentPolicies() {
+        List<DeploymentPolicy> depPolicyList = new 
ArrayList<DeploymentPolicy>();
+        RegistryManager registryManager = RegistryManager.getInstance();
+        String[] depPolicyResourceList = (String[]) 
registryManager.retrieve(AutoScalerConstants.AUTOSCALER_RESOURCE + 
AutoScalerConstants.DEPLOYMENT_POLICY_RESOURCE);
+
+        if (depPolicyResourceList != null) {
+            DeploymentPolicy depPolicy;
+            for (String resourcePath : depPolicyResourceList) {
+                Object serializedObj = registryManager.retrieve(resourcePath);
+                if (serializedObj != null) {
+                    try {
+                        Object dataObj = 
Deserializer.deserializeFromByteArray((byte[]) serializedObj);
+                        if (dataObj instanceof DeploymentPolicy) {
+                            depPolicy = (DeploymentPolicy) dataObj;
+                            if(log.isDebugEnabled()) {
+                                log.debug(String.format("Deployment policy 
read from registry: [id] %s [partitions] %s",
+                                        depPolicy.getId(), 
depPolicy.getAllPartitions()));
+                            }
+                            depPolicyList.add(depPolicy);
+                        } else {
+                            return null;
+                        }
+                    } catch (Exception e) {
+                        String msg = "Unable to retrieve data from Registry. 
Hence, any historical deployment policies will not get reflected.";
+                        log.warn(msg, e);
+                    }
+                }
+            }
+        }
+        return depPolicyList;
     }
 }

Reply via email to