Rigo-Allain Rig Final01

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 35

University of West Bohemia in Pilsen Department of Computer Science and Engineering Univerzitn 8 30614 Pilsen Czech Republic

Model Based Development of Java Distributed Applications for Embedded Devices


Csar Allain Pacheco

Model Based Development of Java Distributed Applications for Embedded Devices


Csar Allain Pacheco Abstract
With the reduction in price of the computers, the information systems have suffered a radical change. From the centralized paradigm, in which the main applications resided in a central mainframe computer, to the decentralized paradigm in which many personal computers share applications, besides to have a local power computation, has changed totally the form of conception of all enterprise information systems. Therefore, the applications, that are composed the information systems, have to be rethinking from a centralized to distributed one. Anybody who had created programs in any programming language knows that the worse part or the tedious part of this work resides in the verification and testing programs. This task in a sequential application that runs in one processor is also very hard to achieve but the results obtained in various executions is the same and reliable. The former is not valid for distributed applications that run in several processors. The results after each running are unpredictable, making the process of debugging and testing very difficult and sometimes impossible. The task becomes more complex if we take into account that this distributed application will be implemented on a real hardware after testing and debugging. This task will have an effect on the costs elevation of the manufacture. Create a method that can help to achieve and relieve this problematic of verification and testing concurrent programs for embedded devices written in Java is the goal of this work. So, this work presents a model based development of Java distributed applications for embedded devices. The model is based on time serialization of threads of the control program, which is accomplished with the J-Serializer. The proposed method uses two kind of computer-environment: control interface, between a computer node and its part of controlled device; and network interface, a serial bus interface. A first approach to this work has been developed; it includes a model of the environment and the application program.

Contents
1. 2. 2.1. 2.1.1. 2.1.1.1. 2.1.1.2. 2.1.2. 2.1.2.1. 2.2. 2.2.1. 2.2.2. 2.2.3. 2.2.4. 2.2.5. 2.2.6. 2.2.7. 2.2.8. 2.2.9. Introduction Related Work Background of Parallel and Distributed Simulation Analytical Simulation Conservative Synchronization Optimistic synchronization Virtual Environments and Real-Time Simulation High Level Architecture (HLA) Best Known Theoretical Methods of Testing and Verification of Software Review Overview Petri Nets -Calculus LTSA Labeled Transition System Analyzer The Model Checker SPIN Checking Formal Models Java PathFinder 1 Constructing Formal Models from Java Multithreaded Programs Bandera Model Checking Propierties of Concurrent Java Software The Model Checker Verisoft Checking UNIX Concurrent Systems An Executable Model of Java Programs The ExitBlock Algorithm 15 Java PathFinder 2 Executable Models of the Java Virtual Machine Model Architecture Overview Model Structure Structure of a Node Model of the Network Master Slave Network Protocol Multi Master Network Protocol Synchronous Message Passing Asynchronous Message Passing The Model of the Simulation on the Network Control Program Verification Procedure The Verification Procedure The State Invariants and the Behavioral Protocols 15 16 16 16 17 16 18 19 20 18 24 24 24 5 6 6 6 7 9 9 10 12 12 13 13 13 14 14 14

3.1. 3.1.1. 3.1.2. 3.1.2.1. 3.1.2.2. 3.1.2.2.1. 3.1.2.2.2. 3.1.3. 4. 4.1. 4.2

5. 6. References

Case Study Conclusion and Future Work

26 27 29

List of Figures
Figure 1: Local control mechanism in optimistic synchronization protocols Figure 2: Structure of the HLA simulation Figure 3: The model of a node in the network Figure 4: Master Slave Network Protocol Figure 5: Code for Sender at Master Side Figure 6: Code for Receive at Master Side Figure 7: Multi-master Network Protocol Figure 8: Architecture of a Frame Figure 9: Model Interfaces Figure 10: Model for two nodes Figure 11: Model for N-nodes Figure 12: Case Study Overview of the Controlled Water System

Chapter 1

Introduction
Working in a distributed computer environment is a very interesting but not a very easy task, mainly when one wants to simulate and verify the correctness of an application. Many general and special purpose-programming languages have been developed over the years, that is a nearly impossible task to decide which language best fits or even a near best fit to any particular application [1]. Over 170 programming languages were in use in the United States in 1972, [2] and today there are even more. We have chosen a language that will be complain with portability and tightly integrated support for threads, which enables developing distributed applications not depending of the software platform or hardware you chose. For that reason, Java is among other languages, e.g. C++, Smalltalk and Simula, that better fit for this goal. As a result, in recent years, the number of Java embedded applications has been growing constantly e.g. mobile phones, PDAs, and consumer electronic devices. Java was conceived from the beginning as a language for embedded applications. The demand of the world market increases the number of applications for those devices [3]. An unresolved question is the verification of correctness of a concurrent Java program. Sequential programs have just one possible path of execution in a time unit. A distributed program leads us to many possibilities of execution in the same portion of time, so proving the correctness of such a program is very complicated or even impossible to deal with. The model (method) that we present is not a theoretical one. This experimental method proofs the correctness of the concurrent program in a distributed embedded environment. The method does not guarantee the total correctness, but it is the best approach to reach the proposed solution. The work is divided six chapters. We beginning with the quick revision of the background of parallel and distributed simulation, thorough the related work of theoretical methods of testing and verification of software overview, and concluding with a case study, conclusion, and future work.

Chapter 2

Related Work

2.1.

Background Simulation

of

Parallel

and

Distributed

Two major classes of simulation exist, the analytical as-fast-as-possible simulations and the real-time ones. Both of these have wide variety of applications. Real-time simulations are used in (distributed) virtual environments. These environments enable effective training and education. Real time is also required when the simulation interacts with physical hardware components. The research in real-time simulation is widely supported by military organizations in many countries, as they are often used to simulate different war scenarios and training soldiers. The as-fast-as-possible analytical simulation is used to analyze various systems, to create prototypes, to forecast system behavior, to collect statistical data and for many other purposes. It is supported and developed mostly at universities. In both of these areas, parallel or distributed computation is often required, although the computational power of single processors grows continuously. Widely accepted paradigms and standards for the parallel and distributed simulation execution emerged over time, and they are continuously improved. We introduce the leading frameworks used in real-time and analytical simulations.

2.1.1.

Analytical Simulation

In the widely used concept [17] a Parallel Discrete Event Simulation (PDES) consists of logical processes (LP). Each LP models some portion of the analyzed system (for example a server in open queuing network model). The LPs can be mapped to different processors to enable parallel or distributed computation. Each LP processes events stored in its calendar like a sequential simulator in non-decreasing timestamp order. This computation results in changes of the LPs state and possibly scheduling new events. These new events can be scheduled for the same LP, but they can also be scheduled for other LPs by sending them a message containing the event and its timestamp. As the LPs

can schedule events for other LPs, some synchronization mechanism is needed to prevent the situation where a LP receives an event with a timestamp lower than its local simulation time (see [18] for the explanation of differences between physical, simulation and wall clock time) a LP can process its events faster and run ahead of the other LPs. Two major classes of synchronization protocols exist today (somewhat similar to transaction processing in databases): Conservative synchronization Optimistic synchronization

The first and older are the conservative protocols that try to avoid the possibility to receive an event in the LPs past. The second class are the optimistic protocols that do not prevent the reception of an event in the past, but instead they detect this situation and recover from it by rolling back the LPs computed events with timestamps greater than the received event. Conservative Synchronization The conservative protocols avoid the possibility of receiving an event in the past. This basic protocol assumes that the reliable communication channels between LPs are known before the execution and the event messages are sent over these channels in nondecreasing timestamp order. LPs process their events with the smallest timestamp. The event computation is allowed only if the timestamp of the processed event is smaller or equal to the smallest timestamp of all channels from which the LP can receive additional events. This however can lead to a deadlock situation where each LP will wait on other LPs because its local events will have greater timestamps than the minimum timestamp of all the communication channels. The first conservative protocols used null messages to avoid the deadlock. A null message is an empty message with a timestamp that LP sends to other LPs. By sending this message the LP promises that the further messages will have timestamps greater or equal than the timestamp of the null message (messages in a channel must be in non-decreasing timestamp order). The null messages increase the timestamps of the channels and eventually some events become ready to be processed the deadlock is avoided. Important for sending the null messages is the value of lookahead. Lookahead is a minimum time increment for a LP. If the LPs local simulation time is T, then the earliest time of a future event that this LP can schedule will be T+ L (where L is the value of lookahead). Consider a traffic simulation where the LPs represent crossroads and events are the car arrivals and departures. The lookahead may be the value that takes the car to travel from one crossroad to another. The disadvantage of the null-message algorithm is that these messages may introduce big overhead, especially with small values of lookahead. Many protocols were designed to avoid this problem and increase the performance (see [18] for extensive review). These include sending the null messages only on request, allowing deadlock and

recovering from it, synchronous execution using global barrier synchronization, time windows and other. The lookahead however complicates the design of the simulation model. It is not trivial to design a model with good lookahead properties. The performance of conservative synchronization is dependent on lookahead models with bad lookahead properties have bad performance. Optimistic Synchronization Optimistic synchronization protocols do not prevent the possibility of receiving events scheduled to the past. Single LPs process events from their calendars optimistically without waiting for the possibly incoming events from other LPs. This however can result in a situation where an event arrives with a timestamp lower than the local simulation time of the LP (called often straggler), violating the local causality constraint. This situation must be solved by rolling back (undoing) the computation of all events with timestamps greater than the timestamp of the straggler.

s a

v e

s t a

t e

v e p u

n r o n p

l i s t c e r o

( c a d

le e d

n v e

d n

a t

r )

s s e

c e s s e

v e

o u t p u t q u e u e ( a n t im e s s a g e

s )

s t r a g g le r m e s s a g e

( o

r d

r )

Figure 1: Local control mechanism in optimistic synchronization protocols Figure 1 shows the local control mechanism of LPs in optimistic protocols. The LP computes events from the event list in increasing timestamp order. Before the computation of the event the state of the LP is saved for the case of rollback. When the LP sends a message with new event, it stores anti-message in the output queue. In the case of rollback, the anti-messages are sent to the target LPs where the positive messages were sent previously. On receipt of the anti-message the LP removes corresponding unprocessed event from its event list (so called annihilation) or initiates rollback to a time prior the timestamp of the anti-message.

The output queues and saved states consume memory and thus a global synchronization mechanism is needed to determine when it is safe to reclaim the memory. This memory reclamation is called fossil collection. It is safe to reclaim only the memory occupied by events that will not possibly be subject of rollback. The events will never be rolled back if their timestamps are lower than the minimum timestamp of all unprocessed events and messages in the whole system. This time is called Global Virtual Time (GVT). The optimistic synchronization was first introduced by Jefferson [18], [19]. Since that time various enhancements regarding the state saving and GVT computation were developed. Two major classes of state saving mechanisms exist checkpointing and incremental methods. In the checkpointing a whole state is saved either before each event or before each n-th event. In the case of rollback the state is immediately available in the saved copy. The incremental methods save only the changed portions of the state with each event, thus saving memory, but in the case of rollback the state must be reconstructed by reading the saved changes in reverse order. Franks et al. [20] introduced new state saving scheme for interactive simulators that offers bounded state reconstruction time. Other new approaches include using reverse computation to reconstruct the state [21] and automatically adjust the parameters using changepoint detection [22]. In [17] a comprehensive review of various mechanisms is available. Comparison of various algorithms can be found in [23] A novel approach to increase performance of both conservative and optimistic synchronization protocols was recently presented by Chen and Szymanski [24, 25]. The basic concept of this approach is lookback. Lookback is the ability of a LP to execute events that are out of the timestamp order, scheduled in the past (see [24] for formal definition). For example in optimistic protocols the straggler event can be processed without causing the rollback.

2.1.2.

Virtual Environments and Real-Time Simulation

One of the key purposes of real-time simulation technologies is to construct Distributed Virtual Environments (DVE). These environments allow to train people (human-in-the-loop) or to test hardware components (hardware-in-the-loop). DVEs often include high resolution animations that depict the simulated world. The application area is very wide, from various vehicle simulators (automobiles, mobile crane [26] and others), virtual surgical operations in medicine (for example vascular reconstruction, [27]), space operations [28], to various military war games and training. DVEs are also increasingly used for entertainment in many multiplayer and MMORPG (Massive Multiplayer On-line Role Playing Games) games where thousands of users can interact with the DVE [29, 30]. The DVEs allow participants from geographically distributed places (even between continents) to participate in the same simulation and thus reduce additional cost (e.g. transportation). The human participants are integral parts of the DVE, in contrast to the analytical simulations, that can be non-interactive or the humans are not such integrated into the

10

simulation. The goal of the analytical simulations is to provide accurate and exact data of the simulated system. In DVEs the goal is to provide realistic perception of the environment to the participants. The real-time performance and high responsiveness is often more important than the exactness. The DVEs can exploit the limitations of human perception, for example if more events happen closely in time, they can be executed in any order and the exact synchronization is not required, because humans will perceive them as if they happened at once. To save communication overhead and increase the real-time performance, the updates of the state of entities in DVE may be less frequent and the state can be extrapolated using the saved history (dead reckoning). High Level Architecture (HLA) HLA was proposed by Defense Modeling and Simulation Office (DMSO) at Department of Defense (DoD) of USA to set standards and rules for creation of interoperable distributed simulations [31]. The HLA framework was later approved by IEEE as open standard (IEEE 1516). Basic structure of HLA distributed simulation is shown in Figure 2 (DMSO RTI 1.3.5). For a comprehensive review of the architecture see [17].

I E

x e c

r a

t i o n F

r a

t i o

I n F F e d e r Fa et e d e

t e e r a d

r - P e

r o

c e n r a F

s s

u n

i c a

t io

r a t i o d e

tF e e

t e e d E x e F c e d e r a t i o n

l i b R

Il i b R I n t e

T r - P

I r o

l i b R

I C o m m u n i c a t i o n

c e s s

Figure 2: Structure of the HLA simulation HLA distributed simulation consist of components called federates. Two or more federates together form federation. The synchronization and data exchange is accomplished by Run-Time Infrastructure (RTI) software (gray components in Figure 2).

11

Federations are managed by Federation Executive (FedExec). The whole RTI is managed by RTI Executive (RTIExec). The HLA standard comprises of three components: Federation rules define the rules that all the federations and federate must follow. Interface specification specification of the interfaces between federates and the RTI. Object Model Template specifies the format and syntax for describing the objects in HLA models. The RTI services are grouped into six categories: Federation management services for federation creation, destroying and management. Time management services that, implement various synchronization policies to allow advancing logical time. Declaration management publication and subscription of object instances and their attributes Object management object management functions at producer and receiver sites, interaction between objects. Ownership management. Data distribution management data distribution according to declared interests.

The main objective of HLA is to provide standards for interoperability and reusability of simulations. The framework allows constructing simulations distributed over multiple nodes. It is often used as a base for distributed virtual environments and real-time simulation. It also offers the possibility to build heterogeneous simulations where some of the components are represented by physical hardware [32].

12

2.2.

Best Known Theoretical Methods of Testing and Verification of Software Overview

Here we introduce several theoretical methods of modeling.

2.2.1.

Petri Nets

A Petri net is a graphical and mathematical modeling tool. It consists of places, transitions, and arcs that connect them. Input arcs connect places with transitions, while output arcs start at a transition and end at a place. There are other types of arcs, e.g. inhibitor arcs. Places can contain tokens; the current state of the modeled system (the marking) is given by the number (and type if the tokens are distinguishable) of tokens in each place. Transitions are active components. They model activities which can occur (the transition fires), thus changing the state of the system (the marking of the Petri net). Transitions are only allowed to fire if they are enabled, which means that all the preconditions for the activity must be fulfilled (there are enough tokens available in the input places). When the transition fires, it removes tokens from its input places and adds some at all of its output places. The number of tokens removed / added depends on the cardinality of each arc. The interactive firing of transitions in subsequent markings is called token game. Petri nets are a promising tool for describing and studying systems that are characterized as being concurrent, asynchronous, distributed, parallel, nondeterministic, and/or stochastic. As a graphical tool, Petri nets can be used as a visual-communication aid similar to flow charts, block diagrams, and networks. In addition, tokens are used in these nets to simulate the dynamic and concurrent activities of systems. As a mathematical tool, it is possible to set up state equations, algebraic equations, and other mathematical models governing the behavior of systems. To study performance and dependability issues of systems it is necessary to include a timing concept into the model. There are several possibilities to do this for a Petri net; however, the most common way is to associate a firing delay with each transition. This delay specifies the time that the transition has to be enabled, before it can actually fire. If the delay is a random distribution function, the resulting net class is called stochastic Petri net. Different types of transitions can be distinguished depending on their associated delay, for instance immediate transitions (no delay), exponential transitions (delay is an exponential distribution), and deterministic transitions (delay is fixed). The concept of Petri nets has its origin in Carl Adam Petri's dissertation Kommunikation mit Automaten, submitted in 1962 to the faculty of Mathematics and Physics at the Technische Universitt Darmstadt, Germany.[4]

2.2.2.

Calculus

13

The Calculus is a process algebra where processes interact by sending communication links to each other. It was developed by Robin Milner in early 1990s as a successor to his CSS language. The Calculus takes the idea of synchronous communication of processes over named channels. The basic computational step is the transfer of a communication link between two processes; the recipient can then use the link for further interaction with other parties. This makes the calculus suitable for modeling systems where the accessible resources vary over time. It also provides a significant expressive power since the notions of access and resource underlie much of the theory of concurrent computation, in the same way as the more abstract and mathematically tractable concept of a function underlies functional computation. Semantics of the Calculus is described in [5]

2.2.3.

LTSA Labeled Transition System Analyzer

LTSA is a verification tool for concurrent systems development. It mechanically checks that the specification of a concurrent system satisfies the properties required of its behavior. It was developed by Jeff Magee and Jeff Kramer. LTSA can be downloaded from [6].

2.2.4.

The Model Checker SPIN Checking Formal Models

SPIN is an efficient verification system for models of distributed software systems. It has been used to detect design errors in applications ranging from high-level descriptions of distributed algorithms to detailed code for controlling telephone exchanges. It supports the design and verification of asynchronous process systems. The verification is mainly focused on proving the correctness of process interaction, specified either with randezvouz primitives or with asynchronous message passing through buffered channels, or access to shared variables or any combination of these. More information about the SPIN see [7].

2.2.5. Java PathFinder 1 Constructing Formal Models from Java Multithreaded Programs
Java PathFinder [8], Jpf, is a prototype translator from Java to Promela, the modeling language of the Spin model checker [9]. Jpf is a product of a major effort by the Automated Software Engineering group at NASA Ames to make model checking technology part of the software process. Experience has shown that severe bugs can be found in final code using this technique [10], and that automated translation from a programming language to a modeling language like Promela can help reducing the effort required. Jpf allows a programmer to annotate his Java program with assertions and verify them using the Spin model checker. In addition, deadlocks can be identified. An assertion is written

14

as a call to an assert method defined in a predefined Java class, the Verify class. The argument to the method is a boolean Java expression over the state variables. The Verify class contains additional temporal logic methods which allow to state temporal logic properties about static variables. Hence Java itself is used as the specification language. An application of Jpf is described elsewhere in the proceedings [11]. A respectable subset of Java is covered by Jpf, including dynamic object creation, object references as first class citizens, inheritance, exceptions, interrupts, and perhaps most importantly: thread operations. Among major concepts not translated are: packages, method overloading and overriding, method recursion, strings, and floating point numbers. Finally, the class library is not translated.

2.2.6. Bandera Model Checking Properties of Concurrent Java Software


Bandera enables the automatic extraction of safe, compact finite-state models from program source code. Bandera takes as input Java source code and generates a program model in the input language of one of several existing verification tools: Bandera also maps verifier outputs back to the original source code. A more detailed information can be found in [12], [13] or downloaded from
http://bandera.projects.cis.ksu.edu/papers/index.shtml.

2.2.7. The

Model Checker Concurrent Systems

VeriSoft

Checking

UNIX

VeriSoft model checker is a verification tool for methodical examination of the state space of systems composed of numerous concurrent processes executing randomly C programs. The heart of the checker is the scheduler, which systematically drives the system along all possible paths, building up the computation tree as it goes. Because the system is checked directly, in principle no abstraction is required. However, the user is required to write processes that simulate the environment, and this may require abstracting away aspects of the environment, like infinite-domain data. As the scheduler drives the system, it reports bad behaviors such as deadlocks and assertion violations. Checking of general temporal logic formulas is not supported. A description of Verisotf model checker can be found in [14].

2.2.8. An Executable Model of Java Programs The ExitBlock Algorithm


ExitBlock systematically and deterministically finds program errors resulting from unintended timing dependencies. ExitBlock executes a program or a portion of a program

15

on a given input multiple times, enumerating meaningful schedules in order to cover all program behaviors. Applying to the Java programs , ExitBlock enumerates all possible behaviors of a Java multithreaded program for a given input. It does not need a separate model or specification of the tested program or its source code, it does the testing dynamically using information gathered while running the program. More detailed information see [15], [16].

2.2.9. Java PathFinder 2 Executable Models of the Java Virtual Machine


Java PathFinder 2 is an explicit-state model checker for programs written in Java. It is itself written in Java and contains a special-purpose Java virtual machine MC-JVM. The brief description can be founded in [16]. JPF2 works directly with Java bytecode, not with source code, as its predecessor.

Chapter 3

Model Architecture Overview


In a previous work [36] is explained a model of testing an verification of Java concurrent control programs aimed to embedded devices, in where threads of the control program are mapped onto a simulation process that can be executed using discrete model-time concept. This model is accomplished by using the J-Sim program simulation of the surrounding environment and the model of the simulation itself, even before the real hardware is developed. The extension of this task to a distributed embedded simulation model is the aim of this work. Roughly, in order to reach this objective we must create the model of the communication interface between a node and network. For that reason, first we present a model structure of a node, followed by the model of the network and describing the methods and classes that we are going to use.

16

3.1.

Model Structure

In this section, we describe the structure of the simulation. We have N-nodes in the network. The nodes represent a processor or a device that we want to simulate. Let us show in the first place, the structure of a node:

3.1.1 Structure of a node


In the figure showed below, we present the structure of a node of the distributed embedded simulation. As we said before, we need two kinds of interface connection (IC). One of them, between the node and hardware (registers) that is achieved through the Java Native Interface (JNI), which read/write data from/to controlled hardware, registers. (e.g. tank, pumps and sensors). The second one is used to communicate to the network, for that purpose we take in account the medium and buffers. Is important to take into account that we have two kinds of nodes, 1-node for the main tank and N-nodes for the stations. (See figure 3).

IC to Network A B Application (Java + JiJ) A B

Network Network Model (medium + buffers)

Hardware Model (registers)

IC to HW computer Figure 3. The model of a node in the network

Model Controlled Environment (tank, pumps, sensors)

3.1.2. Model of the Network


In this section we will concentrate in emphasizing the differences between two models of network, in order to decide which of them better suits with our goals.

17

3.1.2.1. Master Slave Network Protocol Master Slave protocol, is a strategy for node communication in where a single master device allots time slots for all the other nodes on the network to transmit, and schedules these time slots so that multiple nodes cannot collide. The master device addresses each node by name, one at a time, letting that node talk for a certain amount of time. When it is finished, the master addresses the next node, and so on, and so on. [37]. See figure 4.
Master

Bus

Node 1

Node 2

Node n

Figure 4. Master Slave Network Protocol In this contest the master node might have the following functions: Sender(sendDatagram), master sends a message to all the nodes e.g. if all the nodes are working correctly (e.g. the level of water is not under or above the limits, or if are there at least K working bombs, etc.) see Case Study. A first approach of the Java code for this task is showed in figure 5.

import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Sender { publ i c stat i c void main(Str i ng [ ] args) { try { /* sending data structures initialization */ InetAddress receiverHost = InetAddress.getByName("localhost"); DatagramSocket mySendSocket = new DatagramSocket() ; String message = "Hi there! How do you do!?"; byte msgBytes[] = message.getBytes(); /* creation of a test datagram */ DatagramPacket sendDatagram = new DatagramPacket( msgBytes, msgBytes.length, receiverHost, 54321 ); /* sending of the previously created test datagram */

18

System.out.println("Sending: " + message); mySendSocket.send(sendDatagram); mySendSocket.close(); /* receiving data structures initialization */ DatagramSocket myReceiveSocket = new DatagramSocket(12345); byte buffer[] = new byte[50]; DatagramPacket recvDatagram = new DatagramPacket(buffer, 50); /* receiving answer for the test datagram */ System.out.println("Listening..."); myReceiveSocket.receive(recvDatagram); System.out.println(new String(buffer)); myReceiveSocket.close(); } catch (Exception e) { e.printStackTrace(); } } }

Figure 5. Code for Sender at Master Side

Receiver(recvDatagram), all nodes answering to the send message of the master node. Master node evaluates all the responses and does the correction if it is necessary (e.g. turn the pump off/on in order to control the water level in each water station). Also a first approach of the Java code for this task is showed in figure 6.

import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Receiver { public static void main(String[] args) { try { /* receiving data structures initialization */ DatagramSocket myReceiveSocket = new DatagramSocket(54321); byte buffer[] = new byte[50]; DatagramPacket recvDatagram = new DatagramPacket(buffer, 50); /* receiving of a test datagram */ System.out.println("Listening..."); myReceiveSocket.receive(recvDatagram); System.out.println(new String(buffer)); myReceiveSocket.close();

19

/* Wait a moment so that a receiver is ready */ Thread.sleep(1000); /* sending data structures initialization */ InetAddress receiverHost = InetAddress.getByName("localhost"); DatagramSocket mySendSocket = new DatagramSocket(); String message = "Hi! I am fine :-) Thanks."; byte msgBytes[] = message.getBytes(); /* creation of an answer for the test datagram */ DatagramPacket sendDatagram = new DatagramPacket( msgBytes, msgBytes.length, receiverHost, 12345 ); /* sending an answer for the test datagram */ System.out.println("Sending: " + message); mySendSocket.send(sendDatagram); mySendSocket.close(); } catch (Exception e) { e.printStackTrace(); } } }

Figure 6. Code for Receive at Master Side

Each node will have the following functions: Acknowledge(respDatagram), message was received without troubles. Response(acknDatagram), send message to the master node, responding for the claimed task. The code will be similarly to Sender and Receiver classes. 3.1.2.2. Multi Master Network Protocol Multi Master protocol, where each node gets a turn to talk (one at a time), and then grants permission for the next node to talk when it is done. Permission to talk is passed around from node to node as each one hands off the "token" to the next in sequential order. The token itself is not a physical thing: it is a series of binary 1's and 0's broadcast on the network, carrying a specific address of the next node permitted to talk. Although token-passing protocol is often associated with ring-topology networks, it is not restricted to any topology in particular. Moreover, when this protocol is implemented in a ring network, the sequence of token passing does not have to follow the physical connection sequence of the ring. [38]. See figure 7.

20

Node 1

Token

Node 8

Node 2

Bus Node 7 Node 3

Node 6 Node 5

Node 4

Figure 7. Multi-master Network Protocol

In the Multi-master model the communication among the nodes will be achievable through message passing paradigm. There are two types of this paradigm, synchronous and asynchronous. We well explain the advantages an disadvantages of each one, concluding that in our proposed model the asynchronous one suits better our model.

3.1.2.2.1. Synchronous Message Passing The program that initiates the send (receive) waits until the send (receive) is complete. This waiting is called blocking. Completion of a send only means that the message buffer can be reused and does not imply that the message has been received. ssend() and srecv() are the synchronous send and receive system calls. This model suits better in a tightly coupled computer environment where there is a multiprocessor system sharing memory. But in the distributed setting synchronous external calls seem less satisfactory; at best resulting in inefficient use of processor capacity, at worst resulting in deadlock. Furthermore, it is difficult to combine active and passive behavior in concurrent objects. It is clearly less suitable in a distributed setting with loosely coupled components. [39]. 3.1.2.2.2 Asynchronous Message Passing

21

In the other hand, asynchronous message passing gives better control and efficiency, but lacks the structure and discipline inherent in method calls. The integration of the message concept in the object-oriented setting is unsettled, especially with respect to inheritance and redefinition. An object offers methods to its environment, specified through a number of interfaces and co-interfaces. All interaction with an object happens through method calls. In the asynchronous setting method, calls can always be emitted, because the receiving object cannot block communication. Method overtaking is allowed: if methods offered by an object are invoked in one order, the object may start the method instances in another order. A method instance is, roughly speaking, program code with nested processor release points, evaluated in the context of local variables. Due to the possible interleaving of different method executions, the values of an objects program variables are not entirely controlled by a method instance, which suspends itself before completion. A method may have local variables supplementing the object variables. In particular, the values of formal parameters are stored locally, but other local variables may also been created. asend() and areceive() are the asynchronous send and receive system calls. An asynchronous send or receive does not block. It returns a unique message id, which can be used later to check for completion of the message. Implementation of Asynchronous Message Passing In order to follow the develop of this method, we have to take into account several conditions:

Conditions

Tested media is a serial bus. We will use an asynchronous message passing. In this case there are two alternatives: blocked and unblocked asend(), areceive() functions. For the simplicity let get the unblocked situation. Node addresses are integer numbers in the interval 1 to n. We transmit a frame of fixed length of 256 bytes (for example).(see figure 5)

22

Each node has one unlimited buffer for sending and one for receiving. Multiple access (M.A.) is implemented in the same way as in Ethernet it is when a medium is occupied then the station is randomly waiting for a period of time.

Program solution

We build an abstract class NetworkInterface (Java IC) in that two functions are built. Figure 6-A.

asend( adrNode, frame)

adrNode = 0, broadcast. adrNode = 0, accept each message. return null = nothing is incoming.

frame areceive(adrNode)

Type Frame

Address 1-n Index connection 256 bytes of data

23

Figure 8. Architecture of a Frame

Implementation (model) (5 classes) (figure 6-B) Frame sent message sendBuffer passive object is composed by: message queue for sending reference to sending thread SendThread

Application

Network Interface

Network model

A Figure 9. Model Interfaces

24

Implementation of asend(). Put one frame to buffer (queue) and awakes the thread. Function (method) transmitFrame(RecBuffer buf) uses sending thread to own transfer message.

Implementation of SendThread and ReceiveBuffer SendThread . This is a thread that sends message (J-Sim process), contains: Reference to own buffer of type SendBuffer. Reference to shared objects serial bus. Method run() (J-Sim), which follows algorithm: 1. Takes a message from sendBuffer. ( if there arent then passivate() ) (Jsim). 2. Test serialBus, if bus is free then gives the address (reference) from receive buffer then 3, else 4 3. Hold(sending time), transmitFrame(receiveBuffer), free seriaBus release() goto 1 4. If not free then hold(randomize time) then goto 2 ReceiveBuffer. Receiving buffer (analogous like SendBuffer) (thinking!!!) SerialBus. (One for the entire network model). Serial bus model is passive and has: Attribute occupied bus, type Boolean Reference array to receiving buffers Method RecBufferTestBus( int adrNode) (returns either null or occupied, or reference to buffer, then we can start sending). Method releaseBus() release bus when transmission ends. See figure 10.

25

Network IC
1 SendBuffer

Application 1 HW IC Network IC HW IC Application 2

1 ReceiveBuffer 1 SendThread

S E R I A L B U S

1 SendBuffer 1 ReceiveBuffer 1 SendThread

Network model

Figure 10. Model for two nodes

Connections is done by Java references

Connection Network Model

n Application

Communication Communication Communication Controller Controller Controller Model Model Model

Network IC Network Model

Figure 11. Model for N-nodes 26

Chapter 4

Control Program Verification Procedure

4.1. The Verification Procedure


The verification procedure is strongly application dependent, so we can only give some general recommendation here. Generally, the procedure is similar as when testing the control program within its real-world environment, i.e. a well-chosen set of activity scenarios (tests) is developed and then executed. Let us assume a non-stop activity of the overall system. Then the model of environment should issue a (very long) stream of (possibly random) events that the control program should cope with. The model-based execution gives us the possibility of arbitrarily detailed observation of the execution process without a probe effect, i.e. the model-time dynamics of the modeled system is not influenced by the observation. The execution can be deterministically repeated as well, even when a random sequence of events is used to stimulate the control program activity. We have two basic possibilities what to follow during a model-based test execution:

27

4.2.1. The State Invariants


State invariants, i.e. conditions that should apply all the time of execution (or more generally within a bounded part of the model execution). These invariants can be constructed using variables (objects states) from both the control program and environment parts of the simulation model. As for the timing of invariants evaluation we have two possibilities again: to do it either with every change of the model state (i.e. after every step of the dicrete-time simulation run) or regularly using a special Sample and Evaluate simulation process.

4.2.2. The Behavioral Protocols


Behavioral protocols, i.e. rules that should apply for a sequence of events (possibly including their timing) at the control interface. Clearly, the problem of the performed tests number and length (diagnostic coverage, completeness) stays open similarly as when we are testing the program at a real device. But here we have extended possibilities of the tests organization (e.g. the possibility to use a wild environment activity or to change randomly the control program timing in order to reveal race conditions). The possibility of the model activity observation and investigation is better here as well, what means that the number (and the coverage) of the tests performed can be extended in this case.

28

Chapter 5

Case Study
A case study has been development. It is an abstract embedded application that controls water level of a water station tank and several connected water sources (see figure 12). The first prototype was theoretically and practically developed in [33]. Here we concentrate our effort in the distributed embedded application form. Then we have to use two kinds of computer-environment interface control interface (i.e. between a computer node and its part of controlled device) as well as network interface (i.e. a serial bus interface). Obviously, the model complexity will arise fast, because the model should include all the nodes of distributed system and a sub-model of communication protocol as well [34].

29

Water Station
High level

sensor

Low level

sensor sensor flow

full

High level Low level

sensor sensor actuator


Input flow Source N instances Source To village (random consumption)

Figure 12. Case Study Overview of the Controlled Water System

Chapter 6

Conclusion and Future Work


Further work will be focused mainly on customization of the Java source code conversion tool for purposes of this project and also on the J-Sim JiJ (Java in Java) sub package improvements and extensions. The set of demonstration applications will be extended in order to gain more experience. We plan to extend this set for distributed environment using e.g. CAN (Controlled Area Network) or TTP (Time Triggered Protocol) serial bus based control application as well. The Controller Area Network (CAN) and the Time-Triggered Protocol (TTP) are two fundamentally different communication protocols for the design of distributed real-time systems. CAN belong to the class of event triggered protocols where the class of event-triggered protocol where the temporal control signals is derived primarily from non-time events occurring outside

30

or inside the computer system. CAN was originally developed for non-safety critical body-electronics applications within vehicles. TTP belongs to the class of time triggeredprotocols, where the temporal control signals are solely derived from the progression of time. TTP was originally developed for high-dependability hard real-time applications, where timely error detection and fault-tolerance must be provided. We are currently study the background of CAN and TTP. The paper presents a method of a model based development and (partial) verification of concurrent Java-written control programs that are embedded within a device. The method combines model-time serialization of the control program threads with the conventional discrete time simulation of the control program environment. Unlike other existing methods, it is an experimental, method targeted on testing real Java code and not a theoretical system model. Moreover, the method does not require any especial Java virtual machine and is convenient for non-terminating programs running in a distributed environment. The method takes into account the control program environment behavior and tests both parts of the (designed) control system together which is completely omitted in other program verification approaches.

References
[1] Robert E. Shannon.: Introduction to Simulation Languages. Winter Simulation Conference. Proceedings of the 9th conference on Winter Simulation Volume 1. Gaitherburg, Maryland, United States. Pages 14-20. Publication year 1977. [2] Jean E. Sammet.: Programming Languages: history and future. Communications of the ACM, v.15 n.7, p.601-610, July 1972. [3] Jaroslav Kaer, Stanislav Racek.: Model Based Development of Java Embedded Applications, [Extended Abstract], Book of Abstracts of the 5th EuroSim Congress on Modeling and Simulation, EuroSim-FrancoSim-ArgeSim, Francie, z

31

2004 ISBN 3-901608-28-1, Strany: 84-85. [4] http://pdv.cs.tu-berlin.de/~azi/petri.html [5] Robin Milner: The Polyadic _-Calculus: A Tutorial. LFCS Report ECS-LFCS-91-80, Laboratory for Foundations of Computer Science, School of Informatics, University of Edinburgh, Edinburgh, UK, 1991. http://www.lfcs.inf.ed.ac.uk/reports/91/ECS-LFCS-91-180/ECS-LFCS-91-180.ps [6] Jeff Magee: LTSA Labeled Transition System Analyzer. University of London, Imperial College of Science Technology and Medicine, Department of Computing, London, UK, 1999. http://www-dse.doc.ic.ac.uk/concurrency/ltsa/LTSA.html [7] Gerard J. Holzmann: The Model Checker SPIN. IEEE Transactions on Software Engineering, Vol. 23, No. 5, 1997. http://spinroot.com/spin/Doc/ieee97.pdf [8] K. Havelund and T. Pressburger. Model Checking Java Programs using Java PathFinder. Appearing in International Journal on Software Tools for Technol ogy Transfer (STTT), 1999. [9] G. Holzmann. The Design and Protocols. Prentice Hall, 1991. Validation of Computer

[10] K. Havelund, M. Lowry, and J. Penix. Formal Analysis of a Space Craft Controller using SPIN. In G. Holzmann, E. Najm, and A. Serhrouchni, editors, Proceedings of the 4th SPIN workshop, Paris, France, November 1998. To appear in IEEE Transactions of Software Engineering. [11] K. Havelund and J. Skakkeb_k. Applying Model Checking in Java Verification. In R. Gerth, G. Holzmann, and S. Leue, editors, Proceedings of the 6th SPIN workshop (these proceedings), Toulouse, France, September 1999. [12] James C. Corbett, Mathew B. Dwyer, John Hatcliff, Shawn Laubach, Corina S. Pasareanu, Robby, Hongjun Zheng: Bandera: Extracting Finite-state Models from Java source Code. Proceedings of the 22nd International Conference on Software Engineering, 2000. http://www.cis.ksu.edu/santos/bandera/papers/bandera.pdf [13] John Hatcliff, Matwhew Dwyer: Using the Bandera Tool Set to Model-check Properties of Concurrent Java Software. Proceedings of CONCUR 2001

32

Concurrency Theory: 12th International Conference, Aalborg, Denmark, 2001. http://www.cis.ksu.edu/~hatcliff/Papers/ CONCUR01-tutorial.ps.gz [14] Patrice Godefroid: Model Checking for Programming Languages using VeriSoft. Proceedings of the 24th ACM Symposium on Principles of Programming Languages, Paris, France, 1997. http://www.belllabs.com/project/verisoft/popl97.ps [15] Derek Bruening: Systematic Testing of Multithreaded Java Programs. Masters Thesis, Massachusettes Institute of Technology, Cambridge, Massachusettes, USA, 1999. http://web.mit.edu/iye/www/docs/thesis.ps.gz [16] Derek Bruening, John Chapin: Systematic Testing of Multithreaded Programs. MIT/LCS Technical Memo, LCS-TM-607, Massachusetts Institute of Technology, Cambridge, Massachusettes, USA, 2000. http://web.mit.edu/iye/www/docs/testerTM607.ps.gz [17] R. M. Fujimoto: Parallel and Distributed Simulation Systems. Wiley Interscience, January, 2000

[18] D. R. Jefferson, H. Sowizral: Fast Concurrent Simulation using the Time Warp Mechanism. Technical Report N-1906-AF, RAND Corporation, 1982 [19] D. Jefferson, B. Beckman, F. Wieland, L. Blume, M. DiLoreto, P. Hontalas, P. Laroche, K. Sturdevant, J. Tupman, V. Warren, J. Wedel, H. Younger, S. Bellenot: Distributed Simulation and the Time Warp Operating System. In Proceedings of the 12th Symposium on Operating Systems Principles (SIGOPS), pp. 7793, 1987 [20] S. Franks, F. Gomes, B. Unger, J. Cleary: State Saving for Interactive Optimistic Simulation. In Proceedings of the 11th Workshop on Parallel and Distributed Simulation (PADS-97), pp 7279, 1997 [21] Ch. D. Carothers, K. S. Perumalla, R. M. Fujimoto: Efficient Optimistic Parallel Simulations using Reverse Computation. In ACM Transactions on Modeling and Computer Simulation 9(3), pp 224253, Jul 1999 [22] A. Kuratti: Improved Techniques for Parallel Discrete Event Simulation. Ph.D. thesis, University of Illinois at Urbana-Champaign, 1997 [23] E. Niewiadomska-Szynkiewicz, A. Sikora: Algorithms for Distributed Simulation Comparative Study. In Proceedings of the IEEE International Conference on Parallel Computing in Electrical Engineering (PARELEC02), 2002 [24] G. Chen, B. K. Szymanski: Lookback: A New Way of Exploiting Parallelism in Discrete Event Simulation. In Proceedings of the 16th Workshop on Parallel and Distributed Simulation, pp 143152, 2002 33

[25] G. Chen, B. K. Szymanski: Four Types of Lookback. In Proceedings of the 17th Workshop on Parallel and Distributed Simulation (PADS'03), pp 310, 2003 [26] J. Y. Huang, Ch. Y. Gau: Modelling and designing a low-cost high-fidelity mobile crane simulation. In International Journal of Human-Computer Studies 58, pp 151176, 2003 R. G. Belleman, R. Shulakov: High performance distributed simulation for interactive simulated vascular reconstruction, Computational Science - ICCS 2002, Proceedings Part III, in series Lecture Notes in Computer Science, vol. 2331, pp. 265274, 2002

[27]

[28] F. Dubuc: Distributed Interactive Simulation in Europe: The EDISON Project and Perspectives. In Proceedings of the 5th Workshop on Simulation for European Space Programmes (SESP98), 1998 [29] W. T. Cai, P. Xavier, S. J. Turner, B. S. Lee: A Scalable Architecture for Supporting Interactive Games on the Internet. In Proceedings of the 16th IEEE Workshop on Parallel and Distributed Simulation (PADS02), pp 6067, 2002

[30] J. Smed, T. Kaukoranta, H. Hakonen: A Review on Networking and Multiplayer Computer Games, Turku Centre of Computer Science Technical Report No. 454, April 2002 [31] Defense Modeling and Simulation Office: High Level Architecture homepage. https://www.dmso.mil/public/transition/hla/rti/ [32] R. Jokl, J. afak: From monolithic to HLA based model of a safety critical system [sta] / Roman Jokl, Ji afak. - In: 5th international carpathian control conference : Zakopane, Poland : May 25-28, 2004. - Krakow : AGH-UST, 2004. ISBN 83-89772-00-0. - S. 75-80 [33] Jaroslav Kaer.: Simulation-Based Checking of Java Concurrent Programs Ph.D. Thesis, consigned 2005-01-10, (waiting for reviews) University of West Bohemia in Pilsen, Faculty of Applied Sciences, Department of Computer Science and Engineering, Pilsen, Czech Republic, January 2005 Language: English.

[34] FIT Fault Injection for TTA. http://www.fit.zcu.cz [35] Kopetz H.: Real Time Systems, Design Principles for Distributed Embedded Applications. Kluwer Academic Publishers, 1997. [36] Jaroslav Kaer.: Model Based Development of Java Embedded Applications. Technical Report No. DCSE/TR-2004-03. Version 1. University of West Bohemia

34

in Pilsen, Faculty of Applied Sciences, Department of Computer Science and Engineering, Pilsen, Czech Republic, September 2004. Language: English. [37] Network Protocols. http://www.allaboutcircuits.com/vol_4/chpt_14/6.html [38] Einar Broch Johnsen and Olaf Owe. An Asynchronous Communication Model for Distributed Concurrent Objects Department of informatics, University of Oslo PO Box 1080 Blindern, N-0316 Oslo, Norway . Proceedings of the Second International Conference on Software Engineering and Formal Methods (SEFM04) 0-7695-2222-X/04 IEEE.

35

You might also like