diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..12be03f --- /dev/null +++ b/.classpath @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..a578182 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + TibcoEMSMonitor-2.1 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/README b/README new file mode 100644 index 0000000..365ab63 --- /dev/null +++ b/README @@ -0,0 +1 @@ +This file was created by IntelliJ IDEA 12.1.6 for binding GitHub repository \ No newline at end of file diff --git a/TibcoEMSMonitor.iml b/TibcoEMSMonitor.iml new file mode 100644 index 0000000..f9884f0 --- /dev/null +++ b/TibcoEMSMonitor.iml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/conf/controller-info.xml b/conf/controller-info.xml new file mode 100755 index 0000000..1bee987 --- /dev/null +++ b/conf/controller-info.xml @@ -0,0 +1,47 @@ + + + + + localhost + + + 8090 + + + false + + + false + + + + + + + + + + + + false + + diff --git a/conf/logging/log4j.xml b/conf/logging/log4j.xml new file mode 100755 index 0000000..86c5305 --- /dev/null +++ b/conf/logging/log4j.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib-jms/SystemTopicSubscriber.java b/lib-jms/SystemTopicSubscriber.java new file mode 100755 index 0000000..bf53d7e --- /dev/null +++ b/lib-jms/SystemTopicSubscriber.java @@ -0,0 +1,251 @@ +package com.appdynamics.tibco.ems.systopicsubscriber; + +/** + * This class will (adopted from the EMS samples) + * be used to durably subscribe to system topics published + * by the Tibco Hawk micro-agent embedded inside the Tibco + * Enterprise Messaging Service (EMS). + * + * Copyright (c) AppDynamics, Inc. + * @author Pranta Das + * February 2, 2012. + * + */ + +import javax.jms.*; +import javax.naming.Context; + +public class SystemTopicSubscriber implements MessageListener, ExceptionListener +{ + static Context jndiContext = null; + + static final String providerContextFactory = + "com.tibco.tibjms.naming.TibjmsInitialContextFactory"; + + static final String defaultProtocol = "tibjmsnaming"; + + static final String defaultProviderURL = + defaultProtocol + "://localhost:7222"; + + String serverUrl = null; + String userName = "admin"; + String password = null; + + String durableName = "ad_subscriber"; + + final static String sysTopics[][] = { + {"$sys.monitor.admin.change", "The administrator has made a change to the configuration."}, + {"$sys.monitor.connection.connect", "A user attempts to connect to the server."}, + {"$sys.monitor.connection.disconnect", "A user connection is disconnected."}, + {"$sys.monitor.connection.error", "An error occurs on a user connection."}, + {"$sys.monitor.consumer.create", "A consumer is created."}, + {"$sys.monitor.consumer.destroy", "A consumer is destroyed."}, + {"$sys.monitor.flow.engaged", "Stored messages rise above a destination’s limit, engaging the flow control feature."}, + {"$sys.monitor.flow.disengaged", "Stored messages fall below a destination’s limit, disengaging the flow control feature."}, + {"$sys.monitor.limits.connection", "Maximum number of hosts or connections is reached."}, + {"$sys.monitor.limits.queue", "Maximum bytes for queue storage is reached."}, + {"$sys.monitor.limits.server", "Server memory limit is reached."}, + {"$sys.monitor.limits.topic", "Maximum bytes for durable subscriptions is reached."}, + {"$sys.monitor.multicast.stats", "The message published contains low-level PGM statistics from the server and multicast daemons."}, + {"$sys.monitor.multicast.status", "A message consumer subscribes or attempts to subscribe to a multicast-enabled topic."}, + {"$sys.monitor.producer.create", "A producer is created."}, + {"$sys.monitor.producer.destroy", "A producer is destroyed."}, + {"$sys.monitor.queue.create", "A dynamic queue is created."}, + {"$sys.monitor.route.connect", "A route connection is attempted."}, + {"$sys.monitor.route.disconnect", "A route connection is disconnected."}, + {"$sys.monitor.route.error", "An error occurs on a route connection."}, + {"$sys.monitor.route.interest", "A change in registered interest occurs on the route."}, + {"$sys.monitor.server.info", "The server sends information about an event; for example, a log file is rotated."}, + {"$sys.monitor.server.warning", "The primary server detects a disconnection from the backup server."}, + {"$sys.monitor.topic.create", "A dynamic topic is created."}, + {"$sys.monitor.tx.action", "A local transaction commits or rolls back."}, + {"$sys.monitor.xa.action", "An XA transaction commits or rolls back."}, + + /** + * In addition to the above, one can subscribe to destination specific monitor topics: + * + * $sys.monitor.D.E.destination + * + * A message is handled by a destination. The name of + * this monitor topic includes two qualifiers (D and E) + * and the name of the destination you wish to monitor. + * D signifies the type of destination and whether to + * include the entire message: + * + * - T : topic, include full message (as a byte array) + * into each event + * - t : topic, do not include full message into each + * event + * - Q : queue, include full message (as a byte array) + * into each event + * - q : queue, do not include full message into each + * event + * + * E signifies the type of event: + * + * - r for receive + * - s for send + * - a for acknowledge + * - p for premature exit of message + * - * for all event types + * + * For example, $sys.monitor.T.r.corp.News is the + * topic for monitoring any received messages to the topic + * named corp.News. The message body of any received + * messages is included in monitor messages on this + * topic. The topic $sys.monitor.q.*.corp.* monitors + * all message events (send, receive, acknowledge) for all + * queues matching the name corp.*. The message body + * is not included in this topic's messages. + */ + }; + + public static void main(String[] args) throws Exception + { + new SystemTopicSubscriber(args); + + } + + public SystemTopicSubscriber(String[] args) { + + parseArgs(args); + + TopicConnectionFactory factory = null; + + TopicConnection connection = null; + + TopicSession session = null; + + javax.jms.Topic topic = null; + + TopicSubscriber subscriber = null; + + try + + { + + factory = new com.tibco.tibjms.TibjmsTopicConnectionFactory(serverUrl); + + connection = factory.createTopicConnection(userName,password); + + session = connection.createTopicSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + for (int i=0; i < sysTopics.length; i++) + { + + /* + * Lookup the topic and subscribe to it. + */ + try + { + topic = session.createTopic(sysTopics[i][0]); } + catch(Exception e) + { + System.out.println("Unable to create topic:"+sysTopics[i][0]); + continue; + } + + System.err.println("Creating a durable subscriber to topic: "+sysTopics[i][0]); + + subscriber = session.createDurableSubscriber(topic,durableName+sysTopics[i][0]); + + subscriber.setMessageListener(this); + } + + connection.setExceptionListener(this); + connection.start(); + + /* read topic messages */ + System.out.print("Waiting for messages"); + + while(true) + { + Thread.sleep(1000); + System.out.print("."); + + } + + //connection.close(); + + } + catch(Throwable e) + { + e.printStackTrace(); + System.exit(0); + } + } + + /** + This method is called asynchronously by JMS when a message arrives + at the topic. Client applications must not throw any exceptions in + the onMessage method. + @param message A JMS message. + */ + public void onMessage(Message message) + { + com.tibco.tibjms.TibjmsMapMessage msg = (com.tibco.tibjms.TibjmsMapMessage) message; + System.out.println("received: " + msg.toString()); + } + + /** + This method is called asynchronously by JMS when some error occurs. + When using an asynchronous message listener it is recommended to use + an exception listener also since JMS have no way to report errors + otherwise. + @param exception A JMS exception. + */ + public void onException(JMSException exception) + { + System.err.println("something bad happended: " + exception); + } + void usage() + { + System.err.println("\nUsage: java SystemTopicSubscriber [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } +} \ No newline at end of file diff --git a/lib-jms/jms.jar b/lib-jms/jms.jar new file mode 100755 index 0000000..dad227f Binary files /dev/null and b/lib-jms/jms.jar differ diff --git a/lib-jms/tibjms.jar b/lib-jms/tibjms.jar new file mode 100755 index 0000000..e41d7a7 Binary files /dev/null and b/lib-jms/tibjms.jar differ diff --git a/lib-tibco/jms.jar b/lib-tibco/jms.jar new file mode 100755 index 0000000..f83af25 Binary files /dev/null and b/lib-tibco/jms.jar differ diff --git a/lib-tibco/slf4j-api-1.4.2.jar b/lib-tibco/slf4j-api-1.4.2.jar new file mode 100755 index 0000000..d144dca Binary files /dev/null and b/lib-tibco/slf4j-api-1.4.2.jar differ diff --git a/lib-tibco/slf4j-simple-1.4.2.jar b/lib-tibco/slf4j-simple-1.4.2.jar new file mode 100755 index 0000000..d2e332d Binary files /dev/null and b/lib-tibco/slf4j-simple-1.4.2.jar differ diff --git a/lib-tibco/tibcrypt.jar b/lib-tibco/tibcrypt.jar new file mode 100755 index 0000000..36d3fd4 Binary files /dev/null and b/lib-tibco/tibcrypt.jar differ diff --git a/lib-tibco/tibemsd_sec.jar b/lib-tibco/tibemsd_sec.jar new file mode 100755 index 0000000..75f9be8 Binary files /dev/null and b/lib-tibco/tibemsd_sec.jar differ diff --git a/lib-tibco/tibjms.jar b/lib-tibco/tibjms.jar new file mode 100755 index 0000000..e41d7a7 Binary files /dev/null and b/lib-tibco/tibjms.jar differ diff --git a/lib-tibco/tibjmsadmin.jar b/lib-tibco/tibjmsadmin.jar new file mode 100755 index 0000000..b85c3c2 Binary files /dev/null and b/lib-tibco/tibjmsadmin.jar differ diff --git a/lib-tibco/tibjmsapps.jar b/lib-tibco/tibjmsapps.jar new file mode 100755 index 0000000..b2052d8 Binary files /dev/null and b/lib-tibco/tibjmsapps.jar differ diff --git a/lib-tibco/tibjmsufo.jar b/lib-tibco/tibjmsufo.jar new file mode 100755 index 0000000..62b7857 Binary files /dev/null and b/lib-tibco/tibjmsufo.jar differ diff --git a/lib-tibco/tibrvjms.jar b/lib-tibco/tibrvjms.jar new file mode 100755 index 0000000..7e67b36 Binary files /dev/null and b/lib-tibco/tibrvjms.jar differ diff --git a/lib/README b/lib/README new file mode 100755 index 0000000..1e73d51 --- /dev/null +++ b/lib/README @@ -0,0 +1 @@ +Ant task execution complains that the tools.jar is missing. We have added an empty tools.jar to suppress these warning messages from appearing in the task execution output. \ No newline at end of file diff --git a/lib/mysql.jar b/lib/mysql.jar new file mode 100644 index 0000000..e460f97 Binary files /dev/null and b/lib/mysql.jar differ diff --git a/lib/tools.jar b/lib/tools.jar new file mode 100755 index 0000000..e772cd4 Binary files /dev/null and b/lib/tools.jar differ diff --git a/lib/tp/ant-antlr.jar b/lib/tp/ant-antlr.jar new file mode 100755 index 0000000..3702b64 Binary files /dev/null and b/lib/tp/ant-antlr.jar differ diff --git a/lib/tp/ant-apache-bcel.jar b/lib/tp/ant-apache-bcel.jar new file mode 100755 index 0000000..6821049 Binary files /dev/null and b/lib/tp/ant-apache-bcel.jar differ diff --git a/lib/tp/ant-apache-bsf.jar b/lib/tp/ant-apache-bsf.jar new file mode 100755 index 0000000..1b0daf9 Binary files /dev/null and b/lib/tp/ant-apache-bsf.jar differ diff --git a/lib/tp/ant-apache-log4j.jar b/lib/tp/ant-apache-log4j.jar new file mode 100755 index 0000000..32de4b0 Binary files /dev/null and b/lib/tp/ant-apache-log4j.jar differ diff --git a/lib/tp/ant-apache-oro.jar b/lib/tp/ant-apache-oro.jar new file mode 100755 index 0000000..a0a2435 Binary files /dev/null and b/lib/tp/ant-apache-oro.jar differ diff --git a/lib/tp/ant-apache-regexp.jar b/lib/tp/ant-apache-regexp.jar new file mode 100755 index 0000000..2214d89 Binary files /dev/null and b/lib/tp/ant-apache-regexp.jar differ diff --git a/lib/tp/ant-apache-resolver.jar b/lib/tp/ant-apache-resolver.jar new file mode 100755 index 0000000..54388ed Binary files /dev/null and b/lib/tp/ant-apache-resolver.jar differ diff --git a/lib/tp/ant-commons-logging.jar b/lib/tp/ant-commons-logging.jar new file mode 100755 index 0000000..f2eaa8a Binary files /dev/null and b/lib/tp/ant-commons-logging.jar differ diff --git a/lib/tp/ant-commons-net.jar b/lib/tp/ant-commons-net.jar new file mode 100755 index 0000000..0208417 Binary files /dev/null and b/lib/tp/ant-commons-net.jar differ diff --git a/lib/tp/ant-jai.jar b/lib/tp/ant-jai.jar new file mode 100755 index 0000000..4ce81f0 Binary files /dev/null and b/lib/tp/ant-jai.jar differ diff --git a/lib/tp/ant-javamail.jar b/lib/tp/ant-javamail.jar new file mode 100755 index 0000000..1d8a3eb Binary files /dev/null and b/lib/tp/ant-javamail.jar differ diff --git a/lib/tp/ant-jdepend.jar b/lib/tp/ant-jdepend.jar new file mode 100755 index 0000000..4e7d2be Binary files /dev/null and b/lib/tp/ant-jdepend.jar differ diff --git a/lib/tp/ant-jmf.jar b/lib/tp/ant-jmf.jar new file mode 100755 index 0000000..536d507 Binary files /dev/null and b/lib/tp/ant-jmf.jar differ diff --git a/lib/tp/ant-jsch.jar b/lib/tp/ant-jsch.jar new file mode 100755 index 0000000..394fdef Binary files /dev/null and b/lib/tp/ant-jsch.jar differ diff --git a/lib/tp/ant-junit.jar b/lib/tp/ant-junit.jar new file mode 100755 index 0000000..063cce4 Binary files /dev/null and b/lib/tp/ant-junit.jar differ diff --git a/lib/tp/ant-launcher.jar b/lib/tp/ant-launcher.jar new file mode 100755 index 0000000..7c8f849 Binary files /dev/null and b/lib/tp/ant-launcher.jar differ diff --git a/lib/tp/ant-netrexx.jar b/lib/tp/ant-netrexx.jar new file mode 100755 index 0000000..9f368ac Binary files /dev/null and b/lib/tp/ant-netrexx.jar differ diff --git a/lib/tp/ant-nodeps.jar b/lib/tp/ant-nodeps.jar new file mode 100755 index 0000000..98b5518 Binary files /dev/null and b/lib/tp/ant-nodeps.jar differ diff --git a/lib/tp/ant-starteam.jar b/lib/tp/ant-starteam.jar new file mode 100755 index 0000000..ffd7104 Binary files /dev/null and b/lib/tp/ant-starteam.jar differ diff --git a/lib/tp/ant-stylebook.jar b/lib/tp/ant-stylebook.jar new file mode 100755 index 0000000..e78ed49 Binary files /dev/null and b/lib/tp/ant-stylebook.jar differ diff --git a/lib/tp/ant-swing.jar b/lib/tp/ant-swing.jar new file mode 100755 index 0000000..641c5e9 Binary files /dev/null and b/lib/tp/ant-swing.jar differ diff --git a/lib/tp/ant-testutil.jar b/lib/tp/ant-testutil.jar new file mode 100755 index 0000000..10f5230 Binary files /dev/null and b/lib/tp/ant-testutil.jar differ diff --git a/lib/tp/ant-trax.jar b/lib/tp/ant-trax.jar new file mode 100755 index 0000000..7c4d564 Binary files /dev/null and b/lib/tp/ant-trax.jar differ diff --git a/lib/tp/ant-weblogic.jar b/lib/tp/ant-weblogic.jar new file mode 100755 index 0000000..aa7d318 Binary files /dev/null and b/lib/tp/ant-weblogic.jar differ diff --git a/lib/tp/ant.jar b/lib/tp/ant.jar new file mode 100755 index 0000000..7047177 Binary files /dev/null and b/lib/tp/ant.jar differ diff --git a/lib/tp/commons-codec-1.3.jar b/lib/tp/commons-codec-1.3.jar new file mode 100755 index 0000000..957b675 Binary files /dev/null and b/lib/tp/commons-codec-1.3.jar differ diff --git a/lib/tp/commons-fileupload-1.2.1.jar b/lib/tp/commons-fileupload-1.2.1.jar new file mode 100755 index 0000000..aa209b3 Binary files /dev/null and b/lib/tp/commons-fileupload-1.2.1.jar differ diff --git a/lib/tp/commons-httpclient-3.1.jar b/lib/tp/commons-httpclient-3.1.jar new file mode 100755 index 0000000..7c59774 Binary files /dev/null and b/lib/tp/commons-httpclient-3.1.jar differ diff --git a/lib/tp/commons-io-1.4.jar b/lib/tp/commons-io-1.4.jar new file mode 100755 index 0000000..133dc6c Binary files /dev/null and b/lib/tp/commons-io-1.4.jar differ diff --git a/lib/tp/commons-logging-1.1.1.jar b/lib/tp/commons-logging-1.1.1.jar new file mode 100755 index 0000000..8758a96 Binary files /dev/null and b/lib/tp/commons-logging-1.1.1.jar differ diff --git a/lib/tp/commons-logging-adapters-1.1.1.jar b/lib/tp/commons-logging-adapters-1.1.1.jar new file mode 100755 index 0000000..2f23c35 Binary files /dev/null and b/lib/tp/commons-logging-adapters-1.1.1.jar differ diff --git a/lib/tp/commons-logging-api-1.1.1.jar b/lib/tp/commons-logging-api-1.1.1.jar new file mode 100755 index 0000000..bd45116 Binary files /dev/null and b/lib/tp/commons-logging-api-1.1.1.jar differ diff --git a/lib/tp/jetty-6.1.3.jar b/lib/tp/jetty-6.1.3.jar new file mode 100755 index 0000000..ad3d529 Binary files /dev/null and b/lib/tp/jetty-6.1.3.jar differ diff --git a/lib/tp/jetty-util-6.1.3.jar b/lib/tp/jetty-util-6.1.3.jar new file mode 100755 index 0000000..101543b Binary files /dev/null and b/lib/tp/jetty-util-6.1.3.jar differ diff --git a/lib/tp/libsigar-amd64-freebsd-6.so b/lib/tp/libsigar-amd64-freebsd-6.so new file mode 100755 index 0000000..3e94f0d Binary files /dev/null and b/lib/tp/libsigar-amd64-freebsd-6.so differ diff --git a/lib/tp/libsigar-amd64-linux.so b/lib/tp/libsigar-amd64-linux.so new file mode 100755 index 0000000..5a2e4c2 Binary files /dev/null and b/lib/tp/libsigar-amd64-linux.so differ diff --git a/lib/tp/libsigar-amd64-solaris.so b/lib/tp/libsigar-amd64-solaris.so new file mode 100755 index 0000000..6396482 Binary files /dev/null and b/lib/tp/libsigar-amd64-solaris.so differ diff --git a/lib/tp/libsigar-ia64-hpux-11.sl b/lib/tp/libsigar-ia64-hpux-11.sl new file mode 100755 index 0000000..d92ea4a Binary files /dev/null and b/lib/tp/libsigar-ia64-hpux-11.sl differ diff --git a/lib/tp/libsigar-ia64-linux.so b/lib/tp/libsigar-ia64-linux.so new file mode 100755 index 0000000..2bd2fc8 Binary files /dev/null and b/lib/tp/libsigar-ia64-linux.so differ diff --git a/lib/tp/libsigar-pa-hpux-11.sl b/lib/tp/libsigar-pa-hpux-11.sl new file mode 100755 index 0000000..0dfd8a1 Binary files /dev/null and b/lib/tp/libsigar-pa-hpux-11.sl differ diff --git a/lib/tp/libsigar-ppc-aix-5.so b/lib/tp/libsigar-ppc-aix-5.so new file mode 100755 index 0000000..7d4b519 Binary files /dev/null and b/lib/tp/libsigar-ppc-aix-5.so differ diff --git a/lib/tp/libsigar-ppc-linux.so b/lib/tp/libsigar-ppc-linux.so new file mode 100755 index 0000000..4394b1b Binary files /dev/null and b/lib/tp/libsigar-ppc-linux.so differ diff --git a/lib/tp/libsigar-ppc64-aix-5.so b/lib/tp/libsigar-ppc64-aix-5.so new file mode 100755 index 0000000..35fd828 Binary files /dev/null and b/lib/tp/libsigar-ppc64-aix-5.so differ diff --git a/lib/tp/libsigar-ppc64-linux.so b/lib/tp/libsigar-ppc64-linux.so new file mode 100755 index 0000000..a1ba252 Binary files /dev/null and b/lib/tp/libsigar-ppc64-linux.so differ diff --git a/lib/tp/libsigar-s390x-linux.so b/lib/tp/libsigar-s390x-linux.so new file mode 100755 index 0000000..c275f4a Binary files /dev/null and b/lib/tp/libsigar-s390x-linux.so differ diff --git a/lib/tp/libsigar-sparc-solaris.so b/lib/tp/libsigar-sparc-solaris.so new file mode 100755 index 0000000..aa847d2 Binary files /dev/null and b/lib/tp/libsigar-sparc-solaris.so differ diff --git a/lib/tp/libsigar-sparc64-solaris.so b/lib/tp/libsigar-sparc64-solaris.so new file mode 100755 index 0000000..6c4fe80 Binary files /dev/null and b/lib/tp/libsigar-sparc64-solaris.so differ diff --git a/lib/tp/libsigar-universal-macosx.dylib b/lib/tp/libsigar-universal-macosx.dylib new file mode 100755 index 0000000..27ab107 Binary files /dev/null and b/lib/tp/libsigar-universal-macosx.dylib differ diff --git a/lib/tp/libsigar-universal64-macosx.dylib b/lib/tp/libsigar-universal64-macosx.dylib new file mode 100755 index 0000000..0c721fe Binary files /dev/null and b/lib/tp/libsigar-universal64-macosx.dylib differ diff --git a/lib/tp/libsigar-x86-freebsd-5.so b/lib/tp/libsigar-x86-freebsd-5.so new file mode 100755 index 0000000..8c50c61 Binary files /dev/null and b/lib/tp/libsigar-x86-freebsd-5.so differ diff --git a/lib/tp/libsigar-x86-freebsd-6.so b/lib/tp/libsigar-x86-freebsd-6.so new file mode 100755 index 0000000..f080027 Binary files /dev/null and b/lib/tp/libsigar-x86-freebsd-6.so differ diff --git a/lib/tp/libsigar-x86-linux.so b/lib/tp/libsigar-x86-linux.so new file mode 100755 index 0000000..a0b64ed Binary files /dev/null and b/lib/tp/libsigar-x86-linux.so differ diff --git a/lib/tp/libsigar-x86-solaris.so b/lib/tp/libsigar-x86-solaris.so new file mode 100755 index 0000000..c6452e5 Binary files /dev/null and b/lib/tp/libsigar-x86-solaris.so differ diff --git a/lib/tp/log4j-1.2.15.jar b/lib/tp/log4j-1.2.15.jar new file mode 100755 index 0000000..c930a6a Binary files /dev/null and b/lib/tp/log4j-1.2.15.jar differ diff --git a/lib/tp/log4j.jar b/lib/tp/log4j.jar new file mode 100755 index 0000000..c7111d8 Binary files /dev/null and b/lib/tp/log4j.jar differ diff --git a/lib/tp/servlet-api-2.5-6.1.3.jar b/lib/tp/servlet-api-2.5-6.1.3.jar new file mode 100755 index 0000000..8e9777d Binary files /dev/null and b/lib/tp/servlet-api-2.5-6.1.3.jar differ diff --git a/lib/tp/sigar-amd64-winnt.dll b/lib/tp/sigar-amd64-winnt.dll new file mode 100755 index 0000000..1ec8a03 Binary files /dev/null and b/lib/tp/sigar-amd64-winnt.dll differ diff --git a/lib/tp/sigar-x86-winnt.dll b/lib/tp/sigar-x86-winnt.dll new file mode 100755 index 0000000..6afdc01 Binary files /dev/null and b/lib/tp/sigar-x86-winnt.dll differ diff --git a/lib/tp/sigar.jar b/lib/tp/sigar.jar new file mode 100755 index 0000000..58c733c Binary files /dev/null and b/lib/tp/sigar.jar differ diff --git a/lib/tp/singularity-xml.jar b/lib/tp/singularity-xml.jar new file mode 100755 index 0000000..fd4974a Binary files /dev/null and b/lib/tp/singularity-xml.jar differ diff --git a/lib/tp/xercesImpl.jar b/lib/tp/xercesImpl.jar new file mode 100755 index 0000000..e0a4c2e Binary files /dev/null and b/lib/tp/xercesImpl.jar differ diff --git a/lib/tp/xml-apis.jar b/lib/tp/xml-apis.jar new file mode 100755 index 0000000..d42c0ea Binary files /dev/null and b/lib/tp/xml-apis.jar differ diff --git a/libs-other/Screen shot 2012-02-01 at 12.01.17 PM.png b/libs-other/Screen shot 2012-02-01 at 12.01.17 PM.png new file mode 100755 index 0000000..2c57d8b Binary files /dev/null and b/libs-other/Screen shot 2012-02-01 at 12.01.17 PM.png differ diff --git a/libs-other/log4j-1.2.15.jar b/libs-other/log4j-1.2.15.jar new file mode 100755 index 0000000..c930a6a Binary files /dev/null and b/libs-other/log4j-1.2.15.jar differ diff --git a/libs-other/monitor.xml b/libs-other/monitor.xml new file mode 100755 index 0000000..0db0423 --- /dev/null +++ b/libs-other/monitor.xml @@ -0,0 +1,32 @@ + + MysqlMonitor + managed + Monitors Mysql database system + + + + periodic + 60 + Mysql Monitor Run Task + Mysql Monitor Task + Mysql Monitor Task + java + 60 + + + + + + + + + + + mysql.jar;mysql-connector-java-5.1.17-bin.jar + com.singularity.ee.agent.systemagent.monitors.database.mysql.MysqlMonitor + + + \ No newline at end of file diff --git a/libs-other/mysql-connector-java-5.1.17-bin.jar b/libs-other/mysql-connector-java-5.1.17-bin.jar new file mode 100755 index 0000000..026dc39 Binary files /dev/null and b/libs-other/mysql-connector-java-5.1.17-bin.jar differ diff --git a/libs-other/mysql.jar b/libs-other/mysql.jar new file mode 100755 index 0000000..8d6899e Binary files /dev/null and b/libs-other/mysql.jar differ diff --git a/libs-other/singularity-xml.jar b/libs-other/singularity-xml.jar new file mode 100755 index 0000000..fd4974a Binary files /dev/null and b/libs-other/singularity-xml.jar differ diff --git a/machineagent.jar b/machineagent.jar new file mode 100755 index 0000000..7828936 Binary files /dev/null and b/machineagent.jar differ diff --git a/monitor.xml b/monitor.xml new file mode 100644 index 0000000..700b817 --- /dev/null +++ b/monitor.xml @@ -0,0 +1,41 @@ + + TibcoEMSMonitorMonitor + managed + Monitors Tibco EMS + + + + periodic + 60 + Tibco EMS Monitor Run Task + Tibco EMS Monitor Task + Tibco EMS Task + java + 60 + + + + + + + + + + + + + ../../bin:mysql.jar:../../machineagent.jar:jms.jar:slf4j-api-1.4.2.jar:slf4j-simple-1.4.2.jar:tibcrypt.jar:tibemsd_sec.jar:tibjms.jar:tibjmsadmin.jar:tibjmsapps.jar:tibjmsufo.jar:tibrvjms.jar + com.singularity.ee.agent.systemagent.monitors.common.TibcoEMSMonitor3 + + + diff --git a/monitors/HardwareMonitor/aix-stat.sh b/monitors/HardwareMonitor/aix-stat.sh new file mode 100755 index 0000000..0cc442a --- /dev/null +++ b/monitors/HardwareMonitor/aix-stat.sh @@ -0,0 +1,266 @@ +#!/bin/sh +# +# Monitors CPU, Memory, Network and Disks on AIX +# +# version 1.0 +######################################### + +# Set unspecified system commands + NET_TIME=60 + + PATH=$PATH:/bin:/usr/sbin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin + + if [ -f /usr/bin/which ] + then + WHICH="/usr/bin/which" + else + echo "FATAL: Can't set system monitor tools" + exit 1 + fi + + if [ `$WHICH awk` ] + then + AWK=`$WHICH awk` + else + echo "FATAL: Can't find awk" + exit 1 + fi + + if [ `$WHICH grep` ] + then + GREP=`$WHICH grep` + else + echo "FATAL: Can't find grep" + exit 1 + fi + + if [ `$WHICH ps` ] + then + PS=`$WHICH ps` + else + echo "FATAL: Can't find ps" + exit 1 + fi + + if [ `$WHICH cat` ] + then + CAT=`$WHICH cat` + else + echo "FATAL: Can't find cat" + exit 1 + fi + + if [ `$WHICH expr` ] + then + EXPR=`$WHICH expr` + else + echo "FATAL: Can't find expr" + exit 1 + fi + + if [ `$WHICH netstat` ] + then + NETSTAT=`$WHICH netstat` + else + echo "FATAL: Can't find netstat" + exit 1 + fi + + if [ `$WHICH clear` ] + then + CLEAR=`$WHICH clear` + else + echo "FATAL: Can't find clear" + exit 1 + fi + + if [ `$WHICH iostat` ] + then + IOSTAT=`$WHICH iostat` + else + echo "FATAL: Can't find iostat" + exit 1 + fi + + if [ `$WHICH tail` ] + then + TAIL=`$WHICH tail` + else +# removed special character at beginning of next line + echo "FATAL: Can't find tail" + exit 1 + fi + + if [ `$WHICH sleep` ] + then + SLEEP=`$WHICH sleep` + else + exit 1 + fi + + if [ `$WHICH vmstat` ] + then + VMSTAT=`$WHICH vmstat` + else + exit 1 + fi + + if [ `$WHICH pagesize` ] + then + PAGESIZE=`$WHICH pagesize` + else + exit 1 + fi + + if [ `$WHICH sleep` ] + then + SLEEP=`$WHICH sleep` + else + exit 1 + fi + + if [ `$WHICH printf` ] + then + PRINTF=`$WHICH printf` + else + exit 1 + fi + + if [ `$WHICH lsattr` ] + then + LSATTR=`$WHICH lsattr` + else + exit 1 + fi + +while [ 1 ]; do + +# CPU. background process to collect statistics per 60 sec + $IOSTAT -t $(($NET_TIME - 1)) 2 | $TAIL -1 > /tmp/iostat_cpu & + +# Memory. background process to collect statistics per 60 sec + $VMSTAT $(($NET_TIME - 1)) 2 | $TAIL -1 > /tmp/vmstat_mem & + +# Disk. background process to collect statistics per 60 sec + $IOSTAT -sd $(($NET_TIME - 1)) 2 | $GREP '^ ' | $TAIL -1 > /tmp/iostat_disk & + +# NETWORK + + $NETSTAT -v > /tmp/net_all + + TMP_NET_PACKETS1_IN=`$CAT /tmp/net_all | $GREP "^Packets:" | $AWK '{ sum+=$4}END{printf ( "%i\n",sum )}'` + TMP_NET_PACKETS1_OUT=`$CAT /tmp/net_all | $GREP "^Packets:" | $AWK '{ sum+=$2}END{printf ( "%i\n",sum )}'` + + TMP_NET_BYTES1_IN=`$CAT /tmp/net_all | $GREP "^Bytes:" | $AWK '{ sum+=$4}END{printf ( "%i\n", sum )}'` + TMP_NET_BYTES1_OUT=`$CAT /tmp/net_all | $GREP "^Bytes:" | $AWK '{ sum+=$2}END{printf ( "%i\n",sum )}'` + +# Calculate again to find network usage + $SLEEP $NET_TIME + + $NETSTAT -v > /tmp/net_all + + TMP_NET_PACKETS2_IN=`$CAT /tmp/net_all | $GREP "^Packets:" | $AWK '{ sum+=$4}END{printf ( "%i\n",sum )}'` + TMP_NET_PACKETS2_OUT=`$CAT /tmp/net_all | $GREP "^Packets:" | $AWK '{ sum+=$2}END{printf ( "%i\n",sum )}'` + + TMP_NET_BYTES2_IN=`$CAT /tmp/net_all | $GREP "^Bytes:" | $AWK '{ sum+=$4}END{printf ( "%i\n",sum )}'` + TMP_NET_BYTES2_OUT=`$CAT /tmp/net_all | $GREP "^Bytes:" | $AWK '{ sum+=$2}END{printf ( "%i\n",sum )}'` + + TMP_NET_PACKETS_OUT=`$EXPR $TMP_NET_PACKETS2_OUT - $TMP_NET_PACKETS1_OUT` + TMP_NET_PACKETS_IN=`$EXPR $TMP_NET_PACKETS2_IN - $TMP_NET_PACKETS1_IN` + + TMP_NET_BYTES_IN=`$EXPR $TMP_NET_BYTES2_IN - $TMP_NET_BYTES1_IN` + TMP_NET_BYTES_OUT=`$EXPR $TMP_NET_BYTES2_OUT - $TMP_NET_BYTES1_OUT` + + TMP_NET_BYTES_IN_KB=`$EXPR $TMP_NET_BYTES_IN / 1024` + TMP_NET_BYTES_OUT_KB=`$EXPR $TMP_NET_BYTES_OUT / 1024` + + NET_PACKETS_IN=`$EXPR $TMP_NET_PACKETS_IN / $NET_TIME` + NET_PACKETS_OUT=`$EXPR $TMP_NET_PACKETS_OUT / $NET_TIME` + + NET_KBYTES_IN=`$EXPR $TMP_NET_BYTES_IN_KB / $NET_TIME` + NET_KBYTES_OUT=`$EXPR $TMP_NET_BYTES_OUT_KB / $NET_TIME` + +# CPU + TMP_CPU_IDLE=`$CAT /tmp/iostat_cpu | $AWK '{print $5}'` + CPU_IDLE=`$PRINTF "%0.f\n" $TMP_CPU_IDLE` + CPU_BUSY=$((100 - $CPU_IDLE)) + +# MEMORY +# checking existence and size > 0 of vmstat_mem +if [ -f /tmp/vmstat_mem -a -s /tmp/vmstat_mem ] +then + MEM_TOTAL_MB=$((`$LSATTR -E -l sys0 -a realmem | $AWK '{print $2}'` / 1024)) + TMP_PAGESIZE=`$PAGESIZE` + MEM_FREE_MB=$((`$CAT /tmp/vmstat_mem | $AWK '{print $4}'` \* $TMP_PAGESIZE / 1024 / 1024)) + MEM_USED_MB=$((MEM_TOTAL_MB - MEM_FREE_MB)) + + TMP_MEM_USED_PC=`$EXPR $MEM_USED_MB \* 100` + MEM_USED_PC=`$EXPR $TMP_MEM_USED_PC / $MEM_TOTAL_MB` + MEM_FREE_PC=`$EXPR 100 - $MEM_USED_PC` +# filling emtpy values with 0 +else + MEM_TOTAL_MB=0 + MEM_USED_MB=0 + MEM_FREE_MB=0 + MEM_USED_PC=0 + MEM_FREE_PC=0 +fi + +# Disk +# checking existence and size > 0 of iostat_disk +if [ -f /tmp/iostat_disk -a -s /tmp/iostat_disk ] +then + # changing following line + # TMP_READS_KB=`$CAT /tmp/iostat_disk | $AWK '{print $3}'` + TMP_READS_KB=`$CAT /tmp/iostat_disk | $AWK '{print $4}'` + READS_KB=`$EXPR $TMP_READS_KB / $NET_TIME` + # changing following line + # TMP_WRITES_KB=`$CAT /tmp/iostat_disk | $AWK '{print $4}'` + TMP_WRITES_KB=`$CAT /tmp/iostat_disk | $AWK '{print $5}'` + WRITES_KB=`$EXPR $TMP_WRITES_KB / $NET_TIME` + + # Disk reads and writes + # tps Indicates the number of transfers per second that were issued to the physical disk/tape. + # tps is summ of reads and writes for disk, so we should calculate factor + TMP_TPS=`$CAT /tmp/iostat_disk | $AWK '{print $2}'` + TPS=`$PRINTF "%0.f\n" $TMP_TPS` + TMP_SUM=`$EXPR $TMP_READS_KB + $TMP_WRITES_KB` + # filling empty values with 0 +else + READS_KB=0 + WRITES_KB=0 +fi + + +# Check if performance is 0 +# changing following line +# if [ $TMP_SUM -ne 0 ] + +if [ "$TMP_SUM" -ne 0 ] +then + TMP_READS=`$EXPR $TPS \* $TMP_READS_KB` + READS=`$EXPR $TMP_READS / $TMP_SUM` + TMP_WRITES=`$EXPR $TPS \* $TMP_WRITES_KB` + WRITES=`$EXPR $TMP_WRITES / $TMP_SUM` +else + READS=0 + WRITES=0 +fi + +# Output area + echo "name=Hardware Resources|CPU|%Idle,value="$CPU_IDLE + echo "name=Hardware Resources|CPU|%Busy,value="$CPU_BUSY + echo "name=Hardware Resources|Memory|Total (MB),value="$MEM_TOTAL_MB + echo "name=Hardware Resources|Memory|Used (MB),value="$MEM_USED_MB + echo "name=Hardware Resources|Memory|Free (MB),value="$MEM_FREE_MB + echo "name=Hardware Resources|Memory|Used %,value="$MEM_USED_PC + echo "name=Hardware Resources|Memory|Free %,value="$MEM_FREE_PC + echo "name=Hardware Resources|Network|Incoming packets/sec,value="$NET_PACKETS_IN + echo "name=Hardware Resources|Network|Outgoing packets/sec,value="$NET_PACKETS_OUT + echo "name=Hardware Resources|Network|Incoming KB/sec,value="$NET_KBYTES_IN + echo "name=Hardware Resources|Network|Outgoing KB/sec,value="$NET_KBYTES_OUT + echo "name=Hardware Resources|Disks|Reads/sec,value="$READS + echo "name=Hardware Resources|Disks|Writes/sec,value="$WRITES + echo "name=Hardware Resources|Disks|KB read/sec,value="$READS_KB + echo "name=Hardware Resources|Disks|KB written/sec,value="$WRITES_KB +done diff --git a/monitors/HardwareMonitor/linux-stat.sh b/monitors/HardwareMonitor/linux-stat.sh new file mode 100755 index 0000000..3ad77d1 --- /dev/null +++ b/monitors/HardwareMonitor/linux-stat.sh @@ -0,0 +1,296 @@ +#!/bin/sh +# +# Monitors CPU, Memory, Network and Disks on Linux +# +# version 1.0 +######################################### + +# Set unspecified system commands + NET_TIME=60 + + PATH=$PATH:/bin:/usr/sbin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin + + if [ -f /usr/bin/which ] + then + WHICH="/usr/bin/which" + else + echo "FATAL: Can't set system monitor tools" + exit 1 + fi + + if [ `$WHICH awk` ] + then + AWK=`$WHICH awk` + else + echo "FATAL: Can't find awk" + exit 1 + fi + + if [ `$WHICH grep` ] + then + GREP=`$WHICH grep` + else + echo "FATAL: Can't find grep" + exit 1 + fi + + if [ `$WHICH vmstat` ] + then + VMSTAT=`$WHICH vmstat` + else + echo "FATAL: Can't find vmstat" + exit 1 + fi + + if [ `$WHICH free` ] + then + FREE=`$WHICH free` + else + echo "FATAL: Can't find free" + exit 1 + fi + + if [ `$WHICH ps` ] + then + PS=`$WHICH ps` + else + echo "FATAL: Can't find ps" + exit 1 + fi + + if [ `$WHICH cut` ] + then + CUT=`$WHICH cut` + else + echo "FATAL: Can't find cut" + exit 1 + fi + + if [ `$WHICH cat` ] + then + CAT=`$WHICH cat` + else + echo "FATAL: Can't find cat" + exit 1 + fi + + if [ `$WHICH tail` ] + then + TAIL=`$WHICH tail` + else + echo "FATAL: Can't find tail" + exit 1 + fi + + if [ `$WHICH expr` ] + then + EXPR=`$WHICH expr` + else + echo "FATAL: Can't find expr" + exit 1 + fi + + if [ `$WHICH clear` ] + then + CLEAR=`$WHICH clear` + else + echo "FATAL: Can't find clear" + exit 1 + fi + + if [ `$WHICH iostat` ] + then + IOSTAT=`$WHICH iostat` +else + IOSTAT="NONE" + fi + + +while [ 1 ]; do + +# CPU & MEM + +# Run vmstat stat in background mode. Give 1 sec reserve to execute it in time + + $VMSTAT -a $(($NET_TIME-1)) 2 > /tmp/vmstat_tmp & + +# NETWORK & DISK + +# Read disk stat in stage 1 + + $CAT /proc/diskstats | $GREP -e "sd[a-z][0-9]\|hd[a-z][0-9] " > /tmp/diskstats + + if [ $IOSTAT = "NONE" ] + then + TMP_READS_SECTORS1=`$CAT /tmp/diskstats | $AWK '{ sum += $6 }END{printf ( "%i\n",sum)}'` + TMP_WRITES_SECTORS1=`$CAT /tmp/diskstats | $AWK '{ sum += $10 }END{printf ( "%i\n",sum)}'` + TMP_READS_KB1=0 + TMP_WRITES_KB1=0 + else + # IOSTAT is installed here + $IOSTAT -k | $GREP '^[a-z][a-z][a-z][0-9]' > /tmp/disk_iostat + TMP_READS_KB1=`$CAT /tmp/disk_iostat | $AWK '{ sum += $5 }END{printf ( "%i\n",sum)}'` + TMP_WRITES_KB1=`$CAT /tmp/disk_iostat | $AWK '{ sum += $6 }END{printf ( "%i\n",sum)}'` + TMP_READS_SECTORS1=0 + TMP_WRITES_SECTORS1=0 + fi + + TMP_DISK_READS1=`$CAT /tmp/diskstats | $AWK '{ sum += $4}END{printf ( "%i\n",sum)}'` + TMP_DISK_WRITES1=`$CAT /tmp/diskstats | $AWK '{ sum += $8}END{printf ( "%i\n",sum)}'` + +# Read network stat in stage 1 + + TMP_NET_BYTES1_IN=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ bytes += $1 } END { printf ( "%i\n",bytes )}'` + TMP_NET_PACKETS1_IN=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ packets += $2 } END { printf ( "%i\n",packets )}'` + + TMP_NET_BYTES1_OUT=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ bytes += $9 } END { printf ( "%i\n",bytes )}'` + TMP_NET_PACKETS1_OUT=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ packets += $10 } END { printf ( "%i\n",packets )}'` + + sleep $NET_TIME + +# Calculate again to find network and disk usage + +# Read disk stat in stage 2 + + $CAT /proc/diskstats | $GREP -e "sd[a-z][0-9]\|hd[a-z][0-9] " > /tmp/diskstats + + if [ $IOSTAT = "NONE" ] + then + TMP_READS_SECTORS1=`$CAT /tmp/diskstats | $AWK '{ sum += $6 }END{printf ( "%i\n",sum)}'` + TMP_WRITES_SECTORS1=`$CAT /tmp/diskstats | $AWK '{ sum += $10 }END{printf ( "%i\n",sum)}'` + TMP_READS_KB2=0 + TMP_WRITES_KB2=0 + else + # IOSTAT is installed here + $IOSTAT -k | $GREP '^[a-z][a-z][a-z][0-9]' > /tmp/disk_iostat + TMP_READS_KB2=`$CAT /tmp/disk_iostat | $AWK '{ sum += $5 }END{printf ( "%i\n",sum)}'` + TMP_WRITES_KB2=`$CAT /tmp/disk_iostat | $AWK '{ sum += $6 }END{printf ( "%i\n",sum)}'` + TMP_READS_SECTORS1=0 + TMP_WRITES_SECTORS1=0 + fi + + TMP_READS_SECTORS2=`$CAT /tmp/diskstats | $AWK '{ sum += $6 }END{printf ( "%i\n",sum)}'` + TMP_WRITES_SECTORS2=`$CAT /tmp/diskstats | $AWK '{ sum += $10 }END{printf ( "%i\n",sum)}'` + + TMP_DISK_READS2=`$CAT /tmp/diskstats | $AWK '{ sum += $4}END{printf ( "%i\n",sum)}'` + TMP_DISK_WRITES2=`$CAT /tmp/diskstats | $AWK '{ sum += $8}END{printf ( "%i\n",sum)}'` + +# Calculate disk stat during NET_TIME interval + + READS=$(( $(($TMP_DISK_READS2 - $TMP_DISK_READS1)) / $NET_TIME )) + WRITES=$(( $(($TMP_DISK_WRITES2 - $TMP_DISK_WRITES1)) / $NET_TIME )) + + READS_SECTORS=$(( $(($TMP_READS_SECTORS2 - $TMP_READS_SECTORS1)) / $NET_TIME )) + WRITES_SECTORS=$(( $(($TMP_WRITES_SECTORS2 - $TMP_WRITES_SECTORS1)) / $NET_TIME )) + + if [ $IOSTAT = "NONE" ] + then + #READS_KB=`$EXPR $READS_SECTORS \* 512` + #WRITES_KB=`$EXPR $WRITES_SECTORS \* 512` + READS_KB=-1 + WRITES_KB=-1 + else + READS_KB=$(( $(($TMP_READS_KB2 - $TMP_READS_KB1)) / $NET_TIME )) + WRITES_KB=$(( $(($TMP_WRITES_KB2 - $TMP_WRITES_KB1)) / $NET_TIME )) + fi + +# Read network stat in stage 2 + + TMP_NET_BYTES2_IN=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ bytes += $1 } END { printf ( "%i\n",bytes )}'` + TMP_NET_PACKETS2_IN=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ packets += $2 } END { printf ( "%i\n",packets )}'` + + TMP_NET_BYTES2_OUT=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ bytes += $9 } END { printf ( "%i\n",bytes )}'` + TMP_NET_PACKETS2_OUT=`$CAT /proc/net/dev | $CUT -d: -f2 -s | $AWK '{ packets += $10 } END { printf ( "%i\n",packets )}'` + +# Calculate network stat during NET_TIME interval + + NET_KBYTES_IN=$(($(($TMP_NET_BYTES2_IN - $TMP_NET_BYTES1_IN)) / $NET_TIME / 1024)) + NET_PACKETS_IN=$(($(($TMP_NET_PACKETS2_IN - $TMP_NET_PACKETS1_IN)) / $NET_TIME)) + + NET_KBYTES_OUT=$(($(($TMP_NET_BYTES2_OUT - $TMP_NET_BYTES1_OUT)) / $NET_TIME / 1024)) + NET_PACKETS_OUT=$(($(($TMP_NET_PACKETS2_OUT - $TMP_NET_PACKETS1_OUT)) / $NET_TIME)) + +## CPU + + CPU_IDLE=`$TAIL -1 /tmp/vmstat_tmp | $AWK '{print $15}'` + + CPU_BUSY=$((100-$CPU_IDLE)) + +## MEMORY + + MEM_TOTAL_MB=`$FREE -m | $GREP Mem | $AWK '{print $2}'` + + #MEM_FREE_INACTIVE_MB=$((`$TAIL -1 /tmp/vmstat_tmp | $AWK '{print $5}'`/1024)) + + MEM_FREE_MB=`$FREE -m | $GREP buffers\/cache | awk '{print $4}'` + + #MEM_USED_MB=$(($MEM_TOTAL_MB - ($MEM_FREE_MB + $MEM_FREE_INACTIVE_MB))) + MEM_USED_MB=$(($MEM_TOTAL_MB - $MEM_FREE_MB )) + + MEM_LOGICAL_FREE_MB=$(($MEM_TOTAL_MB - ($MEM_USED_MB))) + + TMP_MEM_USED_PC=`$EXPR $MEM_USED_MB \* 100` + + MEM_USED_PC=`$EXPR $TMP_MEM_USED_PC / $MEM_TOTAL_MB` + + MEM_FREE_PC=`$EXPR 100 - $MEM_USED_PC` + +# Verify the -ve values and set them to zero. + + st=$(echo "$NET_PACKETS_IN < 0" | bc) + if test $st -eq 1 + then NET_PACKETS_IN=0 + fi + + st=$(echo "$NET_PACKETS_OUT < 0" | bc) + if test $st -eq 1 + then NET_PACKETS_OUT=0 + fi + + st=$(echo "$NET_KBYTES_IN < 0" | bc) + if test $st -eq 1 + then NET_KBYTES_IN=0 + fi + + st=$(echo "$NET_KBYTES_OUT < 0" | bc) + if test $st -eq 1 + then NET_KBYTES_OUT=0 + fi + + st=$(echo "$READS < 0" | bc) + if test $st -eq 1 + then READS=0 + fi + + st=$(echo "$WRITES < 0" | bc) + if test $st -eq 1 + then WRITES=0 + fi + + st=$(echo "$READS_KB < 0" | bc) + if test $st -eq 1 + then READS_KB=0 + fi + + st=$(echo "$WRITES_KB < 0" | bc) + if test $st -eq 1 + then WRITES_KB=0 + fi + +# Output area + echo "name=Hardware Resources|CPU|%Idle,value="$CPU_IDLE + echo "name=Hardware Resources|CPU|%Busy,value="$CPU_BUSY + echo "name=Hardware Resources|Memory|Total (MB),value="$MEM_TOTAL_MB + echo "name=Hardware Resources|Memory|Used (MB),value="$MEM_USED_MB + echo "name=Hardware Resources|Memory|Free (MB),value="$MEM_LOGICAL_FREE_MB + echo "name=Hardware Resources|Memory|Used %,value="$MEM_USED_PC + echo "name=Hardware Resources|Memory|Free %,value="$MEM_FREE_PC + echo "name=Hardware Resources|Network|Incoming packets/sec,value="$NET_PACKETS_IN + echo "name=Hardware Resources|Network|Outgoing packets/sec,value="$NET_PACKETS_OUT + echo "name=Hardware Resources|Network|Incoming KB/sec,value="$NET_KBYTES_IN + echo "name=Hardware Resources|Network|Outgoing KB/sec,value="$NET_KBYTES_OUT + echo "name=Hardware Resources|Disks|Reads/sec,value="$READS + echo "name=Hardware Resources|Disks|Writes/sec,value="$WRITES + echo "name=Hardware Resources|Disks|KB read/sec,value="$READS_KB + echo "name=Hardware Resources|Disks|KB written/sec,value="$WRITES_KB +done diff --git a/monitors/HardwareMonitor/macos-stat.sh b/monitors/HardwareMonitor/macos-stat.sh new file mode 100755 index 0000000..44f7466 --- /dev/null +++ b/monitors/HardwareMonitor/macos-stat.sh @@ -0,0 +1,309 @@ +#!/bin/sh +# +# Monitors CPU, Memory, Network and Disks on MacOS +# +# version 1.0 +######################################### + +# Set unspecified system commands +NET_TIME=60 + +PATH=$PATH:/bin:/usr/sbin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin + +if [ -f /usr/bin/which ] +then +WHICH="/usr/bin/which" +else +echo "FATAL: Can't set system monitor tools" +exit 1 +fi + +if [ `$WHICH awk` ] +then +AWK=`$WHICH awk` +else +echo "FATAL: Can't find awk" +exit 1 +fi + +if [ `$WHICH grep` ] +then +GREP=`$WHICH grep` +else +echo "FATAL: Can't find grep" +exit 1 +fi + +if [ `$WHICH vm_stat` ] +then +VMSTAT=`$WHICH vm_stat` +else +echo "FATAL: Can't find vm_stat" +exit 1 +fi + +if [ `$WHICH iostat` ] +then +IOSTAT=`$WHICH iostat` +else +echo "FATAL: Can't find iostat" +exit 1 +fi + +if [ `$WHICH ps` ] +then +PS=`$WHICH ps` +else +echo "FATAL: Can't find ps" +exit 1 +fi + +if [ `$WHICH cut` ] +then +CUT=`$WHICH cut` +else +echo "FATAL: Can't find cut" +exit 1 +fi + +if [ `$WHICH cat` ] +then +CAT=`$WHICH cat` +else +echo "FATAL: Can't find cat" +exit 1 +fi + +if [ `$WHICH netstat` ] +then +NETSTAT=`$WHICH netstat` +else +echo "FATAL: Can't find netstat" +exit 1 +fi + +if [ `$WHICH tail` ] +then +TAIL=`$WHICH tail` +else +echo "FATAL: Can't find tail" +exit 1 +fi + +if [ `$WHICH printf` ] +then +PRINTF=`$WHICH printf` +else +echo "FATAL: Can't find printf" +exit 1 +fi + +if [ `$WHICH expr` ] +then +EXPR=`$WHICH expr` +else +echo "FATAL: Can't find expr" +exit 1 +fi + +if [ `$WHICH sysctl` ] +then +SYSCTL=`$WHICH sysctl` +else +echo "FATAL: Can't find sysctl" +exit 1 +fi + +if [ `$WHICH pagesize` ] +then +PAGESIZE=`$WHICH pagesize` +else +echo "FATAL: Can't find pagesize" +exit 1 +fi + +if [ `$WHICH clear` ] +then +CLEAR=`$WHICH clear` +else +echo "FATAL: Can't find clear" +exit 1 +fi + +if [ `$WHICH sed` ] +then +SED=`$WHICH sed` +else +echo "FATAL: Can't find sed" +exit 1 +fi + +if [ `$WHICH sleep` ] +then +SLEEP=`$WHICH sleep` +else +echo "FATAL: Can't find sleep" +exit 1 +fi + +if [ `$WHICH top` ] +then +TOP=`$WHICH top` +else +echo "FATAL: Can't find top" +exit 1 +fi + +if [ `$WHICH kill` ] +then +KILL=`$WHICH kill` +else +echo "FATAL: Can't find kill" +exit 1 +fi + +if [ `$WHICH top` ] +then +TOP=`$WHICH top` +else +echo "FATAL: Can't find top" +exit 1 +fi + +if [ `$WHICH ifconfig` ] +then +IFCONFIG=`$WHICH ifconfig` +else +echo "FATAL: Can't find ifconfig" +exit 1 +fi + +PAGESIZE=`$PAGESIZE` +RANDOMNM=$RANDOM + +while [ 1 ]; do +## CPU +# Run iostat in background. Give 1 sec reserve to execute it in time + +$IOSTAT -n1 $(($NET_TIME - 1)) 2 > /tmp/iostat_cpu & +#$IFCONFIG -a | $GREP '^[a-z]' | $AWK '{print $1}' | $AWK -F4: '{print $1}' > /tmp/ifconfig_interfaces +$TOP -l2 -cd -s $(($NET_TIME - 1)) > /tmp/top_disk_$RANDOMNM & + +$SLEEP $NET_TIME + +##CPU +CPU_IDLE=`$CAT /tmp/iostat_cpu | $TAIL -1 | $AWK '{ print $6 }'` +CPU_IDLE=`$PRINTF "%0.f\n" $CPU_IDLE` +CPU_BUSY=`$EXPR 100 - $CPU_IDLE` + +## MEM +MEM_FREE_MB=`$TOP -l1 -F -R -s $(($NET_TIME - 1)) | $GREP "PhysMem" | $SED 's/M//g' | $AWK '{print $10}'` +MEM_INACTIVE_MB=`$TOP -l1 -F -R -s $(($NET_TIME - 1)) | $GREP "PhysMem" | $SED 's/M//g' | $AWK '{print $6}'` + +MEM_USED_MB=`$TOP -l1 -F -R -s $(($NET_TIME - 1)) | $GREP "PhysMem" | $SED 's/M//g' | $AWK '{print $8}'` +MEM_TOTAL_MB=`$EXPR $MEM_FREE_MB + $MEM_USED_MB` + +MEM_LOGICAL_FREE_MB=`$EXPR $MEM_FREE_MB + $MEM_INACTIVE_MB` +MEM_LOGICAL_USED_MB=`$EXPR $MEM_USED_MB - $MEM_LOGICAL_FREE_MB` + + TMP_MEM_USED_PC=`$EXPR $MEM_LOGICAL_USED_MB \* 100` + MEM_USED_PC=`$EXPR $TMP_MEM_USED_PC / $MEM_TOTAL_MB` + MEM_FREE_PC=`$EXPR 100 - $MEM_USED_PC` + +#net (from top) +$CAT /tmp/top_disk_$RANDOMNM | $GREP "Networks:" | $TAIL -1 | $SED 's/[a-zA-Z:\/]*//g' > /tmp/top_net_$RANDOMNM +TMP_PACKETS_IN=`$CAT /tmp/top_net_$RANDOMNM | $AWK '{print $1}'` +TMP_PACKETS_OUT=`$CAT /tmp/top_net_$RANDOMNM | $AWK '{print $3}'` +TMP_KBYTES_IN=`$EXPR $TMP_PACKETS_IN / 1024` +TMP_KBYTES_OUT=`$EXPR $TMP_PACKETS_OUT / 1024` + + +TMP_PACKETS_IN=`$PRINTF "%0.f\n" $TMP_PACKETS_IN` +TMP_PACKETS_OUT=`$PRINTF "%0.f\n" $TMP_PACKETS_OUT` +TMP_KBYTES_IN=`$PRINTF "%0.f\n" $TMP_KBYTES_IN` +TMP_KBYTES_OUT=`$PRINTF "%0.f\n" $TMP_KBYTES_OUT` + + +NET_PACKETS_IN=`$EXPR $TMP_PACKETS_IN / $NET_TIME` +NET_PACKETS_OUT=`$EXPR $TMP_PACKETS_OUT / $NET_TIME` +NET_KBYTES_IN=`$EXPR $TMP_KBYTES_IN / $NET_TIME` +NET_KBYTES_OUT=`$EXPR $TMP_KBYTES_OUT / $NET_TIME` + +##Disk +$CAT /tmp/top_disk_$RANDOMNM | $GREP "Disks:" | $TAIL -1 | $SED 's/[a-zA-Z:\/]*//g' > /tmp/top_sed_$RANDOMNM +TMP_READS=`$CAT /tmp/top_sed_$RANDOMNM | $AWK '{print $1}'` +TMP_WRITES=`$CAT /tmp/top_sed_$RANDOMNM | $AWK '{print $3}'` +TMP_READS_KB=`$EXPR $TMP_READS / 1024` +TMP_WRITES_KB=`$EXPR $TMP_WRITES / 1024` + + +TMP_READS=`$PRINTF "%0.f\n" $TMP_READS` +TMP_WRITES=`$PRINTF "%0.f\n" $TMP_WRITES` +TMP_READS_KB=`$PRINTF "%0.f\n" $TMP_READS_KB` +TMP_WRITES_KB=`$PRINTF "%0.f\n" $TMP_WRITES_KB` + + +READS=`$EXPR $TMP_READS / $NET_TIME` +WRITES=`$EXPR $TMP_WRITES / $NET_TIME` +READS_KB=`$EXPR $TMP_READS_KB / $NET_TIME` +WRITES_KB=`$EXPR $TMP_WRITES_KB / $NET_TIME` + +# Verify the -ve values and set them to zero. + + st=$(echo "$NET_PACKETS_IN < 0" | bc) + if test $st -eq 1 + then NET_PACKETS_IN=0 + fi + + st=$(echo "$NET_PACKETS_OUT < 0" | bc) + if test $st -eq 1 + then NET_PACKETS_OUT=0 + fi + + st=$(echo "$NET_KBYTES_IN < 0" | bc) + if test $st -eq 1 + then NET_KBYTES_IN=0 + fi + + st=$(echo "$NET_KBYTES_OUT < 0" | bc) + if test $st -eq 1 + then NET_KBYTES_OUT=0 + fi + + st=$(echo "$READS < 0" | bc) + if test $st -eq 1 + then READS=0 + fi + + st=$(echo "$WRITES < 0" | bc) + if test $st -eq 1 + then WRITES=0 + fi + + st=$(echo "$READS_KB < 0" | bc) + if test $st -eq 1 + then READS_KB=0 + fi + + st=$(echo "$WRITES_KB < 0" | bc) + if test $st -eq 1 + then WRITES_KB=0 + fi + +## Output area +echo "name=Hardware Resources|CPU|%Idle,value="$CPU_IDLE +echo "name=Hardware Resources|CPU|%Busy,value="$CPU_BUSY +echo "name=Hardware Resources|Memory|Total (MB),value="$MEM_TOTAL_MB +echo "name=Hardware Resources|Memory|Used (MB),value="$MEM_LOGICAL_USED_MB +echo "name=Hardware Resources|Memory|Free (MB),value="$MEM_LOGICAL_FREE_MB +echo "name=Hardware Resources|Memory|Used %,value="$MEM_USED_PC +echo "name=Hardware Resources|Memory|Free %,value="$MEM_FREE_PC +echo "name=Hardware Resources|Network|Incoming packets/sec,value="$NET_PACKETS_IN +echo "name=Hardware Resources|Network|Outgoing packets/sec,value="$NET_PACKETS_OUT +echo "name=Hardware Resources|Network|Incoming KB/sec,value="$NET_KBYTES_IN +echo "name=Hardware Resources|Network|Outgoing KB/sec,value="$NET_KBYTES_OUT +echo "name=Hardware Resources|Disks|Reads/sec,value="$READS +echo "name=Hardware Resources|Disks|Writes/sec,value="$WRITES +echo "name=Hardware Resources|Disks|KB read/sec,value="$READS_KB +echo "name=Hardware Resources|Disks|KB written/sec,value="$WRITES_KB +done diff --git a/monitors/HardwareMonitor/monitor.xml b/monitors/HardwareMonitor/monitor.xml new file mode 100755 index 0000000..48b6a61 --- /dev/null +++ b/monitors/HardwareMonitor/monitor.xml @@ -0,0 +1,27 @@ + + HardwareMonitor + managed + false + true + true + Monitors system resources - CPU, Memory, Network I/O, and Disk I/O. + + + + + continuous + Run + executable + + + + file + linux-stat.sh + macos-stat.sh + windows-stat.bat + solaris-stat2.sh + solaris-stat2.sh + aix-stat.sh + + + \ No newline at end of file diff --git a/monitors/HardwareMonitor/solaris-stat.sh b/monitors/HardwareMonitor/solaris-stat.sh new file mode 100755 index 0000000..8a4b981 --- /dev/null +++ b/monitors/HardwareMonitor/solaris-stat.sh @@ -0,0 +1,248 @@ +#!/bin/sh +# +# Monitors CPU, Memory, Network and Disks on Solaris +# +# version 1.0 +######################################### + +# Set unspecified system commands + NET_TIME=60 + TIME1=59 + + PATH=$PATH:/bin:/usr/sbin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin + + if [ -f /usr/bin/which ] + then + WHICH="/usr/bin/which" + else + echo "FATAL: Can't set system monitor tools" + exit 1 + fi + + if [ `$WHICH awk` ] + then + AWK=`$WHICH awk` + else + echo "FATAL: Can't find awk" + exit 1 + fi + + if [ `$WHICH grep` ] + then + GREP=`$WHICH grep` + else + echo "FATAL: Can't find grep" + exit 1 + fi + + if [ `$WHICH vmstat` ] + then + VMSTAT=`$WHICH vmstat` + else + echo "FATAL: Can't find vmstat" + exit 1 + fi + + if [ `$WHICH iostat` ] + then + IOSTAT=`$WHICH iostat` + else + echo "FATAL: Can't find iostat" + exit 1 + fi + + if [ `$WHICH ps` ] + then + PS=`$WHICH ps` + else + echo "FATAL: Can't find ps" + exit 1 + fi + + if [ `$WHICH cut` ] + then + CUT=`$WHICH cut` + else + echo "FATAL: Can't find cut" + exit 1 + fi + + if [ `$WHICH cat` ] + then + CAT=`$WHICH cat` + else + echo "FATAL: Can't find cut" + exit 1 + fi + + if [ `$WHICH prtconf` ] + then + PRTCONF=`$WHICH prtconf` + else + echo "FATAL: Can't find prtconf" + exit 1 + fi + + if [ `$WHICH expr` ] + then + EXPR=`$WHICH expr` + else + echo "FATAL: Can't find expr" + exit 1 + fi + + if [ `$WHICH netstat` ] + then + NETSTAT=`$WHICH netstat` + else + echo "FATAL: Can't find netstat" + exit 1 + fi + + if [ `$WHICH kstat` ] + then + KSTAT=`$WHICH kstat` + else + echo "FATAL: Can't find kstat" + exit 1 + fi + + if [ `$WHICH printf` ] + then + PRINTF=`$WHICH printf` + else + echo "FATAL: Can't find printf" + exit 1 + fi + + if [ `$WHICH clear` ] + then + CLEAR=`$WHICH clear` + else + echo "FATAL: Can't find clear" + exit 1 + fi + + if [ `$WHICH sed` ] + then + SED=`$WHICH sed` + else + echo "FATAL: Can't find sed" + exit 1 + fi + + if [ `$WHICH tail` ] + then + TAIL=`$WHICH tail` + else + echo "FATAL: Can't find tail" + exit 1 + fi + + +while [ 1 ]; do + +# DISK & CPU + +# Run iostat and vmstat in background mode. Give 1 sec reserve to execute it in time + + $IOSTAT -x $TIME1 2 | $SED '1d' | $SED '/extended device statistics/,$d' | $SED '1d' > /tmp/tmp_iostat_disk & + $IOSTAT -c $TIME1 2 | $TAIL -1 > /tmp/tmp_iostat_cpu & + $VMSTAT $TIME1 2 | $TAIL -1 > /tmp/tmp_vmstat_memory & + +# NETWORK usage +# example +# Name Mtu Net/Dest Address Ipkts Ierrs Opkts Oerrs Collis Queue +# lo0 8232 loopback localhost 165 0 165 0 0 0 +# pcn0 1500 unknown unknown 29532 0 26541 0 0 0 +# pcn1 1500 dfsdf dfsdf 18975 0 21 0 0 0 +# +# example +# name: pcn0 class: net +# obytes 2998449822 +# rbytes 2996409010 + + $KSTAT > /tmp/tmp_net_bytes + $NETSTAT -i > /tmp/tmp_net_packets + + TMP_NET_BYTES1_IN=`$CAT /tmp/tmp_net_bytes | $GREP rbytes | $AWK '{ sum += $2 }END {printf ("%d\n",sum)}'` + TMP_NET_BYTES1_OUT=`$CAT /tmp/tmp_net_bytes | $GREP obytes | $AWK '{ sum += $2 }END {printf ("%d\n",sum)}'` + + TMP_NET_PACKETS1_IN=`$CAT /tmp/tmp_net_packets | $AWK '{ in_pk += $5 } END {printf ("%d\n",in_pk)}'` + TMP_NET_PACKETS1_OUT=`$CAT /tmp/tmp_net_packets | $AWK '{ out_pk += $7 } END {printf ( "%d\n",out_pk)}'` + + sleep $NET_TIME + +# Calculate again to find network usage + + $KSTAT > /tmp/tmp_net_bytes + $NETSTAT -i > /tmp/tmp_net_packets + + TMP_NET_PACKETS2_IN=`$CAT /tmp/tmp_net_packets | $AWK '{ in_pk += $5 } END {printf ("%d\n",in_pk)}'` + TMP_NET_PACKETS2_OUT=`$CAT /tmp/tmp_net_packets | $AWK '{ out_pk += $7 } END {printf ( "%d\n",out_pk)}'` + + TMP_NET_PACKETS_OUT=`$EXPR $TMP_NET_PACKETS2_OUT - $TMP_NET_PACKETS1_OUT` + TMP_NET_PACKETS_IN=`$EXPR $TMP_NET_PACKETS2_IN - $TMP_NET_PACKETS1_IN` + + TMP_NET_BYTES2_IN=`$CAT /tmp/tmp_net_bytes | $GREP rbytes | $AWK '{ sum += $2 }END {printf ("%d\n",sum)}'` + TMP_NET_BYTES2_OUT=`$CAT /tmp/tmp_net_bytes | $GREP obytes | $AWK '{ sum += $2 }END {printf ("%d\n",sum)}'` + + TMP_NET_BYTES_IN=`$EXPR $TMP_NET_BYTES2_IN - $TMP_NET_BYTES1_IN` + TMP_NET_BYTES_OUT=`$EXPR $TMP_NET_BYTES2_OUT - $TMP_NET_BYTES1_OUT` + + TMP_NET_BYTES_IN_KB=`$EXPR $TMP_NET_BYTES_IN / 1024 ` + TMP_NET_BYTES_OUT_KB=`$EXPR $TMP_NET_BYTES_OUT / 1024 ` + + NET_PACKETS_IN=`$EXPR $TMP_NET_PACKETS_IN / $NET_TIME` + NET_PACKETS_OUT=`$EXPR $TMP_NET_PACKETS_OUT / $NET_TIME` + + NET_KBYTES_IN=`$EXPR $TMP_NET_BYTES_IN_KB / $NET_TIME` + NET_KBYTES_OUT=`$EXPR $TMP_NET_BYTES_OUT_KB / $NET_TIME` + + +# DISK + + TMP_READS=`$CAT /tmp/tmp_iostat_disk | $AWK '{ sum += $2 }END{printf("%d\n",sum)}'` + TMP_WRITES=`$CAT /tmp/tmp_iostat_disk | $AWK '{ sum += $3 }END{printf ("%d\n",sum)}'` + + TMP_READS_KB=`$CAT /tmp/tmp_iostat_disk | $AWK '{ sum += $4 }END{printf("%d\n",sum)}'` + TMP_WRITES_KB=`$CAT /tmp/tmp_iostat_disk | $AWK '{ sum += $5 }END{printf("%d\n",sum)}'` + + READS=`$PRINTF "%0.f\n" $TMP_READS` + WRITES=`$PRINTF "%0.f\n" $TMP_WRITES` + + READS_KB=`$PRINTF "%0.f\n" $TMP_READS_KB` + WRITES_KB=`$PRINTF "%0.f\n" $TMP_WRITES_KB` + +# CPU + + CPU_IDLE=`$CAT /tmp/tmp_iostat_cpu | $AWK '{print $4}'` + CPU_BUSY=`$EXPR 100 - $CPU_IDLE` + +# MEMORY usage + + MEM_TOTAL_MB=`$PRTCONF | $GREP Memory | $AWK '{ print $3 }'` + TMP_FREE_VMSTAT=`$CAT /tmp/tmp_vmstat_memory | $AWK '{ free += $5 } END {print free}'` + MEM_FREE_MB=`$EXPR $TMP_FREE_VMSTAT / 1024` + MEM_USED_MB=`$EXPR $MEM_TOTAL_MB - $MEM_FREE_MB` + TMP_MEM_USED_PC=`$EXPR $MEM_USED_MB \* 100` + MEM_USED_PC=`$EXPR $TMP_MEM_USED_PC / $MEM_TOTAL_MB` + MEM_FREE_PC=`$EXPR 100 - $MEM_USED_PC` + +# Output area + echo "name=Hardware Resources|CPU|%Idle,value="$CPU_IDLE + echo "name=Hardware Resources|CPU|%Busy,value="$CPU_BUSY + echo "name=Hardware Resources|Memory|Total (MB),value="$MEM_TOTAL_MB + echo "name=Hardware Resources|Memory|Used (MB),value="$MEM_USED_MB + echo "name=Hardware Resources|Memory|Free (MB),value="$MEM_FREE_MB + echo "name=Hardware Resources|Memory|Used %,value="$MEM_USED_PC + echo "name=Hardware Resources|Memory|Free %,value="$MEM_FREE_PC + echo "name=Hardware Resources|Network|Incoming packets/sec,value="$NET_PACKETS_IN + echo "name=Hardware Resources|Network|Outgoing packets/sec,value="$NET_PACKETS_OUT + echo "name=Hardware Resources|Network|Incoming KB/sec,value="$NET_KBYTES_IN + echo "name=Hardware Resources|Network|Outgoing KB/sec,value="$NET_KBYTES_OUT + echo "name=Hardware Resources|Disks|Reads/sec,value="$READS + echo "name=Hardware Resources|Disks|Writes/sec,value="$WRITES + echo "name=Hardware Resources|Disks|KB read/sec,value="$READS_KB + echo "name=Hardware Resources|Disks|KB written/sec,value="$WRITES_KB +done \ No newline at end of file diff --git a/monitors/HardwareMonitor/solaris-stat2.sh b/monitors/HardwareMonitor/solaris-stat2.sh new file mode 100755 index 0000000..33435c8 --- /dev/null +++ b/monitors/HardwareMonitor/solaris-stat2.sh @@ -0,0 +1,4 @@ +( +cd solaris +bash ./core.sh +) diff --git a/monitors/HardwareMonitor/solaris/core.sh b/monitors/HardwareMonitor/solaris/core.sh new file mode 100755 index 0000000..62205fe --- /dev/null +++ b/monitors/HardwareMonitor/solaris/core.sh @@ -0,0 +1,42 @@ +#/bin/bash +PATH=$PATH:/bin:/usr/sbin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin +NET_TIME=60 +TIME1=59 + +#Checking the Availablity of all the commands +. ./dependency.sh + +while ( true ) +do + +#Network I/O before going to sleep + . ./network_dep.sh + +#Going to Sleep for 60 sec + sleep $NET_TIME + + #Checking the Solaris version + cat /etc/release | grep -w 'Solaris 11' > /dev/null + if [ $? -eq 0 ] + then + #Memory metrics in Solaris 11 + . ./memory11.sh + + else + #Memory metrics in Solaris 10 + + . ./memory10.sh + fi + + #Calculating CPU usage + . ./cpu.sh + + #Calculating network I/O script + . ./network.sh + + #Executing disk I/O script + . ./disk.sh + +done + + diff --git a/monitors/HardwareMonitor/solaris/cpu.sh b/monitors/HardwareMonitor/solaris/cpu.sh new file mode 100755 index 0000000..d4b7d5c --- /dev/null +++ b/monitors/HardwareMonitor/solaris/cpu.sh @@ -0,0 +1,6 @@ +zone=`zonename` +CPU_BUSY_TEMP=`prstat -Z 1 1 | grep $zone | awk ' { print $7 } ' | sed 's/%//'` +CPU_BUSY=`printf "%0.f\n" $CPU_BUSY_TEMP` +CPU_IDLE=`expr 100 - $CPU_BUSY` +echo "name=Custom Metrics|CPU|%Idle,value="$CPU_IDLE +echo "name=Custom Metrics|CPU|%Busy,value="$CPU_BUSY diff --git a/monitors/HardwareMonitor/solaris/cpu2.sh b/monitors/HardwareMonitor/solaris/cpu2.sh new file mode 100755 index 0000000..34de5ac --- /dev/null +++ b/monitors/HardwareMonitor/solaris/cpu2.sh @@ -0,0 +1,4 @@ +CPU_IDLE=`$CAT /tmp/tmp_iostat_cpu | $AWK '{print $4}'` +CPU_BUSY=`$EXPR 100 - $CPU_IDLE` +echo "name=Custom Metrics|CPU|%Idle,value="$CPU_IDLE +echo "name=Custom Metrics|CPU|%Busy,value="$CPU_BUSY diff --git a/monitors/HardwareMonitor/solaris/dependency.sh b/monitors/HardwareMonitor/solaris/dependency.sh new file mode 100755 index 0000000..308936d --- /dev/null +++ b/monitors/HardwareMonitor/solaris/dependency.sh @@ -0,0 +1,127 @@ + if [ -f /usr/bin/which ] + then + WHICH="/usr/bin/which" + else + echo "FATAL: Can't set system monitor tools" + exit 1 + fi + + if [ `$WHICH awk` ] + then + AWK=`$WHICH awk` + else + echo "FATAL: Can't find awk" + exit 1 + fi + + if [ `$WHICH grep` ] + then + GREP=`$WHICH grep` + else + echo "FATAL: Can't find grep" + exit 1 + fi + + if [ `$WHICH vmstat` ] + then + VMSTAT=`$WHICH vmstat` + else + echo "FATAL: Can't find vmstat" + exit 1 + fi + + if [ `$WHICH iostat` ] + then + IOSTAT=`$WHICH iostat` + else + echo "FATAL: Can't find iostat" + exit 1 + fi + + if [ `$WHICH ps` ] + then + PS=`$WHICH ps` + else + echo "FATAL: Can't find ps" + exit 1 + fi + + if [ `$WHICH cut` ] + then + CUT=`$WHICH cut` + else + echo "FATAL: Can't find cut" + exit 1 + fi + + if [ `$WHICH cat` ] + then + CAT=`$WHICH cat` + else + echo "FATAL: Can't find cut" + exit 1 + fi + + if [ `$WHICH prtconf` ] + then + PRTCONF=`$WHICH prtconf` + else + echo "FATAL: Can't find prtconf" + exit 1 + fi + + if [ `$WHICH expr` ] + then + EXPR=`$WHICH expr` + else + echo "FATAL: Can't find expr" + exit 1 + fi + + if [ `$WHICH netstat` ] + then + NETSTAT=`$WHICH netstat` + else + echo "FATAL: Can't find netstat" + exit 1 + fi + + if [ `$WHICH kstat` ] + then + KSTAT=`$WHICH kstat` + else + echo "FATAL: Can't find kstat" + exit 1 + fi + + if [ `$WHICH printf` ] + then + PRINTF=`$WHICH printf` + else + echo "FATAL: Can't find printf" + exit 1 + fi + + if [ `$WHICH clear` ] + then + CLEAR=`$WHICH clear` + else + echo "FATAL: Can't find clear" + exit 1 + fi + + if [ `$WHICH sed` ] + then + SED=`$WHICH sed` + else + echo "FATAL: Can't find sed" + exit 1 + fi + + if [ `$WHICH tail` ] + then + TAIL=`$WHICH tail` + else + echo "FATAL: Can't find tail" + exit 1 + fi \ No newline at end of file diff --git a/monitors/HardwareMonitor/solaris/disk.sh b/monitors/HardwareMonitor/solaris/disk.sh new file mode 100755 index 0000000..a218a1a --- /dev/null +++ b/monitors/HardwareMonitor/solaris/disk.sh @@ -0,0 +1,39 @@ + cat /tmp/tmp_iostat_disk | awk ' { print $1 } ' > /tmp/tmp_disk_list + + for dev in `cat /tmp/tmp_disk_list` + do + + TMP_READS=`cat /tmp/tmp_iostat_disk | grep $dev | awk '{ print $2 } '` + TMP_WRITES=`cat /tmp/tmp_iostat_disk | grep $dev | awk '{ print $3 } '` + TMP_READS_KB=`cat /tmp/tmp_iostat_disk | grep $dev | awk '{ print $4 } '` + TMP_WRITES_KB=`cat /tmp/tmp_iostat_disk | grep $dev | awk '{ print $5 } '` + + READS=`printf "%0.f\n" $TMP_READS` + WRITES=`printf "%0.f\n" $TMP_WRITES` + + READS_KB=`printf "%0.f\n" $TMP_READS_KB` + WRITES_KB=`printf "%0.f\n" $TMP_WRITES_KB` + + echo "name=Custom Metrics|Disks|$dev|Reads/sec,value="$READS + echo "name=Custom Metrics|Disks|$dev|Writes/sec,value="$WRITES + echo "name=Custom Metrics|Disks|$dev|KB read/sec,value="$READS_KB + echo "name=Custom Metrics|Disks|$dev|KB written/sec,value="$WRITES_KB +done + + + TMP_READS=`cat /tmp/tmp_iostat_disk | awk '{ sum += $2 }END{printf("%d\n",sum)}'` + TMP_WRITES=`cat /tmp/tmp_iostat_disk | awk '{ sum += $3 }END{printf ("%d\n",sum)}'` + + TMP_READS_KB=`cat /tmp/tmp_iostat_disk | awk '{ sum += $4 }END{printf("%d\n",sum)}'` + TMP_WRITES_KB=`cat /tmp/tmp_iostat_disk | awk '{ sum += $5 }END{printf("%d\n",sum)}'` + + READS=`printf "%0.f\n" $TMP_READS` + WRITES=`printf "%0.f\n" $TMP_WRITES` + + READS_KB=`printf "%0.f\n" $TMP_READS_KB` + WRITES_KB=`printf "%0.f\n" $TMP_WRITES_KB` + + echo "name=Custom Metrics|Disks|Reads/sec,value="$READS + echo "name=Custom Metrics|Disks|Writes/sec,value="$WRITES + echo "name=Custom Metrics|Disks|KB read/sec,value="$READS_KB + echo "name=Custom Metrics|Disks|KB written/sec,value="$WRITES_KB \ No newline at end of file diff --git a/monitors/HardwareMonitor/solaris/memory10.sh b/monitors/HardwareMonitor/solaris/memory10.sh new file mode 100755 index 0000000..892680f --- /dev/null +++ b/monitors/HardwareMonitor/solaris/memory10.sh @@ -0,0 +1,12 @@ + MEM_TOTAL_MB=`prtconf | grep Memory | awk '{ print $3 }'` + prstat -Z 1 1 | grep `zonename` | awk ' { print $5 } ' | sed 's/%//' > MEM_USED_PC.txt + MEM_USED_PC=`cat MEM_USED_PC.txt` + MEM_FREE_PC=`expr 100 - $MEM_USED_PC` + MEM_USED_MB=`echo "$MEM_TOTAL_MB * $MEM_USED_PC" / 100 | bc` + MEM_FREE_MB=`echo "$MEM_TOTAL_MB - $MEM_USED_MB" | bc` + + echo "name=Custom Metrics|Memory|Total (MB),value="$MEM_TOTAL_MB + echo "name=Custom Metrics|Memory|Used (MB),value="$MEM_USED_MB + echo "name=Custom Metrics|Memory|Free (MB),value="$MEM_FREE_MB + echo "name=Custom Metrics|Memory|Used %,value="$MEM_USED_PC + echo "name=Custom Metrics|Memory|Free %,value="$MEM_FREE_PC \ No newline at end of file diff --git a/monitors/HardwareMonitor/solaris/memory11.sh b/monitors/HardwareMonitor/solaris/memory11.sh new file mode 100755 index 0000000..b438d8c --- /dev/null +++ b/monitors/HardwareMonitor/solaris/memory11.sh @@ -0,0 +1,14 @@ + MEM_TOTAL_MB=`prtconf | grep Memory | awk '{ print $3 }'` + zonestat 1 1 | awk '/'`zonename`'/ { print $4 } ' | sed 's/M//' > MEM_USED_MB.txt + TMP_MEM_USED_MB=`cat MEM_USED_MB.txt` + MEM_USED_MB=`printf "%0.f\n" $TMP_MEM_USED_MB` + MEM_FREE_MB=`echo "$MEM_TOTAL_MB - $MEM_USED_MB" | bc` + MEM_USED_PC=`echo "100 * $MEM_USED_MB" / $MEM_TOTAL_MB | bc` + MEM_FREE_PC=`expr 100 - $MEM_USED_PC` + + + echo "name=Custom Metrics|Memory|Total (MB),value="$MEM_TOTAL_MB + echo "name=Custom Metrics|Memory|Used (MB),value="$MEM_USED_MB + echo "name=Custom Metrics|Memory|Free (MB),value="$MEM_FREE_MB + echo "name=Custom Metrics|Memory|Used %,value="$MEM_USED_PC + echo "name=Custom Metrics|Memory|Free %,value="$MEM_FREE_PC \ No newline at end of file diff --git a/monitors/HardwareMonitor/solaris/network.sh b/monitors/HardwareMonitor/solaris/network.sh new file mode 100755 index 0000000..5a804e4 --- /dev/null +++ b/monitors/HardwareMonitor/solaris/network.sh @@ -0,0 +1,95 @@ +#!/bin/bash + +#++++++++++++++++++++++++++++++++++ +#Running kstat and netstat command +#+++++++++++++++++++++++++++++++++ +$KSTAT > /tmp/tmp_net_bytes + $NETSTAT -i > /tmp/tmp_net_packets + +#+++++++++++++++++++++++ +#Calculating Network I/O +#+++++++++++++++++++++++ + TMP_NET_BYTES2_IN=0 + TMP_NET_PACKETS2_IN=`cat /tmp/tmp_net_packets | $AWK '{ in_pk += $5 } END {printf ("%d\n",in_pk)}'` + TMP_NET_PACKETS2_OUT=`cat /tmp/tmp_net_packets | $AWK '{ out_pk += $7 } END {printf ( "%d\n",out_pk)}'` + + TMP_NET_PACKETS_OUT=`$EXPR $TMP_NET_PACKETS2_OUT - $TMP_NET_PACKETS1_OUT` + TMP_NET_PACKETS_IN=`$EXPR $TMP_NET_PACKETS2_IN - $TMP_NET_PACKETS1_IN` + + for i in `cat /tmp/tmp_net_bytes | grep rbytes | awk ' { print $2 } '`; do TMP_NET_BYTES2_IN=`expr $TMP_NET_BYTES2_IN + $i`; done + TMP_NET_BYTES2_OUT=`$CAT /tmp/tmp_net_bytes | $GREP obytes | $AWK '{ sum += $2 }END {printf ("%d\n",sum)}'` + + TMP_NET_BYTES_IN=`$EXPR $TMP_NET_BYTES2_IN - $TMP_NET_BYTES1_IN` + TMP_NET_BYTES_OUT=`$EXPR $TMP_NET_BYTES2_OUT - $TMP_NET_BYTES1_OUT` + + TMP_NET_BYTES_IN_KB=`$EXPR $TMP_NET_BYTES_IN / 1024` + TMP_NET_BYTES_OUT_KB=`$EXPR $TMP_NET_BYTES_OUT / 1024 ` + + NET_PACKETS_IN=`$EXPR $TMP_NET_PACKETS_IN / $NET_TIME` + NET_PACKETS_OUT=`$EXPR $TMP_NET_PACKETS_OUT / $NET_TIME` + + NET_KBYTES_IN=`$EXPR $TMP_NET_BYTES_IN_KB / $NET_TIME` + NET_KBYTES_OUT=`$EXPR $TMP_NET_BYTES_OUT_KB / $NET_TIME` + + + echo "name=Custom Metrics|Network|Incoming packets,value="$TMP_NET_PACKETS_IN + echo "name=Custom Metrics|Network|Outgoing packets,value="$TMP_NET_PACKETS_OUT + echo "name=Custom Metrics|Network|Incoming packets/sec,value="$NET_PACKETS_IN + echo "name=Custom Metrics|Network|Outgoing packets/sec,value="$NET_PACKETS_OUT + echo "name=Custom Metrics|Network|Incoming KB/sec,value="$NET_KBYTES_IN + echo "name=Custom Metrics|Network|Outgoing KB/sec,value="$NET_KBYTES_OUT + echo "name=Custom Metrics|Network|Incoming KB,value="$TMP_NET_BYTES_IN_KB + echo "name=Custom Metrics|Network|Outgoing KB,value="$TMP_NET_BYTES_OUT_KB + +for inet in `netstat -i | sed '1d' | grep -v loopback | awk ' { print $1 } '` +do + kstat -n $inet > /tmp/tmp_net_bytes_$inet + netstat -i -I $inet > /tmp/tmp_net_packets_$inet + + TMP_NET_BYTES2_IN=0 + export TMP_NET_PACKETS2_IN_$inet=`cat /tmp/tmp_net_packets_$inet | awk '{ in_pk += $5 } END {printf ("%d\n",in_pk)}'` + export TMP_NET_PACKETS2_OUT_$inet=`cat /tmp/tmp_net_packets_$inet | awk '{ out_pk += $7 } END {printf ( "%d\n",out_pk)}'` + +TMP_VAR_IN_BYTES1=`echo TMP_NET_BYTES1_IN_$inet` +TMP_VAR_OUT_BYTES1=`echo TMP_NET_BYTES1_OUT_$inet` +TMP_VAR_IN_PACK1=`echo TMP_NET_PACKETS1_IN_$inet` +TMP_VAR_OUT_PACK1=`echo TMP_NET_PACKETS1_OUT_$inet` + + +TMP_VAR_IN_PACK2=`echo TMP_NET_PACKETS2_IN_$inet` +TMP_VAR_OUT_PACK2=`echo TMP_NET_PACKETS2_OUT_$inet` + + TMP_NET_PACKETS_OUT=`expr ${!TMP_VAR_OUT_PACK2} - ${!TMP_VAR_OUT_PACK1}` + TMP_NET_PACKETS_IN=`expr ${!TMP_VAR_IN_PACK2} - ${!TMP_VAR_IN_PACK1}` + + for i in `cat /tmp/tmp_net_bytes_$inet | grep rbytes | awk ' { print $2 } '`; do TMP_NET_BYTES2_IN=`expr $TMP_NET_BYTES2_IN + $i`; done + export TMP_NET_BYTES2_IN_$inet=`echo $TMP_NET_BYTES2_IN` + export TMP_NET_BYTES2_OUT_$inet=`cat /tmp/tmp_net_bytes_$inet | grep obytes | awk '{ sum += $2 }END {printf ("%d\n",sum)}'` + +TMP_VAR_IN_BYTES2=`echo TMP_NET_BYTES2_IN_$inet` +TMP_VAR_OUT_BYTES2=`echo TMP_NET_BYTES2_OUT_$inet` + + TMP_NET_BYTES_IN=`expr ${!TMP_VAR_IN_BYTES2} - ${!TMP_VAR_IN_BYTES1}` + TMP_NET_BYTES_OUT=`expr ${!TMP_VAR_OUT_BYTES2} - ${!TMP_VAR_OUT_BYTES1}` + + TMP_NET_BYTES_IN_KB=`expr $TMP_NET_BYTES_IN / 1024` + TMP_NET_BYTES_OUT_KB=`expr $TMP_NET_BYTES_OUT / 1024 ` + + NET_PACKETS_IN=`expr $TMP_NET_PACKETS_IN / $NET_TIME` + NET_PACKETS_OUT=`expr $TMP_NET_PACKETS_OUT / $NET_TIME` + + NET_KBYTES_IN=`expr $TMP_NET_BYTES_IN_KB / $NET_TIME` + NET_KBYTES_OUT=`expr $TMP_NET_BYTES_OUT_KB / $NET_TIME` + + + echo "name=Custom Metrics|Network|$inet|Incoming packets,value="$TMP_NET_PACKETS_IN + echo "name=Custom Metrics|Network|$inet|Outgoing packets,value="$TMP_NET_PACKETS_OUT + echo "name=Custom Metrics|Network|$inet|Incoming packets/sec,value="$NET_PACKETS_IN + echo "name=Custom Metrics|Network|$inet|Outgoing packets/sec,value="$NET_PACKETS_OUT + echo "name=Custom Metrics|Network|$inet|Incoming KB/sec,value="$NET_KBYTES_IN + echo "name=Custom Metrics|Network|$inet|Outgoing KB/sec,value="$NET_KBYTES_OUT + echo "name=Custom Metrics|Network|$inet|Incoming KB,value="$TMP_NET_BYTES_IN_KB + echo "name=Custom Metrics|Network|$inet|Outgoing KB,value="$TMP_NET_BYTES_OUT_KB +done + + diff --git a/monitors/HardwareMonitor/solaris/network_dep.sh b/monitors/HardwareMonitor/solaris/network_dep.sh new file mode 100755 index 0000000..7c2bc3b --- /dev/null +++ b/monitors/HardwareMonitor/solaris/network_dep.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +#++++++++++++++++++++++++++++++++++++++++++ +#Network I/O checking before going to sleep +#++++++++++++++++++++++++++++++++++++++++++ + +$IOSTAT -c $TIME1 2 | $TAIL -1 > /tmp/tmp_iostat_cpu & + +for inet in `netstat -i | sed '1d' | grep -v loopback | awk ' { print $1 } '` +do + kstat -n $inet > /tmp/tmp_net_bytes_$inet + netstat -i -I $inet > /tmp/tmp_net_packets_$inet + +TMP_NET_BYTES1_IN=0 +for i in `cat /tmp/tmp_net_bytes_$inet | grep rbytes | awk ' { print $2 } '`; do TMP_NET_BYTES1_IN=`expr $TMP_NET_BYTES1_IN + $i`; +done +export TMP_NET_BYTES1_IN_$inet=`echo $TMP_NET_BYTES1_IN` +export TMP_NET_BYTES1_OUT_$inet=`cat /tmp/tmp_net_bytes_$inet | grep obytes | awk '{ sum += $2 }END {printf ("%d\n",sum)}'` + +export TMP_NET_PACKETS1_IN_$inet=`cat /tmp/tmp_net_packets_$inet | awk '{ in_pk += $5 } END {printf ("%d\n",in_pk)}'` +export TMP_NET_PACKETS1_OUT_$inet=`cat /tmp/tmp_net_packets_$inet | awk '{ out_pk += $7 } END {printf ( "%d\n",out_pk)}'` +done + + iostat -x 59 2 | sed '1d' | sed -n '/extended device statistics/,$p' | sed '1d' | sed '1d' > /tmp/tmp_iostat_disk & + $IOSTAT -c $TIME1 2 | $TAIL -1 > /tmp/tmp_iostat_cpu & + + kstat > /tmp/tmp_net_bytes + netstat -i > /tmp/tmp_net_packets + + TMP_NET_BYTES1_IN=0 + for i in `cat /tmp/tmp_net_bytes | grep rbytes | awk ' { print $2 } '`; do TMP_NET_BYTES1_IN=`expr $TMP_NET_BYTES1_IN + $i`; done + TMP_NET_BYTES1_OUT=`cat /tmp/tmp_net_bytes | grep obytes | awk '{ sum += $2 }END {printf ("%d\n",sum)}'` + + TMP_NET_PACKETS1_IN=`cat /tmp/tmp_net_packets | awk '{ in_pk += $5 } END {printf ("%d\n",in_pk)}'` + TMP_NET_PACKETS1_OUT=`cat /tmp/tmp_net_packets | awk '{ out_pk += $7 } END {printf ( "%d\n",out_pk)}'` + + diff --git a/monitors/HardwareMonitor/windows-stat.bat b/monitors/HardwareMonitor/windows-stat.bat new file mode 100755 index 0000000..129d9bb --- /dev/null +++ b/monitors/HardwareMonitor/windows-stat.bat @@ -0,0 +1,2 @@ +@echo off +cscript /nologo windows-stat.vbs \ No newline at end of file diff --git a/monitors/HardwareMonitor/windows-stat.vbs b/monitors/HardwareMonitor/windows-stat.vbs new file mode 100755 index 0000000..1cc9881 --- /dev/null +++ b/monitors/HardwareMonitor/windows-stat.vbs @@ -0,0 +1,146 @@ +' ======================================================== +' +' Monitors CPU, Memory, Network and Disks on Windows +' +' version 1.0 +' +' ======================================================== +Option Explicit + +Dim oWsh, oWshSysEnv, objFSO, objWMIService, objRefresher +Dim colItems, objItem, colItems1, objItem1, ColCPU, ColMemPh, ColMem +Dim CPU_IDLE, CPU_BUSY, MEM_TOTAL_MB, MEM_USED_MB, MEM_FREE_MB, MEM_USED_PC, MEM_FREE_PC, NET_PACKETS_IN +Dim NET_PACKETS_OUT, NET_KBYTES_IN, NET_KBYTES_OUT, READS, WRITES, READS_KB, WRITES_KB +Dim TMP_NET_PACKETS1_IN, TMP_NET_PACKETS1_OUT, TMP_NET_BYTES1_IN, TMP_NET_BYTES1_OUT +Dim TMP_NET_PACKETS2_IN, TMP_NET_PACKETS2_OUT, TMP_NET_BYTES2_IN, TMP_NET_BYTES2_OUT +Dim TMP_READS2_KB, TMP_READS1_KB, TMP_WRITES2_KB, TMP_WRITES1_KB +Dim TMP_READS1, TMP_READS2, TMP_WRITES2, TMP_WRITES1 +Dim NET_TIME, Bool +Dim TEST_VAL + +Set oWsh = WScript.CreateObject("WScript.Shell") +Set oWshSysEnv = oWsh.Environment("PROCESS") +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2") +Set objRefresher = CreateObject("WbemScripting.SWbemRefresher") +Set ColCPU = objRefresher.Add(objWMIService,"Win32_PerfFormattedData_PerfOS_Processor.Name='_Total'").Object +Set ColMemPh = objRefresher.AddEnum(objWMIService,"Win32_ComputerSystem").ObjectSet +Set ColMem = objRefresher.AddEnum(objWMIService,"Win32_PerfFormattedData_PerfOS_Memory").ObjectSet +objRefresher.Refresh + +NET_TIME = 60 +Bool = 0 + +Do +'take initial reading, sleep for a minute then find the diff + +' NETWORK & DISK Usage +'Network + + TMP_NET_PACKETS1_IN = 0 + TMP_NET_PACKETS1_OUT = 0 + TMP_NET_BYTES1_IN = 0 + TMP_NET_BYTES1_OUT = 0 + TMP_NET_PACKETS2_IN = 0 + TMP_NET_PACKETS2_OUT = 0 + TMP_NET_BYTES2_IN = 0 + TMP_NET_BYTES2_OUT = 0 + + Set colItems = GetObject("WinMgmts:root/cimv2").ExecQuery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface") +' calculate for each network adapter + For Each objItem1 In colItems + TMP_NET_PACKETS1_IN = TMP_NET_PACKETS1_IN + objItem1.PacketsReceivedPersec + TMP_NET_PACKETS1_OUT = TMP_NET_PACKETS1_OUT + objItem1.PacketsSentPersec + TMP_NET_BYTES1_IN = TMP_NET_BYTES1_IN + objItem1.BytesReceivedPersec + TMP_NET_BYTES1_OUT = TMP_NET_BYTES1_OUT + objItem1.BytesSentPersec + Next + +'Disk + Set colItems = GetObject("WinMgmts:root/cimv2").ExecQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk WHERE Name='_Total'") + For Each objItem In colItems + TMP_READS1_KB = Round(objItem.DiskReadBytesPersec / 1024) + TMP_WRITES1_KB = Round(objItem.DiskWriteBytesPersec / 1024) + TMP_READS1 = Round(objItem.DiskReadsPersec) + TMP_WRITES1 = Round(objItem.DiskWritesPersec) + Next + + WScript.Sleep(NET_TIME * 1000) + +'Calculate again to find disk and network usage + +'Network + Set colItems = GetObject("WinMgmts:root/cimv2").ExecQuery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface") +' calculate for each network adapter + For Each objItem1 In colItems + TMP_NET_PACKETS2_IN = TMP_NET_PACKETS2_IN + objItem1.PacketsReceivedPersec + TMP_NET_PACKETS2_OUT = TMP_NET_PACKETS2_OUT + objItem1.PacketsSentPersec + TMP_NET_BYTES2_IN = TMP_NET_BYTES2_IN + objItem1.BytesReceivedPersec + TMP_NET_BYTES2_OUT = TMP_NET_BYTES2_OUT + objItem1.BytesSentPersec + Next + +'Disk + Set colItems = GetObject("WinMgmts:root/cimv2").ExecQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk WHERE Name='_Total'") + For Each objItem In colItems + TMP_READS2_KB = Round(objItem.DiskReadBytesPersec / 1024) + TMP_WRITES2_KB = Round(objItem.DiskWriteBytesPersec / 1024) + TMP_READS2 = Round(objItem.DiskReadsPersec) + TMP_WRITES2 = Round(objItem.DiskWritesPersec) + Next + + NET_KBYTES_IN=Round((TMP_NET_BYTES2_IN - TMP_NET_BYTES1_IN)/NET_TIME/1024 ) + NET_PACKETS_IN=Round((TMP_NET_PACKETS2_IN - TMP_NET_PACKETS1_IN)/NET_TIME) + + NET_KBYTES_OUT=Round((TMP_NET_BYTES2_OUT - TMP_NET_BYTES1_OUT)/NET_TIME/1024) + NET_PACKETS_OUT=Round((TMP_NET_PACKETS2_OUT - TMP_NET_PACKETS1_OUT)/NET_TIME) + + READS_KB = Round((TMP_READS2_KB - TMP_READS1_KB) / NET_TIME) + WRITES_KB = Round((TMP_WRITES2_KB - TMP_WRITES1_KB) / NET_TIME) + + READS = Round((TMP_READS2 - TMP_READS1) / NET_TIME) + WRITES = Round((TMP_WRITES2 - TMP_WRITES1) / NET_TIME) + + objRefresher.Refresh + +' CPU Usage + CPU_BUSY = ColCPU.PercentProcessorTime + CPU_IDLE = 100 - CPU_BUSY + +' Memory + For Each objItem In ColMemPh + MEM_TOTAL_MB = Round(objItem.TotalPhysicalMemory / (1024 * 1024)) + Next + + For Each objItem In ColMem + MEM_FREE_MB = objItem.AvailableMbytes + Next + + MEM_USED_MB = MEM_TOTAL_MB - MEM_FREE_MB + + If MEM_USED_MB <> 0 Then + MEM_USED_PC = Round((MEM_USED_MB * 100) / MEM_TOTAL_MB) + End If + + MEM_FREE_PC = 100 - MEM_USED_PC + +' Output area +' The first output isn't showed + If Bool Then + WScript.Echo "name=Hardware Resources|CPU|%Idle,value=" & CPU_IDLE + WScript.Echo "name=Hardware Resources|CPU|%Busy,value=" & CPU_BUSY + WScript.Echo "name=Hardware Resources|Memory|Total (MB),value=" & MEM_TOTAL_MB + WScript.Echo "name=Hardware Resources|Memory|Used (MB),value=" & MEM_USED_MB + WScript.Echo "name=Hardware Resources|Memory|Free (MB),value=" & MEM_FREE_MB + WScript.Echo "name=Hardware Resources|Memory|Used %,value=" & MEM_USED_PC + WScript.Echo "name=Hardware Resources|Memory|Free %,value=" & MEM_FREE_PC + WScript.Echo "name=Hardware Resources|Network|Incoming packets/sec,value=" & NET_PACKETS_IN + WScript.Echo "name=Hardware Resources|Network|Outgoing packets/sec,value=" & NET_PACKETS_OUT + Wscript.Echo "name=Hardware Resources|Network|Incoming KB/sec,value=" & NET_KBYTES_IN + WScript.Echo "name=Hardware Resources|Network|Outgoing KB/sec,value=" & NET_KBYTES_OUT + WScript.Echo "name=Hardware Resources|Disks|Reads/sec,value=" & READS + WScript.Echo "name=Hardware Resources|Disks|Writes/sec,value=" & WRITES + WScript.Echo "name=Hardware Resources|Disks|KB read/sec,value=" & READS_KB + WScript.Echo "name=Hardware Resources|Disks|KB written/sec,value=" & WRITES_KB + End If + Bool = 1 +Loop +WScript.Quit \ No newline at end of file diff --git a/monitors/JavaHardwareMonitor/monitor.xml b/monitors/JavaHardwareMonitor/monitor.xml new file mode 100755 index 0000000..2bec4dd --- /dev/null +++ b/monitors/JavaHardwareMonitor/monitor.xml @@ -0,0 +1,19 @@ + + SigarHardwareMonitor + managed + true + false + Monitors system resources - CPU, Memory, Network I/O, and Disk I/O, Disk Space. + + + + + java + scheduled + + internal.hardware.monitor + + + + + \ No newline at end of file diff --git a/monitors/JavaHardwareMonitor/task-template.xml b/monitors/JavaHardwareMonitor/task-template.xml new file mode 100755 index 0000000..cb25273 --- /dev/null +++ b/monitors/JavaHardwareMonitor/task-template.xml @@ -0,0 +1,10 @@ + + devfs + /dev/disk0s2 + lo0 + p2p0 + vmnet1 + en0 + en1 + vmnet8 + diff --git a/monitors/TibcoEMSMonitor/monitor.xml b/monitors/TibcoEMSMonitor/monitor.xml new file mode 100755 index 0000000..ae91067 --- /dev/null +++ b/monitors/TibcoEMSMonitor/monitor.xml @@ -0,0 +1,40 @@ + + TibcoEMSMonitorMonitor + managed + Monitors Tibco EMS + + + + periodic + 60 + Tibco EMS Monitor Run Task + Tibco EMS Monitor Task + Tibco EMS Task + java + 60 + + + + + + + + + + + + + + + ../../bin:../../lib/mysql.jar:../../machineagent.jar:../../lib/jms.jar:../../lib-tibco/slf4j-api-1.4.2.jar:../../lib-tibco/slf4j-simple-1.4.2.jar:../../lib-tibco/tibcrypt.jar:../../lib-tibco/tibemsd_sec.jar:../../lib-tibco/tibjms.jar:../../lib-tibco/tibjmsadmin.jar:../../lib-tibco/tibjmsapps.jar:../../lib-tibco/tibjmsufo.jar:../../lib-tibco/tibrvjms.jar + com.singularity.ee.agent.systemagent.monitors.common.TibcoEMSMonitor3 + + + \ No newline at end of file diff --git a/monitors/TibcoEMSMonitor/task-template.xml b/monitors/TibcoEMSMonitor/task-template.xml new file mode 100755 index 0000000..67b7695 --- /dev/null +++ b/monitors/TibcoEMSMonitor/task-template.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/readme.txt b/readme.txt new file mode 100755 index 0000000..8b3a5c6 --- /dev/null +++ b/readme.txt @@ -0,0 +1,170 @@ +et Tibco EMS Monitor for the Machine Agent +--------------------------------------- + + +tcp://localhost:7222> quit +bye +hughsmac:bin hbrien$ ./tibemsadmin + +TIBCO Enterprise Message Service Administration Tool. +Copyright 2003-2011 by TIBCO Software Inc. +All rights reserved. + +Version 6.1.0 V6 8/4/2011 + +Type 'help' for commands help, 'exit' to exit: +> connect +Login name (admin): admin +Password: +Connected to: tcp://localhost:7222 +tcp://localhost:7222> set server statistics=enabled +Server parameters have been changed +tcp://localhost:7222> + + + +A machine needs only one active machine agent installation at a time. Make sure you don't +have any previous running installation processes before you install. + +1. Edit the controller-info.xml file to point to installed controller host and controller port. + +Go to /conf/controller-info.xml and change the following tags: + + + + false , change to "true" if HTTPS is enabled between the agent and the controller. + +If the machine agent is connecting to a multi-tenant controller or the AppDynamics SaaS controller +set the account name and access key +(Otherwise these values are optional): + + + + +If the machine agent is being installed on a machine which does not have the app server agent, +or the machine agent will be installed BEFORE the app server agent, these tags may be added: + + , the name of the application this machine belongs to. + , the tier this machine is associated with. + , the node name assigned to this machine. + +This information can also be specified using environment variables or system properties: + +Using Environment Variables to specify the information in controller-info.xml +-------------------------------------------------------------------------------- + + +Controller Host APPDYNAMICS_CONTROLLER_HOST_NAME +Controller Port APPDYNAMICS_CONTROLLER_PORT +Agent Account Name APPDYNAMICS_AGENT_ACCOUNT_NAME +Agent Account Access Key APPDYNAMICS_AGENT_ACCOUNT_ACCESS_KEY +Application Name APPDYNAMICS_AGENT_APPLICATION_NAME +Tier Name APPDYNAMICS_AGENT_TIER_NAME +Node Name APPDYNAMICS_AGENT_NODE_NAME +SSL Enabled APPDYNAMICS_CONTROLLER_SSL_ENABLED + + +Using System Properties to specify the information in controller-info.xml +-------------------------------------------------------------------------------- + + +Controller Host appdynamics.controller.hostName +Controller Port appdynamics.controller.port +Agent Account Name appdynamics.agent.accountName +Agent Account Access Key appdynamics.agent.accountAccessKey +Application Name appdynamics.agent.applicationName +Tier Name appdynamics.agent.tierName +Node Name appdynamics.agent.nodeName +SSL Enabled appdynamics.controller.ssl.enabled + + +2. The machine agent does not ship with a JRE. It runs with any JRE version 1.5 or higher. + +The following command will start it - + + +java -jar machineagent.jar + + +The machineagent.jar file would be in the directory where you extracted the machine agent. + +3. Verify that the agent has been installed correctly. + +Check that you have received the following message that the java agent was started successfully in the agent.log file in your /logs/agent.log folder. +This message is also printed on the stdout of the process. + +Started APPDYNAMICS Machine Agent Successfully. + + +4. If you are installing the machine agent on a machine which has a running app server agent, the hardware data is automatically assigned to the app server node/s running + on the machine. + +5. If you are installing the machine agent on a machine which does not have a running app server agent i.e. on a database server/ Message server, or if you did not +specify the Application Name and Tier Name explicitly in Step 1 + + a) you will have to register the machine agent and associate it with an application. + b) once the relevant database server/message server is discovered in a business transaction, click on the display name link and then on 'Resolve' to associate + the hardware data to the right tier. + + +Creating and running a custom monitor/script to send data to the controller as part of the machine agent. +------------------------------------------------------------------------------------------------------------ + + A custom monitor has a script attached to it which writes data to the STDOUT of the process in a specific format. This is parsed automatically by the + machine agent and sent as data to the controller every minute. Every metric has a name and a value which is converted to a java 'long' value. + + The format of the line is + + name=,value= + + The metric names must start either with "Hardware Resources|" or with "Custom Metrics|". You can use "|" separator + for further hierarchy in the metric name. For example: + "Hardware Resources|Disks|Total Disk Usage %" + "Hardware Resources|Disks|Disk 1|Current Disk Usage %" + + "Custom Metrics|MySQL|Avg Query Time" + "Custom Metrics|Apache|Avg Wait Time" + + If you have multiple metrics, print a different line for each one of them. For example: + name=Hardware Resources|Disks|Total Disk Usage %, value=23 + name=Hardware Resources|Disks|Disk 1|Current Disk Usage %, value=56 + name=Custom Metrics|MySQL|Avg Query Time, value=500 + name=Custom Metrics|Apache|Avg Wait Time, value=800 + +Please Refer to http://help.appdynamics.com/entries/318710-use-custom-monitor-to-extend-appdynamics-monitoring-capability for more help with adding custom metrics. + +Connecting to the Controller through a Proxy Server +-------------------------------------------------- + +Use the following system properties to set the host and port of the proxy server so that it can route requests to the controller. + +com.singularity.httpclientwrapper.proxyHost= +com.singularity.httpclientwrapper.proxyPort= + + +Specifying custom host name +--------------------------- + +The host name for the machine on which the Agent is running is used as an identifying property for the Agent Node. +If the machine host name is not constant or if you prefer to use a specific name of your choice, please specify the +following system property as part of your startup command. + +-Dappdynamics.agent.uniqueHostId= + + +Uploading custom metrics with HTTP URL +--------------------------------------- +1) Start Machine agent with an additional parameter. +java -Dmetric.http.listener=true -jar machineagent.jar + +This starts an http listener on port 8293. To use a different port , use the system property metric.http.listener.port. + +2) Use the metric upload URL to upload metrics, e.g. +http://localhost:8293/machineagent/metrics?name=Custom Metrics|ACME|Cache Access&value=20&type=sum +to sum up all values for the last minute. + +http://localhost:8293/machineagent/metrics?name=Hardware Resources|ACME|Cache Size&value=50&type=average +to average all values for last minute + +In the example above 'Custom Metrics|ACME|Cache Access' is the name of the metric here. + diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..60345e6 --- /dev/null +++ b/run.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +java -classpath ./bin -jar machineagent.jar \ No newline at end of file diff --git a/scripts/extend-os-version.sh b/scripts/extend-os-version.sh new file mode 100755 index 0000000..bed2f16 --- /dev/null +++ b/scripts/extend-os-version.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +[ -z "$1" ] && exit 1 + +if [ "$1" == "solaris" ] || [ "$1" == "sunos" ]; then + if [ -f /usr/sbin/zoneadm ]; then + /usr/sbin/zoneadm list -vi | grep `zonename` | awk '{ print $1 }' + if [ $? -eq 0 ]; then + echo "global" + else + echo "non-global" + fi + exit 0 + else + exit 1 + fi +elif [ "$1" == "mac os x" ]; then + echo "lion" + exit 0 +else + exit 1 +fi diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/CollectionTesting.java b/src/com/singularity/ee/agent/systemagent/monitors/common/CollectionTesting.java new file mode 100755 index 0000000..f4f85f9 --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/CollectionTesting.java @@ -0,0 +1,95 @@ +/** + * + */ +package com.singularity.ee.agent.systemagent.monitors.common; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.HashMap; +import java.util.Date; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.*; + + + +/** + * @author hbrien + * + * + */ +public class CollectionTesting { + + Map stringMap = new HashMap(); + + + + public void run() { + + for (int i = 0; i < 20000; i++) { + stringMap.put("key" + i, "Joe App :" + 1 + new Date().toString()); + //System.out.println(("key" + i + ":" + "Joe App : " + new Date().toString())); + } + + for (String key : stringMap.keySet()) { + + //System.out.println( key + ":" + stringMap.get(key)); + } + + Map dateMap = new LinkedHashMap(); + for (int j = 0; j < 20000; j++) { + dateMap.put(new Integer(j).toString(), new Date()); + } + + for (String key : dateMap.keySet()) { + Date dateValue = dateMap.get(key); + //System.err.println(key + " " + dateValue.toString()); + + } + + + Stack stack = new Stack(); + stack.push("Hugh"); + stack.push("Joe"); + stack.push("What"); + stack.push("Hello"); + stack.push("Where"); + + while(!stack.isEmpty()) + { + String name = stack.pop(); + System.out.println(name); + } + + Queue queue = new PriorityQueue(); + queue.add("Hugh"); + queue.add("Bill"); + queue.add("Brien"); + queue.add("Knowledge"); + queue.add("Demo"); + queue.add(new Date().toString()); + System.out.println("================================"); + while (!queue.isEmpty()) { + String value = queue.remove(); + System.out.println(value); + + + } + + + + + + + + } + /** + * @param args + */ + public static void main(String[] args) { + + new CollectionTesting().run(); + + } + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/JavaServersMonitor.java b/src/com/singularity/ee/agent/systemagent/monitors/common/JavaServersMonitor.java new file mode 100644 index 0000000..7d20acb --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/JavaServersMonitor.java @@ -0,0 +1,243 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.singularity.ee.agent.systemagent.api.AManagedMonitor; +import com.singularity.ee.agent.systemagent.api.EnvPropertyWriter; +import com.singularity.ee.agent.systemagent.api.MetricWriter; +import com.singularity.ee.agent.systemagent.api.TaskExecutionContext; +import com.singularity.ee.agent.systemagent.api.TaskOutput; +import com.singularity.ee.agent.systemagent.api.exception.TaskExecutionException; + +public abstract class JavaServersMonitor extends AManagedMonitor +{ + protected final Logger logger = Logger.getLogger(this.getClass().getName()); + + protected volatile String host; + protected volatile String port; + protected volatile String userName; + protected volatile String passwd; + protected volatile String serverRoot = "C:/Program Files/Apache Software Foundation/Apache2.2"; // root directory of the server we are monitoring (for finding files or deploying programs) + protected volatile String restartAllowed = "TRUE"; + + protected volatile Map oldValueMap; + protected volatile Map valueMap; + protected volatile long oldTime = 0; + protected volatile long currentTime = 0; + + public abstract TaskOutput execute(Map taskArguments, TaskExecutionContext taskContext) + throws TaskExecutionException; + + protected void parseArgs(Map args) + { + host = getArg(args, "host", "3localhost"); + userName = getArg(args, "user", userName); + passwd = getArg(args, "password", passwd); + port = getArg(args, "port", "90"); + serverRoot = getArg(args, "serverRoot", serverRoot); + restartAllowed = getArg(args, "restartAllowed", restartAllowed); + } + + // safe way to get parameter from monitor, but if null, use default + protected String getArg(Map args,String arg, String oldVal) + { + String result = args.get(arg); + + if (result == null) + return oldVal; + + return result; + } + + protected void printStringMetric(String name, String value) + { + String metricName = getMetricPrefix() + name; + EnvPropertyWriter writer = this.getPropertyWriter(); + writer.printEnvironmentProperty(metricName, value); + + // just for debug output + + if (logger.isDebugEnabled()) + { + logger.debug("METRIC STRING: NAME:" + name + " VALUE:" + value); + } + } + + protected void printMetric(String name, String value, String aggType, String timeRollup, String clusterRollup) + { + String metricName = getMetricPrefix() + name; + MetricWriter metricWriter = getMetricWriter(metricName, aggType, timeRollup, clusterRollup); + metricWriter.printMetric(value); + + // just for debug output + if (logger.isDebugEnabled()) + { + logger.debug("METRIC: NAME:" + metricName + " VALUE:" + value + " :" + aggType + ":" + timeRollup + ":" + + clusterRollup); + } + } + + protected String getMetricPrefix() + { + return ""; + } + + protected void startExecute(Map taskArguments, TaskExecutionContext taskContext) + { + valueMap = Collections.synchronizedMap(new HashMap()); + parseArgs(taskArguments); + } + + protected TaskOutput finishExecute() + { + oldValueMap = valueMap; + oldTime = currentTime; + + // just for debug output + logger.debug("Finished METRIC COLLECTION for Monitor......."); + + return new TaskOutput("Success"); + } + + protected void close(ResultSet rs, Statement stmt, Connection conn) + { + if (rs != null) + { + try + { + rs.close(); + } + catch (Exception e) + { + // ignore + } + } + + if (stmt != null) + { + try + { + stmt.close(); + } + catch (Exception e) + { + // ignore + } + } + + if (conn != null) + { + try + { + conn.close(); + } + catch (Exception e) + { + // ignore + } + } + } + + protected String getString(float num) + { + int result = Math.round(num); + return Integer.toString(result); + } + + // lookup value for key, convert to float, round up or down and then return as string form of int + protected String getString(String key) + { + return getString(key, true); + } + + // specify whether to convert this key to uppercase before looking up the value + protected String getString(String key, boolean convertUpper) + { + if (convertUpper) + key = key.toUpperCase(); + + String strResult = valueMap.get(key); + + if (strResult == null) + return "0"; + + // round the result to a integer since we don't handle fractions + float result = Float.valueOf(strResult); + String resultStr = getString(result); + return resultStr; + } + + protected String getPercent(String numerator, String denumerator) + { + float tmpResult = 0; + + try + { + tmpResult = getValue(numerator) / getValue(denumerator); + } + catch (Exception e) + { + return null; + } + tmpResult = tmpResult * 100; + return getString(tmpResult); + } + + protected String getReversePercent(float numerator, float denumerator) + { + if (denumerator == 0) + return null; + + float tmpResult = numerator / denumerator; + tmpResult = 1 - tmpResult; + tmpResult = tmpResult * 100; + return getString(tmpResult); + } + + protected String getPercent(float numerator, float denumerator) + { + if (denumerator == 0) + return getString(0); + + float tmpResult = numerator / denumerator; + tmpResult = tmpResult * 100; + return getString(tmpResult); + } + + // math utility + protected float getValue(String key) + { + String strResult = valueMap.get(key.toUpperCase()); + + if (strResult == null) + return 0; + + float result = Float.valueOf(strResult); + return result; + } + + protected float getDiffValue(String key) + { + String strResult = valueMap.get(key.toUpperCase()); + + if (strResult == null) + return 0; + + float result = Float.valueOf(strResult); + float oldResult = 0; + + String oldResultStr = oldValueMap.get(key.toUpperCase()); + if (oldResultStr != null) + oldResult = Float.valueOf(oldResultStr); + + return (result - oldResult); + } + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/MessageTester.java b/src/com/singularity/ee/agent/systemagent/monitors/common/MessageTester.java new file mode 100644 index 0000000..f85b6d6 --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/MessageTester.java @@ -0,0 +1,93 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +import javax.jms.Message; +import javax.jms.Queue; +import javax.jms.QueueConnection; +import javax.jms.JMSException; +import javax.jms.QueueSession; +import javax.jms.TextMessage; + +import com.tibco.tibjms.Tibjms; +import com.tibco.tibjms.TibjmsConnectionFactory; +import com.tibco.tibjms.TibjmsQueueConnectionFactory; + +public class MessageTester { + + + public QueueConnection createConnection() { + + TibjmsQueueConnectionFactory factory = new TibjmsQueueConnectionFactory("tcp://hughsmac:7222", "Tester1"); + + try { + return factory.createQueueConnection("admin","admin"); + + } catch (JMSException e) { + + e.printStackTrace(); + return null; + } + + } + + public void createMessages() { + + QueueConnection conn = createConnection(); + if (conn != null) + { + + System.out.println(conn.toString()); + try { + printLines(conn.getMetaData().getJMSProviderName()); + printLines(conn.getClass().getName()); + QueueSession session = conn.createQueueSession(false, Tibjms.NO_ACKNOWLEDGE); + Queue que1 = new com.tibco.tibjms.TibjmsQueue("DEMO_QUEUE_04"); + + while(true){ + + TextMessage message = session.createTextMessage(); + String mesg = "Demo Message One" + new java.util.Date().toString(); + message.setText(mesg); + session.createSender(que1).send(message); + printLines(mesg); + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + + + + + + } catch (JMSException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + + } + + + + public void printLines(String value) { + + System.out.println(value); + + } + + /** + * @param args + */ + public static void main(String[] args) { + new MessageTester().createMessages(); + + } + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/SystemTopicSubscriber.java b/src/com/singularity/ee/agent/systemagent/monitors/common/SystemTopicSubscriber.java new file mode 100755 index 0000000..75d6e36 --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/SystemTopicSubscriber.java @@ -0,0 +1,211 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +/** + * This class will (adopted from the EMS samples) + * be used to durably subscribe to system topics published + * by the Tibco Hawk micro-agent embedded inside the Tibco + * Enterprise Messaging Service (EMS). + * + * Copyright (c) AppDynamics, Inc. + * @author Pranta Das + * February 2, 2012. + * + */ + +import javax.jms.Destination; +import javax.jms.ExceptionListener; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.TopicConnection; +import javax.jms.TopicConnectionFactory; +import javax.jms.TopicSession; +import javax.jms.TopicSubscriber; +import javax.naming.Context; + +public class SystemTopicSubscriber implements MessageListener, + ExceptionListener { + static Context jndiContext = null; + + static final String providerContextFactory = "com.tibco.tibjms.naming.TibjmsInitialContextFactory"; + + static final String defaultProtocol = "tibjmsnaming"; + + static final String defaultProviderURL = defaultProtocol + + "://192.168.105.141:7222"; + + String serverUrl = null; + String userName = "admin"; + String password = null; + + String durableName = "ad_subscriber"; + + final static String sysTopics[][] = { + + { "$sys.monitor.Q.*.com.appd.*", "Performance of logs" } + + }; + //{ "com.appd.*", "Stats on all com.appd.* queue" }, + + /** + * In addition to the above, one can subscribe to destination specific + * monitor topics: + * + * $sys.monitor.D.E.destination + * + * A message is handled by a destination. The name of this monitor topic + * includes two qualifiers (D and E) and the name of the destination you + * wish to monitor. D signifies the type of destination and whether to + * include the entire message: + * + * - T : topic, include full message (as a byte array) into each event - t : + * topic, do not include full message into each event - Q : queue, include + * full message (as a byte array) into each event - q : queue, do not + * include full message into each event + * + * E signifies the type of event: + * + * - r for receive - s for send - a for acknowledge - p for premature exit + * of message - * for all event types + * + * For example, $sys.monitor.T.r.corp.News is the topic for monitoring any + * received messages to the topic named corp.News. The message body of any + * received messages is included in monitor messages on this topic. The + * topic $sys.monitor.q.*.corp.* monitors all message events (send, receive, + * acknowledge) for all queues matching the name corp.*. The message body is + * not included in this topic's messages. + */ + + + public static void main(String[] args) throws Exception { + new SystemTopicSubscriber(args); + + } + + public SystemTopicSubscriber(String[] args) { + + parseArgs(args); + TopicConnectionFactory factory = null; + TopicConnection connection = null; + TopicSession session = null; + javax.jms.Topic topic = null; + TopicSubscriber subscriber = null; + + try + + { + factory = new com.tibco.tibjms.TibjmsTopicConnectionFactory(serverUrl); + connection = factory.createTopicConnection(userName, password); + session = connection.createTopicSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); + for (int i = 0; i < sysTopics.length; i++) { + /* + * Lookup the topic and subscribe to it. + */ + try { + topic = session.createTopic(sysTopics[i][0]); + + } catch (Exception e) { + System.out.println("Unable to create topic:" + + sysTopics[i][0]); + continue; + } + System.out.println("Creating a durable subscriber to topic: " + sysTopics[i][0]); + subscriber = session.createDurableSubscriber(topic, durableName + sysTopics[i][0]); + subscriber.setMessageListener(this); + } + connection.setExceptionListener(this); + connection.start(); + + /* read topic messages */ + System.out.print("Waiting for messages"); + + while (true) { + Thread.sleep(1000); + System.out.print("."); + } + + // connection.close(); + } catch (Throwable e) { + e.printStackTrace(); + System.exit(0); + } + } + + /** + * This method is called asynchronously by JMS when a message arrives at the + * topic. Client applications must not throw any exceptions in the onMessage + * method. + * + * @param message + * A JMS message. + */ + public void onMessage(Message message) { + com.tibco.tibjms.TibjmsMapMessage msg = (com.tibco.tibjms.TibjmsMapMessage) message; + System.out.println("received: " + msg.toString()); + Destination destination = null; + try { + destination = msg.getJMSDestination(); + if (destination != null) { + System.out.println(destination); + } + } catch (JMSException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + * This method is called asynchronously by JMS when some error occurs. When + * using an asynchronous message listener it is recommended to use an + * exception listener also since JMS have no way to report errors otherwise. + * + * @param exception + * A JMS exception. + */ + public void onException(JMSException exception) { + System.err.println("something bad happended: " + exception); + } + + void usage() { + System.err.println("\nUsage: java SystemTopicSubscriber [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err + .println(" -server - EMS server URL, default is local server"); + System.err + .println(" -user - user name, default is null"); + System.err + .println(" -password - password, default is null"); + System.exit(0); + } + + void parseArgs(String[] args) { + int i = 0; + + while (i < args.length) { + if (args[i].compareTo("-server") == 0) { + if ((i + 1) >= args.length) + usage(); + serverUrl = args[i + 1]; + i += 2; + } else if (args[i].compareTo("-user") == 0) { + if ((i + 1) >= args.length) + usage(); + userName = args[i + 1]; + i += 2; + } else if (args[i].compareTo("-password") == 0) { + if ((i + 1) >= args.length) + usage(); + password = args[i + 1]; + i += 2; + } else if (args[i].compareTo("-help") == 0) { + usage(); + } else { + System.err.println("Unrecognized parameter: " + args[i]); + usage(); + } + } + } +} \ No newline at end of file diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMS.java b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMS.java new file mode 100755 index 0000000..93b4134 --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMS.java @@ -0,0 +1,101 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +import javax.management.Query; + +import com.tibco.tibjms.admin.ConnectionInfo; +import com.tibco.tibjms.admin.ConsumerInfo; +import com.tibco.tibjms.admin.DetailedDestStat; +import com.tibco.tibjms.admin.QueueInfo; +import com.tibco.tibjms.admin.TibjmsAdmin; +import com.tibco.tibjms.admin.TibjmsAdminException; + + +public class TibcoEMS { + + String[] serverURL = {"tcp://hughsmac:7222"}; + + String userid = "admin"; + String password = "admin"; + + + + + + public void start() { + try { + TibjmsAdmin tibcoAdmin = new TibjmsAdmin(serverURL[0], userid, password); + + System.out.println("Connection Information"); + ConnectionInfo[] connectionInformation = tibcoAdmin.getSystemConnections(); + for (int i = 0; i < connectionInformation.length; i++) { + ConnectionInfo connectionInfo = connectionInformation[i]; + System.out.println("====================================="); + String host = connectionInfo.getHost(); + System.out.println("Host\t"+ host); + System.out.println("Connection Product Count\t" + connectionInfo.getProducerCount()); + System.out.println("Address\t" + connectionInfo.getAddress()); + System.out.println("Client Type\t" + connectionInfo.getClientType()); + System.out.println("Session Count\t " + connectionInfo.getSessionCount()); + } + + + ConsumerInfo[] consumers = tibcoAdmin.getConsumersStatistics(); + System.out.println("Consumer Information"); + + for (int i = 0; i < consumers.length; i++) { + ConsumerInfo consumerInfo = consumers[i]; + System.out.println("Durable Name\t\t" + consumerInfo.getDurableName()); + System.out.println("==============================="); + + + ConsumerInfo.Details details = consumerInfo.getDetails(); + if (details != null) { + System.out.println("ElapsedSinceLastSent " + consumerInfo.getDetails().getElapsedSinceLastSent()); + System.out.println("TotalAcknowledgedCount " + consumerInfo.getDetails().getTotalAcknowledgedCount()); + System.out.println("CurrentMsgCountSentByServer " + consumerInfo.getDetails().getCurrentMsgCountSentByServer()); + } + System.out.println("DestinationName\t\t" + consumerInfo.getDestinationName()); + System.out.println("Username\t\t" + consumerInfo.getUsername()); + System.out.println("PendingMessageCount\t\t" + consumerInfo.getPendingMessageCount()); + System.out.println("PendingMessageSize\t\t" + consumerInfo.getPendingMessageSize()); + System.out.println("Selector\t\t" + consumerInfo.getSelector()); + System.out.println("ConnectionID\t" + consumerInfo.getConnectionID()); + System.out.println(""); + } + + System.out.println(""); + System.out.println("Queue Information"); + QueueInfo[] queueInformation = tibcoAdmin.getQueuesStatistics(); + for (int i = 0; i < queueInformation.length; i++) { + QueueInfo queueInfo = queueInformation[i]; + System.out.println(queueInfo.getName()); + System.out.println("================================"); + System.out.println("Consumer Count\t\t\t" + queueInfo.getConsumerCount()); + System.out.println("Delivered Message Count\t\t" + queueInfo.getDeliveredMessageCount()); + System.out.println("Flow Control Max Bytes\t\t" + queueInfo.getFlowControlMaxBytes()); + System.out.println("Pending Message Count\t\t" + queueInfo.getPendingMessageCount()); + System.out.println(""); + } + + + System.out.println("Closing Connection to Server"); + tibcoAdmin.close(); + + + } catch (TibjmsAdminException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + public static void main(String[] args) { + new TibcoEMS().start(); + + } + + + + + + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSConnectionCheck.java b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSConnectionCheck.java new file mode 100755 index 0000000..2c7f15b --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSConnectionCheck.java @@ -0,0 +1,86 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +import java.util.HashMap; +import java.util.Map; + +import javax.management.Query; + +import com.tibco.tibjms.admin.ConnectionInfo; +import com.tibco.tibjms.admin.ConsumerInfo; +import com.tibco.tibjms.admin.DetailedDestStat; +import com.tibco.tibjms.admin.QueueInfo; +import com.tibco.tibjms.admin.TibjmsAdmin; +import com.tibco.tibjms.admin.TibjmsAdminException; + + +public class TibcoEMSConnectionCheck { + + String[] serverURL = { + "tcp://tparhetibu027.nielsen.com:57223", + "tcp://tparhetibu027.nielsen.com:57225", + "tcp://tparhetibu034.nielsen.com:57222", + "tcp://tparhetibu035.nielsen.com:57222"}; + + String userid = "appdynamicpocuser"; + String password = "appdynamicpocpwd"; + + Map connectionSuccessMap = new HashMap(); + + + TibjmsAdmin tibcoAdmin = null; + + public void execute() { + + for (int i = 0; i < serverURL.length; i++) { + try { + tibcoAdmin = new TibjmsAdmin(serverURL[i], userid, password); + System.out.println(tibcoAdmin.toString()); + System.out.println("Connection " + serverURL[i] + " Successful"); + + connectionSuccessMap.put(tibcoAdmin, new Boolean(true)); + + } catch (TibjmsAdminException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + public void printResult() { + for (TibjmsAdmin connection : connectionSuccessMap.keySet()) { + System.out.println(connection + " : " + connectionSuccessMap.get(connection)); + } + } + + + + public static void main(String[] args) { + + TibcoEMSConnectionCheck connection = new TibcoEMSConnectionCheck(); + connection.execute(); + connection.printResult(); + connection.cleanup(); + } + + private void cleanup() { + + for (TibjmsAdmin connection : connectionSuccessMap.keySet()) { + try { + connection.close(); + System.out.println(connection + " Closed"); + } catch (TibjmsAdminException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + + } + + + + + + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor.java b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor.java new file mode 100755 index 0000000..4813396 --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor.java @@ -0,0 +1,114 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.Date; +import java.util.Map; + +import com.singularity.ee.agent.systemagent.api.MetricWriter; +import com.singularity.ee.agent.systemagent.api.TaskExecutionContext; +import com.singularity.ee.agent.systemagent.api.TaskOutput; +import com.singularity.ee.agent.systemagent.api.exception.TaskExecutionException; + +public class TibcoEMSMonitor extends JavaServersMonitor { + + Connection conn = null; + + private volatile String tierName; + private volatile String userid; + private volatile String password; + private volatile String hostname; + private volatile String port; + + + @Override + public TaskOutput execute(Map taskArguments, TaskExecutionContext taskContext) + throws TaskExecutionException + { + startExecute(taskArguments, taskContext); + + try + { + populate(valueMap, new String[]{"show global variables", "show global status"}); + } + catch (Exception ex) + { + throw new TaskExecutionException(ex); + } + + String adminChange = "$sys.monitor.admin.change"; //The administrator has made a change to the configuration. + String userConnects = "$sys.monitor.connection.connect"; //A user attempts to connect to the server. + String userDisconnects = "$sys.monitor.connection.disconnect"; //A user connection is disconnected. + String userErrorConnection = "$sys.monitor.connection.error"; //An error occurs on a user connection. + String consumerCreate = "$sys.monitor.consumer.create"; //A consumer is created. + String consumerDestroy = "$sys.monitor.consumer.destroy"; //A consumer is destroyed. + String monitorMessageFlow = "$sys.monitor.flow.engaged"; //Stored messages rise above a destinationŐs limit, + + logger.debug("Starting METRIC COLLECTION for Tibco EMS Monitor......."); + + + + print("Resource Utilization|Total Active Threads", "10.0"); + + return this.finishExecute(); + } + + + // collects all monitoring data for this time period from database + private void populate(Map valueMap, String[] queries) throws Exception + { + + boolean debug = logger.isDebugEnabled(); + valueMap.put("Queue1|Size".toUpperCase(), new Long(new Date().getTime()).toString()); + valueMap.put("Queue2|Size".toUpperCase(), new Long(new Date().getTime()).toString()); + valueMap.put("Queue3|Size".toUpperCase(), new Long(new Date().getTime()).toString()); + valueMap.put("Queue4|Size".toUpperCase(), new Long(new Date().getTime()).toString()); + valueMap.put("Queue5|Size".toUpperCase(), new Long(new Date().getTime()).toString()); + valueMap.put("Queue6|Size".toUpperCase(), new Long(new Date().getTime()).toString()); + valueMap.put("Queue7|Size".toUpperCase(), new Long(new Date().getTime()).toString()); + currentTime = System.currentTimeMillis(); + } + + + protected String getMetricPrefix() + { + if (tierName != null) + { + return "Server|Component:"+tierName+"|EMS Server|"; + } + else + { + return "Custom Metrics|EMS Server|"; + } + } + + + protected void parseArgs(Map args) + { + super.parseArgs(args); + tierName = getArg(args, "tier", null); // if the tier is not specified then create the metrics for all tiers + userid = getArg(args, "userid", null); + password = getArg(args, "password", null); + hostname = getArg(args, "hostname", null); + port = getArg(args, "port", "7222"); + } + + + public void print(String metricName, String value) { + + printMetric(metricName, getString(value), + MetricWriter.METRIC_AGGREGATION_TYPE_OBSERVATION, MetricWriter.METRIC_TIME_ROLLUP_TYPE_CURRENT, + MetricWriter.METRIC_CLUSTER_ROLLUP_TYPE_COLLECTIVE); + + } + + + private String connect() + { + return ""; + } + + + + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor2.java b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor2.java new file mode 100755 index 0000000..b813c3c --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor2.java @@ -0,0 +1,174 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + + + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.singularity.ee.agent.systemagent.api.MetricWriter; +import com.singularity.ee.agent.systemagent.api.TaskExecutionContext; +import com.singularity.ee.agent.systemagent.api.TaskOutput; +import com.singularity.ee.agent.systemagent.api.exception.TaskExecutionException; +import com.singularity.ee.agent.systemagent.monitors.common.JavaServersMonitor; +import com.singularity.ee.util.clock.ClockUtils; + +public class TibcoEMSMonitor2 extends JavaServersMonitor +{ + private volatile String tierName; + private volatile String database; // the database we are interested in collecting metrics on + private volatile int refreshIntervalInExecutionTicks; + private final Map cachedValueMap; + private volatile int currentNumExecutionTicks = -1; + private volatile List columnNames; + + public TibcoEMSMonitor2() + { + oldValueMap = Collections.synchronizedMap(new HashMap()); + cachedValueMap = Collections.synchronizedMap(new HashMap()); + } + + protected void parseArgs(Map args) + { + super.parseArgs(args); + tierName = getArg(args, "tier", null); // if the tier is not specified then create the metrics for all tiers + database = getArg(args, "target-database", "postgres"); + + // Assume all the columns we want values for are in a comma separated list + String columnNamesString = getArg(args, "columns", null); + + if (columnNamesString == null || columnNamesString.length() == 0) + { + columnNames = Collections.emptyList(); + } + else + { + columnNames = Arrays.asList(columnNamesString.split(",")); + } + + int refreshIntervalSecs = Integer.parseInt(getArg(args, "refresh-interval", "60")); + + if (refreshIntervalSecs <= 60) + { + refreshIntervalInExecutionTicks = 1; + } + else + { + // Convert refresh interval to milliseconds and round up to the nearest minute timeslice. + // From that we can get the number of 60 second ticks before the next refresh. + // We do this to prevent time drift issues from preventing this task from running. + refreshIntervalInExecutionTicks = (int)(ClockUtils.roundUpTimestampToNextMinute(refreshIntervalSecs*1000)/60000); + } + + if (currentNumExecutionTicks == -1) + { + // This is the first time we've parsed the args. Assume we refresh the data + // the next time we execute the monitor. + currentNumExecutionTicks = refreshIntervalInExecutionTicks; + } + } + + private boolean connect() + { + + logger.debug("Successfully connected to Postgres DB"); + return true; + + } + + // collects all monitoring data for this time period from database + private Map getValuesForColumns(List columnNames, + String query) throws Exception { + Map columnName2Value = new HashMap(); + + boolean debug = logger.isDebugEnabled(); + + //columnName2Value.put(columnName.toUpperCase(), value); + return Collections.synchronizedMap(columnName2Value); + } + + public TaskOutput execute(Map taskArguments, TaskExecutionContext taskContext) + throws TaskExecutionException + { + startExecute(taskArguments, taskContext); + + try + { + if (++currentNumExecutionTicks >= refreshIntervalInExecutionTicks) + { + logger.debug("Querying fresh values for Postgres PgStatActivity Monitor......."); + + // Store the current values for the columns specified in the list + valueMap = getValuesForColumns(columnNames, "select * from pg_stat_database where datname='"+database+"'"); + + // Update the cached values + cachedValueMap.clear(); + cachedValueMap.putAll(valueMap); + + currentNumExecutionTicks = 0; + } + else + { + logger.debug("Using cached values for Postgres PgStatActivity Monitor......."); + + // Use the cached values + valueMap = Collections.synchronizedMap(new HashMap(cachedValueMap)); + } + } + catch (Exception ex) + { + throw new TaskExecutionException(ex); + } + + // just for debug output + logger.debug("Starting METRIC COLLECTION for Postgres PgStatActivity Monitor......."); + + Set uniqueColumnNames = new HashSet(columnNames); + + printMetric("numbackends", "PgStatActivity|Num Backends", uniqueColumnNames); + printMetric("xact_commit", "PgStatActivity|Txn Commits", uniqueColumnNames); + printMetric("xact_rollback", "PgStatActivity|Txn Rollbacks", uniqueColumnNames); + printMetric("blks_read", "PgStatActivity|Blocks Read", uniqueColumnNames); + printMetric("blks_hit", "PgStatActivity|Blocks Hit", uniqueColumnNames); + printMetric("tup_returned", "PgStatActivity|Tuples Returned", uniqueColumnNames); + printMetric("tup_fetched", "PgStatActivity|Tuples Fetched", uniqueColumnNames); + printMetric("tup_inserted", "PgStatActivity|Tuples Inserted", uniqueColumnNames); + printMetric("tup_updated", "PgStatActivity|Tuples Updated", uniqueColumnNames); + printMetric("tup_deleted", "PgStatActivity|Tuples Deleted", uniqueColumnNames); + + return this.finishExecute(); + } + + private void printMetric(String columnName, String metricLabel, Set uniqueColumnNames) + { + if (uniqueColumnNames.contains(columnName)) + { + printMetric(metricLabel, getString(columnName), + MetricWriter.METRIC_AGGREGATION_TYPE_OBSERVATION, + MetricWriter.METRIC_TIME_ROLLUP_TYPE_CURRENT, + MetricWriter.METRIC_CLUSTER_ROLLUP_TYPE_COLLECTIVE); + } + } + + protected String getMetricPrefix() + { + if (tierName != null) + { + return "Server|Component:"+tierName+"|Postgres Server|"+database+"|"; + } + else + { + return "Custom Metrics|Postgres Server|"+database+"|"; + } + } + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor3.java b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor3.java new file mode 100755 index 0000000..a804fce --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEMSMonitor3.java @@ -0,0 +1,296 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +//import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +//import java.util.HashSet; +import java.util.Iterator; +//import java.util.List; +import java.util.Map; +//import java.util.Set; + +import com.singularity.ee.agent.systemagent.api.MetricWriter; +import com.singularity.ee.agent.systemagent.api.TaskExecutionContext; +import com.singularity.ee.agent.systemagent.api.TaskOutput; +import com.singularity.ee.agent.systemagent.api.exception.TaskExecutionException; +import com.singularity.ee.util.clock.ClockUtils; +import com.tibco.tibjms.admin.*; + +public class TibcoEMSMonitor3 extends JavaServersMonitor { + private volatile String tierName; + private volatile String serverName; + private volatile int refreshIntervalInExecutionTicks; + private final Map cachedValueMap; + private volatile int currentNumExecutionTicks = -1; +// private volatile List columnNames; + + private volatile String userid; + private volatile String password; + private volatile String hostname; + private volatile String port; + private String showTempQueues = "false"; + private String showSysQueues = "true"; + Boolean showTempQueuesValue = new Boolean(false); + Boolean showSysQueuesValue = new Boolean(true); + + public TibcoEMSMonitor3() { + oldValueMap = Collections + .synchronizedMap(new HashMap()); + cachedValueMap = Collections + .synchronizedMap(new HashMap()); + } + + protected void parseArgs(Map args) { + super.parseArgs(args); + tierName = getArg(args, "tier", "tibcoems"); // if the tier is not specified + // then create the metrics for + // all tiers + userid = getArg(args, "userid", "admin"); + password = getArg(args, "password", "admin"); + hostname = getArg(args, "hostname", "localhost"); + port = getArg(args, "port", "7222"); + serverName = getArg(args, "emsservername", null); + showTempQueues = getArg(args, "showTempQueues", "false"); + showSysQueues = getArg(args, "showSysQueues", "true"); + showTempQueuesValue = new Boolean(showTempQueues); + showSysQueuesValue = new Boolean(showSysQueues); + + + + // Assume all the columns we want values for are in a comma separated + // list +// String columnNamesString = getArg(args, "columns", null); +// +// if (columnNamesString == null || columnNamesString.length() == 0) { +// columnNames = Collections.emptyList(); +// } else { +// columnNames = Arrays.asList(columnNamesString.split(",")); +// } + + int refreshIntervalSecs = Integer.parseInt(getArg(args, "refresh-interval", "60")); + + if (refreshIntervalSecs <= 60) { + refreshIntervalInExecutionTicks = 1; + } else { + // Convert refresh interval to milliseconds and round up to the + // nearest minute timeslice. + // From that we can get the number of 60 second ticks before the + // next refresh. + // We do this to prevent time drift issues from preventing this task + // from running. + refreshIntervalInExecutionTicks = (int) (ClockUtils + .roundUpTimestampToNextMinute(refreshIntervalSecs * 1000) / 60000); + } + + if (currentNumExecutionTicks == -1) { + // This is the first time we've parsed the args. Assume we refresh + // the data + // the next time we execute the monitor. + currentNumExecutionTicks = refreshIntervalInExecutionTicks; + } + } + + private TibjmsAdmin connect() throws TibjmsAdminException { + + logger.debug("Connecting to tcp://" + hostname + ":"+ port + " " + userid + " " + password); + TibjmsAdmin tibcoAdmin = new TibjmsAdmin("tcp://" + hostname + ":"+ port, userid, password); + + return tibcoAdmin; + } + + private void putServerValue(Map valueMap, String key, long value) { + valueMap.put(key, Long.toString(value)); + } + + private void putQueueValue(Map valueMap, String queueName, String key, long value) { + valueMap.put(queueName + "|" + key, Long.toString(value)); + } + + // collects all monitoring data for this time period from database + private Map putValuesIntoMap() throws Exception { + Map map = new HashMap(); + + TibjmsAdmin conn = null; + boolean debug = logger.isDebugEnabled(); + try { + if (conn == null) + { + if (debug) { + logger.debug("Connecting to " + conn.getInfo()); + } + conn = connect(); + } + + ServerInfo serverInfo = conn.getInfo(); +// serverInfo.getAsyncDBSize(); +// serverInfo.getDetailedStatistics(); + +// serverInfo.getMaxClientMsgSize(); +// serverInfo.getMaxMsgMemory(); +// serverInfo.getMaxStatisticsMemory(); + + putServerValue(map, "DiskReadRate", serverInfo.getDiskReadRate()); + putServerValue(map, "DiskWriteRate", serverInfo.getDiskWriteRate()); + + putServerValue(map, "InboundBytesRate", serverInfo.getInboundBytesRate()); + putServerValue(map, "InboundMessageRate", serverInfo.getInboundMessageRate()); + putServerValue(map, "OutboundBytesRate", serverInfo.getOutboundBytesRate()); + putServerValue(map, "OutboundMessageRate", serverInfo.getOutboundMessageRate()); + + putServerValue(map, "ConnectionCount", serverInfo.getConnectionCount()); + putServerValue(map, "MaxConnections", serverInfo.getMaxConnections()); + + putServerValue(map, "ProducerCount", serverInfo.getProducerCount()); + putServerValue(map, "ConsumerCount", serverInfo.getConsumerCount()); + + putServerValue(map, "PendingMessageCount", serverInfo.getPendingMessageCount()); + putServerValue(map, "PendingMessageSize", serverInfo.getPendingMessageSize()); + putServerValue(map, "InboundMessageCount", serverInfo.getInboundMessageCount()); + putServerValue(map, "OutboundMessageCount", serverInfo.getOutboundMessageCount()); + + + // get most accurate time + currentTime = System.currentTimeMillis(); + logger.debug("Retrieving Queue Information"); + + QueueInfo[] queueInfos = null; + ProducerInfo[] producerInfos = null; + + try { + producerInfos = conn.getProducersStatistics(); + if (debug) { + logger.debug("Retrieving Producer Information"); + if (producerInfos.length > 0) { + logger.debug("Producing Information is Greater than ZERO"); + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + + try { + queueInfos = conn.getQueuesStatistics(); + if (debug) { + logger.debug("Retrieving Queue Information"); + if (queueInfos.length > 0) { + logger.debug("Queue Information is Greater than ZERO"); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + if (queueInfos == null) { + logger.warn("Unable to get queue statistics"); + } else + { + + for (int i = 0; i < queueInfos.length; i++) { + QueueInfo queueInfo = queueInfos[i]; + String queueName = queueInfo.getName(); + + if ( queueName.startsWith("$TMP$.") || queueName.startsWith("$sys.")) + { + logger.info("Skipping system queue " + queueName); + } + else + { + putQueueValue(map, queueName, "ConsumerCount", queueInfo.getConsumerCount()); + putQueueValue(map, queueName, "DeliveredMessageCount", queueInfo.getDeliveredMessageCount()); + putQueueValue(map, queueName, "ConsumerCount", queueInfo.getFlowControlMaxBytes()); + putQueueValue(map, queueName, "PendingMessageCount", queueInfo.getPendingMessageCount()); + putQueueValue(map, queueName, "FlowControlMaxBytes", queueInfo.getFlowControlMaxBytes()); + putQueueValue(map, queueName, "MaxMsgs", queueInfo.getMaxMsgs()); + putQueueValue(map, queueName, "PendingMessageSize", queueInfo.getPendingMessageSize()); + putQueueValue(map, queueName, "ReceiverCount", queueInfo.getReceiverCount()); + putQueueValue(map, queueName, "MaxMsgs", queueInfo.getMaxMsgs()); + putQueueValue(map, queueName, "MaxBytes", queueInfo.getMaxBytes()); + + // Inbound metrics + StatData inboundData = queueInfo.getInboundStatistics(); + putQueueValue(map, queueName, "InboundByteRate", inboundData.getByteRate()); + putQueueValue(map, queueName, "InboundMessageRate", inboundData.getMessageRate()); + putQueueValue(map, queueName, "InboundByteCount", inboundData.getTotalBytes()); + putQueueValue(map, queueName, "InboundMessageCount", inboundData.getTotalMessages()); + + // Outbound metrics + StatData outboundData = queueInfo.getInboundStatistics(); + putQueueValue(map, queueName, "OutboundByteRate", outboundData.getByteRate()); + putQueueValue(map, queueName, "OutboundMessageRate", outboundData.getMessageRate()); + putQueueValue(map, queueName, "OutboundByteCount", outboundData.getTotalBytes()); + putQueueValue(map, queueName, "OutboundMessageCount", outboundData.getTotalMessages()); + + logger.debug(queueName + "|ConsumerCount = " + Integer.toString(queueInfo.getConsumerCount())); + } + + } + } + System.out.println("Closing Connection to Server"); + conn.close(); + } + catch (com.tibco.tibjms.admin.TibjmsAdminException ex) { + logger.error("Error connecting to EMS server" + serverName + " " + + port + " " + this.hostname + " " + this.password, ex); + } + catch (Exception ex) { + logger.error("Error getting performance data from Tibco EMS", ex); + throw ex; + } + finally { + conn.close(); + } + return Collections.synchronizedMap(map); + } + + public TaskOutput execute(Map taskArguments,TaskExecutionContext taskContext) throws TaskExecutionException { + + logger.debug("Starting Execute Thread: " + taskArguments + " : " + taskContext); + + startExecute(taskArguments, taskContext); + try { + Thread.sleep(5000); + } catch (Exception e) { + + } + // just for debug output + logger.debug("Starting METRIC COLLECTION for Tibco EMS Monitor......."); + + Map map; + try { + map = this.putValuesIntoMap(); + Iterator keys = map.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + String value = map.get(key); + printMetric(key, value); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return this.finishExecute(); + } + + private void printMetric(String name, String value) { + if (logger.isDebugEnabled()) { + logger.debug("* * * KEY :" + name + " VALUE : " + value); + } + printMetric(name, value, + MetricWriter.METRIC_AGGREGATION_TYPE_OBSERVATION, + MetricWriter.METRIC_TIME_ROLLUP_TYPE_CURRENT, + MetricWriter.METRIC_CLUSTER_ROLLUP_TYPE_COLLECTIVE); + + } + + protected String getMetricPrefix() { + logger.debug("Tier Name is " + tierName); + if (tierName != null) { + return "Custom Metrics|" + tierName + "|" + serverName +"|"; + } else { + return "Custom Metrics|Tibco EMS Server|"; + } + } + +} diff --git a/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEnterpriseEventMonitor.java b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEnterpriseEventMonitor.java new file mode 100755 index 0000000..d57ff9a --- /dev/null +++ b/src/com/singularity/ee/agent/systemagent/monitors/common/TibcoEnterpriseEventMonitor.java @@ -0,0 +1,256 @@ +package com.singularity.ee.agent.systemagent.monitors.common; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.jms.ExceptionListener; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.TopicConnection; +import javax.jms.TopicConnectionFactory; +import javax.jms.TopicSession; +import javax.jms.TopicSubscriber; + +import com.singularity.ee.agent.systemagent.api.MetricWriter; +import com.singularity.ee.agent.systemagent.api.TaskExecutionContext; +import com.singularity.ee.agent.systemagent.api.TaskOutput; +import com.singularity.ee.agent.systemagent.api.exception.TaskExecutionException; +import com.singularity.ee.util.clock.ClockUtils; +import com.tibco.tibjms.admin.ConnectionInfo; +import com.tibco.tibjms.admin.QueueInfo; +import com.tibco.tibjms.admin.TibjmsAdmin; +import com.tibco.tibjms.admin.TibjmsAdminException; + +public class TibcoEnterpriseEventMonitor extends JavaServersMonitor implements + MessageListener, ExceptionListener { + private volatile String tierName; + private volatile int refreshIntervalInExecutionTicks; + private final Map cachedValueMap; + private volatile int currentNumExecutionTicks = -1; + private volatile List columnNames; + + private volatile String userid; + private volatile String password; + private volatile String hostname; + private volatile String port; + + TopicConnectionFactory factory = null; + TopicConnection connection = null; + TopicSession session = null; + javax.jms.Topic topic = null; + TopicSubscriber subscriber = null; + String durableName = "ad_subscriber"; + + public TibcoEnterpriseEventMonitor() { + oldValueMap = Collections.synchronizedMap(new HashMap()); + cachedValueMap = Collections.synchronizedMap(new HashMap()); + } + + final static String sysTopics[][] = { + + { "$sys.monitor.Q.*.com.appd.*", "Performance of logs" } + + }; + + // { "com.appd.*", "Stats on all com.appd.* queue" }, + + /** + * In addition to the above, one can subscribe to destination specific + * monitor topics: + * + * $sys.monitor.D.E.destination + * + * A message is handled by a destination. The name of this monitor topic + * includes two qualifiers (D and E) and the name of the destination you + * wish to monitor. D signifies the type of destination and whether to + * include the entire message: + * + * - T : topic, include full message (as a byte array) into each event - t : + * topic, do not include full message into each event - Q : queue, include + * full message (as a byte array) into each event - q : queue, do not + * include full message into each event + * + * E signifies the type of event: + * + * - r for receive - s for send - a for acknowledge - p for premature exit + * of message - * for all event types + * + * For example, $sys.monitor.T.r.corp.News is the topic for monitoring any + * received messages to the topic named corp.News. The message body of any + * received messages is included in monitor messages on this topic. The + * topic $sys.monitor.q.*.corp.* monitors all message events (send, receive, + * acknowledge) for all queues matching the name corp.*. The message body is + * not included in this topic's messages. + */ + + protected void parseArgs(Map args) { + super.parseArgs(args); + tierName = getArg(args, "tier", null); // if the tier is not specified + // then create the metrics for + // all tiers + userid = getArg(args, "userid", null); + password = getArg(args, "password", null); + hostname = getArg(args, "hostname", null); + port = getArg(args, "port", "7222"); + + int refreshIntervalSecs = Integer.parseInt(getArg(args, + "refresh-interval", "60")); + + if (refreshIntervalSecs <= 60) { + refreshIntervalInExecutionTicks = 1; + } else { + // Convert refresh interval to milliseconds and round up to the + // nearest minute timeslice. + // From that we can get the number of 60 second ticks before the + // next refresh. + // We do this to prevent time drift issues from preventing this task + // from running. + refreshIntervalInExecutionTicks = (int) (ClockUtils + .roundUpTimestampToNextMinute(refreshIntervalSecs * 1000) / 60000); + } + + if (currentNumExecutionTicks == -1) { + // This is the first time we've parsed the args. Assume we refresh + // the data + // the next time we execute the monitor. + currentNumExecutionTicks = refreshIntervalInExecutionTicks; + } + } + + private TibjmsAdmin connect() throws TibjmsAdminException { + + TibjmsAdmin tibcoAdmin = new TibjmsAdmin("tcp://" + hostname + ":" + + port, userid, password); + + return tibcoAdmin; + } + + // collects all monitoring data for this time period from database + private Map putValuesIntoMap() throws Exception { + Map columnName2Value = new HashMap(); + + TibjmsAdmin conn = null; + boolean debug = logger.isDebugEnabled(); + try { + conn = connect(); + // get most accurate time + currentTime = System.currentTimeMillis(); + columnName2Value.put("Queue_NAME" + "|ConsumerCount".toUpperCase(), "23"); + + + System.out.println("Closing Connection to Server"); + conn.close(); + + } catch (Exception ex) { + logger.error("Error getting performance data from Tibco EMS.", ex); + throw ex; + } finally { + + } + return Collections.synchronizedMap(columnName2Value); + } + + public TaskOutput execute(Map taskArguments, TaskExecutionContext taskContext) throws TaskExecutionException { + startExecute(taskArguments, taskContext); + + // just for debug output + logger.debug("Starting Listener......."); + + Map map; + try { + map = this.putValuesIntoMap(); + Iterator keys = map.keySet().iterator(); + while (keys.hasNext()) { + String key = (String) keys.next(); + String value = map.get(key); + printMetric(key, value); + if (logger.isDebugEnabled()) { + logger.debug("Key :" + key + " : " + value); + } + + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return this.finishExecute(); + } + + public void startSubscriber() { + try + + { + factory = new com.tibco.tibjms.TibjmsTopicConnectionFactory( + "tcp://" + hostname + ":" + port); + connection = factory.createTopicConnection(userName, password); + session = connection.createTopicSession(false, + javax.jms.Session.AUTO_ACKNOWLEDGE); + for (int i = 0; i < sysTopics.length; i++) { + /* + * Lookup the topic and subscribe to it. + */ + try { + topic = session.createTopic(sysTopics[i][0]); + + } catch (Exception e) { + System.out.println("Unable to create topic:" + sysTopics[i][0]); + continue; + } + System.out.println("Creating a durable subscriber to topic: " + + sysTopics[i][0]); + subscriber = session.createDurableSubscriber(topic, durableName + + sysTopics[i][0]); + subscriber.setMessageListener(this); + } + connection.setExceptionListener(this); + connection.start(); + + /* read topic messages */ + System.out.print("Waiting for messages"); + + while (true) { + Thread.sleep(1000); + System.out.print("."); + } + + // connection.close(); + } catch (Throwable e) { + e.printStackTrace(); + System.exit(0); + } + } + + private void printMetric(String name, String value) { + printMetric(name, value, + MetricWriter.METRIC_AGGREGATION_TYPE_OBSERVATION, + MetricWriter.METRIC_TIME_ROLLUP_TYPE_CURRENT, + MetricWriter.METRIC_CLUSTER_ROLLUP_TYPE_COLLECTIVE); + + } + + protected String getMetricPrefix() { + if (tierName != null) { + return "Server|Component:" + tierName + "|Tibco EMS Server|"; + } else { + return "Custom Metrics|Tibco EMS Server|"; + } + } + + @Override + public void onException(JMSException arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void onMessage(Message arg0) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/com/singularity/jms/tibjmsAsyncMsgConsumer.java b/src/com/singularity/jms/tibjmsAsyncMsgConsumer.java new file mode 100755 index 0000000..a64aa2c --- /dev/null +++ b/src/com/singularity/jms/tibjmsAsyncMsgConsumer.java @@ -0,0 +1,221 @@ + + + +package com.singularity.jms; + +import java.io.IOException; +import javax.jms.*; + +public class tibjmsAsyncMsgConsumer + implements ExceptionListener, MessageListener +{ + /*----------------------------------------------------------------------- + * Parameters + *----------------------------------------------------------------------*/ + + String serverUrl = null; + String userName = null; + String password = null; + String name = "topic.sample"; + boolean useTopic = true; + + /*----------------------------------------------------------------------- + * Variables + *----------------------------------------------------------------------*/ + Connection connection = null; + Session session = null; + MessageConsumer msgConsumer = null; + Destination destination = null; + + + public tibjmsAsyncMsgConsumer(String[] args) + { + parseArgs(args); + + try + { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch(JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + /* print parameters */ + System.err.println("------------------------------------------------------------------------"); + System.err.println("tibjmsAsyncMsgConsumer Sample"); + System.err.println("------------------------------------------------------------------------"); + System.err.println("Server....................... "+serverUrl != null?serverUrl:"localhost"); + System.err.println("User......................... "+userName != null?userName:"(null)"); + System.err.println("Destination.................. "+name); + System.err.println("------------------------------------------------------------------------"); + + try + { + int c; + + ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl); + + /* create the connection */ + connection = factory.createConnection(userName,password); + + /* create the session */ + session = connection.createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + /* set the exception listener */ + connection.setExceptionListener(this); + + /* create the destination */ + if(useTopic) + destination = session.createTopic(name); + else + destination = session.createQueue(name); + + System.err.println("Subscribing to destination: "+name); + + /* create the consumer */ + msgConsumer = session.createConsumer(destination); + + /* set the message listener */ + msgConsumer.setMessageListener(this); + + /* start the connection */ + connection.start(); + + // Note: when message callback is used, the session + // creates the dispatcher thread which is not a daemon + // thread by default. Thus we can quit this method however + // the application will keep running. It is possible to + // specify that all session dispatchers are daemon threads. + } + catch(Exception e) + { + e.printStackTrace(); + } + } + + /*----------------------------------------------------------------------- + * usage + *----------------------------------------------------------------------*/ + void usage() + { + System.err.println("\nUsage: java tibjmsAsyncMsgConsumer [options] [ssl options]"); + System.err.println("\n"); + System.err.println(" where options are:\n"); + System.err.println("\n"); + System.err.println(" -server - EMS server URL, default is local server\n"); + System.err.println(" -user - user name, default is null\n"); + System.err.println(" -password - password, default is null\n"); + System.err.println(" -topic - topic name, default is \"topic.sample\"\n"); + System.err.println(" -queue - queue name, no default\n"); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + /*----------------------------------------------------------------------- + * parseArgs + *----------------------------------------------------------------------*/ + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + name = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-queue")==0) + { + if ((i+1) >= args.length) usage(); + name = args[i+1]; + i += 2; + useTopic = false; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } + + + /*--------------------------------------------------------------------- + * onException + *---------------------------------------------------------------------*/ + public void onException(JMSException e) + { + /* print the connection exception status */ + System.err.println("CONNECTION EXCEPTION: "+ e.getMessage()); + } + + /*--------------------------------------------------------------------- + * onMessage + *---------------------------------------------------------------------*/ + public void onMessage(Message msg) + { + try + { + System.err.println("Received message: " + msg); + } + catch(Exception e) + { + System.err.println("Unexpected exception in the message callback!"); + e.printStackTrace(); + System.exit(-1); + } + } + + /*----------------------------------------------------------------------- + * main + *----------------------------------------------------------------------*/ + public static void main(String[] args) + { + new tibjmsAsyncMsgConsumer(args); + } + +} + + diff --git a/src/com/singularity/jms/tibjmsBrowser.java b/src/com/singularity/jms/tibjmsBrowser.java new file mode 100755 index 0000000..3db9d5a --- /dev/null +++ b/src/com/singularity/jms/tibjmsBrowser.java @@ -0,0 +1,292 @@ +package com.singularity.jms; + + + +/* + * This sample demonstrates the use of QueueBrowser with + * TIBCO Enterprise Message Service using the JMS 1.1 API. + * + * Notice that TIBCO Enterprise Message Service implements dynamic + * queue browsers. This means that the QueueBrowser can + * dynamically receive new messages added to the queue. + * If hasMoreElements() method of the Enumeration returned by + * the QueueBrowser class returns false, the JMS application + * can wait and try to call it later. If the queue being browsed + * has received new messages, the hasMoreElements() method will + * return true and the application can browse new messages. + * If hasMoreElements() returns false, the application can choose + * to quit browsing or can wait for more messages to be delivered + * into the queue. + * + * After all queue messages have been delivered to the queue + * browser, TIBCO Enterprise Message Service waits for some time and then + * tries to query if any new messages. This happens behind the scene, + * user application can try to call hasMoreElements() at any time, + * the internal engine will only actually query the queue every fixed + * interval. TIBCO Enterprise Message Service release 1.0 queries the queue + * not more often than every 5 seconds but the length of that + * interval is a subject to change without notice. + * + * Usage: java tibjmsBrowser [options] + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -queue Queue name. Default is "queue.sample.browser" + * -user User name. Default is null. + * -password User password. Default is null. + * + * + */ + +import javax.jms.*; +import javax.naming.*; +import java.util.Enumeration; + +public class tibjmsBrowser +{ + String serverUrl = null; + String userName = null; + String password = null; + String queueName = "queue.sample.browser"; + + public tibjmsBrowser(String[] args) { + + parseArgs(args); + + try { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + System.err.println("Browser sample."); + System.err.println("Using server: "+serverUrl); + System.err.println("Browsing queue: "+queueName); + + try + { + ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl); + + Connection connection = factory.createConnection(userName,password); + + Session session = connection.createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + javax.jms.Queue queue = session.createQueue(queueName); + + MessageProducer producer = session.createProducer(queue); + + javax.jms.Message message = null; + + connection.start(); + + /* + * drain the queue + */ + MessageConsumer consumer = session.createConsumer(queue); + + int drain_count = 0; + + System.err.println("Draining the queue "+queueName); + + /* read queue until empty */ + while (consumer.receive(1000) != null) + { + drain_count++; + } + System.err.println("Drained "+drain_count+" messages from the queue"); + + /* + * close consumer to prevent any + * queue messages to be delivered + */ + consumer.close(); + + int message_number = 0; + + /* + * send 5 messages into queue + */ + System.err.println("Sending 5 messages into queue."); + for (int i=0; i<5; i++) + { + message_number++; + message = session.createMessage(); + message.setIntProperty("msg_num",message_number); + producer.send(message); + } + + /* + * create browser and browse what is there in the queue + */ + System.err.println("--- Browsing the queue."); + + javax.jms.QueueBrowser browser = session.createBrowser(queue); + + Enumeration msgs = browser.getEnumeration(); + + int browseCount=0; + + while(msgs.hasMoreElements()) + { + message = (javax.jms.Message)msgs.nextElement(); + System.err.println("Browsed message: number="+message.getIntProperty("msg_num")); + browseCount++; + } + + System.err.println("--- No more messages in the queue."); + + /* + * send 5 more messages into queue + */ + System.err.println("Sending 5 more messages into queue."); + for (int i=0; i<5; i++) + { + message_number++; + message = session.createMessage(); + message.setIntProperty("msg_num",message_number); + producer.send(message); + } + + /* + * try to browse again, if no success for some time + * then quit + */ + + /* notice that we will *not* receive new messages + * instantly. It happens because QueueBrowser limits + * the frequency of query requests sent into the queue + * after the queue was empty. Internal engine only queries + * the queue every so many seconds, so we'll likely have + * to wait here for some time. + */ + + int attemptCount = 0; + + while(!msgs.hasMoreElements()) + { + attemptCount++; + System.err.println("Waiting for messages to arrive, count="+attemptCount); + Thread.sleep(1000); + if (attemptCount > 30) + { + System.err.println("Still no messages in the queue after "+attemptCount+" seconds"); + System.exit(0); + } + } + + /* + * got more messages, continue browsing + */ + System.err.println("Found more messages. Continue browsing."); + while(msgs.hasMoreElements()) + { + message = (javax.jms.Message)msgs.nextElement(); + System.err.println("Browsed message: number="+message.getIntProperty("msg_num")); + } + + /* + * close all and quit + */ + browser.close(); + + connection.close(); + } + catch(JMSException e) + { + e.printStackTrace(); + System.exit(0); + } + catch(InterruptedException e) + { + e.printStackTrace(); + System.exit(0); + } + + } + + public static void main(String args[]) + { + tibjmsBrowser t = new tibjmsBrowser(args); + } + + void usage() + { + System.err.println("\nUsage: java tibjmsBrowser [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -queue - queue name, default is \"queue.sample.browser\""); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-queue")==0) + { + if ((i+1) >= args.length) usage(); + queueName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } + +} + + diff --git a/src/com/singularity/jms/tibjmsDurable.java b/src/com/singularity/jms/tibjmsDurable.java new file mode 100755 index 0000000..faea7f4 --- /dev/null +++ b/src/com/singularity/jms/tibjmsDurable.java @@ -0,0 +1,247 @@ +package com.singularity.jms; + + +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsDurable.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a simple sample of a topic durable subscriber using the JMS 1.1 API. + * + * This sampe creates durable subscriber on the specified topic and + * receives and prints all received messages. + * + * When this sample started with -unsubscribe parameter, + * it unsubsribes from specified topic and quits. + * If -unsubscribe is not specified this sample creates a durable + * subscriber on the specified topic and receives and prints + * all received messages. Note that you must provide correct clientID + * and durable name for this sample to work correctly. + * + * Notice that the specified topic should exist in your configuration + * or your topics configuration file should allow + * creation of the specified topic. + * + * This sample can subscribe to dynamic topics thus it is + * using Session.createTopic() method in order to obtain + * the Topic object. + * + * Usage: java tibjmsDurable [options] + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -user User name. Default is null. + * -password User password. Default is null. + * -topic Topic name. Default is "topic.sample" + * -clientID Connection Client ID. Default is null. + * -durable Durable name. Default is "subscriber". + * -unsubscribe Unsubscribe and quit. + * + * + */ + +import javax.jms.*; +import javax.naming.*; + +public class tibjmsDurable +{ + String serverUrl = null; + String userName = null; + String password = null; + + String topicName = "topic.sample"; + String clientID = null; + String durableName = "subscriber"; + + boolean unsubscribe = false; + + public tibjmsDurable(String[] args) { + + parseArgs(args); + + try { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + if (!unsubscribe && (topicName == null)) { + System.err.println("Error: must specify topic name"); + usage(); + } + + if (durableName == null) { + System.err.println("Error: must specify durable subscriber name"); + usage(); + } + + System.err.println("Durable sample."); + System.err.println("Using clientID: "+clientID); + System.err.println("Using Durable Name: "+durableName); + + try + { + ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl); + + Connection connection = factory.createConnection(userName,password); + + /* if clientID is specified we must set it right here */ + if (clientID != null) + connection.setClientID(clientID); + + Session session = connection.createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + if (unsubscribe) { + System.err.println("Unsubscribing durable subscriber "+durableName); + session.unsubscribe(durableName); + System.err.println("Successfully unsubscribed "+durableName); + connection.close(); + return; + } + + System.err.println("Subscribing to topic: "+topicName); + + /* + * Use createTopic() to enable subscriptions to dynamic topics. + */ + javax.jms.Topic topic = session.createTopic(topicName); + + TopicSubscriber subscriber = session.createDurableSubscriber(topic,durableName); + + connection.start(); + + /* read topic messages */ + while(true) + { + javax.jms.Message message = subscriber.receive(); + if (message == null) + break; + + System.err.println("\nReceived message: "+message); + } + + connection.close(); + } + catch(JMSException e) + { + e.printStackTrace(); + System.exit(0); + } + } + + public static void main(String args[]) + { + tibjmsDurable t = new tibjmsDurable(args); + } + + void usage() + { + System.err.println("\nUsage: java tibjmsDurable [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -topic - topic name, default is \"topic.sample\""); + System.err.println(" -clientID - clientID, default is null"); + System.err.println(" -durable - durable subscriber name,"); + System.err.println(" default is \"subscriber\""); + System.err.println(" -unsubscribe - unsubscribe and quit"); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + topicName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-durable")==0) + { + if ((i+1) >= args.length) usage(); + durableName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-clientID")==0) + { + if ((i+1) >= args.length) usage(); + clientID = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-unsubscribe")==0) + { + unsubscribe = true; + i += 1; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } + +} + + diff --git a/src/com/singularity/jms/tibjmsDurableSubscriber.java b/src/com/singularity/jms/tibjmsDurableSubscriber.java new file mode 100755 index 0000000..c50b889 --- /dev/null +++ b/src/com/singularity/jms/tibjmsDurableSubscriber.java @@ -0,0 +1,246 @@ +package com.singularity.jms; + +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsDurableSubscriber.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a simple sample of a topic durable subscriber. + * + * This sampe creates durable subscriber on the specified topic and + * receives and prints all received messages. + * + * When this sample started with -unsubscribe parameter, + * it unsubsribes from specified topic and quits. + * If -unsubscribe is not specified this sample creates a durable + * subscriber on the specified topic and receives and prints + * all received messages. Note that you must provide correct clientID + * and durable name for this sample to work correctly. + * + * Notice that the specified topic should exist in your configuration + * or your topics configuration file should allow + * creation of the specified topic. + * + * This sample can subscribe to dynamic topics thus it is + * using TopicSession.createTopic() method in order to obtain + * the Topic object. + * + * Usage: java tibjmsDurableSubscriber [options] + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -user User name. Default is null. + * -password User password. Default is null. + * -topic Topic name. Default is "topic.sample" + * -clientID Connection Client ID. Default is null. + * -durable Durable name. Default is "subscriber". + * -unsubscribe Unsubscribe and quit. + * + * + */ + +import javax.jms.*; +import javax.naming.*; + +public class tibjmsDurableSubscriber +{ + String serverUrl = null; + String userName = null; + String password = null; + + String topicName = "topic.sample"; + String clientID = null; + String durableName = "subscriber"; + + boolean unsubscribe = false; + + public tibjmsDurableSubscriber(String[] args) { + + parseArgs(args); + + try { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + if (!unsubscribe && (topicName == null)) { + System.err.println("Error: must specify topic name"); + usage(); + } + + if (durableName == null) { + System.err.println("Error: must specify durable subscriber name"); + usage(); + } + + System.err.println("DurableSubscriber sample."); + System.err.println("Using clientID: "+clientID); + System.err.println("Using Durable Name: "+durableName); + + try + { + TopicConnectionFactory factory = new com.tibco.tibjms.TibjmsTopicConnectionFactory(serverUrl); + + TopicConnection connection = factory.createTopicConnection(userName,password); + + /* if clientID is specified we must set it right here */ + if (clientID != null) + connection.setClientID(clientID); + + TopicSession session = connection.createTopicSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + if (unsubscribe) { + System.err.println("Unsubscribing durable subscriber "+durableName); + session.unsubscribe(durableName); + System.err.println("Successfully unsubscribed "+durableName); + connection.close(); + return; + } + + System.err.println("Subscribing to topic: "+topicName); + + /* + * Use createTopic() to enable subscriptions to dynamic topics. + */ + javax.jms.Topic topic = session.createTopic(topicName); + + TopicSubscriber subscriber = session.createDurableSubscriber(topic,durableName); + + connection.start(); + + /* read topic messages */ + while(true) + { + javax.jms.Message message = subscriber.receive(); + if (message == null) + break; + + System.err.println("\nReceived message: "+message); + } + + connection.close(); + } + catch(JMSException e) + { + e.printStackTrace(); + System.exit(0); + } + } + + public static void main(String args[]) + { + tibjmsDurableSubscriber t = new tibjmsDurableSubscriber(args); + } + + void usage() + { + System.err.println("\nUsage: java tibjmsDurableSubscriber [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -topic - topic name, default is \"topic.sample\""); + System.err.println(" -clientID - clientID, default is null"); + System.err.println(" -durable - durable subscriber name,"); + System.err.println(" default is \"subscriber\""); + System.err.println(" -unsubscribe - unsubscribe and quit"); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + topicName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-durable")==0) + { + if ((i+1) >= args.length) usage(); + durableName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-clientID")==0) + { + if ((i+1) >= args.length) usage(); + clientID = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-unsubscribe")==0) + { + unsubscribe = true; + i += 1; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } + +} + + diff --git a/src/com/singularity/jms/tibjmsLoadBalancedTopicPublisher.java b/src/com/singularity/jms/tibjmsLoadBalancedTopicPublisher.java new file mode 100755 index 0000000..2080bfa --- /dev/null +++ b/src/com/singularity/jms/tibjmsLoadBalancedTopicPublisher.java @@ -0,0 +1,260 @@ +package com.singularity.jms; + + +/* + + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsLoadBalancedTopicPublisher.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a sample illustrating the use of a load balancing connection + * factory. + * + * This sample creates a load balancing connection factory locally (as + * opposed to looking one up via JNDI) which create connections to the least + * busy server. To best illustrate the load balancing, several instances of + * this client should be run simultaneously. + * + * The default behavior is for the client to create a connection factory + * that supplies a connection to the EMS Server with the lowest number of + * connections. To illustrate an alternative way to load balance, the + * -balanceByRate option can be used which will create a connection + * factory which balances across servers by returning a connection to the + * server with the lowest total inbound and outbound rate (in bytes). + * + * Notice that the specified topic should exist in your configuration + * or your topics configuration file should allow + * creation of the specified topic. Sample configuration supplied with + * the TIBCO Enterprise Message Service distribution allows creation of any + * topics. + * + * This sample can publish into dynamic topics thus it is + * using TopicSession.createTopic() method to obtain the Topic object. + * + * If this sample is used to publish messages into + * tibjmsTopicSubscriber sample, the tibjmsTopicSubscriber + * sample must be started first. + * + * If -topic is not specified this sample will use topic named + * "topic.sample". + * + * Usage: java tibjmsLoadBalancedTopicPublisher [options] + * -servers url1 url2 .... + * + * where options are: + * + * -user User name for publishing. Default is + * null. + * -password User password for publishing. Default is + * null. + * -topic Topic name. Default value is + * "topic.sample". + * -messages Number of messages to publish. Default is + * 100. + * -delay Number of seconds delay between + * publishes. Default is 1 sec. + * -balanceByRate Choose the EMS Server with lowest + * byte rate (inbound + outbound). + */ + +import javax.jms.*; +import java.util.HashMap; + +import com.tibco.tibjms.Tibjms; +import com.tibco.tibjms.TibjmsConnection; + +public class tibjmsLoadBalancedTopicPublisher +{ + String serverList = ""; + String userName = null; + String password = null; + + String topicName = "topic.sample"; + + int messages = 100; + int delay = 1; + + boolean balanceByConnections = true; + + public tibjmsLoadBalancedTopicPublisher(String[] args) { + + parseArgs(args); + + /* print parameters */ + System.out.println("\n------------------------------------------------------------------------"); + System.out.println("tibjmsLoadBalancedTopicPublisher SAMPLE"); + System.out.println("------------------------------------------------------------------------"); + System.out.println("Servers...................... "+serverList); + System.out.println("User......................... "+(userName!=null?userName:"(null)")); + System.out.println("Topic........................ "+topicName); + System.out.println("Messages..................... "+messages); + System.out.println("Delay........................ "+delay); + System.out.println("------------------------------------------------------------------------\n"); + + System.err.println("Publishing on topic '"+topicName+"'\n"); + + try + { + HashMap properties = new HashMap(); + Integer metric; + if (balanceByConnections) + metric = new Integer(Tibjms.FACTORY_LOAD_BALANCE_METRIC_CONNECTIONS); + else + metric = new Integer(Tibjms.FACTORY_LOAD_BALANCE_METRIC_BYTE_RATE); + + properties.put(Tibjms.FACTORY_LOAD_BALANCE_METRIC, metric); + + TopicConnectionFactory factory = new com.tibco.tibjms.TibjmsTopicConnectionFactory(serverList, + null,properties); + + TopicConnection connection = factory.createTopicConnection(userName,password); + + TopicSession session = connection.createTopicSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + /* + * Use createTopic() to enable publishing into dynamic topics. + */ + javax.jms.Topic topic = session.createTopic(topicName); + + TopicPublisher publisher = session.createPublisher(topic); + + /* publish messages */ + for (int i=0; i User name for publishing. Default is"); + System.err.println(" null. "); + System.err.println(" -password User password for publishing. Default is"); + System.err.println(" null."); + System.err.println(" -topic Topic name. Default value is"); + System.err.println(" \"topic.sample\"."); + System.err.println(" -messages Number of messages to publish. Default is"); + System.err.println(" 100."); + System.err.println(" -delay Number of seconds delay between"); + System.err.println(" publishes. Default is 1 sec."); + System.err.println(" -balanceByRate Choose the EMS Server with lowest"); + System.err.println(" byte rate (inbound + outbound)."); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + boolean first = true; + + while(i < args.length) + { + if (args[i].compareTo("-servers")==0) + { + if ((i+1) >= args.length) usage(); + i++; + while (i < args.length && !(args[i].startsWith("-"))) + { + if (!first) + serverList += "|"; + else + first = false; + serverList += args[i]; + i++; + } + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + topicName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-messages")==0) + { + if ((i+1) >= args.length) usage(); + messages = Integer.parseInt(args[i+1]); + i += 2; + } + else + if (args[i].compareTo("-delay")==0) + { + if ((i+1) >= args.length) usage(); + delay = Integer.parseInt(args[i+1]); + i += 2; + } + else + if (args[i].compareTo("-balanceByRate")==0) + { + balanceByConnections = false; + i += 1; + } + else + { + usage(); + } + } + + if (first) + { + System.err.println("\nNo server urls specified.\n"); + usage(); + } + } +} + + diff --git a/src/com/singularity/jms/tibjmsMsgConsumer.java b/src/com/singularity/jms/tibjmsMsgConsumer.java new file mode 100755 index 0000000..e15a0cf --- /dev/null +++ b/src/com/singularity/jms/tibjmsMsgConsumer.java @@ -0,0 +1,288 @@ +package com.singularity.jms; + + +/* + * + * Copyright (c) 2001-2007 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsMsgConsumer.java 33694 2007-09-17 16:34:18Z $ + * + */ + +/* + * This is a simple sample of a basic tibjmsMsgConsumer. + * + * This sampe subscribes to specified destination and + * receives and prints all received messages. + * + * Notice that the specified destination should exist in your configuration + * or your topics/queues configuration file should allow + * creation of the specified destination. + * + * If this sample is used to receive messages published by + * tibjmsMsgProducer sample, it must be started prior + * to running the tibjmsMsgProducer sample. + * + * Usage: java tibjmsMsgConsumer [options] + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -user User name. Default is null. + * -password User password. Default is null. + * -topic Topic name. Default is "topic.sample" + * -queue Queue name. No default + * -ackmode Message acknowledge mode. Default is AUTO. + * Other values: DUPS_OK, CLIENT, EXPLICIT_CLIENT, + * EXPLICIT_CLIENT_DUPS_OK and NO. + * + * + */ + +import javax.jms.*; + +import com.tibco.tibjms.Tibjms; + +public class tibjmsMsgConsumer + implements ExceptionListener +{ + /*----------------------------------------------------------------------- + * Parameters + *----------------------------------------------------------------------*/ + + String serverUrl = null; + String userName = null; + String password = null; + String name = "topic.sample"; + boolean useTopic = true; + int ackMode = Session.AUTO_ACKNOWLEDGE; + + /*----------------------------------------------------------------------- + * Variables + *----------------------------------------------------------------------*/ + Connection connection = null; + Session session = null; + MessageConsumer msgConsumer = null; + Destination destination = null; + + public tibjmsMsgConsumer(String[] args) + { + parseArgs(args); + + try { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + /* print parameters */ + System.err.println("\n------------------------------------------------------------------------"); + System.err.println("tibjmsMsgConsumer SAMPLE"); + System.err.println("------------------------------------------------------------------------"); + System.err.println("Server....................... "+((serverUrl != null)?serverUrl:"localhost")); + System.err.println("User......................... "+((userName != null)?userName:"(null)")); + System.err.println("Destination.................. "+name); + System.err.println("------------------------------------------------------------------------\n"); + + try { + run(); + } catch (JMSException e) { + e.printStackTrace(); + } + } + + + /*----------------------------------------------------------------------- + * usage + *----------------------------------------------------------------------*/ + void usage() + { + System.err.println("\nUsage: tibjmsMsgConsumer [options] [ssl options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -topic - topic name, default is \"topic.sample\""); + System.err.println(" -queue - queue name, no default"); + System.err.println(" -ackmode - acknowledge mode, default is AUTO"); + System.err.println(" other modes: CLIENT, DUPS_OK, NO,"); + System.err.println(" EXPLICIT_CLIENT and EXPLICIT_CLIENT_DUPS_OK"); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + /*----------------------------------------------------------------------- + * parseArgs + *----------------------------------------------------------------------*/ + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + name = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-queue")==0) + { + if ((i+1) >= args.length) usage(); + name = args[i+1]; + i += 2; + useTopic = false; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-ackmode")==0) + { + if ((i+1) >= args.length) usage(); + if (args[i+1].compareTo("AUTO")==0) + ackMode = Session.AUTO_ACKNOWLEDGE; + else if (args[i+1].compareTo("CLIENT")==0) + ackMode = Session.CLIENT_ACKNOWLEDGE; + else if (args[i+1].compareTo("DUPS_OK")==0) + ackMode = Session.DUPS_OK_ACKNOWLEDGE; + else if (args[i+1].compareTo("EXPLICIT_CLIENT")==0) + ackMode = Tibjms.EXPLICIT_CLIENT_ACKNOWLEDGE; + else if (args[i+1].compareTo("EXPLICIT_CLIENT_DUPS_OK")==0) + ackMode = Tibjms.EXPLICIT_CLIENT_DUPS_OK_ACKNOWLEDGE; + else if (args[i+1].compareTo("NO")==0) + ackMode = Tibjms.NO_ACKNOWLEDGE; + else + { + System.err.println("Unrecognized -ackmode: "+args[i+1]); + usage(); + } + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } + + + /*--------------------------------------------------------------------- + * onException + *---------------------------------------------------------------------*/ + public void onException( + JMSException e) + { + /* print the connection exception status */ + System.err.println("CONNECTION EXCEPTION: " + e.getMessage()); + } + + /*----------------------------------------------------------------------- + * run + *----------------------------------------------------------------------*/ + void run() + throws JMSException + { + Message msg = null; + String msgType = "UNKNOWN"; + + System.err.println("Subscribing to destination: "+name+"\n"); + + ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl); + + /* create the connection */ + connection = factory.createConnection(userName,password); + + /* create the session */ + session = connection.createSession(false,ackMode); + + /* set the exception listener */ + connection.setExceptionListener(this); + + /* create the destination */ + if(useTopic) + destination = session.createTopic(name); + else + destination = session.createQueue(name); + + /* create the consumer */ + msgConsumer = session.createConsumer(destination); + + /* start the connection */ + connection.start(); + + /* read messages */ + while(true) + { + /* receive the message */ + msg = msgConsumer.receive(); + if (msg == null) + break; + + if (ackMode == Session.CLIENT_ACKNOWLEDGE || + ackMode == Tibjms.EXPLICIT_CLIENT_ACKNOWLEDGE || + ackMode == Tibjms.EXPLICIT_CLIENT_DUPS_OK_ACKNOWLEDGE) + msg.acknowledge(); + + System.err.println("Received message: "+ msg); + } + + /* close the connection */ + connection.close(); + } + + /*----------------------------------------------------------------------- + * main + *----------------------------------------------------------------------*/ + public static void main(String[] args) + { + new tibjmsMsgConsumer(args); + } +} diff --git a/src/com/singularity/jms/tibjmsMsgProducer.java b/src/com/singularity/jms/tibjmsMsgProducer.java new file mode 100755 index 0000000..9ca4502 --- /dev/null +++ b/src/com/singularity/jms/tibjmsMsgProducer.java @@ -0,0 +1,250 @@ +package com.singularity.jms; + +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsMsgProducer.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a simple sample of a basic tibjmsMsgProducer. + * + * This sample publishes specified message(s) on a specified + * destination and quits. + * + * Notice that the specified destination should exist in your configuration + * or your topics/queues configuration file should allow + * creation of the specified topic or queue. Sample configuration supplied with + * the TIBCO Enterprise Message Service distribution allows creation of any + * destination. + * + * If this sample is used to publish messages into + * tibjmsMsgConsumer sample, the tibjmsMsgConsumer + * sample must be started first. + * + * If -topic is not specified this sample will use a topic named + * "topic.sample". + * + * Usage: java tibjmsMsgProducer [options] + * + * ... + * + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * -user User name. Default is null. + * -password User password. Default is null. + * -topic Topic name. Default value is "topic.sample" + * -queue Queue name. No default + * + */ + +import java.util.*; +import javax.jms.*; + +public class tibjmsMsgProducer +{ + /*----------------------------------------------------------------------- + * Parameters + *----------------------------------------------------------------------*/ + + String serverUrl = null; + String userName = null; + String password = null; + String name = "topic.appdynamics.ems.perf"; + Vector data = new Vector(); + boolean useTopic = true; + + /*----------------------------------------------------------------------- + * Variables + *----------------------------------------------------------------------*/ + Connection connection = null; + Session session = null; + MessageProducer msgProducer = null; + Destination destination = null; + + public tibjmsMsgProducer(String[] args) + { + parseArgs(args); + + try { + tibjmsUtilities.initSSLParams(serverUrl, args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + /* print parameters */ + System.err.println("\n------------------------------------------------------------------------"); + System.err.println("tibjmsMsgProducer SAMPLE"); + System.err.println("------------------------------------------------------------------------"); + System.err.println("Server....................... "+((serverUrl != null)?serverUrl:"localhost")); + System.err.println("User......................... "+((userName != null)?userName:"(null)")); + System.err.println("Destination.................. "+name); + System.err.println("Message Text................. "); + for(int i=0;i"); + System.err.println(" [] ..."); + System.err.println("\n"); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -topic - topic name, default is \"topic.sample\""); + System.err.println(" -queue - queue name, no default"); + System.err.println(" -help-ssl - help on ssl parameters"); + System.exit(0); + } + + /*----------------------------------------------------------------------- + * parseArgs + *----------------------------------------------------------------------*/ + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + name = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-queue")==0) + { + if ((i+1) >= args.length) usage(); + name = args[i+1]; + i += 2; + useTopic = false; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + data.addElement(args[i]); + i++; + } + } + } + + /*----------------------------------------------------------------------- + * main + *----------------------------------------------------------------------*/ + public static void main(String[] args) + { + tibjmsMsgProducer t = new tibjmsMsgProducer(args); + } +} + diff --git a/src/com/singularity/jms/tibjmsQueueBrowser.java b/src/com/singularity/jms/tibjmsQueueBrowser.java new file mode 100755 index 0000000..9160108 --- /dev/null +++ b/src/com/singularity/jms/tibjmsQueueBrowser.java @@ -0,0 +1,300 @@ +package com.singularity.jms; + +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsQueueBrowser.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This sample demonstrates the use of QueueBrowser with + * TIBCO Enterprise Message Service. + * + * Notice that TIBCO Enterprise Message Service implements dynamic + * queue browsers. This means that the QueueBrowser can + * dynamically receive new messages added to the queue. + * If hasMoreElements() method of the Enumeration returned by + * the QueueBrowser class returns false, the JMS application + * can wait and try to call it later. If the queue being browsed + * has received new messages, the hasMoreElements() method will + * return true and the application can browse new messages. + * If hasMoreElements() returns false, the application can choose + * to quit browsing or can wait for more messages to be delivered + * into the queue. + * + * After all queue messages have been delivered to the queue + * browser, TIBCO Enterprise Message Service waits for some time and then + * tries to query if any new messages. This happens behind the scene, + * user application can try to call hasMoreElements() at any time, + * the internal engine will only actually query the queue every fixed + * interval. TIBCO Enterprise Message Service currently queries the queue + * not more often than every 5 seconds but the length of that + * interval is a subject to change without notice. + * + * Usage: java tibjmsQueueBrowser [options] + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -queue Queue name. Default is "queue.sample.browser" + * -user User name. Default is null. + * -password User password. Default is null. + * + * + */ + +import javax.jms.*; +import javax.naming.*; +import java.util.Enumeration; + +public class tibjmsQueueBrowser +{ + String serverUrl = null; + String userName = null; + String password = null; + String queueName = "queue.sample.browser"; + + public tibjmsQueueBrowser(String[] args) { + + parseArgs(args); + + try { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + System.err.println("QueueBrowser sample."); + System.err.println("Using server: "+serverUrl); + System.err.println("Browsing queue: "+queueName); + + try + { + QueueConnectionFactory factory = new com.tibco.tibjms.TibjmsQueueConnectionFactory(serverUrl); + + QueueConnection connection = factory.createQueueConnection(userName,password); + + QueueSession session = connection.createQueueSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + javax.jms.Queue queue = session.createQueue(queueName); + + QueueSender sender = session.createSender(queue); + + javax.jms.Message message = null; + + connection.start(); + + /* + * drain the queue + */ + QueueReceiver receiver = session.createReceiver(queue); + + int drain_count = 0; + + System.err.println("Draining the queue "+queueName); + + /* read queue until empty */ + while (receiver.receive(1000) != null) + { + drain_count++; + } + System.err.println("Drained "+drain_count+" messages from the queue"); + + /* + * close receiver to prevent any + * queue messages to be delivered + */ + receiver.close(); + + int message_number = 0; + + /* + * send 5 messages into queue + */ + System.err.println("Sending 5 messages into queue."); + for (int i=0; i<5; i++) + { + message_number++; + message = session.createMessage(); + message.setIntProperty("msg_num",message_number); + sender.send(message); + } + + /* + * create browser and browse what is there in the queue + */ + System.err.println("--- Browsing the queue."); + + javax.jms.QueueBrowser browser = session.createBrowser(queue); + + Enumeration msgs = browser.getEnumeration(); + + int browseCount=0; + + while(msgs.hasMoreElements()) + { + message = (javax.jms.Message)msgs.nextElement(); + System.err.println("Browsed message: number="+message.getIntProperty("msg_num")); + browseCount++; + } + + System.err.println("--- No more messages in the queue."); + + /* + * send 5 more messages into queue + */ + System.err.println("Sending 5 more messages into queue."); + for (int i=0; i<5; i++) + { + message_number++; + message = session.createMessage(); + message.setIntProperty("msg_num",message_number); + sender.send(message); + } + + /* + * try to browse again, if no success for some time + * then quit + */ + + /* notice that we will *not* receive new messages + * instantly. It happens because QueueBrowser limits + * the frequency of query requests sent into the queue + * after the queue was empty. Internal engine only queries + * the queue every so many seconds, so we'll likely have + * to wait here for some time. + */ + + int attemptCount = 0; + + while(!msgs.hasMoreElements()) + { + attemptCount++; + System.err.println("Waiting for messages to arrive, count="+attemptCount); + Thread.sleep(1000); + if (attemptCount > 30) + { + System.err.println("Still no messages in the queue after "+attemptCount+" seconds"); + System.exit(0); + } + } + + /* + * got more messages, continue browsing + */ + System.err.println("Found more messages. Continue browsing."); + while(msgs.hasMoreElements()) + { + message = (javax.jms.Message)msgs.nextElement(); + System.err.println("Browsed message: number="+message.getIntProperty("msg_num")); + } + + /* + * close all and quit + */ + browser.close(); + + connection.close(); + } + catch(JMSException e) + { + e.printStackTrace(); + System.exit(0); + } + catch(InterruptedException e) + { + e.printStackTrace(); + System.exit(0); + } + + } + + public static void main(String args[]) + { + tibjmsQueueBrowser t = new tibjmsQueueBrowser(args); + } + + void usage() + { + System.err.println("\nUsage: java tibjmsQueueBrowser [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -queue - queue name, default is \"queue.sample.browser\""); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-queue")==0) + { + if ((i+1) >= args.length) usage(); + queueName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } + +} + + diff --git a/src/com/singularity/jms/tibjmsQueueReceiver.java b/src/com/singularity/jms/tibjmsQueueReceiver.java new file mode 100755 index 0000000..163af7a --- /dev/null +++ b/src/com/singularity/jms/tibjmsQueueReceiver.java @@ -0,0 +1,197 @@ +package com.singularity.jms; + +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsQueueReceiver.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a simple sample of basic QueueReceiver. + * + * This sampe subscribes to specified queue and + * receives and prints all received messages. + * This sample never quits. + * + * Notice that specified queue should exist in your configuration + * or your queues configuration file should allow + * creation of the specified queue. + * + * This sample can receive from dynamic queues thus it is + * using the QueueSession.createQueue() method in order to + * obtain the Queue object. + * + * Usage: java tibjmsQueueReceiver [options] + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -user User name. Default is null. + * -password User password. Default is null. + * -queue Queue name. Default is "queue.sample". + * + * + */ + +import javax.jms.*; +import javax.naming.*; + +public class tibjmsQueueReceiver +{ + String serverUrl = null; + String userName = null; + String password = null; + String queueName = "queue.sample"; + + public tibjmsQueueReceiver(String[] args) { + + parseArgs(args); + + /* print parameters */ + System.err.println("\n------------------------------------------------------------------------"); + System.err.println("tibjmsQueueReceiver SAMPLE"); + System.err.println("------------------------------------------------------------------------"); + System.err.println("Server....................... "+((serverUrl != null)?serverUrl:"localhost")); + System.err.println("User......................... "+((userName != null)?userName:"(null)")); + System.err.println("Queue........................ "+queueName); + System.err.println("------------------------------------------------------------------------\n"); + + try + { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + if (queueName == null) + { + System.err.println("Error: must specify queue name"); + usage(); + } + + System.err.println("Receiving from queue: "+queueName+"\n"); + + try + { + QueueConnectionFactory factory = new com.tibco.tibjms.TibjmsQueueConnectionFactory(serverUrl); + + QueueConnection connection = factory.createQueueConnection(userName,password); + + QueueSession session = connection.createQueueSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + /* + * Use createQueue() to enable receiving from dynamic queues. + */ + javax.jms.Queue queue = session.createQueue(queueName); + + QueueReceiver receiver = session.createReceiver(queue); + + connection.start(); + + /* read queue messages */ + while(true) + { + javax.jms.Message message = receiver.receive(); + if (message == null) + break; + + System.err.println("Received message: "+message); + } + + connection.close(); + } + catch(JMSException e) + { + e.printStackTrace(); + System.exit(0); + } + } + + public static void main(String args[]) + { + tibjmsQueueReceiver t = new tibjmsQueueReceiver(args); + } + + void usage() + { + System.err.println("\nUsage: java tibjmsQueueReceiver [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -queue - queue name, default is \"queue.sample\""); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-queue")==0) + { + if ((i+1) >= args.length) usage(); + queueName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } +} + + diff --git a/src/com/singularity/jms/tibjmsQueueSender.java b/src/com/singularity/jms/tibjmsQueueSender.java new file mode 100755 index 0000000..2c1fa12 --- /dev/null +++ b/src/com/singularity/jms/tibjmsQueueSender.java @@ -0,0 +1,218 @@ +package com.singularity.jms; + +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsQueueSender.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a simple sample of basic QueueSender. + * + * This sample publishes specified message(s) on a specified + * queue and quits. + * + * Notice that specified queue should exist in your configuration + * or your queues configuration file should allow + * creation of the specified queue. + * + * This sample can send into dynamic queues thus it is + * using the QueueSession.createQueue() method + * to obtain the Queue object. + * + * Usage: java tibjmsQueueSender [options] + * + * ... + * + * + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -user User name. Default is null. + * -password User password. Default is null. + * -queue Queue name. Default is "queue.sample" + * + * + */ + +import javax.jms.*; +import javax.naming.*; +import java.util.Vector; + +public class tibjmsQueueSender +{ + String serverUrl = null; + String userName = null; + String password = null; + String queueName = "queue.sample"; + + String[] queues = { "tibco.singularity.queue.inbound", "tibco.singularity.queue.outbound"}; + String[] topics = { "tibco.singularity.topic.inbound", "tibco.singularity.topic.outbound"}; + + Vector data = new Vector(); + + public tibjmsQueueSender(String[] args) { + + parseArgs(args); + + /* print parameters */ + System.out.println("\n------------------------------------------------------------------------"); + System.out.println("tibjmsQueueSender SAMPLE"); + System.out.println("------------------------------------------------------------------------"); + System.out.println("Server....................... "+(serverUrl!=null?serverUrl:"localhost")); + System.out.println("User......................... "+(userName!=null?userName:"(null)")); + System.out.println("Queue........................ "+queueName); + System.out.println("------------------------------------------------------------------------\n"); + + + try + { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + if (queueName == null) + { + System.err.println("Error: must specify queue name"); + usage(); + } + + if (data.size() == 0) + { + System.err.println("Error: must specify at least one message text"); + usage(); + } + + System.err.println("Publishing into queue: '"+queueName+"'\n"); + + try + { + QueueConnectionFactory factory = new com.tibco.tibjms.TibjmsQueueConnectionFactory(serverUrl); + QueueConnection connection = factory.createQueueConnection(userName,password); + QueueSession session = connection.createQueueSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + QueueSender sender = null; + /* + * Use createQueue() to enable sending into dynamic queues. + */ + + for (int i = 0; i < queues.length; i++) { + javax.jms.Queue queue = session.createQueue(queues[i]); + sender = session.createSender(queue); + } + + for (int i = 0; i < topics.length; i++) { + javax.jms.Topic topic1 = session.createTopic(topics[i]); + } + + + /* publish messages */ + for (int i=0; i"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -queue - queue name, default is \"queue.sample\""); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-queue")==0) + { + if ((i+1) >= args.length) usage(); + queueName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + data.addElement(args[i]); + i++; + } + } + } + +} + + diff --git a/src/com/singularity/jms/tibjmsTopicPublisher.java b/src/com/singularity/jms/tibjmsTopicPublisher.java new file mode 100755 index 0000000..d491855 --- /dev/null +++ b/src/com/singularity/jms/tibjmsTopicPublisher.java @@ -0,0 +1,219 @@ +package com.singularity.jms; +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsTopicPublisher.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a simple sample of a basic TopicPublisher. + * + * This sample publishes specified message(s) on a specified + * topic and quits. + * + * Notice that the specified topic should exist in your configuration + * or your topics configuration file should allow + * creation of the specified topic. Sample configuration supplied with + * the TIBCO Enterprise Message Service distribution allows creation of + * any topics. + * + * This sample can publish into dynamic topics thus it is + * using TopicSession.createTopic() method to obtain the Topic object. + * + * If this sample is used to publish messages into + * tibjmsTopicSubscriber sample, the tibjmsTopicSubscriber + * sample must be started first. + * + * If -topic is not specified this sample will use topic named + * "topic.sample". + * + * Usage: java tibjmsTopicPublisher [options] + * + * ... + * + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * -user User name. Default is null. + * -password User password. Default is null. + * -topic Topic name. Default value is "topic.sample" + * + */ + +import javax.jms.*; +import javax.naming.*; +import java.util.Vector; + +public class tibjmsTopicPublisher +{ + String serverUrl = null; + String userName = null; + String password = null; + + String topicName = "topic.sample"; + + Vector data = new Vector(); + + public tibjmsTopicPublisher(String[] args) { + + parseArgs(args); + + /* print parameters */ + System.out.println("\n------------------------------------------------------------------------"); + System.out.println("tibjmsTopicPublisher SAMPLE"); + System.out.println("------------------------------------------------------------------------"); + System.out.println("Server....................... "+(serverUrl!=null?serverUrl:"localhost")); + System.out.println("User......................... "+(userName!=null?userName:"(null)")); + System.out.println("Topic........................ "+topicName); + System.out.println("Message Text................. "); + for(int i=0;i"); + System.err.println(" [] ..."); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -topic - topic name, default is \"topic.sample\""); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + topicName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + data.addElement(args[i]); + i++; + } + } + } +} + + diff --git a/src/com/singularity/jms/tibjmsTopicSubscriber.java b/src/com/singularity/jms/tibjmsTopicSubscriber.java new file mode 100755 index 0000000..0051eb7 --- /dev/null +++ b/src/com/singularity/jms/tibjmsTopicSubscriber.java @@ -0,0 +1,202 @@ +package com.singularity.jms; + +/* + * Copyright (c) 2001-2006 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsTopicSubscriber.java 21731 2006-05-01 21:41:34Z $ + * + */ + +/* + * This is a simple sample of a basic TopicSubscriber. + * + * This sampe subscribes to specified topic and + * receives and prints all received messages. + * This sample never quits. + * + * Notice that the specified topic should exist in your configuration + * or your topics configuration file should allow + * creation of the specified topic. + * + * This sample can subscribe to dynamic topics thus it is + * using TopicSession.createTopic() method to obtain the Topic object. + * + * If this sample is used to receive messages published by + * tibjmsTopicPublisher sample, it must be started prior + * to running the tibjmsTopicPublisher sample. + * + * Usage: java tibjmsTopicSubscriber [options] + * + * where options are: + * + * -server Server URL. + * If not specified this sample assumes a + * serverUrl of "tcp://localhost:7222" + * + * -user User name. Default is null. + * -password User password. Default is null. + * -topic Topic name. DEfault is "topic.sample" + * + * + */ + +import javax.jms.*; +import javax.naming.*; + +public class tibjmsTopicSubscriber +{ + String serverUrl = null; + String userName = null; + String password = null; + String topicName = "topic.sample"; + + public tibjmsTopicSubscriber(String[] args) { + + parseArgs(args); + + /* print parameters */ + System.err.println("\n------------------------------------------------------------------------"); + System.err.println("tibjmsTopicSubscriber SAMPLE"); + System.err.println("------------------------------------------------------------------------"); + System.err.println("Server....................... "+((serverUrl != null)?serverUrl:"localhost")); + System.err.println("User......................... "+((userName != null)?userName:"(null)")); + System.err.println("Topic........................ "+topicName); + System.err.println("------------------------------------------------------------------------\n"); + + try + { + tibjmsUtilities.initSSLParams(serverUrl,args); + } + catch (JMSSecurityException e) + { + System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + + + if (topicName == null) { + System.err.println("Error: must specify topic name"); + usage(); + } + + System.err.println("Subscribing to topic: "+topicName); + + try + { + TopicConnectionFactory factory = new com.tibco.tibjms.TibjmsTopicConnectionFactory(serverUrl); + + TopicConnection connection = factory.createTopicConnection(userName,password); + + TopicSession session = connection.createTopicSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE); + + /* + * Use createTopic() to enable subscriptions to dynamic topics. + */ + javax.jms.Topic topic = session.createTopic(topicName); + + TopicSubscriber subscriber = session.createSubscriber(topic); + + connection.start(); + + /* read topic messages */ + while(true) + { + javax.jms.Message message = subscriber.receive(); + if (message == null) + break; + + System.err.println("Received message: "+ message); + + } + + connection.close(); + } + catch(JMSException e) + { + System.err.println("JMSException: "+e.getMessage()+", provider="+e.getErrorCode()); + e.printStackTrace(); + System.exit(0); + } + } + + public static void main(String args[]) + { + tibjmsTopicSubscriber t = new tibjmsTopicSubscriber(args); + } + + void usage() + { + System.err.println("\nUsage: java tibjmsTopicSubscriber [options]"); + System.err.println(""); + System.err.println(" where options are:"); + System.err.println(""); + System.err.println(" -server - EMS server URL, default is local server"); + System.err.println(" -user - user name, default is null"); + System.err.println(" -password - password, default is null"); + System.err.println(" -topic - topic name, default is \"topic.sample\""); + System.err.println(" -help-ssl - help on ssl parameters\n"); + System.exit(0); + } + + void parseArgs(String[] args) + { + int i=0; + + while(i < args.length) + { + if (args[i].compareTo("-server")==0) + { + if ((i+1) >= args.length) usage(); + serverUrl = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-topic")==0) + { + if ((i+1) >= args.length) usage(); + topicName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-user")==0) + { + if ((i+1) >= args.length) usage(); + userName = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-password")==0) + { + if ((i+1) >= args.length) usage(); + password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-help")==0) + { + usage(); + } + else + if (args[i].compareTo("-help-ssl")==0) + { + tibjmsUtilities.sslUsage(); + } + else + if(args[i].startsWith("-ssl")) + { + i += 2; + } + else + { + System.err.println("Unrecognized parameter: "+args[i]); + usage(); + } + } + } +} + + diff --git a/src/com/singularity/jms/tibjmsUtilities.java b/src/com/singularity/jms/tibjmsUtilities.java new file mode 100755 index 0000000..f631679 --- /dev/null +++ b/src/com/singularity/jms/tibjmsUtilities.java @@ -0,0 +1,313 @@ +package com.singularity.jms; +/* + * Copyright (c) 2001-2009 TIBCO Software Inc. + * All rights reserved. + * For more information, please contact: + * TIBCO Software Inc., Palo Alto, California, USA + * + * $Id: tibjmsUtilities.java 40106 2009-04-02 21:32:09Z $ + * + */ + +/* + * This sample uses JNDI to retrieve administered objects. + * + * Optionally all parameters hardcoded in this sample can be + * read from the jndi.properties file. + * + * This file also contains an SSL parameter helper class to enable + * an SSL connection to a TIBCO Enterprise Message Service server. + * + */ + +import javax.jms.*; +import javax.naming.*; +import java.util.Hashtable; +import java.util.Vector; +import java.security.*; + + +public class tibjmsUtilities +{ + static Context jndiContext = null; + + static final String providerContextFactory = + "com.tibco.tibjms.naming.TibjmsInitialContextFactory"; + + static final String defaultProtocol = "tibjmsnaming"; + + static final String defaultProviderURL = + defaultProtocol + "://localhost:7222"; + + public static void initJNDI(String providerURL) throws NamingException + { + initJNDI(providerURL,null,null); + } + + public static void initJNDI(String providerURL, String userName, String password) throws NamingException + { + if (jndiContext != null) + return; + + if (providerURL == null || (providerURL.length() == 0)) + providerURL = defaultProviderURL; + + try + { + Hashtable env = new Hashtable(); + env.put(Context.INITIAL_CONTEXT_FACTORY,providerContextFactory); + env.put(Context.PROVIDER_URL,providerURL); + + if (userName != null) { + + env.put(Context.SECURITY_PRINCIPAL,userName); + + if (password != null) + env.put(Context.SECURITY_CREDENTIALS,password); + } + + jndiContext = new InitialContext(env); + } + catch (NamingException e) + { + System.out.println("Failed to create JNDI InitialContext with provider URL set to "+ + providerURL+", error = "+e.toString()); + throw e; + } + } + + public static Object lookup(String objectName) throws NamingException + { + if (objectName == null) + throw new IllegalArgumentException("null object name not legal"); + + if (objectName.length() == 0) + throw new IllegalArgumentException("empty object name not legal"); + + /* + * check if not initialized, then initialize + * with default parameters + */ + initJNDI(null); + + /* + * do the lookup + */ + return jndiContext.lookup(objectName); + } + + + public static void initSSLParams(String serverUrl,String[] args) throws JMSSecurityException{ + if (serverUrl != null && serverUrl.indexOf("ssl://") >= 0) { + SSLParams ssl = new SSLParams(args); + + ssl.init(); + } + } + + public static void sslUsage() + { + System.err.println("\nSSL options:"); + System.err.println(""); + System.err.println(" -ssl_vendor - SSL vendor: 'j2se' or 'entrust6'"); + System.err.println(" -ssl_trace - trace SSL initialization"); + System.err.println(" -ssl_vendor_trace - trace SSL handshake and related"); + System.err.println(" -ssl_trusted[n] - file with trusted certificates,"); + System.err.println(" this parameter may repeat if more"); + System.err.println(" than one file required"); + System.err.println(" -ssl_verify_hostname - do not verify certificate name."); + System.err.println(" (this disabled by default)"); + System.err.println(" -ssl_expected_hostname - expected name in the certificate"); + System.err.println(" -ssl_custom - use custom verifier (it shows names"); + System.err.println(" always approves them)."); + System.err.println(" -ssl_identity - client identity file"); + System.err.println(" -ssl_issuer[n] - client issuer file"); + System.err.println(" -ssl_private_key - client key file (optional)"); + System.err.println(" -ssl_password - password to decrypt client identity"); + System.err.println(" or key file"); + System.err.println(" -ssl_ciphers - cipher suite names, colon separated"); + System.exit(0); + } + +private static class SSLParams implements com.tibco.tibjms.TibjmsSSLHostNameVerifier { + String ssl_vendor = null; + boolean ssl_trace = false; + boolean ssl_debug_trace = false; + boolean ssl_verify_hostname = false; + String ssl_expected_hostname = null; + Vector ssl_trusted = null; + Vector ssl_issuers = null; + String ssl_identity = null; + String ssl_private_key = null; + String ssl_password = null; + boolean ssl_custom = false; + String ssl_ciphers = null; + + public SSLParams(String[] args) { + int trusted_pi = 0; + String trusted_suffix = ""; + int issuer_pi = 0; + String issuer_suffix = ""; + + int i=0; + while(i < args.length) + { + if (args[i].compareTo("-ssl_vendor")==0) + { + if ((i+1) >= args.length) sslUsage(); + ssl_vendor = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-ssl_trace")==0) + { + ssl_trace = true; + i += 1; + } + else + if (args[i].compareTo("-ssl_debug_trace")==0) + { + ssl_debug_trace = true; + i += 1; + } + else + if (args[i].compareTo("-ssl_expected_hostname")==0) + { + if ((i+1) >= args.length) sslUsage(); + ssl_expected_hostname = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-ssl_verify_hostname")==0) + { + ssl_verify_hostname = true; + i += 1; + } + else + if (args[i].compareTo("-ssl_custom")==0) + { + ssl_custom = true; + i += 1; + } + else + if (args[i].compareTo("-ssl_ciphers")==0) + { + if ((i+1) >= args.length) sslUsage(); + ssl_ciphers = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-ssl_identity")==0) + { + if ((i+1) >= args.length) sslUsage(); + ssl_identity = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-ssl_private_key")==0) + { + if ((i+1) >= args.length) sslUsage(); + ssl_private_key = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-ssl_password")==0) + { + if ((i+1) >= args.length) sslUsage(); + ssl_password = args[i+1]; + i += 2; + } + else + if (args[i].compareTo("-ssl_trusted"+trusted_suffix)==0) + { + if ((i+1) >= args.length) sslUsage(); + String cert = args[i+1]; + if (cert == null) continue; + if (ssl_trusted == null) + ssl_trusted = new Vector(); + ssl_trusted.addElement(cert); + trusted_pi++; + trusted_suffix = String.valueOf(trusted_pi); + i += 2; + } + else + if (args[i].compareTo("-ssl_issuer"+issuer_suffix)==0) + { + if ((i+1) >= args.length) sslUsage(); + String cert = args[i+1]; + if (cert == null) continue; + if (ssl_issuers == null) + ssl_issuers = new Vector(); + ssl_issuers.addElement(cert); + issuer_pi++; + issuer_suffix = String.valueOf(issuer_pi); + i += 2; + } + else + { + i++; + } + } + } + + public void init() throws JMSSecurityException { + if (ssl_trace) + com.tibco.tibjms.TibjmsSSL.setClientTracer(System.err); + + if (ssl_debug_trace) + com.tibco.tibjms.TibjmsSSL.setDebugTraceEnabled(true); + + if (ssl_vendor != null) + com.tibco.tibjms.TibjmsSSL.setVendor(ssl_vendor); + + if (ssl_expected_hostname != null) + com.tibco.tibjms.TibjmsSSL.setExpectedHostName(ssl_expected_hostname); + + if (ssl_custom) + com.tibco.tibjms.TibjmsSSL.setHostNameVerifier(this); + + if (!ssl_verify_hostname) + com.tibco.tibjms.TibjmsSSL.setVerifyHostName(false); + + if (ssl_trusted != null) { + for (int i=0; i