How the EOS workflow engine works
23:56:05 | category:
Workflow | Tag:
| Large font size, medium/small subscription
Reproduced on:
Http://lanhy2000.blog.163.com/blog/static/43678608201172115428592/
1. Basic workflow knowledge
......
2. operating principle of the EOS workflow engine
This article is a bit of my understanding of the EOS workflow I wrote after work. My understanding may not be all correct, but may be different from the true face of the engine. Therefore, we can only provide you with some reference.
2.1. Core Scheduling Algorithm of the EOS workflow engine
The most important component of an EOS workflow is its core scheduling algorithm. Before we study its working principle in depth, we think that its working principle is at work, activities and process instance objects are marked to drive the process. The engine is completely a database-driven flow engine (the workflow platform of Anhui Phase II seems to be driving the flow operation using database tables ), in fact, it is an engine driven by events, and the database only persists the status before and after the engine is running. After my recent work, I tracked the working principle of the engine to find out the "event-driven" workflow engine introduced in the EOS help document.
2.1.1. EOS workflow engine Event Type
Each of the above events is atomic and inseparable. The collection of a series of events uses the event scheduling mechanism of the EOS engine to implement the startup process and end work items that we often encounter at work. (In the event type class, Eos defines 29 types of events, but in the event factory class, Eos defines 26 types .)
1.1.1. EOS workflow event scheduling mechanism
The scheduling service of the EOS event is to load the service factory class to the memory (servicefactory. initeventservice () when the workflow engine is initialized ()). You can use servicefactory to obtain the unique event service instance of JVM for transaction scheduling. All event program entries are event services. This class is actually an interface and has two implementation classes, one is the singlethreadeventservice implementation class of a single thread (in the implementation code, it is not a single thread, but a single instance object), and the other is the multi-threaded implementation class multhreadthreadsvc, (The implementation method is not described in detail here. The multi-threaded class is followed by a lot of thread pool implementation code.) In the event service class, one attribute class is wfeventdisposer, this class contains event registration, event publishing, and event registration is implemented by a static code block. After registering the 29 types of events described in the previous section, you can register the corresponding Event code to the corresponding processing class. The event processing classes share five (processscheduler, activityexecuter, exceptionhandler, workitemhandler, applicationhandler), corresponding to the first five digits of the Event code. There are two types of event Publishing, one is normal publishing, one is release without exceptions (that is, exception handling is disabled when an event is executed ). The so-called event publishing is to pass an event object (wfevent class) to the Event Service class. This event object contains the event type, thread name, event ID, process definition ID, activity definition ID, activity instance id, and work item ID.
The above briefly describes the event model. Next we will take the most commonly used component: finish the work item to track its event processing in detail. The end work item may be the most representative process action, because the process of the entire process instance is traversed after this time:
1. the user calls the finishworkitem method of the workitemmanager class through the engine API. This method obtains the Data Access Service of the persistent layer through the Service Factory and obtains the wfworkitem object according to the workitemid. After relevant judgment, create an event object (wfevent) with the Event code 3004 through the createfinishworkitemevent method of the event factory class ). Then, the event object is published to the event processing service through the event service class. From now on, the EOS event scheduling service has been running.
2. The event service class (taking the single thread event service class as an example) obtains the event class and publishes the event through wfeventdisposer. The specific release process is very simple, that is, to determine whether the event type has been registered, if it has been registered, it will be obtained to change the registration class of the Event code. If the code is 3004, workitemhandler should be used. Then call the workitemhandler's invoke () method,
3. The workitemhandler class invoke () is written to: If (event. getType () = 30004) {finishworkitem (event);} Then find the method. After the method starts to make a judgment, modify the flag bit: set the current work item status to 12, and then determine whether the current activity is complete. (The approximate algorithm is to obtain the completed work items and the total work items of the activity, and determine whether to start multiple work items defined by the activity. If there are multiple work items, determine the number of completed policies: by percentage or by number of operators, etc. After a series of judgments, we can get the work items that should end, if the number is less than or equal to the number of completed work items, the activity ends. If more than one work item is not started, the corresponding processing should be simple.) If the activity has been completed, call the createfinishactivityevent event of the end activity instance of event service. If the event does not end, determine whether the start policy of the work item is "at_the_same_time" or "one_by_one ", if it is "one_by_one", find the job in the status of 1 in the active instance and start it.
4. The end activity instance calls the createfinishactivityevent method of the event factory to create an event Code 2004. Use the createfinishworkitemevent method to publish the event. Locate finishactivity in the activityexecuter class. Modify the activity instance status to 7 and enter the activity end time. If this activity has been registered, the registration will be canceled. If the active instance defines a trigger action to terminate the activity, this action is triggered (called through wfappcaller ). Finally, the event factory generates a createschedulenextactivityevent event with the Event code 1002. Events are published by the event service.
5. The event action to start the next activity instance is the schedulenextactivity method called by the event factory. This method finds the Transfer Condition of the next link through the process definition, A link definition list is generated based on the Transfer Condition and branch mode (all branches: And; multiple branches: XOR; single branch: Or. The engine first finds unstarted and suspended activity instances. If not, an activity instance is generated. Generate a transfer object (wftransition) and put the object of the active instance to be started into a list. Launch an activity instance based on the launch policy defined in the activity list (Direct start, to be activated, specified by the rule logic; if an active instance is started directly, the event factory creates an event startactivity with the event Code 2001. If the policy to be activated is enabled, the event factory generates the event prestartactivity with the event Code 2000. Similarly, if an event triggered by creating an active instance is defined in the process definition, this event is triggered. The schedulenextactivity method does a lot of business processing, so it is complicated.
6. The event service calls the startactivity method, modifies the current activity status bit to 2, registers the time limit to the time limit management service, and then assigns work items through the help class of the activity execution class, the process of assigning a work item is to determine whether it is a multi-work item. If not, it is assigned by the participants. If yes, it is to determine the startup policy of multiple work items. It is complicated to start the work item business, there is no corresponding Event code, which is not detailed here.
The above six steps have completed the most common methods for completing work items. In summary, we should be able to have a clear understanding of the event scheduling mechanism of the EOS workflow, for example, a 3004-> 2004-> 1002-> 2001-> event is triggered. Also, we usually use the process instance startup method to create a process instance first, then start event scheduling: 10001-> 10002-> 2001, and finally assign work items.
Osworkflow also has its own scheduling mechanism, but it is much simpler than EOS in terms of business. To be precise, osworkflow has only two concepts: steps and actions ). A simple scheduling process may flow from one step to another (or sometimes stay in the same step ). Its scheduling is actually a class: abstractworkflow. There are two methods in this class: doaction and transitionworkflow basically implement all scheduling (in fact, it cannot be regarded as scheduling, but it can only be regarded as status migration ). The biggest advantage of osworkflow is a series of functions executed during the execution and scheduling process (Service Model in SOA and presentation logic in Eos ), it is still complicated when executing the client service mechanism. If you are interested, you can take a look at it later.
There is also a popular open-source engine recently. I have never seen it in jbpm. It seems to be complicated to integrate it into JBoss again.
1.2. Time Limit Management Service
1.2.1. Classification of time limits
There are two types of time limits: one is the time limit for triggering completion, and the other is the cycle trigger (for example, the interval for a reminder) and the number of triggering times can be set.
1.2.2. Time Calculator
The time-limit calculator that starts a unique JVM instance when the workflow engine starts. This class can be used by the default engine. You can also implement a custom computing method by yourself. Just register the class name to be rewritten in the configuration file. The time limit calculator of the engine has only two methods: calculation End Time and calculation reminder time. It is actually a static class.
1.2.3. Start of time-limited service
There are two time-limit services in the engine. One is the time-limit service started when the engine starts, and the other is the time-limit Object List initialized by the service after the engine starts, this service is used to round-robin The time-limit objects in the list, trigger events corresponding to the time-limit objects that trigger the time-out, and remove the time-limit objects. The thread processing of the Time Limit uses a large number of procedural Program structures. Here we are still confused.
1.2.4. Time Limit registration and Removal
In the process engine, the time limit Service maintains a list of time limit objects, which records the Time Limit objects of running activities.
Determines the time limit of the activity or process when a link or process is started. If the activity or process defines the time limit, the time limit will be registered with the time limit service; the implementation of the Registration Method in the timermanager class is to call the registetimer method of the Time Limit service class and append a record to the time limit Object List (vector.
If a time-out operation is performed at the end of an activity event or at the end of the process, the time-limit object of the activity is not displayed in the time-limit object list because the object has been triggered and removed by the time-limit trigger. If no timeout occurs, remove the time limit object in the vector list. The implementation of registering the removal method in the timermanager class is to call the unregistetimer method of the Time Limit service class and remove a record from the time limit Object List (vector.
1.2.5. Trigger of time limit events
The time limit is triggered by the background thread. This thread polls the list of Time-limit objects maintained by the time-limit service. If a time-out object is found, the predefined action is triggered, this action is the trigger action we usually set in studio for what if the timeout occurs.
The processing of the time limit is implemented through the java. util. Timer class. Is to create a time-limit task (mytimertask) for timer to execute. And an oncetimerhandler object instance is passed to the class. This object has a method timertrigged, which is triggered at the scheduled time. This method first calls the handlertimer method of the timerhandler class, that is, if an event is triggered, the event code discussed in the previous section starts with 4 is called. Then, modify the current status of the Time Limit class to 3 to complete a time limit trigger.
2. Process Synchronization Service
The Process Synchronization Service is a custom lock defined by the engine for the process instance and process. For example, you can specify the participants in the Next Step (appointnextactparticipant method in wfappointparticle antmanager) first, the current process instance to the wretched (servicefactory. getlockservice (). lockprocinstance ). Then, after the method is completed, lock the process instance to release (servicefactory. getlockservice (). releaseprocinstance ). Two types of locks are defined in the synchronization service. One is the process definition lock, and the other is the process instance (two lists ), check whether the modified ID (process instance id or process definition ID) is already in the cumbersome list. If so, add it to the cumbersome list. A thread is used to operate the lock list (waitinglist) between addition and unlock. The implementation method is to add a Lock Object to the waitinglist when locking, and then remove a lock object from the waitinglist when unlocking, and thread y (). The implementation of the Process Synchronization Service is still complicated. Although only seven or eight classes are used.
3. Organization Management
EOS provides its own organizational model, which we reference in Service Assurance phase III in Anhui. The implementation of the Service session of the organization model is configured in the configuration file, and then the engine uses the Java reflection mechanism to load the configuration class (in the engine, there is a "service locator" to achieve this, this service locator is the same as what we usually use, but it reads service definitions from files, hiding specific addressing details ). If you do not need the organization model provided by EOS, You can implement the wfomservice interface and implement the methods in it. It is estimated that the original intention of EOS is to provide a relaxed coupling between the organizational model and the engine service, but it does not seem to have done so in the implementation of its engine.
Omserviceimpl class is the organizational unit model session class loaded by the engine by default. This class defines personnel, roles, institutions, etc. The omserviceimpl2 class contains the post organization model (currently the engine is not supported yet, it is not clear that EOS does not include positions in the organizational unit model), but the open-source organizational unit model provided by EOS is not supported.
4. Audit Service
This service records the changes to all process templates and the operation history of process instances. The engine defines 39 Audit types, including template changes, startup processes, and work items. Because of the audit type code and the engine Event code, the engine maps the Event code and the audit code one by one (the audit code is more than the Event code ). In the audit process, a record is added to the audit table.
5. Log Service
The engine's Log service is very simple, similar to the logs we usually use. When logging, input the log context wflogcontext of the JVM unique instance. This class defines the log headers required for a log, such as the level (@ level), operator (@ operator ), SQL (@ SQL), timestamp (@ timestamp), and so on. Then, when a specific log is created, the log header and log content are assembled to form a log.
The engine logs are used to read and write logs, and the rollingfileappender and patternlayout of log4j are referenced. It also provides the service for intercepting logs before and after the method similar to AOP (I don't know whether the interception logs before and after the method are manually added in the code or automatically loaded by the AOP agent, because when AOP is used, the code is inserted into the intercept entry point during compilation ).
6. Persistent layer services
The persistence layer of the engine adopts the same design as the persistence layer in studio. Generally, the database fields correspond to the XML definition of the persistence layer one by one, and the or_mapping is not as complex as the CMP or BMP of hibernate or EJB. The persistence layer driven by JDBC is efficient in the system. However, the XML Description files in the database and persistence layer are used to correspond one to one. Therefore, the relational data is not made very unique. (I have not read the code in depth, maybe I do not understand it ).
7. Engine Cache
The cache of the workflow engine is maintained by a hashmap. The following types of caches are used: Process instance cache; active instance cache; work item cache; related data Dom cache; process attribute data cache, the cache quantity of the above types of instances is configured in the configuration file, another type of Process Template caching is to parse the XML definition of the Process Template when the engine starts (because the process definition is stored in the database through the XML file ), parse the object into a process definition and load it into the memory.
7.1. cache Configuration
The workflow cache configuration is configured in the wfconfig. xml file. The following configurations are available:
- <! -- Whether to use cache for database access -->
- <Configvalue key = "enabled"> false </configvalue>
- <! -- Process instance cache count -->
- <Configvalue key = "maid"> 1000 </configvalue>
- <! -- Number of active instance cache -->
- <Configvalue key = "activityinstcachecount"> 5000 </configvalue>
- <! -- Number of work item caches -->
- <Configvalue key = "maid"> 10000 </configvalue>
- <Configvalue key = "workitemviewcachecount"> 10000 </configvalue>
- <! -- Related data cache count -->
- <Configvalue key = "relatdatacachecount"> 1000 </configvalue>
- <! -- Related data domcache count -->
- <Configvalue key = "relatdatadomcachecount"> 1000 </configvalue>
- <! -- Process attribute data cache count -->
- <Configvalue key = "procinstattrdomcachecount"> 1000 </configvalue>
7.2. cache implementation
The workflow configuration information is obtained when the engine is started. If the cache is allowed, the above six types of cache are initialized. The default cache lifetime of the engine during initialization is 0x1499700l. The cache size is configured in the configuration file. In this way, six cache class instances are generated in the JVM. Each cache has a hashmap attribute, which stores the objects to be cached. In the cachefactory class, there is another hashmap object attribute, which stores a set of cache objects. Is the set of the above six cache class instances. Puyuan developers named the object caches. When an active instance is retrieved, it is read in the cache first. If it is found, it is returned directly. If not, it is loaded from the database.
The engine cache does not directly put the objects obtained from the database into map, but implements a layer of optimization to encapsulate the objects found in the database into cacheobject objects, this object has a linked list attribute object. This object has a forward node and a successor node, and its node is the object we want to put. The specific optimization policy is the same as that for most caches. It adopts the most recent access policy and has two lists for maintenance. One is that the most recently accessed object is in the first place, and the other is that the most visited object is in the first place.
8. Highlights of the EOS Engine
The most exciting part in the design of the EOS engine is the multi-threaded event scheduling mechanism. In event processing, there is a thread pool at the lower layer to process events, one thread obtains an event and starts release and migration of the event. (I think the multi-threaded collaborative programming should be the most complicated part of the programming, not only should we discard the so-called "Everything is an object" view, A large number of goto statements may need to be used to solve the problem that the idea of object-oriented is hard to solve, in addition, Thread Scheduling in Java may also depend on the operating system and hardware environment where the program runs, and there are many unpredictable situations. I suspect there must be a problem with this thread pool, or a single thread is enough to solve all the problems, otherwise, why does the EOS engine not take multi-thread processing events as the default processing method but a single thread as the default ?)
? Initialization of multi-thread scheduling: The engine creates so many threads based on the number of threads (event_thread_num) in the configuration file (wfconfig. XML. And put these threads in the defined thread group. These thread objects have an object attribute: eventlist, where all event objects processed by the thread are loaded. Then start () the threads all round. This thread polls the event object list in eventlist. If the Object List is empty, it blocks itself (wait ()), if an event object exists, take the first event and publish the event. The processing of the event is the same as that of a single thread.
Response of the thread pool to client actions: the customer wants to publish an event to the engine and first finds the activecount of the thread group, then, create so many threads Based on the obtained quantity and then copy them to the thread group. The engine converts these thread objects into event processing threads, traverses these threads, and then finds a thread with the least event in the eventlist of these thread objects, add the event object to the eventlist of the thread object to be released, wake up the thread, publish an event, and complete the collaboration between the thread and itself.
9. Insufficient EOS Engine
9.1. Organization Model
The organization model provided by EOS cannot resolve the assignment of work items by position or administrative level. However, this is a common scenario (the workflow platform of Anhui Phase II seems to have implemented the submission of work items at the administrative level ). There is a popular organization model on the Internet.
If this organizational model can be evolved and applied to the engine, it may solve the problem of setting participants by position, administrative level, and position, it can even solve the problem that an organization has only one process, instead of having a set of processes that are the same as those of other subordinate organizations (only the participants are different ). In our applications, we only need a set of common processes and the implementation of personalized processes of subordinate organizations. Because the customer may have deficiencies in management or rely on the system for management, we hope our system's shortcomings can be remedied in management, therefore, to achieve a balance between them, we need to find the balance between them.
9.2. cannot be applied to Distributed Systems
When the engine starts, the engine parses the process definition XML file into a process definition object and then loads it into the memory. the publishing process action can only come from one cluster node, the modified process definition cannot be synchronized to other cluster nodes. The current method of synchronization is to call a remote method of another node at the same time during the publishing process. Although this problem is solved through an external solution, it does not fundamentally compensate for engine defects.
The same cache problem also exists in the management of the business Dictionary of EOS. A business dictionary created on a node cannot be synchronized to other nodes.
The time limit of a link is also cached. When a link is started, if the time limit is defined, the service is registered with the time limit and a time limit object is generated in the memory, there is a background thread that is maintaining it. When the link ends, the registration of this link is canceled, the time limit object in the link's memory is removed, and the data of the time limit table in the database is deleted. There is an extreme scenario (impossible): All users start the next step after finishing their own step (assuming that the completion time of this step is one month ). This action is performed on node A, and the memory of node A has a time limit object for all next steps. The background thread of node A maintains the object and constantly judges whether the object has timed out. Assume that all users in the Next Step complete their work items without timeout, and the operation occurs on Node B, after you complete the link operation, cancel the Time Limit registration and delete the time limit table. However, the time limit object of node A is not removed. The background thread of node A maintains it until it times out and deletes it from the memory, causing junk data in the memory.
In my opinion, the engine layer should still have a cache Synchronization Service (maybe I am not talking about it), for example, adding a status to be released during the migration process where the process is not released and the status bit is successfully released, when a publishing process is implemented, the publishing status defined in this process is defined as to be released, and two threads work collaboratively. One thread is scheduled (for example, 20 s) to poll the process definition to be released and load it to a list of processes to be released (the list is similar to a semaphore in the operating system). If the list is not empty, wake up another process publishing thread, this thread sleep for a certain period of time (this time must be greater than or equal to the polling time to ensure that all nodes have loaded the process definition to be released to the memory) then release the process, set the process to the publishing status, and block itself.
9.3. Sub-Process Design
The sub-process of EOS is implemented as a main process. I don't think there should be any sub-process or parent process, or a process as a process. Communication between processes can be implemented through certain interface definitions and communication rules. The parent-child relationship is only one of them (a mesh model for workflow collaboration), and there is also a chain model, end-to-end model and parallel Synchronization Model. In this way, with the interface standard, it not only solves the Process Communication of the parent-child relationship, but also solves the cross operation of different instances of the EOS workflow, it even solves the process communication between different workflow products (as long as the interface definition standard is followed, this interface is the interface 4 defined by WfMC, this interface defines a series of interoperability layers (such as eight), but may not meet the requirements of engines like Eos with Chinese characteristics (such as free stream, CC ......) Workflow requirements ).
10. A theoretical engine principle
Petri Net is a mathematical representation of a discrete parallel system. I cannot understand its mathematical representation, but I can only understand something on its surface. It is not produced for a workflow, but if we can combine Petri Net and xpdl to construct an engine, it may not meet the actual needs, but I believe it will be very promising. It is also very competitive.
In Petri Net, there are four main elements:
1. Place:
Place is a State, such as a traffic light on the road. Its place can be a red light or a green light.
2. Transition
Transition is the process of switching from one state to another.
3. Arc
ARC is a directed arc connecting place and transition. It can point From Transition to place, or from place to transition, but cannot point from place to place or From Transition to transition, there must be a process of state change in the middle.
4. Token
A token is an object that represents anything. It can be changed from one State to another only when place or transition has enough token.
How Petri Net Works
Definition of elements:
The following status is displayed when the enter enters pass through the fire:
To enable enter, fire must consume one token for free and one for wait. Then enter can have one for before and one for occupied. And so on.
So far, we can define a process scheduling algorithm such as PN Network: if each input place of a change has a token, this change is allowed ). When a change is allowed, the change will take place (fire), the input place token is consumed, and a token is generated for the output place.
The workflow engines using this algorithm include the open-source yawl and Bossa. You can study it after a meal.