Introduction

PXE's BPEL implementation relies on the JACOB framework to implement the BPEL constructs. The framework provides the mechanism necessary to deal with two key issues in implementing BPEL constructs:

  1. Persistence of execution state.
  2. Concurrency.

By rolling up these concerns in the framework, the implementation of the BPEL constructs can be simpler by limiting itself to implementing the BPEL logic and not the infrastructure necessary to support it.

The approach we'll take in this tutorial is looking at the #rational of Jacob and its #concepts first. Then we'll illustrate with one complete example. But if you're a reverse reader, you can also decide to start with the example.

Rationale behind the model

Let's start from the most classical example of all:

   1 void process(order) {
   2   billingService.bill(order.billing);
   3   shippingService.ship(order.product, order.shipping, self);
   4   shipping = receive("shipping")
   5   order.customer.send(shipping.details);
   6 }

It's Java like pseudo code that works extremely well, unless:

  1. You fail somewhere in the middle and the customer has to order a second time.
  2. Your have too many waiting threads and the VM crashes.

So you change it to:

   1 void process(order) {
   2   billingService.bill(order.billing);
   3   shippingService.ship(order.product, order.shipping, self);
   4   listenOn("shipping", part2);
   5 }

   1 void part2(shipping) {
   2   order.customer.send(shipping.details);
   3 }

That's almost better, but still has a lot of points of failure, where you're not sure if you actually billed the customer and shipped the product or not. So:

   1 void process(order) {
   2   billingService.bill(order.billing);
   3   continue("part2");
   4 }
   5 
   6 void part2() {
   7   shippingService.ship(order.product, order.shipping, self);
   8   listenOn("shipping", part2);
   9 }
  10 
  11 void part2(shipping) {
  12   order.customer.send(shipping.details);
  13 }  

You're just fracturing the code with two primitives: continue which lets you persist state and go to the next one, and listenOn which lets you persist state and wait for an external event.

Fracturing the code also addresses concurrency of execution even if you only have one thread. For example you could have a large number of 'process' calls to bill and ship an order. As we've broken down the whole treatment into several small parts, we can control when these separate parts actually get called and executed. And we're free to order them.

Let's say we have a small process doing in a sequence:

1. Invoke
2. Receive
3. Wait
4. Invoke

If we have 2 parrallel executions of this process and implement it in a simple way we'd have:

1. Invoke1
2. Receive1
3. Wait1
4. Invoke1
5. Invoke2
6. Receive2
7. Wait2
8. Invoke2

However if we break down the code as shown above by introducing a "middle man" (or stack) and do not allow activities to directly call each other (or do not have the activity directly calling the sequence that directly calls the next activity) we could well obtain the following:

1. Invoke1
5. Invoke2
2. Receive1
3. Wait1
6. Receive2
7. Wait2
4. Invoke1
8. Invoke2

From a client standpoint, we've achieved concurrency of execution even with one thread.

Next step is adding links, fault handling/termination, compensation and event handlers and seeing that continue/listenOn is all you need. The last step is just adding implementation details.

Jacob Example

Consider the issue of persistence. Imagine a simplified and naive implementation of the BPEL constructs <sequence>, <wait>, and <empty>:

   1 class Sequence extends Activity {
   2   /** From BPEL Definition */
   3   OSequence def;
   4   ...
   5   void run() {
   6      for (OActivity child:def.children)
   7        createActivity(child).run();
   8   }
   9 }
  10 
  11 class Wait extends Activity {
  12   /** From BPEL Definition */
  13   OWait def;
  14   ...
  15   void run() {
  16      Thread.wait(def.duration);
  17   }
  18 }
  19 
  20 class Empty extends Activity {
  21   /** From BPEL Definition */
  22   OEmpty def;
  23   ...
  24   void run() {
  25      // <empty> activity: do nothing.
  26   }
  27 }

The above is the "natural" implementation of the constructs in the Java language. However, this implementation has some serious and obvious problems: the <wait> may specify a duration of days in which case a system failure during those days of waiting would mean that the process execution state would be lost. It would be nice to replace Thread.wait() in the Wait class with some sort of "suspend" operator that would save the execution state to disk.

However there are practical issues to "suspending" to disk. At the point we wish to suspend, the call stack looks like:

Sequence.run()
Wait.run()

In order to save the process to disk, we need to end the current thread of control which means popping both stack frames. To do this we have no choice but to require the implementation of Wait and Sequence to "cooperate" with this requirement thereby greatly complicating the implementation of those constructs. This also means that the "natural" implementation model cannot be used directly.

JACOB aims to solve this problem by providing an alternate "natural" model that allows execution state to be suspended without cooperation from the implementation classes. The idea in JACOB is to flatten the call stack and rely on explicit communication channels to handle control flow. We now consider a simplified JACOB representation of our three BPEL activities:

   1 class Empty  {
   2   OEmpty def;
   3 
   4   /** channel we use to notify parent we are done. */
   5   CompletionChannel myCompletionChannel;
   6   ...
   7   void run() {
   8      // <empty> activity: do nothing...except to
   9      // notify our parent that we are done.
  10      myCompletionChannel.completed();
  11   }
  12 }
  13 
  14 class Sequence  {
  15   OSequence def;
  16   CompletionChannel myCompletionChannel;
  17   ...
  18   void run() {
  19     // Start of by instantiating a sequential child runner for the first
  20     // (0th) child...
  21     instance(new SequenceChildRunner(0))
  22   }
  23 
  24   class SequenceChildRunner {
  25     int currentchild;
  26     SequenceChildRunner(int childNumber) { currentchild = childNumber; }
  27     void run() {
  28        if(currentChild == def.children.size()) {
  29          // We are past the last child, the sequence is done.
  30          myCompletionChannel.completed();
  31        } else {
  32          // We still have more children to run..
  33   
  34          // Create a completion channel for our child.
  35          CompletionChannel childCompletionChannel = 
  36             newChannel(CompletionChannel.class);
  37 
  38          // create a child activity based on the activity type
  39          // and parameterized with the model and the completion
  40          // channel we just created
  41          Activity childActivity = 
  42             createActivity(def.children.get(currentChild),
  43                            childCompletionChannel);
  44 
  45          // instantiate the child activity
  46          instance(childActivity);
  47 
  48          // create an object to wait for the "completed()" notification
  49          // from the child activity.
  50          object(new CompletionChannelML(childCompletionChannel)) {
  51             void completed() {
  52                // Ok, finished with the child, create a runner
  53                // to do the next child.
  54                instance(new SequenceChildRunner(currentChild+1));
  55             }
  56          }
  57        }
  58     }
  59   }
  60 }
  61 
  62 class Wait extends Activity {
  63   OWait def;
  64   CompletionChannel myCompletionChannel;
  65    
  66   ...
  67   void run() {
  68      // Create a channel for an externally managed alarm.
  69      TimerChannel timerChannel = newChannel(TimerChannel.class);
  70      // register the alarm with the runtime.
  71      getRuntimeContext().registerTimer(timerChannel, def.duration);
  72 
  73      // create an object to wait for the alarm and then send an
  74      // activity completed message to our parent.
  75      object(new TimerChannelML(timerChannel) {
  76         onTimer() {
  77            myCompletionChannel.completed();
  78         }
  79      });
  80    
  81   }
  82 }

So Jacob constructs help us in breaking the execution stack.

Main Jacob Concepts

Channels

As briefly demonstrated above, channels are interfaces used for communication between activities in PXE engine. There are several types of channels like TerminationChannel, ParentScopeChannel or CompensationChannel (their respective purpose should be obvious from their name). Some basic channels are provided to all activities when they're created to allow them to interact with their environment. When an activity wants to notifies its parent that it has terminated for example, it just calls its parent TerminationChannel (see the Empty example above).

Don't look for channels implementations because there are none. Channels implementation is provided through a dynamic proxy (see ChannelFactory.createChannel() and ChannelFactory.ChannelInvocationHandler for more). That's one of the levels of decoupling between invocation and actual execution in Jacob.

JacobObject / JacobRunnable

If you don't care much about the details, the bottom line is: a JacobObject and an JacobRunnable are just a method implementation. This method gets executed when the abstraction is executed.

A JacobObject is meant to be a closure. From Wikipedia: "A closure combines the code of a function with a special lexical environment bound to that function (scope). Closure lexical variables differ from global variables in that they do not occupy the global variable namespace. They differ from object oriented object variables in that they are bound to functions, not objects.". Normally closures aren't supported in Java so JacobObject tries to feel that gap. But it's not a true closure anyway, which makes thing easier. Closures in Jacob are statically coded, whereas in most languages supporting closures these are dynamic. So basically in Jacob, a closure is expected to implement some methods and provides other utility methods to manipulate channels and replicate itself.

JacobRunnable is just a JacobObject that requires the implementation of only one method: run(). As all activities inherit from http://svn.apache.org/repos/asf/incubator/ode/trunk/jacob/src/main/java/org/apache/ode/jacob/JacobRunnable.javJacobRunnableable they're all supposed to implement their main processing in this run() method. Their initialization occur in their respective constructors.

Method Lists (MLs)

ML classes can be seen as the other end of a channel. Only they're not invoked directly when one calls a channel method, but only once the Jacob engine has popped the channel invocation from its internal stack (again you can see how the execution stack gets broken here).

Usually MLs implementations in PXE are inlined because it's just easier to declare them in the activities run() method. For example if you look at the Sequence example shown above you'll see something like:

   1     void run() {
   2         ...
   3          // create an object to wait for the "completed()" notification
   4          // from the child activity.
   5          object(new CompletionChannelML(childCompletionChannel)) {
   6             void completed() {
   7                // Ok, finished with the child, create a runner
   8                // to do the next child.
   9                instance(new SequenceChildRunner(currentChild+1));
  10             }
  11          }
  12        }
  13     }

The object method here is inherited from JacobObject and is just a way to hand our ML to Jacob. So that the Jacob runtime can match it with an incoming channel message later on.

VPU and ExecutionQueue

The VPU is where all the Jacob processing is occuring. When a JacobObject is injected inside the VPU, it's actually registered as a Continuation, which is just wrapping the JacobObject with the method to call on the JacobObject to execute it (in our case always the run() method as we're only dealing with JacobRunnable instances).

The ExecutionQueue (and its implementation FastExecutionQueueImpl) is just a container for all the artifacts managed by the VPU (mostly channels and reactions) to organize them in queues where artifacts can be pushed and popped. It also records some execution statistics.

So the VPU main processing is just dequeuing a reaction from the soup and executing it by calling its abstraction's run() method (remember that the reaction just wraps an abstraction). That's all (check JacobVPU.execute(), you'll see that I'm not lying). However when the JacobRunnable (usually an activity) gets executed the following things can happen:

* if other abstractions (usually other activities) are created, they will be appended to the reaction queue, * if new channels are created, they will be saved for later usage, * if channels are invoked, the message will be saved to match against a new ML, * if a new ML instance is created, it will be submitted to the VPU that will try to match it against a channel invocation.

The VPU is also responsible for persisting its internal state. So when an execution stops (for example our process has reach a receive) the VPU state is serialized and saved for later reuse. This logic can be seen in RuntimeContextImpl.execute().

There's one more thing that should be mentioned here. Continuations (and hence JacobRunnables) don't "stay" in the VPU queues. They just get popped, executed and that's it. So if an abstraction must last more than one execution, it should simply fork itself. This explains why in our Sequence example already pasted above we see the line:

   1    instance(new SequenceChildRunner(currentChild+1));

This simple adds a new ChildRunner that will monitor the next child completion. If you browse PXE's activities code you will even find things like instance(this) which directly enqueues a new instance of the same Jacob abstraction.

Walking through examples

While

<process name="while1" 
    targetNamespace="http://pxe/bpel/unit-test" 
    xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
    xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
    xmlns:tns="http://pxe/bpel/unit-test"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:test="http://pxe/bpel/unit-test.wsdl" 
    suppressJoinFailure="yes">
   <partnerLinks>
      <partnerLink name="testPartnerLink" 
         partnerLinkType="test:TestPartnerLinkType" 
         myRole="me" />
   </partnerLinks>

   <variables>
     <variable name="var1" messageType="test:TestMessage2"/>
   </variables>

   <sequence>
       <receive 
          createInstance="yes"
          name="startReceive"
          partnerLink="testPartnerLink"
          portType="test:TestPortType"
          operation="testOperation"
          variable="var1"/>
      <while condition="bpws:getVariableData('var1', 'TestPart') &lt; 10">
        <assign>
           <copy>
             <from expression="bpws:getVariableData('var1', 'TestPart') + 1"/>
             <to variable="var1" part="TestPart"/>
          </copy>
        </assign>
       </while>
       <reply name="endReply" 
              operation="testOperation" 
              partnerLink="testPartnerLink"
              portType="test:TestPortType" 
              variable="var1"/>
   </sequence>
</process>

Everything starts with a receive. So our entry point here in our Jacob-focused discussion is going to be BpelProcess.PartnerLinkMyRoleImpl.inputMsgRcvd(). The code that matters to us now is the following (executed when a message is targeted at a createInstance receive):

   1     BpelRuntimeContextImpl instance = createRuntimeContext(newInstance, new PROCESS(_oprocess), messageExchange);
   2     ...
   3     // run the vpu
   4     instance.execute();

If you check the code executed by BpelRuntimeContextImpl constructor you'll see among other things the following:

   1     if (PROCESS != null) {
   2       vpu.inject(PROCESS);
   3     }

The process itself get injected. When executed, PROCESS just instantiates a scope to control the execution of its child activity and starts listening on compensation and completion channel. From the process we go to a scope, then our main sequence and finally our receive.

Receives are just mapped to a pick onMessage so its Jacob implementation should be looked for in PICK. The PICK is just about isolating the right correlations and selecting a message for it, then waiting for the message. In our createInstance case we'll be more interested in the following code, located in BpelRuntimeContextImpl.select() (and called by PICK):

   1     if (_instantiatingMessageExchange != null && _dao.getState() == ProcessState.STATE_READY) {
   2       for (int i = 0 ; i < correlators.size(); ++i) {
   3         CorrelatorDAO ci = correlators.get(i);
   4         if (ci.equals(_dao.getInstantiatingCorrelator())) {
   5           inputMsgMatch(pickResponseChannelStr, i, _instantiatingMessageExchange);
   6           return;
   7         }
   8       }
   9     }

Which just happens to call something like:

   1     vpu.inject(new JacobRunnable() {
   2         public void run() {
   3             PickResponseChannel responseChannel = importChannel(responsechannel, PickResponseChannel.class);
   4             responseChannel.onRequestRcvd(idx, mex);
   5         }
   6     });

That's where things really start. When injected, this abstraction just calls the response channel for our receive. The other side of this channel is implemented as a ML in the PICK:

   1     object(false, new PickResponseML(_pickResponseChannel) {
   2         public void onRequestRcvd(int selectorIdx, Object msgex) {
   3             ...
   4           ActivityInfo child = new ActivityInfo(genMonotonic(), onMessage.activity, _self.self, _self.parent);
   5           instance(createChild(child,_scopeFrame,_linkFrame));
   6         }
   7     });

This method just does what a receive needs to do (like variable and correlation initialization) and creates a new child. When dealing with a real pick, this child would be the onMessage activity, however in the case of a receive, this is an empty activity. So when does our receive completes? Well, when the child completes. As you can see on the child constructor, we're passing the same !ParentScopeML that we've been provided. So when the child completes, the receive's parent is notified which means to our receive doesn't need to do it itself. And an empty immediately completes:

   1     _self.parent.completed(null, CompensationHandler.emptySet());

The parent sequence gets notified almost immediately after the onRequestRcvd() methods finishes.

Now how does our sequence gets the control back? Well, once again, let's look at the ML, the other side of the channel. As one of the most important job of the VPU is matching channels invocations and MLs, we'll get to the sequence by its !ParentScopeML implementation:

   1 class SEQUENCE extends ACTIVITY {
   2   ...
   3   private class ACTIVE extends BpelJacobRunnable {
   4     ....
   5     public void run() {
   6       ...
   7       object(new ParentScopeML(_child.parent) {
   8         public void compensate(OScope scope, SynchChannel ret) {
   9           _self.parent.compensate(scope,ret);
  10           instance(ACTIVE.this);
  11         }
  12 
  13         public void completed(FaultData faultData, Set<CompensationHandler> compensations) {
  14           HashSet<CompensationHandler> comps = new HashSet<CompensationHandler>(_compensations);
  15           comps.addAll(compensations);
  16           if (faultData != null || _terminateRequested || _remaining.size() <= 1) {
  17             _self.parent.completed(faultData, comps);
  18           } else /* !fault && ! terminateRequested && !remaining.isEmpty */ {
  19             ArrayList<OActivity> remaining = new ArrayList<OActivity>(_remaining);
  20             remaining.remove(0);
  21             instance(new SEQUENCE(_self, _scopeFrame, _linkFrame, remaining, comps));
  22           }
  23         }
  24       }));
  25     }
  26   }
  27   ...
  28 }

The method that will get executed is of course the completed() method. It simply completes if a fault has been thrown, a termination has been requested and if no child activities remain. Being of an optimistic nature, we'll check what happens when everything goes just fine. In this second case a remaining activity is removed and the SEQUENCE abstraction itself is reinstantiated. Which leads us to what the SEQUENCE does:

   1   public void run() {
   2     final ActivityInfo child = new  ActivityInfo(genMonotonic(),
   3             _remaining.get(0),
   4             newChannel(TerminationChannel.class), newChannel(ParentScopeChannel.class));
   5     instance(createChild(child, _scopeFrame, _linkFrame));
   6     instance(new ACTIVE(child));
   7   }

As you can see, it just instantiates the next child abstraction and also another abstraction named ACTIVE. So what's this ACTIVE that we've already seen a bit before? Well, it's just the abstraction that keeps on following child activities when they execute. It's more like a convention on all containment-based activity in PXE (while, sequence, pick, ...) that the main activity abstraction just kicks off the processing. Then an ACTIVE (also sometimes called WAITER) abstraction takes care of following the children.

Continuing to the next step, we've just instantiated an abstraction for the while in our example process, as it's the next child of the sequence. So what happens there?

   1   public void run() {
   2     boolean condResult = false;
   3     try {
   4       condResult = checkCondition();
   5     } catch (FaultException fe) {
   6       _self.parent.completed(createFault(fe.getQName(), _self.o),_compHandlers);
   7       return;
   8     }
   9     if (condResult) {
  10       ActivityInfo child = new ActivityInfo(genMonotonic(),
  11               getOWhile().activity,
  12               newChannel(TerminationChannel.class), newChannel(ParentScopeChannel.class));
  13       instance(createChild(child, _scopeFrame, _linkFrame));
  14       instance(new WAITER(child));
  15     } else /* stop. */ {
  16       _self.parent.completed(null, _compHandlers);
  17     }
  18   }

Now you should be getting more familiar with that sort of code. First step is evaluating the while condition. If it turns out it's true, then a child abstraction gets created as well as a WAITER to follow its execution. The WAITER implementation is again pretty straightforward:

   1   private class WAITER extends BpelJacobRunnable {
   2     private ActivityInfo _child;
   3     private boolean _terminated;
   4 
   5     WAITER(ActivityInfo child) {
   6       _child = child;
   7     }
   8 
   9     public void run() {
  10       object(false, new TerminationML(_self.self) {
  11         public void terminate() {
  12           _terminated = true;
  13           _child.self.terminate();
  14           instance(WAITER.this);
  15         }
  16       }.or(new ParentScopeML(_child.parent) {
  17         public void compensate(OScope scope, SynchChannel ret) {
  18           _self.parent.compensate(scope,ret);
  19           instance(WAITER.this);
  20         }
  21         public void completed(FaultData faultData, Set<CompensationHandler> compensations) {
  22           _compHandlers.addAll(compensations);
  23           if (_terminated || faultData != null)
  24             _self.parent.completed(faultData, compensations);
  25           else
  26             instance(WHILE.this);
  27         }
  28       }));
  29     }
  30   }

Termination and compensation aren't doing anything really interesting. Completion, just like for the sequence, re-instantiates the WHILE abstraction. And that's how we get our loop, by re-instantiating the main WHILE abstraction (again evaluating the condition and creating a child if it's true).

Finally, when the while condition becomes false, it notifies its parent channel. The sequence then goes to our last activity: reply. As expected, the reply replies, just sending the variable content and notifying its parent for completion. The sequence has no more children to execute so it also notifies its own parent, which is the process. We then just declare the process to be completed and that's it! We're done!

Jacob (last edited 2009-09-20 23:19:40 by localhost)