Debian Codegraph @

subprojects/groovy-jmx/src/spec/doc/jmx.adoc

raw
1 //////////////////////////////////////////
2
3 Licensed to the Apache Software Foundation (ASF) under one
4 or more contributor license agreements. See the NOTICE file
5 distributed with this work for additional information
6 regarding copyright ownership. The ASF licenses this file
7 to you under the Apache License, Version 2.0 (the
8 "License"); you may not use this file except in compliance
9 with the License. You may obtain a copy of the License at
10
11 http://www.apache.org/licenses/LICENSE-2.0
12
13 Unless required by applicable law or agreed to in writing,
14 software distributed under the License is distributed on an
15 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 KIND, either express or implied. See the License for the
17 specific language governing permissions and limitations
18 under the License.
19
20 //////////////////////////////////////////
21
22 = Working with JMX
23
24
25 == Introduction
26
27 Given that Groovy sits directly on top of Java, Groovy can leverage the tremendous amount of work already done for http://www.oracle.com/technetwork/java/javase/tech/javamanagement-140525.html[JMX] with Java. In addition, Groovy provides a `GroovyMBean` class which makes an MBean look like a normal Groovy object. This simplifies Groovy code for interacting with __MBeans__. For example, the following code:
28
29 [source,groovy]
30 ----
31 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=introduction_example,indent=0]
32 ----
33
34 can be simplified to:
35
36 [source,groovy]
37 ----
38 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=introduction_simplified_example,indent=0]
39 ----
40
41 The remainder of this page shows you how to:
42
43 - Monitor the JVM using MXBeans
44 - Monitor Apache Tomcat and display statistics
45 - Monitor Oracle OC4J and display information
46 - Monitor BEA WebLogic and display information
47 - Leverage Spring's MBean annotation support to export your Groovy beans as MBeans
48
49 == Monitoring the JVM
50
51 MBeans are not accessed directly by an application but are managed by a repository called an __MBean server__. Java includes a special MBean server called the __platform MBean server__, which is built into the JVM. Platform MBeans are registered in this server using unique names.
52
53 You can monitor the JVM through its platform MBeans with the following code:
54
55 [source,groovy]
56 ----
57 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=the_jvm,indent=0]
58 ----
59
60 When run, you will see something like this:
61
62 ----
63 OPERATING SYSTEM:
64 architecture = x86
65 name = Windows XP
66 version = 5.1
67 processors = 2
68
69 RUNTIME:
70 name = 620@LYREBIRD
71 spec name = Java Virtual Machine Specification
72 vendor = Sun Microsystems Inc.
73 spec version = 1.0
74 management spec version = 1.0
75
76 CLASS LOADING SYSTEM:
77 isVerbose = false
78 loadedClassCount = 919
79 totalLoadedClassCount = 919
80 unloadedClassCount = 0
81
82 COMPILATION:
83 totalCompilationTime = 91
84
85 MEMORY:
86 HEAP STORAGE:
87 committed = 3108864
88 init = 0
89 max = 66650112
90 used = 1994728
91 NON-HEAP STORAGE:
92 committed = 9240576
93 init = 8585216
94 max = 100663296
95 used = 5897880
96
97 name: Code Cache
98 Manager Name: CodeCacheManager
99 mtype = Non-heap memory
100 Usage threshold supported = true
101 name: Eden Space
102 Manager Name: MarkSweepCompact
103 Manager Name: Copy
104 mtype = Heap memory
105 Usage threshold supported = false
106 name: Survivor Space
107 Manager Name: MarkSweepCompact
108 Manager Name: Copy
109 mtype = Heap memory
110 Usage threshold supported = false
111 name: Tenured Gen
112 Manager Name: MarkSweepCompact
113 mtype = Heap memory
114 Usage threshold supported = true
115 name: Perm Gen
116 Manager Name: MarkSweepCompact
117 mtype = Non-heap memory
118 Usage threshold supported = true
119
120 THREADS:
121 Thread name = Monitor Ctrl-Break
122 Thread name = Signal Dispatcher
123 Thread name = Finalizer
124 Thread name = Reference Handler
125 Thread name = main
126
127 GARBAGE COLLECTION:
128 name = Copy
129 collection count = 60
130 collection time = 141
131 mpool name = Eden Space
132 mpool name = Survivor Space
133 name = MarkSweepCompact
134 collection count = 0
135 collection time = 0
136 mpool name = Eden Space
137 mpool name = Survivor Space
138 mpool name = Tenured Gen
139 mpool name = Perm Gen
140 ----
141
142 == Monitoring Tomcat
143
144 First start up http://tomcat.apache.org[Tomcat] with JMX monitoring enabled by setting the following:
145
146 [source,shell]
147 ----
148 set JAVA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9004\
149 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
150 ----
151
152 You can do this in your startup script and may choose any available port, we used 9004.
153
154 The following code uses JMX to discover the available MBeans in the running Tomcat, determine which are web modules, extract the processing time for each web module and displays the result in a graph using JFreeChart:
155
156 [source,groovy]
157 ----
158 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=tomcat,indent=0]
159 ----
160
161 When run, we will see a trace of progress being made:
162
163 ----
164 Connected to: Apache Tomcat/6.0.13
165 Found 5 web modules. Processing ...
166 Catalina:j2eeType=WebModule,name=//localhost/,J2EEApplication=none,J2EEServer=none
167 Catalina:j2eeType=WebModule,name=//localhost/host-manager,J2EEApplication=none,J2EEServer=none
168 Catalina:j2eeType=WebModule,name=//localhost/docs,J2EEApplication=none,J2EEServer=none
169 Catalina:j2eeType=WebModule,name=//localhost/examples,J2EEApplication=none,J2EEServer=none
170 Catalina:j2eeType=WebModule,name=//localhost/manager,J2EEApplication=none,J2EEServer=none
171 ----
172
173 The output will look like this:
174
175 image:assets/img/catalina.gif[]
176
177 Note: if you get errors running this script, see the **Troubleshooting** section below.
178
179 == OC4J Example
180
181 Here is a script to access OC4J and print out some information about the server, its runtime and (as an example) the configured JMS destinations:
182
183 [source,groovy]
184 ----
185 import javax.management.remote.*
186 import oracle.oc4j.admin.jmx.remote.api.JMXConnectorConstant
187
188 def serverUrl = new JMXServiceURL('service:jmx:rmi://localhost:23791')
189 def serverPath = 'oc4j:j2eeType=J2EEServer,name=standalone'
190 def jvmPath = 'oc4j:j2eeType=JVM,name=single,J2EEServer=standalone'
191 def provider = 'oracle.oc4j.admin.jmx.remote'
192 def credentials = [
193 (JMXConnectorConstant.CREDENTIALS_LOGIN_KEY): 'oc4jadmin',
194 (JMXConnectorConstant.CREDENTIALS_PASSWORD_KEY): 'admin'
195 ]
196 def env = [
197 (JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES): provider,
198 (JMXConnector.CREDENTIALS): credentials
199 ]
200 def server = JmxFactory.connect(serverUrl, env).MBeanServerConnection
201 def serverInfo = new GroovyMBean(server, serverPath)
202 def jvmInfo = new GroovyMBean(server, jvmPath)
203 println """Connected to $serverInfo.node. \
204 Server started ${new Date(serverInfo.startTime)}.
205 OC4J version: $serverInfo.serverVersion from $serverInfo.serverVendor
206 JVM version: $jvmInfo.javaVersion from $jvmInfo.javaVendor
207 Memory usage: $jvmInfo.freeMemory bytes free, \
208 $jvmInfo.totalMemory bytes total
209 """
210
211 def query = new javax.management.ObjectName('oc4j:*')
212 String[] allNames = server.queryNames(query, null)
213 def dests = allNames.findAll { name ->
214 name.contains('j2eeType=JMSDestinationResource')
215 }.collect { new GroovyMBean(server, it) }
216
217 println "Found ${dests.size()} JMS destinations. Listing ..."
218 dests.each { d -> println "$d.name: $d.location" }
219 ----
220
221 Here is the result of running this script:
222
223 ----
224 Connected to LYREBIRD. Server started Thu May 31 21:04:54 EST 2007.
225 OC4J version: 11.1.1.0.0 from Oracle Corp.
226 JVM version: 1.6.0_01 from Sun Microsystems Inc.
227 Memory usage: 8709976 bytes free, 25153536 bytes total
228
229 Found 5 JMS destinations. Listing ...
230 Demo Queue: jms/demoQueue
231 Demo Topic: jms/demoTopic
232 jms/Oc4jJmsExceptionQueue: jms/Oc4jJmsExceptionQueue
233 jms/RAExceptionQueue: jms/RAExceptionQueue
234 OracleASRouter_store: OracleASRouter_store
235 ----
236
237 As a slight variation, this script displays a pie chart of memory usage using JFreeChart:
238
239 [source,groovy]
240 ----
241 import org.jfree.chart.ChartFactory
242 import javax.swing.WindowConstants as WC
243 import javax.management.remote.*
244 import oracle.oc4j.admin.jmx.remote.api.JMXConnectorConstant
245
246 def url = 'service:jmx:rmi://localhost:23791'
247 def credentials = [:]
248 credentials[JMXConnectorConstant.CREDENTIALS_LOGIN_KEY] = "oc4jadmin"
249 credentials[JMXConnectorConstant.CREDENTIALS_PASSWORD_KEY] = "password"
250 def env = [:]
251 env[JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES] = "oracle.oc4j.admin.jmx.remote"
252 env[JMXConnector.CREDENTIALS] = credentials
253 def server = JMXConnectorFactory.connect(new JMXServiceURL(url), env).MBeanServerConnection
254 def jvmInfo = new GroovyMBean(server, 'oc4j:j2eeType=JVM,name=single,J2EEServer=standalone')
255
256 def piedata = new org.jfree.data.general.DefaultPieDataset()
257 piedata.setValue "Free", jvmInfo.freeMemory
258 piedata.setValue "Used", jvmInfo.totalMemory - jvmInfo.freeMemory
259
260 def options = [true, true, true]
261 def chart = ChartFactory.createPieChart('OC4J Memory Usage', piedata, *options)
262 chart.backgroundPaint = java.awt.Color.white
263 def swing = new groovy.swing.SwingBuilder()
264 def frame = swing.frame(title:'OC4J Memory Usage', defaultCloseOperation:WC.EXIT_ON_CLOSE) {
265 panel(id:'canvas') { rigidArea(width:350, height:250) }
266 }
267 frame.pack()
268 frame.show()
269 chart.draw(swing.canvas.graphics, swing.canvas.bounds)
270 ----
271
272 Which looks like:
273
274 image:assets/img/oc4jpie.gif[]
275
276 == WebLogic Example
277
278 This script prints out information about the server followed by information about JMS Destinations (as an example). Many other mbeans are http://docs.oracle.com/cd/E13222_01/wls/docs90/wlsmbeanref/core/index.html[available].
279
280 [source,groovy]
281 ----
282 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=weblogic,indent=0]
283 ----
284
285 Here is the output:
286
287 ----
288 Server: name=examplesServer, state=RUNNING, version=WebLogic Server 10.0 Wed May 9 18:10:27 EDT 2007 933139
289 JMS Destination: name=examples-jms!exampleTopic, type=Topic, messages=0
290 JMS Destination: name=examples-jms!exampleQueue, type=Queue, messages=0
291 JMS Destination: name=examples-jms!jms/MULTIDATASOURCE_MDB_QUEUE, type=Queue, messages=0
292 JMS Destination: name=examplesJMSServer!examplesJMSServer.TemporaryQueue0, type=Queue, messages=68
293 JMS Destination: name=examples-jms!quotes, type=Topic, messages=0
294 JMS Destination: name=examples-jms!weblogic.wsee.wseeExamplesDestinationQueue, type=Queue, messages=0
295 JMS Destination: name=examples-jms!weblogic.examples.ejb30.ExampleQueue, type=Queue, messages=0
296 ----
297
298 == Spring Example
299
300 You can also use Spring to automatically register beans as JMX aware.
301
302 Here is an example class (Calculator.groovy):
303
304 [source,groovy]
305 ----
306 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=spring_classes,indent=0]
307 ----
308
309 Here is the Spring configuration file (beans.xml):
310
311 [source,xml]
312 ----
313 <?xml version="1.0" encoding="UTF-8"?>
314 <beans xmlns="http://www.springframework.org/schema/beans"
315 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
316 xsi:schemaLocation="
317 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
318 <bean id="mbeanServer"
319 class="org.springframework.jmx.support.MBeanServerFactoryBean">
320 <property name="locateExistingServerIfPossible" value="true"/>
321 </bean>
322
323 <bean id="exporter"
324 class="org.springframework.jmx.export.MBeanExporter">
325 <property name="assembler" ref="assembler"/>
326 <property name="namingStrategy" ref="namingStrategy"/>
327 <property name="beans">
328 <map>
329 <entry key="bean:name=defaultCalcName" value-ref="calcBean"/>
330 </map>
331 </property>
332 <property name="server" ref="mbeanServer"/>
333 <property name="autodetect" value="true"/>
334 </bean>
335
336 <bean id="jmxAttributeSource"
337 class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>
338
339 <!-- will create management interface using annotation metadata -->
340 <bean id="assembler"
341 class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
342 <property name="attributeSource" ref="jmxAttributeSource"/>
343 </bean>
344
345 <!-- will pick up the ObjectName from the annotation -->
346 <bean id="namingStrategy"
347 class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
348 <property name="attributeSource" ref="jmxAttributeSource"/>
349 </bean>
350
351 <bean id="calcBean"
352 class="Calculator">
353 <property name="base" value="10"/>
354 </bean>
355 </beans>
356 ----
357
358 Here is a script which uses this bean and configuration:
359
360 [source,groovy]
361 ----
362 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=spring_usage,indent=0]
363 ----
364
365 And here is the resulting output:
366
367 ----
368 Number of invocations: 5
369 MBean Name:
370 bean:name=calcMBean
371
372 Attributes:
373 (rw) int Base
374 (r) int Invocations
375 Operations:
376 int add(int x, int y)
377 java.lang.String addStrings(java.lang.String x, java.lang.String y)
378 int getInvocations()
379 int getBase()
380 void setBase(int p1)
381 ----
382
383 You can even attach to the process while it is running with http://docs.oracle.com/javase/1.5.0/docs/guide/management/jconsole.html[jconsole]. It will look something like:
384
385 image:assets/img/jconsole.gif[]
386
387 We started the Groovy application with the `-Dcom.sun.management.jmxremote` JVM argument.
388
389 See also:
390
391 - https://docs.spring.io/spring/docs/current/spring-framework-reference/languages.html#dynamic-language-beans[Dynamic language beans in Spring]
392 - https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#jmx[Spring JMX Documentation]
393
394 == Troubleshooting
395
396 === java.lang.SecurityException
397
398 If you get the following error, your container's JMX access is password protected:
399
400 ----
401 java.lang.SecurityException: Authentication failed! Credentials required
402 ----
403
404 To fix that, add an environment with the credentials when connecting, like this (password has to be set before that):
405
406 [source,groovy]
407 ----
408 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=troubleshooting,indent=0]
409 ----
410
411 Details for the software you are trying to monitor/manage may differ slightly. Check out the other examples using credentials above if appropriate (e.g. OC4J and WebLogic). If you still have troubles, you will have to consult the documentation for the software you are trying to monitor/manage for details on how to provide credentials.
412
413 [[jmx_jmxbuilder]]
414 == JmxBuilder
415
416 **JmxBuilder is a Groovy-based domain specific language for the Java Management Extension (JMX) API**. It uses the builder pattern (FactoryBuilder) to create an internal DSL that facilitates the exposure of POJO's and Groovy beans as management components via the MBean server. JmxBuilder hides the complexity of creating and exporting management beans via the JMX API and provides a set of natural Groovy constructs to interact with the JMX infrastructure.
417
418 === Instantiating JmxBuilder
419
420 To start using JmxBuilder, simply make sure the jar file is on your class path. Then you can do the following in your code:
421
422 [source,groovy]
423 ----
424 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=instantiating_jmxbuilder,indent=0]
425 ----
426
427 **That's it!** You are now ready to use the JmxBuilder.
428
429 **NOTE**
430
431 - You can pass in an instance of **your own MBeanServer** to the builder (**JmxBuilder(MBeanServer)**)
432 - If no MBeanServer is specified, the builder instance will default to the underlying platform MBeanServer.
433
434 Once you have an instance of JmxBuilder, you are now ready to invoke any of its builder nodes.
435
436 === JMX Connectors
437
438 Remote connectivity is a crucial part of the JMX architecture. JmxBuilder facilitates the creation of connector servers and connector clients with a minimal amount of coding.
439
440 ==== Connector Server
441
442 JmxBuilder.connectorServer() supports the full Connector api syntax and will let you specify properties, override the URL, specify your own host, etc.
443
444 **Syntax**
445
446 ----
447 jmx.connectorServer(
448 protocol:"rmi",
449 host:"...",
450 port:1099,
451 url:"...",
452 properties:[
453 "authenticate":true|false,
454 "passwordFile":"...",
455 "accessFile":"...",
456 "sslEnabled" : true | false
457 // any valid connector property
458 ]
459 )
460 ----
461
462 Note that the serverConnector node will accept four ServerConnector property aliases (authenticate, passwordFile,accessFile, and sslEnabled). You can use these aliases or provided any of the RMI-supported properties.
463
464 **Example - Connector Server (see correction below)**
465
466 [source,groovy]
467 ----
468 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=connector_server,indent=0]
469 ----
470
471 The snippet above returns an RMI connector that will start listening on port 9000. By default, the builder will internally generate URL **"service:jmx:rmi:///jndi/rmi://localhost:9000/jmxrmi"**.
472
473 __NOTE: Sadly you are as likely to get something like the following when attempting to run the previous snippet of code (example is incomplete, see below):__
474
475 ----
476 Caught: java.io.IOException: Cannot bind to URL [rmi://localhost:9000/jmxrmi]: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: localhost; nested exception is:
477 ?????? java.net.ConnectException: Connection refused]
478 ??
479 ----
480
481 __This occurs on Mac and Linux (CentOS 5) with Groovy 1.6 installed. Perhaps there were assumptions made about the configuration of the /etc/hosts file?__
482
483 NOTE: __The correct example is shown below.__
484
485 **Connector Example (Corrected) - Connector Server**
486
487 The example above does not create the RMI registry. So, in order to export, you have to first export the RMI object registry (make sure to import `java.rmi.registry.LocateRegistry`).
488
489 [source,groovy]
490 ----
491 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=connector_server_and_local_registry,indent=0]
492 ----
493
494 ==== Connector Client
495
496 JmxBuilder.connectorClient() node lets you create JMX connector client object to connect to a JMX MBean Server.
497
498 **Syntax**
499
500 ----
501 jmx.connectorClient (
502 protocol:"rmi",
503 host:"...",
504 port:1099,
505 url:"...",
506 )
507 ----
508
509 **Example - Client Connector**
510
511 Creating a connector client can be done just as easily. With one line of code, you can create an instance of a JMX Connector Client as shown below.
512
513 [source,groovy]
514 ----
515 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=client_connector,indent=0]
516 ----
517
518 You can then access the MBeanServerConnection associated with the connector using:
519
520 [source,groovy]
521 ----
522 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=client_connector_usage,indent=0]
523 ----
524
525 === JmxBuilder MBean Export
526
527 You can **export a Java object or a Groovy object** with minimal coding. JmxBuilder will even find and **export dynamic Groovy methods** injected at runtime.
528
529 ==== Implicit vs Explicit Descriptors
530
531 When using the builder, you can **let JmxBuilder implicitly generate** all of your MBean descriptor info. This is useful when you want to write minimal code to quickly export your beans. You can also explicitly declare all descriptor info for the bean. This gives you total control on how you want to describe every piece of information that you want to export for the underlying bean.
532
533 ==== The JmxBuilder.export() Node
534
535 The **JmxBuilder.export() node provides a container** where all management entities to be exported to the MBeanServer are placed. You can place one or more bean() or timer() nodes as children of the export() node. JmxBuilder will **automatically batch export the entities described** by the nodes to the MBean server for management (see example below).
536
537 [source,groovy]
538 ----
539 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=jmxbuilder_export,indent=0]
540 ----
541
542 In the code snippet above, **JmxBuilder.export() will export three management beans** to the MBean server.
543
544 ==== JmxBuilder.export() Syntax
545
546 JmxBuilder.export() node supports the **registrationPolicy** parameter to specify how JmxBuilder will behave to resolve bean name collision during MBean registration:
547
548 ----
549 jmx.export(policy:"replace|ignore|error")
550 or
551 jmx.export(regPolicy:"replace|ignore|error")
552 ----
553
554 - **replace** - JmxBuilder.export() will replace any bean already registered with the MBean during export.
555 - **ignore** - The bean being exported will be ignored if the same bean is already registered.
556 - **error** - JmxBuilder.export() throws an error upon bean name collision during registration.
557
558 ==== Integration with GroovyMBean Class
559
560 When you export an MBean to the MBeanServer, **JmxBuilder will return an instance of GroovyMBean** representing the management bean that have been exported by the builder. Nodes such as **bean()** and **timer()** will return an instances of GroovyMBean when they are invoked. The **export()** node returns an **array of all of GroovyMBean[]** representing all managed objects exported to the MBean server.
561
562 ==== MBean Registration with JmxBuilder.bean()
563
564 This portion of this reference uses class **RequestController** to illustrate how to use JmxBuilder to export runtime management beans. The class is for illustration purpose and can be a POJO or a Groovy bean.
565
566 **RequestController**
567
568 [source,groovy]
569 ----
570 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=request_controller,indent=0]
571 ----
572
573 ===== Implicit Export
574
575 As mentioned earlier, you can use JmxBuilder's flexible syntax to export any POJO/POGO with no descriptor. The builder can automatically describe all aspects of the management beans using implicit defaults. These default values can easily be overridden as we'll see in this in the next section.
576
577 The simplest way to export a POJO or POGO is listed below.
578
579 [source,groovy]
580 ----
581 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=implicit_export,indent=0]
582 ----
583
584 **What this does:**
585
586 - First, the **JmxBuilder.export() node will export** an MBean to the MBeanServer representing **the declared POJO** instance.
587 - The builder will **generate a default ObjectName** for the MBean and all other MBean descriptor information.
588 - **JmxBuilder will automatically export** all declared **attributes** (MBean getter/setters), **constructors**, and **operations** on the instance.
589 - The exported **attributes** will have **read-only** visibility.
590
591 Remember, **JmxBuilder.export() returns an array of GroovyMBean[] objects** for all exported instances. So, once you call JmxBuilder.export(), **you have immediate access to the underlying MBean proxy** (via GroovyMBean).
592
593 ====== JConsole view of Exported Bean
594
595 image:assets/img/jconsole-implicit-export.png[]
596
597 ==== JmxBuilder.bean() Syntax
598
599 The JmxBuilder.bean() node supports an extensive set of descriptors to describe your bean for management. The JMX MBeanServer uses these descriptors to expose meta data about the bean exposed for management.
600
601 ----
602 jmx.export {
603 bean(
604 target:bean instance,
605 name:ObjectName,
606 desc:"...",
607 attributes:"*",
608 attributes:[]
609 attributes:[ "AttrubuteName1","AttributeName2",...,"AttributeName_n" ]
610 attributes:[
611 "AttributeName":"*",
612 "AttributeName":[
613 desc:"...",
614 defaultValue:value,
615 writable:true|false,
616 editable:true|false,
617 onChange:{event-> // event handler}
618 ]
619 ],
620
621 constructors:"*",
622 constructors:[
623 "Constructor Name":[],
624 "Constructor Name":[ "ParamType1","ParamType2,...,ParamType_n" ],
625 "Constructor Name":[
626 desc:"...",
627 params:[
628 "ParamType1":"*",
629 "ParamType2":[desc:"...", name:"..."],...,
630 "ParamType_n":[desc:"...", name:"..."]
631 ]
632 ]
633 ],
634
635 operations:"*",
636 operations:[ "OperationName1", "OperationName2",...,"OperationNameN" ],
637 operations:[
638 "OperationName1":"*",
639 "OperationName2":[ "type1","type2,"type3" ]
640 "OperationName3":[
641 desc:"...",
642 params:[
643 "ParamType1":"*"
644 "ParamType2":[desc:"...", name:"..."],...,
645 "ParamType_n":[desc:"...", name:"..."]
646 ],
647 onInvoked:{event-> JmxBuilder.send(event:"", to:"")}
648 ]
649 ],
650
651 listeners:[
652 "ListenerName1":[event: "...", from:ObjectName, call:{event->}],
653 "ListenerName2":[event: "...", from:ObjectName, call:&methodPointer]
654 ]
655
656 )
657 }
658 ----
659
660 Instead of describing the entire node, the following section explore each attribute separately.
661
662 ==== Bean() Node - Specifying MBean ObjectName
663
664 Using the bean() node descriptors, you can specify your own MBean ObjectName.
665
666 [source,groovy]
667 ----
668 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=using_bean,indent=0]
669 ----
670
671 The ObjectName can be specified as a String or an instance of the ObjectName.
672
673 === Bean() Node - Attribute Export
674
675 JMX attributes are the setters and getters on the underlying bean. The JmxBuilder.bean() node provides several ways to flexibly describe and export MBean attributes. You can combine them however you want to achieve any level of attribute visibility. Let's take a look.
676
677 ==== Export All Attributes with Wildcard "*"
678
679 The following code snippet **will describe and export all attributes** on the bean as read-only. **JmxBuilder will use default values** to describe the attributes that exported for management.
680
681 [source,groovy]
682 ----
683 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_all_attributes,indent=0]
684 ----
685
686 ==== Export Attribute List
687
688 JmxBuilder will let you specify a list of attributes to export.
689
690 [source,groovy]
691 ----
692 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_attribute_list,indent=0]
693 ----
694
695 In the snippet above, **only the "Resource" and "RequestCount" attributes will be exported**. Again, since no descriptors are provided, **JmxBuilder will use sensible defaults** to describe the exported attributes.
696
697 ==== Export Attribute with Explicit Descriptors
698
699 One of the strengths of JmxBuilder is its flexibility in describing MBean. With the builder you can describe all aspects of the MBeans attribute that you want to export to the MBeanServer (see syntax above).
700
701 [source,groovy]
702 ----
703 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_attribute_with_explicit_descriptors,indent=0]
704 ----
705
706 In the snippet above, attribute **"Resource" is fully-described** using all supported descriptors (i.e. desc, readable, writable, defaultValue) for a JMX attribute. However, we use the wildcard to describe attribute **RequestCount** and it will be exported and described using defaults.
707
708 === Bean() Node - Constructor Export
709
710 JmxBuilder **supports the explicit description and export of constructors** defined in the underlying bean. There are several options available when exporting constructors. You can combine them however you want to achieve the desired level of manageability.
711
712 ==== Export all Constructors with "*"
713
714 You can use the builder's special '""' **notation to *export all constructors** declared on the underlying bean. The builder will use default values to describe the MBean constructors.
715
716 [source,groovy]
717 ----
718 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_all_constructors,indent=0]
719 ----
720
721 ==== Export Constructors using Parameter Descriptor
722
723 JmxBuilder lets you **target specific constructor** to export **by describing the parameter signature**. This is useful when you have several constructors with different parameter signature and you want to export specific constructors.
724
725 [source,groovy]
726 ----
727 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_constructors_using_parameter_descriptor,indent=0]
728 ----
729
730 Here, JmxBuilder will **export a constructor that takes one parameter of type "Object"**. Again, JmxBuilder will use default values to fill in the description of the constructor and the parameters.
731
732 ==== Export Constructor with Explicit Descriptors
733
734 JmxBuilder allows you to **fully-describe** the constructor that you want to target for export (see syntax above).
735
736 [source,groovy]
737 ----
738 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_constructor_with_explicit_descriptors,indent=0]
739 ----
740
741 In the code above, JmxBuilder will target a constructor that takes one parameter for export to the MBeanServer. Notice how the constructor can be fully-described using all optional descriptor keys including parameter descriptors.
742
743 === Bean() Node - Operation Export
744
745 Similar to constructors, JmxBuilder supports the description and export of MBean operations using a flexible notation (see above for syntax). You can combine these notations however you want to achieve the level of operation manageability desired.
746
747 ==== Export All Operations with "*"
748
749 You can use the builder's special '""'' **notation to *export all operations** defined on the bean to be exposed for management. The builder will use default descriptor values for the operations being exported.
750
751 [source,groovy]
752 ----
753 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_all_operations,indent=0]
754 ----
755
756 In this snippet, JmxBuilder will **export all bean operations** and will use default values to describe them in the MBeanServer.
757
758 ==== Export Operation List
759
760 JmxBuilder has a shorthand notation that lets you quickly target operations to be exported by providing a list of methods to export.
761
762 [source,groovy]
763 ----
764 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_operation_list,indent=0]
765 ----
766
767 In the snippet above, the **builder will only export methods start() and stop()**. All other methods will be ignored. JmxBuilder will use default descriptor values to describe the operations being exported.
768
769 ==== Export Operations by Signature
770
771 Using JmxBuilder, you can target methods to export for management using the methods's parameter signature. This is useful when you want to distinguish methods with the same name that you want to export (i.e. stop() instead of stop(boolean)).
772
773 [source,groovy]
774 ----
775 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_operations_by_signature,indent=0]
776 ----
777
778 In the snippet above, JmxBuilder would **select method makeRequest(String)** to be exported instead of the other version makeRequest() which takes no parameter. In this shorthand context, the signature is specified as a list of type (i.e. "String").
779
780 ==== Export Operations with Explicit Descriptors
781
782 JmxBuilder supports detailed descriptors for bean operations. You can supply deep descriptor info about any operation on your bean including a name, description, method parameters, parameter type, and parameter description.
783
784 [source,groovy]
785 ----
786 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=export_operations_with_explicit_descriptors,indent=0]
787 ----
788
789 The snippet above shows all of the ways JmxBuilder allows you to describe an operation targeted for management:
790
791 - Operations **start() and stop()** are described by the "desc" key (this is enough since there are no params).
792 - In operation **setResource()** uses of a shorthand version of **params**: to describe the parameters for the method.
793 - **makeRequest()** uses the the extended descriptor syntax to describe all aspects of the operation.
794
795 === Embedding Descriptor
796
797 JmxBuilder supports the ability to **embed descriptors directly in your Groovy class**. So, instead of wrapping your description around the declared object (as we've seen here), you can embed your JMX descriptors directly in your class.
798
799 **RequestControllerGroovy**
800
801 [source,groovy]
802 ----
803 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=embedding_descriptor,indent=0]
804 ----
805
806 There are two things going on in the code above:
807
808 - Groovy class RequestControllerGroovy is defined and includes a **static descriptor** member. That member is used to declare a JmxBuilder descriptor to describe member of the class targeted for JMX export.
809 - The second part of the code shows how to use JmxBuilder to export that class for management.
810
811 === Timer Export
812
813 JMX standards mandate that the implementation of the API makes available a timer service. Since JMX is a component-based architecture, timers provide an excellent signalling mechanism to communicate to registered listener components in the MBeanServer. JmxBuilder supports the creation and export of timers using the same easy syntax we've seen so far.
814
815 ==== Timer Node Syntax
816
817 ----
818 timer(
819 name:ObjectName,
820 event:"...",
821 message:"...",
822 data:dataValue
823 startDate:"now"|dateValue
824 period:"99d"|"99h"|"99m"|"99s"|99
825 occurrences:long
826 )
827 ----
828
829 The timer() node supports several attributes:
830
831 - **name**: - Required The qualified JMX ObjectName instance (or String) for the timer.
832 - **event**: - The JMX event type string that will be broadcast with every timing signal (default **"jmx.builder.event"**).
833 - **message**: - An optional string value that can be sent to listeners.
834 - **data**: - An optional object that can be sent to listeners of timing signal.
835 - **startDate**: - When to start timer. Set of valid values [ "now", date object ]. Default is "now"
836 - **period**: - A timer's period expressed as either a number of millisecond or time unit (day, hour, minute, second). See description below.
837 - **occurrences**: - A number indicating the number of time to repeat timer. Default is forever.
838
839 ==== Exporting a Timer
840
841 [source,groovy]
842 ----
843 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=exporting_timer,indent=0]
844 ----
845
846 This snippet above **describes, creates, and exports a standard JMX Timer** component. Here, the **timer()** node **returns a GroovyMBean** that represents the registered timer MBean in the MBeanServer.
847
848 An **alternative way of exporting timers** is within the JmxBuilder.export() node.
849
850 [source,groovy]
851 ----
852 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=exporting_timer_beans,indent=0]
853 ----
854
855 ==== Timer Period
856
857 The **timer() node supports a flexible notation** for specifying the **timer period values**. You can specify the time in second, minutes, hour, and day. The default is millisecond.
858
859 - timer(**period: 100**) = 100 millisecond
860 - timer(**period: "1s"**) = 1 second
861 - timer(**period: "1m"**) = 1 minute
862 - timer(**period: "1h"**) = 1 hour
863 - timer(**period: "1d"**) = 1 day
864
865 The node will automatically translate.
866
867 === JmxBuilder and Events
868
869 An integral part of **JMX** is its **event model**. Registered management beans can **communicate with each other by broadcasting events** on the MBeanServer's event bus. **JmxBuilder provides several ways to easily listen and react to events** broadcasted on the MBeanServer's event bus. Developers can **capture any event on the bus or throw their own** to be consumed by other components registered on the MBeanServer.
870
871 ==== Event Handling Closures
872
873 JmxBuilder leverages Groovy's use of closures to provide simple, yet elegant, mean of reacting to JMX events. JmxBuilder supports two closure signatures:
874
875 ===== Parameterless
876
877 [source,groovy]
878 ----
879 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=event_handling_closures,indent=0]
880 ----
881
882 JmxBuilder executes the closure and passes no information about the event that was captured on the bus.
883
884 ===== With Event Parameter
885
886 [source,groovy]
887 ----
888 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=event_handling_closures_event,indent=0]
889 ----
890
891 JmxBuilder will pass an **"event" object to the closure** using this format. The event object contains information about the event was intercepted so that it can be handled by the handler. The parameter will contain different set of info depending on the event that was captured.
892
893 ==== Handling Attribute onChange Event
894
895 When describing attributes (see bean() node section above), you can **provide a closure (or method pointer) for callback to be executed when the value of the attribute is updated** on the exported MBean. This gives developers an opportunity to listen to and react to state changes on the MBean.
896
897 [source,groovy]
898 ----
899 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=handling_attribute_onchange_event,indent=0]
900 ----
901
902 The sample snippet above shows how to **specify an "onChange" callback closure** when describing MBean attributes. In this sample code, whenever attribute "Resource" is updated via the exported MBean, the **onChange event will be executed**.
903
904 ==== Attribute onChange Event Object
905
906 When handling the attribute onChange event, the handler closure will receive an event object with the following info:
907
908 - event.**oldValue** - the previous attribute value before the change event.
909 - event.**newValue** - the new value of the attribute after the change.
910 - event.**attribute** - the name of the attribute on which the event occurred.
911 - event.**attributeType** - the data type of the attribute that causes the event.
912 - event.**sequenceNumber** - a numeric value representing the sequence number of event.
913 - event.**timeStamp** - a time stamp for the event occurrence.
914
915 ==== Handling Operation onCall Event
916
917 Similar to mbean attributes, JmxBuilder affords developers the **ability to listen for operation invocation** on an MBean registered in the MBeaServer. JmxBuilder accepts a **callback closure that will be executed after the MBean method has invoked**.
918
919 [source,groovy]
920 ----
921 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=event_handler,indent=0]
922 ----
923
924 [source,groovy]
925 ----
926 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=event_handler_usage,indent=0]
927 ----
928
929 The snippet above **shows how to declare an "onCall" closure to be used as listener** when operation "start()" is invoked on the MBean. This sample **uses the method pointer syntax** to illustrate the versatility of JmxBuilder.
930
931 ==== Operation onCall Event Object
932
933 When handling the operation onCall event, the callback closure will receive an event object with the following info:
934
935 - event.**event** - the event type string that was broadcasted.
936 - event.**source** - The object on which the method was invoked.
937 - event.**data** - the data type of the attribute that causes the event.
938 - event.**sequenceNumber** - a numeric value representing the sequence number of event.
939 - event.**timeStamp** - a time stamp for the event occurrence.
940
941 === Listener MBean
942
943 When you export an MBean with the bean() node, you can define events the MBean can listen and react to. The bean() node provides a "listeners:" attribute that lets you define event listeners that your bean can react to.
944
945 [source,groovy]
946 ----
947 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=listener_mbean,indent=0]
948 ----
949
950 In the sample above, we see the **syntax for adding listeners to an exported MBean**.
951
952 - Fist, a **timer is exported** and started.
953 - Then an **MBean is declared that will listen to the timer** event and do something meaningful.
954 - The **"heartbeat:"** name is arbitrary and has no correlation to the timer declared above.
955 - The **source** of the event **is specified using the "from:" attribute**.
956
957 You can also specify an **event type** you are interested in receiving from a broadcaster (since a broadcaster can be emitting multiple events).
958
959 ==== Listening to JMX Events
960
961 In some cases, you will want to create stand-alone event listeners (not attached to exported MBeans). JmxBuilder provides the Listener() node to let you create JMX listeners that can listen to MBeanServer events. This is useful when creating JMX client applications to monitor/manage JMX agents on remote JMX MBeanServers.
962
963 ==== Listener Node Syntax
964
965 ----
966 jmx.listener(
967 event: "...",
968 from: "object name" | ObjectName,
969 call: { event-> }
970 )
971 ----
972
973 Here is the description of the **listener()** node attributes:
974
975 - event: An optional string that identifies the JMX event type to listen for.
976 - from (required): The JMX ObjectName of the component to listen to. This can be specified as a string or an instance of ObjectName
977 - call: The closure to execute when the event is captured. This can also be specified as a Groovy method pointer.
978
979 Here is an example of JmxBuilder's listener node:
980
981 [source,groovy]
982 ----
983 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=jmxbuilders_listener,indent=0]
984 ----
985
986 This example shows how you can use a stand alone listener (outside of an MBean export). Here, we **export a timer with a 1 second** resolution. Then, we specify a listener to that timer that will print "beep" every second.
987
988 === Emitting JMX Events
989
990 JmxBuilder provides the **tools needed to broadcast your own events** on the MBeanServer's event bus. There are no restrictions on the event type you can broadcast. You simply **declare your emitter** and the event type that you want to send, then **broadcast your event** at any time. Any registered component in the MBeanServer can register themselves to listen to your events.
991
992 ==== Emitter Syntax
993
994 ----
995 jmx.emitter(name:"Object:Name", event:"type")
996 ----
997
998 The attributes for the node Emitter() can be summarized as follows:
999
1000 - name: an optional JMX ObjectName used to register your emitter in the MBeanServer. Default is jmx.builder:type=Emitter,name=Emitter@OBJECT_HASH_VALUE
1001 - event: an option string value that describes the JMX event type. Default is **"jmx.builder.event.emitter"**.
1002
1003 ==== Declare the Emitter
1004
1005 [source,groovy]
1006 ----
1007 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=declare_emitter,indent=0]
1008 ----
1009
1010 The snippet **declares the emitter using implicit descriptor syntax**. JmxBuilder will do the followings:
1011
1012 - Create and register an emitter MBean with a default ObjectName.
1013 - Setup a **default event type** with value **"jmx.builder.event.emitter"**.
1014 - Return a GroovyMBean representing the emitter.
1015
1016 As with other nodes in the builder, **you can override all keys in the emitter() node**. You can specify the **ObjectName** and the **event type**.
1017
1018 ==== Broadcast Event
1019
1020 Once you have declared your emitter, you can broadcast your event.
1021
1022 [source,groovy]
1023 ----
1024 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=emitter_broadcast_event,indent=0]
1025 ----
1026
1027 The sample above shows the **emitter sending an event**, once it has been declared. Any JMX component registered in the MBeanServer can register to receive message from this emitter.
1028
1029 ==== Sending Event Objects
1030
1031 You can optionally pass data to the receiver when you send the message.
1032
1033 [source,groovy]
1034 ----
1035 include::{rootProjectDir}/subprojects/groovy-jmx/src/spec/test/JmxTest.groovy[tags=emitter_broadcast_event_with_objects,indent=0]
1036 ----
1037
1038 If you use an **event listener closure (see above) that accepts a parameter**, you can access that value.
1039
1040 == Further JMX Information
1041
1042 - http://www.ddj.com/dept/java/184406481?pgno=1[Monitoring the Java Virtual Machine]
1043 - http://buttso.blogspot.com/2006/05/using-groovy-for-system-management.html[Using Groovy for System Management]
1044 - https://blogs.oracle.com/sundararajan/entry/groovier_jconsole[Groovier jconsole!]
1045 - http://jmesnil.net/weblog/2007/05/23/jmx-scripts-with-eclipse-monkey[JMX Scripts with Eclipse Monkey]
1046 - http://activemq.apache.org/jmx.html[Using JMX to monitor Apache ActiveMQ]