Sunday, December 11, 2011

Scala JMX console & scripts examples

I've released a JMX API for scala, ( project-link ) which is straightforward to use in scripts : I provide a single executable jar file named "jajmx.jar", containing everything required to start a scala console or to run a scala script dedicated to jmx operations.
Console mode usage example :
$ java -jar jajmx.jar -usejavacp
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_29).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import fr.janalyse.jmx._
import fr.janalyse.jmx._

scala> val jmx=JMX("localhost", 9999, None)
jmx: fr.janalyse.jmx.JMX = fr.janalyse.jmx.JMX@1ce59895

scala> jmx.domains
res0: List[java.lang.String] = List(JMImplementation, com.sun.management, java.lang, java.util.logging)

scala> jmx.runtime map {_.get[Long]("Uptime")}
res5: Option[Long] = Some(149014)

scala> jmx.os map {_.get[String]("Version")}
res6: Option[String] = Some(3.0.6-gentoo)

scala> jmx("java.lang:type=Memory").set("Verbose", true)

scala> jmx("java.lang:type=Memory").call("gc")
[GC 45515K->28456K(310720K), 0.0010380 secs]
[Full GC 28456K->26792K(310720K), 0.2427710 secs]
res11: Option[Nothing] = None

A simple script example (Invoke an explicit GC from JMX) :
#!/bin/sh
exec java -jar jajmx.jar -nocompdaemon -usejavacp -savecompiled "$0" "$@"
!#
import fr.janalyse.jmx._

if (args.size != 2) {
  println("Usage : gcforce host port")
  System.exit(1)
}
val host=args(0)
val port=args(1).toInt

JMX.connect(host, port) { jmx =>
  val mem  = jmx("java.lang:type=Memory")
  mem.call("gc")
  println("Explicit GC invoked on host %s port %d".format(host,port))
}

No comments:

Post a Comment