You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by sa...@apache.org on 2013/11/11 13:33:24 UTC
git commit: Incorparating pub/sub model for artifact synchronization
removing ssh based scripts. Added event-subscriber module. STRATOS-103
Updated Branches:
refs/heads/master 6c2509184 -> d01efa6ad
Incorparating pub/sub model for artifact synchronization removing ssh based scripts. Added event-subscriber module. STRATOS-103
Project: http://git-wip-us.apache.org/repos/asf/incubator-stratos/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-stratos/commit/d01efa6a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-stratos/tree/d01efa6a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-stratos/diff/d01efa6a
Branch: refs/heads/master
Commit: d01efa6ad989baebde99b64379e883cef51587bd
Parents: 6c25091
Author: Sajith Kariyawasam <sa...@wso2.com>
Authored: Mon Nov 11 17:57:42 2013 +0530
Committer: Sajith Kariyawasam <sa...@wso2.com>
Committed: Mon Nov 11 17:57:42 2013 +0530
----------------------------------------------------------------------
.../internal/ADCManagementServerComponent.java | 17 ++-
.../stratos/adc/mgt/internal/DataHolder.java | 11 ++
.../mgt/listener/InstanceStatusListener.java | 51 +++++++
.../mgt/publisher/ArtifactUpdatePublisher.java | 39 ++++++
.../mgt/service/RepoNotificationService.java | 62 +--------
.../adc/mgt/utils/PersistenceManager.java | 138 +++++++------------
.../adc/mgt/utils/RepoPasswordMgtUtil.java | 108 +++++++++++++++
.../synchronization/ArtifactUpdatedEvent.java | 29 ++++
.../modules/event-subscriber/pom.xml | 130 +++++++++++++++++
.../event-subscriber/src/main/assembly/bin.xml | 71 ++++++++++
.../src/main/bin/event-subscriber.sh | 28 ++++
.../event/subscriber/ArtifactListener.java | 99 +++++++++++++
.../agent/event/subscriber/EventSubscriber.java | 108 +++++++++++++++
.../event/subscriber/EventSubscriberClient.java | 103 ++++++++++++++
.../cartridge/agent/event/subscriber/Main.java | 83 +++++++++++
.../src/main/resources/jndi.properties | 22 +++
.../src/main/resources/log4j.properties | 37 +++++
.../member-activated-event.json.template | 1 +
.../member-started-event.json.template | 1 +
19 files changed, 992 insertions(+), 146 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
index e7d2c86..53bd3d1 100644
--- a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
@@ -20,10 +20,14 @@ package org.apache.stratos.adc.mgt.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.listener.InstanceStatusListener;
import org.apache.stratos.adc.mgt.utils.CartridgeConfigFileReader;
import org.apache.stratos.adc.mgt.utils.StratosDBUtils;
-import org.osgi.service.component.ComponentContext;
import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.apache.stratos.messaging.broker.publish.EventPublisher;
+import org.apache.stratos.messaging.broker.subscribe.TopicSubscriber;
+import org.apache.stratos.messaging.util.Constants;
+import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.ConfigurationContextService;
@@ -56,7 +60,7 @@ import org.wso2.carbon.utils.ConfigurationContextService;
public class ADCManagementServerComponent {
private static final Log log = LogFactory.getLog(ADCManagementServerComponent.class);
-
+
protected void activate(ComponentContext componentContext) throws Exception {
if (log.isInfoEnabled()) {
log.info("ADC Management Server Component activated");
@@ -65,6 +69,15 @@ public class ADCManagementServerComponent {
try {
CartridgeConfigFileReader.readProperties();
StratosDBUtils.initialize();
+ DataHolder.setEventPublisher(new EventPublisher(Constants.ARTIFACT_SYNCHRONIZATION_TOPIC));
+
+ //initialting the subscriber
+ // Not implemented for M2 release
+ /*TopicSubscriber subscriber = new TopicSubscriber("instance-status");
+ subscriber.setMessageListener(new InstanceStatusListener());
+ Thread tsubscriber = new Thread(subscriber);
+ tsubscriber.start();*/
+
} catch (Exception e) {
log.fatal("Error while initializing the ADC Management Server Component", e);
}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
index 83da5d9..41a9a5b 100644
--- a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
@@ -22,6 +22,7 @@ package org.apache.stratos.adc.mgt.internal;
import org.apache.axis2.context.ConfigurationContext;
import org.wso2.carbon.registry.core.Registry;
import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.apache.stratos.messaging.broker.publish.EventPublisher;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.CarbonUtils;
@@ -35,6 +36,7 @@ public class DataHolder {
private static RealmService realmService;
private static Registry registry;
private static TopologyManagementService topologyMgtService;
+ private static EventPublisher eventPublisher;
public static RealmService getRealmService() {
return realmService;
@@ -77,4 +79,13 @@ public class DataHolder {
public static void setTopologyMgtService(TopologyManagementService topologyMgtService) {
DataHolder.topologyMgtService = topologyMgtService;
}
+
+ public static EventPublisher getEventPublisher() {
+ return eventPublisher;
+ }
+
+ public static void setEventPublisher(EventPublisher eventPublisher) {
+ DataHolder.eventPublisher = eventPublisher;
+ }
+
}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/listener/InstanceStatusListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/listener/InstanceStatusListener.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/listener/InstanceStatusListener.java
new file mode 100644
index 0000000..d8a50dc
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/listener/InstanceStatusListener.java
@@ -0,0 +1,51 @@
+/**
+ *
+ */
+package org.apache.stratos.adc.mgt.listener;
+
+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.apache.stratos.adc.mgt.publisher.ArtifactUpdatePublisher;
+import org.apache.stratos.adc.mgt.utils.PersistenceManager;
+import org.apache.stratos.messaging.event.instance.status.MemberStartedEvent;
+import org.apache.stratos.messaging.util.Constants;
+import org.apache.stratos.messaging.util.Util;
+
+/**
+ * @author wso2
+ *
+ */
+public class InstanceStatusListener implements MessageListener {
+
+ private static final Log log = LogFactory
+ .getLog(InstanceStatusListener.class);
+
+ @Override
+ public void onMessage(Message message) {
+ TextMessage receivedMessage = (TextMessage) message;
+ String clusterId = null;
+
+ log.info(" --- instance status message received --- ");
+ try {
+ String type = message.getStringProperty(Constants.EVENT_CLASS_NAME);
+ // If member started event is received publish artifact update message
+ if (MemberStartedEvent.class.getName().equals(type)) {
+ String json = receivedMessage.getText();
+ MemberStartedEvent event = (MemberStartedEvent) Util
+ .jsonToObject(json, MemberStartedEvent.class);
+ clusterId = event.getClusterId();
+ log.info("--- cluster id is --- : " + clusterId);
+ new ArtifactUpdatePublisher(
+ PersistenceManager.getRepository(clusterId), clusterId)
+ .publish();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/publisher/ArtifactUpdatePublisher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/publisher/ArtifactUpdatePublisher.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/publisher/ArtifactUpdatePublisher.java
new file mode 100644
index 0000000..1c6b59e
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/publisher/ArtifactUpdatePublisher.java
@@ -0,0 +1,39 @@
+/**
+ *
+ */
+package org.apache.stratos.adc.mgt.publisher;
+
+import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.apache.stratos.adc.mgt.repository.Repository;
+import org.apache.stratos.adc.mgt.utils.RepoPasswordMgtUtil;
+import org.apache.stratos.messaging.broker.publish.EventPublisher;
+import org.apache.stratos.messaging.event.artifact.synchronization.ArtifactUpdatedEvent;
+
+/**
+ * @author wso2
+ *
+ */
+public class ArtifactUpdatePublisher {
+
+ private Repository repository;
+ private String clusterId;
+
+ public ArtifactUpdatePublisher(Repository repository, String clusterId) {
+ this.repository = repository;
+ this.clusterId = clusterId;
+ }
+
+ public void publish() {
+ EventPublisher depsyncEventPublisher = DataHolder.getEventPublisher();
+ depsyncEventPublisher.publish(createArtifactUpdateEvent());
+ }
+
+ private ArtifactUpdatedEvent createArtifactUpdateEvent() {
+ ArtifactUpdatedEvent artifactUpdateEvent = new ArtifactUpdatedEvent();
+ artifactUpdateEvent.setClusterId(clusterId);
+ artifactUpdateEvent.setRepoUserName(repository.getUserName());
+ artifactUpdateEvent.setRepoPassword(RepoPasswordMgtUtil.decryptPassword(repository.getPassword())); // Decrypt
+ artifactUpdateEvent.setRepoURL(repository.getUrl());
+ return artifactUpdateEvent;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
index 28542b2..27ffe6b 100644
--- a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
@@ -30,9 +30,13 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.adc.mgt.dao.CartridgeSubscriptionInfo;
import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.apache.stratos.adc.mgt.publisher.ArtifactUpdatePublisher;
import org.apache.stratos.adc.mgt.utils.CartridgeConstants;
import org.apache.stratos.adc.mgt.utils.PersistenceManager;
+import org.apache.stratos.adc.mgt.utils.RepoPasswordMgtUtil;
import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.apache.stratos.messaging.broker.publish.EventPublisher;
+import org.apache.stratos.messaging.event.artifact.synchronization.ArtifactUpdatedEvent;
import org.wso2.carbon.core.deployment.SynchronizeGitRepositoryRequest;
import org.wso2.carbon.utils.CarbonUtils;
@@ -93,63 +97,9 @@ public class RepoNotificationService {
createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
UUID.randomUUID(), subscription.getClusterDomain(),
subscription.getClusterSubdomain());
- //for manager node
- /* if (subscription.getMgtClusterSubDomain() != null && !subscription.getMgtClusterSubDomain().isEmpty()) {
- createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
- UUID.randomUUID(), subscription.getMgtClusterDomain(),
- subscription.getMgtClusterSubDomain());
- }
- else {
- if(log.isDebugEnabled())
- log.debug("Manager node cluster information not found, not sending the SynchronizeGitRepositoryRequest");
- }*/
-
- } else {
-
- // Query DB and get all the IP s for this tenant
- // Invoke update-subscription script
- String appPath = subscription.getBaseDirectory();
- String cartridgePrivateKey = System.getProperty(CartridgeConstants.CARTRIDGE_KEY);
-
- File keyFile = new File(cartridgePrivateKey);
- if (!keyFile.exists()) {
- log.error("The key file does not exist! " + cartridgePrivateKey);
- }
-
- if (subscription != null) {
- TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
-
-
- if (topologyMgtService == null) {
- String msg = " Topology Management Service is null ";
- log.error(msg);
- throw new Exception(msg);
- }
-
- String[] activeIpArray =
- topologyMgtService.getActiveIPs(subscription.getCartridge(),
- subscription.getClusterDomain(),
- subscription.getClusterSubdomain());
- try {
-
- for (String instanceIp : activeIpArray) {
- String command =
- CarbonUtils.getCarbonHome() + File.separator + "bin" +
- File.separator + "update-subscription.sh " +
- instanceIp + " " + appPath + " " +
- cartridgePrivateKey + " /";
- log.info("Update subscription command.... " + command);
- Process proc = Runtime.getRuntime().exec(command);
- proc.waitFor();
- }
-
- } catch (Exception e) {
- log.error("Exception is occurred in notify update operation. Reason : " +
- e.getMessage());
- throw e;
- }
- }
+ } else {
+ new ArtifactUpdatePublisher(subscription.getRepository(),subscription.getClusterDomain()).publish();;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
index 4d8e6ea..ad7fc1c 100644
--- a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
@@ -18,9 +18,16 @@
*/
package org.apache.stratos.adc.mgt.utils;
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
-import org.apache.commons.codec.binary.Base64;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.adc.mgt.dao.CartridgeSubscriptionInfo;
@@ -28,17 +35,6 @@ import org.apache.stratos.adc.mgt.dao.DataCartridge;
import org.apache.stratos.adc.mgt.dao.PortMapping;
import org.apache.stratos.adc.mgt.dao.RepositoryCredentials;
import org.apache.stratos.adc.mgt.repository.Repository;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.securevault.SecretResolver;
-import org.wso2.securevault.SecretResolverFactory;
-
-import javax.crypto.Cipher;
-import javax.crypto.SecretKey;
-import javax.crypto.spec.SecretKeySpec;
-import javax.xml.namespace.QName;
-import java.io.File;
-import java.sql.*;
-import java.util.*;
/**
* This class is responsible for handling persistence
@@ -266,7 +262,7 @@ public class PersistenceManager {
repoCredentials = new RepositoryCredentials();
repoCredentials.setUrl(resultSet.getString("REPO_NAME"));
repoCredentials.setUserName(resultSet.getString("REPO_USER_NAME"));
- repoCredentials.setPassword(decryptPassword(resultSet.getString("REPO_USER_PASSWORD")));
+ repoCredentials.setPassword(RepoPasswordMgtUtil.decryptPassword(resultSet.getString("REPO_USER_PASSWORD")));
}
} catch (Exception s) {
String msg = "Error while sql connection :" + s.getMessage();
@@ -326,7 +322,7 @@ public class PersistenceManager {
con = StratosDBUtils.getConnection();
// persist repo
if (cartridgeSubscriptionInfo.getRepository() != null) {
- String encryptedRepoUserPassword = encryptPassword(cartridgeSubscriptionInfo.getRepository()
+ String encryptedRepoUserPassword = RepoPasswordMgtUtil.encryptPassword(cartridgeSubscriptionInfo.getRepository()
.getPassword());
String insertRepo = "INSERT INTO REPOSITORY (REPO_NAME,STATE,REPO_USER_NAME,REPO_USER_PASSWORD)"
+ " VALUES (?,?,?,?)";
@@ -506,9 +502,13 @@ public class PersistenceManager {
private static void populateSubscription(CartridgeSubscriptionInfo cartridgeSubscriptionInfo, ResultSet resultSet)
throws Exception {
String repoName = resultSet.getString("REPO_NAME");
+ String repoUserName = resultSet.getString("REPO_USER_NAME");
+ String repoPassword = resultSet.getString("REPO_USER_PASSWORD");
if (repoName != null) {
Repository repo = new Repository();
repo.setUrl(repoName);
+ repo.setUserName(repoUserName);
+ repo.setPassword(repoPassword);
cartridgeSubscriptionInfo.setRepository(repo);
}
@@ -754,43 +754,7 @@ public class PersistenceManager {
return instanceIpToStateMap;
}
- public static String getSecurityKey() {
- String securityKey = CartridgeConstants.DEFAULT_SECURITY_KEY;
- OMElement documentElement = null;
- File xmlFile = new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "conf"
- + File.separator + CartridgeConstants.SECURITY_KEY_FILE);
-
- if (xmlFile.exists()) {
- try {
- documentElement = new StAXOMBuilder(xmlFile.getPath()).getDocumentElement();
- } catch (Exception ex) {
- String msg = "Error occurred when parsing the " + xmlFile.getPath() + ".";
- log.error(msg, ex);
- ex.printStackTrace();
- }
- if (documentElement != null) {
- Iterator<?> it = documentElement.getChildrenWithName(new QName(CartridgeConstants.SECURITY_KEY));
- if (it.hasNext()) {
- OMElement securityKeyElement = (OMElement) it.next();
- SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
- String alias = securityKeyElement.getAttributeValue(new QName(CartridgeConstants.ALIAS_NAMESPACE,
- CartridgeConstants.ALIAS_LOCALPART, CartridgeConstants.ALIAS_PREFIX));
-
- if (secretResolver != null && secretResolver.isInitialized()
- && secretResolver.isTokenProtected(alias)) {
- securityKey = "";
- securityKey = secretResolver.resolve(alias);
- // TODO : a proper testing on the secure vault protected
- // user defined encryption key
- }
- }
- }
- }
- else {
- log.error(String.format("File does not exist: %s", xmlFile.getPath()));
- }
- return securityKey;
- }
+
public static void updateInstanceState(String state, String[] ips, String clusterDomain, String clusterSubDomain, String cartridgeType)
throws Exception {
@@ -843,44 +807,42 @@ public class PersistenceManager {
}
}
-
- private static String encryptPassword(String repoUserPassword) {
- String encryptPassword = "";
- String secret = getSecurityKey(); // secret key length must be 16
- SecretKey key;
- Cipher cipher;
- Base64 coder;
- key = new SecretKeySpec(secret.getBytes(), "AES");
+
+
+ public static Repository getRepository(String clusterId) throws Exception {
+
+ Repository repository =null;
+ Connection con = null;
+ PreparedStatement statement = null;
+ ResultSet resultSet = null;
+
try {
- cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
- coder = new Base64();
- cipher.init(Cipher.ENCRYPT_MODE, key);
- byte[] cipherText = cipher.doFinal(repoUserPassword.getBytes());
- encryptPassword = new String(coder.encode(cipherText));
- } catch (Exception e) {
- e.printStackTrace();
+ con = StratosDBUtils.getConnection();
+ String sql = "SELECT REPO_NAME,REPO_USER_NAME,REPO_USER_PASSWORD FROM REPOSITORY R "
+ + "WHERE R.REPO_ID IN (SELECT REPO_ID FROM CARTRIDGE_SUBSCRIPTION C WHERE C.CLUSTER_DOMAIN=? AND C.STATE != 'UNSUBSCRIBED') ";
+
+ statement = con.prepareStatement(sql);
+ statement.setString(1, clusterId);
+ if (log.isDebugEnabled()) {
+ log.debug("Executing query: " + sql);
+ }
+ resultSet = statement.executeQuery();
+ while (resultSet.next()) {
+ repository = new Repository();
+ repository.setUrl(resultSet.getString("REPO_NAME"));
+ repository.setUserName(resultSet.getString("REPO_USER_NAME"));
+ repository.setPassword(RepoPasswordMgtUtil.decryptPassword(resultSet.getString("REPO_USER_PASSWORD")));
+ }
+ } catch (Exception s) {
+ String msg = "Error while sql connection :" + s.getMessage();
+ log.error(msg, s);
+ throw new Exception("An error occurred while listing cartridge information.");
+ } finally {
+ StratosDBUtils.closeAllConnections(con, statement, resultSet);
}
- return encryptPassword;
+ return repository;
}
- private static String decryptPassword(String repoUserPassword) {
- String decryptPassword = "";
- String secret = getSecurityKey(); // secret key length must be 16
- SecretKey key;
- Cipher cipher;
- Base64 coder;
- key = new SecretKeySpec(secret.getBytes(), "AES");
- try {
- cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
- coder = new Base64();
- byte[] encrypted = coder.decode(repoUserPassword.getBytes());
- cipher.init(Cipher.DECRYPT_MODE, key);
- byte[] decrypted = cipher.doFinal(encrypted);
- decryptPassword = new String(decrypted);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return decryptPassword;
- }
+
}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepoPasswordMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepoPasswordMgtUtil.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepoPasswordMgtUtil.java
new file mode 100644
index 0000000..ee82d8e
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepoPasswordMgtUtil.java
@@ -0,0 +1,108 @@
+/**
+ *
+ */
+package org.apache.stratos.adc.mgt.utils;
+
+import java.io.File;
+import java.util.Iterator;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * @author wso2
+ *
+ */
+public class RepoPasswordMgtUtil {
+
+ private static final Log log = LogFactory.getLog(RepoPasswordMgtUtil.class);
+
+ public static String getSecurityKey() {
+ String securityKey = CartridgeConstants.DEFAULT_SECURITY_KEY;
+ OMElement documentElement = null;
+ File xmlFile = new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "conf"
+ + File.separator + CartridgeConstants.SECURITY_KEY_FILE);
+
+ if (xmlFile.exists()) {
+ try {
+ documentElement = new StAXOMBuilder(xmlFile.getPath()).getDocumentElement();
+ } catch (Exception ex) {
+ String msg = "Error occurred when parsing the " + xmlFile.getPath() + ".";
+ log.error(msg, ex);
+ ex.printStackTrace();
+ }
+ if (documentElement != null) {
+ Iterator<?> it = documentElement.getChildrenWithName(new QName(CartridgeConstants.SECURITY_KEY));
+ if (it.hasNext()) {
+ OMElement securityKeyElement = (OMElement) it.next();
+ SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+ String alias = securityKeyElement.getAttributeValue(new QName(CartridgeConstants.ALIAS_NAMESPACE,
+ CartridgeConstants.ALIAS_LOCALPART, CartridgeConstants.ALIAS_PREFIX));
+
+ if (secretResolver != null && secretResolver.isInitialized()
+ && secretResolver.isTokenProtected(alias)) {
+ securityKey = "";
+ securityKey = secretResolver.resolve(alias);
+ // TODO : a proper testing on the secure vault protected
+ // user defined encryption key
+ }
+ }
+ }
+ }
+ else {
+ log.error(String.format("File does not exist: %s", xmlFile.getPath()));
+ }
+ return securityKey;
+ }
+
+ public static String encryptPassword(String repoUserPassword) {
+ String encryptPassword = "";
+ String secret = getSecurityKey(); // secret key length must be 16
+ SecretKey key;
+ Cipher cipher;
+ Base64 coder;
+ key = new SecretKeySpec(secret.getBytes(), "AES");
+ try {
+ cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
+ coder = new Base64();
+ cipher.init(Cipher.ENCRYPT_MODE, key);
+ byte[] cipherText = cipher.doFinal(repoUserPassword.getBytes());
+ encryptPassword = new String(coder.encode(cipherText));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return encryptPassword;
+ }
+
+ public static String decryptPassword(String repoUserPassword) {
+
+ String decryptPassword = "";
+ String secret = getSecurityKey(); // secret key length must be 16
+ SecretKey key;
+ Cipher cipher;
+ Base64 coder;
+ key = new SecretKeySpec(secret.getBytes(), "AES");
+ try {
+ cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
+ coder = new Base64();
+ byte[] encrypted = coder.decode(repoUserPassword.getBytes());
+ cipher.init(Cipher.DECRYPT_MODE, key);
+ byte[] decrypted = cipher.doFinal(encrypted);
+ decryptPassword = new String(decrypted);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return decryptPassword;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/event/artifact/synchronization/ArtifactUpdatedEvent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/event/artifact/synchronization/ArtifactUpdatedEvent.java b/components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/event/artifact/synchronization/ArtifactUpdatedEvent.java
index ac5bde9..18a0318 100644
--- a/components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/event/artifact/synchronization/ArtifactUpdatedEvent.java
+++ b/components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/event/artifact/synchronization/ArtifactUpdatedEvent.java
@@ -25,6 +25,9 @@ package org.apache.stratos.messaging.event.artifact.synchronization;
public class ArtifactUpdatedEvent {
private String clusterId;
private String status;
+ private String repoUserName;
+ private String repoPassword;
+ private String repoURL;
public String getClusterId() {
return clusterId;
@@ -41,4 +44,30 @@ public class ArtifactUpdatedEvent {
public void setStatus(String status) {
this.status = status;
}
+
+ public String getRepoUserName() {
+ return repoUserName;
+ }
+
+ public void setRepoUserName(String repoUserName) {
+ this.repoUserName = repoUserName;
+ }
+
+ public String getRepoPassword() {
+ return repoPassword;
+ }
+
+ public void setRepoPassword(String repoPassword) {
+ this.repoPassword = repoPassword;
+ }
+
+ public String getRepoURL() {
+ return repoURL;
+ }
+
+ public void setRepoURL(String repoURL) {
+ this.repoURL = repoURL;
+ }
+
+
}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/pom.xml
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/pom.xml b/products/cartridge-agent/modules/event-subscriber/pom.xml
new file mode 100644
index 0000000..869e6e4
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/pom.xml
@@ -0,0 +1,130 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied. See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+
+<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>cartidge-agent</artifactId>
+ <version>4.0.0-SNAPSHOT</version>
+ <relativePath>../../pom.xml</relativePath>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>apache-stratos-event-subscriber</artifactId>
+ <name>Apache Stratos - Event Subscriber</name>
+
+ <repositories>
+ <repository>
+ <id>wso2-nexus</id>
+ <name>WSO2 internal Repository</name>
+ <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
+ <releases>
+ <enabled>true</enabled>
+ <updatePolicy>daily</updatePolicy>
+ <checksumPolicy>ignore</checksumPolicy>
+ </releases>
+ </repository>
+ </repositories>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.wso2.andes.wso2</groupId>
+ <artifactId>andes-client</artifactId>
+ <version>0.13.wso2v8</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs.wso2</groupId>
+ <artifactId>geronimo-jms_1.1_spec</artifactId>
+ <version>1.1.0.wso2v1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <version>1.7.5</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>2.2.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.stratos</groupId>
+ <artifactId>org.apache.stratos.messaging</artifactId>
+ <version>4.0.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.0</version>
+ </dependency>
+ <!-- <dependency>
+ <groupId>org.eclipse.jgit</groupId>
+ <artifactId>org.eclipse.jgit</artifactId>
+ <version>2.1.0.wso2v1</version>
+ </dependency>
+ <dependency>
+ <groupId>com.jcraft</groupId>
+ <artifactId>jsch</artifactId>
+ <version>0.1.49.wso2v1</version>
+ </dependency> -->
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.4</version>
+ <configuration>
+ <archive>
+ <manifest>
+ <mainClass>org.apache.stratos.cartridge.agent.event.subscriber.Main</mainClass>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.2.1</version>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/bin.xml</descriptor>
+ </descriptors>
+ <archiverConfig>
+ <fileMode>420</fileMode>
+ <directoryMode>493</directoryMode>
+ <defaultDirectoryMode>493</defaultDirectoryMode>
+ </archiverConfig>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>attached</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/assembly/bin.xml
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/assembly/bin.xml b/products/cartridge-agent/modules/event-subscriber/src/main/assembly/bin.xml
new file mode 100644
index 0000000..9552ad8
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/assembly/bin.xml
@@ -0,0 +1,71 @@
+<!--
+ ~ 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.
+ -->
+
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+ <id>bin</id>
+ <formats>
+ <format>zip</format>
+ </formats>
+ <fileSets>
+ <fileSet>
+ <directory>${project.basedir}/src/main/bin</directory>
+ <outputDirectory>/bin</outputDirectory>
+ <fileMode>0755</fileMode>
+ <includes>
+ <include>event-subscriber.sh</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}/src/main/templates</directory>
+ <outputDirectory>/templates</outputDirectory>
+ <fileMode>0600</fileMode>
+ <includes>
+ <include>member-started-event.json.template</include>
+ <include>member-activated-event.json.template</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}</directory>
+ <outputDirectory>/</outputDirectory>
+ <fileMode>0600</fileMode>
+ <includes>
+ <include>README*</include>
+ <include>LICENSE*</include>
+ <include>NOTICE*</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}/src/main/resources</directory>
+ <outputDirectory>/conf</outputDirectory>
+ <fileMode>0600</fileMode>
+ <includes>
+ <include>jndi.properties</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>/lib</outputDirectory>
+ <useProjectArtifact>true</useProjectArtifact>
+ <scope>runtime</scope>
+ </dependencySet>
+ </dependencySets>
+</assembly>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/bin/event-subscriber.sh
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/bin/event-subscriber.sh b/products/cartridge-agent/modules/event-subscriber/src/main/bin/event-subscriber.sh
new file mode 100644
index 0000000..a372410
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/bin/event-subscriber.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# --------------------------------------------------------------
+#
+# 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.
+#
+# --------------------------------------------------------------
+
+echo "Starting event subscriber..."
+lib_path=./../lib/
+class_path=${lib_path}commons-io-2.0.jar:${lib_path}andes-client-0.13.wso2v8.jar:${lib_path}apache-stratos-event-subscriber-4.0.0-SNAPSHOT.jar:${lib_path}commons-codec-1.8.jar:${lib_path}commons-logging-1.1.1.jar:${lib_path}geronimo-jms_1.1_spec-1.1.0.wso2v1.jar:${lib_path}geronimo-jms_1.1_spec-1.1.jar:${lib_path}gson-2.2.4.jar:${lib_path}log4j-1.2.13.jar:${lib_path}org.apache.log4j-1.2.13.v200706111418.jar:${lib_path}org.apache.stratos.messaging-4.0.0-SNAPSHOT.jar:${lib_path}org.wso2.carbon.logging-4.1.0.jar:${lib_path}slf4j-api-1.7.5.jar:${lib_path}slf4j-log4j12-1.7.5.jar
+
+java -cp $class_path org.apache.stratos.cartridge.agent.event.subscriber.Main ../conf
+echo "Event subscriber completed"
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/ArtifactListener.java
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/ArtifactListener.java b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/ArtifactListener.java
new file mode 100644
index 0000000..3238c5f
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/ArtifactListener.java
@@ -0,0 +1,99 @@
+/**
+ *
+ */
+package org.apache.stratos.cartridge.agent.event.subscriber;
+
+import java.io.File;
+import java.util.Scanner;
+
+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.apache.stratos.messaging.event.artifact.synchronization.ArtifactUpdatedEvent;
+import org.apache.stratos.messaging.util.Constants;
+import org.apache.stratos.messaging.util.Util;
+
+/**
+ * @author wso2
+ *
+ */
+public class ArtifactListener implements MessageListener{
+
+ private static final Log log = LogFactory.getLog(ArtifactListener.class);
+ private String script = "/opt/apache-stratos-cartridge-agent/git.sh";
+ private String launchParams = "/opt/apache-stratos-cartridge-agent/payload/launch-params";
+
+ @Override
+ public void onMessage(Message message) {
+
+ // If cluster id of the node is equal to that of message's, invoke the script
+ TextMessage receivedMessage = (TextMessage) message;
+ log.info(" ++++++++ artifact listener +++++++++");
+ String type = null;
+ String json = null;
+ try {
+ type = receivedMessage.getStringProperty(Constants.EVENT_CLASS_NAME);
+ json = receivedMessage.getText();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ // if(ArtifactUpdatedEvent.class.getName().equals(type)) {
+ ArtifactUpdatedEvent event = (ArtifactUpdatedEvent) Util.jsonToObject(json, ArtifactUpdatedEvent.class);
+ String clusterIdInPayload = readClusterIdFromPayload();
+ String clusterIdInMessage = event.getClusterId();
+ String repoURL = event.getRepoURL();
+ String repoPassword = event.getRepoPassword();
+ String repoUsername = event.getRepoUserName();
+
+ if (log.isDebugEnabled()) {
+ log.debug(" cluster id from message " + clusterIdInMessage + " repo details"
+ + repoURL + repoUsername + repoPassword);
+ }
+
+
+ // execute script
+ if(clusterIdInPayload != null && clusterIdInPayload.equals(clusterIdInMessage)) {
+
+ try {
+ String command = script + " " + repoUsername+ " " +repoPassword+ " "+repoURL+ " /";
+ log.info("Executing command " + command);
+ Process proc = Runtime.getRuntime().exec(command);
+ proc.waitFor();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+ private String readClusterIdFromPayload() {
+ String clusterId = null;
+ // read launch params
+ File file = new File(launchParams);
+
+ try {
+ Scanner scanner = new Scanner(file);
+
+ while (scanner.hasNextLine()) {
+ String line = scanner.nextLine();
+ String[] params = line.split(",");
+ for (String string : params) {
+ String[] var = string.split("=");
+ if("CLUSTER_ID".equals(var[0])){
+ clusterId = var[1];
+ }
+ }
+ }
+ scanner.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return clusterId;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriber.java
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriber.java b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriber.java
new file mode 100644
index 0000000..bef15e5
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriber.java
@@ -0,0 +1,108 @@
+/*
+ * 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.cartridge.agent.event.subscriber;
+
+import com.google.gson.Gson;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.messaging.event.Event;
+import org.apache.stratos.messaging.util.Constants;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import java.io.IOException;
+import java.util.Properties;
+
+/**
+ * A generic topic publisher.
+ */
+public class EventSubscriber {
+ private static final Log log = LogFactory.getLog(EventSubscriber.class);
+
+ private TopicConnection topicConnection;
+ private TopicSession topicSession;
+ private Topic topic;
+ private String mbIpAddress;
+ private int mbPort;
+ private String topicName;
+
+ public EventSubscriber(String mbIpAddress, int mbPort, String topicName) {
+ this.mbIpAddress = mbIpAddress;
+ this.mbPort = mbPort;
+ this.topicName = topicName;
+ }
+
+ private Properties getProperties() throws IOException {
+ Properties properties = new Properties();
+ properties.load(EventSubscriber.class.getClassLoader().getResourceAsStream("jndi.properties"));
+
+ // Set message broker ip and port
+ String connectionFactoryName = properties.get("connectionfactoryName").toString();
+ String key = "connectionfactory." + connectionFactoryName;
+ String connectionFactoryStr = (String) properties.get(key);
+ connectionFactoryStr = connectionFactoryStr.replace("MB-IP-ADDRESS", mbIpAddress);
+ connectionFactoryStr = connectionFactoryStr.replace("MB-PORT", String.valueOf(mbPort));
+ properties.setProperty(key, connectionFactoryStr);
+
+ return properties;
+ }
+
+ public void connect() throws NamingException, JMSException, IOException {
+ // Prepare JNDI properties
+ Properties properties = getProperties();
+ InitialContext ctx = new InitialContext(properties);
+
+ // Lookup connection factory
+ String connectionFactoryName = properties.get("connectionfactoryName").toString();
+ TopicConnectionFactory connectionFactory = (TopicConnectionFactory) ctx.lookup(connectionFactoryName);
+ topicConnection = connectionFactory.createTopicConnection();
+ topicConnection.start();
+ topicSession = topicConnection.createTopicSession(false, QueueSession.AUTO_ACKNOWLEDGE);
+
+ // Create topic
+ topic = topicSession.createTopic(topicName);
+ }
+
+ public void publish(Event event) throws NamingException, JMSException, IOException {
+ Gson gson = new Gson();
+ String json = gson.toJson(event);
+ publish(json, event.getClass().getName());
+ }
+
+ private void publish(String message, String eventClassName) throws NamingException, JMSException, IOException {
+ TextMessage textMessage = topicSession.createTextMessage((String) message);
+ textMessage.setStringProperty(Constants.EVENT_CLASS_NAME, eventClassName);
+ javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);
+ topicPublisher.publish(textMessage);
+
+ if (log.isDebugEnabled()) {
+ log.debug(String.format("Message published: [topic] %s [header] %s [body] %s", topicName, eventClassName, message));
+ }
+ }
+
+ public void close() throws JMSException {
+ // Clean up resources
+ if (topicSession != null)
+ topicSession.close();
+ if (topicConnection != null)
+ topicConnection.close();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriberClient.java
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriberClient.java b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriberClient.java
new file mode 100644
index 0000000..6ee1794
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/EventSubscriberClient.java
@@ -0,0 +1,103 @@
+/*
+ * 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.cartridge.agent.event.subscriber;
+
+import com.google.gson.Gson;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.messaging.event.Event;
+
+import javax.jms.JMSException;
+import javax.naming.NamingException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+/**
+ * Cartridge agent lifecycle implementation.
+ */
+public class EventSubscriberClient {
+ private static final Log log = LogFactory.getLog(EventSubscriberClient.class);
+
+ private String mbIpAddress;
+ private int mbPort;
+ private String eventClassName;
+ private String jsonFilePath;
+
+ public EventSubscriberClient(String mbIpAddress, int mbPort, String eventClassName, String jsonFilePath) {
+ this.mbIpAddress = mbIpAddress;
+ this.mbPort = mbPort;
+ this.eventClassName = eventClassName;
+ this.jsonFilePath = jsonFilePath;
+ }
+
+ private Event jsonToEvent(String jsonFilePath) {
+ FileInputStream fileInputStream = null;
+ try {
+ fileInputStream = new FileInputStream(new File(jsonFilePath));
+ String json = IOUtils.toString(fileInputStream, "UTF-8");
+ if (log.isDebugEnabled()) {
+ log.debug(String.format("Json: %s", json));
+ }
+ Class eventClass = Class.forName(eventClassName);
+ return (Event) new Gson().fromJson(json, eventClass);
+ } catch (FileNotFoundException e) {
+ if (log.isErrorEnabled()) {
+ log.error(e);
+ }
+ throw new RuntimeException(String.format("Could not find json file %s", jsonFilePath));
+ } catch (ClassNotFoundException e) {
+ if (log.isErrorEnabled()) {
+ log.error(e);
+ }
+ throw new RuntimeException(String.format("Event class name %s is not valid", eventClassName));
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error(e);
+ }
+ throw new RuntimeException(String.format("Could not read json file %s", jsonFilePath));
+ }
+ }
+
+ public void run() throws JMSException, NamingException, IOException {
+ if (log.isInfoEnabled()) {
+ log.info("\nEvent publisher started");
+ }
+ Event event = jsonToEvent(jsonFilePath);
+ publishEvent(event);
+ }
+
+
+ private void publishEvent(Event event) throws JMSException, NamingException, IOException {
+ EventSubscriber publisher = new EventSubscriber(mbIpAddress, mbPort, org.apache.stratos.messaging.util.Constants.INSTANCE_STATUS_TOPIC);
+
+ try {
+ publisher.connect();
+ publisher.publish(event);
+ if (log.isInfoEnabled()) {
+ log.info(String.format("Event %s published", eventClassName));
+ }
+ } finally {
+ publisher.close();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/Main.java
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/Main.java b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/Main.java
new file mode 100644
index 0000000..2aa16ae
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/java/org/apache/stratos/cartridge/agent/event/subscriber/Main.java
@@ -0,0 +1,83 @@
+/*
+ * 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.cartridge.agent.event.subscriber;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.messaging.broker.subscribe.TopicSubscriber;
+import org.apache.stratos.messaging.util.Constants;
+
+/**
+ * Event publisher main class.
+ */
+public class Main {
+ private static final Log log = LogFactory.getLog(Main.class);
+
+ public static void main(String[] args) {
+
+
+ log.info(" ************** in main **************** ");
+ log.info(" arg0 : " + args[0]);
+
+ System.setProperty("jndi.properties.dir", args[0]);
+
+ //initialting the subscriber
+ TopicSubscriber subscriber = new TopicSubscriber(Constants.ARTIFACT_SYNCHRONIZATION_TOPIC);
+ subscriber.setMessageListener(new ArtifactListener());
+ Thread tsubscriber = new Thread(subscriber);
+ tsubscriber.start();
+
+ /* try {
+ if (log.isInfoEnabled()) {
+ log.info("Event subscriber started");
+ }
+ if ((args != null) && (args.length == 4)) {
+
+ EventSubscriberClient client = new EventSubscriberClient(args[0], Integer.parseInt(args[1]), args[2], args[3]);
+ client.run();
+ System.exit(0);
+ } else {
+ printInvalidArgs(args);
+ }
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("Could not publish event", e);
+ }
+ printInvalidArgs(args);
+ }
+ System.exit(-1);*/
+ }
+
+ private static void printInvalidArgs(String[] args) {
+ if (log.isErrorEnabled()) {
+ if(args != null) {
+ StringBuilder builder = new StringBuilder();
+ for(String arg : args) {
+ builder.append("[" + arg + "] ");
+ }
+ log.error(String.format("Arguments %s not valid. Event publisher could not be started.", builder.toString()));
+ }
+ else {
+ log.error("Arguments not found. Event publisher could not be started.");
+ }
+ log.error("Expected: mb-ip-address mb-port event-class-name event-json-file-path");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/resources/jndi.properties
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/resources/jndi.properties b/products/cartridge-agent/modules/event-subscriber/src/main/resources/jndi.properties
new file mode 100644
index 0000000..d3b29bc
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/resources/jndi.properties
@@ -0,0 +1,22 @@
+#
+# 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.
+#
+
+connectionfactoryName=topicConnectionfactory
+connectionfactory.topicConnectionfactory=amqp://admin:admin@carbon/carbon?brokerlist='tcp://MB-IP-ADDRESS:MB-PORT'
+java.naming.factory.initial=org.wso2.andes.jndi.PropertiesFileInitialContextFactory
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/resources/log4j.properties b/products/cartridge-agent/modules/event-subscriber/src/main/resources/log4j.properties
new file mode 100644
index 0000000..9b416b5
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/resources/log4j.properties
@@ -0,0 +1,37 @@
+#
+# 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.
+#
+
+# Set root logger level and appenders
+log4j.rootLogger=INFO, CONSOLE_APPENDER, FILE_APPENDER
+
+# CONSOLE_APPENDER is set to be a ConsoleAppender.
+log4j.appender.CONSOLE_APPENDER=org.apache.log4j.ConsoleAppender
+
+# The standard error log where all the warnings, errors and fatal errors will be logged
+log4j.appender.FILE_APPENDER=org.apache.log4j.FileAppender
+log4j.appender.FILE_APPENDER.File=/var/log/apache-stratos/cartridge-agent-event-subscriber.log
+log4j.appender.FILE_APPENDER.layout=org.apache.log4j.PatternLayout
+log4j.appender.FILE_APPENDER.layout.ConversionPattern=%d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n
+log4j.appender.FILE_APPENDER.threshold=DEBUG
+
+# CONSOLE_APPENDER uses PatternLayout.
+log4j.appender.CONSOLE_APPENDER.layout=org.apache.log4j.PatternLayout
+log4j.appender.CONSOLE_APPENDER.layout.ConversionPattern=[%d{ISO8601}] %5p - [%c{1}] %m%n
+
+log4j.logger.org.apache.stratos.cartridge.agent.event.subscriber=DEBUG
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-activated-event.json.template
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-activated-event.json.template b/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-activated-event.json.template
new file mode 100644
index 0000000..e2b2371
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-activated-event.json.template
@@ -0,0 +1 @@
+{"serviceName":"SERVICE_NAME","clusterId":"CLUSTER_ID","memberId":"MEMBER_ID"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/d01efa6a/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-started-event.json.template
----------------------------------------------------------------------
diff --git a/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-started-event.json.template b/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-started-event.json.template
new file mode 100644
index 0000000..e2b2371
--- /dev/null
+++ b/products/cartridge-agent/modules/event-subscriber/src/main/templates/member-started-event.json.template
@@ -0,0 +1 @@
+{"serviceName":"SERVICE_NAME","clusterId":"CLUSTER_ID","memberId":"MEMBER_ID"}
\ No newline at end of file