You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by im...@apache.org on 2013/12/01 15:35:06 UTC

git commit: Implemented synapse configurator to configure synapse settings using load balancer configuration

Updated Branches:
  refs/heads/master 96db3160a -> 8627efd45


Implemented synapse configurator to configure synapse settings using load balancer configuration


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

Branch: refs/heads/master
Commit: 8627efd4547ec5d9f6ff5c6374a5ecfa703ce84c
Parents: 96db316
Author: Imesh Gunaratne <im...@apache.org>
Authored: Sun Dec 1 20:04:42 2013 +0530
Committer: Imesh Gunaratne <im...@apache.org>
Committed: Sun Dec 1 20:04:42 2013 +0530

----------------------------------------------------------------------
 .../load/balancer/conf/SynapseConfigurator.java | 184 +++++++++++++++++++
 .../internal/LoadBalancerServiceComponent.java  |   3 +
 .../sample/configuration/loadbalancer1.conf     |   2 +-
 .../sample/configuration/loadbalancer2.conf     |   2 +-
 .../sample/configuration/loadbalancer3.conf     |   2 +-
 .../synapse-configs/default/sequences/main.xml  |  29 +--
 6 files changed, 199 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/8627efd4/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/conf/SynapseConfigurator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/conf/SynapseConfigurator.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/conf/SynapseConfigurator.java
new file mode 100644
index 0000000..2d276e8
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/conf/SynapseConfigurator.java
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.conf;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.load.balancer.conf.domain.Algorithm;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+/**
+ * Synapse configurator to configure Synapse settings required for the load balancer.
+ */
+public class SynapseConfigurator {
+    private static final Log log = LogFactory.getLog(SynapseConfigurator.class);
+
+    /**
+     * Configure Synapse using load balancer configuration.
+     * @param configuration
+     */
+    public static void configure(LoadBalancerConfiguration configuration) {
+        configureMainSequence(configuration);
+    }
+    /**
+     * Configure main sequence send mediator endpoint.
+     * @param configuration Load balancer configuration.
+     */
+    public static void configureMainSequence(LoadBalancerConfiguration configuration) {
+        String filePath = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "deployment" + File.separator + "server" + File.separator
+                          + "synapse-configs" + File.separator + "default" + File.separator + "sequences" + File.separator + "main.xml";
+        configureMainSequence(configuration, filePath, filePath);
+    }
+
+    /**
+     * Configure main sequence send mediator endpoint.
+     * @param configuration Load balancer configuration.
+     * @param inputFilePath Input file path.
+     * @param outputFilePath Output file path.
+     */
+    public static void configureMainSequence(LoadBalancerConfiguration configuration, String inputFilePath, String outputFilePath) {
+        try {
+            if(log.isInfoEnabled()) {
+                log.info("Configuring synapse main sequence...");
+            }
+            if (log.isDebugEnabled()) {
+                log.debug(String.format("Reading synapse main sequence: %s", inputFilePath));
+            }
+            File inputFile = new File(inputFilePath);
+            if(!inputFile.exists()) {
+                throw new RuntimeException(String.format("File not found: %s", inputFilePath));
+            }
+            FileInputStream file = new FileInputStream(inputFile);
+            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
+            DocumentBuilder builder = builderFactory.newDocumentBuilder();
+            Document xmlDocument = builder.parse(file);
+            XPath xPath = XPathFactory.newInstance().newXPath();
+
+            String expression = "/sequence/in/send/endpoint/class/parameter";
+            if (log.isDebugEnabled()) {
+                log.debug(String.format("xpath expression = %s", expression));
+            }
+            boolean updated = false;
+            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
+            for (int i = 0; i < nodeList.getLength(); i++) {
+                Node node = nodeList.item(i);
+                Node parameter = node.getAttributes().getNamedItem("name");
+                if (parameter.getNodeValue().equals("algorithmClassName")) {
+                    String defaultAlgorithmName = configuration.getDefaultAlgorithmName();
+                    if (StringUtils.isBlank(defaultAlgorithmName)) {
+                        throw new RuntimeException("Default algorithm name not found in load balancer configuration");
+                    }
+                    Algorithm defaultAlgorithm = configuration.getAlgorithm(defaultAlgorithmName);
+                    if (defaultAlgorithm == null) {
+                        throw new RuntimeException("Default algorithm not found in load balancer configuration");
+                    }
+                    String algorithmClassName = defaultAlgorithm.getClassName();
+                    if (log.isDebugEnabled()) {
+                        log.debug(String.format("Setting algorithmClassName = %s", algorithmClassName));
+                    }
+                    node.setTextContent(algorithmClassName);
+                    updated = true;
+                } else if (parameter.getNodeValue().equals("failover")) {
+                    String value = String.valueOf(configuration.isFailOver());
+                    if (log.isDebugEnabled()) {
+                        log.debug(String.format("Setting failover = %s", value));
+                    }
+                    node.setTextContent(value);
+                    updated = true;
+                } else if (parameter.getNodeValue().equals("sessionAffinity")) {
+                    String value = String.valueOf(configuration.isSessionAffinity());
+                    if (log.isDebugEnabled()) {
+                        log.debug(String.format("Setting sessionAffinity = %s", value));
+                    }
+                    node.setTextContent(value);
+                    updated = true;
+                } else if (parameter.getNodeValue().equals("sessionTimeout")) {
+                    String value = String.valueOf(configuration.getSessionTimeout());
+                    if (log.isDebugEnabled()) {
+                        log.debug(String.format("Setting sessionTimeout = %s", value));
+                    }
+                    node.setTextContent(value);
+                    updated = true;
+                }
+            }
+            if (updated) {
+                if (log.isDebugEnabled()) {
+                    log.debug(String.format("Updating synapse main sequence: %s", outputFilePath));
+                }
+                write(xmlDocument, outputFilePath);
+                if(log.isInfoEnabled()) {
+                    log.info("Synapse main sequence configured successfully");
+                }
+            }
+            else {
+                throw new RuntimeException(String.format("Send mediator endpoint configuration not found: %s", inputFilePath));
+            }
+        } catch (Exception e) {
+            throw new RuntimeException("Could not configure synapse settings", e);
+        }
+    }
+
+    /**
+     * Write xml document to file.
+     * @param document
+     * @param outputFilePath
+     * @throws IOException
+     */
+    private static void write(Document document, String outputFilePath) throws IOException {
+        try {
+            Transformer transformer = TransformerFactory.newInstance().newTransformer();
+            DocumentType documentType = document.getDoctype();
+            if (documentType != null) {
+                String publicId = documentType.getPublicId();
+                if (publicId != null) {
+                    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, publicId);
+                }
+                transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId());
+            }
+            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
+            Source source = new DOMSource(document);
+            FileOutputStream outputStream = new FileOutputStream(outputFilePath);
+            Result result = new StreamResult(outputStream);
+            transformer.transform(source, result);
+        } catch (Exception e) {
+            throw new RuntimeException(String.format("Could not write xml file: s%", outputFilePath), e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/8627efd4/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalancerServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalancerServiceComponent.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalancerServiceComponent.java
index fc41345..5a0263c 100644
--- a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalancerServiceComponent.java
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalancerServiceComponent.java
@@ -27,6 +27,7 @@ import org.apache.stratos.load.balancer.TenantAwareLoadBalanceEndpointException;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.load.balancer.conf.LoadBalancerConfiguration;
+import org.apache.stratos.load.balancer.conf.SynapseConfigurator;
 import org.apache.stratos.messaging.message.filter.topology.ClusterFilter;
 import org.apache.stratos.messaging.message.filter.topology.ServiceFilter;
 import org.apache.synapse.config.SynapseConfiguration;
@@ -102,7 +103,9 @@ public class LoadBalancerServiceComponent {
             registerDeployer(LoadBalancerContext.getInstance().getAxisConfiguration(),
                     synEnvService.getSynapseEnvironment());
 
+            // Configure synapse settings
             LoadBalancerConfiguration configuration = LoadBalancerConfiguration.getInstance();
+            SynapseConfigurator.configure(configuration);
 
             if (configuration.isTopologyEventListenerEnabled()) {
                 // Start topology receiver

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/8627efd4/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer1.conf b/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer1.conf
index 7d7b2b8..7800f2c 100755
--- a/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer1.conf
+++ b/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer1.conf
@@ -60,7 +60,7 @@ loadbalancer {
     # Load balancing defaultAlgorithmName class names.
     algorithms {
         round-robin {  # defaultAlgorithmName name
-            class-name: org.apache.stratos.load.balancer.defaultAlgorithmName.RoundRobin;
+            class-name: org.apache.stratos.load.balancer.algorithm.RoundRobin;
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/8627efd4/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer2.conf b/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer2.conf
index d848c46..1a8c153 100755
--- a/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer2.conf
+++ b/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer2.conf
@@ -60,7 +60,7 @@ loadbalancer {
     # Load balancing defaultAlgorithmName class names.
     algorithms {
         round-robin {  # defaultAlgorithmName name
-            class-name: org.apache.stratos.load.balancer.defaultAlgorithmName.RoundRobin;
+            class-name: org.apache.stratos.load.balancer.algorithm.RoundRobin;
         }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/8627efd4/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer3.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer3.conf b/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer3.conf
index 07b92ce..d9f4598 100755
--- a/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer3.conf
+++ b/components/org.apache.stratos.load.balancer/src/test/resources/sample/configuration/loadbalancer3.conf
@@ -60,7 +60,7 @@ loadbalancer {
     # Load balancing defaultAlgorithmName class names.
     algorithms {
         round-robin {  # defaultAlgorithmName name
-            class-name: org.apache.stratos.load.balancer.defaultAlgorithmName.RoundRobin;
+            class-name: org.apache.stratos.load.balancer.algorithm.RoundRobin;
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/8627efd4/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
----------------------------------------------------------------------
diff --git a/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml b/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
index 175a2bd..39c67f3 100644
--- a/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
+++ b/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
@@ -17,20 +17,17 @@
   ~ specific language governing permissions and limitations
   ~ under the License.
   -->
-
-<!-- Default main sequence shipped with the WSO2 ESB -->
 <sequence xmlns="http://ws.apache.org/ns/synapse" name="main" onError="fault">
     <description>The main sequence for the message mediation</description>
     <in>
-        <property name="SERVICE_PREFIX" expression="$axis2:SERVICE_PREFIX"/>
+        <property expression="$axis2:SERVICE_PREFIX" name="SERVICE_PREFIX"/>
         <send>
 	          <endpoint name="tenantAwareLBEndpoint">
-                <class name ="org.apache.stratos.load.balancer.endpoint.TenantAwareLoadBalanceEndpoint">
+                <class name="org.apache.stratos.load.balancer.endpoint.TenantAwareLoadBalanceEndpoint">
                      <parameter name="algorithmClassName">org.apache.stratos.load.balancer.algorithm.RoundRobin</parameter>
                      <parameter name="failover">true</parameter>
                      <parameter name="sessionAffinity">true</parameter>
                      <parameter name="sessionTimeout">90000</parameter>
-                     <!-- parameter name="configuration">$system:loadbalancer.conf</parameter -->
   	            </class>
  	          </endpoint>
         </send>
@@ -42,26 +39,18 @@
         </class>
 
         <!-- Updating location value in response header -->
-        <filter source="$trp:Location" regex=".+">
-            <property name="LB_SP_HOST_NAME" expression="$ctx:SERVICE_PREFIX"
-                      pattern="(^http.?://\b)(.*):(\d*)(.*)" group="2"/>
-            <property name="EP_RESPONSE_LOC_PROTOCOL" expression="$trp:Location"
-                      pattern="(^http.?://\b)(.*):(\d*)(.*)" group="1"/>
-            <property name="EP_RESPONSE_LOC_HOST_NAME" expression="$trp:Location"
-                      pattern="(^http.?://\b)(.*):(\d*)(.*)" group="2"/>
-            <property name="EP_RESPONSE_LOC_PATH" expression="$trp:Location"
-                      pattern="(^http.?://\b)(.*):(\d*)(.*)" group="4"/>
+        <filter regex=".+" source="$trp:Location">
+            <property expression="$ctx:SERVICE_PREFIX" group="2" name="LB_SP_HOST_NAME" pattern="(^http.?://\b)(.*):(\d*)(.*)"/>
+            <property expression="$trp:Location" group="1" name="EP_RESPONSE_LOC_PROTOCOL" pattern="(^http.?://\b)(.*):(\d*)(.*)"/>
+            <property expression="$trp:Location" group="2" name="EP_RESPONSE_LOC_HOST_NAME" pattern="(^http.?://\b)(.*):(\d*)(.*)"/>
+            <property expression="$trp:Location" group="4" name="EP_RESPONSE_LOC_PATH" pattern="(^http.?://\b)(.*):(\d*)(.*)"/>
 
             <switch source="fn:lower-case($ctx:EP_RESPONSE_LOC_PROTOCOL)">
                 <case regex="https://">
-                    <property name="Location"
-                              expression="fn:concat($ctx:EP_RESPONSE_LOC_PROTOCOL,$ctx:LB_HOST_NAME,':',$ctx:LB_HTTPS_PORT,$ctx:EP_RESPONSE_LOC_PATH)"
-                              scope="transport"/>
+                    <property expression="fn:concat($ctx:EP_RESPONSE_LOC_PROTOCOL,$ctx:LB_HOST_NAME,':',$ctx:LB_HTTPS_PORT,$ctx:EP_RESPONSE_LOC_PATH)" name="Location" scope="transport"/>
                 </case>
                 <case regex="http://">
-                    <property name="Location"
-                              expression="fn:concat($ctx:EP_RESPONSE_LOC_PROTOCOL,$ctx:LB_HOST_NAME,':',$ctx:LB_HTTP_PORT,$ctx:EP_RESPONSE_LOC_PATH)"
-                              scope="transport"/>
+                    <property expression="fn:concat($ctx:EP_RESPONSE_LOC_PROTOCOL,$ctx:LB_HOST_NAME,':',$ctx:LB_HTTP_PORT,$ctx:EP_RESPONSE_LOC_PATH)" name="Location" scope="transport"/>
                 </case>
             </switch>
         </filter>