Tuesday, 17 May 2011

Byteman Demo at JUDCon

I just got back online after a couple of weeks holiday following the Byteman talk at JUDCon in Boston. JUDCon is the part of Red Hat's JBossWorld/Summit conference where JBoss/Java tecchies get together to present all the neat things they have invented over the last 6 months/year. So, of course, one of the neat things on the agenda was Byteman.

The presentation was very well received and there were lots of interesting questions during and after the talk. A pdf is available from the Byteman
docs page. The presentation included a small demo which showed some Byteman rules being injected into a simple Quartz timer bean stolen from one the JBoss EAP5 EJB tutorial. Like all demos it is slightly artificial but it does show just how simple it is to run up Byteman and introduce timing constraints into a threaded application. Since the demo was not recorded I'll present the code example here and show the demo output for those who missed the talk.

The Demo Code

The example code used in the demo displays the Quartz timer capability provided as part of the standard JBoss app server release. The original example was coded for EAP5 but I actually ran it quite happily on AS 6.
To avoid introducing too much clutter into the demo output I modified the example code so that only the annotated Quartz timer bean is deployed. Here is the definition I used for the bean:

 @MessageDriven(activationConfig =
{@ActivationConfigProperty(propertyName =
"cronTrigger", propertyValue = "0/5 * * * * ?")})
@ResourceAdapter("quartz-ra.rar")
public class AnnotatedQuartzMDBBean implements Job
{
private static final Logger log =
Logger.getLogger(AnnotatedQuartzMDBBean.class);
public void
execute(JobExecutionContext jobExecutionContext)
throws JobExecutionException
{
AnnotatedQuartzMDBBean.log.info("************** here in annotated!!!!");
}
}
The bean is pretty simple. It just prints a message saying here I am when the callback is triggered. The annotation declares it as a message driven bean triggered by the Quartz timer and the cron trigger property requests that the callback is triggered every 5 seconds on a 5 second boundary.

Running The Demo

The bean is deployed by starting up JBoss AS and then running 'ant' in subdirectory
jca_inflow_quartz of the downloaded tutorial code. Here's the output you get when the bean is deployed into JBoss AS 6.

 [adinn@localhost adinn]$ $JBOSS_HOME/bin/run.sh
=========================================================================
JBoss Bootstrap Environment
JBOSS_HOME: /home/adinn/jboss/jbossas/jboss-6.0.0.Final
. . .
[6.0.0.Final "Neo"] Started in 22s:617ms
06:12:27,678 INFO [org.jboss.ejb3.deployers.Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@1809001556{vfs:///ssd/home/adinn/jboss/jbossas/jboss-6.0.0.Final/server/default/deploy/jboss-ejb3-tutorial-jca_inflow_quartz.jar}
. . .
06:12:27,748 INFO [org.jboss.ejb3.deployers.JBossASKernel] Added bean(jboss.j2ee:jar=jboss-ejb3-tutorial-jca_inflow_quartz.jar,name=AnnotatedQuartzMDBBean,service=EJB3) to KernelDeployment of: jboss-ejb3-tutorial-jca_inflow_quartz.jar
06:12:27,800 INFO [org.jboss.ejb3.EJBContainer] STARTED EJB: org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean ejbName: AnnotatedQuartzMDBBean
06:12:30,083 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
06:12:35,010 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
06:12:40,004 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
06:12:45,006 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
06:12:50,004 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
06:12:52,923 INFO [org.jboss.ejb3.EJBContainer] STOPPED EJB: org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean ejbName: AnnotatedQuartzMDBBean
06:12:52,948 INFO [org.jboss.ejb3.instantiator.deployer.BeanInstantiatorDeployerBase] Uninstalled org.jboss.ejb3.instantiator.impl.Ejb31SpecBeanInstantiator@2f385f78 from MC at org.jboss.ejb.bean.instantiator/jboss-ejb3-tutorial-jca_inflow_quartz/jboss-ejb3-tutorial-jca_inflow_quartz/AnnotatedQuartzMDBBean
As you can see the bean callback is executed every 5 seconds as expected.

The Byteman Rules

The Byteman demo uses two rules defined as follows:


RULE set up rendezvous
CLASS AnnotatedQuartzMDBBean
METHOD <init>
AT EXIT
IF NOT isRendezvous("quartz", 3)
DO createRendezvous("quartz", 3, true)
ENDRULE

RULE delay quartz bean
CLASS AnnotatedQuartzMDBBean
METHOD execute
AT ENTRY
IF isRendezvous("quartz", 3)
DO traceln("**** enter quartz rendezvous ");
traceln("*** exit " + rendezvous("quartz"));
ENDRULE

The first rule is attached to the constructor method for the timer bean class (<init> is the internal name used by the JVM for a constructor method). It is triggered when an instance of the timer bean class is created just before the constructor method returns. The rule uses the standard Byteman built-in operation createRendezvous to create a rendezvous identified using the String "quartz". The call to isRendezvous in the condition ensures that only one rendezvous is ever created.

A rendezvous is used to introduce a synchronization point for some given number of threads (a rendezvous is also commonly referred to as a barrier). Any thread which attempts to enter the rendezvous may be suspended until the required number of threads has arrived. Once the required number of threads have entered all of them are released and allowed to continue past the rendezvous call. In this case the rendezvous count is supplied by the second argument, 3.

Normally when a rendezvous has been met by all the required threads it gets deleted. Any thread which subsequently tries to enter the rendezvous just continues without suspending. The 3rd boolean argument true supplied in the create call makes this a repeatable rendezvous. So, after 3 threads arrive the rendezvous is reinstated allowing a further 3 threads to meet and so on.

The second rule is injected at the start of the timer bean callback method execute and it is this rule which makes the timer threads enter the rendezvous. The condition ensures the rule only fires if the rendezvous is present. The first statement in the rule action is a call to builtin operation traceln which prints a message to System.out saying the thread is entering the rendezvous. The second call to traceln prints a String created by pasting together the prefix "exit *** " and the integer value returned by calling built-in method rendezvous. This printout will not be executed until the call to rendezvous returns.

So, when the first timer callback is created the timer thread will print the enter message, call rendezvous and suspend. 5 seconds later Quartz creates a new thread to run the second callback and this also prints the enter message then calls rendezvous and suspends. 5 seconds later the 3rd callback thread prints its enter message and calls rendezvous. All 3 threads are released and they all print the exit message. The return value is either 0, 1 or 2 depending upon which thread arrived in which order. All 3 threads go on to execute the body of the callback and exit. 5 seconds later the whole cycle starts again.

Running the Demo With Byteman

This time after booting up AS 6 we load the agent into the app server and then load the rule script. The rules need to be loaded before the quartz bean is created so that the <init> rule is in place before the timer bean is created. The agent can be loaded on the JVM command line but it is easier to start up AS 6 and then load the agent once the app server is running.


 [adinn@localhost jca_inflow_quartz]$ ${BYTEMAN_HOME}/bin/bminstall.sh org.jboss.Main
[adinn@localhost jca_inflow_quartz]$

The script bminstall.sh uploads the byteman agent into a running JVM. You can specify which JVM by supplying as argument either its process id or, as in this case, the name of the application class providing the JVM entry point.

The agent can now be talked to using script bmsubmit.sh. If we provide it with the name of the rule script file as an argument it will upload rules into the JVM ready for injection into the classes mentioned in the rules.

 [adinn@localhost jca_inflow_quartz]$ ${BYTEMAN_HOME}/bin/bmsubmit.sh rules.btm
install rule set up rendezvous
install rule delay quartz bean
[adinn@localhost jca_inflow_quartz]$

If we now execute bmsubmit.sh with no arguments it will show us that the rules are loaded but not yet injected. This is because the classes they apply to have not yet been deployed It is possible to install rules into classes which have already been loaded into the JVM but in this case we want to trigger the <init> rule when the timer bean is created. That will happen during loading so we need to install the rules before deploying the application.

 [adinn@localhost jca_inflow_quartz]$ ${BYTEMAN_HOME}/bin/bmsubmit.sh
# File rules.btm line 13
RULE delay quartz bean
CLASS AnnotatedQuartzMDBBean
METHOD execute
AT ENTRY
IF isRendezvous("quartz", 3)
DO traceln("**** enter quartz rendezvous ");
traceln("*** exit " + rendezvous("quartz"));
ENDRULE
# File rules.btm line 5
RULE set up rendezvous
CLASS AnnotatedQuartzMDBBean
METHOD <init>
AT EXIT
IF NOT isRendezvous("quartz", 3)
DO createRendezvous("quartz", 3, true)
ENDRULE
[adinn@localhost jca_inflow_quartz]$

The listing from the agent shows that the rules are in place. When we deploy the app they get injected into the bean code as it is loaded. The rendezvous gets created and the subsequent timer thread output is delayed until a group of 3 threads have arrived at the rendezvous. The next 3 threads are also grouped and so on.

 07:00:44,028 INFO [org.jboss.bootstrap.impl.base.server.AbstractServer] JBossAS [6.0.0.Final "Neo"] Started in 23s:706ms
07:00:59,209 INFO [org.jboss.ejb3.deployers.Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@1865896779{vfs:///ssd/home/adinn/jboss/jbossas/jboss-6.0.0.Final/server/default/deploy/jboss-ejb3-tutorial-jca_inflow_quartz.jar}
. . .
07:00:59,334 INFO [org.jboss.ejb3.EJBContainer] STARTED EJB: org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean ejbName: AnnotatedQuartzMDBBean
07:01:00,192 INFO [STDOUT] **** enter quartz rendezvous
07:01:05,018 INFO [STDOUT] **** enter quartz rendezvous
07:01:10,006 INFO [STDOUT] **** enter quartz rendezvous
07:01:10,007 INFO [STDOUT] *** exit 0
07:01:10,007 INFO [STDOUT] *** exit 2
07:01:10,007 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:10,007 INFO [STDOUT] *** exit 1
07:01:10,007 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:10,007 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:15,004 INFO [STDOUT] **** enter quartz rendezvous
07:01:20,004 INFO [STDOUT] **** enter quartz rendezvous
07:01:25,004 INFO [STDOUT] **** enter quartz rendezvous
07:01:25,005 INFO [STDOUT] *** exit 1
07:01:25,005 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:25,005 INFO [STDOUT] *** exit 2
07:01:25,006 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:25,006 INFO [STDOUT] *** exit 0
07:01:25,008 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!

At this point if we run the submit script with no arguments we can see that the rules have been injected into the target methods. The listing now shows the class and method the rule was injected into and the classloader which loaded the rule. It also indicates that the rule was injected, type-checked and compiled correctly.
 [adinn@localhost jca_inflow_quartz]$ bmsubmit
# File rules.btm line 13
RULE delay quartz bean
CLASS AnnotatedQuartzMDBBean
METHOD execute
AT ENTRY
IF isRendezvous("quartz", 3)
DO traceln("**** enter quartz rendezvous ");
traceln("*** exit " + rendezvous("quartz"));
ENDRULE
Transformed in:
loader: BaseClassLoader@25f4cf3c{vfs:///ssd/home/adinn/jboss/jbossas/jboss-6.0.0.Final/server/default/deploy/jboss-ejb3-tutorial-jca_inflow_quartz.jar}
trigger method: org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean.execute(org.quartz.JobExecutionContext) void
compiled successfully
# File rules.btm line 5
RULE set up rendezvous
CLASS AnnotatedQuartzMDBBean
METHOD <init>
AT EXIT
IF NOT isRendezvous("quartz", 3)
DO createRendezvous("quartz", 3, true)
ENDRULE
Transformed in:
loader: BaseClassLoader@25f4cf3c{vfs:///ssd/home/adinn/jboss/jbossas/jboss-6.0.0.Final/server/default/deploy/jboss-ejb3-tutorial-jca_inflow_quartz.jar}
trigger method: org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean.<init>() void
compiled successfully
[adinn@localhost jca_inflow_quartz]$

We can run the script again with the -u flag to remove the rules.
 [adinn@localhost jca_inflow_quartz]$ bmsubmit -u
uninstall RULE delay quartz bean
uninstall RULE set up rendezvous
[adinn@localhost jca_inflow_quartz]$

We now see that the injected code is removed, the timer bean reverts to its normal behaviour and once again the messages start being printed every 5 seconds.
 07:01:30,010 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:35,005 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:40,006 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!
07:01:45,005 INFO [org.jboss.tutorial.quartz.bean.AnnotatedQuartzMDBBean] ************** here in annotated!!!!

Wednesday, 2 February 2011

Byteman Release 1.5.1 is now available

The Byteman 1.5.1 patch release is now available from the JBoss maven
repo
and from the Byteman project download page.

1.5.1 upgrades the BMUnit contrib package to integrate Byteman into both
the JUnit and (new) TestNG test frameworks. The upgrade also simplifies
the deployment process. In particular, this means that you can now plug
Byteman rules into your maven Surefire tests simply by adding the
Byteman jars as test dependencies. So, now there is no excuse for not
using fault injection in your tests.

Full details are in the BMUnit package README.

Monday, 17 January 2011

Byteman 1.5.0 JUnit Integration Makes Fault Injection Simple

Byteman 1.5.0 has just been released and the major new feature is a really nice user contributed package, BMUnit, which provides integration with JUnit. It makes fault injection testing and execution tracing unbelievably simple.

BMUnit provides annotations which you use to identify the Byteman rules needed for each of your JUnit tests. Annotations attached to a test class specify rules which apply to all test methods. Annotations attached to a method identify rules which only apply for that specific test.

The BMUnit test runner ensures the Byteman agent is installed in the JUnit JVM before any testing starts. It automatically loads all required rules into the JVM before running a test and unloads them when they are no longer needed. All you need to do to use BMUnit is is attach an @RunWith(BMUnitRunner.class) annotation to your test class.

Here's a simple example to show you how quick and easy BMUnit is to use
@RunWith(BMUnitRunner.class)
public class FileOpenTest {
@BMRule(name="throw security exception",
targetClass="FileInputStream",
targetMethod="<init>(File)",
condition="$1.getName().equals\"badname.txt\")"
action="throw new SecurityException(\"bad name!\")")
@Test
public void testSecurityException() {
MyTestClass myTestObj = new MyTestClass();
myTestObj.processFile("badname.txt");
}
. . .
}
In this example a single rule is provided inline in the test program itself, using a @BMRule annotation attached to test method testSecurityException. The rule is triggered on entry to the constructor FileInputStream(File). The condition restricts the rule to firing only when the File argument has name "badname.txt" (which we have cunningly arranged to be the name supplied in the test call). When the rule does fire the action causes a SecurityException to be thrown from the constructor.

So, when this unit test is run the runner class, BMUnitRunner, will install the agent into the test JVM then load the rule defined in the annotation into the agent database, injecting it into the constructor method. When a file open is attempted under the call to myTestObj.processFile() the rule is triggered, ensuring that the test class, MyTestClass, receives a SecurityException.

Clearly, it would be more interesting if we could be sure that the security exception was handled correctly. A few more rules can be used to check that the correct handler code has been called or, if not, force a test failure. In this case we will place the rules in a separate script to avoid adding too much clutter to the test class. First we change the annotation to @BMScript, pointing the BMUnit test runner at a rule script file.

@RunWith(BMUnitRunner.class)
public class FileOpenTest {
@BMScript(value="security-exception", dir="scripts")
@Test
public void testSecurityException() {
MyTestClass myTestObj = new MyTestClass();
myTestObj.processFile("badname.txt");
}
. . .
}
The BMScript annotation identifies the name and location of the script file. Locations with a non-absolute path are interpreted relative to the working directory of the test JVM. The script file name is looked for using either a ".btm" or ".txt" extension. So, let's assume we have placed the following rules in a file called "security-exception.btm" located in subdirectory "scripts".

RULE throw security exception 
CLASS FileInputStream
METHOD <init>(File)",
IF "$1.getName().equals\"badname.txt\"
DO clear("handled");
throw new SecurityException("bad name!")
ENDRULE
RULE track handler call,
CLASS MyTestClass
METHOD handle(SecurityException)
IF true
DO flag("handled")
ENDRULE
RULE ensure handler call
CLASS MyTestClass
METHOD processFile(File)
AT RETURN
IF !flagged("handled")
DO throw new RuntimeException("unhandled security exception")
ENDRULE
The first rule is essentially the same as the one we had in the @BMRule annotation. The only difference is that it clears any flag associated with keyword "handled". The second rule is triggered when method handle(SecurityException) of class MyTestClass gets called. It fires unconditionally, setting a flag labelled by the keyword string "handled". We will assume that calling this method is enough to guarantee that the test has passed. The third rule is triggered when method processFile(File) returns normally. If the "handled" flag has not been set it throws an exception, causing the unit test to fail. If processFile(File) returns abnormally this rule will be bypassed but the exception will be detected by JUnit, also indicating a failure.

Of course, we could have used the BMScript and BMRule annotations in combination, defining, say, the first rule inline and the second and third rule in the script. We can also specify more than one rule or more than one script by using the annotations @BMRules and @BMScripts. The values of these annotations are an array of, respectively, @BMRule or @BMScript annotations. For example
@RunWith(BMUnitRunner.class)
public class FileOpenTest {
@BMRules( {
@BMRule(name = "throw security exception", ...)
@BMRule(name = "track handler call", ...)
})
@Test
public void testSecurityException() {
MyTestClass myTestObj = new MyTestClass();
myTestObj.processFile("badname.txt");
}
. . .
}
Full details of how to use the package are included in the README located in the contrib/bmunit subdirectory of the 1.5.0 release.

Wednesday, 22 December 2010

Meet Byteman at JBoss Asylum

Not to be confused with Arkham Asylum, JBoss Community Asylum is a podcast about, for and by the JBoss Community. It provides news about what the JBoss community is up, including interviews with JBoss developers. The latest sensational podcast reveals the identity of the man behind the mask, Byteman lead developer Andrew Dinn. If you want to hear how Byteman chases down and banishes evil bugs or find out how Byteman was conceived and grew into one of software's toughest enforcers then tune in to the JBoss Asylum Byteman Christmas Special at

http://in.relation.to/Bloggers/Podcast16BytemanBegins

Thursday, 25 November 2010

Byteman 1.4.1 Now Available For Download

Byteman patch release 1.4.1 is now available at the project download page or from the JBoss maven repository. The release patches a few important bugs and omissions including:
  • a regression introduced into AT LINE triggers has been corrected
  • assignment of arrays and creation of arrays has been implemented
    e.g. you can now write things like BIND strArray = new String[2] and DO strArray[0] = "foo"
The release also provides a couple of new features:
  • trigger points can now include local or parameter variable accesses
    e.g. the rule location can now be something like AT READ $loopvar where $loopvar identifies a local variable or AFTER WRITE $1 where $1 identifies the first method parameter
  • AFTER INVOKE rules can now read and reassign $!, the value returned by the method invocation which triggered rule processing
    e.g. a rule injected into the trigger method after a call to myIntMethod (location AFTER INVOKE myIntMethod) might employ the condition IF $! < 0 and action DO $! = 0 to ensure that the value returned from myintMethod was never negative.
Details of all features and bug fixes are provided in the release notes. A full explanation of all new behaviour is available in the programmer's guide.

Thursday, 28 October 2010

Collecting and Displaying Runtime Statistics With Byteman

The latest 1.4.0 Byteman release includes a couple of example rule scripts in the sample directory which show off just how powerful a tool Byteman is. Both scripts use Byteman rules to count statistically important events. One of them monitors events in the JVM like Thread creates, and starts, FileStream opens etc. The other counts the number of times your application makes calls to any of the javax Transaction API methods. Well, that's not exactly very impressive is it? I mean, it's fairly easy to inject code which increments a counter, no?

The nice part is that the rules in the script automatically turn those counters into a variety of statistics then format and present the statistics in a dynamically generated MBean displayed in the JMX console. Even nicer the rules in the script control what gets counted and how it gets presented. So, if you can write a rule to count events you are interested in, either in JVM code or in your application code, then you can automatically present this data as statistics. The MBean gets installed when you load your Byteman rules. Unload the rules and the MBean gets uninstalled. Tweak the rules and reload them and you can measure different data. Ad hoc monitoring of your JVM or your app is now fully dynamic and takes just seconds.

In the rest of this blog I'm going to take a walk through how the script operates. For those who want to see the end result here is a quick look ahead at the MBean display for the JVM stats script. After that I talk about how the scripts are written. Hopefully, by the end of it you should know enough to be able to write your own counting rules and generate a statistics display for your own app. Here's the screenshot

JVMMBeanStats.txt is the script which was used to create and populate that MBean. First off let's see how it counts raw events. As one example, consider the following rule
# this rule counts Thread creates
RULE count thread creates
CLASS java.lang.Thread
METHOD <init>
AT EXIT
IF TRUE
DO debug("create thread " + $0.getName());
incrementCounter("thread creates")
ENDRULE

The rule gets injected into any constructor method of class java.lang.Thread and, since its condition is TRUE, it always fires. It uses the built-in method incrementCounter to add one to the counter identified by the String object "thread creates". Now, every thread create, whether for a java.lang.Thread or for a subclass of java.lang.Thread will end up executing one of the constructor methods and triggering this rule. So, effectively the counter tracks the number of threads created in the JVM.

Note that the rule is injected AT EXIT -- i.e. it triggers just before the method returns. This ensures that the Thread instance has been initialised before the debug statement in the rule makes a call to Thread.getName().

It is obviously relatively simple to inject Byteman rules into any JVM or application method and have them increment or decrement counters in order to track what the runtime/application is doing. Note that method incrementCounter() can be provided with an extra integer argument defining the value to be added to the counter. Method readCounter() allows the counter to be reset to zero while retrieving the current count atomically. This makes it is possible to count in many different ways e.g. by adding in the value of a method parameter or field value each time the rule is triggered.

Sometimes the location and condition of a rule need to be a little more sophisticated in order to ensure that only relevant events are counted. For example, the following rule only counts calls to run methods of Thread classes when they are entered from the VM.
# this rule counts Thread runs
RULE count thread run
CLASS ^java.lang.Thread
METHOD run()
# only count run when called from JVM i.e. when there is no caller frame
IF !callerMatches(".*")
DO debug("run thread " + $0.getName());
incrementCounter("thread runs")
ENDRULE

This rule uses the ^ notation in the CLASS clause. This means that the rule is injected down the class hierarchy i.e. not just into Thread.run() but also into any overriding implementation of run() defined by a subclass of Thread.

The condition in this rule uses the built-in operation callerMatches() to ensure that the call is made from the JVM itself (i.e. in response to a call to Thread.start()) rather than from Java code. Method callerMatches() is implemented with a variety of argument patterns; in this one the argument is a regular expression (regexp) to be matched against the name of the method which directly called the trigger method. callerMatches() returns true if the caller method name matches the regexp; if not it returns false. Here's an example of a call which would not fire the rule. In this case the caller method name would be runFooThread.
class FooThreadExecutor {
public runFooThread(FooThread fooThread) {
fooThread.run();
}
}
Now, the pattern ".*" in the Byteman rule will match any method name. So, in the example above the call returns true making the condition false. The only way callerMatches can return false when called with ".*" as an argument is if there is no caller frame in the stack when the run() method gets entered. This is precisely the situation where run() is called from the JVM as a result of some other thread calling Thread.start(). So, this rule does not count pseudo-run operations like the example above.

That's all very well as far as doing the raw counting is concerned but how do the statistics get sampled and displayed to the user? Well, there's a give away in the name of the example scripts, both of which contain the word MBean. The rules in both scripts employ a special helper class called JMXHelper which collects the raw counter data and then presents it in an MBean.

At the top of each script is a line like this
 HELPER org.jboss.byteman.sample.helper.JMXHelper
This means that all the rules in the script will use this class unless they specify their own helper by including a HELPER clause in the rule body. A rule's helper class is used to resolve built-in calls like the ones in the example rules above, incrementCounter() or debug(). Built-in calls have no target object and look like static method calls but without any package qualifier.

Helper classes do not need to implement any special interface or be annotated in any specific way. JMXHelper is just a POJO class. It can be found in the byteman-sample jar included with the Byteman release. JMXHelper inherits from Byteman's default helper class which is why the example rules are able to call the standard built-in methods. So, for example, debug(String) is a public instance method of the default helper and the call to debug("run thread " + $0.getName()) in the example rules gets executed by calling this method. Any public instance method provided by the helper can be called in the rule body as a built-in.

Actually, JMXHelper does not add any extra public methods to the set provided by the default helper class. However, what it does do is implement some public static lifecycle methods. Helper lifecycle methods get called when rules which employ the helper are installed and/or deinstalled by Byteman. Here is one of the methods on JMXHelper
public static void activated()
{
if (theHelper == null) {
theHelper = new JMXHelper(null);
theHelper.start();
}
}

This method gets run when the first rule which employs the helper class is installed into the JVM by Byteman. So, if you load one of these scripts on the java command line or if you upload the rules at runtime using the bmsubmit.sh script then this method will get called once only.

The lifecycle method assigns an instance of JMXHelper to static field theHelper and then runs the instance's start() method. The latter method starts a background thread which wakes up at regular intervals and samples the counters incremented by the rules in the script. The background thread also creates and installs a DynamicMBean into the JVM's MBean server to display the counter values.

Of course, it is possible to use the bmsubmit.sh script provided with the release to deinstall the rules which employ JMXHelper from the runtime. Once all these rules have been removed it is only appropriate to unregister the MBean and shutdown the background thread. Naturally, there is a corresponding lifecycle method which gets called when the last rule employing JMXHelper gets removed from the runtime
public static void deactivated()
{
if (theHelper != null) {
theHelper.shutdown();
theHelper = null;
}
}

Ok, so that explains how the sampling and display operates (well modulo the details of exactly how the thread and MBean get created and started/stopped but that's just bread and butter coding). The more important question is how does the background thread know which counters to sample, how often to sample them and how to display them in the MBean. It would not be much use if these values were hard-wired into class JMXHelper since that would mean that every time you wanted to collect different statistics you would need to rewrite and redeploy the class.

In fact it is perfectly possible to use Byteman rules to parameterise the behaviour of the helper and the MBean. Class JMXHelper provides three methods which are called by the background thread when it is started. A script can inject code into these methods which supplies all the information needed to configure the behaviour of the background thread and the MBean.

So, the first rule we will look at is the one which defines the sample period i.e. how long the background thread waits before waking up and checking the value of the counters used in the script. Here is the method implemented by JMXHelper
public final static long DEFAULT_PERIOD = 10000L;
private long samplePeriod()
{
return DEFAULT_PERIOD;
}

So, by default the background thread wakes up every 10,000 milliseconds i.e. every 10 seconds. The scripts override this period using the following rule which resets the sample period to 5 seconds by injecting code which returns value 5000 when the method is called.
# this rule is triggered when the periodic helper thread starts
# it returns a sample period in milliseconds for which the
# periodic helper thread sits and waits before sampling each
# of the counters and updating the MBean
RULE set period
CLASS JMXHelper
METHOD samplePeriod()
AT ENTRY
IF TRUE
DO RETURN 5000
ENDRULE

So, how about configuring the counters and the MBean display? Well, the background thread calls the following method during startup
private KeyInfo keyInfo()
{
// if the rule set does not generate a keyinfo value then we return this one to indicate
// that something is missing.
String[] keyNames = new String[1];
keyNames[0] = "No counters defined";
return new KeyInfo("Byteman Periodic Statistics", keyNames);
}

The method returns a KeyInfo object. Essentially this contains 3 lists of data. The first list identifies the names of the counters to be sampled. The second list identifies the format in which each corresponding counter value should be displayed and the third provides a descriptive label for each counter. The default implementation above creates a KeyInfo object with only one counter which, presumably, never gets incremented. The format and description take the default values.

This method is overridden by the JVMMBeanStats script as follows
# this rule is triggered when the periodic helper thread starts
# it returns a KeyInfo object identifying the stats counters
# updated by rules in this rule set
RULE return key info
CLASS JMXHelper
METHOD keyInfo()
BIND keyInfo : KeyInfo = new KeyInfo("JVM Statistics in a Dynamic MBean")
IF TRUE
DO keyInfo.addKey("thread creates", KeyInfo.KEY_TYPE_CUMULATIVE, "Thread() total calls");
keyInfo.addKey("thread runs", KeyInfo.KEY_TYPE_CUMULATIVE, "Thread.run() total calls");
...
keyInfo.addKey("thread creates", KeyInfo.KEY_TYPE_RATE, "Thread() calls per second");
keyInfo.addKey("thread runs", KeyInfo.KEY_TYPE_RATE, "Thread.run() calls per second");
...
keyInfo.addKey("class loads", KeyInfo.KEY_TYPE_MEAN, "ClassLoader.defineClass() mean calls per sample");
RETURN keyInfo
ENDRULE

The rule creates a KeyInfo object in the BINDS clause binding it to variable keyInfo. The rule action calls the addkey method repeatedly to add the name, format type and description for each of the counters updated in the rule set. Finally it returns the object identified by keyInfo to the background thread. The thread uses this object to construct a dynamic MBean populated with fields each of whose name, format, description and value is derived from each key entry and associated counter. Every time the thread wakes up it samples the value of the counters. When the MBean is refreshed the latest sampled values are used to recompute the displayed statistic.

Note that the same counter can be used more than once with a different format. So, for example, the first counter, "thread creates", is added with format CUMULATIVE and then added again later with format RATE. Format CUMULATIVE indicates that the MBean should display the last sampled value for the counter. With this format the counter is simply being presented as raw data.

By contrast format RATE means that the MBean should compute the difference between successive sample values and divide it by the sample period to compute the rate at which the counter is changing. So, if the latest sampled value for "thread creates" is 5090 and the previous sampled value was 4940 then the statistic displayed in the MBean would be (5090 - 4944) / 5.0 i.e. 29.2 Thread() calls per second.

In fact the sampling is slightly more sophisticated in order to smooth out variations which occur because of wakeup delays and overlap of application phase changes with the sample intervals. The RATE algorithm can be configured to employ up to 11 prior samples (i.e up to 10 differences) and it divides the difference by the actual time interval between samples rather than the nominal wakeup period.

The MEAN statistic provides another view of the counter data. It computes the change in the counter value across a sample period i.e. it represents how many things were counted during the period. Once again it can be based on up to 11 sample counter readings and the value is corrected to allow for the number of samples included and the variation in the sample intervals.

How is the sample set count defined? Well, that's the third method of class JMXHelper which can be overridden by a rule. It's called sampleSetSize() and it returns 5 as the default set size. It can be overridden using a rule as follows
# this rule is triggered when the periodic helper thread starts
# it returns a count for the number of samples which will be
# combined when computing counter rates or counter sample period
# means
RULE set sample set size
CLASS JMXHelper
METHOD sampleSetSize()
IF TRUE
DO RETURN 3
ENDRULE

Ok, so it's clear that JMXHelper provides a general purpose display mechanism which can be used to present any statistics which you can gather by injecting calls to incrementCounter(). How do you actually install it into a running JVM and what does the final display look like?
Well, the scripts themselves contain detailed instructions but for now I'll show you how to install the JVMMBeanStats script into a JBoss Application Server instance. In the process I'll show off another neat feature of the latest Byteman release

Normally, in order to be able to load and unload byteman rules into a JVM you need to install the Byteman agent when you start up the JVM. There is a useful script in the installed bin directory called bmjava.sh which simplifies this job in the case where you are starting your program using the java command. In most cases you simply call bmjava.sh instead of java. Unfortunately, JBoss AS wraps up the call to java inside its own startup script. This means that you have to set environment variable JAVA_OPTS to pass the -javaagent argument on the java command line. Also, the javaagent argument needs to have several options appended to it to identify the location of the byteman jar and either point Byteman at a rule script or switch on the agent listener so you can upload rules using bmsubmit.sh after the program is started.

With the 1.4.0 release you can now start up JBoss and then upload the agent once the JVM is running. This is possible on any JVM which implements the server side of the com.sun.tools.attach.VirtualMachine API. Ok, you don't actually need to know what that means but you do need to know that it has been found to work on Sun's JDK6 (naturally), OpenJDK6 and JRockit JDK6. I have not yet found an IBM JDK6 on which it does work (although the other Byteman features all appear to work fine) but I have not made a comprehensive survey of all their releases so you'll have to verify this for yourselves.

So, first off you need to start your JBoss instance by calling run.sh
 [adinn@localhost adinn]$ $JBOSS_HOME/bin/run.sh
=========================================================================
JBoss Bootstrap Environment
JBOSS_HOME: /home/adinn/jboss/jbossas/trunk/build/target/jboss-6.0.0-SNAPSHOT
JAVA: /usr/java/jdk1.6.0_21/bin/java
...
Now you need to identify the process id of the JBoss AS process
 [adinn@localhost adinn]$ jps -l
23812 org.jboss.Main
23892 sun.tools.jps.Jps
Now you run the bminstall.sh script to upload the agent into the JBoss JVM
 [adinn@localhost adinn]$ ${BYTEMAN_HOME}/bin/bminstall.sh -b \
-Dorg.jboss.byteman.transform.all=true 23812
I have added a couple of extra arguments to the install command. The -b argument ensures that the agent jar is installed into the JVM bootstrap classpath and the -D argument sets a system property checked by the agent. Why are these needed? Well, the JVMMBeanStats script needs to be able to inject code into JVM classes in the java.* packages. This feature is normally disabled to stop you shooting yourself in the foot. Setting this system property when the agent is loaded allows injection into any class including those in the java.* package. Even with this enabled injection into java.* classes will not 'just work'. The problem is that the injected code must be able to reference exception types declared in the byteman jar. Since the java.* classes live in the bootstrap classpath the agent jar must also be added to that path.

Ok, so just to check that the agent is running let's see if we can talk to it using the bmsubmit.sh script.
 [adinn@localhost adinn]$ ${BYTEMAN_HOME}/bin/bmsubmit.sh -l
no rules installed
Good, the agent is running and responding. Now, with JBoss also up and running we can take a look at the JMX console.


Nothing there at present that mentions Byteman. That's because we haven't yet loaded any rules which use JMXHelper. So, let's upload the rules in the JVMMBeanStats rule set and then run some code to exercise them. Before loading the rule set we also need to install the sample jar into the boot classpath so that our injected rule code can reference classes JMXHelper and KeyInfo. We use bmsubmit.sh with the -b flag to load a jar into the bootstrap classpath and then again with the -l flag to load a rule script.
[adinn@localhost adinn]$ ${BYTEMAN_HOME}/bin/bmsubmit.sh -b ${BYTEMAN_HOME}/sample/lib/byteman-sample.jar
append boot jar /home/adinn/jboss/byteman/trunk/install/sample/lib/byteman-sample.jar
[adinn@localhost adinn]$ ${BYTEMAN_HOME}/bin/bmsubmit.sh ${BYTEMAN_HOME}/sample/scripts/JVMMBeanStats.txt
install rule return key info
install rule set period
install rule set sample set size
install rule count thread create
install rule count thread start
install rule count thread run
install rule count thread exit
install rule count file open read File
install rule count file open read File Descriptor
install rule count file open write File
install rule count file open write File Descriptor
install rule count file input stream close
install rule count file output stream close
install rule count class loads
Right, the agent should now have injected the rules into the relevant methods of classes Thread, FileOutputStream etc and then activated the JMXHelper class. So lets take another look at the JMX console. We can see that a new bean has popped up in the left hand side menu. Clicking on it reveals it to be the bean added by Byteman.
A click on the PeriodicStats element in the display shows us the actual stats.

The period (5) and sample set size (5) are displayed at the top followed by the statistics for each entry defined in the key info. We can see that the total number of threads created since the rule set was loaded is 34. The number created in the last five sample intervals must be 5 since the creation rate appears to be exactly 0.2 per second. Only 2 threads have exited which, presumably, indicates that the allocated threads are being used to fill up a thread pool.

Note that the sample period is a writeable property resettable from the MXBean. The MXBean also provides an operation (off screen in this snapshot) which allows all counters to be reset to zero.

Finally, we can use the bmsubmit.sh script to deinstall all the rules. This causes JMXHelper to be deactivated and it removes the MBean from the display. The agent removes all the injected rule code, restoring the affected JVM methods back exactly as they were before the rule script was uploaded.
[adinn@localhost adinn]$ ${BYTEMAN_HOME}/bin/bmsubmit.sh -u /home/adinn/jboss/byteman/trunk/install/sample/scripts/JVMMBeanStats.txt
uninstall RULE return key info
uninstall RULE set period
uninstall RULE set sample set size
uninstall RULE count thread create
uninstall RULE count thread start
uninstall RULE count thread run
uninstall RULE count thread exit
uninstall RULE count file open read File
uninstall RULE count file open read File Descriptor
uninstall RULE count file open write File
uninstall RULE count file open write File Descriptor
uninstall RULE count file input stream close
uninstall RULE count file output stream close
uninstall RULE count class loads

Here's the JMX console again, with the Byteman stats MBean removed

If we want to vary the information displayed or the way it is computed we can just tweak the rule script to record different events or use different counting rules for the same events and then reload the script by calling bmsubmit.sh. The MBean is automatically recreated and reloaded into the JMX console.

If you want to try this out you can download the latest release from the Byteman downloads page. The binary and full source releases both include the sample jar and scripts plus the latest Byteman programmers guide. I'll also be happy to answer any questions you have or advise on developing rules to track your application behaviour on the Byteman user forum. Enjoy!

Monday, 11 October 2010

Allowing full access to objects in rules

Some months back one of the developers at JBoss was trying to use Byteman to test some code and he was rather puzzled that his rule was not compiling correctly. It turned out that his rule action included an assignment to a private field. Up until now Byteman has only allowed rule actions to change public state or call public methods. Rule conditions and actions have no special privileges as far as encapsulation is concerned.

As an example, given this class
class Regulator
{
private float throttle;
public void adjustThrottle(float amount);
}
the following rule fails
CLASS SteamEngine
METHOD adjustPressure(float)
AT CALL Regulator.adjustThrottle
IF ($0.getRegulator().throttle + $1 > 0.95)
DO traceln("Illegal setting for throttle"),
traceStack(),
THROW new BoilerRupture("too much pressure")
ENDRULE
Class Regulator allows clients to increment or decrement the throttle setting but it does not enable access to the current value, presumably because it handles any illegal settings itself. However, when testing or validating the application it is useful to be able to identify erroneous situations such as the one above where a client is making an invalid request. Regulator may handle the error but it is still important to know where errors arise.

Unfortunately, the rule does not typecheck correctly. Byteman complains that the condition is trying to access an unknown field called throttle. The same issue applies with method invocations. If a method is private then any attempt to call it inside a rule condition or action leads to an unknown method error during type checking. Well, the answer is obvious isn't it. Why not just let rules access whatever state they want?

I have modified the trunk release of Byteman to do just this. It is working and there don't appear to be any problems with it. Of course, enabling this feature raises a whole load more opportunities for you to shoot yourself in the foot when using Byteman. In particular, if you use Byteman to modify JVM static and instance data or call private JVM methods you can easily break your Java runtime into shiny little pieces. But then again, this feature makes it possible to do a whole load more tracing and verification of your application's behaviour and to engineeer a lot more unexpected situations during testing. Caveat emptor, as the Romans used to say.

Assuming no issues arise during testing over the next few weeks this feature should be included in the upcoming 1.3.1 Byteman release. If you want an early peek then check out and build the trunk code and give it a try.