JMX Access

Version 20.1 by Denis Gervalle on 2021/03/18 11:25

cogGet and set JMX MBean attributes
TypeSnippet
Category
Developed by

Vincent Massol

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Description

Shows how to use Groovy to access (get/set) JMX attributes.

Example 1: Accessing JVM information

{{groovy}}
import java.lang.management.*

def os = ManagementFactory.operatingSystemMXBean
println """OPERATING SYSTEM:
\tarchitecture = $os.arch
\tname = $os.name
\tversion = $os.version
\tprocessors = $os.availableProcessors
"""


def rt = ManagementFactory.runtimeMXBean
println """RUNTIME:
\tname = $rt.name
\tspec name = $rt.specName
\tvendor = $rt.specVendor
\tspec version = $rt.specVersion
\tmanagement spec version = $rt.managementSpecVersion
"""


def cl = ManagementFactory.classLoadingMXBean
println """CLASS LOADING SYSTEM:
\tisVerbose = ${cl.isVerbose()}
\tloadedClassCount = $cl.loadedClassCount
\ttotalLoadedClassCount = $cl.totalLoadedClassCount
\tunloadedClassCount = $cl.unloadedClassCount
"""


def comp = ManagementFactory.compilationMXBean
println """COMPILATION:
\ttotalCompilationTime = $comp.totalCompilationTime
"""


def mem = ManagementFactory.memoryMXBean
def heapUsage = mem.heapMemoryUsage
def nonHeapUsage = mem.nonHeapMemoryUsage
println """MEMORY:
HEAP STORAGE:
\tcommitted = $heapUsage.committed
\tinit = $heapUsage.init
\tmax = $heapUsage.max
\tused = $heapUsage.used
NON-HEAP STORAGE:
\tcommitted = $nonHeapUsage.committed
\tinit = $nonHeapUsage.init
\tmax = $nonHeapUsage.max
\tused = $nonHeapUsage.used
"""


ManagementFactory.memoryPoolMXBeans.each{ mp ->
    println "\tname: " + mp.name
    String[] mmnames = mp.memoryManagerNames
    mmnames.each{ mmname ->
        println "\t\tManager Name: $mmname"
   }
    println "\t\tmtype = $mp.type"
    println "\t\tUsage threshold supported = " + mp.isUsageThresholdSupported()
}
println()

def td = ManagementFactory.threadMXBean
println "THREADS:"
td.allThreadIds.each { tid ->
    println "\tThread name = ${td.getThreadInfo(tid).threadName}"
}
println()

println "GARBAGE COLLECTION:"
ManagementFactory.garbageCollectorMXBeans.each { gc ->
    println "\tname = $gc.name"
    println "\t\tcollection count = $gc.collectionCount"
    println "\t\tcollection time = $gc.collectionTime"
    String[] mpoolNames = gc.memoryPoolNames
    mpoolNames.each { mpoolName ->
        println "\t\tmpool name = $mpoolName"
   }
}
{{/groovy}}

Results in:

jvm.png

Example 2: TCPPING get/set log level

Shows how to display and how to change the current log level of a JGroups Protocol (TCPPING). This allows enabling logging JGroups information in a running XWiki instance, which is useful when trying to diagnose issues in a XWiki Cluster (it uses JGroups).

{{groovy}}
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;

MBeanServer server = ManagementFactory.getPlatformMBeanServer();
def mbean = new GroovyMBean(server, 'jgroups:type=protocol,cluster=event,protocol=TCPPING')

println "Current log level for TCPPING:"
println mbean.Level

println "Set log level to DEBUG"
mbean.Level = "debug"
{{/groovy}}

Example 3: List all JGroups attribute values

{{groovy}}
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;

MBeanServer server = ManagementFactory.getPlatformMBeanServer();

def query = new ObjectName('jgroups:*')
def allNames = server.queryNames(query, null)

for(protocol in allNames) {
 def mbean = new GroovyMBean(server, protocol)
  println "== Config for {{{ ${protocol} }}} =="
 for(attr in mbean.listAttributeNames()) {
    println "* ${attr}: ${mbean.getProperty(attr)}"
  }
}
{{/groovy}}

Results in:

jmx.png

Example 4: Set Log Level for any XWiki category

Example to set the "org.xwiki" category log level to DEBUG:

{{groovy}}
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;

MBeanServer server = ManagementFactory.getPlatformMBeanServer();
def mbean = new GroovyMBean(server, 'logback:type=xwiki')

println "Current log level for 'org.xwiki':"
println mbean.getLoggerLevel("org.xwiki")

println "Set log level to DEBUG"
mbean.setLoggerLevel("org.xwiki", "debug")
{{/groovy}}

Example 5: Getting a full thread-dump

The below code delivers a thread-dump similar to when the QUIT signal is sent on Unix boxes.

{{groovy}}
import java.lang.management.ManagementFactory

def tmxB = ManagementFactory.getThreadMXBean();
def threadDump = tmxB.dumpAllThreads(true,true);

response.setContentType("text/plain")
println("Thread Dump: "+ new Date())
println("")
int n=threadDump.length;
for(int i=0; i<n; i++) {
    println(\"" + threadDump[i].getThreadName()  + "\" " + threadDump[i].threadState);
   def stackTrace = threadDump[i].stackTrace;
   def l =stackTrace.length;
   for(int j=0; j<l; j++) {
       def frame = stackTrace[j]
        StringBuilder b = new StringBuilder();
        b.append("   ");
        b.append(frame.getClassName()).append('.').append(frame.methodName);
       if(frame.isNativeMethod()) {
            b.append("(Native)");
        } else {
            String filename = frame.fileName;
           if(filename!=null) b.append(frame.fileName).append(':').append(frame.lineNumber);
        }
        println(b);
    }
    println();
}
{{/groovy}}

Example 6: List cache statistics

{{groovy}}
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;

MBeanServer server = ManagementFactory.getPlatformMBeanServer();
def query = new ObjectName("org.xwiki.infinispan:component=Statistics,*")
def names = server.queryNames(query, null)
names.each {
  println "== Cache: ${it.getKeyProperty('name')} =="
 def mbean = new GroovyMBean(server, it)
 for(attr in mbean.listAttributeNames()) {
    println "* ${attr}: ${mbean.getProperty(attr)}"
  }
}
{{/groovy}}

Example 7: Switch statistics collection states (enabled/disabled) on a cache

Example to switch the current state of statistics collection for the page cache ("xwiki.store.pagecache(local)"):

{{groovy}}
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Attribute;

MBeanServer server = ManagementFactory.getPlatformMBeanServer();
def objectName = new ObjectName('org.xwiki.infinispan:type=Cache,name="xwiki.store.pagecache(local)",manager="xwiki",component=Statistics')
def statsState = server.getAttribute(objectName,'statisticsEnabled')
println "Statistics were ${statsState ? 'enabled' : 'disabled'}";
def enableStats = new Attribute("statisticsEnabled", !statsState);
server.setAttribute(objectName,enableStats);
println "Statistics are now ${server.getAttribute(objectName,'statisticsEnabled') ? 'enabled' : 'disabled'}";
{{/groovy}}
     

Get Connected