Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach...

278
Frameworks for Implementing Protocols: a Model Based Approach Ciro de Barros Barbosa

Transcript of Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach...

Page 1: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

Frameworks for Implementing Protocols: a Model Based Approach

Ciro de Barros Barbosa

Page 2: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

ISBN 90-365-1434-7

Copyright © 2001 by C. de Barros Barbosa, Enschede, The Netherlands.All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, ortransmitted, in any form or by any means, electronic, mechanical, photocopying, recording, orotherwise, without prior written permission of the author.

CTIT Ph.D- thesis series, no. 01-33CTIT, P.O. Box 217, 7500 AE Enschede, The Netherlands

Page 3: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

FRAMEWORKS FOR IMPLEMENTING PROTOCOLS:

A MODEL BASED APPROACH

PROEFSCHRIFT

ter verkrijging van, de graad van doctor aan de Universiteit Twente,

op gezag van de rector magnificus,prof.dr. F.A. van Vught,

volgens besluit van het College voor Promotiesin het openbaar te verdedigen

op vrijdag 9 februari 2001 te 15.00 uur.

door

Ciro de Barros Barbosa

geboren op 4 januari 1965

te Barra Mansa, Brazilië

Page 4: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

Dit proefschrift is goedgekeurd door:

promotor prof. dr. ir. C.A. Vissers

assistent-promotor dr. Luís Ferreira Pires

Page 5: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

In memory of

Rafael Evaristo Barbosa (26.10.1910 - 27.5.1992, grandfather),Newton Gonçalves de Barros (13.7.1915 - 20.3.1997, uncle),

Nathercia de Barros (9.2.1919 - 14.8.1995, aunt),Nelly de Barros (25.10.1926 - 16.7.1998, aunt).

For the place these remarkable people gave me in their good hearts.

Page 6: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents
Page 7: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

i

Preface

This thesis investigates the use of frameworks to implement protocols for distributed systems,linking currently available design approaches based on formal methods to software engineeringmethods. Frameworks are software structures developed for a specific application domain. Theycan be re-used in the implementation of various concrete systems in this domain.

Distributed systems bring expressive benefits to society. Examples are production automationsystems, large scale communication systems (e.g.: telephone systems), business administrationsystems (e.g.: bank and stock-market control), medical systems (e.g.: On-line Patient Monitoringand Telemedicine), distributed embedded control systems (e.g.: robots and aircrafts), and Internet.Distributed systems are implemented by protocols that coordinate the communication and co-operation among system parts. Because applications of distributed systems are generally critical,requirements like reliability, security and performance are essential. Protocols must also be devel-oped efficiently and be easy to maintain, in order to address the constant demand for new func-tionality. To cope with such requirements in a competitive way, system developers needmethodologies and tools to support the protocol development process.

The protocol development process is usually carried out in two phases: functional design and soft-ware implementation. Some methods and tools that have been proposed to support protocol devel-opment apply formal methods to describe the protocol functional design, i.e., structure andbehaviour. Formal methods supply means for analysing properties and validate the system design.As such, formal methods contribute to produce correct protocol implementation and to evaluateits conformance to its specification.

The scope of our investigation is the implementation process. We strive to cover a broad range ofrequirements in this process. We consider three aspects that contribute to this broad range ofrequirements: 1) the design step of the development process may apply different design models;2) developments may be targeted to different implementation environments; and 3) different pri-orities may be attributed to strategic requirements.

Examples of strategic requirements are implementation effectiveness and quality of software.Aspects of software quality are execution performance, maintainability and portability.

In order to link our implementation method to design methods, we define a systematic way to mapthe design concepts of design models onto implementation constructs. Such implementation con-structs are used to build our frameworks and to define templates to map protocol dependent parts

Page 8: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

ii

Preface

onto implementation code that fits in the framework. Our mapping process preserves the protocolspecification structure in the implementation. This saves the learning effort to understand theimplementation for maintenance purpose.

Concerning the effectiveness of the implementation process there are two aspects to consider:first, once the frameworks are available, experience has shown that they can increase the speed ofthe implementation process [40][64]; second, a systematic approach for developing frameworksspeeds up the process of obtaining such frameworks and supplies the basis for developing compil-ers to produce implementations from specifications. Concrete compiler construction however, isbeyond the scope of this research.

To address the implementation maintenance issue, we use software engineering techniques, suchas object oriented programming and design patterns. These techniques provide extensible andreusable implementation code.

Different frameworks are required to support the implementation of protocols specified using dif-ferent design models. Besides that, the same design model may be supported by different frame-works applying different implementation techniques. This leeds us to a catalogue of frameworks.We develop in this thesis four frameworks that apply different implementation techniques andsupport different design models. They have been used to evaluate the benefits of frameworks andto make our method ready to be applied in practice. They can also be adapted to faster the devel-opment of new frameworks to support other design models.

In order to address execution performance issues, we consider alternative implementation solu-tions when building frameworks. Different implementation environments offer different imple-mentation constructs and a specific environment offers alternative implementation constructs forthe same purpose. We present a set of implementation solutions that support the most importantdesign constructs. Users of the frameworks can select solutions as they are presented here oradapt them to fit better to specific problems. Selecting a specific solution is done based on imple-mentation experience or comparing implementations that apply different solutions and evaluatingthem to determine which one is the best option.

In order to enforce implementation correctness, we strive to define a systematic implementationprocess. The final assessment of the implementation conformance is based on tests upon theresulting implementation code.

Although our approach is general enough to be applied to the implementation of protocols in dif-ferent implementation environments, we have decided to limit our experiments to SUN worksta-tions, running the Solaris operating system, and using the C++ programming language, for purepragmatic reasons.

As part of our research, and for the purpose of validating our objectives in practice, we have pro-totyped several experimental frameworks towards various degrees of completion. Three of theseframeworks have been substantially elaborated so that they can be demonstrated. These frame-works are described in this thesis in chapters 5, 6 and 7. Running code of these frameworks andsome implementation examples can be downloaded from [80].

The structure of the thesis is the following:

Page 9: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

iii

Chapter 1 - Introduction: discusses the context, motivation, objectives and approach of ourresearch. This chapter also briefly introduces the most important concepts that underlie thisresearch.

Chapter 2 - Applying Frameworks to Protocols: discusses the application of frameworks to theprotocol implementation process and describes our method to develop frameworks.

Chapter 3 - Functional Requirements: performs the domain analysis step of our framework devel-opment method, covering a comprehensive set of design concepts.

Chapter 4 - Implementation solutions: presents a set of implementation solutions for design con-cepts, by applying alternative implementation constructs. Such solutions are developed applyingobject-oriented programming techniques and design patterns.

Chapter 5 - Basic Event Manager Framework: presents a framework in which an event managerobject plays a central role.

Chapter 6 - Basic Multi-thread Framework: presents a framework that makes use of multi-thread-ing to implement the same design model as the one supported by the Basic Event Manager Frame-work.

Chapter 7 - Advanced Event Manager Framework: presents a framework that extends the BasicEvent Manager Framework, allowing more structured specifications to be implemented directly.

Chapter 8 - Sliding Window Protocol Implementation: presents a detailed example of the use offrameworks in the protocol development process.

Chapter 9 - OSPF Protocol Implementation: presents a case study on protocol implementation,discussing the use of the Advanced Event Manager Framework to implement the OSPF (OpenShortest Path First) protocol.

Chapter 10 - Correctness Assessment: discusses our testing approach to assess the correctness offramework implementations. This testing approach has been designed to assess the correctness ofthe frameworks, abstracting from the characteristics of any particular protocols that may be usedwhile performing the test, and focusing on the behaviour of the implementation of design con-cepts.

Chapter 11 - Conclusions: presents general conclusions about our implementation method, relatedwork and some ideas for future work.

Page 10: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

iv

Preface

Page 11: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

v

Acknowledgements

This work has been possible in the first place thanks to the financial support of the Brazilian Gov-ernment through CNPq, one of the Brazilian organizations responsible for promoting research.Financial support has also been provided by the Faculty of Informatica of the University ofTwente for an extension period of my work.

I would like to thank my promotor Prof.dr.ir. C.A. Vissers for making this work possible, accept-ing me in the research group he leads (Architecture Group) and for the key guidance in the execu-tion of my research.

Special thanks goes to my assistant promotor Dr. L. Ferreira Pires. His resolute and vigorousefforts to help me overcome difficulties and improve the quality of my work was vital and invalu-able.

I am also grateful to the members of my promotion committee, namely Prof.dr. P.M.G. Apers,Prof.dr.ir. I.G.M.M. Niemegeers, Prof.ir. E.F. Michiels, Prof.dr. W.L. Souza, Prof.dr. L.J.M. Nieu-wenhuis and Dr.ir. H. Bakker for the precious time they invested evaluating my work and gather-ing for the promotion ceremony.

A number of colleagues have also contributed to improve this work by means of inspiring discus-sions or reviewing earlier versions of my thesis, namely, Dick Quartel, Marten van Sinderen,Pedro R. D’Argenio, Alex M.R. Slingerland , Val Jones and Cléver R.G. de Farias.

The help of supporting personnel of my research group or from the faculty, namely Joke M.W.Lammerink, Ila Reinders, Helen A. Kool, Marlous J. Weghorst and the helpdesk staff has pro-vided an effective environment where the work could be done in a pleasant way.

Many people I met in the Netherlands helped me bring some warmth to the years I have livedabroad. For the sake of space I name just a few of them here, as to be complete I should list tensof names. Some of these great people are Pedro, Marcos, Glória, Évelin, Kelen, Cléver, Rajan,Xierong Song, Cristina, João Paulo, Annemieke, Marcelo, Alex, Nikolay, Guilhermo, Giancarlo,Val, Abdal and Cecília.

Finalmente eu gostaria de agradecer minha família que, apesar da distância, sempre me apoioucarinhosamente na realização desse sonho.

Ciro de Barros Barbosa

Page 12: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

vi

Acknowledgements

Page 13: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

vii

Table of Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Chapter 1Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.1 Research Context .....................................................................................................1

1.2 Protocol Design........................................................................................................2

1.3 Protocol Implementation..........................................................................................4

1.4 Research Objectives.................................................................................................5

1.5 Approach..................................................................................................................7

1.6 Scope and Limitations .............................................................................................9

1.7 Related Work ...........................................................................................................9

1.8 Thesis structure ......................................................................................................12

Chapter 2Applying Frameworks to Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.1 Introduction............................................................................................................15

2.2 Implementation Process .........................................................................................17

2.3 Framework Development Process .........................................................................192.3.1 Domain Analysis................................................................................................................20

2.3.2 Software Architecture Definition.......................................................................................24

2.3.3 Coding................................................................................................................................26

2.3.4 Documentation...................................................................................................................28

2.3.5 Conformance Assessment..................................................................................................28

Chapter 3Functional Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

3.1 Approach................................................................................................................31

3.2 Component.............................................................................................................323.2.1 ESTELLE Representation..................................................................................................33

3.2.2 LOTOS Representations ....................................................................................................34

3.2.3 SDL Representations .........................................................................................................34

3.3 Interaction Means ..................................................................................................35

Page 14: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

viii

Table of Contents

3.3.1 ESTELLE Representations................................................................................................ 36

3.3.2 LOTOS Representations.................................................................................................... 36

3.3.3 SDL Representations ......................................................................................................... 37

3.4 Behaviour ..............................................................................................................373.4.1 Behaviour Concepts .......................................................................................................... 37

3.4.2 ESTELLE Representations................................................................................................ 40

3.4.3 LOTOS Representation ..................................................................................................... 40

3.4.4 SDL Representations ......................................................................................................... 41

3.4.5 Time Based Event.............................................................................................................. 41

3.4.6 Behaviour Composition Relations..................................................................................... 43

3.5 Interactions ............................................................................................................473.5.1 Synchronous Interactions .................................................................................................. 47

3.5.2 Asynchronous Interactions ................................................................................................ 48

3.6 Design Models Consistency ..................................................................................48

Chapter 4Implementation Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

4.1 Approach ...............................................................................................................51

4.2 Event-driven and Parallel Behaviour.....................................................................534.2.1 Event Dispatcher Pattern ................................................................................................... 53

4.2.2 Multi-threading.................................................................................................................. 55

4.3 Behaviour Implementation ....................................................................................564.3.1 Nested Case-Statements .................................................................................................... 57

4.3.2 State Pattern....................................................................................................................... 59

4.3.3 Event Evaluation Cycle ..................................................................................................... 60

4.4 Interactions and Interaction Means .......................................................................614.4.1 Synchronous Interactions .................................................................................................. 61

4.4.2 Asynchronous Interactions ................................................................................................ 63

4.4.3 External Interaction Means ............................................................................................... 64

4.4.4 Timing Requirements ........................................................................................................ 67

4.5 Behaviour Composition.........................................................................................69

4.6 Boundary Conditions.............................................................................................704.6.1 Initialization and Termination ........................................................................................... 71

4.6.2 Exceptions ......................................................................................................................... 71

4.6.3 Consistency ....................................................................................................................... 72

4.7 General Components .............................................................................................72

4.8 Conclusions ...........................................................................................................73

Chapter 5Basic Event Manager Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

5.1 Approach ...............................................................................................................75

Page 15: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

ix

5.2 Domain Analysis....................................................................................................76

5.3 Software Architecture ...........................................................................................775.3.1 EventManager ....................................................................................................................78

5.3.2 EventHandler .....................................................................................................................79

5.3.3 EventPoint..........................................................................................................................84

5.3.4 Boundary conditions ..........................................................................................................88

5.3.5 Definition of classes...........................................................................................................89

5.3.6 Dynamic Behaviour ...........................................................................................................91

5.3.7 Consequences of Implementation Solutions......................................................................92

5.4 Usage Information .................................................................................................935.4.1 Constants Definition ..........................................................................................................93

5.4.2 External class Specialization .............................................................................................93

5.4.3 EventHandler Specialization..............................................................................................95

5.4.4 Entity Class ........................................................................................................................97

5.4.5 Template General Structure ...............................................................................................97

5.5 Implementation Example .......................................................................................98

5.6 Conclusions and Evaluation.................................................................................102

Chapter 6Basic Multi-thread Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

6.1 Approach..............................................................................................................107

6.2 Domain Analysis..................................................................................................108

6.3 Software architecture ...........................................................................................1086.3.1 EventHandler ...................................................................................................................109

6.3.2 EventPoint........................................................................................................................111

6.3.3 Handling Boundary Conditions .......................................................................................113

6.3.4 Definition of Classes........................................................................................................114

6.3.5 Dynamic Behaviour .........................................................................................................116

6.3.6 Consequences...................................................................................................................117

6.4 Usage Information ...............................................................................................1186.4.1 Mutexes and Condition Variables ....................................................................................118

6.4.2 Environment-Specific Code.............................................................................................119

6.4.3 EventHandler Specialization............................................................................................119

6.4.4 Entity Class ......................................................................................................................119

6.5 Implementation Example .....................................................................................120

6.6 Evaluation ............................................................................................................121

Chapter 7Advanced Event Manager Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

7.1 Approach..............................................................................................................123

7.2 Domain Analysis..................................................................................................124

Page 16: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

x

Table of Contents

7.2.1 Component ...................................................................................................................... 124

7.2.2 Behaviour Composition................................................................................................... 125

7.3 Software Architecture..........................................................................................1267.3.1 Class term ........................................................................................................................ 127

7.3.2 Class relation ................................................................................................................... 128

7.3.3 Class sequence................................................................................................................. 128

7.3.4 Class choice ..................................................................................................................... 129

7.3.5 Class interleaving ............................................................................................................ 129

7.3.6 Class behaviour ............................................................................................................... 130

7.3.7 Boundary Conditions....................................................................................................... 130

7.3.8 Definition of Classes ....................................................................................................... 131

7.3.9 Dynamic Behaviour......................................................................................................... 134

7.3.10 Consequences .................................................................................................................. 137

7.3.11 Alternative Implementation Solutions............................................................................. 138

7.4 Usage Information ...............................................................................................1397.4.1 Behaviour Composition................................................................................................... 139

7.4.2 Dynamic Manipulation of Components .......................................................................... 141

7.4.3 EventHandler Specialization ........................................................................................... 143

7.5 Implementation Example.....................................................................................144

7.6 Evaluation............................................................................................................147

Chapter 8Sliding Window Protocol Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

8.1 Introduction .........................................................................................................149

8.2 Protocol Description............................................................................................150

8.3 Protocol Specification .........................................................................................151

8.4 Refinement for Implementation ..........................................................................1568.4.1 Tool Supported refinement of LOTOS specification ...................................................... 156

8.4.2 Saving the Behaviour Structure....................................................................................... 158

8.5 Implementation using the Advanced Event Manager Framework ......................1598.5.1 TPE Implementation........................................................................................................ 160

8.5.2 RPE Implementation ...................................................................................................... 163

8.6 Conclusions .........................................................................................................168

Chapter 9OSPF Protocol Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

9.1 Introduction .........................................................................................................171

9.2 OSPF Protocol .....................................................................................................1739.2.1 Overview ......................................................................................................................... 173

9.2.2 Interface Function Operation........................................................................................... 175

9.2.3 Neighbour Function Operation........................................................................................ 175

9.2.4 Updating the Link-State Database................................................................................... 178

Page 17: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

xi

9.2.5 Reliable Flooding.............................................................................................................179

9.2.6 Routing-Table Calculation ...............................................................................................179

9.3 Protocol Design Structure ....................................................................................180

9.4 Protocol Implementation Structure ......................................................................1849.4.1 Interaction Point...............................................................................................................185

9.4.2 Behaviour.........................................................................................................................185

9.4.3 Dynamic Structuring........................................................................................................186

9.4.4 Coding Functions .............................................................................................................187

9.5 OSPF Implementation..........................................................................................1879.5.1 Constant Definitions (step 1) ...........................................................................................187

9.5.2 Specialization of External Class (step 2) .........................................................................188

9.5.3 Specialization of eventHandler class (step 3) ..................................................................188

9.5.4 Definition of the Initialization Class (step 4)...................................................................189

9.6 Conclusions..........................................................................................................189

Chapter 10Correctness Assessment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

10.1 Introduction..........................................................................................................191

10.2 Testing Approach .................................................................................................193

10.3 Design Concepts Specification ............................................................................195

10.4 Test Coverage.......................................................................................................197

10.5 The Tester Program..............................................................................................19910.5.1 Log and Pseudo-Events ...................................................................................................199

10.5.2 FSM Description..............................................................................................................200

10.5.3 Tester Algorithm ..............................................................................................................200

10.5.4 Tester Interface.................................................................................................................202

10.6 Testing Case Study...............................................................................................20510.6.1 Choice Relation................................................................................................................205

10.6.2 Synchronous Interaction ..................................................................................................210

10.7 Conclusions..........................................................................................................214

Chapter 11Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

11.1 General Conclusions ............................................................................................217

11.2 Evaluation of Results ...........................................................................................21811.2.1 Various Design Models ....................................................................................................218

11.2.2 Different Implementation Environments .........................................................................219

11.2.3 Flexibility of Requirements .............................................................................................219

11.3 Future Work .........................................................................................................219

References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

Page 18: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

xii

Table of Contents

Appendix A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

A.1 Global Structure...................................................................................................227

A.2 The Send/Receive Service ...................................................................................228

A.3 The Send/Receive Protocol .................................................................................228

A.4 Messages Flow ....................................................................................................230

A.5 Lower Level Service............................................................................................230

A.6 Configuration Information...................................................................................230

Appendix B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

B.1 Basic Event Manager Framework .......................................................................231

B.2 Basic Multi-thread Framework............................................................................236

B.3 Advanced Event Manager Framework ................................................................241

Appendix C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

C.1 Protocol Specification .........................................................................................247

Appendix D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255

D.1 Transmitter Process .............................................................................................255

D.2 Receiver Process..................................................................................................256

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

Page 19: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

1

Chapter 1

Introduction

This thesis investigates the use of frameworks to implement protocols for distributed systems,linking currently available design approaches, based on formal methods, to software engineeringmethods. Frameworks are software structures developed for a specific application domain, thatcan be re-used in the implementation of various concrete systems in this domain.

This chapter presents the context and motivation of our work. It clarifies a number of conceptswhich underlie this research, regarding their role in the context of this thesis. This chapterdescribes our objectives and the strategies we have applied to reach such objectives. It defines theissues we have addressed, and the ones beyond our scope. It presents an analysis of other develop-ment that give contributions in the same area, comparing the objectives and approaches of thesedevelopments with ours, in order to assess the degree of innovations of our contributions. Finally,we describe how this thesis is structured.

Section 1.1 presents the context of our research; sections 1.2 and 1.3 introduce the design andimplementation phases of protocol development, respectively, which form the background of thiswork; section 1.4 discusses our objectives; section 1.5 discusses the strategies we have applied toreach our objectives; section 1.6 describes the scope of our work; section 1.7 discusses somerelated developments and section 1.8 presents the structure of the thesis.

1.1 Research Context

The importance of distributed systems can be assessed by observing the benefits they bring to dif-ferent segments of our society. Some examples are production automation systems, large scalecommunication systems (e.g.: telephone companies), business administration systems (e.g.: bankand stock-market control), medical systems (e.g.: On-line Patient Monitoring and Telemedicine),distributed embedded control systems (e.g.: robots and aircrafts). Distributed systems are compu-tational systems consisting of distributed and interconnected processing nodes.

Distributed systems are implemented by protocols that coordinate the communication and cooper-ation among system parts. We focus our attention on the development process of such protocols.

Page 20: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2

Chapter 1: Introduction

Because most of the applications of distributed systems technology are critical, requirements likereliability, security and performance are essential.

Protocols must also have an efficient development process and be easy to extend and to maintain,in order to attend the constant demand for new functions. To cope with such requirements in acompetitive way, and considering the complexity of most practical systems, system developersneed methodologies and tools to support the protocol development process.

The protocol development process is usually carried out in two phases: design and implementa-tion. The protocol design phase can be supported by using formal methods, which are based onmathematical models to specify, verify and test systems. Formal methods supply the precisionrequired for analysing functional properties and performing validation on system properties, withthe objective to enforce correctness during the design phase. Such precision also contributes toproduce correct system implementations and provides the means to evaluate their conformance tothe related specification.

The scope of this work is the implementation phase of the protocol development process. Wework on an implementation process connected with design methods that use formal techniques.Therefore, the input for our implementation process is a specification of the system to be imple-mented that is written according to the rules of some formalism.

A lot of work has already been done on protocol implementation (see section 1.7). Yet we claimthat contributions the current methods can still be improuved towards a better balance betweeneffectiveness of the implementation process, implementation correctness, maintainability of theimplementation code and execution performance.

1.2 Protocol Design

The deliverable of the protocol design phase is an instance of a protocol specification that con-forms to the user requirements and can be given to an implementer. A protocol specification mustbe produced that enables communication between the system designer and the system user inorder to evaluate the designer’s correct understanding about the user requirements. This helps thedialogue between designer and user. Such specifications also play the role of a contract for theproduct that must be delivered.

While producing the protocol specification, we apply the concept of modelling. A model of a sys-tem is an abstraction of this system [82]. The model of a system considers only the characteristicsof the system which are relevant for the purpose of the modelling activity, while abstracting fromtechnical details which are not of concern. In our case, modelling helps us designing systems.

The production of an abstract specification of a protocol implicitly establishes standards for inter-operability among systems of different vendors. An abstract protocol specification lets industryapply their own skills, methods and tools, i.e., their design culture, to define technical details, forcompetition purpose.

In order to develop techniques for protocol design and specification, the basic characteristics ofprotocols must be identified. For that purpose we identify design concepts, which are abstractions

Page 21: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

1.2 Protocol Design

3

of such characteristics. A set of design concepts together with their combination rules define adesign model. The choice of a design model must be guided by design objectives and technicalneeds. In our context, an abstract instance of a protocol is called a design.

Designs have to be documented. This implies that specification languages are necessary, as anotation for representing designs in a concise, complete and unambiguous way. A specificationlanguage consists of notational elements that represent design concepts, the rules for their possi-ble combinations and the interpretation of such elements and rules, i.e., the semantics [58].

The formal semantics of a specification language is defined in terms of concepts of some mathe-matical model. Specification languages with formal semantics are called formal specification lan-guages. Formal specification languages are the basis for applying formal methods in the design ofprotocols.

The motivation for applying formal specification languages in protocol design are:

• it allows the unambiguous definition of systems characteristics in terms of the underlyingsemantics;

• it allows one to compare different specifications;

• it provides the basis for making automated tools for specification support and analysis of thedesign.

The design trajectory according to a top-down design approach [82] consists of creating newinstances of the protocol specification while working from specifications towards implementa-tion. Each new instance is produced at a new level of abstraction where more details are consid-ered. Several levels may be produced in the design trajectory such that details can be includedgradually.

Figure 1.1 illustrates an hierarchy of levels of design instances of a protocol.

In order to go from one abstraction level to another in the hierarchy of designs we need a notion toguarantee that one design conforms to another. This notion is called implementation relation. Aspecification language with a suitable collection of implementation relations and capable of repre-senting designs at many abstraction levels is called a design language.

Abstraction level n

Abstraction level n+1

Abstraction level n+2

design instance n

design instance n+1

design instance n+2

implementation relations

specification

implementation

(end-user oriented)

(machine oriented)

Figure 1.1 Hierarchy of design instances

Page 22: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4

Chapter 1: Introduction

Considering the current state-of-the-art in design languages, it is not possible to cover the wholedesign trajectory, from specification to implementation, by applying the same design language.At a certain point of the design trajectory one is forced to adopt a development approach that con-centrates on software implementation issues.

1.3 Protocol Implementation

We call an implementation an instance of design that can be executed in a specific processingnode of the distributed system. An implementation environment is a set of available resources,also called implementation constructs or implementation building blocks, in hardware, e.g., boardand buses, or software, e.g., programming languages and operating systems, that can be used toconstruct an implementation. We call the implementation process the trajectory that is necessaryto go from the lower level formal design instance to an executable implementation.

Issues that must be considered while producing an implementation are:

• available resources in the implementation environment (the ultimate building bricks);

• characteristics specific of some protocols (e.g., connection-oriented or connectionless);

• business strategical arguments;

• quality of software (maintainability, portability, performance, etc.)

Some protocols have special characteristics that require customising some parts of the implemen-tation. For example, some protocols may require more optimized solution for the buffering ofmessages, or an efficient solution for dynamic allocation of resources.

Business strategical arguments are mainly those that influence the priority for the different soft-ware quality requirements. For example, one may need to sacrifice performance in order to havethe implementation earlier in the market.

The maintainability of an implementation can be understood as the easiness of repair of an imple-mentation in case of implementation errors, easiness of extension to incorporate new functionsand easiness of re-usability of implementation parts to build new implementations. Portability isthe easiness of adaptation of an implementation to run in different implementation environments.By performance we mean how fast the implementation executes.

Since implementations have to cope with concerns that cannot be represented by most abstractdesign languages, a gap has to be bridged between design languages concepts and the concepts ofthe implementation level. There are, in general, two ways to overcome this problem, as suggestedin [23]:

• restrict the use of design concepts in the elaboration of a final specification to only those con-cepts that can be directly found in the target implementation environment;

• enhance the capabilities of the implementation environment, so that a set of key architecturalconcepts are already implemented, making the translation straightforward.

Page 23: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

1.4 Research Objectives

5

In order to enhance the capabilities of the implementation environment, coping with implementa-tion requirements, one should use implementation techniques developed by the software engi-neering community while adding implementation details to the specification. Software engineershave been developing analysis, design and implementation methods to cope with requirements ofdeveloping general purpose systems. This development culture stresses implementation require-ments and does not supply the benefits provided by formal based-approaches. Some examples ofimplementation techniques are object-oriented programming [61] [10] and design patterns [25].

The method for the development of protocols we have developed makes use of formal designtechniques already available, complemented by the implementation techniques of software engi-neering like the ones we have just mentioned.

1.4 Research Objectives

This thesis investigates the use of frameworks to implement protocols for distributed systems,linking currently available design approaches based on formal methods to software engineeringmethods.

We strive for defining an implementation process based on frameworks, and propose a systematicway to apply this process, considering different alternative characteristics of this process, whichare: 1) different design models may underlie the protocol specification that forms the input of theimplementation process; 2) the implementations may be targeted to different implementationenvironments; 3) different priorities for business strategic requirements may be assumed in differ-ent implementations.

Examples of strategic requirements are implementation effectiveness, quality of software and cor-rectness enforcement. The aspects we consider on quality of software are: execution performance,maintainability and portability.

Our method towards protocol implementation must define techniques that address the differentcharacteristics of the protocol implementation process, allowing the process to be tuned to reachthe most appropriate balance between requirements. Striving for a balance between requirementsis necessary because some of these requirements may contradict each other. For example, theremust be a balance between producing highly portable implementation code and dedicated highperformance code. Another trade-off exists between conformance and effectiveness aspects.Increasing the confidence in the conformance between specification and implementation maycompromise the effectiveness of the implementation process.

Extremely critical systems may demand an accurate and therefore time-consuming correctnessassessment method. Some other systems may rely on a faster approach that yields acceptableresults.

Keeping the commitment with maintainability conflicts with the performance requirement. Theexplicit support to structuring at implementation level imposes an execution overhead when com-pared to monolithic implementations.

Page 24: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6

Chapter 1: Introduction

Direct support of abstract concepts at the implementation level usually demands an extra effort inthe implementation. For example, the concept of multi-way synchronization interaction supportsspecification styles like the constraint-oriented specification style [69], but has a high cost inimplementation performance. Another example is the decomposition of a protocol in severalcomponents, possibly hierarchically related. This is a common structuring technique that maycompromise the performance.

Business strategy may require, for example, methods more suitable for environments where thechanges in the required protocol functions are frequent. This may demand a rapid developmentprocess, for rapid changes and corrections in the developed protocols.

Yet another strategic decision could be to pay the price in performance imposed by maintainabil-ity. Considering the fast development in hardware and the consequent improvement in the sys-tems performance, and the increasing costs of human resources necessary for such developments,some may claim this decision is worthwhile.

Figure 1.2 summarizes the dependencies among the elements of the protocol development proc-ess.

In Figure 1.2, rectangles with rounded corners represent the requirements of the protocol develop-ment process and normal rectangles represent the milestones of the development process. Weclassify functional requirements in specific and general requirements. Specific functional require-ments are those exclusively related to a particular protocol being implemented. General func-tional requirements are used as building blocks in the definition of many different protocols.These two classes of functional requirements determine the protocol specification and the designmodel used in the development process, respectively. We divide strategic requirements intoimplementation environment and software quality. We also represent in Figure 1.2 the trade-off

Protocol Development

functional requirements strategic requirements

specific general

design model

protocolspecification

implementationenvironment

softwarequality

requirements

portability

performance

implementationefficiency

maintainabilityimplementationtechniques

framework

protocol implementation

trade-off

Figure 1.2 Dependencies among the elements of the protocol development process

Page 25: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

1.5 Approach

7

between four aspects of software quality requirement considered in our investigation. Implemen-tation techniques are chosen based on strategic requirements and are used to build frameworks.The process of building a framework also depends on the particular design model the frameworkmust support. The protocol implementation depends directly from the protocol specification andthe framework.

This thesis, therefore, is intended develop generic guidelines, providing the foundation for morespecialized work, where choices concerning some of the possible characteristics of the protocoldevelopment process can be made, such as, e.g., which design model should be used and the stra-tegic requirements to be adopted.

1.5 Approach

In this thesis we apply frameworks to the protocol implementation process. The main idea is toapply frameworks to bridge the abstraction gap between design and implementation. Frameworksare software structures developed for a specific application domain, which can be re-used in theimplementation of various different concrete systems in this domain. In our case, the applicationdomain is the design model underlying the protocol design process, and the concrete systems arethe protocol implementations. By supporting design models we provide a protocol implementa-tion process that can be connected to multiple different design approaches.

When using our implementation approach, once an appropriate framework is available, that sup-ports the necessary design concepts, the speed of the implementation process is potentiallyimproved.

Because we want to investigate the application of this process to a broad spectrum of develop-ments, and different frameworks must be provided to support different development characteris-tics (see chapter 2, section 2.1), it is not practical to provide a comprehensive set of frameworks.Instead, we provide a method to develop frameworks. While defining this method we strive foraddressing the following requirements:

• Support to different design models: a design model comprehends a set of design concepts.Different design models for protocol design used in practice overlap considerably in their setof concepts, but differ in a few concepts. A design model may even be totally contained inanother design model. Our framework development method provides a systematic way toadjust our protocol implementation process to design techniques based on different designmodels. We adapt the object-oriented design methods as presented in [61] and [10] to copewith this goal. We define process milestones with corresponding inputs and outputs. In chap-ters 3 we provide support for performing framework development. This support consists ofinformation that has been saved from previous framework developments and can be used tospeed up new developments.

• Implementation performance: the framework development method does not impose fixedimplementation solutions to support design concepts. Some alternative solutions are dis-cussed in chapter 4 to bring insights and contribute with our experience. However, creativityhas its role in this method and developers can provide their own solutions, whenever bettersuit the performance requirements.

Page 26: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8

Chapter 1: Introduction

• Implementation maintenance: we address the maintainability issue using the state-of-the-artin software engineering (e.g.: object-oriented programming and design patterns) to produceextensible and reusable implementation code. For the same purpose, we offer in our methodthe possibility to preserve the protocol specification structure in the implementation. Thissaves learning effort to understand the implementation, while helping maintenance. The pro-tocol specification can then be used as the abstract level documentation of the implementa-tion.

• Implementation conformance: we strive for implementation correctness by defining a sys-tematic implementation process. The final assessment of the implementation conformance isdiscussed in chapter 10, where we present an approach based on tests upon the implementa-tion.

• Implementation portability: implementation portability is addressed in three ways: 1) imple-mentation solutions for design concepts are elaborated, as much as possible, using an imple-mentation model whose concepts are easily mapped onto implementation constructs, but thatstill abstracts from implementation techniques specific to some environments. We discussour implementation model in chapter 2. By following this approach we enforce portablesolutions; 2) in chapter 4 we advise identify some implementation techniques that can beused to contribute in this issue; 3) whenever we migrate frameworks to a new implementa-tion environment, we theoretically can port directly all individual protocol implementationsbased on that framework to the new environment.

In this thesis we present three examples of frameworks. They provide the means to start experi-menting with the proposed protocol implementation method and provide earlier prototypes fromwhich more elaborated frameworks can be derived. They are intended to cover a reasonable spec-trum of design concepts and implementation techniques, in the context of our experiments. In thisway, our method for protocol implementation is ready to be applied in practice and the frameworkdevelopment process is illustrated.

The domain analysis and software architecture definition steps of our method to develop frame-works resembles the analysis and design steps of the protocol development process. Such a devel-opment steps, however, are not redundant, since these two steps are performed for differentrequirements using constructs of different abstraction levels.

Our frameworks support a small but useful set of design concepts. We support a basic and anadvanced design model. The advanced model extends the basic model with behaviour structuringtechniques and dynamic creation and termination of components. The framework examples sup-port each one of these design models, and have been developed applying different implementa-tion techniques.

The purpose of supporting two different design models is to provide some parameters to analysethe effect of increasing the number and complexity of concepts supported and to exemplify theprototyping technique. The purpose of applying different implementation techniques is to illus-trate the use of two major implementation solutions, and evaluate their use concerning the codecomplexity and the performance of the resulting implementation.

Through the analysis of the framework examples, we provide protocol developers using thisimplementation approach with information that allows them to make decisions concerning the

Page 27: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

1.6 Scope and Limitations

9

tuning of development process towards a trade-off of requirements that better suits the devel-oper’s goals.

1.6 Scope and Limitations

Mastering all available techniques for protocol design and implementation and place them into asingle development process that takes the best from them is an extremely challenging, if notimpossible task. The effort we have done here was to build a main body for this process, to iden-tify and analyse the fundamental issues involved, and to propose and evaluate solutions to theseissues.

Concerning the design domain, we do not try to be rigorous in the presentation of the semantics ofdesign concepts, or to be exhaustive when identifying them. We limit ourselves to constructivedesign models, which are closer to implementation. We analyse design concepts through a limitednumber of interpretations of these concepts, i.e., the way they are captured in the specificationlanguages LOTOS [36][81], ESTELLE [18][35][81] and SDL [81].

Concerning the implementation domain, although we apply an implementation meta-model (seesection 2.3.1) that offers some degree of abstraction from environment specific issues, our imple-mentation solutions are to some extent targeted to the environment used in our experiments. SUNworkstations, running the Solaris operating system, and the C++ programming language is theimplementation environment that has been used in our work.

Some protocol requirements that are not addressed here are real-time aspects and data types. Byreal-time we mean some critical time-related restrictions applied to the execution of protocolfunctions. By data types we mean the definition of data formats and the operations upon them.Although we do not focus on data types, we discuss it marginally in chapter 4, when addressingimplementation requirements.

1.7 Related Work

In the literature we found three different types of developments that contribute to the protocolimplementation process:

• construction of implementation building blocks: such building blocks provide programmingsimplicity, portability and abstract functions. Some developments provide protocol functionsas coarse granularity building blocks for protocol development;

• specification language compilers: in this approach the implementation code is producedsemi-automatically by a compiler that receives as input the formal specification of a protocol;

• combined approach: some support is given for the protocol design step while improving thelevel of abstraction for the implementation facilities. According to this approach one definesa closer matching between design concepts and implementation concepts, while keepingsome concern with quality of software requirements.

Page 28: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10

Chapter 1: Introduction

Below we present some developments that give a significant contribution to the protocol develop-ment process and are representative for the types of developments we have identified above.

Da CaPo

Da CaPo [55] [56] is an approach to develop end-to-end communication systems. It is based onbuilding blocks of coarse granularity. The main contribution of this work is the development of aflexible implementation that supports configuration and re-configuration of the protocol inresponse to QoS requirements. In this approach the building blocks are called modules. Combina-tions of modules to compose a protocol implementation are defined through graphs of functionaldependence between modules. Such graphs are stored in a database and are passed to a runtimeenvironment that controls the flow of data through modules. A specification language has beendefined to describe application requirements and properties of modules. Once the minimum QoSrequirements are established, the graph that matches those requirements is selected using specialheuristics to improve performance. The underlying communication service is monitored and ifthe quality of service changes, the protocol is automatically reconfigured.

This approach focuses on treating QoS issues. The coarse granularity limits the implementationflexibility and the approach for implementing each component is not addressed. Therefore we seethis approach as a complement for our approach related to and dealing with QoS issues. The DaCapo solution could be built using our fine granularity building blocks, profiting from the bene-fits of applying formal methods into the design of the protocol.

ACE

The ADAPTIVE Communication Environment (ACE) [63] [12] is an object-oriented frameworkthat implements many core design patterns for concurrent communication software across a rangeof operating systems platforms. The communication software tasks provided by ACE includeevent demultiplexing and event handler dispatching, signal handling, service initialization, inter-process communication, shared memory management, message routing, dynamic (re)configura-tion of distributed services, concurrent execution and synchronization.

The main contribution of ACE is to speed up the implementation process by providing communi-cation functions and services, in the form of portable implementation building blocks. However,ACE does not provide a way to address the design and implementation steps of software develop-ment as an integrated process, which is one of the goals of our work.

x-Kernel

x-Kernel [32] is an operating system kernel that provides a set of support routines that can be usedto implement protocols. Some of these routines are:

• buffer management routines, which provide facilities for concatenating two buffers, break-ing a buffer into two separate buffers, and truncating the left or right end of a buffer;

• map manager routines, which provide a facility for maintaining a set of bindings of one gen-eral purpose identifier to another. Protocol implementations use these routines to translateidentifiers extracted from message headers onto capabilities for kernel objects;

Page 29: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

1.7 Related Work

11

• event manager routines, which provide an alarm clock facility. This event manager lets theprotocol specify a timer event as a procedure that is to be called at some future time;

• a support for communication objects, which enforce a minimal object-oriented style on theprotocol’s implementation.

The x-kernel has been used as a vehicle for experimenting with the decomposition of large proto-cols and as a workbench for designing and evaluating new protocols. This approach addressesperformance, by embedding protocols in the operating system, and addresses implementationfacility by supplying some implementation building blocks. However, it does not support adynamic implementation process, since this would involve changes in the operating system. x-Kernel is a workbench to implement protocols that does not comprise formal design techniques,differing in this respect from our approach.

Specification Language Compilers

Developments with compilers may follow different alternative approaches:

• before compiling, some correctness preserving transformations are done in the specificationtill its implementation is straightforward, i.e., the design concepts applied in the specificationcan be easily mapped onto code. The transformations can be performed manually or auto-matically;

• specification structure and high abstraction level design constructs are supported in theimplementation.

The first approach emphasizes implementation correctness. This is done by bringing the protocoldesign as close as possible to the implementation domain using the same specification language.This allows the use of techniques that enforce correctness. The second approach emphasizesimplementation maintainability, since it produces a structured implementation code. Supportingabstract design concepts in the implementation makes it harder to guarantee the correctness of theimplementation.

Many developments that use the second approach when applying compilers, only rely on makingthe best effort to be careful while developing their solutions to cope with the correctness issue. Nosystematic approach to guarantee correctness is applied. However, a good reason to follow thesecond approach is that usually compilers are used to produce a first version of the implementa-tion that still needs to be customized and integrated with other developments and maintainablecode facilitates that.

A couple of compilers have been developed for the three specification languages we have consid-ered in our research: LOTOS, ESTELLE and SDL. TOPO and COLOS [9][20] are compiler forLOTOS. EDT [13], some developments reported in [67] and DINGO [68] are examples of com-pilers for ESTELLE. SITE [31] and SDT [77] are examples of compilers for SDL.

SPIN

SPIN [29] fits close in the category of compilers for implementation languages. The specificationlanguage in this case is PROMELA [30]. Valuable lessons can be taken from this development in

Page 30: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

12

Chapter 1: Introduction

terms of implementation solutions for the design concepts used in that specification language,especially because it is well documented. However, SPIN is a protocol design validation toolbased on simulation and was not originally designed for protocol implementation. It interprets aprotocol specification in PROMELA offering features for validating some design properties. Theimplementation solutions in SPIN are not concerned with performance requirements. Someassumptions were made to abstract from some implementation issues like data format and inter-face with the environment. These assumptions simplify the implementation, allowing the devel-opers of SPIN to concentrate on the behavioural aspects of protocols.

General Remarks

The common characteristic of Da Capo, ACE and x-Kernel is the use of a bottom-up approach toimplement protocols. The requirements of the application are mainly reached by combiningimplementation building blocks that were identified and designed to be reusable. Compilers thatrequire specification transformations before compilation follow mainly a top-down approach forprotocol development. Compilers supporting abstract design concepts are examples of a com-bined development approach.

Our implementation approach is a combination of building blocks and compilation. It assumesthat protocol designers use specification languages, which is the top-down characteristic. How-ever, our approach is top-down till a certain stage of development, where the requirements areclearly stated and the solutions developed with some degree of abstraction. Afterwards, itbecomes a bottom-up development process, where abstract design concepts and their combina-tions are implemented, and software engineering techniques are applied to comply to softwarequality requirements.

Some characteristics of the related developments could be used to complement our approach,such as, e.g., flexible configuration for treating QoS negotiation and coarse granularity buildingblocks for design. Compilers could also be developed to complement our development approach,whenever automation is worthwhile, e.g., in case a certain framework is frequently used.

1.8 Thesis structure

The sequence of the chapters in this thesis reflects the order in which we have dealt with theseissues in the research process. Figure 1.3 shows how the chapters in this thesis are related to eachother.

The main body of the thesis consists of two parts: a) the description of an approach to applyframeworks to protocol implementation and b) the application of this approach. Our approach toapply frameworks is described in chapter 2. The chapter describes the implementation processsupported by frameworks and presents a method to develop such frameworks. The method forframework development is the core of our work. Besides the general description in chapter 2, themethod is complemented in chapters 3, 4 and 10. These chapters present methods that can be usedin the support of the development task.

Page 31: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

1.8 Thesis structure

13

Concerning the application of our approach, our method for developing frameworks is applied inchapters 5, 6 and 7, where different frameworks are developed. Our protocol implementationprocess is applied in chapters 8 and 9, where it is illustrated and evaluated, respectively, by meansof realistic protocol examples.

Introduction (chapter 1)

Application of Frameworks to protocol implementation

Implementation Approach (chapter 2)

Analysing design models

Discussing implementation solutions

Framework

Framework examples (chapters 5, 6 and 7)

Applying the implementation approach

Assessing frameworks correctness (chapter 10)

Conclusions

(chapter 3)

(chapter 8)

(chapter 4)

(chapter 11)

developmentsupport

Sliding Window Protocol implementation - illustrating the approach

(chapter 9) OSPF Implementation - evaluating the approach

Figure 1.3 Thesis structure

Page 32: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

14

Chapter 1: Introduction

Page 33: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

15

Chapter 2

Applying Frameworks to Protocols

This chapter describes our approach to apply frameworks to the protocol implementation process.We introduce the rule of frameworks in the implementation process and present a method todevelop such frameworks, in order to systematically address the alternative requirements of thisprocess, i.e., the underlying design model, the target implementation environment and strategicrequirements.

The structure of this chapter is: section 2.1 describes the perspective from which we address theimplementation process; section 2.2 is an overview of our protocol implementation process; sec-tions 2.3 describes in detail each step in the framework development process.

2.1 Introduction

In order to have an implementation process linked with design techniques, the input of such proc-ess must be a protocol specification based on a design model. A specification consists of combi-nations of instances of the concepts of a given design model, in order to define the protocolbehaviour. The output is an executable code that performs the specified behaviour.

In our context, the protocol implementation process consists of mapping the abstract concepts ofthe chosen design model used in the protocol specification onto the concrete concepts of animplementation model. Figure 2.1 illustrates this process.

protocol specification

protocol implementation

mapping

design model

implementation model

metamodels

Figure 2.1 Implementation process as a mapping

Page 34: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

16

Chapter 2: Applying Frameworks to Protocols

The difference between design and implementation models is the level of abstraction from imple-mentation details they offer. Design models abstract from those details while implementationmodels address them. In this chapter we use the term meta-model, i.e., the model of a model, togenerally refer to design models and implementation models.

Ideally, design and implementation models should be well-defined and consistent. By well-defined we mean with precisely defined concepts and their possible relations. A consistent meta-model has rules to combine concepts that avoid the misuse of such concepts. The meta-modelshould have formally defined semantics, allowing us to assess whether an implementation con-forms to the corresponding design. Such assessment could be supported by automatic tools.

Although formal design models generally are well-defined in so far as they have formal seman-tics, implementation models normally lack a formal semantics, such that their correctness is diffi-cult to assess. The latter are not clearly defined sets of building blocks with a well documentedsemantics and rules for consistent use. Building blocks are available and their usage may result ina quite different implementation model than without them. The use of tools for correctness assess-ment is impossible under these circumstances.

Some effort is now being done on formalizing implementation models, as for example in [1] and[26], where the object-oriented model is formalized. The expected benefits allowed by suchachievements, however, are far from available.

Object-orientation is currently applied in software engineering as a design and implementationmodel. However, this meta-model is quite restricted specially when comparing it with designmodels currently available. In terms of design concepts, for example, object-orientation does notoffer many options in terms of possible forms of interaction. Concerning the use of object-orien-tation as an implementation model, actual implementations differ quite a lot from the theoreticaldefinition, imposing limitations or changing the semantics of some constructs. For example, intheory different objects execute independently from each other, however, implementation lan-guages like C++ do not directly support such semantics, providing instead a chain of method callsin a single thread of execution. Therefore, development methods relying on this meta-model donot comply to the ideal situation we have described.

The mapping activity of the implementation process therefore relies on the knowledge thatdesigners have of the implementation environments, and their skills to combine the availablebuilding blocks. Implementing from scratch in these circumstances is not an efficient process.Implementation conformance usually relies on time consuming tests without guarantees.

We have defined a pragmatic approach to address protocol implementation that contributes toovercome the difficulties resulting from the limitations described above. The main contributionsof our approach are:

• an efficient implementation process linked to design techniques.

• a systematic way to customize the implementation process towards alternative requirements;

• flexibility to address maintainability, performance and correctness of the implementation.

Page 35: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2.2 Implementation Process

17

2.2 Implementation Process

We use frameworks to capture implementation solutions for design concepts while letting free-dom to instantiate and combine such implementation solutions in order to implement specific pro-tocols.

Frameworks increase the abstraction level of the implementation model, supporting in a one toone relation the concepts of the design model, by implementing their functionality and the waythey cooperate with each other.

To start the implementation process, developers should produce a protocol specification based ona constructive design model. A protocol specification describes the number of instances of designconcepts the protocol requires and how these instances of concepts are combined. The frameworkmust provide instantiation of implementation solutions of each concept, and provide the ways toconnect these instances. A framework is complemented with code that contain information of aparticular protocol in order to produce an executable code for that protocol.

Figure 2.2 illustrates the rule played by frameworks in the implementation process.

In Figure 2.2 we show the mapping of design concepts (numbered circles) of a design model, ontoimplementation solutions in the framework. Implementation solutions are built using the imple-mentation building blocks (numbered squares) of the implementation model. We also represent

design modeldesignconcepts

+ consistency rules

implementation model

framework

protocol specification

+ consistency rules

instantiationand combination

definition

template+

protocol implementation

1 2 3

1 22 2 3

1

1 2 3

mappingmapping

implementationsolution implementation

building blocks

filled

Figure 2.2 Framework rule in the implementation process

Page 36: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

18

Chapter 2: Applying Frameworks to Protocols

the mapping of a protocol specification onto a complementary code using an implementation tem-plate that, together with the framework, builds a protocol implementation.

Once an appropriate framework is available that supports the necessary design concepts, runningin the target implementation environment and has an acceptable execution performance, experi-ence has shown that the use of frameworks can increase the effectiveness of the implementationprocess [40][64]. The remaining work to reach an implementation is a systematic work of fillingthe framework template with protocol specific information.

Once frameworks are properly implemented, i.e., with a correct implementation of the supportedconcepts, the use of frameworks enforces implementation conformance, since the systematic fill-ing of templates minimizes errors.

When building frameworks for a specific design model, we observed that a multitude of alterna-tive implementation decisions could still be taken, all resulting in valid frameworks. These imple-mentation decisions concern, for example, the techniques for implementing parallel processes,interactions and interfaces. This implies that the set of necessary and possible solutions can beseen as a catalogue of frameworks that can be represented as a matrix, indexed with design mod-els and implementation decisions. The flexibility for considering different implementation solu-tions is our main mechanism to address implementation performance.

In the catalogue, a framework for protocol implementation consists of a set of classes that imple-ment the common aspects of all protocols that can be described according to a specific designmodel. This also implies that when we use a framework to implement a specific protocol, the finalimplementation will consist of the framework complemented with classes that define the specificfunctions of the protocol. In this respect a framework resembles a program with a ‘hole’, whichhas to be ‘filled in’ with specific implementation functions.

Figure 2.3 depicts our catalogue of frameworks. The framework icon reflects our metaphoricalview of a framework.

In a long term development strategy, where experience is accumulated and frameworks consoli-dated, developers consult a catalogue of available frameworks to find a framework that supports

Figure 2.3 Catalogue of frameworks in a matrix form

FW2

FW4

FW5

FW3

FW1

Design models

DM1 DM2 DM3 DM4

IS1

IS2

IS3

Impl

emen

tatio

n de

cisi

ons

Page 37: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2.3 Framework Development Process

19

the design model used in the design phase. The catalogue of frameworks gives indications of thegeneral characteristics of the supported design model and the most important implementationdecisions taken for each framework.

Together with each framework, the catalogue should contain a documentation of the supportedconcepts, implementation solutions, limitations and usage information. Framework usage infor-mation consists of explaining how to map the protocol behaviour and structure, onto implementa-tion code, filling in templates for that specific framework. Developers, while choosingframeworks, should consider strategic requirements and decide about the trade-offs between therequirements mentioned in the introduction.

If no suitable framework is available in the catalogue, i.e., no framework supports the requireddesign concepts with the appropriate performance, a new framework should be developed. Devel-opers may also consider to apply design tools, if available, to transform the protocol specificationinto a specification whose concepts are supported by an available framework. Providing specifi-cation transformation tools though is beyond the scope of this thesis.

Figure 2.4 summarizes, using an UML activity diagram, the process of using frameworks in along term implementation strategy.

2.3 Framework Development Process

Our framework development method was largely inspired by [61] and [10]. The modelling tech-niques follow the UML standard [24]. Our method consists of four steps:

• Domain analysis: the purpose of this step is to capture the characteristics of the domain forwhich we intend to develop the framework. The framework domain consists of the designmodel that the framework will support. We define our own approach to analyse and describedesign models based on the specialization of a basic meta-model we have identified;

• Definition of the Software Architecture: in this step we take the implementation decisionsnecessary to bridge the abstraction gap between design and implementation. We apply some

search for a framework

catalogue

map theprotocol-specific

information

develop a new framework

include theframework inthe catalogue

[not found]

[found]

in thesuitable

Figure 2.4 Implementation method summary

Page 38: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

20

Chapter 2: Applying Frameworks to Protocols

heuristics to develop implementation solutions and some modelling techniques to documentsuch solutions;

• Coding: in this step we map the software architecture of the framework onto implementationbuilding blocks of a specific implementation environment. We adopt a prototyping strategywhere coding and testing are done first for the components of the design model that have thebiggest impact in the implementation process;

• Documentation: definition of guidelines for using the framework.

Figure 2.5 shows the inputs and outputs of our framework development method.

2.3.1 Domain Analysis

In the domain analysis step we strive for a clear definition of the design model we intend to sup-port. The concepts of the design model and their relationships are analysed and presented. Suchanalysis is based on a basic meta-model we have developed. The analysis consists of specializingthe components of the basic meta-model into the specific characteristics of the particular designmodel we intend to use. A clear description of concepts in this step especially contributes to theconformance analysis in the coding step.

The modelling techniques we use in order to describe design concepts and their relations are datadictionaries and class diagrams. A data dictionary consists of one paragraph for each design con-cept, describing the semantics of this concept and its associations to other concepts. Such descrip-tion is done in natural language. We use class diagrams to help describing the static relationsbetween concepts. The result of this step is a specialization of the basic design model for the spe-cific design model we are interested in, applying the modelling techniques we have mentioned.

Below we present our basic meta-model and discuss the specialization of its elements. As anexample, we specialize the basic meta-model to describe the design model of object-oriented pro-gramming, which is the main target model of our implementations.

domain analysis

Conceptsdescription

definition of the

Software architecture

Frameworkimplementation

documentation of the framework

usage

Heuristics Implementationbuilding blocks

Usageguidelines

Coding

Design model

concept

software architecture

Figure 2.5 Framework development summary

Page 39: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2.3 Framework Development Process

21

Basic Meta-Model

To facilitate the analysis of design models, we introduce a basic meta-model which is a generali-zation of the meta-models applied in protocol development. The analysis of a specific meta-modelcan be done identifying how this specific meta-model defines each fundamental concept of thebasic meta-model. We strove for defining a basic-meta model whose concepts are fundamentalenough to be applied in the analysis of design and implementation models.

We have obtained the basic meta-model by analysing the commonalities between the conceptspresent in some architectures for distributed systems, e.g., ISO/OSI [34] and Internet [16]. Thesame basic meta-model can be found by analysing description techniques which were conceivedto model distributed systems [36][81][35]. The concepts identified in the basic meta-model areintroduced below (and further discussed in chapter 3):

• Behaviour: is an abstraction which models the functionality of the system, i.e., how the sys-tem reacts, in each stage of its execution, to stimulus from its environment or the absence ofthem;

• Component: is an abstraction to model system parts. Communication system architecturesare often structured in layers. These layers may be decomposed into different functionalparts. In this way we can reason about the system through smaller parts that are easier tounderstand than the whole. A component represents a system part that can be seen as a carrierof behaviour;

• Interaction: is an abstraction that models an instance of common behaviour between systemparts;

• Interaction means: is an abstraction that represents the mechanisms through which compo-nents cooperate. The relation between interaction means and an interaction is analogous tothe relation between component and behaviour, i.e., an interaction means is a carrier of inter-actions.

For understanding the semantics of these concepts, we classify them into two categories: struc-tural and behavioural concepts. A structural concept has the purpose of defining a structure thathelps understanding the system. Behavioural concepts support the definition of the system’sbehaviour. Basic structural concepts are component and interaction means. Basic behaviouralconcepts are behaviour and interaction.

For each specific meta-model we specialize the above concepts or aggregate new concepts to sup-port them. Some of the basic meta-model concepts may have a few most common specializations,while others may rely on definitions that can vary considerably from meta-model to meta-model.Figure 2.6 and Figure 2.7 show the basic meta-model and the relationships between its elements.Figure 2.6 focus on the specializations of the concepts while Figure 2.7 shows their relations.

Components perform behaviours. Behaviours cooperate with each other by participating in inter-actions. Interaction means connect components and make interactions possible. Figure 2.7 showsonly the relations between concepts. The cardinalities are omitted, since they are only meaningfulwhen specific meta-models are considered.

Page 40: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

22

Chapter 2: Applying Frameworks to Protocols

Figure 2.8 illustrates the concepts of our basic meta-model and their relations. The figure showsboth structural and behavioural concepts. Arrows indicate which structural concept support eachbehavioural concept. The intersections between the graphical representation of the behaviourconcepts reflect the concept of interaction, denoting a portion of behaviour that demands the par-ticipation of the interacting behaviours. This structure resembles the design concepts of systemarchitectures like OSI and Internet where protocol entities in adjacent layers interact in order toperform their functions.

concept

meta-model

interaction component behaviour

structural behavioural

interactionmeans

concept concept

Figure 2.6 The basic meta-model

behaviour

component

interaction

performs

participates

interactionmeans

performs

connect

Figure 2.7 Relations between basic meta-model elements

component1

behaviour1

interaction

interaction means

behaviour2

component2

structural

behavioural

Figure 2.8 Graphical illustration of design concepts

Page 41: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2.3 Framework Development Process

23

Specialization of the basic meta-model onto the OOMM

We analyse in this section some concepts of object-oriented programming in order to exemplifythe definition of specific meta-models through the specialization of our basic meta-model. We callthe meta-models based on the object-oriented paradigm object-oriented meta-models (OOMMs).Such meta-models are discussed for example in [61] and [10], and applied to design as well as toimplementation.

Agreement on a single semantics for OOMMs is still an ongoing process. Besides that, actualimplementations of this meta-models apply different interpretations of concepts. We use one ofthe variants of the OOMMs as the main implementation model of our framework developmentmethod for modelling implementation solutions. The variant of OOMMs we chose is the oneunderlying the programming language we use in our experiments, i.e., the C++ programming lan-guage. We have decided to focus on the concepts that define execution control and specificationstructure, which are directly related to our work, abstracting from other aspects such as inherit-ance and polymorphism.

The definition of the OOMM used in our work is a rough definition with the only purpose of illus-trating the specialization of the basic meta-model. From now on in our text, OOMM refers to themeta-model introduced here. A more theoretical and detailed analysis of object-orientation is asubject under research, and is discussed, for example, in [1].

Behaviour in the OOMM can be described in terms of state diagrams, as presented in [27]. Thebasic concepts that are used in this behaviour description method are state, event, condition andaction. An event in this context is a stimulus that a behaviour receives from another behaviour.States are the attribute values held by a behaviour. An action consists of operations upon the sys-tem information. Condition is a logical expression that must be evaluated as true for an action tobe executed.

Decomposition in the OOMM is handled by objects. In this sense, an object plays the role of acomponent. Each object is an instance of a generic group of objects with common characteristics.This generic group is called class. A system can have as many classes instances, i.e., objects, asnecessary. The allowed stimulus, i.e., methods, are part of the definition of classes. Objects run ina chain of calls which are triggered by interactions with the system environment.

The interaction between objects is the method call. This form of interaction involves two partici-pants: a sender and a receiver. The sending part performs a call with the identification of themethod to be performed and the required parameters, and blocks its execution waiting for ananswer. The specified method is treated in the receiving part and a result is eventually returned tothe sending part that continues its execution. Performing a method may involve other methodcalls, including a call back to previous sending partners. Objects can interact with any otherobjects. The interaction means concept is not present in this model. Figure 2.9 shows the relationsbetween the concepts of the OOMM using UML class diagrams [24].

Page 42: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

24

Chapter 2: Applying Frameworks to Protocols

2.3.2 Software Architecture Definition

In this step we develop the framework software architecture. This step consists of modelling thedeliverables of the domain analysis step, using the target implementation model. We have to pro-vide the functionalities of the concepts of the design model, using the concepts (building blocks)of the implementation model.

A modelling notation has to be used to document the resulting model of this step. For the purposeof defining the software architecture, the modelling notation can still abstract from implementa-tion details like language syntax and communication sub-systems interface. However, the map-ping of the constructs of the modelling notation onto implementation constructs of animplementation environment should be straightforward. Figure 2.10 depicts the conceptsinvolved in this step of our approach to framework development.

component

behaviour

event condition action state

event condition

action state

triggersguards

changes

interaction

methodcall

participatesobject

*

* 1

1

*

11 1

Figure 2.9 OODM concepts relations

formal design model

multithreading

frameworksoftware architecture

modelling process

class diagram

modelling notation

model

UML

OOMM +

meta-model

Figure 2.10 Framework software architecture definition

Page 43: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2.3 Framework Development Process

25

In Figure 2.10, each concept is represented by an ellipsis. Nested concepts are intended to resem-ble the idea of core concepts, i.e., concepts that are fundamental for the enclosing concepts.

In the top part of Figure 2.10 we show the input for the framework software architecture defini-tion, i.e., the design model description. Such design model description is delivered by the domainanalysis step of our method to develop frameworks. The design model is modelled using the UMLclass diagram and natural language as modelling notations. We ignore the meta-model of UML,since we use class diagrams here only to describe the static relations between concepts.

The bottom part of Figure 2.10 shows the framework software architecture. It is the model result-ing from a modelling process that uses some UML techniques as a modelling notation and has theOOMM together with multi-thread programming techniques as implementation model.

Although object-orientation is being formalized, actual implementations of such a meta-model donot cope with the requirements of being well defined and consistent, as stated before. Object-ori-entation is applied here since it is the current state-of-the-art in software engineering. We takeadvantage of the techniques related to object-orientation to reach some of our goals, as discussedlater. The spread knowledge of UML has also motivated us to use it. Our approach can beimproved in future to benefit from the potential achievements in the formalization of implementa-tion models.

In order to cope with the limitations of using the object-orientation as our implementation model,we are open to use other implementation constructs that may change the characteristics of thismodel. New constructs will be properly indicated when applied.

An important addition to the OOMM to form the implementation model we use is multi-thread-ing. A thread is a shorthand for a thread of control, which is the path taken by a program duringexecution [52]. Multi-threading consists of using multiple threads within a single program. Multi-threading may be provided by packages or be embedded in programming languages.

The deliverable of the software architecture phase consists mainly of data dictionaries and classdiagrams. Interaction diagrams [10] are possibly used to represent scenarios that are relevant forthe understanding of dynamic aspects of the software architecture. In order to deal with morecomplex dynamic behaviour, i.e., an object class with a non-trivial number of states, we make useof state diagrams [27] that offer a complete and precise behaviour description. For a moredetailed description of the software architecture, we use CRC cards [10] that contains the respon-sibilities, collaborations, methods and attributes of each class of the frameworks software archi-tecture.

For each class we must also define its boundary conditions, i.e., initialization, termination andfailure. In the initialization, the system must be brought from a quiescent initial state to a sustain-able steady state condition. Termination usually consists of releasing allocated resources. Failurecan arise from environment errors or from lack of resources.

The benefits and drawbacks of the design decisions taken in the development of the softwarearchitecture are documented in natural language, in order to facilitate the selection among alterna-tive frameworks when implementing a specific protocol.

Page 44: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

26

Chapter 2: Applying Frameworks to Protocols

The modelling process that defines the software architecture is mainly a creative process. Never-theless, some heuristics can be applied to support this task. We present such heuristics below.

Heuristics for defining the software architecture

By heuristics we mean actions or procedures whose effectiveness have not been formally provenbut are generally accepted based on experience or common sense. In software engineering, suchan approach still plays an important role [84] and therefore preserving such knowledge is a prag-matic attitude.

The main heuristic for defining software architecture comes from the object-oriented systemdevelopment method presented in [61]. In order to reach the framework software architecture, theclass diagram obtained from the domain analysis must be adapted to an implementation environ-ment. Object classes are excluded or included in the software architecture for implementationoptimization. New responsibilities of object classes must be defined. However, optimization ofthe design should not be excessive.

An heuristic to simplify the implementation code and facilitate the integration of solutions for dif-ferent requirements is to define common interfaces to specializations of the same concepts. Thisallows us to handle less information when reasoning about solutions. This implies that abstractconcepts in our concepts diagram should be kept as abstract classes in the implementation, cap-turing the general information about its specializations.

Another way to apply heuristics is the use of design patterns. A design pattern is a description ofcommunicating objects that are customized to solve a general design problem in a particular con-text [25]. A design pattern is usually the result of a largely applied implementation solution whichbecame well-known and has been made flexible for reuse purposes. Such characteristics of designpatterns help us reasoning about the semantic conformance between the proposed solutions andthe concepts being implemented. The use of design patterns makes the software architecture defi-nition more systematic. Each design pattern focuses on a particular object-oriented design prob-lem or issue. Design patterns represent a compromise between an one-class implementationsolution, e.g., a linked list, which is reused the way it is, and a more complex solution that falls inthe category of a framework, capturing the whole architecture of a problem domain.

For some important issues of protocol implementation, e.g., execution flow control and mappingof protocol behaviour, some design patterns can be found in the literature. For example, a sched-uler pattern can be used to share the opportunity of execution among different parts of a system;an event-demultiplexer pattern can be used to implement an event-driven execution model; thestate pattern can be used for mapping a finite state machine. The use of these patterns is exempli-fied in the frameworks developed in this thesis (see also chapter 4).

2.3.3 Coding

In this step we map the framework software architecture onto the constructs of a specific imple-mentation environment. Because our implementation model is object-oriented, the adoption of animplementation language, such as, e.g., C++ or Java, which supports its concepts, makes this taskalmost straightforward. Some instructions on mapping the object-oriented implementation model

Page 45: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2.3 Framework Development Process

27

onto implementation code is given is the Object Design phase of the Object Modelling Technique(OMT) development method presented in [61].

Different environments supply different and alternative facilities to support our mapping task,e.g., control flow mechanisms and interaction mechanisms. This may lead us to reconsider ourframework software architecture. Therefore, coding is performed in iterations with the softwarearchitecture definition. Alternative frameworks may be proposed to support the same designmodel.

We apply a prototyping strategy for coding. In this approach, the concepts which have strongerimpact in the implementation are coded first. We start by producing a simplified prototype whichallows preliminary tests. New prototypes are then produced which are more robust, i.e., give bet-ter treatment to boundary conditions, or implement more concepts. An iteration-based and incre-mental approach is also recommended in the software development process presented in [10].

The prototyping strategy helps us reasoning about different problems separately. When dealingwith some improvements in a framework, we can abstract from other features that are consoli-dated in previous versions of the same framework. Because of this, an important software qualityrequirement for the implementation solutions is that they are flexible, i.e., they can easily accom-modate extensions. If, however, significant changes are required in a prototype to extend it, it isadvisable first to improve the flexibility of the current solution, make tests, and then extend it.

In the coding step we also have to resolve the trade-off between portability and performance.Building blocks that are intended to improve performance are usually less portable, such as, forexample, multi-threading packages. Some implementation building blocks offer portability, suchas, e.g., wrappers [63], or offer transparency services, such as, e.g., middleware services [6][65].Such techniques always pay a price in performance. An extensive analysis of available buildingblocks, however, is beyond the scope of this work. In this respect, we limit ourselves to a set ofbuilding blocks that are at least realistic, to focus on the fundaments of our method.

Figure 2.11 shows a diagram of our interactive and prototyping coding approach.

software architecture

CodingPrototype

skeleton for coding

adjust

redefinition

software architecture

debugging

implementation mapping

implementation feature

evaluated mapping

Figure 2.11 Coding approach

Page 46: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

28

Chapter 2: Applying Frameworks to Protocols

2.3.4 Documentation

Protocols are specified by creating instances of the concepts of a design model and combiningthese instances. Modelling techniques have constructs representing the concepts and constructs tocombine them, as operators of concepts. Frameworks are intended to support more directly thesemantics of design concepts, but it is not our goal to support any particular specification lan-guage. Therefore, in order to use a framework, we have to provide some guidelines that describehow to create instances of concepts and how to combine them.

Since we are applying object-orientation, instantiation of the constructs supplied by the frame-work to support design concepts can be done by instantiating object classes. Some of thesesobject classes may need specialization in order to capture protocol specific information. Thereuse of frameworks is classified in [75] as whitebox and blackbox. Whitebox reuse is based oninheritance and requires knowledge of the superclasses. Blackbox reuse merely relies on theinterfaces of the involved objects. In our approach for reusing frameworks some components arespecialized and others are only instantiated. Therefore, we can say that we use a mixed approachin this respect.

In order to combine the instantiated concepts, different techniques may be applied, such as:

• template code to be filled in with code for each specific protocol function;

• suggested mappings of behaviour structures of the protocol specification onto implementa-tion patterns.

The instructions for applying a framework must also contain the information for handling bound-ary conditions. Guidelines for using frameworks are formulated in natural language and are illus-trated with some examples.

2.3.5 Conformance Assessment

Protocol development methods that use formal methods emphasize precision as the basis for thedesign activity. An important requirement in our research is the conformance between designconcepts and the way such concepts are supported by the protocol implementation. The semanticsof the design concepts must be preserved in the implementation, otherwise, the effort done in thedesign may be compromised.

The ideal approach to guarantee conformance would be to have a formal description of thesemantics of all design concepts and of the constructs of the implementation language applied. Inprinciple this would enable formal conformance proofs. To follow this ideal approach, we wouldneed tools that could help us proving the conformance of the implementation solutions. However,to build tools that manipulate the formal semantics of the usual programming languages is still abig challenge. Furthermore, most of the implementation languages do not have a formal seman-tics.

We have decided to apply a pragmatic approach to deal with the conformance requirement. Weclaim that we can compare constructs in different domains, i.e., design and implementationdomains, as soon as such constructs, or their decomposed parts, are simple enough. In this case

Page 47: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

2.3 Framework Development Process

29

the conformance assessment is straightforward. We also suggest testing techniques for each con-cept implementation whenever the complexity of the concepts justifies so. We claim that theapplication of test techniques to basic design concepts is simple and produce reliable results.Chapter 10 presents in detail our conformance assessment approach.

Page 48: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

30

Chapter 2: Applying Frameworks to Protocols

Page 49: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

31

Chapter 3

Functional Requirements

The Domain Analysis step of our method for developing frameworks consists of identifying anddescribing the design concepts a framework is intended to support. To speed up the execution ofthis step, we identify, select and briefly describe in this chapter a realistic set of design concepts.In this sense, the chapter identifies the functional requirements to be fulfilled by the frameworks.When applying our framework development method, designers can select from here the conceptsthat match their design models.

The structure of this chapter is: section 3.1 explains the purpose of our domain analysis approach;sections 3.2 to 3.5 present each design concept that should be supported by frameworks and theirpossible characteristics; section 3.6 discusses rules for guaranteeing the consistency of designmodels.

3.1 Approach

Design concepts allow designers to model requirements and characteristics of systems making itpossible for these designers to design system architectures. These architectures are intended toaddress particular classes of systems, such as communication or application systems. Because wefocus our research on protocol implementation, we have chosen as a reference the concepts under-lying the OSI-RM (Open System Interconnection - Reference Model) [34].

Our analysis of architectural concepts are derived from formal concepts underlying the followingspecification languages: ESTELLE (Extended Finite State Machine Language) [18][35][81],LOTOS (Language of Temporal Ordering Specification) [36][81] and SDL (Specification andDescription Language) [81]. Such languages offer formal interpretations of architectural designconcepts and can be seen as design tools that can be used in combination with our implementationapproach.

System architectures are usually defined informally, allowing the designers of specification lan-guages to interpret these architectural design concepts in different alternative ways when estab-lishing these languages. The formal concepts underlying specification languages are therefore

Page 50: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

32

Chapter 3: Functional Requirements

interpretations of architectural design concepts that could be defined more abstractly and funda-mentally, not subject to mathematical elegance or other non-technical motivation.

Our analysis of design concepts starts from the fundamental concepts of system architectures.Such fundamental concepts form our basic meta-model and have been introduced in chapter 2.This chapter specializes these fundamental concepts by considering the interpretations taken ineach of the specification languages mentioned above.

The motivation and the semantics of our fundamental concepts are discussed in more detail in[82][23][58][33]. Our purpose when analysing these concepts is to present them into a perspec-tive that is suitable for our implementation purpose. We model concepts and their relationshipsusing UML class diagrams and data dictionaries, which are techniques extensively applied by thesoftware engineering community. The models obtained in this step can be directly used as startingof the implementation process. A detailed taxonomy of design concepts is out of the scope of thiswork.

While applying UML class diagrams to model concepts, we consider each concept as a class andwe build a class diagram to represent the concepts and their relations. The semantics of each con-cept is discussed informally so that attention is not deviated to mathematical issues but ratherallows us to focus on design issues. The fundamental concepts discussed in this chapter specializethe concepts of component, interaction means, interaction and behaviour.

For each fundamental concept we discuss its interpretation and representation in the specificationlanguages LOTOS, ESTELLE and SDL. Our only purpose on so doing is to illustrate the concep-tual analysis. We do not want to attach or restrict our analysis to any specific interpretation ofthese concepts. While discussing a concept on the light of a language, we use the terminology ofthis language in order to help people who are acquainted to this language understanding the dis-cussion.

When designing systems we are interested in specifying the allowed behaviour of such systems,rather than describing a specific behaviour that has happened. In this sense it is important toemphasise the difference between an abstract concept and an actual instance of such concept.

The concepts presented here are models of real objects and when applying such concepts forbehaviour specification we may abstract from some of their characteristics. In respect to interac-tions, for example, we can apply this concept for specifying behaviour without defining the exactmoment it will happen, or which information it carries. An instance of a concept instead, is a fullycharacterized description of that concept.

In our discussions on design concepts we usually make reference to concepts rather than to theirinstances. References to instances of concepts are made explicitly whenever necessary.

3.2 Component

A Component is an abstraction that models a system part. It is a design concept that models thecarrier of behaviour and can be used for system composition and decomposition. In our context,i.e., the protocol implementation process, system parts can be protocol entities or protocol func-

Page 51: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.2 Component

33

tions in which systems can be decomposed. Each component has an associated behaviour, i.e.,each component performs a function. A component carries and identifies its related behaviour,allowing one to reason about the system in terms of black box parts, without making reference towhat these parts precisely do.

Another purpose of the component concept is to establish the visibility scope for the system infor-mation, since a component can only perform operations upon data within its scope. Componentsonly interfere on each other’s behaviour through interactions, such that they do not directly sharecontext information. This particular characteristics contributes to the modularity of the system.

Components can be created/destroyed statically or dynamically. Static creation means creation atthe system initialization. Static destruction means destruction at the system termination. Dynamiccreation/destruction means creation/destruction during the system execution. Components mayreceive parameters when their are created so that they can be configured.

Furthermore, components perform they behaviour in parallel, i.e., a component does not restrictthe order of events of other components, except when it interacts with these components. Parallelbehaviours are discussed in more detail in section 3.4.6.

3.2.1 ESTELLE Representation

A component can be represented in ESTELLE by a module. ESTELLE modules have differentcharacteristics depending on its qualifiers. Modules classified as system-process or system-activityrepresent components. Modules classified as process or activity do not comply with our concept ofcomponent. They share context information and do not run independently of other modules. Fig-ure 3.2 illustrates the correspondence between modules and components.

Figure 3.2 (1) illustrates a system architecture described in terms of ESTELLE concepts. It con-sists of two system processes M1 and M2, where M1 has two child components M1.1 and M1.2.Figure 3.2 (2) shows the representation of the same system in terms of components. The arrowsindicates the correspondence between concepts.

On purpose, we illustrate that the ESTELLE module concept does not match one-to-one with ourcomponent concept. Processes M1.1 and M1.2 are ESTELLE modules but do not correspond toour concept of component. The design requirement captured by this language construct is handledin our basic meta-model using the concept of sub-behaviour, discussed in section 3.4.6.

component

parameterized statically

created/destroyed dynamically

created/destroyed

{overlap}{disjoint}

Figure 3.1 Component specializations

Page 52: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

34

Chapter 3: Functional Requirements

3.2.2 LOTOS Representations

In LOTOS there is no specific representation for components. Process in LOTOS are used tostructure behaviour. Intuitively one might assume a one-to-one association between a certainbehaviour definition and a component. A process in a LOTOS specification may have its behav-iour combined with the behaviour of another process by a composition relation, such as sequence,interleaving, choice and disruption. This characteristic of processes does not match with our com-ponent concept as independent parts.

Because LOTOS does not model real concurrence, interleaved processes may be interpreted asrepresentation of components when reasoning about the implementation. Final decisions ondecomposing a LOTOS specification into components depend on knowledge about the applica-tion which tell us whether such interpretation for interleaved processes is appropriated.

Processes whose behaviours are combined by other relations than interleaving represent a limitedform of sub-behaviour, where sub-behaviours do not directly share context information. Belowwe illustrate processes that may represent components and processes that may represent sub-behaviours.

3.2.3 SDL Representations

SDL does not have a representation for our component concept. The SDL concept of process canrepresent a component if used with some restrictions. SDL processes share information by means

M1.1 (process)

M1 (systemprocess)

M1.2 (process)

M2 (systemactivity)

ESTELLE Basic Meta-model

components

C2

C1

modules

Figure 3.2 Representing components in ESTELLE(1) (2)

process A[x] := a ; B[x] >> C[x] endproc

process A[x] := a ; ( B[x] ||| C[x] ) endproc

process A[x] := a ; ( B[x] [ ] C[x] ) endproc

A may be interpreted as a representation for a component,

A may be interpreted as a representation for a component,

represent sub-behaviours of Awhile B and C

while B and C may represent components instantiated by A’s behaviour

Page 53: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.3 Interaction Means

35

of exported variables, which violates the independence characteristic of components. An SDLprocess that does not export nor import variables can be used to represent an abstract compo-nent.

3.3 Interaction Means

An Interaction means is an abstraction to represent mechanisms through which componentscooperate. System parts have to cooperate in order to accomplish the goals of the system as awhole. The concept of interaction means can be specialized in the concepts of interaction pointand link for performing synchronous and asynchronous interactions, respectively.

While in synchronous interactions a single design concept is enough to reason about the seman-tics of this design concept, this is not true for asynchronous interactions, forcing us to definethese two specializations. Because in the case of a link we have to reason about buffering infor-mation, it is convenient to create a design concept to represent the buffering means, we call com-munication means, and another concept to capture the actual connections, which we call a accesspoint. The link concept is then used to generally refer, or aggregate, these concepts.

The relation between interaction means and interaction is comparable to the relation betweencomponent and behaviour, i.e., an interaction means supplies a place and an identity for themechanism being performed. The class diagram in Figure 3.3 presents the design concepts thatspecialize interaction means.

Communication among components can happen when they share an interaction means. Figure3.4 shows the possible relations between interaction means and components.

Figure 3.4 Component and interaction means relations

An interaction means is connected to two or more components. A component must be connectedto at least one interaction means because components in a system must interact with other com-ponents in order to be meaningful.

interactionmeans

interactionpoint link

communicationmeans

accesspoint

Figure 3.3 Interaction Means sub-diagram

interactionmeans

component 2..*

connects

1..*

shares

Page 54: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

36

Chapter 3: Functional Requirements

3.3.1 ESTELLE Representations

Since ESTELLE is based on asynchronous interactions, an interaction means in ESTELLE corre-sponds to a link. Links are represented in ESTELLE by access points and channels, which repre-sent our concepts of access point and communication means, respectively. A channel inESTELLE is an abstraction that specifies the message types that can be exchanged between theconnected components.

Below we illustrate how a channel is defined and used in ESTELLE. In the ESTELLE specifica-tion, interactionMeans is the name of the channel being defined. Sender and Receiver are the rolesplayed by the modules connected to this channel. DataReq, DataResp and Ack are the messagesthat can be sent by the modules playing the associated roles. The module Client define the accesspoint P, which makes use of the channel im, in which it plays the role of sender.

channel im (Sender, Receiver); by Sender: DataResp; by Receiver: DataReq, Ack;module Server systemprocess;

ip G: im (Sender) individual queue;end;module Client systemprocess; ip P: im (Receiver) individual queue;

end;

Figure 3.5 illustrates the architecture of this example.

3.3.2 LOTOS Representations

In LOTOS synchronous interactions occur at gates. In LOTOS, a gate corresponds to an interac-tion point in our terms. The example below shows a definition of a LOTOS process, where gate arepresents an interaction point, and P and Q are processes representing components connectedthrough gate a.

specification S [a] : noexit :=Server[a] |[a]| Client[a]

where ...

Server

Client

GP

Figure 3.5 Block diagram of the ESTELLE example

Page 55: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.4 Behaviour

37

3.3.3 SDL Representations

Interaction means are represented in SDL by a language construct called link. A link in SDL isbuilt using channels, signal routes and connection points. Channels and signal routes specify whichmessages can flow through them and represent our concetp of communication means, while con-nection points are references for connecting channels and signal routes and represents our conceptof access point. Below we illustrate a signal route definition.

signalroute interactioMeans from Server to Client with DataResp;

from Client to Server with DataReq, Ack;endchannel interactioMeans;

The definition of a signal route specifies to which processes this signal route is connected and theinformation that flows in each direction.

3.4 Behaviour

The behaviour of a system is an abstraction that represents what this system does in order to per-form its task. In our context, i.e., communication systems, we are interested in the behaviour ofprotocol entities. Such behaviour is defined by the actions taken by a protocol entity or function inresponse to the stimulus of its environment.

Below we discuss the characteristics of the design concepts involved in behaviour definition towhich we restrict ourselves for the purpose of this thesis. For these concepts we chose the ele-ments of a finite state machine, under the perspective of the application domain being modelled,i.e., distributed systems. The concepts are information, interaction participation, event, behaviourcontext, action, condition and behaviour unit. The terminology was inspired by the conceptualarchitecture for distributed systems presented in [82] and adapted to allow us to discuss meta-models based on synchronous and asynchronous interactions using a single conceptual frame-work.

3.4.1 Behaviour Concepts

Information represents the values exchanged between components or between the system and theenvironment in an interaction. Information is characterized by the types and the values it carries.The possible information types are defined for each protocol during the design activity. Such adefinition of type and related values is called a communication primitive.

An interaction participation is the contribution of each interacting part to an interaction. Thereare two elements in an interaction participation: offer and acceptance. Synchronous interaction isa design concept at a high abstraction level that embraces different possible specializations interms of possible scenarios of types of participation played by each interacting party. At this levelof abstraction, synchronous interaction is a symmetric concept, in the sense that all interactingparts are just said to participate in the interaction abstracting from the participation type. Exam-

Page 56: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

38

Chapter 3: Functional Requirements

ples of specializations of this concept are discussed later in this chapter. In asynchronous interac-tions, interaction offer corresponds to the provision of information and interaction acceptancecorresponds to the reception of information.

The concept of event models the stimulus to which the system must react. We consider three typesof events: interaction acceptance, timeout and spontaneous event. Timeout is the elapsing of a cer-tain amount of time. The spontaneous event is used to model spontaneous system reaction, i.e.,without any stimulus from the system’s environment.

The concept of behaviour context represents the set of current values of the variables stored bythe behaviour. Typical elements of a behaviour context are the values of the global state and con-trol variables.

The concept of action represents any number of changes upon the behaviour context (operations),or interaction offers. Actions are executed atomically, i.e., an action runs to completion and can-not be interrupted by other actions.

A condition is a logical expression that guards an interaction acceptance. This logical expressiontests the information related to the interaction. A condition may also refer to elements of thebehaviour context.

An unit of behaviour is an abstraction that gathers an event, a condition, a behaviour context andan action. The elements of a behaviour unit are related in the following way: while the behaviourholds the context CTX, event E is allowed to happen. If E happen, the action A must be executed.If E is an interaction acceptance, it may be guarded by a condition CND. If E is an spontaneousevent, it is automatically considered as happened.

Behaviour is the definition of the relations between units of behaviour. Examples of these rela-tions are sequencial order or enabling relations. Finite state machines (FSM) [7] are used todefine behaviour in this work.

A behaviour can be defined by using other techniques than FSMs, such as, e.g., process algebras(CCS [47] and CSP [28]) and causality relations [23][58]. Protocol development processes usingdesign models where behaviour is defined by means of other techniques than FSMs can alsoapply our implementation method. In order to do so, developers must provide a mapping processbetween the used modelling technique onto a FSM or onto a implementation pattern, in additionto the procedures provided by our method.

Figure 3.6 displays the class diagram for the unit of behaviour concept.

behaviour

condition action event behaviour

unit of

context

Figure 3.6 Unit of Behaviour aggregation sub-diagram

Page 57: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.4 Behaviour

39

Figure 3.7 shows the relation between behavioural concepts as explained before.

Synchronous and asynchronous models differ with respect to the interaction offer concept. In syn-chronous models an interaction offer is a specialization of the event concept. In asynchronousmodels the interaction offer is performed as part of an action. Figure 3.8 shows the class diagramfor these concepts.

A behaviour consists of a collection of behaviour units that a component can perform. A meta-model must have a firing policy, which specifies the relation between units of behaviour within abehaviour. An example of firing policy is when units of behaviour execute sequentially, in theorder they are enabled. If multiple units of behaviour are enabled simultaneously, the executionorder is decided randomly. We refer to this policy as the default firing policy. Other policies canbe thought of, such as, for example, giving different execution priorities to different units ofbehaviour, or concurrent execution (see section 3.4.6). Figure 3.9 shows the class diagram for thebehaviour concept.

guards

context

actioneventenables

interaction timeout conditionparticipation

spontaneous

triggers

{disjoint}

behaviour

Figure 3.7 Behavioural concepts relation

action

operation

0..*0..*

interactionoffer

action

operation

0..*

asynchronous models synchronous models

Figure 3.8 Action Aggregation

behaviour

1..*

behaviour unit of

firing policycontrols

Figure 3.9 Behaviour sub-diagram

Page 58: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

40

Chapter 3: Functional Requirements

3.4.2 ESTELLE Representations

Our concept of information is referred to in ESTELLE as an interaction [81]. Information beingexchanged between ESTELLE modules is hold in queues and described in the definition ofESTELLE channels.

An interaction offer consists of sending a piece of information through a channel. Interactionacceptance is to retrieve information from the queue, and is specified using the when clause.

Behaviour context is defined using the clauses from, provided and priority.

Actions are represented by the TO-clause plus everything that can appear between the keywordsbegin and end in the definition of a transition, i.e., outputs, instantiation of modules, connections,disconnections, module termination and data manipulation (PASCAL-like statements).

Conditions are specified using the provided clause. Timeouts are specified using the delay clause.

A behaviour unit is represented using the transition clause. The specification below exemplifies atransition definition.

trans when N.NI(p) from IDLE to WAIT provided (p > present) begin keep_copy(p,saved); output U.UC end;

The keyword trans initiates the definition of a transition. This behaviour definition relates to ourdesign concepts in the following way:

• behaviour context: global state with value IDLE, variable present;

• event: an interaction acceptance at the interaction point N and information NI(p), where NI isthe information type and p the value it carries;

• condition: the value of p must be greater than the value of the variable present;

• action: the operation keep_copy(p,saved) is performed and an interaction offer with commu-nication primitive UC is generated through the link U.

3.4.3 LOTOS Representation

An interaction participation is represented in LOTOS by the event concept. The concept of infor-mation corresponds to the values exchanged in a LOTOS event. Behaviour contexts are specifiedusing parameters. The action concept consists of data operations on parameters or information.Conditions are represented by selection predicates and guards.

Because the LOTOS model is based on observable behaviour, the concept of interaction plays animportant role. However, in LOTOS there is no single language construct comparable to our con-

Page 59: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.4 Behaviour

41

cept of behaviour unit. Below we present a piece of a LOTOS specification exemplifying a behav-iour unit.

process A [input] (x: bool) : noexit :=[x] -> input? y: Nat [y>10]; A[input] (not(x)) [][not(x)] -> input? y: Nat [y<10]; A[input] (not(x))

endproc

The behaviour of the process A reacts to interactions at gate input. x and y are variables that belongto the behaviour context of A. The interaction participation occurs in the gate input and is guardedby the condition [y>10]. The occurrence of this event triggers an action that is the attribution of avalue to y.

LOTOS allows one to describe behaviour defining the temporal order between its events. Timeoutevents can be represented in LOTOS by internal events.

3.4.4 SDL Representations

Information exchanged between components is represented by a signal. An interaction acceptancein SDL consists of accepting a signal from an input port of a process. An interaction offer corre-sponds to the sending of a signal. Actions in SDL correspond to sending of signals, changing val-ues of variables, creation of process instances, branching, activation of procedures andmanipulation of timers. A condition is represented in SDL in terms of enabling conditions.

In SDL the concept of transition represents a behaviour unit. Below we exemplify a behaviour unitin SDL.

...state odd; input Probe; output Win to player; task count := count + 1; nextstate -; ...

In the SDL example above, the context is specified in terms of the current state in the clause state.The interaction acceptance is defined in the clause input. The actions performed as a reaction tothe interaction acceptance are an output operation, the increase of a counter and the update of thebehaviour state.

3.4.5 Time Based Event

Time based event is a design concept that models time related system requirements and can beexpressed in different ways. In this sub-section we present some ways to describe time require-ments.

A time based event happens when a logical condition involving time values, e.g., the current timeand time intervals, becomes true. Examples of such conditions are:

Page 60: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

42

Chapter 3: Functional Requirements

• the system must remain in a certain state for at least t units of time before an action can even-tually be triggered. This condition we call a delay;

• once the system enters in a certain state, a specified action has to be executed before t unitsof time have elapsed. This condition allows one to define real time constraints.

In ESTELLE, two time delays, d1 and d2, can be associated with a unit of behaviour, where d1 <= d2. The action in this unit of behaviour can not be triggered until the enabling conditions of itsguard have remained true continuously for a period of time d1. If the guarding conditions remaintrue longer than d1 but shorter than d2, the activity may be triggered but it does not have to. Afterthe delay d2 has elapsed, the activity must be triggered.

Another approach to handle time requirements is used in SDL. This specification languagedefines the data sorts time and duration, and the concept of timer. These sorts are used to define var-iables that refer to time in an absolute and a relative way respectively. A timer is an object ownedby a process so that the process can generate a timer signal that is put into its input queue [5].Besides that, the system variable now represents the current absolute time of the system. The setand reset constructs are used to manipulate the timer. Figure 3.10 illustrates the use of these con-cepts.

The example of Figure 3.10 uses the graphical notation of SDL. a1 is a variable of sort Time. Thevariable is initialized and used in a decision. The use of the variable now is also illustrated.

Time requirements can not be explicitly defined in standard LOTOS. Some extensions to LOTOShave been proposed to cope with this limitation (e.g., see [45] and [38]). A discussion on timedextensions of LOTOS is outside the scope of this work.

ESTELLE and SDL do not support real-time requirements specification. An example of real timerelated constructor can be found in [45] where a value of sort time can be associated to an action.Such value defines the amount of time within which the action has to be triggered. In that specifi-cation technique, time constructs can only be applied to actions that do not have any associatedinteractions.

a1 := now + tol

a1

(< now) ( > now)

dcl a1 Time;dcl tol Duration;

Figure 3.10 Time restrictions in SDL

Page 61: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.4 Behaviour

43

3.4.6 Behaviour Composition Relations

Besides decomposing a system into components, in case the behaviour of a component is stillcomplex, this behaviour may also be structured in parts. In order to structure a behaviour, we canthink of behaviours composed with some pre-defined relations, providing the expected finalbehaviour. These pre-defined relations we call behaviour composition relations. Behaviour com-position defines explicitly the relations between units of behaviour that otherwise would beimplicit in the behaviour context. Figure 3.11 illustrates the concept of behaviour compositionrelation. Each behaviour is represented by a metaphorical view of flow of execution. The arrowsrepresent the relations that must be defined between the behaviours.

The idea of having a behaviour consisting of a composition of behaviours is recursive. For thepurpose of representing such relations in the form of a class diagram we call a composition of atleast two behaviours a composed behaviour. In order to have a consistent diagram presenting therelations between these concepts, we call a behaviour without further structuring a monolithicbehaviour.

The firing policy adopted in the design model is applied to the units of behaviour belonging to thesame monolithic behaviour. Figure 3.12 shows a class diagram that presents the different behav-iour types and their relationship. A behaviour may be in a composition relation with other behav-iours or not. Composition relations relate at least two behaviours.

In the specification languages we have analysed, we have identified a couple of ways to composebehaviour. To relate behaviours means to apply restrictions to the execution of one behaviour dueto the execution of another behaviour. Composition relations can be binary (relating two behav-iours) or n-ary (relate n behaviours). They can also be symmetric or asymmetric, which meansthat the related behaviours impose the same restrictions to each other or not, respectively.

component

behaviour

relation

Figure 3.11 Behaviour Composition Relations

behaviour

monolitic composed behaviour

2..*

compositionrelation

composes

2..*

0..*

Figure 3.12 Behaviour specialization class diagram

Page 62: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

44

Chapter 3: Functional Requirements

The behaviour composition relations we have identified are: sequence, choice, parallelism anddisruption. This list is not exhaustive, but it is realistic and representative. The understanding ofthe implementation solutions for these composition relations supply enough insight for develop-ers to create other relations.

Parallelism

Parallelism is a n-ary and symmetric relation. There are two forms of parallelism: concurrenceand interleaving. If A and B are concurrent behaviours, the units of behaviour of A and B areindependent of each other and their execution can overlap in time. If the same A and B are ininterleaving, their units of behaviour are not completely independent, the units of behaviour of Acan not overlap in time with the units of behaviour of B.

Figure 3.13 illustrates the concepts of concurrence and interleaving. It shows a possible executionof behaviour units of two related behaviours considering the two forms of parallelism. We repre-sent the time required to treat a behaviour unit by a rectangle.

A behaviour execution starts when a first unit of behaviour is being processed, and it finisheswhen no other behaviour units are expected to execute.

Parallel behaviours can be either deterministic or non-deterministic. If two or more parallelbehaviours have behaviour units triggered by the same event, and are guarded by the same condi-tion, then the choice of which behaviour will actually trigger an action is taken at random and thisform of parallelism is said to be non-deterministic. Otherwise, the parallelism is deterministic. Weexemplify below a non-deterministic behaviour using the LOTOS syntax. It consists of two sub-behaviours composed in interleaving and triggered by the same event b.

b; c; exit ||| b; e; exit

Another possible requirement while composing behaviours is to define that, when some behav-iours are composed in parallel, the end of their execution must be indicated at once to otherrelated behaviours. We call this characteristic synchronous termination. If related behaviours areinformed at different time moments, we call it asynchronous termination.

Figure 3.14 shows the specialization class diagram for the parallelism concept.

concurrence interleaving

overlap execution time of a unit of behaviour

time lineR

R: R:

Figure 3.13 Illustration of concurrence and interleaving

Page 63: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.4 Behaviour

45

Sequence

Sequence is a binary and asymmetric composition relation. If the behaviour A is sequentiallycomposed with behaviour B, then B can only start executing after A has finished its execution.

Choice

The choice composition relation is n-ary and symmetric. If n behaviours are in a choice composi-tion, once one of them starts execution, the other n-1 related behaviours can not execute any more,i.e., they are disabled. The situation in which behaviour units belonging to different behaviours ina choice composition are triggered by the same event is called a non-deterministic choice. Other-wise, the choice is called deterministic. Figure 3.15 shows the specialization class diagram for thechoice concept.

We exemplify below a non-deterministic choice using the LOTOS syntax. It consists of two sub-behaviours composed in a choice relation and triggered by the same event b.

b; c; exit [] b; e; exit

Disruption

Disruption is a binary and asymmetric composition relation. If behaviour A disrupts behaviour B,when the first behaviour unit of A executes, B is disrupted and is no longer allowed to proceed itsexecution. Figure 3.16 shows the specialization class diagram for the behaviour composition rela-tion concept.

parallelism

asynchronoussynchronous deterministic non-deterministic

{overlapping}

{disjoint}{disjoint}

termination termination

Figure 3.14 Parallelism class diagram

choice

deterministic non-deterministic

{disjoint}

Figure 3.15 Choice Sub-diagram

Page 64: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

46

Chapter 3: Functional Requirements

ESTELLE Representations

In ESTELLE we can specify the two types of parallelism by means of class attributes, i.e., sys-temactivity, activity, process and systemprocess. The first two attributes define an interleaving com-position among the embedded modules while the last two define a concurrent compositionrelation. The only composition relation supported between the behaviours of parent and childmodules is interleaving and units of behaviour of parent modules have a higher execution prioritythan the units of behaviour of their child modules. ESTELLE uses deterministic parallelism.

In ESTELLE there is no particular clause to represent sequence, choice or disruption compositionbetween behaviours.

ESTELLE defines an execution cycle that provides synchronization among the execution of par-allel behaviour units. This characteristic of ESTELLE, however, should not be mistaken with syn-chronous termination parallel composition, which is related to the termination of behavioursrather than single units of behaviour. The termination of parallelism in ESTELLE is asynchro-nous.

LOTOS Representations

The only type of parallelism that can be represented in LOTOS is interleaving. Non-deterministicinterleaving is allowed in LOTOS specifications, since interleaved processes may share the samegate. The operator “|||” is used in LOTOS to denote the interleaving composition.

LOTOS has operators to specify sequence, choice and disruption composition relations. They are“>>”, “[]” and “[>” respectively. Interleaved behaviours have synchronous termination.

SDL Representations

SDL can only represent concurrence. The behaviour of all blocks and processes run concurrentlyand with asynchronous termination. SDL does not have a single construct to represent the othercomposition relations such as, e.g., interleaving and disruption.

composition

parallelism sequence choice disruption

relation

behaviour

{disjoint,incomplete}

Figure 3.16 Behaviour composition relations class diagram

Page 65: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.5 Interactions

47

3.5 Interactions

Interactions can be classified as synchronous or asynchronous. In a synchronous interaction, theinteraction participation events of the interacting parts either do or do not happen for all parts. Theunits of behaviour involved in the interaction execute atomically, without interleaving with otherunits of behaviour not involved in the interaction. In the asynchronous interaction, one of theinteracting participants sends information and continues its execution. The information is buff-ered and eventually read by the other interacting part.

Figure 3.17 shows the specialization for the interaction concept.

Figure 3.17 Interaction specialization

3.5.1 Synchronous Interactions

In a synchronous interaction an interaction participation may consist of an offer of a set of values,or an acceptance of a set of offers or both. These types of interaction participation supply the fol-lowing ways of behaviour cooperation: value passing, value checking and value generation,respectively. Value passing occurs when an interacting component offers a value and the othercomponent accepts this value. Value checking occurs when all interacting components offer thesame value, if the values are different the interaction does not happen. In value generation theinteracting components offer each one a range of acceptable values and the interaction happens ifit is possible to establish a value that matches all requirements. More than two components can beconnected by a synchronous interaction point. An interaction can have any combination of thethree forms of behaviour cooperation.

From the specification languages we are analysing, LOTOS is the only one that can represent syn-chronous interactions. LOTOS allows one to represent all the characteristics mentioned above.

interaction

synchronous asynchronous

{disjoint}

interaction interactionparticipation

2..*means *

performs

synchronous

two-party multi-partyvalue-passing value-checking value-generation

0..*0..* 0..*

interaction

{disjoint}

Figure 3.18 Synchronous interaction class diagram

Page 66: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

48

Chapter 3: Functional Requirements

3.5.2 Asynchronous Interactions

The number of information units that can be buffered in an asynchronous interaction may be lim-ited (bounded interaction) or it may be unlimited (unbounded interaction). If the limit of abounded interaction is reached when trying to make an event offer, or there is no information onthe buffering point when trying to accept an offer, the interaction may block (blocking) or fail(non-blocking). An asynchronous interaction can be two-party or multi-party. In a multi-partyasynchronous communication, one party is a sender and the others are receivers. Figure 3.19shows the class diagram for the asynchronous interaction concept with its associated characteris-tics.

The channels and access points of ESTELLE support asynchronous communication, withunbounded queues and two-part interaction. The interaction means of SDL support the same typeof interaction as ESTELLE.

3.6 Design Models Consistency

We have presented in this chapter a comprehensive set of design concepts and their relations.These concepts allow us to describe protocol requirements. Many realistic design models consistof a sub-set of these concepts. Other models may require concepts that were not identified in ouranalysis or that are specializations of the ones presented here. In this case a framework developershould complement the design model in the domain analysis according to our framework devel-opment method.

Besides defining design concepts that are the building blocks for the design activity, while defin-ing a design model we also have to define rules for combining the design concepts. For example,we have to define restrictions for connecting components through interaction means and definethe allowed behaviour compositions. These rules are intended to guarantee the consistency of thedesign model, avoiding that some particular design can be built with the design model, usingcombinations of concepts that do not work properly together.

These rules are part of the static semantics of the model. When applying specification languages,we are also limited by the static semantics rules of the language, which can be automaticallychecked in preparation for simulation or prototype generation.

An example of inconsistent design is when two components whose behaviours are sequentiallycomposed are connected through interaction means supporting synchronous interaction. These

asynchronous

bounded unbounded two-part multi-part

{disjoint}{disjoint}

{overlapping}

interaction

blocking non-blocking

{disjoint}

Figure 3.19 Asynchronous interaction sub-diagram

Page 67: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

3.6 Design Models Consistency

49

components would never be able to synchronize resulting in a deadlock. A cyclic chain of sequen-tially composed behaviours is another inconsistent construction, since it results in deadlock.

In this thesis we assume that design models are used consistently in the design phase of the proto-col development. The semantic rules that lead to a consistent design are considered to be part ofthose models. Implementations of specific protocols inherit the consistency from the designphase. The implementation of mechanisms to support each concept is a matter of implementationcorrectness and is discussed later.

While performing the analysis of design models for developing frameworks, we are interested inthose consistency rules that can be performed automatically, i.e., that do not require design deci-sions. We pay special attention to this type of consistency rules because they can be captured inthe frameworks.

Page 68: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

50

Chapter 3: Functional Requirements

Page 69: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

51

Chapter 4

Implementation Solutions

This chapter presents the most relevant implementation problems we have identified in our appli-cation domain, i.e., the implementation of meta-models for design of distributed systems, andsome implementation techniques to address such problems. We also discuss the treatment ofboundary conditions (initialization, termination and failure) at the implementation level. Thischapter also discusses how implementation effectiveness can be improved by making use of gen-eral components for protocol implementation.

The structure of this chapter is the following: section 4.1 discusses our approach to developimplementation solutions; sections 4.2 to 4.5 present the main implementation problems we haveidentified; section 4.6 discusses how to handle boundary conditions; section 4.7 discusses generalcomponents for protocol implementation and section 4.8 presents some general conclusions.

4.1 Approach

The framework development process consists of the design and implementation tasks. In ourapproach, these tasks are performed in the software architecture and coding steps respectively(see chapter 2). A framework supports the concepts of a design model. Therefore, the architec-tural semantics [23] of these concepts form the functional requirements for the framework devel-opment process. These concepts are specified in the domain analysis step. Other requirements,such as the restrictions imposed by the implementation environment, available implementationtechniques, and software quality requirements, must be considered in the framework developmentprocess.

In an implementation environment with no provisions for concurrent execution threads, theabsence of mechanisms for directly implementing concurrent threads is an example of restrictionimposed by the implementation environment. Examples of implementation techniques are the useof design patterns, software packages and general purpose components. General purpose compo-nents are pieces of code that can be used in many different frameworks. The software qualityrequirements prescribe that implementation code must be reusable, extendable, portable and effi-cient. The trade-off among these requirements must also be kept in mind while building imple-

Page 70: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

52

Chapter 4: Implementation Solutions

mentation solutions. Figure 4.1 shows an overview of the inputs to the development ofimplementation solutions for frameworks.

Because of the number and nature of requirements in the software development process in generaland also in our particular application domain, this process should rely on human creativity. Anapproach to make the developing of implementation solutions more systematic is the use of heu-ristics, as discussed in chapter 2.

Since we have a specific application domain (protocol implementation), the most common imple-mentation problems in this domain can be identified. By listing these problems, discussing theirpossible solutions, and relating these solutions to the implementation requirements presentedabove, one can considerably improve the efficiency of the framework development process.Therefore, this chapter discusses the implementation problems we have identified when perform-ing experiments with the implementation of frameworks. We analyse the proposed implementa-tion solutions by means of their software architecture. This provides some implementationenvironment independence, improving the reuse of these proposed solutions. An abstract analysisalso shields us from the burden of implementation details. Alternative solutions and the reasonsfor our choices are also discussed in this chapter.

Although the solutions presented in this chapter do not, and could not, cover the whole spectrumof possible solutions, we claim that they can be largely reused, or adapted to support minor varia-tions of the original design concepts being supported.

The implementation problems we have identified relate to the concepts of the Basic Meta-Modelpresented in chapter 2. The main classes of implementation problems we have identified are:

• the implementation of event-driven behaviour;

• the implementation of parallel behaviours, i.e., the behaviour of different components can beperformed in parallel;

• the mapping of component’s behaviour onto implementation code;

• the support of interactions between components, and between components and the systemenvironment;

• the composition of behaviours.

implementation techniques

environment restrictions

software quality requirementsdevelopment

framework

design concepts

reusableextendableportableefficient

design patternssoftware packages

generic components

Figure 4.1 Inputs to the framework development process

Page 71: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.2 Event-driven and Parallel Behaviour

53

Each of these classes of problems is addressed in the sequel.

4.2 Event-driven and Parallel Behaviour

Event-driven and parallel behaviour are basic characteristics of protocols. A protocol entity nor-mally handles events happening at multiple interfaces; the typical example is a protocol entitythat interfaces with a higher and a lower protocol layer. The handling of events at multiple inter-faces characterizes event-driven behaviours. A protocol entity may also perform functions in par-allel, like handling multiple connections, or sending and receiving data.

The support of both event-driven and parallel behaviour determines the high level structure of theframeworks. In essence, each framework should support a collection of components that handleevents and perform functions possibly in parallel.

Since we are implementing components using object-oriented programming, we have decided todefine a component class that implements the component types and a component object thatimplements component instances. This implies that the following is required:

• a component object has an identity, which can be used to connect communication mecha-nisms to this object;

• a component object holds context variables of the component;

• a component class allows components to be dynamically instantiated as often as necessary.During instantiation, a component object can be configured by defining specific parametervalues.

A simple solution to implement parallel behaviour is to map each component’s behaviour onto adistinct operating system process. In this case the operating system is responsible for handlingthe parallelism and interactions among components. However, the mechanisms for implementinginteractions between different processes (inter-process communication) are usually slower thanthe mechanisms for implementing interactions inside a process. Therefore, this solution poten-tially compromises the overall performance of the system. Based on this observation, we havedecided to investigate only those solutions which implement components in a single process.

Depending on the support of parallelism given by the implementation environment, we can applydifferent techniques in the development of the frameworks. Below we present the two most pop-ular of these implementation techniques: the event dispatcher pattern and multi-threading.

4.2.1 Event Dispatcher Pattern

Assuming that objects in a software architecture share a single thread of control and can onlycommunicate by calling each others methods, the treatment of events can only happen in chainsof method calls. In case we decide that a component object blocks its execution waiting for anevent, such as, e.g., an interaction with the environment, the whole collection of objects would beblocked, such that no other event can be handled and no other functions can be performed beforethe waiting object is unblocked. This implies that only one event at a time can be handled andparallelism is not properly supported. Another alternative would be to let each component object

Page 72: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

54

Chapter 4: Implementation Solutions

monitor the occurrence of events by using non-blocking mechanisms, and passing the executioncontrol to another component object when it is ready. This alternative, however, results in a wasteof processing resources, since monitoring tasks and the switching of control between componentswould be continuously done even if no event happens.

Considering that component objects monitor the occurrence of events in a non-blocking way, onecan define a scheduler object that schedules the execution of these component objects. The bene-fit of a scheduler is that each component object does not need references to other componentobjects in order to keep the system running. In this case, the scheduler knows the componentobjects and determines which object gets the opportunity to execute. The next object componentto execute is determined by the scheduler according to a policy. Examples of policies are a pre-defined execution order, or a random choice. After a component object has treated an event or ithas determined that no event was pending, this object returns the control to the scheduler. Figure4.2 shows an execution scheme of this solution.

A scheduler used as above still does not solve the problem of wasted processing resources, sincethe whole system executes continuously even if no event is pending. A solution for this problemcan be obtained by introducing a design pattern in which an event dispatcher object blocks wait-ing for pending events and dispatches the events to the appropriate component objects only whenthese events occur. An event dispatcher object can be seen as a enhanced scheduler that uses theoccurrence of events as the policy to schedule components for execution.

Since the event dispatcher object monitors the occurrence of the events, each component objecthas to register itself and its expected events with the event dispatcher. The event dispatcher objectperforms a loop in which it detects occurred events and calls the appropriate component objects.An execution policy still must be defined to determine which component should be executed eachtime events occur, because multiple events may happen at a time. Different policies can bedefined, for example, based on the relative priority of components or a random choice. The exe-cution policy must be defined according to the requirements of each implementation concerningthe characteristics of the protocol being implemented. Figure 4.3 illustrates this approach.

A similar solution is applied in event-driven interfaces, like the X-Window System [71], where anotifier plays the role of an event dispatcher. Other similar solutions have also been proposed forimplementing protocols in [2] and as a design pattern for communication software in [62] (Reac-

scheduler interfaces

event1

2

3

4

5

6

c1:component

c2:component

c3:component

Figure 4.2 Scheduling scheme

Page 73: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.2 Event-driven and Parallel Behaviour

55

tor Pattern). The event dispatcher pattern has been tailored to solve the problem of implementingasynchronous and parallel behaviour on a single thread of execution.

4.2.2 Multi-threading

Another solution to implement parallelism between components is the use of multi-threadingfacilities [51]. These facilities support several execution threads inside a single operating systemprocess. The use of multi-thread packages allow us to have different chains of method calls of theOOMM being performed in different threads of execution. We assume that each componentobject controls the execution of a thread. This is necessary in order to implement the parallelismbetween components. Since components can interact, one needs to define objects that can executein multiple threads, allowing the exchange of information between the component objects.

Figure 4.4 shows, for example, three component objects, such that each object controls a thread.In order to communicate, a controller object in a thread calls a method of another componentobject. This solution requires that objects must be re-entrant, i.e., their data must be protectedagainst inconsistencies that can be caused by concurrent access.

Since each component object controls its own thread, this scheme allows us to make each compo-nent object monitor its events, in case we allow each component object to block its thread waitingfor its events. This solution works in case each component object interacts with the environment

Interface dispatcher

events

12

3

45

67 8

9c3:component

c2:component

c1:component

event

Figure 4.3 Event dispatcher pattern

c1: comp c2: comp

c3: comp

controller

controller

thread1

c1: comp c2: comp

c3: comp

controller

controller

thread2

Figure 4.4 Multi-threading scheme

Page 74: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

56

Chapter 4: Implementation Solutions

of the system through a single interface. If that is not the case, a scheme similar to the event dis-patcher pattern discussed above could be used. However, this would result in the proliferation ofthe event dispatcher pattern throughout the software architecture (one for each componentobject), such that the system would become much more complex and possibly more inefficientthan if we had used a single event dispatcher for all the component objects.

In order to implement components that interact with the environment of the system through mul-tiple interfaces, we have introduced objects that implement these interfaces, the so-called interac-tion means objects. Each interaction means object monitors the events that can occur at aninterface and controls a thread. Whenever an event occurs, the interaction means object calls thecomponent objects connected to the interface it implements. Figure 4.5 shows that interactionmeans are the controllers of the execution flows in a thread, reacting to occurred events. The com-ponent c1 is called by interaction means im1 and im2, to treat the events they have detected.Objects im1 and im2 hold the control in threads 1 and 2 respectively.

In a multi-processor machine, this solution exploits efficiently the parallel functionalities of pro-tocols. Different threads can be assigned to different processors and real parallelism is obtained.In mono-processor machines, the multi-thread solution only simulates parallelism. Moreover,some extra implementation effort may be necessary, when using threads, to guarantee portability.Multi-thread libraries may have different interfaces in different implementation environments oroffer different functionalities. This problem has been addressed in the development of ACE [63],which consists of APIs for multi-threading that have been implemented in different environments,such as Unix and Windows. By using these APIs one can develop systems that are portable tothese different environments.

4.3 Behaviour Implementation

A protocol behaviour determines the protocol dependent part of a protocol implementation and isintentionally not captured in a framework. Therefore, guidelines for mapping protocol dependentbehaviour onto code that uses the framework must be provided to enforce the efficiency of theimplementation process and its correctness.

im1 :

controller

thread1

interactionMeans

c1: comp

controller

thread2

im2 : interactionMeans

Figure 4.5 Parallel and Synchronous behaviour solution

Page 75: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.3 Behaviour Implementation

57

We have assumed in this thesis that behaviour in our protocol development process can be definedusing finite state machines (FSMs). Therefore, we have to develop a generic solution for imple-menting FSMs and to define corresponding templates that can be filled with code for specific pro-tocols.

According to the definition presented in chapter 3, a behaviour consists of a set of behaviour unitsthat can be triggered in each state of the behaviour’s execution. Each behaviour unit is triggeredby an event. Each event is characterized by the interaction means where it happens and by thecommunication primitive it carries. The triggering of a unit of behaviour is guarded by conditions.In a synchronous model, an event can be an interaction offer, an interaction acceptance or a time-out. In an asynchronous model, an event can be an interaction acceptance or an timeout. Multipleinteraction means can be connected to a component. Multiple communication primitives can hap-pen at an interaction means. A component may react to a communication primitive in differentalternative ways, depending on its current state.

In order to provide a generic solution for implementing FSMs considering the concepts above, wehave to solve the following problems:

• define how a component object determines which behaviour unit is triggered for executionwhen an interaction acceptance has to be performed, considering its current state of execu-tion;

• define how a component object handles timeouts;

• in case of a synchronous model, define which interaction offers are issued by the componentobject, considering its current state of execution.

Furthermore, when implementing behaviours of components we have to consider two importantrequirements: avoid execution when no units of behaviour can be triggered, and guarantee that allenabled units of behaviour receive a chance to make an attempt to interact. These requirementsare discussed in section 4.3.3.

In synchronous models, interaction offers must be given a chance whenever they are enabled. Ifthe interacting components are not synchronized, the interaction offer is refused. However, theinteraction offer should be kept enabled waiting for synchronization, until it is disabled by somechange in the behaviour context. An enabled interaction offer, however, should not keep the sys-tem busy trying to interact, since in this case system resources are wasted.

Below we present two approaches to the implementation of FSMs: nested case-statements and thestate pattern.

4.3.1 Nested Case-Statements

A possible implementation solution for FSMs is to define a method that receives as parametersthe identification of the interaction means where an event has happened (im_id), and the identifica-tion of the communication primitive delivered in the interaction (cp_code). Nested case statementsare then used to identify the unit of behaviour being fired, based on the parameters. The piece ofcode that implements the actions associated with the selected unit of behaviour can be executed ifthe guarding conditions are evaluated as true.

Page 76: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

58

Chapter 4: Implementation Solutions

Figure 4.6 shows our template using an UML Activity Diagram.

The template in Figure 4.6 initially verifies the current state (st) of the component behaviour. Foreach state there are a number of interaction means (im) where events are expected. For each inter-action means, there is a set of possible communication primitives (cp) that can be conveyed. If the

im_idcp_code

[im=im_id1]

[oth

erw

ise]

[cp=cp_code1] [guarding_cond OK]

execute operations

[oth

erw

ise]

[oth

erw

ise]

transition 1

return fail

transition K

[cp=cp_codeK]

release buffer[oth

erw

ise]

im_id1 related transitions

im_idM related transitions

[im=im_idM]

return success

[state=st1]

state1

stateZ

[state=stZ]

[oth

erw

ise]

Figure 4.6 Case-statement based template for FSM implementation

Page 77: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.3 Behaviour Implementation

59

occurred communication primitive is not expected, the event offer is ignored and the data buffer isreleased.

If the communication primitive is expected, a transition may be fired, depending on the conditionassociated with the transition. If the condition is satisfied, the related operations are executed andthe method returns an appropriate code indicating a successful interaction. If the condition is notsatisfied or the communication primitive is not expected, the return code indicates that the interac-tion has failed.

This template can be extended to accommodate for other possible characteristics of design mod-els, such as, e.g., to support transitions triggered by the same interaction offer, i.e., the same inter-action means carrying the same communication primitive, but guarded by different conditions. Inthis case we can add another level of selection to our scheme, in which different guarding condi-tions can be checked.

Figure 4.6 illustrates the use of nested case-statements for the selection of interaction acceptances.This solution can be applied to the selection of interaction offers in the case of synchronous mod-els in a similar way.

4.3.2 State Pattern

The state pattern [2] is a design pattern that can be used to implement FSMs. We discuss here theuse of this pattern to build templates to map protocol behaviour onto code. The state pattern is analternative solution to the one presented above, with the advantage that it conforms better to therules and objectives of object-oriented programming.

The state pattern is applicable when an object’s behaviour depends on its state, such that theobject must change its behaviour at run time depending on its current state. The pattern consists ofa context class, whose behaviour we want to implement, an abstract class called state root andspecializations of the state root. The state root class defines the interface for all the operationsnecessary in the context class. The specializations of state root are concrete classes, whose namemust resemble the meaning of that state. We generically call these classes concrete states. Eachconcrete state class defines the behaviour that is performed by each available operation for a stateof the context. For each possible state there should be a specialization of state root, implementingin this way the complete state space of the object.

The context class must keep a pointer to the concrete state object that corresponds to the currentstate. This allows the context object to re-direct requests, to be treated by the appropriate concretestate object, i.e., the object related to the current behaviour state.

In C++, concrete state classes must be defined as friend in the context class, and receive as param-eter a pointer to the context object. This allows these concrete state classes to work on the contextvariables of the context object as part of the actions being performed. Figure 4.7 shows the struc-ture of the State Pattern.

When applying this pattern to our frameworks, the context class corresponds to the class thatimplements the component design concept. The state root class receives the pair interaction point,

Page 78: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

60

Chapter 4: Implementation Solutions

communication primitive as parameter. The Request method of the context class is called when-ever an event has to be treated by the component.

4.3.3 Event Evaluation Cycle

The process of selecting appropriate units of behaviour to be fired must be continuously per-formed by each component. We call this task the event evaluation cycle. Each time the behaviourgoes into a new state, different events are enabled, and interaction offers must be given a chanceto execute.

In order to avoid a busy waiting loop, the evaluation cycle must block its execution when all ena-bled events have been given an opportunity to execute but none of them have been executed. Wecall this situation a stable (execution) state. After blocking, the evaluation cycle waits until anexternal stimulus brings the state machine to an instable state. External stimulus are typically anincoming interaction offer.

In the case of synchronous interactions, units of behaviour containing an interaction acceptanceshould wait for incoming interaction offers in order to synchronize. However, whenever the inter-acting components do not synchronize in the initial attempt, new attempts should be made. If thisis implemented using busy waiting in the offering component, system resources can be unneces-sarily wasted. A possible solution is to make the accepting component indicate to the offeringcomponent when it is ready to accept the interaction.

When a component indicates its readiness to execute an interaction acceptance to another compo-nent, the latter component moves to an instable state. If each component indicates its enabledinteraction acceptances to their cooperating components without any restrictions, it is possiblethat these cooperating components remain indefinitely in a instable state. In this case, starvation[76] may take place, i.e., the components in the system execute indefinitely but no progress ismade. An example of starvation is presented in section 5.3.2, where we discuss how this can beavoided in the implementation of the event evaluation cycle using the event dispatcher pattern.

Since the actual contents of the units of behaviour are protocol dependent, part of the event eval-uation cycle should be implemented within the code templates that accompany the frameworks.When using the event dispatcher pattern, the event dispatcher must give opportunities to compo-nents to continue their event evaluation cycle, as part of their monitoring loop. When using multi-threading, the evaluation cycle is implemented within a component, requiring an execution thread

Context

Request()

state->Handle()

State Root

Handle()

ConcreteStateA

Handle()

ConcreteStateB

Handle()

Figure 4.7 State pattern structure

Page 79: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.4 Interactions and Interaction Means

61

that blocks its execution when the component reaches the stable state and resumes as a result of anexternal stimulus.

4.4 Interactions and Interaction Means

Considering components mapped onto objects, the basic mechanism for communication betweentwo components is method activation. Method activation can be modelled as two synchronoustwo-party value-passing interactions. Method activation is a blocking mechanism where thereceiving component must treat the incoming message and reply before the sending componentcan proceed its execution. This mechanism has to be extended in case we have to implement morecomplex forms of interaction, such as multi-party and value generation interactions.

We want to develop mechanisms to implement both synchronous and asynchronous interactions.Besides that, the techniques that can be applied to build these mechanisms are constrained by thechoices made for implementing event-driven and parallel behaviour, as discussed in section 4.2.

When implementing mechanisms to support interactions we have to take into account that interac-tions between components (internal interactions) normally have a different nature than interac-tions between components and the environment (external interactions). While implementers havefreedom to develop the mechanisms that implement internal interactions, they are constrained byagreements, like APIs that have to be used or supported, when implementing external interac-tions. This means that we have to treat each of these types of interactions separately at the imple-mentation level.

4.4.1 Synchronous Interactions

The following mechanisms have to be developed in order to support the different forms of syn-chronous interactions:

• Two-party value-passing interaction: a mechanism to send information to the receiving com-ponent, which indicates the acceptance or refusal of the interaction;

• Multi-party value-passing interaction: a mechanism to send information to the multipleinteracting parties. All receiving parties must acknowledge the acceptance of the informa-tion. All parts are informed whether the interaction has been successful or not;

• Multi-party value-generation interaction: a mechanism that waits for all participating partiesand decides about common values that obey the restrictions imposed by all of them. If it ispossible to reach such an agreement, the agreed common values are sent to all participatingparties, otherwise all parties are informed that the interaction has not been successful. Amechanism that can be used for this purpose has been described in [70].

Value-matching interactions can be treated in a similar way as value-generation interactions.

Since each synchronous interaction is expected to be atomic, once a synchronous interaction isexecuted we have to be sure that all actions related to this interaction are performed. A conserva-tive implementation decision is that when an interaction is executed, no actions that do not belong

Page 80: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

62

Chapter 4: Implementation Solutions

to this interaction are executed by the participating components before the interaction is com-pleted. Actions related to an interaction are performed in arbitrary order.

Another issue to be decided upon in the development of interaction mechanisms is the support toconsecutive attempts to synchronize behaviours. These mechanisms can be optimized if theykeep track of the status of each component participating in an interaction, only triggering theinteraction when the synchronization is enabled by all participants. The specific mechanismsdepend on the way interaction means are implemented, and are discussed in the presentation ofthe frameworks.

Event Dispatcher Pattern

An intuitive solution for implementing synchronous interaction is the use of an interaction point(IP) class that concentrates the control of the mechanism for interaction. An instance of such anIP class communicates with the interacting components through the basic OOMM form of inter-action in order to perform the intended mechanism.

The mechanism implemented in an interaction point can be triggered by an interaction offerdelivered by one of the connected components, or triggered by an indication that a component isready to accept an interaction. Indication of readiness is necessary since it is possible that aninteraction does not happen in the first attempt because a component is not ready to interact, butthe same component may change its state, enabling the interaction afterwards.

In order to improve the fairness of the treatment of interactions, an indication of readiness of acomponent is only registered by the other component; the latter does not react immediately, butonly when it executes its event evaluation cycle. After indicating its enabled acceptance, a com-ponent may return the execution control to the event dispatcher, avoiding that a component keepsthe execution control for too long.

In case we want to extend this solution to cope with multiple interacting components (multi-partyinteractions), the interaction point object can be used to keep track of all pending interactionacceptances, and the handling of the corresponding indication of readiness. In this case the eventdispatcher passes the execution control to the interaction point object, which guarantees that allcomponents execute when the interaction is enabled. Figure 4.8 illustrates this approach.

c1:component A c2:component B

ip1:interaction point

synchronous interaction means

connects connects

d:dispatcher

Figure 4.8 Synchronous interaction means

Page 81: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.4 Interactions and Interaction Means

63

In Figure 4.8, the dashed rectangle indicates the code that implements the synchronous interactionmeans. This code consists of part of the component objects and their common interaction pointobject.

Multi-threading

An interaction point that centralizes the control of an internal interaction in order to provide syn-chronization can also be used in combination with the multi-threaded solution. In this case, wecan make use of inter-thread communication techniques, such as signals and common conditionvariables. Although some of these techniques contradict some principles of the object-orientedprogramming, the resulting implementations have proved to be efficient and simple.

The general idea when using threads is to eliminate the event dispatcher by providing a thread toeach element of the implementation to perform their tasks. Therefore, interaction points and com-ponents perform their tasks using separate execution threads. Interaction points monitor externalevents and synchronize with the receiving components. Components trigger their enabled offersand indicate readiness to accept interactions.

Each component executes in a protected way, in order to avoid concurrent access to data. Compo-nents block their execution when trying to get access to a protected code which is already in use.This blocking characteristic of threads implementations may lead to deadlock situations. Forexample, two components blocked trying to get access to each other’s critical region would causea deadlock.

A potential for starvation also exist in the multi-threaded solution we have just proposed. Forexample, components may keep indicating indefinitely to each other their readiness to accept aninteraction, if their interactions do not reach the required synchronization. Algorithms to avoiddeadlock and starvation must be considered when implementing synchronous interactions usingmulti-threading.

Figure 4.9 shows three execution threads controlled by components c1, c2 and interaction pointip1, respectively. ip1 contains a condition variable called condVar. The condition variable is usedby ip1 to monitor interaction acceptance indications. Signals associated to the condition variableare exchanged between threads in order to allow components to indicate interaction acceptance tothe interaction point. If c1 is the sending part of a value passing interaction, thread1 is used to exe-cute the offer. If synchronization initially fails, c2 sends a signal to thread3 when it is ready for theinteraction acceptance.

This solution can be extended for an arbitrary number of interacting components. Chapter 6shows a framework that supports two-party value-passing synchronous interactions, and copeswith deadlock and starvation problems.

4.4.2 Asynchronous Interactions

The support for asynchronous interactions consists essentially of providing a buffering mecha-nism for storing information concerning the interactions and delivering this information. An

Page 82: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

64

Chapter 4: Implementation Solutions

object implementing a link can keep a message queue while communicating with the interactingcomponents through the basic mechanism of the OOMM.

A straightforward implementation of asynchronous interactions is to make the components’behaviours responsible for performing interaction offers and interaction acceptances. An alterna-tive is to use the interaction means implementation to trigger interaction acceptances.

When using the event dispatcher pattern, an object implementing interaction means can be usedto store event offers information. The status of such interaction means must be monitored by theevent dispatcher, in order to awake the interaction means periodically to trigger pending interac-tion acceptances.

When using multi-threading, condition variables can be used in the components to check if anyinformation is buffered in an object implementing an interaction means, to possibly trigger aninteraction acceptance. Such solution must also consider the need to periodically try to performpending interaction acceptances.

4.4.3 External Interaction Means

External interfaces are normally implemented by communication mechanisms such as inter-proc-ess communication (IPC) or interfaces with system devices. IPC mechanisms are required whenthe communicating elements execute in different operating system processes. These communica-tion elements can implement, e.g., two protocol layers, two protocol functions of the same proto-

c1: comp c2: comp

condVarthread1

c1: comp c2: comp

condVar

thread2

uses

ip1:interPoint ip1:interPoint

uses uses uses

signal

data data

c1: comp c2: comp

condVar

thread3

ip1:interPoint

uses uses

signal

data

Figure 4.9 Synchronous internal interaction means with multi-threads

Page 83: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.4 Interactions and Interaction Means

65

col, or a protocol and its user application. Examples of system devices are files, console, keyboardand underlying communication protocols. Some common IPCs and interfaces available areSocket interface [44], System V transport layer interface (TLI) [74], SVR4 STREAM pipes [59],UNIX named pipe/FIFOS [72], and Windows NT named pipes [17].

The communication mechanisms mentioned above have their own characteristics and therefore,we have to deal with their specific constraints. For example, most of these mechanisms supportasynchronous interactions, since information concerning the interactions is buffered before beingprocessed.

Concerning the different types of interfaces, a systematic solution is to build interaction mecha-nisms that hide the details about the interaction from components. A component should be able tointeract with other components without knowing if they are in another operating system processand which construct has been used to support the interaction (sockets, pipes, etc.). Below we dis-cuss the implementation of synchronous and asynchronous external interaction means.

Synchronous Interaction Means

In order to handle external synchronous interactions we can extend the mechanisms for support-ing internal synchronous interactions presented in section 4.4.1. A specialization of the IP classcan be introduced to handle external interactions. We call this specialization external interactionpoint (EIP) class. An EIP object connects an environment object to the internal components of thesystem, giving a differentiated treatment of the interactions with the environment.

In Figure 4.10, the EIP handles multi-party synchronous interactions. EIP could interact with thesystem environment through IPC, IO routines, or any other mechanism.

The EIP specialization should handle the different implementation techniques for external interac-tion. Since the environment of a protocol may be determined at the design level, specializations ofEIP have to be treated as an environment-dependent part of the protocol implementation, andtherefore they can not be captured by the framework. However, when building frameworks wecan provide code templates that contain the generic part of the functionalities that must be sup-ported by EIPs. The process of handling an external interaction consists of the following tasks:

• detecting that an interaction offer has happened;

• getting/putting information from/in the buffer of the system external interface;

component a

component b

EIP environment

protocol entity (OSP)

basic OO communicationmechanism

IPC, IO routines

Figure 4.10 External interaction point

Page 84: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

66

Chapter 4: Implementation Solutions

• decoding/coding the information on the interactions happening at this interaction point, suchas, e.g., service primitives;

• validate the interaction, i.e., check if the communication primitive can be accepted by thebehaviour of the components at their current state (see section 4.6.2);

• possibly react to the interaction (protocol-dependent behaviour).

Considering the event dispatcher pattern, these tasks are distributed among the event dispatcher,the interaction point and the component objects. The event dispatcher detects events, interactionpoints get and put information on external interfaces and perform coding, decoding, and valida-tion of this information, and components react to these events.

Considering multi-threading, an EIP must monitor its related interactions. Interacting EIP andcomponent objects can generate signals to each other, in order to indicate the occurrence of aninteraction or the readiness to accept a pending interaction, respectively.

Most mechanisms that implement external interaction means are asynchronous, such as, e.g.,sockets and pipes. Therefore, when implementing synchronous interaction means using thesemechanisms we need to handle this difference. An alternative is to build synchronization mecha-nisms making use of the available asynchronous mechanisms. In this case, one component canplay the role of initiator and the other can be a responder. The initiator generates an interactionoffer, sends it to the responder and blocks waiting for a confirmation. The responder accepts theinteraction offer and sends a confirmation to the initiator. In this way, a synchronous interaction isbuilt using two asynchronous interactions. Since in this alternative we make assumptions on theway both the initiator and the responder behave in order to implement their interactions, this alter-native is mostly suitable to implement interactions between components that are in the sameimplementation domain (e.g., being implemented by the same manufacturer).

Another alternative to build external synchronous interactions is to consider the interaction withthe environment as synchronous, by assuming that the buffering functionality belongs to the envi-ronment. By making this assumption we support the direct implementation of simple forms ofsynchronous interactions, such as sending and getting some data from the environment’s interface(value-passing). Protocol designers using this alternative must be aware that the environment pro-vides an asynchronous service. If, for example, a synchronous underlying service is required andan asynchronous service is available, as it is the case in the socket interface, the protocol beingdeveloped must provide such functionality itself.

Asynchronous Interaction Means

The implementation of an external interaction means for asynchronous interactions has to copewith the buffering of received information and the triggering of pending interaction acceptances.Besides these requirements, the interaction offers must be detected, information must be takenfrom these offers and put in the buffers of the external interfaces, information must be coded anddecoded, and events must be validated and treated.

In order to implement asynchronous external interactions, interaction offers can be detected bythe event dispatcher or by the EIP in a multi-threaded solution. The EIP can code, decode and

Page 85: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.4 Interactions and Interaction Means

67

buffer information. The EIP can also check if communication primitives are valid and can notifythe occurrence of an interaction offer to the appropriate component. Acceptance and treatment ofinteraction offers are performed by the components.

In chapters 5 and 7 we discuss the implementation of an interaction means that supports synchro-nous two-party value-passing interactions using the event dispatcher pattern. In chapters 6 and 8we discuss the implementation of an interaction means that supports the same type of interactionas above, but using multi-threading. We focus on the synchronous interactions in our frameworks.The development of a flexible solution that allows the coexistence of synchronous and asynchro-nous interactions in a single framework remains a subject for future work.

4.4.4 Timing Requirements

A timing requirement often found in protocol designs is timeout, in which a behaviour waits forsome event to happen and if this event does not happen in a certain period of time some actionsare taken. Therefore, we have to implement mechanisms that monitors the elapsing of a certainamount of time. Such monitoring mechanism we call a timer. A timer is started when required andconfigured to wait for a given amount of time. It should be also possible to reset the timer if theevent being expected happens in the meantime. Frameworks should allow multiple timers to berelated to a single component.

Event Dispatcher Pattern

Our solution for implementing timeout consists of defining a timer object. The timer must work inparallel with the component that needs its service. In this case, this implies that the event dis-patcher must give the timer opportunities to execute.

Timers are registered in the event dispatcher object as interaction means. The amount of elapsedtime that has to be monitored by the timer is informed to the event dispatcher at the moment of theregistration. The event dispatcher calculates the earlier timeout based on the registered timers andpass this value to an operating system function that blocks waiting for events or the indicatedtimeout (e.g., the select in Unix). If this function returns an indication that no event has happened,it means that the timeout has expired. The event dispatcher informs the occurrence of the timeoutto an object implementing the related timer. The timer then indicates the occurrence of an event oftype timeout to the corresponding component. When a single component uses more than onetimer, timeout events should properly identify their related timers. Timeouts are handled by com-ponents in the same way as the other events.

A timer may be active or inactive. An active timer is monitored by the event dispatcher, while aninactive one is not. A timer is inactive when it is instantiated and must be activated by its relatedcomponent. Activation is performed through an operation called by the component object, givingthe timeout period as parameter. A timer should be deactivated when it is no longer necessary.

Figure 4.11 shows the use of a timer in the implementation of a protocol behaviour. The behaviourused in the example has two states, IDLE and WAITING. In the IDLE state, when a communica-tion primitive DR occurs, the timer is activated to wait for 5 units of time. In the state WAITING,the behaviour allows the occurrence of an AC communication primitive or a TO (timeout). If an

Page 86: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

68

Chapter 4: Implementation Solutions

AC happens, the timer is no longer needed and is deactivated. If a TO happens, some operationsare performed and the timer may be activated again, for example, to wait once more for an ACprimitive.

Multi-threading

In the case of multiple threads, each timer needs to execute in a separate thread in order to blockthe execution while monitoring the timeout. A command for blocking the execution flow basedon condition variables can be used for that purpose.

When blocking the execution flow we must apply a function that allows one to specify, throughparameters, the maximum time the thread blocks waiting for a change in the condition variable.For example, the pthread_cond_timedwait function of the POSIX threads package [57] fulfils thisrequirement. Signals can be sent by other threads in order to indicate changes in the conditionvariable. The sending of a signal can cause the timer to be deactivated. When the specified timeelapses, the timer indicates a timeout event to the component.

An object implementing a timer creates a new thread for performing the monitoring function eachtime the timer is activated. Such thread finishes its execution as soon as the timeout occurs or thetimer is deactivated. Timers must hold an identification to allow components to distinguish time-outs indicated by different timers.

Deactivation requires some more attention in this case than in the event dispatcher pattern, wheredeactivation is performed by simply setting a flag in the timer. When using multiple threads, atimeout event may have been already triggered when we want to deactivate the timer. The threadused to monitor the timeout could be waiting to perform a component’s method that is blocked bya mutual exclusion mechanism. The timer’s thread must check the status of the timer after it gainsaccess to the component’s method, in order to avoid unexpected timeouts.

parameters

[state=IDLE]

action activate timerto 5 seconds

[state=WAITING]

[cp=AC]actions deactivate

timer

[cp=TO]actions

activate timerto 5 seconds

return success

[cp=DR]

Figure 4.11 Using timers

Page 87: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.5 Behaviour Composition

69

4.5 Behaviour Composition

In order to implement behaviour composition, we define a composition class and use compositionobjects inside a component to represent the structure of the component’s behaviour. The composi-tion objects restrict the behaviour that is executed based on the protocol-dependent behaviour ofthe component. The composition is specialized in sub-classes that implement the different typesof behaviour composition. This section illustrates the functioning of behaviour composition bydiscussing the choice specialization of a composition object.

Consider, for example, a component’s behaviour consisting of two behaviours in a choice compo-sition. For each incoming event, a choice object (specialization of a composition object), deter-mines the behaviour that is allowed to treat the event. Since the choice object does not know aprior which behaviour is capable of handling the event, it offers the event to both related behav-iours, one at a time, until one of these behaviours executes. Each behaviour returns to the choiceobject an execution indication or indicates a match failure. Once a successful execution indicationis received, the choice stores the information on which behaviour accepted the event. Thereafter,all new interaction offers are delivered to the chosen behaviour. Figure 4.12 illustrates this proce-dure using an UML Interaction Diagram.

In Figure 4.12, the first interaction offer is refused by behaviour-1 and accepted by behaviour-2.The second interaction offer is delivered directly to behaviour-2, because it has being chosen inthe first interaction. However, since the interaction offer does not match any transition in behav-iour-2, a failure indication is returned to the choice object. The third interaction offer is acceptedby behaviour-2, and we suppose that behaviour-2 finishes its execution as a result of this interac-tion.

The composition behaviour can be seen as a tree of related composition objects that point to behav-iours that correspond to the leaves in the tree. Each composition object has to propagate theresults of the interaction attempts to the higher level compositions of the tree. Results may have tobe properly interpreted before being propagated upwards.

behaviour1 behaviour2choice

interaction offer consult

[no match] consult

[success]

interaction offer

[finished]

[success]

[finished]

interaction offer

[no match][fail]

Figure 4.12 Choice behaviour composition procedure

consult

consult

Page 88: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

70

Chapter 4: Implementation Solutions

For example, if the composition relation is an interleaving, the indication of end of behaviour exe-cution ([finished] in Figure 4.12) by one of the composed behaviours may not imply that the result-ing composed behaviour also finishes its execution. If other behaviours of the interleavingcomposition remain executing, the result to be propagated should be modified to [success].

Figure 4.13 shows a tree of related behaviours and compositions. In this figure, boxes representbehaviours (sets of units of behaviour), the lines indicate the associations, and the rounded-cornerrectangles represent compositions.

In order to be generic, this solution must handle the following issues:

• composition objects must be capable of handling n-ary compositions;

• composition objects should be capable of delivering notifications to other composition objectsthat implement composition of composed behaviours, e.g., when a composition of behav-iours A and B is composed with a behaviour C.

This approach to behaviour composition has been used with both the event dispatcher pattern andmulti-threading in this work. Since true concurrence is not possible with the event dispatcher pat-tern, the resulting software architecture only supports interleaving. Using multi-threading, welimited our experiments to the implementation of interleaving, since the support to parallelismwould imply in drastic modifications of the software architecture. The implementation of concur-rent behaviours within a component in the scope of the approach presented here remains forfuture work.

4.6 Boundary Conditions

This section discusses some implementation decisions that are necessary to handle boundary con-ditions: initialization, termination and failures. In this context, this section also discusses issuesrelated to exceptions, such as the ones generated by unexpected events, and the consistencyrequirements imposed by the design models.

sequence sequence

choice

interleaving

B

B B B B B B

Figure 4.13 Tree of behaviours and compositions

Page 89: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.6 Boundary Conditions

71

4.6.1 Initialization and Termination

During system initialization, the state variables of components are initialized with appropriatedvalues, the necessary resources are allocated and the system is configured. An example of statevariable is the global state of a component behaviour. Examples of resources that must be allo-cated are lists and buffers. Instantiation of classes can also be seen as an example of allocation ofresources in the object-oriented programming paradigm. System configuration consists of con-necting the related elements of the implementation, e.g., through the exchange of references.

Whenever an object is terminated, its references should be removed from other objects. When thesystem is terminated, buffers should be deallocated.

In object-oriented programming, constructors and destructors of classes are the proper places totake care of initialization and termination issues, respectively. For handling initialization issuesinvolving multiple objects, we can introduce an initialization object that instantiates and connectsthese objects in order to properly initialize the system.

Initialization and termination can be static or dynamic. Static initialization takes place during sys-tem initialization, before the system is operational. Dynamic initialization takes place at run-time,possibly as an operation performed by the protocol. Static termination takes place when the sys-tem terminates its operation and dynamic termination takes place when objects of the implemen-tation terminate but the system still keeps running. This classification is necessary in order todetermine the level of robustness to be supported by the frameworks (see section 4.6.3).

4.6.2 Exceptions

When using design models based on synchronous interactions, a system designer specifies theinteractions that take place at a certain abstraction level, leaving the treatment of exceptions suchas unexpected or incomplete interactions, to be handled at lower abstraction levels. For example,when implementing synchronous interactions using asynchronous mechanisms, information onunexpected interaction offers has to be constantly removed from buffers, in order to avoid dead-locks.

An interaction offer may be refused for two reasons: it contains an invalid communication primi-tive for the receiving interaction point or one of the interacting components is not ready to per-form the interaction. In the first case, the interaction offer can be discarded and the interactiondoes not take place. In the second case, two alternative approaches can be used:

• the interaction offer is evaluated and discarded in the component. A warning message maybe issued to the sending part of the interaction, depending on how synchronism is beingimplemented. In this case, an exception handler procedure to perform this task must beattached to the code templates that are filled in with protocol-dependent code;

• the protocol-dependent part of the implementation contains a method that informs whichevents are expected at the current state of the protocol. The code template must provide a pro-totype for this method. Unexpected interaction offers can be discarded by the interactionpoint object or by the event dispatcher object. These objects can ask the components for theirexpected events, discard or deliver incoming events, and possibly notify the sender part of

Page 90: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

72

Chapter 4: Implementation Solutions

the interaction.

Asynchronous design models normally provide means to specify the procedures to handle unex-pected events. This is the case, for example, in ESTELLE, which allows the designer to specifyan ‘otherwise’ clause for handling unexpected events in a certain state of a behaviour.

4.6.3 Consistency

A design model normally contains a set of consistency rules that restricts the use of the designconcepts in order to guarantee that only consistent designs are produced. A typical example ofthese rules is the LOTOS static semantics requirements [36].

When designing a framework, one has the choice of assuming that the designs that will be imple-mented using the framework always comply to the consistency rules of the supported designmodel. In this case, the framework is relieved from the task of checking consistency. Alterna-tively, one may assume that the designs can be inconsistent, leaving the responsibility of guaran-teeing consistency to the framework. This choice determines the robustness of the frameworkwith respect to the designs being implemented. For example, an interaction point has to be con-nected to at least two components, or each component needs to be attached to at least one interac-tion point. We may assume that all designs being implemented obey these rules or we may buildfacilities in the framework that check these rules and warn when interaction points and compo-nents that do not comply to these rules are created.

Some procedures that follow from consistency rules can be automated by the framework, reliev-ing the designer from the task of explicitly specifying all these procedures. Normally these proce-dures are related to the dynamic termination of objects that implement design concepts. A typicalexample is the termination of a component, which implies in the termination of all its behaviourparts, behaviour compositions, and interaction points.

In addition to the consistency rules discussed above, we also identify consistency rules that applyto the implementation at runtime, such as the rules that guarantee the consistent state of datastructures and buffers. A mechanism that implements such rules is, for example, garbage collec-tion. Consistency rules at runtime are software engineering issues and have been considered inthe development of the frameworks but are not further discussed in this work.

4.7 General Components

Our model-based approach for protocol implementation applies fine granularity building blocks,i.e., we provide elementary design constructs at the implementation level. This gives maximumflexibility for designers to build solutions, but may decrease the effectiveness of the implementa-tion process. Other approaches, as, for example, the one in [56], use building blocks of coarsegranularity as a strategy for increasing the efficiency of the implementation process at the cost ofdecreasing design flexibility.

The ideal situation is to use both approaches discussed above in combination, taking advantage ofboth of them. Protocol functions that are commonly used in different protocols can be identified

Page 91: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

4.8 Conclusions

73

and re-designed to be generic, and therefore more re-usable. We call these commonly used proto-col functions general components. Requirements that could not be fulfilled by applying generalcomponents are then addressed by using fine granularity design concepts. Implementations ofgeneral components can be placed in libraries and their interface can be documented to be used atboth the design and implementation levels.

General components for protocol implementation can be either more related with data manipula-tion, such as, buffering management, or more related with behavioural concepts, such as, func-tions to perform flow control. Our approach for implementing protocols gives support to theimplementation of the second group of general components. General data manipulation compo-nents, which have being studied and tested, are available in the literature [11] and therefore can beconsidered reliable. Some tools that give support to the implementation of general components inthis class also exist, producing reliable code [50].

General components related to behavioural concepts can be implemented using our method oncethey are specified using the design concepts supported by an available framework. The develop-ment of a library of general components for each framework remains for future work.

4.8 Conclusions

The process of defining implementation solutions for abstract concepts involves a large number offactors, mainly when we do not consider a specific implementation environment. Besides that,numerous implementation techniques are available and in different environments, and softwarequality requirements are difficult to quantify and assess. These characteristics make it hard toestablish a systematic and detailed procedure to perform this step of software development in gen-eral, and also for the development of our frameworks. Developing software solutions under thesecircumstances has to be done for each case. This is a research process on its own.

In this chapter, we have provided support for performing the implementation step by structuringthis problem in sub-problems and proposing architectural solutions for each sub-problem, consid-ering some available programming techniques. For each solution, we have discussed its requiredfunctionality and some issues on integration with other solutions. The architectural solutions pre-sented here are applied in the framework examples presented in the next chapters. Therefore,more details on the implementation of these solutions is found in the description of the frame-works in the next chapters.

We have also contributed to the process of implementing design concepts by discussing issuesrelated to boundary conditions, and by pointing potential areas for future developments, e.g.,development of building blocks of coarser granularity.

Page 92: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

74

Chapter 4: Implementation Solutions

Page 93: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

75

Chapter 5

Basic Event Manager Framework

This chapter presents the Basic Event Manager Framework, which is the first of our three frame-work examples. The Basic Event Manager Framework supports components that perform an asso-ciated behaviour and interact through synchronous interaction means. This chapter also discussesin detail the use of our framework development method.

The structure of this chapter is the following: section 5.1 presents our approach for the develop-ment of this framework; section 5.2 presents the domain analysis step; section 5.3 presents thesoftware architecture step; section 5.4 documents the information necessary for an implementer touse this framework; section 5.5 presents an example of application of this framework to imple-ment a simple protocol and section 5.6 presents some conclusions.

5.1 Approach

The Basic Event Manager Framework supports a simple design model, which, however, defines aset of concepts that is applicable to protocol development, as we show. This framework consti-tutes a contribution to the catalogue of frameworks for protocol implementation discussed inchapter 2. In this framework we apply the implementation solutions presented in chapter 4. Thischapter discusses some relevant implementation decisions that have been added to those pre-sented in chapter 4.

The framework documentation presented in this chapter is also intended to provide a documenta-tion pattern to be used when adding entries to the framework catalogue. A good documentationmust provide support to developers when analysing the suitability of a framework for the imple-mentation of a specific protocol, considering the restrictions and consequences of its implementa-tion solutions. The documentation must clearly guide the protocol implementation processapplying the framework, and provide support for framework maintenance, e.g., when reusing aframework in the prototyping of new ones.

This basic framework is also used to discuss the framework development method in detail. A sim-ple framework avoids the burden of the complexity of the framework itself, allowing us to focuson the steps to be performed in the protocol development process. We present the framework in

Page 94: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

76

Chapter 5: Basic Event Manager Framework

terms of the deliverables of the framework development method recommended in chapter 2, i.e.,domain analysis, software architecture and documentation.

We use in the domain analysis the definitions of design concepts presented in chapter 3, such thatdata dictionaries can be omitted. For sake of space, we do not discuss the coding step. The inter-ested reader can refer to [80] for the complete implementation code.

The implementation decisions taken in the development of this framework are largely supportedby the solutions discussed in chapter 4, to which we refer whenever appropriate. Such solutionswere also partially guided by the heuristics presented in chapter 2. These implementation solu-tions are also the result of experiments carried out to combine design patterns and the implemen-tation solutions roughly elaborated in chapter 4 into stable implementation code.

This framework also forms a core implementation that can be extended when developing morecomplex frameworks. For example, the framework presented in chapter 7 has been obtained byadding capabilities to the basic framework presented in this chapter.

The framework presented in this chapter relies strongly on the implementation concept of anevent dispatcher. In this framework, an event manager object plays the role of event dispatcher.This framework is called Basic Event Manager Framework due to the central role played by theevent manager object in the software architecture of this framework.

5.2 Domain Analysis

This section defines the characteristics of the design model supported by the Basic Event Man-ager Framework. We refer to this design model as basic design model (BDM). The definition ofthe concepts belonging to the BDM is made by selecting the concepts from those presented inchapter 3. The classes drawn in gray in the figures presented in this section indicate concepts thatdo not belong in the design model being supported by the framework.

The BDM uses the concept of component. Components are statically created/destroyed and canbe parameterized. Figure 5.1 shows the class diagram for these concepts.

The BDM makes use of the interaction point specialization of the interaction means concept. Aninteraction means in this design model can only be connected to two components. A componentcan have many interaction means connected to it. Figure 5.2 shows the relation between compo-nents and interaction mechanisms in the BDM.

component

parameterized statically

created/destroyed dynamically

created/destroyed

{overlap}{disjoint}

Figure 5.1 Component specializations

Page 95: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

77

Only synchronous interactions are supported by this framework. Interactions are single valuepassing and two-party. Figure 5.3 shows the specialization of the interaction concept supportedby the Basic Event Manager framework.

All the behavioural concepts that compose an unit of behaviour are present in the BDM. Thetypes of events monitored in this model are interaction acceptance, interaction offer and timeout.The BDM applies the default firing policy for the execution of units of behaviour within a mono-lithic behaviour. Figure 5.4 shows the specializations of the event concept. An extended finitestate machine is used to relate behavioural concepts in behaviour specification.

5.3 Software Architecture

This section discusses the software architecture of the Basic Event Manager Framework. The col-lection of components of a system altogether execute in a single operating system process. Themain implementation decisions taken during the development of this framework are: a) the use ofa single thread implementation, with the consequent use of an event dispatcher (eventManagerobject) to handle the event-driven characteristic of protocols, and b) the mapping of componentsonto specializations of a single abstract class eventHandler. These implementation decisions havedetermined the global structure of the framework and characterize this framework.

interactionmeans

interactionpoint link

component 2is connected to

1..*{disjoint}

Figure 5.2 Event means sub-diagram

synchronous

two-part multi-partvalue-passing value-checking value-generation

0..*0..* 0..*

interaction

{disjoint}

Figure 5.3 Interaction specialization

guards

context

actioneventuses

interaction timeout conditionparticipation

spontaneous

triggers

{disjoint}

behaviour

Figure 5.4 Event types in the BDM

Page 96: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

78

Chapter 5: Basic Event Manager Framework

This framework consists basically of three object classes: eventHandler, eventPoint and event-Manager. The specializations of the class eventPoint are explained later in this chapter. Figure 5.5shows the class diagram for the Basic Event Manager Framework software architecture. Theclasses drawn in gray are protocol dependent part of the framework and available as templates. Atemplate is an incomplete implementation code that must be filled in with protocol specific code.

Figure 5.5 Basic Event Manager Framework high-level software architecture

5.3.1 EventManager

The event dispatcher pattern must be specialized in order to be integrated with other implementa-tion solutions adopted in this framework, such as the implementation of external interactionpoints, time events and component’s behaviour. External interaction points implementations areresponsible to treat the occurrence of events, which are indicated by the event dispatcher. Theevent dispatcher also reports time events to timer implementations to be handled, and give theopportunity to behaviours implementations to execute their enabled interaction offers.

The event dispatcher is defined in the eventManager class. It implements a monitoring cycle wherea) the monitoring function is prepared, based on active interaction points and timers, b) detectedexternal events and timeouts are dispatched, and c) an opportunity for execution is given to exist-ing components. External interaction points, timers and components register themselves with theevent manager, which uses their references to perform its functions. Figure 5.6 describes monitor-ing cycle, which consists of the following steps:

(1) evaluation of the earliest expected timeout;

(2) preparation of the parameters for the monitoring function, defining the file handlers that must be monitored and the time interval;

(3) start monitoring function;

(4) activates the interaction means related to an occurred interaction offer;

(5) call the appropriate timer implementation to treat a timeout;

(6) call appropriate components to perform their interaction offers.

monitors

calls

specific interface n

eventManager

eventHandler eventPoint

timerexternal

1..*

uses 1..*

1..*

1..*

internal

*

{disjoint, incomplete}

{disjoint}

{abstract} {abstract}

{abstract}

{abstract, template}

component n{template}

{disjoint, incomplete}

protocol specific ip n

{disjoint, incomplete}

{abstract, template}

Page 97: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

79

The result of the monitoring function is a list of file handlers where interaction offers have beendone by the system environment. If more than one interaction offer have happened, only one ofthem is treated per monitoring cycle. In order to choose an eventPoint in case of multiple events,we introduced a token that circulates through the list of registered interaction means. The interac-tion means that has the token is allowed to execute the event. The reason for treating a single exter-nal interaction offer at this point is to provide fair chances for the treatment of internal andexternal interactions.

If more than one active timer implementation are registered in the eventManager object, only theearliest expected timeout is monitored in this evaluation cycle. If there are no timer objects active,the function waits indefinitely for an external interaction to occur.

In step 6, components are given an opportunity to execute their tasks. In this step, all possibleinternal interactions must be treated to avoid a deadlock situation. A deadlock may happenbecause the event manager’s monitoring cycle blocks its execution waiting for external events inthe next cycle, and future external interaction may need to be enabled by a pending internal inter-action. Therefore, it is necessary to find a condition that guarantees that no internal interaction canbe triggered in a certain stage of the execution, without the protocol entity receiving an externalstimulus, i.e., an external interaction. This condition can then be used to stop giving opportunitiesto components to execute their event evaluation cycle.

Since, an internal interaction can enable other internal interactions, it is not enough to give a sin-gle opportunity for execution to each component. An appropriate condition is to give opportuni-ties to components until all components have received an opportunity and no one has performedan interaction. This condition assumes that once a component receives an opportunity to performits monitoring cycle, it triggers one interaction whenever possible.

The monitoring cycle of the eventManager is called at the end of the system initialization and runswhile the protocol implementation is operational.

5.3.2 EventHandler

The eventHandler is an abstract class that supports the implementation of components. Since thebehaviour performed by components is protocol-specific, in this abstract class we only implementthe generic functionalities of components, leaving the protocol-specific functions to be imple-mented by its specializations. This abstract class simplifies the framework implementation proc-ess, reducing the complexity of the remaining required code to implement protocol behaviour.

1 2

4

5

3

[interaction offer]

[timeout]

6

Figure 5.6 EventManager class monitoring cycle

Page 98: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

80

Chapter 5: Basic Event Manager Framework

The basic functionality implemented in the eventHandler class consists of common attributes ofcomponents, like the major execution state and behaviour stability flag, methods to support theimplementation of the event evaluation cycle, and a common prototype for the method that cap-tures the component’s protocol-specific behaviour (Interact method).

The event evaluation cycle is responsible for selecting and treating enabled units of behaviour,until the first unit of behaviour triggers an event, or until the component reaches the stable state.The execution control is delivered back to the eventManager when the evaluation is completed,informing whether an event was triggered or not.

The event evaluation cycle is implemented in this framework using two methods: EvalCycle andInteract. The EvalCycle method implements the fixed part of the evaluation cycle, i.e., the controlof whether the cycle should be suspended or not. The Interact method is used to implement thecomponent’s behaviour, which is the protocol-specific part. Each component of a protocol isimplemented as a concrete class that inherits from the eventHandler class. This concrete classoverloads the Interact method to implement the component’s behaviour.

The eventHandler class also provides an abstract class that can be referred to when one wants tomanipulate the different components in an implementation, abstracting from the differencesbetween these components. Such abstraction is provided by the dynamic polymorphism sup-ported in some object-oriented languages, which makes use of references to abstract classes. Forexample, the eventManager object can manage the different components in a protocol by keepingreferences to their abstract class, i.e., the eventHandler class. When a method is called of an objectknown by the eventManager only by its abstract class, the method actually executed is the methoddefined in the specialization class.

Interact Method

The basic tasks to be performed in the Interact method are the acceptance and treatment of incom-ing interaction offers, and the triggering of enabled interaction offers. The case-statement solutionfor behaviour implementation is used here to perform this task. Due to our implementation deci-sion to leave the synchronization of interacting components to be treated together with the behav-iour implementation, the Interact method must also cope with this requirement. This isaccomplished by indicating to the synchronizing components that interaction acceptances havebeen enabled.

The method EvalCycle calls the Interact method to trigger enabled interaction offers or to indicateenabled interaction acceptances. The triggering of an interaction acceptance occurs when aninteraction point calls the Interact method to treat an incoming interaction offer.

The Interact method receives three parameters: the identification of an interaction point (im-id), acommunication primitive (cp-code) and an indication (role) of whether the call is to treat anincoming offer (role=offer) or if it is an attempt of the EvalCycle to reach the component stability(role=stability). The two first parameters are only meaningful if the role is an offer.

To each incoming call, the Interact method first identifies the group of enabled units of behaviour,based on the current behaviour’s major state. Each unit of behaviour in the selected group is then

Page 99: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

81

processed according to its characteristics (acceptance or offer), and according to the value of therole parameter. If the purpose of the call to the Interact method is to perform an acceptance, theunit of behaviour that matches the incoming offer must be selected and triggered. If the purpose ofthe call is to trigger enabled offers, all offering units of behaviour must be triggered and all ena-bled interaction acceptances must be indicated. The details of processing each one of these casesare presented in Figure 5.7.

The Interact method returns a failure indication in case no unit of behaviour matches the incomingoffer, or if no outgoing offers are accepted. The method returns an indication of success when thefirst outgoing offer or an acceptance is processed. The code template for the Interact method mustbe filled with the appropriate code for as many units of behaviour as required for the behaviour.This code consists of the communication primitives expected in each state and the correspondingactions and guarding conditions. Protocol specific information is underlined in the template pic-ture in Figure 5.7.

The Interact method also treats the end of a component’s behaviour. This method defines as one ofthe possible states a state called END in which any incoming interaction attempts fail. Therefore,if the protocol behaviour eventually reaches an end, the behaviour’s global state must be set toEND.

The implementation of the Interact method is provided to protocol developers as a code templateto be filled in during the implementation of protocols.

Timing Events

In chapter 4 (section 4.4.4) we have proposed some basic implementation constructs to handletiming events. Such constructs are: timer creation, activation and deactivation. As suggested inFigure 4.11, these constructs should be placed in the actions of different units of behaviour toobtain the intended semantics of a timeout. In this way, implementers should decide where andunder which conditions timers should be activated or deactivated.

In the sequel, we describe a more systematic approach to map time based events onto implemen-tation code, making use of the constructs proposed so far. The requirements to be fulfilled hereare: the monitoring of the elapsing of a certain period of time should be triggered once the behav-iour reaches the timing event enabling state. The triggering of the monitoring task may be guardedby a condition. A timeout will happen if the behaviour remains in the enabling state and theguarding condition remains true for the specified period of time. The occurrence of other events inthe enabling state, which do not change the conditions for timeout, do not interrupt the timingmonitoring. If the timeout occurs and all the enabled conditions remain unchanged, the monitor-ing task is re-started. Figure 5.8 illustrates such cases. The event e1 leads the behaviour to the ena-bling state, where e2, e3 and T are enabled. T represents the timing event and is guarded by thecondition c1. The occurrence of e2 do not stop the monitoring of T if c1 still holds. The occurrenceof T, re-starts the monitoring if c1 still holds. T, however, must be deactivated if e3 occurs, sincethe current state changes in this case.

Our proposal is to build an implementation construct that can be applied systematically, onlyrequiring the introduction of the protocol-specific information like guarding condition, action,

Page 100: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

82

Chapter 5: Basic Event Manager Framework

elapsing time and reference to the timer implementation. The solution is to define a general tem-plate to build the units of behaviour related to timing events. The algorithm to activate and deacti-vate the timer is contained in this template. Such an algorithm is shown in Figure 5.9.

(offer template)

[offer] execute interaction

offer[succeed]

[acceptance]

[acceptance] [ep&&cp] getinformation

[guardingcondition]

action

[offer]

indicateenabledcondition

[otherwise] [otherwise]

im-idcp-coderole

[st1]unit of behaviour 1

unit of behaviour 2

unit of behaviour n

...

st1 related units of behaviour

st2 related units of behaviour[st2]

end state procedure [END]

...

fail

Interact method

unit of behaviour

unit of behaviour

(accept template)(ep)

action(ep,cp,data)

(ep)

Figure 5.7 Behaviour implementation templates

timer relatedtemplate

success

Page 101: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

83

In order to deactivate the timer, the code shown in Figure 5.10 is required in the template of theInteract method. Figure 5.7 shows the position of such code within the Interact method.

Avoiding Starvation

In the implementation of the event evaluation cycle, a potential exists for starvation. Figure 5.11shows an example of starvation, using the UML notation for state diagrams. The figure shows thebehaviour of two components A and B. The current state of each component is represented by adot inside the state. An external event is represented by E. Interaction offers and acceptances areidentified by o and a, respectively. Corresponding interaction events (offers and acceptances) arerepresented using the same number in Figure 5.11.

enabling state

e1

e2

T/c1

e3

Figure 5.8 Timing event situation

[timer is not active]

action

[otherwise]

unit of behaviour(timeout template)

[act==offer]

[ep=timer]

returnsuccess

[guarding condition holds]

[otherwise]

[otherwise]

Figure 5.9 Template for time related unit of behaviour

activate timer

[timer active][ guarding condition

unit of behaviour

does not hold ] deactivatetimer

(timer related template)

Figure 5.10 Timer related template

Page 102: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

84

Chapter 5: Basic Event Manager Framework

When performing its event evaluation cycle, component A indicates a2 to B and goes to a stablestate. The indication of a2 takes B to an instable state. When B executes its event evaluation cycle,it indicates a1 to component A, taking A to an instable state. Considering the event dispatcher pat-tern, when the event dispatcher gives opportunities to the components to perform their internalinteractions, all components should reach the stable state before the event dispatcher can continuewith its monitoring cycle. At this point, the event dispatcher checks the occurrence of externalevents. Since in this example the components remain instable, starvation can be observed becauseno external event can be handled.

A possible solution to this problem is to allow acceptance indications only when the global stateof the component’s behaviour has been changed, compared to the state in the previous evaluationcycle. In this way, components only perform acceptance indications once, which is enough for thesynchronization process.

5.3.3 EventPoint

In the Basic Event Manager Framework we use the abstract class eventPoint to support the imple-mentation of timers, internal and external interaction means. In order to support these concepts,the eventPoint class is specialized in internal, external and timer classes, as shown in Figure 5.5.Below we discuss each of these specializations.

The eventPoint class implements the common features of all its specialization, such as associationwith other elements of the implementation, buffering area, data manipulation, and prototypes forvirtual methods.

External Class

The external class implements the common characteristics of external interaction point specializa-tions, such as the use of file handlers and interaction synchronization. This class has to be special-ized in classes that handle different types of communication interfaces, e.g., file handlers andlower level communication services. The typical tasks performed by the specializations of theexternal class are getting and putting messages on system interfaces, coding and decoding of inter-action information, and opening and closing handlers.

The specializations of the external class are developed as part of the implementation of particularprotocols, capturing the specific characteristics of the protocol external interfaces available in thetarget implementation environment. The framework provides templates to guide the implementa-tion of environment specific code to handle external interfaces.

Figure 5.11 Starvation situation

E

a2

o1a1o2

Component A Component B

Page 103: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

85

We implement synchronous interactions with asynchronous interfaces in this framework using theapproach presented in section 4.4.3. Incoming interaction offers into the interfaces must wait forsynchronization of the receiving component. Synchronization is achieved by indicating to theeventManager that a given interaction point is waiting for synchronization, and therefore this inter-action point does not need to be monitored. The interaction point moves to the synchronizing stateafter having an offer refused. The interaction point’s state changes when the receiving componentindicates it is ready for an acceptance, and the postponed interaction is finally performed.

Each external object keeps a reference to its associated eventHandler object. An external object sup-ports interactions between the system environment and a component, such that only one referenceof an object is required. The method Connect provides the connection of the associated eventHan-dler object.

Additional specializations of the external class can be defined in the implementation of the interac-tion points of specific protocols, by including information about the communication primitivesthat are allowed to happen on this eventPoint. Such a specialization overloads the method that callsthe associated eventHandler object (CallEH method) to validate communication primitives. If acommunication primitive is not valid, the interaction offer is discarded, releasing the buffer con-taining the information concerning the interaction offer. In case a communication primitive isvalid, the eventHandler object connected to this eventPoint object is called to treat the interactionoffer. The implementation of the CallEH method is provided to protocol developers as code tem-plate to be used when applying the framework. Figure 5.12 presents the UML Activity Diagramof the CallEH method.

Figure 5.13 illustrates the dynamic behaviour of external interaction points. The eventManagerobject gives two opportunities for the external object to interact (ReadData method). In the firstopportunity, ev object is not synchronized and indicates it as a return to the Interact method,putting the external object in the synchronizing state. Later the ev object indicates that it is ready tointeract (InterInt method). The eventManager then gives the second opportunity to external to inter-act, and the interaction is performed successfully. The information related to this interaction offeris taken from the system interface in the first attempt to interact (ReadData method). The ev objecttakes the interaction information from external when treating the event (GetData method).

check communication primitive (cp)

cp E {c1, c2, .. , cn}

call eventHandler

[otherwise]

releasemessagebuffer

return result

Figure 5.12 Activity diagram of the CallEH method

Page 104: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

86

Chapter 5: Basic Event Manager Framework

In this solution, the eventManager only monitors events from interaction points that are not wait-ing for synchronization, avoiding that the system is busy with interaction offers that can not betreated yet.

Internal Class

The approach suggested in chapter 4, where an interaction means concentrates the task of moni-toring the synchronization of the interacting behaviours, optimizes the attempts to interact at thecost of distributing the behaviour information of the communicating parts. In that approach, theinteraction means must be constantly updated concerning the status of each communicating part,i.e., whether their interaction participation is still enabled or not. Such solution must also supportthe monitoring of different instances of interactions that are in a synchronization process.

The use of an object to coordinate internal interactions is questionable when implementing inter-actions such as the two-way value passing type of interaction supported by this framework.Therefore, we apply a more straightforward solution for this problem by using a single methodcall.

When implementing synchronous interactions using direct method call, we have to define ways tohandle synchronization. A possible solution for this problem is to have the return of the methodcall indicating whether the interaction has been successful or not, which depends on the state ofthe component. In this solution, components’ behaviour implementations are responsible to keepon trying to interact while the corresponding event is enabled by the behaviour.

Although our approach makes the task of the interaction means trivial, we chose to keep thisobject in the implementation, so that the same interface can be offered to components to perform

:eventManager :external ev:eventHandler

ReadData CallEH

Interact

[no]

InterInd

ReadData CallEH

Interact

[ok]

GetData

Figure 5.13 External Interaction Dynamic Behaviour

Page 105: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

87

both internal and external interactions. Furthermore, the framework can be easily extended to sup-port more complex interaction types by specializing the interaction means object.

In this framework, the internal class specializes the eventPoint class. Two connected internal objectsare used to implement a single internal interaction means. Each internal object is associated to oneof the interacting components and handles the participation of that component in the interaction.The two internal objects are associated in order to recognize each other as partners performing thesame interaction.

When a component wants to interact with another component, it uses methods of the internalobject directly connected to it. These methods support the interaction offer and the interactionacceptance indications used by the behaviour’s implementation to synchronize, and deliver theinformation associated to the interaction.

Since the eventManager, in principle, only reacts to external interactions, the triggering of internalinteractions would naturally be implemented as an operation of an action. However, this impliesthat another unit of behaviour is triggered before the end of interaction, which violates the atomic-ity requirement of a synchronous interaction. To solve this problem, interaction offers are trig-gered by the components event evaluation cycle.

Figure 5.14 shows the details of the operation of the internal objects. In Figure 5.14, objects cp1and cp2, implement sending and receiving components, respectively. Objects ip1 and ip2 areinstances of the internal class connected to cp1 and cp2, respectively.

In this figure, cp1 receives the opportunity to interact (Interact) and performs an interaction offer(SendData). This offer is forwarded by ip1 to ip2 (SendDataFw), indicating the offer to cp2 (Inter-act). cp2 gets the information associated with this interaction (GetData) that was forwarded to ip2together with the offer, and, after evaluating the conditions guarding the related unit of behaviour,executes the associated action. The object cp2 sets its status to instable (InterInd). The interactionis successful and this result is propagated back to cp1 that executes its related action.

cp1:eventHandler ip1:internal ip2:internal cp2:eventHandler

Interact

[ok][ok]

[ok]

GetData

[data]

SendDataSendDataFw

Interact

InterInd

Figure 5.14 Internal interaction through internal objects

Page 106: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

88

Chapter 5: Basic Event Manager Framework

Timer Class

The class Timer is a concrete class used to support time-related events. Timer objects are instanti-ated by a component and become ready for use in an idle state. In this state, no time monitoringactivity is performed. The behaviour activates a timer object through the SetTimeout method whenneeded. At this moment a period of time is set for the timeout. When the timeout happens, thetimer object calls its eventHandler object and changes its status automatically to idle. If the timeoutdoes not happen but it is no longer needed, it must be set to idle by the object using the timer (Idlemethod). The monitoring of time elapsing is done by the eventManager.

5.3.4 Boundary Conditions

This section discusses how the Basic Event Manager Framework handles the boundary conditions(initialization, termination and exceptions). Other boundary conditions are discussed in section5.4, since they are more related to the implementation of protocol-specific functions.

Initialization and Termination

In the initialization of the objects of the Basic Event Manager Framework, the following actionsare taken:

• external eventPoint and eventHandler specialization objects register themselves with the event-Manager object;

• external specialization objects initialize their file handlers;• attributes, like buffer areas and state flags, are initialized in all objects;• initialization tasks that are depend on protocol-specific code are executed.

In the Basic Event Manager Framework, objects can only be statically destroyed, i.e., objects canonly be destroyed when the protocol entities finish their execution. Therefore, the only concernwhen handling system termination is to close the files used by the external interaction points,which is done in the destructor of the external class.

In this framework, when a component reaches the end of its behaviour execution, the behaviourglobal state must be set to the END state. Interactions due to incoming events in the END state areignored.

Exceptions

In this framework, the treatment of exceptions such as unexpected events is performed only forexternal interactions, since the information flow internal to a component is expected to be consist-ent. An eventPoint object tries to detect an invalid communication primitive when validating theinformation of an interaction offer. Specializations of eventPoints contain the list of valid commu-nication primitives for each direction of communication. In case a communication primitive isinvalid, the interaction offer is discarded.

In this framework we consider the interaction with the environment as synchronous and the asyn-chronism of the interface is considered as a characteristic of the environment’s behaviour. There-

Page 107: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

89

fore, in case a communication primitive is valid but the event is not expected in the current stateof the eventHandler, the implementation must synchronize the environment and the behaviour ofthe receiving component.

Our solution for this problem is to maintain a flag in the interaction point object indicating thecurrent status of the interaction process. The interaction point is either waiting for an externalevent or waiting for synchronization between the environment and the component’s behaviour.The eventManager object only monitors events related to interaction points that are waiting forevents. An interaction point object waits for synchronization when a component has refused oneof the environment’s interaction offers. An interaction point object waiting for synchronizationmakes a new attempt to interact when receiving an indication that the interacting component hasenabled one or more unit of behaviours triggered by interaction acceptance events.

5.3.5 Definition of Classes

The classes defined in this framework are presented below, according to the CRC cards approach,i.e., by explicitly defining their responsibility, collaborator classes, attributes and methods.

Class EventManager

The responsibilities of this class are to register interaction points and components implementa-tions, monitor the occurrence of events at the external interaction points and time events, givecontrol to the appropriate event points once an event is detected, and give opportunity for compo-nents to execute. This class collaborates with class eventPoint.

This class has the following attributes:

• list<ipStruc> _ipList // list of monitored event points and associated file handlers• list<eventHnalder> _ehList // list of related components

This class has the following methods:

• void WaitEvents() // loop that monitors the occurrence of events• void AddEP(eventPoint*) // registers an event point for monitoring• void AddEH(eventHandler*) // registers a component

Class EventHandler

The responsibilities of this class are to offer a common reference to different components, holdinformation that is common to all components, provide new attempts for synchronization, andprovide a common prototype for performing component’s behaviour. This class collaborates withclass eventPoint.

This class has the following attributes:

• int _state // current component global execution state• int _instable // indicates whether all enable events have received a chance to execute

Page 108: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

90

Chapter 5: Basic Event Manager Framework

This class has the following methods:

• virtual int Interact(eventPoint*, int ,int) // common abstract method for treating events• void EvalCycle() // give opportunity to interactions related to enabled events to happen. The

evaluation cycle implemented in this method blocks when the behaviour is stable.

Class EventPoint

The responsibilities of this class are to inform its associated event handler that an event has hap-pened, register and de-register itself at the eventManager, and connect itself to eventHandlers. Thisclass collaborates with classes eventManager and eventHandler.

This class has the following attributes:

• eventHandler* _eh // associated eventHandlers

This class has the following methods:

• void Connect(eventHandler*) // connects itself to an eventHandler

• virtual int Type() // gets the type of the event point• virtual void CallEH() // informs the event point that the event has happened, by asking the event

point to call its event handler• eventHandler* GetHandler() // informs the connected eventHandler

• void GetData() // delivers the reference to the information buffer of the interaction

Class External

This class specializes class eventPoint for handling external interfaces. This class collaborates withclasses eventManager and eventHandler.

This class has the following attributes:

• int _descr // file or socket descriptor• int _waitSynchr // indicates whether the interaction point is waiting synchronization in order to

interact• int _cp // stores the communication primitive being exchanged in a interaction

This class has the following methods:

• virtual int Type() // gets the type of the event point• int GetFd() // gets the file handler of the event point (if any)• virtual int CallEH() // abstract method for treating interactions• virtual int ReadData() // get interaction offer information from external interfaces• void InterInd() // indicates behaviour’s synchronization• int Waiting() // informs the status of the interaction point (if waiting synchronization)

Class Timer

This class specializes class eventPoint for handling timeout. This class collaborates with classeseventManager and eventHandler.

Page 109: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.3 Software Architecture

91

This class has the following attributes:

• long int _nextto // absolute time in milliseconds when a timeout occurs• int _active // indicates if timer is active or not, i.e., the timer status.

This class has the following methods:

• int Type() // gets the type of the event point• void SetTimeout(int) // sets a timeout for current time plus the given value (in seconds)• void TimeLeft() // informs the time left before the next timeout • virtual int CallEH() // abstract method for treating interactions• int Active() // gets the timer status• void Idle() // set timer to idle status

Class Internal

This class specializes the eventPoint class in order to treat internal interaction points. It supports aone directional delivery of interaction offers and interaction acceptances between communicatingcomponents. A pair of instances of this class must be used to support bi-directional communica-tion between components. This class collaborates with itself and specializations of the eventHandler

class.

This class has the following attributes:

• internal *_partner // reference to the partner internal object

This class has the following methods:

• int Type() // gets the type of the event point• void SetPartner(internal*) // set the partner internal object• void InterInd() // forwards indication of interaction acceptance to partner internal object• void InterIndFw() // forwards indication of interaction acceptance to related eventHandler

• int SendData(int,char*) // forwards interaction offer to partner internal object• int SendDataFw(int,char*) // forwards interaction offer to related eventHandler

5.3.6 Dynamic Behaviour

During the initialization of the system, the eventManager object, eventPoint objects and eventHan-dler specialization objects of the system are instantiated and the appropriate registrations with theeventManager object are performed. Once initialization is completed, the eventManager object exe-cutes its monitoring cycle (method WaitEvents).

The monitoring cycle first monitors external events. Once an event is detected, the eventManagerobject calls the eventPoint object that corresponds to this event. This eventPoint object then callsthe eventHandler object that treats the event. When the eventHandler finishes, the control returns tothe eventManager.

At this point, the WaitEvents method gives the opportunity to all eventHandler objects to continuetheir event evaluation cycle, in order to reach stability, by calling the EvalCycle method. While

Page 110: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

92

Chapter 5: Basic Event Manager Framework

eventHandler objects perform their event evaluation cycle, internal interactions are triggered andsynchronization indications are sent to external interaction points, by calling the Interact method.When the EvalCycle method returns, the monitoring cycle starts again and repeats until the systemis terminated. Figure 5.15 depicts the interaction diagram for the collaboration among the ele-ments of this framework in a representative situation.

Figure 5.15 represents the situation in which the eventManager object monitors events at two exter-nal specialization objects. Once the eventManager object detects that an event has occurred, byusing the select system call, it searches in the list of eventPoint objects for the eventPoint associatedto this event. Figure 5.15 illustrates an event associated to ip2 object. Once the eventManager hasfound the associated external object, it calls the method ReadData of this object. This method getsthe data from the corresponding file or socket descriptor and calls the CallEH method to validatethe information. CallEH calls the destination eventHandler, using the Interaction method. After that,the eventManager object gives the chance to eventHandler object to trigger its interaction offersusing the method Interact. After receiving the control back, the WaitEvents method starts a newevent monitoring cycle.

5.3.7 Consequences of Implementation Solutions

Protocols implemented using the Basic Event Manager Framework require an execution thread tooperate. If another protocol layer or application is intended to be implemented in the same operat-ing system process, an integration scheme must be provided. Such scheme consists of defining anew environment-specific specialization of the external class for the interaction with the otherprotocol layer or application, and creating an execution thread exclusive for the framework.

Another constraint of the Basic Event Manager Framework is that the eventManager class relies ina function (select) that is also environment related. This hampers portability, since, e.g., the Java

:eventManager ip1:external

WaitEvents()

ip2:external :eventHandler

CallEH()

Interact()

treats event

AddEP()

AddEH()

EvalCycle() Interact()

ReadData()

Figure 5.15 Interaction diagram for the treatment of an external event.

event is detected

Page 111: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.4 Usage Information

93

language does not have a similar function and the Windows NT operating system offers a differ-ent interface for the same event dispatching functionality (WaitForMultipleObjects). A similarapproach as the one used in ACE [63] can be applied to the framework implementation to enforceportability.

5.4 Usage Information

The protocol implementation process that makes use of this framework consists of providing pro-tocol-specific code to be attached to the framework to produce executable program. Protocol- spe-cific code are classes that specialize the classes defined in the framework, capturing informationthat are peculiar to a specific protocol. The development of protocol-specific code is performedby filling in framework templates, which are provided together with the framework (see appendixC). The framework templates guide the protocol developers into the specialization of the frame-work classes.

Protocol development can be done without knowledge of details of the implementation of theframework. The framework implementation is available in the form of a class library that isattached to the framework template including a header file through pre-compilation macros (e.g.,as in #include ‘BEMF.h’). The binary code of the framework is linked together with the filledtemplate.

The use of the Basic Event Manager Framework templates consists of the following steps:

(1) - definition of constants representing the behaviour states and communication primitives of the protocol;

(2) - specialization of external class for the concrete interaction points;

(3) - specialization of eventHandler class for the implementation of the protocol components;

(4) - definition of initialization class.

Each one of these items is discussed in the sequel.

5.4.1 Constants Definition

Behaviour states and communication primitives are enumerated, making them uniquely identifia-ble. In this part of the template, implementors provide meaningful names to substitute the integersthat enumerate states and primitives within the implementation code.

5.4.2 External class Specialization

The interaction points required by the protocol are implemented as specializations of the availableeventPoints, i.e., internal and external. The internal class does not require further specialization, andcan be instantiated as many times as required during protocol initialization. Specializations of theexternal class are required to capture environment specific and protocol-specific information.Environment specific information concerns the details of a particular external interface. Protocol-

Page 112: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

94

Chapter 5: Basic Event Manager Framework

specific information concerns the possible communication primitives that can be exchangedthrough each interaction point in each direction of communication.

Figure 5.16 shows, on the left side, a hypothetical definition of an interaction point at the designlevel, and on the right side, the corresponding implementation. The interaction point is the inter-face between a component of the protocol and an underlying service provider (lower layer proto-col). Assuming, for example, that UDP provides the underlying service, the implementation ofthis interaction point would require a new class that specializes the external class to capture spe-cific implementation of the generic interaction point functionality for UDP. We identify this spe-cialization class in the Figure 5.16 by udp.

The design of an interaction point also specifies the possible communication primitivesexchanged through the interaction point, in this example DaReq and DaInd. This information ismapped onto constraints of a specialization of the udp class we call ip_1.

Environment-specific Specializations (step 2.1)

The following steps should be taken when defining the environment-specific specializations ofexternal class: definition of class header, definition of class constructor, and overload of ReadDataand SendData methods. Each different implementation technique used in the interface with theenvironment (file handlers, protocols APIs, etc.) requires a specialization of this type.

Specialization class’s header (step 2.1.1)

The implementation template for this step only requires the name of the new class, and itsrequired parameters and attributes. Examples of parameters are a file handle number and acommunication address. An example of attribute is a buffering data structure.

Class Constructor (step 2.1.2)

In the constructor of environment-specific specializations of the external class, externalinterfaces are properly initialized, e.g., file handles are open and bound, and underlying

component

underlying

interactionpoint

udp

ip_1

DaIndDaReq

DaReqDaInd

Design scheme Implementation

service

external

Figure 5.16 Interaction point implementation

scheme

(UDP)

Page 113: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.4 Usage Information

95

services are initialized. The class parameter values may need to be saved into the classinstances.

Overload of Method ReadData (step 2.1.3)

This method is responsible for taking interaction information from the interface and storeit in internal buffers. Once information is read, it is offered to the component connected tothis external interaction point. If the component does not accepted the interaction, thismethod sets the status of the interaction point to waiting for synchronization. The environ-ment-specific code of this template is the procedure to read the interface. We assume thatthe interface is able to deliver a string of octets with discernable size.

Overload of Method SendData (step 2.1.4)

This method is responsible for sending data through the interface with the environment.We assume that interactions always contain a communication primitive and a string ofoctets of recognizable size. These communication primitives are mapped in this methodonto the service primitives of the communication service being used or they are delivereddirectly as service primitives of the service provided by the protocol being implemented.

Protocol-specific Specializations (step 2.2)

The following two steps should be taken when specializing the environment-specific specializa-tions of external class:

Class Header (step 2.2.1)

The definition of the header of a concrete class implementing an external interaction point,requires a class name and definition of inheritance and parameters. The frameworkabstract classes that can be specialized here are the ones defined in step 3.1.

CallEH Method (step 2.2.2)

The template for implementation of the CallEH method must be complemented with thecodes for communication primitives, defined in step1, that are valid codes for interactionoffers made by the environment through this external interaction point.

5.4.3 EventHandler Specialization

The components of a protocol are implemented by specializing the eventHandler class. The con-crete classes specializing eventHandler captures the particular behaviour of each protocol compo-nent. Multiple instances of a component class may be created from a single class definition ifnecessary. Figure 5.17 shows the mapping of a component onto eventHandler specializations.Three steps are necessary to specialize eventHandler and are described below.

Page 114: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

96

Chapter 5: Basic Event Manager Framework

EventHandler Header (step 3.1)

Definition of the class header consists of a class name and parameters. A reference to the event-Manager object is required as parameter. Other possible parameters depend on protocol functions.

Class Constructor (step 3.2)

The definition of the constructor of the eventHandler specialization consists of the following tasks:

• instantiation of local eventPoints: instantiate eventPoints only used by the eventHandler beingdefined.

• connection of required eventPoints: the method Connect() of the eventPoint object is appliedto connect interaction points implementations to components. A reference to the connectingcomponent is passed as a parameter in this method call.

Interact Method (step 3.3)

The implementation of the Interact method consists of filling in a template with behaviour infor-mation extracted from the protocol specification. The required information can be summarized inthe table illustrated in TABLE 5.1, that resembles a transition table as used, for example, in [29].

In the TABLE 5.1, each line contains the information related to a unit of behaviour. The columnsprovide the following information:

• state: the behaviour global state;• IP: the interaction point where the related event is expected to occur;• CP: the communication primitive;• Action: the set of operations executed in this unit of behaviour;• Condition: guarding condition for the unit of behaviour;• Type: indicates whether the unit of behaviour is an ACCEPTANCE or an OFFER.

component A

component B

eventHandler

C_A C_B

Interact

Design Implementation

Interact

Figure 5.17 Implementation of Components

TABLE 5.1 Required information for the Interact method

State IP CP Action Condition Type

Page 115: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.4 Usage Information

97

The pieces of the template code corresponding to behaviour states and units of behaviour (interac-tion offer, interaction acceptance and time) must be multiplied as many times as required by theprotocol behaviour. The _state attribute of the class eventHandler must be used to update thebehaviour global state when necessary. Updating the _state attribute is done as part of the actionof an unit of behaviour. The code template indicates where each piece of information must beplaced (see Appendix B).

Initialization Method (step 3.4)

This method initializes the attributes of the eventHandler class specialization. The possible tasks inthis method are:

• initialization of component global state: set the attribute _state to the initial state of the com-ponents behaviour.

• initialization of protocol attributes: initialization of attributes required by the protocol.

5.4.4 Entity Class

The entity class is a concrete class that builds and initializes the protocol entity. The building of theprotocol entity is performed by the class constructor and the initialization is performed by anmethod called Initialization. Code template for defining and instantiating this class is suppliedtogether with the framework. The steps to fill in these templates are described in the sequel.

Class Header (step 4.1)

To complete the template for the definition of the header of the entity class, the protocol developermust specify the required parameters that are used to configure the protocol entity.

Class Constructor (step 4.2)

The tasks to build the structure of the implementation of the protocol that must be performed bythe entity class are listed below:

• instantiate eventManager;• treat possible configuration parameters;• instantiate required interaction points;• set internal eventPoints as partners using the SetPartner method;• instantiation of components;• execute the Initialization method;• call WaitEvent method.

The Initialization method consists of initializing protocol-specific global context information.

5.4.5 Template General Structure

Figure 5.18 and Figure 5.19 illustrate the implementation structure of protocols that make use ofthe Basic Event Manager Framework. The rectangles denote scope areas. The filled rectangles

Page 116: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

98

Chapter 5: Basic Event Manager Framework

represent files. The symbol “...” indicates repetition of template structures. In Figure 5.18, therectangle named protocol.h represents the header file of the implementation. The other rectanglesare classes definition. The titles of the classes are C++ like and indicate the inheritance relationsand commands. This illustration shows a protocol with m specializations of the eventHandler classand i specializations of the eventPoint class (udp and fileIO).

Figure 5.19 shows the structure of the body file of a protocol implementation, which is called pro-tocol.cpp. The code starts with the definition of the CallEH method of the eventPoint class speciali-zations.

After defining the eventPoint classes specializations (interaction points), we define the specializa-tions of the eventHandler class (components). These definitions provide a constructor and an Inter-act method for each eventHandler specialization. Interaction points must be connected tocomponent object in the constructor of this component object.

5.5 Implementation Example

This section illustrates the protocol implementation process using the Basic Events ManagerFramework. We follow the instructions of the framework usage information to implement theSend/Receive protocol presented in Appendix A. Figure 5.20 shows the structure of this protocol.

We present below the protocol specific information required on each task identified in section 5.4.The tasks are numbered according to their identification in the Usage Information section of theframework documentation. Figure 5.21 shows the specializations required in this protocol imple-mentation.

(1) Constants definition

The behaviour states defined in the protocol specification are Idle, Sending and Waiting (sendingcomponent), and Normal, Send-Ack, Rec-Ack and Receiving (receiving component). The communi-cation primitives are DataReq, Data and Ack (Send component), Data, DataInd and Ack (Receivecomponent), Data, Ack, udp-DR and udp-DI (underlying service).

protocol.h

class component_1 : eventHandler

class component_m : eventHandler ...

class interactionPoint_1 : udp

class interactionPoint_i : fileIO ...

constants definition

#include “BEMF.h”

class entity

Figure 5.18 Header file of the protocol code

Page 117: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.5 Implementation Example

99

(2) EventPoint specializations

The required eventPoint specializations are the external interaction points identified in the protocolspecification, i.e., ip1 and ip2. For the sake of simplicity, the interface with the service providedby the protocol being implemented is the console. This requires a specialization of external classto handle the standard I/O. We call such specialization class fileIO. The LLS (Lower Level Serv-ice) defined in the protocol specification is supported by UDP. Therefore, the external class has tobe specialized to handle the UDP interface. We call this specialization class udp.

(2.1) Environment dependent specializations

(2.1.1) specializations’ header: the names of the specializations are fileIO and udp. ThefileIO specialization receives the file handler as parameter. Its required attribute is a datastructure to address the standard interface. The udp specialization receives the local portnumber, the remote port number and the remote host name as parameters. Its requiredattribute is a data structure to address the UDP interface.

component_1 :: component_1

protocol.cppinteractionPoint_1:: CallEH <body>

interactionPoint_i :: CallEH <body>

component_1 :: Interaction

component_m :: component_m <body>

component_m :: Interaction <body>

entity :: entity

instantiate eventManager

instantiate component_1

instantiate interactioPoint_1

instantiate interactionPoint_i

starts eventManager->WaitEvents

connect interactionPoint_1...connect interactionPoint_g

Finite State Machine

...

... instantiate component_m

...

...

save protocol parameters

main {

instantiate entity}

Figure 5.19 Body file of the protocol code

Initialization();

Page 118: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

100

Chapter 5: Basic Event Manager Framework

(2.1.2) specializations’ constructor: the constructor of the fileIO class stores the filehandler identifier, opens the file handler and sets the interaction point status to “waitinginteraction”. The constructor of the udp class initializes the UDP interface, the localand remote data structure addresses, and the interaction point status.

(2.1.3) ReadData method: each class uses the commands of their related interfaces toread a string from the interface’s buffer. This method always provides an udpDI as com-munication primitive associated to the incoming message.

(2.1.4) SendData method: in the fileIO class, the communication primitive and the dataare used to compose a single string that is sent to the interface. No mapping of commu-nication primitives are required, since the communication primitives correspond to theservice primitives of the underlying service. In the udp class, there is a single communi-cation primitive (udpDR) used to indicate to the interface the intention of sending amessage. The SendData method uses the already initialized address structures to pro-vide the UDP interface with the required information to send the message.

lower level service

send receive

user 1 user 2

entity entity

SRSAP - send/receive service access point

SRSAP

LLSAP

LLSAP - lower level service access point

ip1

ip2

ip3 ip4pduhandler

Figure 5.20 Protocol global structure

eventHandler

send pduHandler

fileIO udp

ip1 ip2

receive

Figure 5.21 Definition of protocol classes

external

Page 119: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.5 Implementation Example

101

(2.2) Protocol-dependent specializations

(2.2.1) specialization: ip1 and ip2 are defined as specializations of fileIO and udp, respec-tively. The parameters in the base classes must also be defined in these specializations.

(2.2.2) validation of communication primitives: the communication primitives thatrequire to be validated at the interaction points are: DataReq primitives from the user atip1 and UdpDI coming from the lower level service at ip2. Outcoming and internalevents do not require validation, since the consistency of the protocol implementationguarantees that no other events are generated.

(3) EventHandler specializations

The specified protocol has three components: Send, Receive and PduHandler.

(3.1) specializations: component objects by default inherit from the eventHandler class, and,therefore, Send, Receive and PduHandler are concrete classes that specialize the eventHandlerclass.

(3.2) Class constructor

(3.2.1) local eventPoint: since the Send component handles timeout events, it mustinstantiate the class timer.

(3.2.2) connections: the Send component connects itself to ip1, timer and two internalobjects implementing ip3 and ip4, respectively. Component Receive connects itself totwo internal objects implementing ip3 and ip5. The PduHandler component connects itselfto ip2 and two internal objects implementing ip4 and ip5. The internal objects are requiredto implement ip3, as defined in the protocol specification, and to connect the Send andReceive components to PduHandler.

(3.3) Interact method: TABLE 5.2 to TABLE 5.4 show the protocol specific informationrequired to fill in the template for the Interact method of classes send, receive and pduHandler,respectively. These figures present the starting state, the event point, the communicationprimitive, information, the action, and the participation type belonging to units of behaviourdescribed in each line. The functions codePDU and decodePDU must be provided by the proto-col developer to handle PDU formats defined in the protocol specification. Actions aredescribed in C-like syntax.

(3.4) Initialization method: sets the initial global state of the Send, Receive and PduHandlerobjects to IDLE, NORMAL and WAITING, respectively.

(4) Protocol initialization class

The following tasks are required in the constructor of the entity class:

Page 120: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

102

Chapter 5: Basic Event Manager Framework

(4.1) parameters: the parameters are the configuration information of the protocol entitydefined in the protocol specification. The parameter are local_port (integer), remote_port (inte-ger) and remote_host (string).

(4.2) interaction points instantiation: one instance of ip1 and ip2 specializations each, twoinstances of internal class to implement the ip3 interaction point and two instances of internalclass for implementing ip4 are necessary.

(4.3) set partner internal objects: the pairs of internal objects implementing ip3 and ip4 are setas partners.

(4.4) components instantiation: Send, Receive and PduHandler objects are created.

5.6 Conclusions and Evaluation

From the experience of developing this framework we have identified two main sources of diffi-culty in the definition of the framework software arquitecture. The implementation solutions pre-sented in chapter 4 are the core of the software architecture of the Basic Event HandlerFramework and contribute considerably to speed-up the software architecture definition step ofthe framework development process. The following issues, however, still had to be addressed:

• Integration of the implementation solutions: in some cases, for implementaion efficiencyreasons, an implementation solution for one concept may have to be adapted to support therequirements of other concepts. For example, the implementation of component’s behaviourpresented in chapter 4 have been adapted to support behaviour’s synchronization for inter-

TABLE 5.2 Behaviour of Send component (step 3.3)

State EP CP Action Condition Type

IDLE ip1 DataReq _state = SENDING; __ ACCEPT

SENDING ip3 Data _state = WAITING; __ OFFER

WAITING ip3 Ack release buffer;_state = IDLE;

__ ACCEPT

timer Timeout _state = SENDING; _state==WAITING ACCEPT

TABLE 5.3 Behaviour of Receive component (step 3.3)

State EP CP Action Condition Type

NORMAL ip4 Data _state=RECEIVING; __ ACCEPT

RECEIVING ip1 DataInd _state = ACKNOW; __ OFFER

ACKNOW ip4 Ack _state = NORMAL; __ OFFER

Page 121: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.6 Conclusions and Evaluation

103

action as well;• Generalization of the implementation solutions: the framework must support all possible

combinations of concept instances. The implementation must handle the use of n instancesof a concept used in the protocol being implemented and also the absence of this concept inthe protocol. For example, the choice composition is and n-ary relation and therefore must beimplemented to support any number of composed behaviours, and a protocol may not requiretimed events.

The example of section 5.5 shows that once the protocol being implemented is specified using thedesign concepts supported by a framework, the mapping process of protocol specific informationonto code based on the framework templates is straightforward. This contributes to the effective-ness of the implementation process and its correctness. The resulting code contributes remarkablyto the maintenability of the implementation, since this code is based on templates that are well-structured and well-documented.

In order to evaluate the effectiveness of the use of our framework, we asked an experienced pro-grammer to implement the protocol of Appendix A, giving him the protocol design and the frame-work documentation. It took him 30 minutes to get familiar with the usage of the framework.After becoming acquainted with the protocol specification and making use of the code templates,it took the programmer 2 hours and 15 minutes to finish the compilation process.

The resulting implementation code for the send/receive protocol used in this experiment, exclud-ing the framework code, has 450 lines. After reaching an executable code, minor errors on datamanipulation (e.g., coding PDUs and buffering tasks) have been corrected. The compilation proc-ess plus runtime error corrections took a total of 1 hour and 45 minutes.

Our protocol implementation approach does not help in the coding of data (e.g., PDU coding anddecoding, conditions). This implies that, the efficiency in the implementation process obtained inthis experiment could still be improved by the use of code libraries for data manipulation and the

TABLE 5.4 Behaviour of coding and decoding component (step 3.3)

State EP CP Action Condition Type

WAITING ip2 udp-DI cp=decodePDU(pdu,&buf);_state=RECEIVING;

__ ACCEPT

ip3 Ack pdu=codePDU(Ack);_state=SENDING;

__ ACCEPT

ip4 Data pdu=codePDU(Data,buffer);_state=SENDING;

__ ACCEPT

RECEIVING ip3 Ack _state=WAITING; cp==Ack OFFER

ip4 Data _state=WAITING; cp==Data OFFER

SENDING ip2 udp-DR release pdu;_state=WAITING;

__ OFFER

Page 122: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

104

Chapter 5: Basic Event Manager Framework

acquaintance of developers with the problems common in protocol implementation, since pro-gramming experience on data manipulation had some influence on the results.

Concerning the performance of protocols implemented using this framework, the main issue to beconsidered is the overhead caused by the control of the structuring techniques. To evaluate thisoverhead, we have carried out some experiments that compare a structured implementation, con-sisting of connected components, and a corresponding monolithic implementation that usesshared memory and a single state machine.

In our experiment we measured the performance of two communicating protocol entities:

• A sending entity receives as service primitive an execution request, with an integer and amessage. The integer indicates how many times the message must be transmitted to the peerentity.

• A receiving entity receives the message and starts 5 interleaved tasks, which indicate theirresults to a synchronizer element. After receiving the results of all tasks, the synchronizeracknowledges the receiving of the message to the sender entity. The number of interleavedtasks has been arbitrarily chosen among the values that would resemble realistic situations.There are in total 7 components manipulating 11 interaction points in this experiment. Real-istic protocols usually have more complex data manipulation procedures than the protocol inour experiment, but the number of components normally do not increase proportionally tothe complexity of the data manipulation procedures.

The repetition of the process allows us to make measurements involving larger periods of time,minimizing in this way the influence of imprecision in the timing function used to collect themeasurements, and of other processes running in the machines used in the experiment.

In this experiment, processing is due to three aspects: data communication between entities, datamanipulation within entities, and execution overhead to process the structuring mechanisms ofthe implementation. The monolithic and structured implementations, in principle, spend the sameamount of time in the first two aspects. Therefore, we are interested in the measurement of thethird aspect, i.e., the overhead of the structuring mechanisms.

In order to focus our attention on the structuring overhead, we minimize the execution overheadwith data communication and data manipulation. Therefore, we can consider the measurements ofthe total execution time of the protocol entities as due to structuring overhead. We minimize datacommunication by running the entities in the same computing node and we minimize data manip-ulation by not performing any operation in the actions of the units of behaviour of the protocolentities. Figure 5.22 illustrates the structure of the performance evaluation experiment.

The execution overhead introduced by the framework to support a structured implementation ison average 41% the execution time of the corresponding monolithic implementation. For exam-ple, using 100 as the number of repetitions in the execution of this experiment, the total executiontime in the monolithic implementation is, on average, 19.6 milliseconds and in the structuredimplementation is, on average, 27.7 milliseconds. This means that the execution overhead in thestructured implementation is, on average, 1.41 times the execution time of a corresponding mon-olithic implementation. The overhead due to structuring in realistic protocols varies in differentprotocols, but is always proportionally much smaller than the overhead with data manipulation

Page 123: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

5.6 Conclusions and Evaluation

105

(CRC, for example, is extremely time consuming). Therefore, the overhead of handling a struc-tured implementation with respect to the system as a whole is also proportionally small.

senderentity

receive

task1

task2

task5

...

synchronizer

receiverentityexec(repetition,msg)

Figure 5.22 Performance evaluation scheme

Page 124: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

106

Chapter 5: Basic Event Manager Framework

Page 125: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

107

Chapter 6

Basic Multi-thread Framework

This chapter presents the Basic Multi-thread framework for protocol implementation. The BasicMulti-thread Framework supports the same design model supported by the Basic Event ManagerFramework but has been developed by applying different implementation techniques. The domi-nant technique applied in this framework is multi-thread programming, which justifies the nameof this framework.

This chapter has the same structure as chapter 5. Each section of this chapter presents the deliver-able of a step of our approach to develop frameworks. The structure of the chapter is the follow-ing: section 6.1 presents our approach for presenting this framework example; section 6.2presents the domain analysis; section 6.3 presents the software architecture definition; section 6.4documents the usage information; section 6.5 presents an example of using this framework andsection 6.6 presents some conclusions on the development of this framework.

6.1 Approach

The Basic Multi-thread Framework supports the same design model supported by the Basic EventManager Framework. In the framework discussed in this chapter, however, we have applied dif-ferent implementation techniques. The main purpose of developing a functionally similar frame-work built using different implementation techniques, is to contribute to the catalogue offrameworks with an alternative core implementation solution. The implementations produced inthis way are expected to be more suitable to protocols with different characteristics than those thatcan be better supported by the previous framework. This alternative framework also allows us tocompare the use of alternative implementation techniques in terms of code complexity and effi-ciency.

We have already exemplified the documentation of a framework in chapter 5 by presenting indetail the deliverable of our method to develop frameworks. In this chapter we limit ourselves tothe information necessary to introduce and discuss the alternative implementations used in thisframework.

Page 126: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

108

Chapter 6: Basic Multi-thread Framework

The implementation techniques applied in the Basic Multi-thread Framework are brieflydescribed in chapter 4. In this chapter, we discuss these techniques in more detail and considerthey combined application. This chapter also illustrates how to apply the Basic Multi-threadFramework, by discussing the Send Receive protocol presented in the appendix A.

Although the Basic Multi-thread Framework can be applied in practice, it is mostly intended forprototyping purposes. The implementation code of this framework is available to the interestedreader in [80].

6.2 Domain Analysis

The Basic Multi-thread Framework supports the BDM described in chapter 5. The following con-cepts have been defined in the BDM:

• Component: can be created or destroyed statically, and can be parameterized;

• Interaction means: the type of interaction means supported is the interaction point;

• Behaviour: applies the default firing policy, timeout, interaction-acceptance and interaction-offer types of event;

• Interaction: synchronous, two-party and value passing.

6.3 Software architecture

The most important implementation decision taken in the software architecture of this frameworkhas been to delegate the scheduling of the execution of components to a multi-threading imple-mentation package, such that parallel activities can be executed in separate threads. In our solu-tion, events happening at different interaction points are monitored and treated in parallel,whenever allowed by the protocol behaviour.

The software architecture of the Basic Multi-thread Framework is similar to the one proposed forthe Basic Event Manager Framework. The main difference between these architectures is that theBasic Multi-thread framework lacks a centralized event dispatcher, which has become unneces-sary due to the presence of multiple execution threads.

The software architecture of the Basic Multi-thread framework maps one-to-one to the structuralconcepts of the BDM. In the Basic Multi-thread Framework, each component is implemented asan object. Each interaction means is also implemented as a separate object. The implementationof these components and interaction means run in a single operating system process. A separateexecution thread is started for each interaction means and each component. Interaction means areresponsible for monitoring their own related events while components trigger their enabled inter-action offers.

Alternative solutions to implement parallel behaviour using multiple threads can be elaborated.One of these alternatives is to use a centralized event monitor to control all the events, as appliedin the Basic Event Manager Framework. This monitor would activate the components to treat anincoming event in a new thread. Using this approach, we would avoid the duplication of the mon-

Page 127: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6.3 Software architecture

109

itoring code. However, in order to be generic enough to handle all possible interaction offers, thiscode would certainly be more complex and probably less efficient. The duplication of monitoringcode implies in significant increase in complexity without clear benefits in performance, there-fore, we have decided to avoid it.

The multi-thread solution for supporting event-driven and parallel behaviour (chapter 4, section4.2.2), is the core solution of the Basic Multi-thread Framework. The base classes applied here areeventHandler and eventPoints, to implement components and interaction points, respectively. TheeventPoint class is specialized in external, timer and internal, which implement external interactionpoints, timing events and internal interaction point, respectively. External class is again specializedto handle different implementation building blocks used for the interaction between the differentsystem parts. Figure 6.1 shows the class diagram for the software architecture of this framework.Classes drawn in gray represent implementation templates.

6.3.1 EventHandler

The functionality of the EventHandler class in this framework is similar to the EventHandler used inthe Basic Event Manager Framework. It is an abstract class that implements the general character-istics of components. This class has to be specialized in order to capture the particular behaviourof each component.

The common characteristics of components implemented in the eventHandler are: definition ofcommon context variables; handling of boundary conditions like initialization of the component’sexecution; definition of a common interface for the method that implements the component’sbehaviour (Interact method); and a scheduling procedure for triggering the units of behaviour asso-ciated with internal interactions.

The eventHandler abstract class provides a single reference to all its specializations, allowing tomanipulate the different components of a protocol as implementation elements of the same type.Such a single reference allows other elements of the implementation to handle components whileabstracting from different existing specializations.

callseventHandler eventPoint

timerexternal

uses 1..*

1..*

1..*

internal

{disjoint}

*

specific interface n

{disjoint, incomplete}

{abstract, template}

{abstract}{abstract}

component n{template}

{disjoint, incomplete}

protocol specific ip n

{disjoint, incomplete}

{abstract, template}

Figure 6.1 Framework software architecture

Page 128: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

110

Chapter 6: Basic Multi-thread Framework

Event Evaluation Cycle

In order to implement a component’s behaviour in this framework, the eventHandler class appliesthe event evaluation cycle as introduced in chapter 4, section 4.3.3 (EvalCycle method). The eventevaluation cycle is responsible for triggering the behaviour’s interaction offers and synchronizingwith communicating components. A component reacts to incoming interaction offers by the acti-vation of its Interact method.

Similar to the Basic Events Manager Framework, behaviour synchronization is done by perform-ing several attempts to interact. In each evaluation cycle, enabled units of behaviour, that are trig-gered by interaction offer events, perform they offer. Enabled interaction acceptances indicate tothe connected peer component its readiness to interact.

In the multi-thread solution the event evaluation cycle is executed in each component’s thread, bycontinuously evaluating the enabled units of behaviour. This is done by calling the Interact methodto perform an offer and indicate readiness to accept interactions. Such scheme provides the distri-bution of the execution opportunity among components.

The identification of a component’s state is used to suspend the evaluation cycle, avoiding wasteof computing resources in the execution of a continuous loop. This suspension is implemented byputting the execution thread in a waiting state. An external stimulus that takes the component tothe unstable state is communicated to the evaluation cycle by means of a signal (InterInd method),which allows the component to continue the evaluation cycle since the execution thread of thecomponent goes to an active state.

Buffering Stimulus

While a component performs one round of its evaluation cycle, a signal may be sent indicating anincoming offer or an indication of readiness. In this case, the signal would be lost, since the threadreceiving the signal is not waiting for it. Missing one external stimulus may jeopardize requiredcomponents’ synchronization with incorrect implementation of the system behaviour.

To solve this problem, a condition variable is increased each time a stimulus is received by a cer-tain component. At each evaluation cycle, this condition variable would be decreased, when astimulus is treated. The event evaluation cycle only blocks when the variable is equal to zero.

Avoiding Livelock

A potential for livelock exists in the suggested implementation of the event evaluation cycle incombination with the multi-thread programming technique. This situation occurs when two ormore components continuously put each other in the unstable state, without actually performingan interaction. This happens if the involved components have acceptance readiness to indicate toeach other but these components are not yet synchronized.

A solution for this problem is to indicate the acceptance readiness once each time the behaviourenters into a new global state. Synchronization can happen in two different ways: a) the offeringparty waits for synchronization or b) the accepting party is ready to interact first. At most one

Page 129: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6.3 Software architecture

111

indication of acceptance readiness is enough to synchronize the interacting parties, because, in thefirst case of synchronization, the offering party is ready to interact when the indication is sent, andin the second case, the interaction happens with the first interaction offer.

In order to provide this solution, the Interact method must identify the three possible different con-texts of its execution. The Interact method can be called by an interaction point to indicate an eventoffer, it can be called by the EvalCycle method to perform an offer or indication of acceptancereadiness, and it can be called by the EvalCycle method to perform only an offer. The valuesACCEPT, ANY or OFFER of the act parameter of the Interact method indicate these cases, respec-tively.

6.3.2 EventPoint

The eventPoint class is an abstract class that implements the general characteristics of interactionmeans. This class is further specialized in order to capture details of different interaction meansrequired in protocols. As in the eventHandler class, the eventPoint class also supplies a single refer-ence to all specializations of interaction means, allowing the program to manipulate these special-izations as an eventPoint object.

The general characteristics of interaction means implemented in the eventPoint class are connec-tion to eventHandlers, monitoring of events, and provision of an interface to activate the associatedeventHandler object.

The eventPoint class is specialized into classes implementing interaction means that performexternal and internal interactions, as introduced in chapter 4. Furthermore, the eventPoint class isspecialized to implement timers. Below we discuss these specializations.

External Class

The external class specializes the eventPoint class to implement the interfaces of protocol entitieswith their environment. The external class handles the asynchronous characteristic of the imple-mentation building blocks available in the implementation environment for inter-process commu-nication. The external class provides the protocol entity being implemented with an interface to itsenvironment that performs the synchronous interaction required in the design model.

The solution applied here to implement the external class follows the idea introduced in chapter 4and is similar to the one applied in chapter 5, but differs in the assignment of responsibilities todetect events. The external is an abstract class that provides the functionality that is common toexternal interaction points. When implementing protocols, the external class requires new special-izations to incorporate implementation code that is environment-specific. Environment-specificcode concerns the details to handle the chosen external interfaces. In our experiments with theBasic Multi-thread Framework, we use the specializations of external interaction points that han-dle interfaces using file descriptors (fileIO class) and UDP protocol (udp class). Such environment-specific classes must be specialized to capture protocol-specific information.

The solution for external classes in the Basic Event Manager Framework differs the Basic Multi-thread Framework in that each external object is responsible for monitoring its own events. Each

Page 130: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

112

Chapter 6: Basic Multi-thread Framework

instance of external class specialization monitors its related interface with the system environ-ment. The monitoring task consists of performing a loop, implemented in the WaitEvent methodand using a separated execution thread. This thread blocks when waiting for messages from theenvironment. Once an interaction offer is detected by an external specialization object, this objectindicates this offer to the associated component. The component is responsible for taking the nec-essary actions to handle the event.

The approach used in this framework to provide external synchronous interaction with the envi-ronment is the same as the one used in the Basic Event Manager Framework.

Internal Interaction Point

The Basic Multi-thread Framework uses a class internal to implement internal interaction points.This class is a specialization of eventPoint and is implemented in the same way as the internalclass in the previous framework (see chapter 5, section 5.3.3).

When applying this solution in combination with the multi-threading solution, deadlock situa-tions may be introduced. Since different components perform their event evaluation cycle simul-taneously, the code to handle events in this component has to be executed in mutual exclusion.Components have to wait the availability of the protected code, i.e., the code must be unlocked, inorder to have their interaction offer treated. For example, it is possible that two componentsexchange offers simultaneously and both of them wait indefinitely to get access to each other’smutually exclusive code.

This is a well-known problem identified by Dijkstra as the so called Dining Philosophers problem[76]. A simple solution adopted in our framework is to allow only one component to try an inter-action offer at once. We use this solution for the sake of simplicity. Other solutions that optimizeparallelism can be applied as it has been proposed in [76].

Timer

The monitoring of timing events is implemented in the Basic Multi-Thread Framework by a con-crete class called timer, which is another specialization of the eventPoint class. After being instanti-ated, a timer object must be connected to a component’s implementation (eventHandlerspecialization). Each instance of the timer class waits for an amount of time to elapse, and informsthe related eventHandler of the occurrence of a timeout. The waiting time is specified by the com-ponent that uses the timer at their activation. Timer objects must be activated when needed anddeactivated if no longer necessary.

In our solution to cope with the requirements of timing events, the timer object starts a new threadof execution to monitor the time elapsing when activated. The timeout is indicated to theeventHandler specialization object by means of an interaction offer. The thread used by the timerterminates after the time event happens. The monitoring function consists of a timed waiting con-dition (cond_timedwait function in Unix environment). Such condition waits the timer deactivationfor a specified period of time. Deactivation is performed by the component’s behaviour threadusing a method that signals the timer thread and sets the timer status to deactivated. When the

Page 131: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6.3 Software architecture

113

specified period of time expires, the associated component is notified and the timer status is set todeactivated.

When using the multi-thread technique, there is a chance that the attempt to deactivate a timerfails. This happens if the timeout indication has already been triggered when the component’sbehaviour attempts to deactivate the timer. In this case, the thread that monitors the elapsed timewould be waiting to have access to the mutual exclusion code of the Interact method. Therefore,although deactivated, the timeout is indicated. If the component’s behaviour has changed its glo-bal state, the timeout event is no longer enabled and is simply discarded. In case the timer is deac-tivated and needs to be reactivated before the timer’s monitoring task has been concluded we havea problem. In this case we would have a second thread started with possible corruption of thetimer status, or an early timeout indication. To avoid this situation, we have to guarantee that theInteract method discards pending timeout indications before a new activation. Therefore, ourimplementation of the Interact method in this framework checks whether a timer should be deacti-vated, and performs the deactivation if appropriate in all event evaluation cycles. This implemen-tation also requires another evaluation cycle after deactivation to activate the timer. In betweenthe two evaluation cycles, potential unexpected timeout indications have access to the interactionmethod. They are in this case identified and discarded.

Timer is a concrete class and therefore does not require further specializations. The period of timeto be monitored is passed to the timer object as a parameter at the time of its activation. Whenmore than one instance of the timer object is required by a component, we use an identifier inorder to determine which timer has actually expired.

6.3.3 Handling Boundary Conditions

Below we discuss three topics concerning the treatment of boundary conditions: unexpectedevents, system initialization and termination.

Unexpected Events

Similarly to the Basic Event Manager Framework, the unexpected events considered here areincorrect communication primitives and lack of synchronization interacting with the environment.This framework treats these two unexpected events in the same way as it is done in the BasicEvent Manager Framework, by discarding incorrect communication primitives and blocking newincoming events, waiting for synchronization.

Initialization Tasks

The initialization tasks required in the Basic Multi-thread Framework are:

• each external interaction point starts an execution thread to perform the monitoring of events;

• each component starts an execution thread to perform the event evaluation cycle;

• initialization parameters are stored, such as reference to cooperating objects and configura-tion information.

Page 132: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

114

Chapter 6: Basic Multi-thread Framework

Protocol-specific initialization tasks are described in the Usage Information section (6.4).

Termination Tasks

Similar to the Basic Event Manager Framework, in this framework objects are staticallydestroyed. Therefore, our only concern when handling termination is to close the file handlersused in the external interaction points. The component’s global state must be set to END when thecomponent finishes its execution. In this state any attempt to interact fails and the event evalua-tion cycle is no longer performed.

6.3.4 Definition of Classes

Classes of this framework have been defined by applying the CRC cards approach, i.e., by explic-itly identifying responsibility, collaborator, attributes and methods for each class in the design.These classes are:

Class eventHandler

This class defines a common reference for the manipulation of different components and toimplement the event evaluation cycle. This class collaborates with class eventPoint.

This class has the following attributes:

• int _state // major state of related behaviour• pthread_mutex_t _mut // mutex to protect access to the Interact method• pthread_mutex_t _mp // mutex to implement the wait condition in the event evaluation cycle• cond_t _cv // condition variable to implement the wait condition in the event evaluation cycle• thread_t _thr // thread data structure to create the component’s execution thread

This class has the following methods:

• virtual void Interact(eventPoint*, int ,int) // implements component behaviour• void EvalCycle() // implements the event evaluation cycle• void InterInd() // used by eventPoints to indicate successful interactions or used by other

eventHandlers to indicate their enabled interaction acceptance.

Class eventPoint

This class monitors event offers, defines common attributes of interaction points, informs associ-ated eventHandlers that an event has happened, connects itself to eventHandlers, and takes interac-tion information from system interfaces. This class collaborates with class eventHandler.

This class has the following attributes:

• pthread_t _thr // thread structure• eventHandler* _eh // reference to associated eventHandler • char* _msg // buffer for interaction information

Page 133: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6.3 Software architecture

115

This class has the following methods:

• virtual void Connect(eventHandler*) // connects itself to a eventHandler• virtual void WaitEvent() // monitors events• virtual pthread_t GetThread() // informs the thread structure• virtual void CallEH() // informs the event point that the event has happened, by asking the event

point to call its event handler• void GetData(char**) // delivers interaction information• void ReadData() // takes read information from interface

Class External

This class specializes the class eventPoint to implement external interaction points. This class col-laborates with class eventHandler.

This class has the following attributes:

• int _descr // file or socket descriptor• int _cp // buffers the code of current interaction’s communication primitive• mutex_t _mp // mutex to associated to the implementation of waiting condition• cond_t _cv // condition variable

This class has the following methods:

• virtual void WaitEvent() // monitors events• void InterInd() // informs connected component of a successful interaction• virtual void CallEH() // calls component to treat interaction offer• virtual void ReadData() // read information from corresponding external interface

Class timer

This class specializes class eventPoint for handling timeout. This class collaborates with classeventHandler.

This class has the following attributes:

• int _active // indicates that timer is active• int _to // amount of time in seconds to elapse before timeout

This class has the following methods:

• void SetTimeout(int) // sets a timeout for current time plus the given value (in seconds)• void WaitEvent() // monitors timeout • virtual void CallEH() // abstract method for treating interactions• void Idle() // set timer to idle status

Class Internal

This class specializes class eventPoint for implementing synchronous internal interaction point. Itcollaborates with class eventHandler.

Page 134: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

116

Chapter 6: Basic Multi-thread Framework

This class has the following attributes:

• internal _partner // reference to another instance of internal that cooperates with this one to performinteractions.

This class has the following methods:

• int SendData(int,char*) // sends an interaction offer• int SendDataFw(int,char*) // forwards an interaction offer• void InterInd() // used by a component to indicate to a connected component the enabling of

interaction acceptances• void InterIndFw() // forwards indications of interaction acceptances• void SetPartner(internal*) // gets the reference for the associated internal object

6.3.5 Dynamic Behaviour

This section discusses the interactions between instances of the classes defined in this framework.

Interactions between external and eventHandler objects

Figure 6.2 shows the interaction diagram for the typical cooperation between a specialization ofthe external class and its associated eventHandler specialization. The scenario being represented isthe occurrence of an external event. In Figure 6.2 the external interaction point performs its eventmonitoring task (WaitEvent method) and calls the associated eventHandler when an event isdetected (Interact method). The eventHandler object gets the interaction information (GetDatamethod), processes the incoming offer, wakes up its event evaluation cycle (InterInd method) andreturns an indication of successful interaction. When a second external event offer is detected, themethod CallEH detects an invalid identification for the communication primitive and the event isignored.

:external

WaitEvent

:eventHandlerCallEH

Interact

GetData

[ data ]

[ success ]

InterInd

CallEH

detects event at the externalinterface

Figure 6.2 Execution of an external event

Page 135: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6.3 Software architecture

117

Internal Class

Figure 6.3 illustrates the most common situation in the cooperation between an internal object andits connected components. The scenario being represented is the execution of an internal interac-tion. During its event evaluation cycle (EvalCycle method) the offering component o tries to per-form an interaction offer by calling the method Interact. The interaction offer is performed bycalling the SendData method on the immediately connected internal object r. The r object forwardsthe offer to the destination component by calling the SendDataFw method on the peer internalobject l. l forwards the offer to the accepting component a by calling its Interact method, whichtreats the incoming offer. a gets the interaction information buffered in l by calling the GetDatamethod, accepts and treats the offer. Before returning a success indication, the accepting compo-nent a indicates the occurred interaction to the thread that processes its event evaluation cycle bycalling the InterInd method. The success indication is sent back to o.

Timer Class

Figure 6.4 shows the typical cooperation between a timer and a component implementation, i.e.,an instance of specialization of the eventHandler class. The scenario being represented is the set-ting of a timer and timeout expiration. The cooperation consists of an activation of a timer objectthrough the SetTimeout method. The SetTimeout method starts the method WaitEvent in a newthread to monitor the elapsed time. When the timeout occurs, the related eventHandler is informedusing the method Interact. Another scenario would be the deactivation of the monitoring task bycalling the Idle method of the timer object by the eventHandler.

6.3.6 Consequences

Multi-thread programming may lead to quite complex implementation solutions and therefore it isdifficult to verify its correctness. This technique generates complex structures because of the fol-lowing issues:

r:internal o:eventHandlera:eventHandler

SendData

(accepting) (offering)

Interact

l:internal

SendDataFwInteract

GetData

InterInd [data]

EvalCycle

[success][success]

[success]

Figure 6.3 Execution of an internal interaction

Page 136: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

118

Chapter 6: Basic Multi-thread Framework

• inconsistencies can be easily introduced due to concurrent access to data structures;

• deadlock and starvation can be easily introduced by mistake;

• debugging is difficult since some error situations are difficult to reproduce in debuggingmode.

In this framework, the implementation of the concept of atomicity associated to actions is guaran-teed only when considering actions belonging to the same component, as defined by the BDM. Adefinition of atomicity, considering all actions of a protocol entity is not supported here.

Another consequence of using multi-thread packages is that they compromise to some extent theportability of the implementation, since many slightly different thread packages exist in differentimplementation environments.

6.4 Usage Information

The use of the Basic Multi-thread Framework for implementing protocols is similar to the use ofthe Basic Event Manager Framework. In this section we discuss the differences in the usage infor-mation of these two frameworks. The tasks required to add protocol-specific code to the frame-work are the following:

(1) definition of constants that represent the behaviour states and communication primi-tives required in the protocol;

(2) specialization of required eventPoints;

(3) specialization of required eventHandlers;

(4) definition of the entity class.

The tasks performed in step 1 are identical to those described in chapter 5. The templates used toperform these tasks are presented in Appendix B. Below we concentrate on tasks 2, 3 and 4.

6.4.1 Mutexes and Condition Variables

A new requirement in tasks 2 and 3 is the definition of mutexes and condition variables. This isrequired for the implementation of regions of code where execution threads are mutually exclu-

:timer :eventHandler

InteractSetTimeout

WaitEvent

Interact

Figure 6.4 Timer and eventHandler cooperation

Page 137: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6.4 Usage Information

119

sive and to implement the suspension of an execution thread that performs the event evaluationcycle, to wait for the instability of a component’s behaviour.

In our implementation environment, the required data structures to use mutex and condition vari-ables must be defined as global, which is against some basic rules of the object-oriented program-ming. Each component and external interaction point requires the use of mutexes and conditionvariables in their implementation to protect execution code against concurrent access. In theimplementation of components, protected code is a protocol-dependent part of the implementa-tion, and therefore is supported by the framework’s templates. This piece of code is a fixed part ofthe template that must be copied without changes as many times as required.

Each component requires two mutexes and one condition variable, for suspending the evaluationcycle and protecting the execution of the Handler method. Each external interaction point imple-mentation (external class specializations) requires one mutex and one condition variable to sus-pend the event monitoring tasks. These global definitions are passed to the instantiated objects asinitialization parameters.

6.4.2 Environment-Specific Code

The use of this framework concerning the implementation of environment-specific code does notdiffer from the use of the Basic Event Manager Framework. Although in the Basic Multi-threadFramework the event monitoring cycle executes in a separate execution thread, differing in thisway from the Basic Event Manager Framework, the implementation code for this task is per-formed in a fixed part of the framework usage template.

6.4.3 EventHandler Specialization

The template to specialize the eventHandler class into a concrete class that implements protocolcomponents differs slightly from the Basic Event Manager Framework template.

For the implementation of the Interact method (task 3.3 of the usage information), we use the samesolution as applied in the Basic Event Manager Framework. A similar template than the one usedto implement the behaviour’s finite state machine is also used here. The template in Figure 6.5and Figure 5.7 differ in the following aspects: a) the former template has a protection against con-current execution by means of a mutual exclusion area of code and b) the Interact method in theformer template has can handle three situations, i.e., offer, acceptance and any. These differencesonly regard the fixed code. The instructions for using the template, i.e., filling protocol-specificcode, remain the same as in chapter 5.

Figure 6.5 shows how the solution discussed in chapter 5 is adapted in this framework. There is acommand locking the mutex at the beginning of the code template and an unlock of the muteximmediately before the return of this method.

6.4.4 Entity Class

The constructor of the initialization class performs the following tasks:

Page 138: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

120

Chapter 6: Basic Multi-thread Framework

• treat configuration parameters;

• instantiate of required interaction points;

• set partnership between internal objects;

• instantiate required components;

• execute the Initialization method;

• synchronize created threads.

This class differs from the entity class in Basic Event Manager Framework since it does notinstantiate the eventManager object and at his to synchronize the end of the execution threads.This synchronization is necessary to avoid that the whole protocol entity terminates while themain execution thread completes the initialization task.

6.5 Implementation Example

The information to fill in the templates of the Basic Multi-thread Framework when implementingthe Send Receive protocol presented in Appendix A is exactly the same as in the Basic EventManager Framework framework. This holds for protocol-specific templates and environment-specific templates. Therefore, components and interaction point specializations implemented forthe Basic Event Manager Framework can be fully reused, applying the appropriate templates ofthis framework.

Figure 6.6 shows the object diagram for the implementation of the Send Receive protocol usingthis framework. send, receive, ip1 and ip2 are the protocol-dependent classes. The protocol imple-mentation requires one instance of each. fileIO and udp are the implementation of the environmentdependent classes and are instantiated once in this protocol. The protocol also requires sixinstances of the internal class and one of timer. Two instances of the internal class are required for

im_idcp_codedata_buffer

return fail

return success

[st1]state1

stateZ[st Z]

[oth

erw

ise]

mutual exclusion

lock

mutual exclusionunlock

mutual exclusionunlock

Figure 6.5 Interact Method

Page 139: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

6.6 Evaluation

121

each internal interaction point implementation. Internal objects are identified by _ipn<side>,where n is a number corresponding to the identification in the protocol specification and <side>differentiates the two instances required (l and r stands for left and right, respectively).

6.6 Evaluation

In the development of the Basic Multi-thread Framework we could evaluate the intertwining ofconcepts at the implementation level. By choosing an alternative solution to implement event-driven and parallel behaviour in this framework, most of the solutions to implement other designconcepts developed in the Basic Event Manager Framework had to be adjusted. A one-to-onemapping from design to implementation, which is attractive for conformance and performanceevaluation, has shown to be difficult to achieve.

Some implementation code from of the Basic Event Manager Framework has been reused in thedevelopment of this framework, showing that our goal of producing maintainable code has beenaccomplished to a certain degree.

The use of multi-threading as implementation technique has reduced the framework complexityin terms of lines of code. However, the freedom provided by implementation environments on theuse of threads, forces the programmer to guarantee the consistency of re-entrant code. We assumethat consistent code is code without concurrent access to data structures and without deadlock orstarvation situations. The use of multi-thread, therefore, may produce elegant solutions, however,these solutions are difficult to conceive and are more vulnerable to mistakes than single threadedimplementations.

Since the protocol-dependent code of the Basic Multi-thread Framework is identical to the BasicEvent Manager Framework example, the same conclusions in terms of implementation process

_send:send::eventHandler _receiver:receive::eventHandler

_ip3r:internal::eventPoint

_pduHandler:pduHandler::eventHandler

_timer:timer::eventPoint

_ip1:ip1::fileIO::external::eventPoint

_ip3l:internal::eventPoint

_ip4r:internal::eventPoint

_ip4l:internal::eventPoint

partnerpartner

connectsconnects

connectsconnects

_ip2:ip2::udp::external::eventPoint

connects

connectsconnects

uses

entity

Figure 6.6 Send Receive protocol using Basic Multi-thread Framework.

Page 140: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

122

Chapter 6: Basic Multi-thread Framework

efficiency and implementation correctness hold here. Some minor differences are discussedbelow.

Although the efficiency and correctness of the implementation process when using this frame-work are equivalent to the results obtained with the Basic Event Manager Framework, the bene-fits when using multi-thread programming are more expressive than in the previous case. Theinherent complexity of multi-thread programming makes developments from scratch more timeconsuming. Therefore, having reliable implementation solutions captured within the frameworkgreatly improve the efficiency of the implementation process and the correctness of resultingimplementation.

In order to evaluate the performance of protocols implemented using this framework, we haveperformed the same experiment described in chapter 5. The execution time of an equivalent mon-olithic implementation is compared to the execution time of a structured implementation usingthe Basic Multi-thread Framework.

We use the same implementation scheme in the structure of the receiving entity with the same pur-pose of reproducing a realistic protocol structure. We also focus our attention on the overheadimposed by the support of implementation structuring.

The execution overhead introduced by the framework to support a structured implementation ison average 366% the execution time of the corresponding monolithic implementation. For exam-ple, using 100 as the number of repetitions in the execution of this experiment, the total executiontime in the monolithic implementation is, on average, 19.6 milliseconds and in the structuredimplementation is, on average, 91.4 milliseconds. This means that the execution overhead in thestructured implementation is, on average, 4.66 times the execution time of a corresponding mon-olithic implementation. The impact of the overhead due to structuring techniques on the protocolperformance as a whole discussed in chapter 5 also applies here. The increase in overhead in thissolution is mainly due to the distributed algorithm for detecting when a component has reached astable state, i.e., when all enabled interaction offers and acceptances have failed to interact in thecurrent stage of execution of the whole protocol entity.

The use of multi-threaded frameworks, despite the complexity on its development, is justified byits known contribution in terms of execution performance on multi-processor machines. Protocolswith functions that can be performed in parallel are expected to benefit from the use of this tech-nique. This could be assessed in future.

Page 141: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

123

Chapter 7

Advanced Event Manager Framework

This chapter presents the Advanced Event Manager Framework. This framework consists of anextension to the Basic Event Manager Framework to support additional design concepts. Theadditional concepts supported in this framework are behaviour composition features, i.e.,sequence, choice and interleaving composition of behaviours, and dynamic creation and termina-tion of components.

The structure of this chapter is the following: section 7.1 presents the general approach for pre-senting this framework example; sections 7.2 to 7.4 present the results of our framework develop-ment method in the development of the Advanced Event Manager Framework, i.e., DomainAnalysis, Definition of Software Architecture and Usage Information, respectively; section 7.5presents an example of application of this framework to the implementation of a protocol; andsection 7.6 presents our conclusions about the development and use of this framework.

7.1 Approach

The Advanced Event Manager Framework is another contribution to the catalogue of frame-works. This framework supports a richer design model compared with the BDM supported in theframeworks presented in chapters 5 and 6. We refer in the text to the design model supported bythis framework as Advanced Design Model (ADM).

The purpose of developing this framework is also to analyse the trade-offs in software quality dis-cussed in chapter 1. The main trade-offs that can be analysed comparing the basic version with theadvanced version of a framework are:

• code complexity increase due to the additional concepts supported by this framework;

• performance penalty for supporting more complex structural concepts.

Similarly to chapters 5 and 6, we present the Advanced Event Manager Framework in this chapterby discussing the results of each step of the framework development process, i.e., domain analy-sis, definition of the software architecture and usage information. For the sake of conciseness, we

Page 142: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

124

Chapter 7: Advanced Event Manager Framework

do not present the actual implementation code. However, we make the implementation codeavailable to the interested reader in [80].

Since the Advanced Event Manager Framework and the Basic Event Manager Framework have acommon set of basic concepts, to avoid repetition we limit the presentation in this chapter to thoseissues which differ between the two frameworks.

The example used to illustrate the application of the Advanced Event Manager Framework in theimplementation of a particular protocol is based on the Symmetric Send-Receive protocol pre-sented in Appendix A.

7.2 Domain Analysis

The Advanced Event Manager Framework supports the same specialization of components, inter-action means, behaviour and interaction concepts, as supported in the Basic Event ManagerFramework. The additional features supported by this framework are behaviour composition rela-tions, and dynamic creation and destruction of components.

To avoid repetition in the content of our domain analysis, the concepts of the ADM that aredefined in the BDM are simply listed below. Class diagrams for the new concepts being sup-ported are presented in the sequel. The concepts of the BDM that are also defined in the ADMare:

• Interaction Means: two-party interaction point;

• Behaviour: default firing policy, timeout, interaction acceptance and interaction offer typesof event, guarding condition and action;

• Interaction: synchronous and value passing.

7.2.1 Component

In the ADM, in contrast with the BDM, components can be created and destroyed dynamically.This means that during its execution, a component can create new components and connect thesenew components to existing ones through interaction points. A component can also destroyanother component. Creation and destruction of components are performed as operations in theactions of a component’s behaviour.

Consistency Rules

The use of dynamic creation and destruction of components in a protocol design are guided byconsistency rules. An example of inconsistency that must be avoided while applying these con-cepts is the connection of an interaction point to a component whose behaviour does not involvethat interaction point. The consistency rules associated to component creation and destructiondesign concepts in the ADM are the following:

• any component can create other components. In this text we use the terms father and childto refer to the creator component and the created component, respectively;

Page 143: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.2 Domain Analysis

125

• a component can only be destroyed dynamically if it was created dynamically;

• a component can only be destroyed by its father component;

• components can only be connected to interaction points by its father component;

• a component can only connect one of its own child components to another of its own childcomponent;

• when a component is destroyed, all its connected interaction points must be disconnected anddestroyed.

We distinguish two types of interaction points with respect to the moment at which an interactionpoint is connected to a component: 1) Static interaction points are those connected to the compo-nent during its creation. 2) Dynamic interaction points are those which are connected to the com-ponent after its creation.

In order to support dynamic interaction points, components’ behaviour in this design model mustbe prepared to treat different classes of interaction points. The set of communication primitivesthat can be executed through interaction points are used to classify these interaction points, suchthat interaction points that allow the same sets of communication primitives to occur belong to thesame class of interaction points. The design of a component can apply an undefined but limitednumber of classes of interaction points. The number of instances of interaction points of a certainclass that can be dynamically connected to a component is conceptually unlimited. The treatmentof classes of interaction points is discussed in more detail later in this chapter.

An additional reason for defining the consistency rules for dynamic creation and destruction in theADM has been to limit the number of possible design constructs. In this way, we keep the com-plexity of the implementation of components creation and destruction manageable within thescope of our work.

7.2.2 Behaviour Composition

The behaviour composition relations supported by the Advanced Event Manager Framework aresequence, choice and interleaving. The semantics of such concepts have been discussed in chapter 3.Figure 7.1 shows the behaviour composition concepts in the Advanced Event Manager Frameworkand their specialization relations. The disruption concept is represented in gray in Figure 7.1 sinceit does not belong to the ADM. Furthermore, the disruption concept has not been required in ourexperiments.

composition

parallelism sequence choice

relation

behaviour

{disjoint, incomplete}

behaviourcomposes

2..*0..*

disruption

Figure 7.1 Behaviour composition relations

Page 144: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

126

Chapter 7: Advanced Event Manager Framework

The type of parallelism supported in the ADM is interleaving with synchronous termination. TheADM allows a non-deterministic interleaving. Figure 7.2 shows the class diagram representingthe type of parallelism considered in the ADM.

In the ADM, the choice behaviour composition relation is non-deterministic (see section 3.4.6).The sequence behaviour composition relation is a n-ary relation that ordinates the related sub-behaviours. A sequence can consist of one execution of the set of related sub-behaviours or of aninfinite loop in which the first behaviour of the sequence is enabled again after the last behaviourhas finished its execution.

Consistency Rules

Consistency rules are required for composing behaviours. For example, two behaviours com-posed simultaneously by a choice and a sequence relations would be inconsistent. Figure 7.3shows some diagrams that describe the possible behaviour compositions in the ADM. In thesediagrams the rounded boxes indicates a behaviour construct, the rectangular boxes refer to otherdiagrams and the arrows indicate the order in which the constructs can appear in the composition.

7.3 Software Architecture

The software architecture of the Advanced Event Manager Framework is an extension of the soft-ware architecture of the Basic Event Manager Framework. New classes have been added to the

parallelism

asynchronoussynchronous deterministic non-deterministic

{overlapping}

{disjoint}{disjoint}

termination termination

Figure 7.2 Parallelism specialization

behaviour composition of

composition of

sequence

monolithic

Figure 7.3 Behaviour composition consistency rules

choice

interleaving

behaviour

behaviour

Page 145: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.3 Software Architecture

127

software architecture of the Basic Event Manager Framework to implement behaviour composi-tion relations. Dynamic creation and destruction of components have been implemented by modi-fying classes of the Basic Event Manager Framework software architecture. The classesintroduced in the Advanced Event Manager Framework are term, behaviour, relation, choice, inter-leaving and sequence.

Behaviour composition has been implemented in this framework by adapting the solution dis-cussed in section 4.5 for composition of behaviours within a component. We use a tree structurewhose nodes and leaves are composition relations and behaviours, respectively. Each componentuses a single tree to implement its composed behaviour. Indications of events to be treated by acomponent are delivered to the root element of the component’s tree and routed by the nodes tothe leaves. The use of a tree of terms was inspired by a scheme commonly applied to implementthe resolution of arithmetical expressions, whose semantics involving operands and operatorsresembles our problem. An analogous scheme has been used in [70] for the implementation of themultirendezvous (multi-way synchronization) of LOTOS processes. A tree of terms is used in thismultirendezvous implementation to optimize the attempts of synchronization for interactionbetween the implementations of LOTOS processes.

Our solution for dynamic creation and destruction of components consists of three parts:

• implement commands for creation and destruction of components, and connection and dis-connection of components to and from interaction points;

• implement support for the manipulation of dynamic interaction points;

• implement the consistency rules that relate to the destruction of components.

Commands are implemented as methods that encapsulate the details of the required operations. Inthe cases of creation of components and connection of interaction points, most of the requiredoperations are already implemented in the static methods of the Basic Event Manager Framework.Examples of details encapsulated in such methods are the updating of the list of dynamic interac-tion points connected to a certain component, the connection of a new interaction point, and amethod to inform an interaction point which component it is connected to. Dynamic creation anddestruction of components implies in the maintenance of a list of dynamic interaction points con-nected to a component. The implementation of consistency rules are discussed further in section7.3.7 and 7.3.8.

Figure 7.4 shows the software architecture for the Advanced Event Manager Framework. Thespecializations of the eventPoint and eventHandler classes are not shown in Figure 7.4 since theyremain unchanged with respect to the Basic Event Manager Framework software architecture.

7.3.1 Class term

The common characteristics of the elements of the behaviour composition tree are captured in aclass which we call term. The name term is chosen since it is commonly used to refer to elementsof an expression, which resembles the concept we want to represent. The common characteristicsto be captured by the term class are: links to other related terms, a link to the component to whichthe term belongs, methods to connect the terms in order to build the tree and the definition of the

Page 146: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

128

Chapter 7: Advanced Event Manager Framework

common interface for the routing indications of an event occurrence. The term class is specializedfor the different composition relations throughout the tree.

7.3.2 Class relation

An abstract class called relation is used in this solution to provide a common reference to the dif-ferent possible behaviour composition relations. Instances of the specializations of the class rela-tion are in the root and nodes of the tree of terms. Each relation controls whether or not the termssubordinated to its branches are currently allowed to treat an event. The routing control in the rela-tion class is specialized in choice, interleaving and sequence policy.

A method called Interact is implemented by the term class to receive incoming events. The Interactmethod is overloaded in the specializations of the relation class to implement the different routingpolicies. An incoming event is forwarded through the tree by each term by calling the Interactmethod of the next term in the branch. Relations use the return code of the Interact method, propa-gated backwards through the tree, to set the context for the next incoming events. The possiblereturn codes are:

• Fail: it was not possible to treat the current event. The possible reasons for that are that theevent is not expected or the event has been not accepted by the guarding condition;

• Success: the event was successfully treated;

• End-of-execution: the term successfully treated the event and has finished its execution.

7.3.3 Class sequence

The sequence specialization of the relation class maintains a list of ordered terms. A sequenceobject keeps track of the next term in the list to be executed (selected term). If a sequence objectreceives an event indication, it propagates this indication to the appropriate term on its list. Thepossible reactions of a sequence object, depending on the received return code, are:

monitors

calls

eventManager

eventHandler eventPoint

+1

uses +1+1

+1

term

behaviour

choice interleaving sequence

Handler()

has

+1

activates

+1

relationcontrols

2..*

aggregates

Figure 7.4 Advanced Event Manager Framework software architecture

controls

+1

Page 147: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.3 Software Architecture

129

• Fail: the sequence object keeps the same selected term and propagates the failure indicationupwards in the tree;

• Success: the sequence object keeps the same selected term and propagates the success indi-cation upwards in the tree;

• End-of-execution: if the selected term is the last in the sequence, the sequence object propa-gates the end-of-execution return code upwards in the tree, otherwise it updates the pointerto the selected term and propagates a success return code upwards in the tree.

In order to configure the sequence class to perform a loop, at the moment of the sequence objectinstantiation a configuration information is passed to this object. This configuration information ischecked when the selected term is updated to decide whether the associated behaviour should berepeated or if it has finished its execution.

In order to allow the repetition of behaviours in a sequence relation, all terms that have alreadyexecuted in the sub-tree that has the sequence as root, must have their context re-initialized to astarting situation. Therefore, all terms re-initialize their status when they reach the end of execu-tion, becoming ready for a possible behaviour repetition.

7.3.4 Class choice

An instance of the class choice maintains a list of terms that are candidates for execution. In itsstarting situation, if the choice object receives an event occurrence, it propagates the event occur-rence indication downwards in the tree to all terms on its list in succession. The first term thatreturns a success indication is marked as the selected term. Thereafter, the selected term is theonly term in that list to receive an opportunity to execute. If an end-of-execution indication isreturned to a choice object by one of the elements of the list, the choice object resets itself to thestarting situation and propagates the end-of-execution indication upwards in the tree.

7.3.5 Class interleaving

Interleaving objects maintain an ordered round list of composed terms and a pointer to a selectedterm to which an execution opportunity should be given. When an interleaving object receives anevent indication, it offers the opportunity to the terms on its list starting from the selected termand following the list order. This is a simple approach to guarantee that each interleaved behav-iour receives an opportunity to execute. Opportunities for execution are given until a term returnsa success or an end-of-execution indication. In case of a success indication, the selected term pointsto the next in the list and the execution control is returned to the calling term with a success returncode. In case of an end-of-execution indication, the executed term is marked and control is returnedto the calling term with a success return code. Marked terms no longer receive opportunities forexecution. If all terms are marked, the interleaving object returns to the start situation and propa-gates the end-of-execution code upwards in the tree.

Page 148: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

130

Chapter 7: Advanced Event Manager Framework

7.3.6 Class behaviour

Behaviour objects are the leaves of the tree. Behaviours are terms that call the method implement-ing the protocol behaviour, delivering events to be treated.

Protocol behaviour is implemented as in chapter 5. However, since in this framework the methodthat executes the unit of behaviour related to an interaction calls the root of the tree when an eventarrives, the method for behaviour implementation has been termed Handler. This scheme providestransparency to the framework developer regarding the solutions for other design concepts sup-ported by the remaining framework, when performing the changes required to support behaviourcomposition.

Behaviour implementations within the Handler method have an identification. When instantiatedbehaviour objects are informed of the identification of their corresponding behaviour implementa-tion. This identification allows behaviour objects to specify to the Handler method which behav-iour is intended to be executed. The return codes of the Handler method are propagated upwardsby the calling behaviour object.

7.3.7 Boundary Conditions

The boundary condition tasks performed in the Advanced Event Manager Framework are in gen-eral the same as those performed in the Basic Event Manager Framework. Some differences arediscussed in the sequel.

Component termination can happen in two situations: the component itself starts its destruction ora component is destroyed by its father component. In the first case, the component’s behaviourends with an end-of-execution return code. Before propagating the end-of-execution code upwards,the behaviour object that receives this code checks if it is the root term of the tree. If so, it executesthe Termination method of its related component and returns a success code to the interaction pointthat has delivered the event, otherwise, propagation is performed as usual. Therefore, the compo-nent is only destroyed when all behaviours of its composed behaviour have terminated. In the sec-ond case, the father component simply calls the Termination method of the component it wants todestroy.

The Termination method informs the event dispatcher of the end of the component’s life time. Theactual destruction of a component is performed by the event dispatcher. This is necessary in orderto avoid inconsistencies in the manipulation of the event dispatcher’s list of components. Whendestroyed, a component destroys the tree of terms implementing its behaviour composition. Thedestructor walks through this tree and destroys its terms.

When it is being destroyed, a component must also disconnect its interaction means. This opera-tion depends on protocol-specific information and therefore it is further explained in the UsageInformation section (7.3.10). Since we only support two-party interaction, the destruction of oneinteracting party of an interaction point implies that this interaction point is no longer useful andcan also be destroyed. The destruction of an interaction means consists of the destruction of thetwo partner internal objects that are used to implement an interaction point. The other component

Page 149: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.3 Software Architecture

131

attached to the interaction means being destroyed is informed of the destruction. Such a compo-nent then removes the interaction point from its list of dynamic components.

7.3.8 Definition of Classes

Classes have been defined in this framework using the CRC cards approach, i.e., explicitly identi-fying responsibilities, collaborators, attributes and methods for each class in the design. Theclasses of chapter 5 that remain unchanged in this framework are not discussed here.

Class term

This class provides the common characteristics of the elements of the behaviour composition tree,defines a common interface to the function that propagates events occurrence indication along thetree, and provides a unique implementation type to refer to when manipulating the tree elements.This class collaborates with classes eventHandler and term.

This class has the following attributes:

• term *_parent // reference to node upwards in the tree• list<term> _termList // reference to the composed terms • eventHandler* _component // reference to the component it belongs

This class has the following methods:

• virtual void AddTerm(term* ) // add terms to _termList• virtual int InteractFw( eventPoint *,int ,int ) // receive indication of event occurrence

Class behaviour

This class specializes the class term to implement the leaves of the tree for behaviour composition,keeps the identification of the related sub-behaviour, activates the related sub-behaviour to treatan event, and propagates upwards the results of event treatment. This class collaborates withclasses eventHandler and term.

This class has the following attributes:

• int _BehId // identification of the related behaviour

This class has the following methods:

• virtual int InteractFw( eventPoint *,int ,int ) // receive indication of event occurrence and forwardit to the appropriate child term

Class choice

This class specializes the class term to implement the behaviour composition of the child terms ina choice relation, and propagates upwards the results of events treatment. This class collaborateswith classes eventHandler and term.

Page 150: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

132

Chapter 7: Advanced Event Manager Framework

This class has the following attributes:

• term* _choice // identification of the chosen child term

This class has the following methods:

• virtual int InteractFw( eventPoint *,int ,int ) // receive indication of event occurrence and forwardit to the appropriate child term

Class interleaving

This class specializes the class term to implement the behaviour composition of the child terms inan interleaving relation, and propagates upwards the results of event treatment. This class collab-orates with classes eventHandler and term.

This class has the following attributes:

• list <int> _exited // list of children terms that have indicated an end-of-execution

This class has the following methods:

• virtual int InteractFw( eventPoint *,int ,int ) // receive indication of event occurrence and forwardit to the appropriate child term

• void InitExited() // initializes the list of exited terms

Class sequence

This class specializes the class term to implement the behaviour composition of the child terms ina sequence relation. This specialization may support the infinite repetition of the sequence. Asequence object propagates upwards the results of each event treatment. This class collaborateswith the classes eventHandler and term.

This class has the following attributes:

• term* _next // reference to the next term to receive an opportunity to execute• int _loop // flag to configure the behaviour as a repetition

This class has the following methods:

• virtual int InteractFw( eventPoint *,int ,int ) // receive indication of event occurrence and forwardit to the appropriate child term

Class eventPoint

The responsibilities of this class are to inform its associated eventHandler that an event has hap-pened, to register and de-register itself at the eventManager, and to connect itself to eventHandlers.This class collaborates with the classes eventManager and eventHandler.

This class has the following attributes:

• eventHandler* _eh // associated eventHandler

Page 151: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.3 Software Architecture

133

• eventsManager* _em // reference to the eventManager object• char *_msg // reference to the buffer for interaction information

This class has the following methods:

• void Connect(eventHandler*) // connects the eventPoint to an eventHandler• virtual int Type() // gets the type of the eventPoint• virtual void CallEH() // informs that an event has happened• eventHandler* GetHandler() // informs the connected eventHandler• void GetData() // delivers the reference to the buffer for interaction information • virtual void Disconnect() // disconnects and removes the interaction point• virtual void DiscoFw() // forwards disconnection request to connected component• virtual int ReadData() // gets interaction information from the external interface, puts informa-

tion in internal buffer and calls related eventPoint• virtual void InterInd() // informs the interaction point that its connected component has enabled

an interaction acceptance

Class eventHandler

This class implements the common attributes and methods of components, handles componenttermination, and provides a unique implementation interface for the method that implements thesub-behaviours of a component (Handler). This class collaborates with classes eventPoint and term.

This class has the following attributes:

• int _state // keeps the main state of a component’s behaviour• term *_root // reference to the root of the tree of terms that implements behaviour composi-

tion• int _instable // indicates whether the component still has units of behaviour to be triggered• eventsManager *_em // reference to the eventManager object• list<internal> _dynamicIPList // list of connected dynamic interaction points

This class has the following methods:

• virtual int Interact( eventPoint *,int ,int ) // receives indication of event occurrence and forwardsit to the root term

• void InterInd() // indicates the possibility of synchronizing one of the enabled interaction offers• int EvalCycle() // performs the component’s event evaluation cycle• virtual int Handler(int ,eventPoint* ,int ,int ) // implements the component’s behaviour• void Terminate() // performs the component’s termination procedure• void AddDIP(internal*) // registers an interaction point in case of dynamic connection• void RemoveDIP(internal*) // removes an interaction point from the list on disconnection• virtual void Initialization() // initializes the component’s context variables

Class internal

This class forwards interaction offers and acceptances to the partner component. This class col-laborates with specializations of the classes internal and eventHandler.

Page 152: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

134

Chapter 7: Advanced Event Manager Framework

This class has the following attributes:

• internal *_partner // reference to the partner internal object

This class has the following methods:

• int Type() // gets the type of the event point• void SetPartner(internal*) // set the partner internal object• void InterInd() // forwards indication of interaction acceptance to partner internal object• void InterIndFw() // forwards indication of interaction acceptance to related eventHandler• int SendData(int,char*) // forwards interaction offer to partner internal object• int SendDataFw(int,char*) // forwards interaction offer to related eventHandler• virtual void Disconnect() // disconnects and removes interaction point• virtual void DiscoFw() // forwards disconnection request to connected component

7.3.9 Dynamic Behaviour

In this section we discuss our solution for dynamic creation and destruction of components, and thehandling of behaviour composition. The dynamic behaviour of the remaining parts of this frame-work is similar to the Basic Event Manager Framework (chapter 5) and therefore is not furtherdiscussed in this chapter.

Dynamic Creation and Destruction of Components

Figure 7.5 illustrates the dynamic creation and connection of a component. An instance of com-ponent cp1 creates two internal objects (int1l and int1r) and set these two instances as partners. Thecp1 object also creates an instance of the component cp2, indicating through a parameter the con-nected interaction point. Afterwards, cp1 dynamically connects itself to the new interaction pointusing the AddDIP method.

In Figure 7.6 shows the destruction procedure up to the command to destroy a component. AneventHandler object reaches the end of its execution as a result of an interaction. In this examplewe suppose that the eventHandler object performs a monolithic behaviour that requires one behav-iour object in the tree of terms. When the behaviour object receives the indication of end of execu-tion (EXIT code) from its related eventHandler object, because this behaviour term is at the root ofthe tree, it calls the Terminate method of the eventHandler. The Terminate method indicates to theeventManager object the destruction of the eventHandler (EndOfExecution method). At the end of itsmonitoring cycle, the eventManager deletes all eventHandler objects that have indicated theirdestruction.

Figure 7.7 shows what happens when an eventHandler is deleted. When it is being destroyed, theeventHandler finishes its connections by calling the Disconnect method on its interaction points. e1in Figure 7.7 is an eventHandler object, i1 and i2 are internal objects implementing an interactionpoint i, and e2 is another eventHandler object connected to e1 by i. The Disconnect method of theinternal class forwards the disconnect indication (DisconnectFw method) to the partner internalobject and destroys i2. Before being destroyed, i2 disconnects itself from e2 (Disconnect method),updating the list of dynamic interaction points of e2. i1 is then destroyed by e1.

Page 153: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.3 Software Architecture

135

Behaviour Composition

We present below two examples of behaviour composition, one using the choice relation (Figure7.8) and another using the interleaving relation (Figure 7.9). Figure 7.8 shows two attempts of achoice object to treat an incoming event.

:cp1:eventHandler int1l:internal

Figure 7.5 Component’s creation and connection

:cp2:eventHandlerint1r:internal

new internal

SetPartner(int1r)

SetPartner(int1l)

new cp2(int1r,_em)

AddDIP(int1l)

new internal

:eventManager :eventHandler :behaviour

Interact() InteractFw()

Handler(1)

[exit]Terminate()

EndOfExecution()

[success][success]

X

Figure 7.6 Component’s end of execution

delete()

Page 154: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

136

Chapter 7: Advanced Event Manager Framework

Figure 7.8 shows an eventPoint object delivering an event to be treated by an eventHandler object(Interact method). Information on the event to be delivered is forwarded down the tree using themethod InteractFw. The eventHandler’s behaviour in this example consists of a choice compositionof two behaviours b1 and b2. The choice object is the root of the tree that implements behaviourcomposition. Therefore, it is the first term to receive the event indication through of the InteractFwmethod. The choice object propagates the indication to the first term in its list of terms. We haveassumed that the choice object is on its initial state, when no choice has been made among theterms immediately downwards following the branches of the sub-tree that has this choice objectas root.

The first term in the choice object’s list of terms is object b1. The choice object invokes b1’s Inter-actFW() method, and this method activates the Handler method of the eventHandler object, sendingits behaviour identification (1). We suppose the eventHandler object is not ready to execute b1, andreturns a FAIL code, indicating an unexpected event. This code is propagated by the behaviourobject to the choice object.

:e1:eventHandler i1:internal i2:internal :e2:eventHandler

delete()Disconnect()

Xdelete()

delete()X

X

Figure 7.7 Disconnecting an interaction point

DisconnectFw()Disconnect()

:eventPoint :eventHandler :choice b1:behaviour b2:behaviour

Interact() InteractFw()

[ fail ]

interactFw()Handler(1)

[ fail ]

InteractFw()Handler(2)

[ success ][ success ]

[ success ][ success ]

Figure 7.8 Dynamic behaviour involving a choice object

Page 155: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.3 Software Architecture

137

The choice object then tries the next term on its list, which is behaviour object (b2). We supposethat the eventHandler is ready to execute behaviour b2 and the Handler method returns SUCCESS.

This result is propagated upwards to the eventPoint that initiated this scenario.

In Figure 7.9, the eventHandler’s behaviour consists of two interleaved behaviours b1 and b2. Theroot term in this example is an interleaving object. The eventPoint object indicates an event occur-rence to the eventHandler (Interact method). The eventHandler propagates this method to the rootterm. The interleaving object propagates the indication (interactFw method) to the first term of itslist of terms (b1). We suppose that the interleaving object is in its initial state, where all childrenterms are still candidates to treat the event. Behaviour b1 calls the Handler method of the eventHan-dler object to treat the incoming event. We suppose that b1 has reached the end of execution, andthe Handler method returns an end-of-execution (eoe) code indicating that the event was treated andreached the end of execution. Since there is still another behaviour executing within this interleav-ing relation, the interleaving object propagates a SUCCESS indication upwards. The SUCCESS indi-cation is propagated by the eventHandler to the eventPoint object.

7.3.10 Consequences

The consequences of applying the Advanced Event Manager Framework are the same as thosereported for the Basic Event Manager Framework, in section 5.3.7, i.e., limitations in the inter-leaving between events and in the portability of the resulting implementation.

Since the Advanced Event Manager Framework supports behaviour composition, there is a conse-quent performance overhead imposed by the controlling mechanisms applied. An assessment ofthis overhead is given in section 7.6.

The consistency rules related to destruction of components were introduced to simplify our imple-mentation solutions. However, these rules slightly deviate from the approaches taken by mostavailable environments. For example, in the Unix operating system, all processes belong to a sin-gle tree of father/child processes and the killing of a father process terminates the execution of itschildren processes.

:eventPoint :eventHandler :interleaving b1:behaviour b2:behaviour

Interact() InteractFw()InteractFw()

Handler(1)

[ eoe ]

[ success ]

[ success ]

[ eoe ]

Figure 7.9 Dynamic behaviour involving the interleaving object

Page 156: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

138

Chapter 7: Advanced Event Manager Framework

7.3.11 Alternative Implementation Solutions

This section discusses some alternative implemetation solutions for the behaviour compositionconcept supported by the Advanced Event Manager Framework.

An alternative implementation of behaviour composition has been discussed in chapter 4. Thisalternative consists of implementing a single monolithic behaviour in an eventHandler and use dif-ferent eventHandler objects to implement the elements of a behaviour composition. The imple-mentation would have two specializations for the eventHandler class: one that does not allow itsinstances’ behaviour to be externally controlled, being composed with the behaviour of othereventHandler objects, and another one that provides the necessary features for its instances’ behav-iour to be controlled by monitoring elements. The first specialization implements a component. Inthe second specialization, monitoring elements would be associated in a tree structure, followingthe same pattern applied in the Advance Event Manager Framework to implement behaviourcomposition. Instances of the first eventHandler specialization would instantiate the second spe-cializations and their composition tree. The component implementation would contain the contextvariables common to all its composed monolithic behaviours.

This solution would be appropriate for a design model where some control is intended in the shar-ing of context variables between different monolithic behaviours, because monolithic behavioursin this solution are implemented in different objects. Many instances of the same monolithicbehaviour would be easily implemented through instantiations of the corresponding eventHandlerspecializations. The definition of a father/child relation among the second type of specializationswould provide a natural implementation for a specification with a hierarchy of composed behav-iours. This solution, however, makes it difficult to share context information between differentcomposed monolithic behaviours.

Another solution for behaviour composition is to extend the tree of terms, where new term spe-cializations would control the execution at the level of units of behaviour. The new term speciali-zations would keep the information concerning a unit of behaviour, i.e., expected communicationprimitives, guarding condition and related action. The behaviour term would be substituted bythese new term specialization. The protocol-specific behaviour would be captured in specializa-tions of the new term specialization. The Handler method would be simplified to a procedure tosynchronize components and handle timeouts.

Alternative solutions can also be elaborated by changing the propagation of the event occurrenceindication, downwards and upwards in the tree of terms, towards a more efficient scheme. Forexample, eventPoint objects could directly call behaviour objects that would report the results ofthe operation to its father term. This would allow the father term to disable the calling of thebehaviour object if required by the composition semantics.

Assuming that we could obtain a correct implementation of the ADM by using anyone of thealternative solutions presented in this section, there are two main criteria which can be used tochoose between these solutions. The first is to assess to what degree these solutions comply withthe heuristics that enforce software quality in our framework development process. The second isa comparison of execution performance. Concerning the first criterion, our choice for the solutionapplied in this framework complies to one of our heuristics for developing frameworks. We

Page 157: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.4 Usage Information

139

choose for the solution that better profits from code reuse, since we are prototyping by extendinga more simple framework. Concerning the second criterion, at the level of minor optimizations, itis necessary to apply a systematic approach for making decisions on performance issues. A deeperanalysis on the performance of algorithms, however, is out of our scope.

7.4 Usage Information

The use of the Advanced Event Manager Framework for protocol implementation is similar to theuse of the Basic Event Manager Framework. The differences are in the composition of behavioursand dynamic manipulation of components. Code templates are presented in detail in Appendix B.In this framework the protocol implementation involves the following steps:

(1) - definition of constants representing the behaviour states and communication primitives of the protocol;

(2) - specialization of external class for the required interaction points;

(3) - specialization of required eventHandlers;

(4) - definition of initialization class.

Below we concentrate on step 3, since the other steps remained unchanged with respect to theframework presented in chapter 5.

7.4.1 Behaviour Composition

Behaviour composition is implemented in the specializations of the eventHandler class. The Inter-act method in this framework just implements an event occurrence notification. The behaviour ofa component is implemented in the Handler method. The body of the Handler method contains atemplate similar to the one discussed in section 5.3.2. This template has been adapted, however, tosupport the following differences: a) if a behaviour reaches the end of its execution, it returns anEXIT code, and changes its global state to END. b) The implementation of different monolithicbehaviours composed within a component must be identified. Figure 7.10 shows the templates forthe implementation of units of behaviour in this framework. An identifier is received as a parame-ter by the Handler method, and used in the behaviour implementation to identify the appropriatedbehaviour to treat an incoming event. This scheme is illustrated in Figure 7.11.

Figure 7.10 shows three diagrams corresponding to the templates of a unit of behaviour triggeredby an interaction offer, an interaction acceptance or a timeout event, respectively. These templatesare part of the template for implementation of the Handler method presented in Figure 7.11, whereunits of behaviour are represented by the unit of behaviour boxes. The protocol-dependent informa-tion in unit of behaviour templates is highlighted using underline and italic font formats. The deci-sion of whether or not the execution of a unit of behaviour ends with a success or an exit dependson the protocol being implemented. The keywords ep, cp, and timer represents variables that storea reference to the related interaction point, the received communication primitive, a reference tothe buffer containing the interaction information and a reference to the timer object, respectively.The first decision taken in each template concerns the type of action being performed in the cur-

Page 158: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

140

Chapter 7: Advanced Event Manager Framework

rent event evaluation cycle. This information is available through the act parameter of the Handlermethod.

Besides implementing the finite state machines of each behaviour within the Handler method, wealso have to build the tree to control the composition of these behaviours. This is done in the con-structor of the specialization of the eventHandler class. Each term of the tree must be created andconnected to its father term using the AddTerm method. The _root attribute of the eventHandlerobject must point to the root term of the tree. behaviour objects must be configured throughparameters with the identifier of the related behaviour within the Handler method. Figure 7.12illustrates this scheme.

Figure 7.12 illustrates the implementation of a particular behaviour composition arrangement.Figure 7.12 shows the composition using a textual notation, the graphic representation of the cor-responding tree of terms, and the implementation code. The implementation code is given in aC++-like syntax and shows the instantiation of each of the terms of the tree. We show how theobjects are related to each other so that the implementation works according to the desired behav-iour. behaviour objects also need a unique behaviour identifier within the related eventHandler.Terms are related to each other using the AddTerm method.

(offer)

[offer] execute interaction

offer[succeed]

[acceptance]

[acceptance] [ep&&cp] getinformation

[guardingcondition]

action

[offer]

indicateenabledcondition

[otherwise] [otherwise]

unit of behaviour

unit of behaviour

(accept)(ep)

action(ep,cp,data)

(ep)

[end of execution]

[otherwise]

[end of execution]

[otherwise]

Figure 7.10 Unit of behaviour algorithms

success

exit

[timer is not active]

action[otherwise]

unit of behaviour(timeout )

[act==offer]

[ep=timer]

activate timer

[ guarding condition holds ]

[otherwise]

[otherwise][end of execution]

[otherwise]

[otherwise]

Page 159: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.4 Usage Information

141

7.4.2 Dynamic Manipulation of Components

The creation of components in this framework is done by instantiating eventHandler specializa-tions, as in the Basic Event Manager Framework. However, this procedure can now be done aspart of an action of a unit of behaviour. The father component must keep references to the createdcomponents to enable future manipulations like connection and destruction. A dynamic list ofcomponents may be necessary if the number of components to be instantiated is defined at run-time.

The created components must be connected to existing components or to the environment. Thereare different possibilities to connect a child component to other components:

• connection of a fixed interaction point: the reference to the interaction point is passed asparameter to the component at the moment of its instantiation;

[st1]unit of behaviour 1

unit of behaviour 2

unit of behaviour n

...

st1 units of behaviours

st2 units of behaviour[st2]

end state procedure [END]

...

fail

success

Figure 7.11 Handler template

[behId=1]

behaviour 1

[behId=2]

[behId=K]

...

behaviour 2

behaviour k

exit

im-idcp-coderulebehId

Page 160: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

142

Chapter 7: Advanced Event Manager Framework

• connection of a dynamic interaction point: the AddDIP method is used to inform componentsof a new dynamic interaction point they have to handle.

The interaction points used to connect components need to be dynamically created to modify theconfiguration of components and interaction points during system operation. Interaction points(internal and external) are created in a similar way as in the Basic Event Manager Framework.Interaction points can be created and destroyed as operations of units of behaviour.

The framework provides each eventHandler with a list of dynamic interaction points. This list isused in the component’s behaviour implementation to allow one to treat a variable number ofinteraction points.

In order to build behaviours that treat a set of similar interaction points, part of the code templatepresented in section 5.3.2, has to be embedded in a loop that executes the unit of behaviour imple-mentation code to all interaction points in the list. Figure 7.13 presents this construction.

interleaving ( choice ( A , B ) , C )

_root interleaving

choice simpleExpression

simpleExpressionsimpleExpressionA B

C

_root = new interleaving (NULL , this);choice *choice1 = new choice (_root , this );behaviour *behA = new behaviour(choice1, “A”, this);behaviour *behB = new behaviour(choice1, “B”, this);behaviour *behC = new behaviour(_root, “C”, this);_root->AddTerm(choice1); _root->AddTerm(behC);choice1->AddTerm(behA); choice->AddTerm(behB);

implementation code

classes structure

Figure 7.12 Building the behaviour composition controlling structure

unit of behaviour dip = first dynamicinteraction point

dip = next dynamicinteraction point

Figure 7.13 Handling dynamic interaction points

[otherwise]

[end of the list]

success

exit

Page 161: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.4 Usage Information

143

The scheme presented in Figure 7.13 substitutes the unit of behaviour implementations in the pre-vious scheme (Figure 5.7). This solution can be applied for interaction offers and interactionacceptances. This solution provides attempts to execute units of behaviour associated with eachconnected dynamic interaction points (IPs). The behaviour template shown in Figure 7.13 tries toexecute units of behaviour associated to each active interaction point, until either a unit of behav-iour is successful, the behaviour reaches an EXIT, or the list has been completely evaluated.

The operation of timer objects and internal eventPoint objects in this framework is similar to theoperation of the corresponding objects in the Basic Event Manager framework.

7.4.3 EventHandler Specialization

The tasks required to specialize the eventHandler class in this framework are described in thesequel. The tasks that have not been modified with respect to chapter 5 are listed here without fur-ther comment.

EventHandler Header (3.1)

The steps required in this task are:

• definition of the prototype of the method implementing the treatment of the set of connecteddynamic interaction points;

• definition of the protocol-specific attributes required by the component’s behaviour.

Class Constructor (3.2)

The steps required in this task are:

• instantiation of local eventPoints;• connection of required eventPoints;• storage of reference to fixed interaction points;• instantiation of terms of behaviour composition tree;• establishment of relationship between the terms of the behaviour composition tree;• initialization of the root term of the behaviour composition tree.

Handler Method (3.3)

The template to implement the Handler method is discussed in sections 7.4.1 and 7.4.2. The differ-ences compared to the Basic Event Manager Framework are the EXIT code, the selection of themonolithic behaviour to be executed, and the implementation of behaviour to treat a set ofdynamic interaction points. Components can create, connect and destroy often components. Themethod AddDIP is used to dynamically connect interaction points to components and the methodTerminate is used to destroy components.

Page 162: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

144

Chapter 7: Advanced Event Manager Framework

Class Destructor (3.4)

Fixed interaction points must be disconnected and destroyed. Destruction of dynamic interactionpoints are handled by the framework.

Initialization Method (3.5)

The steps required in this task are:

• component global state initialization;• protocol attributes initialization.

7.5 Implementation Example

This section shows the use of the Advanced Event Manager Framework to implement the sym-metric Send-Receive protocol with confirmation and re-transmission presented in Appendix A.We discuss the use of the framework in so far as it differs from the use of the Basic Event Man-ager Framework.

Since the main functions in this protocol, i.e., send, receive, and pduHandler, are relatively simple,elaborated structuring is not required. Different arrangements are possible when structuring thisprotocol in terms of components and composed behaviours. The motivation for the protocolstructure proposed in this section is mainly to illustrate the behaviour composition concept sup-ported by this framework, rather than efficiency or performance issues.

The protocol is implemented here as two components. One component implements the behaviourof pduHandler and the second component, called SR (Send-Receive), implements two interleavedmonolithic behaviours, i.e., the send and receive protocol functions. The tree of terms to controlthe behaviour of the second component consists of an interleaving object in the root of the tree andtwo behaviour objects, one for each monolithic behaviour, in the leaves. Figure 7.14 illustrates thistree.

The descriptions of the tasks required to implement the Send-Receive protocol, in so far as theydiffer from the Basic Event Manager Framework, are the following:

Figure 7.14 Behaviour composition tree for the SR component

SR::eventHandler

_root

:interleaving

:behaviour :behaviour

_listOfTerms

controlscontrols

_behaviour_id _behaviour_id

Handler()

activates

activates

Page 163: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.5 Implementation Example

145

(3) EventHandler specializations

The specified protocol has two components: PduHandler and SR.

(3.1) eventHandler header: SR and PduHandler are concrete classes that specialize theeventHandler class.

(3.1.1) parameters: SR receives a reference to ip1 (specialization of fileIO) and to ip3(internal IP). PduHandler receives a reference to ip2 (specialization of udp) and ip3.

(3.1.2) IP references: references to ip1, ip2 and ip3 must be defined in SR and PduHan-dler. SR also requires a reference to a timer object.

(3.1.3) behaviour context: stores the global state for each behaviour within SR (state-1and state-2).

(3.2) class constructor

(3.2.1) local interaction point: the class timer is instantiated to be used by the sendbehaviour of component SR.

(3.2.2) connections: SR is connected to ip1, ip3 and the timer object. PduHandler is con-nected to ip2 and ip3.

(3.2.4) tree of terms: the tree presented in Figure 7.14 is built for the class SR. ClassPduHandler only requires a behaviour term in the root of the tree.

(3.3) Handler method: TABLE 7.1, illustrates the use of the state table containing the protocolspecific information required to implement the Handler method of PduHandler class.

In TABLE 7.1, buffer is a variable used to store interaction information. cp is used to store thecode of the communication primitive in the PDU delivered by ip2. _state is a variable that

TABLE 7.1 Behaviour of PduHandler component

State EP CP Action Participation

WAITING ip2 udpDI cp=decodePDU(pdu,&buf)_state=RECEIVING

ACCEPT

ip3 Ack pdu=codePDU(AckInd)_state=SENDING

ACCEPT

ip3 Data pdu=codePDU(Data,buffer)_state=SENDING

ACCEPT

RECEIVING ip3 cp _state=WAITING OFFER

SENDING ip2 udpDR release pdurelease buffer_state=WAITING

OFFER

Page 164: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

146

Chapter 7: Advanced Event Manager Framework

contains the behaviour global state. The actions in TABLE 7.1 are directly derived from theprotocol description. They consist of commands to update the behaviour global state, executePDU coding and decoding functions (codePDU and decodePDU), and dealocate data bufferingmemory (release instruction).

(3.4) Class destructor: disconnection and destruction of ip3 in SR and PduHandler.

(3.5) Initialization method: state initialization: _state1 is initialized with value IDLE; receivebehaviour: _state2 is initialized with value NORMAL; and _state is initialized with value WAIT-ING in component PduHandler.

Figure 7.15 shows the object diagram for this implementation. SR, PduHandler, ip1 and ip2 are theprotocol dependent classes and the protocol implementation requires one instance of each to beactive during runtime. fileIO and udp are implementation environment dependent classes and areinstantiated once in this protocol. The protocol also requires two instances of the internal class andone timer. Internal objects are identified by _ipn<side>, where n is a number corresponding to theidentification in the protocol specification and <side> is an identification to differentiate the twoinstances required (left and right).

:sr::eventHandler

:pduHandler::eventHandler

_timer:timer::eventPoint

_ip1:ip1::fileIO::external::eventPoint

_ip3r:internal::eventPoint

_ip3l:internal::eventPoint

partner

connects

connects

_ip2:ip2::udp::external::eventPoint

connects

uses

:entity

Figure 7.15 Send-Receive protocol using Advanced Event Manager Framework.

connects

:eventManager

controls

:interleaving

b1:behaviour

b2:behaviour

controls

controls

controls

triggers

controls triggers

uses

Page 165: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

7.6 Evaluation

147

7.6 Evaluation

When developing this framework we mainly experimented with our prototyping strategy. Thisstrategy consists of extending an existing framework with extra features. In this case, we extendedthe Basic Event Manager Framework.

Behaviour composition has been implemented by extending the existing code. This allowed us toconsider previous implementation requirements fulfilled to some extend, simplifying the develop-ment process. The main concern in this approach is to evaluate whether or not changed code stillsupport the previous features. In this particular case of extending a framework, the prototypingapproach has being successful, since the new features required minimum changes in the existingcode. The characteristics of the Basic Event Manager Framework concerning behaviour imple-mentation, becomes a particular case of the new framework, in which the composition tree con-tains a single behaviour object. The Handler method implements a monolithic behaviour in thesame way as in the Basic Event Manager Framework.

The implementation of dynamic manipulation of components, however, implied in some adapta-tion of the Basic Event Manager Framework code. This shows that the success of the prototypingapproach relies largely on the degree of code extensibility of the core implementation. More efforton applying software engineering techniques to enforce code extensibility may improve the bene-fits of our framework development approach.

The application of the Advanced Event Manager Framework is similar to the application of theBasic Event Manager Framework. Although new constructs are available in the Advanced EventManager Framework, most of the code required for handling these constructs is embedded in theframework and therefore does not affect the efficiency of the implementation process. The frame-work still supports a one-to-one mapping between design concepts and corresponding implemen-tation and, therefore, we can conclude that the templates can be applied efficiently in theimplementation process. The complexity due to dynamic changes in the implementation structureand composition of behaviour are handled mostly at the protocol design level.

Although the templates of this framework are more complex than the templates of the Basic EventManager Framework, the mapping of protocol-specific information onto code using these tem-plates can still be done in a systematic way. This enforces the correctness of the implementation.In our experiments with the Send-Receive protocol, and with the performance tests describedbelow, the errors made were often related to data manipulation procedures, which have beenmainly performed in an ad-hoc manner.

Performance

In order to evaluate the performance of the protocols implemented using this framework, we com-pare a monolithic implementation of a protocol with its corresponding structured implementationusing this framework.

In order to assess the overhead imposed by dynamic creation of components and behaviour com-position, we apply a different structure here for the Receiver entity: the tasks performed whenreceiving a message are implemented as interleaved behaviours within a single component called

Page 166: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

148

Chapter 7: Advanced Event Manager Framework

Perform. This component is created when a message arrives and destroyed after the acknowledgeis sent to the Sender entity. The Receive component sends five requests to perform a task to thePerform component; these can be processed by any of the interleaved behaviours. Each inter-leaved task ends its behaviour after performing once. This guarantees that each task receives achance to execute. Figure 7.16 shows the architecture of the performance evaluation scheme.

The actions regarding the evaluation of structuring mechanisms, applied in the performance eval-uation in chapter 5 and 6, were also taken for this framework. The execution overhead introducedby the framework to support a structured implementation is on average 120% the execution timeof the corresponding monolithic implementation. For example, using 100 as the number of repeti-tions in the execution of this experiment, the total execution time in the monolithic implementa-tion is, on average, 19.6 milliseconds and in the structured implementation is, on average, 43.3milliseconds. This means that the execution overhead in the structured implementation is, onaverage, 2.20 times the execution time of a corresponding monolithic implementation.

senderentity

Receive

task1

task2

task5

...

Synchronize

Receiverentityexec(msg)

Figure 7.16 Performance evaluation scheme

inte

rleav

ing

Perform

Page 167: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

149

Chapter 8

Sliding Window Protocol Implementation

This chapter presents a detailed example of the use of frameworks in the protocol developmentprocess. The example consists of the implementation of a LOTOS specification of the SlidingWindow Protocol, using the Advanced Event Manager Framework and with C++/Unix as the tar-get implementation environment.

The structure of this chapter is: section 8.1 presents the goals and assumptions of this case study;section 8.2 introduces the Sliding Window protocol; section 8.3 presents the protocol specifica-tion in LOTOS; section 8.4 presents some tool-supported refinements of the specification towardsimplementation; section 8.5 presents the protocol implementation using the chosen framework;and section 8.6 presents some conclusions.

8.1 Introduction

The purpose of this chapter is to illustrate the application of our framework-based approach toprotocol implementation on a realistic protocol development. This chapter shows the use of ourframeworks in combination with LOTOS and LOTOS design tools. The main issue to be investi-gated is the mapping of the constructs of this particular formal description technique onto thearchitectural concepts supported by a framework.

The Sliding Window Protocol was chosen as case study because its specification uses a signifi-cant set of behavioural and structural concepts, suitable for exemplifying our implementationapproach. Besides that, this protocol is simple enough to allow a detailed description of its imple-mentation.

This case study uses LOTOS only for the purpose of illustrating the application of our techniquesin the implementation process using a specific formal description language. We do not presentgeneral guidelines for implementing LOTOS specifications in this chapter. Instead, we limit our-selves to presenting some general rules for implementing LOTOS specifications that were appliedin this example.

Page 168: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

150

Chapter 8: Sliding Window Protocol Implementation

8.2 Protocol Description

The service supported by the Sliding Window Protocol provides flow control of messagesbetween two communicating systems, a transmitter and a receiver. Flow control ensures that mes-sages are not lost because the receiver entity can not treat the data at the sending speed, causingthe overflow of intermediary buffers. The protocol also provides reordering of messages anddetection and retransmission of lost messages. The technique applied by this protocol to supportsuch functionalities is commonly known as Sliding Window [22] [29]. Figure 8.1 shows the archi-tecture of our protocol example.

Figure 8.1 shows a transmitter protocol entity and a receiver protocol entity communicatingthrough a lower level service (LLS). We assume an LLS where service data units (SDUs) can belost or delivered in a different order than that in which they were sent. We suppose that the LLSdelivers SDUs without corruption. The service primitives related to the LLS are MDataReq andMDataInd, to send and deliver data, respectively.

We consider the simplex case of this protocol, which consists of a transmitter entity and a receiverentity, forming an asymmetric system. A sending service user executes a DataReq to send data anda receiving service user executes a DataInd to receive data. The transmitter protocol entity con-tains a finite buffer where user data sent by the service user through interaction point ut is storeduntil it can be sent to the receiver protocol entity. The finite buffer in the transmitter protocolentity implements a backpressure mechanism in case the buffer is full.

The sliding window technique avoids that the receiver gets overloaded with data, by providing acredit for transmission that allows a certain number of PDUs to be in transit at the same time. Thiscredit is called transmitter window size (wst). In this approach, the receiving of PDUs must beacknowledged and the transmitter stops sending PDUs when the number of outstanding PDUsreaches wst. Outstanding PDUs are the PDUs sent and not yet acknowledged or not acknowledgedin the proper order.

The Sliding Window Protocol deals with reordering of PDUs by assigning to each PDU a sequen-tial numerical identifier. To handle the limitations on the number of identifiers which can be rep-resented by computational systems, these identifiers are reused. An initial identifier and amaximum identifier are predefined and after the maximum identifier has been used, the protocolassigns the initial identifier to the next PDU and cycles through from initial to maximum again.

The PDUs of the Sliding Window Protocol are:

• Data: used to send user data. This PDU contains the PDU identifier and the user data.

Figure 8.1 Architecture of the Sliding Window Protocol

Transmitter Receiver

LLS

ut ur

mt mr

PE PE

Transmitterservice user

Receiver service user

Page 169: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.3 Protocol Specification

151

• Ack: used to acknowledge user data. Contains the identification of the PDU being acknowl-edged.

PDUs in the buffer of the transmitter entity are constantly transmitted while the number of PDUsin transit is less than or equal to the window size. After they are transmitted, PDUs are stored forretransmission in a retransmission queue, waiting for an acknowledgement from the receivingentity. The oldest PDU waiting for acknowledgement is retransmitted after waiting for a period oftime called retransmission timeout. Acknowledged PDUs are deleted from the retransmissionqueue.

The receiver protocol entity monitors the order of the received PDUs by checking their identifier.User data of PDUs received in the correct order are immediately delivered to the service user atthe ur service access point and are acknowledged. PDUs containing identifiers out of the sequen-tial order are either stored or discarded, depending on the PDU identifier. The receiver entity storeseach out of order PDU in a queue, providing its identifier is within a certain maximum number ofPDUs in transit that are not duplicated PDUs. The maximum number of PDUs in transit is calledreceiver window size (wsr). PDUs are considered duplicated if they can still be in the sender win-dow. This can be calculated based on the identifier of the received PDU, the identifier of the lastacknowledged PDU and wsr. All duplicated PDUs are acknowledged. The acknowledgementapproach adopted in this protocol is called explicit acknowledge [29], because each PDU isacknowledged separately.

Figure 8.2 shows how the window sizes determine the PDUs that can be sent by the transmitter orstored by the receiver. In this windowing scheme, lat identifies the last PDU at the transmitter sidefor which an acknowledgement has been received. lat identifies the last PDU at the receiver sidefor which an acknowledgement has been sent. sid is the identifier of the next PDU that will be sentand maxId is the maximum identifier of the protocol. Considering totalIds equal to (maxId+1), cal-culations involving identifiers in this protocol are always modulo totalIds.

8.3 Protocol Specification

The LOTOS specification of the Sliding Window protocol is presented in this section using G-LOTOS [9][14], which is a graphical notation to represent LOTOS processes. Here we focus onthe protocol behaviour and structure rather than on the data types. The complete textual specifica-tion of the protocol is presented in Appendix C. Figure 8.2 shows the high-level specification of

range of possible Ids

max

Id

wst

lat sid

Transmitter

range of possible Ids

max

Idwsr

lar

Receiver

Figure 8.2 Sliding window scheme

Page 170: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

152

Chapter 8: Sliding Window Protocol Implementation

the Sliding Window Protocol, defining the global constraints applied to the value of window size(ws), and the structure of the protocol. For our convenience we make both wst and wsr equal to ws.

The processes TPE and RPE specify the behaviour of the transmitter and receiver protocol entityrespectively. This behaviour is structured in composition with the constraints applied to serviceprimitives executed at the SAPs represented by the gates ut and ur (RSConstraints). The transmitterand the receiver protocol entities are specified in the Transmit and Receive processes, respectively.

Figure 8.4 shows the specification of the Transmit process. This process contains four sub-proc-esses (AcceptData, SendData, RecFromUS and Retransmit) and an internal event in a choice compo-sition that represents a retransmission timeout. The AcceptData process receives user data throughut and stores it in the data queue. SendData transmits PDUs from the data queue while the retrans-mission queue is not full (NotFull operation), RecFromUS receives acknowledgement PDUs, andthe Retransmit process retransmit PDUs on timeout. The Transmit process receives as parameter aqueue of PDUs (tq), a queue of sent PDUs (rtq), the identification of the next PDU that will besent (sid), the identification of the oldest sent PDU that has received an acknowledgement (lu),and an indication that timeout has occurred. The behaviour of Transmit is recursive. The evalua-tion of the NotFull operation considers the range of identifiers involved in the retransmission proc-ess and is evaluated by applying the following equation:

NotFull(sid,lu,ws)= (((sid+totalIds) - lu) % totalIds) <= ws [22] (EQ 1)

Figure 8.5 shows the specification of the Receive process. This process specifies two sub-proc-esses AcceptData and DeliverData in a choice composition. The process AcceptData receives PDUssent by the Transmit entity and stores and acknowledges the PDUs when appropriate. The processDeliverData takes PDUs from the queue and delivers the user data of the PDUs to the service userthrough service access point ur. The behaviour of the Receive process is recursive. The Receiveprocess has as parameters the queue of PDUs to be delivered, the identification of the next PDUto be received and the window size.

mrmt

Medium

ws

mrur

RPE

ws

mtut

TPE

= true( ), ( ), ( ), ws( )( )0SuccSucc*TotalIdsge( ), 0wsgtand

: Natws

urutmrmt

Protocol

Figure 8.3 Sliding Window Protocol hight-level specification

Page 171: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.3 Protocol Specification

153

The detailed specification of the AcceptData process is presented in Figure 8.6. In this process aUSDataInd LLS primitive is performed and the PDU contained in this primitive is processed. Thepossibilities are: a) the PDU is in the correct order, b) the PDU is a duplication of some PDUreceived before (Received operation), c) the PDU is in the range of the receiving window (InWin-dow operation) but not in the correct order and d) otherwise. The definition of an ‘otherwise’ alter-

, , , , , falsewslusidrtqtq

mtut

Transmitter

( )rtqTop

mt

Retransmit

= trueto

, , , , , truewslusidrtqtq

mtut

Transmitter

= true( ), rtqPDUIsTopOf

: PDUPDU

, , , , , towsnewlusidnewrtqtq

mtut

Transmitter, : PDUIdnewlu: PDUQueuenewrtq

, , lusidrtq

mt

RecFromUS

, , , , , towslu( )sidNextIdnewrtqnewtq

mtut

Transmitter, : PDUQueuenewrtq: DataQueuenewtq

, , , , wssidlurtqtq

mt

SendData

, , , , , towslusidrtqnewtq

mtut

Transmitter: DataQueuenewtq

tq

ut

AcceptData

, , , , : Boolto: Natws: PDUIdlusid: PDUQueuertq: DataQueuetq

mtut

Transmitter

Figure 8.4 Transmit specification

Page 172: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

154

Chapter 8: Sliding Window Protocol Implementation

native is necessary in this case to avoid that the Transmit process deadlocks. In Figure 8.6 thisbehaviour alternative is represented as <BEH> for the sake of conciseness.

The detailed specification of the DeliverData process is presented in Figure 8.7.

In the DeliverData process, the operation PDUtoDeliver evaluates if the PDU at the top of the queueis the next PDU to be delivered. If that is true, the user data of this PDU is delivered to the service

, , wsnewlanewpq

mrur

Receiver, : PDUIdnewla: PDUQueuenewpq

, lapq

mrur

DeliverData

, , wsnewlanewpq

mrur

Receiver, : PDUIdnewla: PDUQueuenewpq

, , wslapq

mrur

AcceptData

, , : Natws: PDUIdla: PDUQueuepq

mrur

Receiver

Figure 8.5 Receiver specification

exit ( ), ( )laNextId( ), pqPDURemove

! ( )( )( )PDUPDUIdAckPDUUS_DaReqmr

! ( )( )PDUPDUDataRS_DaIndur

= ( )pqTop: PDUPDU

= true( ), lapqPDUtoDeliver

PDUIdPDUQueue

, : PDUIdla: PDUQueuepq

mrur

DeliverData

Figure 8.7 DeliverData Specification

Page 173: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.3 Protocol Specification

155

user, the PDU is acknowledged and removed from the queue and la is updated to the next allowedidentification.

The Received and InWindow operations can be evaluated using the following equations:

Bex

exit ( ), la( ), pqPDUEnqueue

= true( ), , , TotalIdsws( )laNat( )( )PDUPDUIdNatInWindow

exit ( ), lapq

! ( )( )( )PDUPDUIdAckPDUUS_DaReqmr

= true( ), , , TotalIdsws( )laNat( )( )PDUPDUIdNatReceived

exit ( ), ( )laNextIdpq

! ( )( )( )PDUPDUIdAckPDUUS_DaReqmr

! ( )( )PDUPDUDataRS_DaIndur

= true( ), ( )( )laNextIdNat( )( )PDUPDUIdNateq

= ( )mspPDU: PDUPDU

= true( )mspIsUSDaInd

? : USPmspmr

PDUIdPDUQueue

, , : Natws: PDUIdla: PDUQueuepq

mrur

AcceptData

Figure 8.6 AcceptData specification

Page 174: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

156

Chapter 8: Sliding Window Protocol Implementation

Received(p,la,ws) = 1 < (((la+totalIds) - p) % totalIds) < ws [22] (EQ 2)

InWindow(p,la,ws) = 1 < (((p+totalIds) - la) % p) <= ws [22] (EQ 3)

where p denotes the identifier of the PDU being treated.

8.4 Refinement for Implementation

The component design concept supported by our frameworks does not map one-to-one onto thesemantics of LOTOS processes. Some implementation interpretations must be made regardingwhether a LOTOS process should be mapped onto a component or should be considered only as asyntactic construct describing behaviour composition within a component. In this respect, wehave chosen the following mappings:

• the TRE process is mapped onto a single component that performs the combined behaviourof RSConstraints and Transmit processes as a single behaviour;

• the RPE is mapped onto a single component that performs the composed behaviour ofRSConstrains and Receive processes. Such a component performs a choice composition of twobehaviours that correspond to the behaviour of the processes AcceptData and DeliverData.

In the implementation of the behaviour of LOTOS processes when using our approach, thesemantics of the LOTOS specification has to be translated to a state machine representation. Sucha translation can be performed automatically by applying LOTOS transformation tools. In thesequel we describe a tool-supported process to translate LOTOS specifications to an ExtendedFinite State Machine (EFSM). We perform these transformations using some tools available inthe LOTOSphere Integrated Tool Environment (LITE)[46].

8.4.1 Tool Supported refinement of LOTOS specification

We have applied the following steps to obtain an EFSM representation of a LOTOS behaviour:

a) Using the Smile tool [9], which is a symbolic simulator for LOTOS, we produced an intermedi-ate representation of an EFSM corresponding to the behaviour of a selected process within theprotocol specification. Smile receives as an input a .cr (common representation internal notation)file generated by the lcr static semantics analyser, which is executed automatically by Smile.

a.1) The menu used to start the Smile simulator in the LITE environment is shown on theleft side of Figure 8.8;

a.2) Using Smile, we selected the process for which we wanted to produce a correspondingEFSM. Such a selection is shown on the right side of Figure 8.8;

a.3) We executed the complete state machine of the selected process. The left side of Fig-ure 8.9 shows the command for this operation in the Smile window;

a.4) We saved tree of possible paths in such an execution as illustrated on the right side ofFigure 8.9.

Page 175: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.4 Refinement for Implementation

157

b) Executing the FC2 tool in the menu Behaviour Analysis of LITE the EFSM representation pro-duced by Smile is translated to a FC2 automaton format;

c) We loaded the output of FC2 into the Autograph tool available in the Miscellaneous menu ofLITE. Using the explore functionality of Autograph reached from the Placing menu, we obtainedthe complete EFSM of the Transmit process. Figure 8.10 shows the resulting graph.

The EFSM displayed by the Autograph tool can be directly used to fill in the state tables of theframework usage procedure.

Figure 8.8 Lite and Smile simulator

Figure 8.9 Operations using Smile

Page 176: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

158

Chapter 8: Sliding Window Protocol Implementation

This approach to implement LOTOS behaviour, however, is not applicable when the LOTOSspecification defines a behaviour with an infinite number of states. Behaviour instantiation orrecursion in combination with interleaving or parallel composition induces an infinite statemachine, such as, for example, in:

Q = (a;Q) ||| (b; STOP)

In this example, each time an a action is executed, the number of b actions that are enabled andcan be executed in future increases by one, increasing the number of states infinitely. This kind ofconstruct should be avoided during specification or removed by applying design transformations[8] in order to make it possible to generate a finite state machine from the specification.

8.4.2 Saving the Behaviour Structure

The approach described above flattens the hierarchy of the LOTOS specification into a mono-lithic behaviour. Since one of the characteristics of our protocol implementation approach is tosupport design constructs applied to structure the specification, we should define ways to avoidflattening.

One possible approach to preserve the specification structure is to produce separated EFSMs foreach process in the specification hierarchy whose structure we intend to preserve. If such pro-cesses are at the bottom level of the hierarchy of processes, it is enough to select the process (stepa.2) and follow the described procedure. If the process to be implemented instantiates other pro-

Figure 8.10 Transmitter EFSM

Page 177: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.5 Implementation using the Advanced Event Manager

159

cesses, the behaviour of the process must be mapped onto code using the behaviour compositionconstructs supported by the Advanced Event Manager Framework, e.g., sequence, choice andinterleaving.

We illustrate the preservation of specification structure in the implementation of the RPE protocolentity. The Receive process instantiates the processes AcceptData and DeliverData. In order to pre-serve this structure, the mapping of LOTOS processes to EFSMs is applied to the embedded pro-cesses. The implementation of the Receive process consists of the composition of two EFSMscorresponding to the embedded processes in a choice relation, which is directly supported by theframework. Figure 8.11 shows the EFSM of AcceptData and DeliverData processes.

In order to implement the loop specified through the recursive instantiation of the Receive processin the RPE, we use the implementation constructs of the Advanced Event Manager Frameworkshown in Figure 8.12.

8.5 Implementation using the Advanced Event Manager Framework

The framework usage guidelines have been followed to implement the two protocol entities of theSliding Window protocol, i.e., TPE and RPE. Therefore, the steps to be performed in the imple-mentation of each of the protocol entities are:

• constants definition;

• specialization of external class;

• specialization of eventHandler class;

IDLE SENDING

A: US_DaInd(Data(s,msg))B: US_DaReq(Ack(s))

A

A*

A**

* Duplicated PDU** PDU in rec. window

DaInd(msg)

ACKN.1

B B

AcceptData

WAITING SENDING

DaInd(msg)

B

DeliverData

Figure 8.11 Functions of RPE Protocol Entity

ACKN.2

:sequence_loop=true;

:choice

AcceptData:behaviour DeliverData:behaviour

composes

composes composes

Figure 8.12 Receiver process implementation

Page 178: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

160

Chapter 8: Sliding Window Protocol Implementation

• definition of initialization class.

In the code templates shown to illustrate these steps, the fixed part of the code is highlightedusing bold character format. The remaining code implements protocol-specific requirements.

8.5.1 TPE Implementation

In accordance with the implementation decisions made in the previous section, the TPE is imple-mented by a single framework component communicating with its environment through twoexternal interaction points. The steps followed in this implementation are described in the sequel.Figure 8.13 presents the object diagram for the implementation of the TPE.

Constants Definition

The identification of the constants used in the behaviour of the TPE (step 1) is straightforward.The constants are the maximum number of PDUs identification (TotalIds) and the maximum sizeof the data buffer (BufferSize). The window size is a protocol parameter and therefore we have notdefined it as a constant.

Other constants in this implementation are the possible behaviour states. Such states can bederived from Figure 8.10, which shows the EFSM of the behaviour to be implemented. AlthoughFigure 8.10 displays several states, each state that has an (i) exit functionality as triggering eventto its transition can be excluded from the implementation, since behaviour a; i; B is weak bisimu-lation congruent to behaviour a; B [22]. Weak bisimulation congruence is a proper equivalencerelation to express observation equivalence and can be used as implementation relation in thiscase.

The resulting state machine, therefore, contains a single state and several alternative events trig-gering recursive transitions. We call this state Waiting.

The protocol implementation also requires the definition of constants to represent the possiblecommunication primitives within the protocol behaviour. The primitives used in this protocol are(see RSP and USP data type definitions in appendix C) RS_DaInd, RS_DaReq, US_DaInd, andUS_DaReq.

_ut:ut::fileIO::external

_mt:mt::udp::external

:transmitter::eventHandler :behaviourem:eventManager

triggers

triggers

connects

connectscontrols

Figure 8.13 TPE Object Diagram

Page 179: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.5 Implementation using the Advanced Event Manager

161

Specialization of external Class

The external interaction points (step 2) used by the TPE are ut and mt for interacting with the serv-ice user and the LLS, respectively. The detailed characteristics of these interaction points is animplementation decision, and these characteristics are captured by the environment-specific spe-cialisation of the external class (step 2.1). We assume in this implementation that the service userinteracts with the service provided by this protocol through the system’s standard interface, i.e.,the keyboard and the console. We also assume that the LLS is provided by UDP, which compliesto the medium specification.

Specialisations of the external class to build interaction points based on such interfaces have beendeveloped and applied in chapter 5. We reuse these specializations here, which are availablethrough the classes fileIO and udp.

The final implementation of the required external interaction points consists of the protocol-spe-cific specialisation of the fileIO and udp classes (step 2.2) implementing the interaction points utand mt, respectively. Filling in the template code for these specialization results in the code in Fig-ure 8.14. The constraints captured in this code are defined in the RSConstrains and Medium proc-esses of the protocol specification.

Specialization of eventHandler Class

The TPE consists of one component performing a single behaviour. We call such a component aTransmitter. The filled template for the Transmitter header (step 3.1) is shown in Figure 8.15. TheTransmitter class receives as parameters the window size and the references to the connected inter-action points. A single behaviour requires only one behaviour state (_state1). The Transmitterrequires the manipulation of a timer (_timer), declared in the class header. The local attributesrequired by the Transmitter are window size (ws), next PDU identification (sid), last acknowledgedPDU (lu), a queue of received PDUs (tq), a queue for storing PDUs that may need retransmission(rtq), the references to the connected interaction points (_ut and _mt) and a flag to indicate timeout(_timeout).

class ut: public fileIO { public: ut(int fd, eventsManager* em): fileIO(fd,em){} virtual int CallEH(); }; int ut::CallEH() { if (_cp==RS_DaReq) return (_eh->Interact(this,_cp,ACCEPT)); else { printf("Wrong communication primitive\n"); delete _msg; _cp=0; return 1; }; }

class mt: public udp { public: mt(int lp, int rp, char* rh, eventsManager* em): udp(lp, rp, rh,em){} virtual int CallEH(); }; int mt::CallEH() { if (_cp==US_DaInd) return (_eh->Interact(this,_cp,ACCEPT)); else { printf("Wrong communication primitive\n"); delete _msg; _cp=0; return 1; }; }

Figure 8.14 Protocol-specific specializations

Page 180: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

162

Chapter 8: Sliding Window Protocol Implementation

The constructor of the Transmitter class (step 3.2) stores the received parameters (ws, ut, mt),instantiates the timer, connects the eventPoints (_timer, _ut, _mt), initializes _state1, lu and _timeoutand builds the behaviour composition tree. This tree consists of a single behaviour term in its root.The right side of Figure 8.15 shows the code for the Transmitter constructor.

For the implementation of the Handler method (step 3.3) we build the state table containing thedescriptions of the Transmitter’s units of behaviour according to the results obtained in section8.4.1. Table 8.1 shows the resulting state table.

Figure 8.17 shows the global structure of the Handler method for the Transmitter class. The com-plete filled templates implementing the units of behaviour described above are shown in Appen-dix D. The implementation for the unit of behaviour UB6, indicated in Table 8.1, is illustrated inFigure 8.16. The internal event used in process Transmitter defines a timeout event and therefore it

// Specialization of required eventHandlers (3) // EventHandler Header (3.1) class Transmitter : public eventHandler { public: Transmitter(int, ut*,mt*, eventsManager*); ~Transmitter(); int Handler(int,eventPoint*,int,int); void Destroy() {delete this;} private: char *msg; int state1; ut *_ut; mt *_mt; pdu *_pdu, *_pduWaitingRet; timer *_timer; int ws; // window size int sid; // next pdu identifier int lu; // last acknowledgment list <pdu> rtq; // pdu queue list <char> tq; // data queue int _timeout; };

Figure 8.15 Transmitter class header

// EventHandler construct (3.2) Transmitter::Transmitter(int w,ut *ip1, mt *ip2, eventsManager* em):eventHandler(em) { ws=w; _ut=ip1; _mt=ip2; _timer=new timer(_em); _timer->Connect(this); _ut->Connect(this); _mt->Connect(this); // behaviour context variables msg=new char[80]; state1=WAITING; sid=0; lu=PrevId(sid,TotalIds); _timeout=0; // creation of behaviour composition tree _root=new simpleExpression(NULL,1,this); }

Table 8.1 Transmitter state table

State EP CP Action Condition Type UB1 WAITING _ut RS_DaReq Enqueue(RSPData(usp), tq) BufferSize gt Length(tq) ACCEPT

UB2 WAITING _mt US_DaInd RemovePDU(pdu,rtq); [not(IsEmpty(Remove(pdu, rtq)))]-> ( lu=PrevId(sid,TotalIds); rtq=Remove(pdu, rtq) ) [IsEmpty(Remove(pdu, rtq))]-> ( lu=PrevId(PDUId(Top(rtq))), rtq=Remove(pdu,rtq) )

pdu:PDU=DataPDU(sid,Top(tq)) pdu IsAckFor rtq

ACCEPT

UB3 WAITING _mt US_DaInd

not(pdu IsAckFor rtq) ACCEPT

UB4 WAITING i to=TRUE choice pdu:PDU [ ] [pdu IsTopOf rtq]

TIMEOUT

UB5 WAITING _mt US_DaReq

to=FALSE to eq true OFFER

UB6 WAITING _mt US_DaReq

pdu:PDU=DataPDU(sid, Top(tq)) in rtq=Enqueue (pdu,rtq) sid=NextId(sid,TotalIds); tq=Dequeue(tq);

NotFull(sid,lu,ws,TotalIds) and (Length(rtq) gt 0)

OFFER

Page 181: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.5 Implementation using the Advanced Event Manager

163

is implemented using the unit of behaviour template for timeouts. The semantics of the LOTOSchoice construct, applied in the unit of behaviour UB4, has been implemented by storing the PDUat the top of the retransmission queue, in order to evaluate if the timer guarding condition stillholds (_pduWaitingRet).

Definition of the Initialization Class

Figure 8.18 shows the filled template for the initialization class of the TPE implementation (step4). This implementation checks the value of window size and instantiates the required interactionpoints and the required component.

8.5.2 RPE Implementation

The implementation of this protocol entity consists of a single framework component whosebehaviour consists of two monolithic behaviours composed by a choice relation. This entity com-municates with its environment through two external interaction points. The steps required in thisimplementation are described in the sequel. Figure 8.19 shows the object diagram for the resultingimplementation of the RPE.

// unit of behaviour template (offer) (6) if (act==OFFER) { // guarding condition if (NotFull(sid,lu,ws,TotalIds) && tq.Length()) { // execute interaction offer if(_mt->SendData(US_DaReq, CodePDU(_pdu=PDU(sid,TopOfQueue(&tq))))) { // action printf("Sending PDU\n"); Enqueue (_pdu,&rtq); sid=NextId(sid,TotalIds); Dequeue(&tq); return SUCCESS; }; }; };

Figure 8.16 Unit of behaviour’s implementation

int Transmitter::Handler(int id, eventPoint* ep, int cp, int act) { switch (id) { //----- Timer template ----- if (_timer->Active()) // guarding condition if (!(pduWaitingRet==TopOfQueue(&rtq))) _timer->Idle(); //------------------------------------- case 1: // ACCEPT DATA switch (state1) { case WAITING: /* ub1, ub2, ub3, ub4, ub5, ub6 */ break; default :; }; // switch state default:; } // switch id return FAIL; }

Figure 8.17 Handler method code global structure

Page 182: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

164

Chapter 8: Sliding Window Protocol Implementation

Constants Definition

The constants used in the behaviour of the RPE (step 1) are maximum number of PDU identifiers(TotalIds), the behaviour states IDLE, ACKN1, ACKN2, SENDING, WAITING (see Figure 8.11)and the communication primitives are RS_DaInd, US_DaInd, US_DaReq. Behaviour states andcommunication primitives are enumerated in the implementation, in this specific order.

Specialization of external Class

The external interaction points (step 2) used by the RPE are ur and mr, for interacting with theservice user and the LLS, respectively. Similarly to the implementation of TPE, we also use herethe fileIO and udp specialization of the external class to implement the external interaction points(step 2.1).

The protocol-specific implementation of the interaction points (step 2.2) consists of specializingfileIO and udp to capture the constraints defined in the RSConstraint and Medium processes for ur

// Definition of initialization class (4) // Class Header (4.1) class ENTITY { public: ENTITY (int); // ws ~ENTITY (){} };

// Initialization Class // Class Constructor (4.2) ENTITY :: ENTITY (int ws) { // Event Manager instantiation eventsManager* em = new eventsManager; // treat possible parameters if (ws>(TotalIds/2)) { cout << "Error: WS bigger than TotalIds/2: " << TotalIds/2 << "\n" << flush; exit(0); }; // instantiate required interaction points ut *_ut = new ut(0,em); mt *_mt = new mt(1038, 1039, "demeter",em); // set internal partners // there are no internal interaction points // instantiate components new Transmitter(ws,_ut,_mt,em); // start Event Manager monitoring cycle em->WaitEvent(); }

Figure 8.18 TPE initialization class

Figure 8.19 RPE Object Diagram

:Receiver::eventHandler

_ut:ut::fileIO

:sequence

:choice

AcceptData:behaviour

DeliverData:behaviour

_mr:mr::udp

:eventManagercomposes

com

pose

s

activates

triggers

triggers

activates

connects

connects

Page 183: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.5 Implementation using the Advanced Event Manager

165

and mr, respectively. Figure 8.20 shows the resulting code of the filled template for such speciali-zations.

Specialization of eventHandler Class

The structure of the RPE consists of a Receiver component that performs a loop enclosing thechoice composition of the AcceptData and DeliverData behaviours. The filled template for theReceiver header (step 3.1) is shown on the left side of Figure 8.21.

The parameters of the Receiver class are the window size and the references to the connectedinteraction points. Each of the two behaviours in the Receiver component requires a state variable(_state1 and _state2). The remaining protocol-specific attributes required by the Receiver compo-nent are the window size (ws), the last acknowledged PDU identification (la), the references to theconnected interaction points (_ur and _mr) and the queue for the received PDUs (pq).

The right side of Figure 8.21 shows the code for the constructor of the Receiver component (step3.2). Such a constructor stores the received parameters (ws, ur, mr), initializes la, state1 and state2,connects _us and _mr, and builds the tree of terms to control the behaviour composition (see Fig-

Figure 8.20 ur and mr implementations

class ur: public fileIO { public: ur(int fd, eventsManager* em): fileIO(fd,em){} virtual int CallEH(); }; int ur::CallEH() { if (_cp==RS_DaReq) return (_eh->Interact(this,_cp,ACCEPT)); else { printf("Wrong communication primitive\n"); delete _msg; _cp=0; return 1; }; }

class mr: public udp { public: mr(int lp, int rp, char* rh, eventsManager* em): udp(lp, rp, rh,em){} virtual int CallEH(); }; int mr::CallEH() { if (_cp==US_DaInd) return (_eh->Interact(this,_cp,ACCEPT)); else { printf("Wrong communication primitive\n"); delete _msg; _cp=0; return 1; }; }

Figure 8.21 Receiver Class

// Specialization of required eventHandlers (3) // EventHandler Header (3.1) class Receiver : public eventHandler { public: Receiver(int,ur*,mr*, eventsManager*); ~Receiver(); int Handler(int,eventPoint*,int,int); void Destroy() {delete this;} private: char *msg; int state1, state2; ur *_ur; mr *_mr; pdu *_pdu1, *_pdu2; int ws; // window size int la; // last acknowledged PDU list <pdu> pq;// pdu queue };

// EventHandler construct (3.2) Receiver::Receiver(int win, ur *ip1, mr *ip2, eventsManager* em):eventHandler(em) { msg=new char[80]; ws=win; _ur=ip1; _mr=ip2; a=PrevId(0,TotalIds); _ur->Connect(this); _mr->Connect(this); state1=IDLE; state2=WAITING; term *aux; _root=new sequence(NULL,TRUE,this); _root->AddTerm(aux=new choice(_root,this)); aux->AddTerm(new simpleExpression(aux,1,this)); aux->AddTerm(new simpleExpression(aux,2,this)); }

Page 184: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

166

Chapter 8: Sliding Window Protocol Implementation

ure 8.12). The implementation of the Handler method (step 3.3) requires one state table for each ofthe two behaviours. Such a table is mainly derived from the state machines presented in Figure8.11. The state table for the AcceptData and DeliverData behaviours are presented in Table 8.2 andTable 8.3, respectively.

Figure 8.22 shows the global structure of the Handler method for the Receiver class. The filledtemplates implementing the units of behaviour described in the state tables of Table 8.2 and Table8.3 are presented in Appendix D.

Table 8.2 AcceptData state table

State EP CP Action Condition Type UB1 IDLE mr US_DaInd pdu : PDU = PDU(msp)

state=SENDING Nat(PDUId(pdu)) eq Nat(NextId(la))

ACCEPT

UB2 IDLE mr US_DaInd pdu : PDU = PDU(msp) state=ACK2

Received(Nat(PDUId(pdu)), Nat(la), ws, TotalIds)

ACCEPT

UB3 IDLE mr US_DaInd Enqueue(pdu, pq) exit

InWindow ( Nat(PDUId(pdu)), Nat(la), ws, TotalIds)

ACCEPT

UB4 IDLE mr US_DaInd exit (* otherwise*) ACCEPT

UB5 SENDING ur RS_DaInd state=ACK1 OFFER

UB6 ACK1 mr US_DaInd la=NextId(la) exit

OFFER

UB7 ACK2 mr US_DaInd exit OFFER

Table 8.3 DeliverData state table

State EP CP Action Condition Type UB8 WAITING ur RS_DaInd pdu : PDU = Top(pq)

state=SENDING PDUtoDeliver(pq, la) OFFER

UB9 SENDING mr US_DaInd Remove(pdu, pq) NextId(la) exit

OFFER

Figure 8.22 Handler method global structure

// Definition of Handler method (3.4) int Receiver::Handler(int id, eventPoint* ep, int cp, int act) { switch (id) { case 1: // AcceptData switch (state1) { case IDLE: <ub1 ub2 ub3 ub4>break; case SENDING: <ub5> break; case ACK1:<ub6> break; case ACK2: <ub7> break; defalt; } break case 2: // DeliverData switch (state2) { case WAITING: <ub8> break; case SENDING: <ub9> break; default:; } break; default:; } }

Page 185: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.5 Implementation using the Advanced Event Manager

167

Figure 8.23 illustrates the code for the implementation of the unit of behaviour UB1 defined inTable 8.2. In this implementation, the interaction point related to this unit of behaviour is checkedtogether with the related communication primitive. The DecodePDU function prepares the infor-mation to be evaluated in the guarding condition. The guarding condition is evaluated and if itholds the related action is performed. The methods PDUId and NextId implement the operationsspecified with corresponding names in the data type part of the protocol specification.

Definition of the Initialization Class

Figure 8.24 shows the filled template for the initialization class of the RPE implementation (step4). This implementation checks the value of window size, and instantiates the required interactionpoints and the required component.

// unit of behaviour template (accept) (1) if (act==OFFER) // indicate enabled condition _mr->InterInd(); else { if ((ep==_mr)&&(cp==US_DaInd)) { // get information _mr->GetData(&msg); _pdu1 = DecodePDU(msg); // expected Data-PDU // guarding condition if (PDUId(_pdu1)==NextId(a,TotalIds)){ printf("Receiving PDU\n"); state1=SENDING; return SUCCESS; } }; };

Figure 8.23 Unit of behaviour’s implementation

Figure 8.24 RPE initialization class

// Initialization Class // Class Constructor (4.2) ENTITY :: ENTITY (int ws) { // Event Manager instantiation eventsManager* em = new eventsManager; // treat possible parameters if (!((ws>0)&&((TotalIds*2)>=ws))) { printf("Invalid window size\n"); exit(0); }; // instantiate required interaction points ur *_ur = new ur(0,em); mr *_mr = new mr(1039, 1038, "demeter",em); // set internal partners // there are no internal interaction points // instantiate components new Receiver(ws,_ur,_mr,em); // start Event Manager monitoring cycle em->WaitEvent(); }

// Definition of initialization class (4) // Class Header (4.1) class ENTITY { public: ENTITY (int); // ws ~ENTITY (){} };

Page 186: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

168

Chapter 8: Sliding Window Protocol Implementation

8.6 Conclusions

Three concerns can be evaluated based on this case study: 1) the extent to which the design modelapplied in this case study is supported by the framework; 2) the level of systematization of theimplementation process; 3) the effort necessary to adjust the chosen framework to fully supportthe chosen design model.

Support to the Design Model

Regarding the support to the design model by the framework, two aspects can be considered: sup-port to structural concepts and support to behavioural concepts.

Structural concepts can be supported to different degrees without changing the specified behav-iour. The following aspects could be preserved by implementations:

• instances of design concepts;

• scope rules determined by the design model (e.g., a behaviour is defined in the scope of acomponent);

• rules for creating instances of design concepts;

• relationship between instances of design concepts (e.g., behaviour hierarchies).

The framework supports LOTOS characteristics in respect to the decomposition of the specifica-tion into parts, i.e., the LOTOS processes. The implementation of a process has scope and instan-tiation rules comparable to the scope and instantiation rules of the LOTOS process itself. EachLOTOS process is implemented as a behaviour that executes independently from other behav-iours in an interleaved way. The notion of hierarchy between the LOTOS processes is supportedby the use of behaviour composition relations. Composed behaviours in the Advanced EventManager Framework, however, share the same behaviour context information.

Another structural concept of LOTOS is the gate concept. The Advanced Event Manager Frame-work provides an implementation construct to support two-party gates. The multi-party gates,required in this case study to apply constraints to the service access points, are not directly sup-ported by the framework. In general these constraints can be distributed over the remainingbehaviours and can be found back in code that restricts interactions in the protocol implementa-tion.

From this case study we also learned that we have to consider carefully the mapping of designconstructs onto implementation code. For example, in LOTOS, repetitive behaviour can only berepresented using recursive instantiation, but we should not implement repetitive behaviour byrecursively instantiating constructs due to efficiency. Another typical example is the LOTOSchoice that may be impossible to implement. These special mappings can be catalogued and madeavailable for general use.

After we have provided reasonable interpretations for the behavioural constructions involving theobservations given above, the behavioural concepts of this case study have been fully supportedby the framework. These concepts are independent and interleaved behaviours, atomic unit of

Page 187: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

8.6 Conclusions

169

behaviour, synchronous value-passing two-party interaction, timed event, guarding condition,monolithic behaviour and structured behaviour (n-ary deterministic choice, n-ary loop sequenceand n-ary deterministic interleaving with synchronous termination).

Systematization of the Implementation Process

Regarding how systematic the implementation process is, we have observed that most of the map-ping process of structural and behavioural concepts onto framework implementation constructshas been done according to systematic rules. Some required adjustments could be accomplishedin this case study using tools, such as, e.g., the Smile compiler. One aspect of the mapping ofLOTOS constructs onto implementation constructs that still requires a systematic procedure is thesharing of behaviour context information between composed concepts. This case study was notcomplex enough in this respect and therefore an ad-hoc mapping procedure sufficed.

Possible Adjustments to the Framework

The cost of improving the framework to fully support the design concepts of the design modelunderlying LOTOS depends on whether or not the framework is in line with some key concepts inthis design model. In this case study, the chosen framework supports synchronous interactionsand interleaved behaviours. Therefore, we should be able to incorporate into the framework somemissing concepts, such as, e.g., multi-party interactions. Since synchronous interactions arealready supported we expect that the support to multi-way interactions can be done in a prototypethat makes large reuse of the implementation code of the current framework.

The development of a framework that fully supports LOTOS is only a matter of assuming a newstrategic requirement compared to the ones we had when developing the Advanced Event Man-ager Framework. Supporting LOTOS would possible imply in another trade-off in software qual-ity characteristics of the framework, possibly resulting in more complex implementation code andless efficient protocol implementations than in the case of the Advanced Event Manager Frame-work.

Page 188: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

170

Chapter 8: Sliding Window Protocol Implementation

Page 189: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

171

Chapter 9

OSPF Protocol Implementation

This chapter aims at evaluating the applicability of frameworks by discussing their application onthe implementation of a realistic protocol. This chapter discusses the use of the Advanced EventManager Framework in the implementation of the OSPF routing protocol [49].

The structure of this chapter is the following: section 9.1 presents the goals and assumptions ofthis case study; section section 9.2 gives an overview of the OSPF protocol; section 9.3 presentsthe OSPF design structure; section 9.4 presents the OSPF implementation structure; section 9.5presents the OSPF implementation using the chosen framework; and section 9.7 presents our con-clusions on this case study.

9.1 Introduction

So far in this thesis we have only used simple protocols to illustrate the use of frameworks in theprotocol implementation process. Despite the simplicity of these protocols, they served our pur-pose of illustrating the use of the frameworks. In this chapter we intend to evaluate the applicabil-ity of our frameworks by considering a more realistic implementation process.

Our method for protocol implementation emphasises the support for design concepts intended tostructure the protocol behaviour. Therefore, in order to evaluate our method we have considered acase study with enough possibilities for protocol behaviour structuring. Stateless protocols withintensive data manipulation would not provide proper case studies. Protocols, such as, e.g., RTCP[78] and SNMP [73], handle lots of information, but do not have a complex state space that wouldbenefit from behaviour structuring techniques to facilitate their understanding and implementa-tion.

When applying structuring techniques to protocol design we have to assess whether the resultingdesign can have an efficient implementation, assuming that the implementation step preserves thedesign structure. A monolithic implementation can be optimized without considering structuringconstraints, and therefore can, in general, be made more efficient than structured implementa-tions. The price paid when building monolithic implementations, however, is the complexity ofthe resulting code, which is difficult to maintain and more vulnerable to errors than structured

Page 190: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

172

Chapter 9: OSPF Protocol Implementation

code. The use of structuring techniques increases understandability by, splitting the protocol infunctional parts and delimiting the scope of data manipulation.

A case study with a realistic protocol that benefits from a structured approach allows one to eval-uate two aspects of the protocol implementation process:

• the structuring techniques supported by our frameworks in so far as they provide good struc-turing for a realistic protocol;

• the restrictions imposed by these techniques on the protocol implementation process.

We chose the Open Shortest Path First (OSPF) protocol [49] in this case study. The OSPF proto-col is a link state routing protocol used in the Internet. This protocol is complex enough to applystructuring and has enough requirements on communication between its functional elements toprovide a representative evaluation.

Due to the amount of data shared between the functional components of the OSPF protocol, theinterleaving type of parallelism is appropriate to its implementation avoiding complex proceduresfor protecting the implementation against data corruption. As discussed in chapter 4, frameworksbased on multi-threading are likely to become more complex when concurrent access to datastructures must be protected. Therefore, we have chosen to apply the Advanced Event ManagerFramework in this implementation.

Ideally, the design model used in a protocol development approach should have an associatedmodelling technique and tool set to support the design phase. In our case study, the design modelsupported by our framework has been developed mainly to support our protocol implementationapproach. We use natural language to represent the models produced during the developmentprocess in this case study, supplemented with some diagrams.

The OSPF specification, publicly available as RFC in [54], is not described in any formal model-ling technique besides the state machines that describe the behaviour of its more complex func-tions. No explicit structuring is defined for the protocol in [54], although some elements areidentified in the protocol description that can suggest a structuring, e.g., in terms of interfaces andneighbours. The data structures and the required procedures of the protocol are presented in [54]without any concern for the data scope.

In this chapter we first map the OSPF RFC onto a structured protocol design using a simpledesign model. This design model consists of some concepts presented in chapter 3, extended withconcepts that we discuss in this chapter. The structured OSPF protocol design is subsequentlymapped onto another structure whose concepts are directly supported by the Advanced EventManager Framework. Figure 9.1 illustrates these steps.

To make our case study more didactic, we have considered a limited set of functions of the OSPFprotocol. We assume that OSPF works in a single autonomous system consisting of point-to-pointnetwork segments, as illustrated in Figure 9.2. An autonomous system has a group of routersexchanging routing information via a common routing protocol. The complete OSFP handles net-work segments with many attached routers.

Page 191: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.2 OSPF Protocol

173

9.2 OSPF Protocol

OSPF is too complex for a detailed description in this thesis. Therefore, we explain the functionsof OSPF at an abstraction level that is suitable to the purpose of our study case. For a completedescription of the protocol we refer to the RFC [54].

OSPF runs on top of the Internet Protocol (IP). We have assumed that the network topology con-sists of a collection of routers connected by point-to-point links. Each router may have more thanone interface with the network. Each interface is associated with an IP number. An OSPF router’sidentification is selected from one of the IP numbers of the underlying IP interfaces. Protocols useIP through an access point identified by an IP protocol number. The IP protocol number associ-ated with OSPF is 89.

When the IP layer receives a packet through one of the network interfaces, it identifies an OSPFpacket by means of the IP protocol number. IP delivers the OSPF packet to the OSPF protocoltogether with an identification of the receiving interface. An OSPF protocol entity sends packetsto one of its neighbour OSPF entities through an attached interface whose IP address it learnswhen exchanging configuration packets. Figure 9.3 illustrates this scheme.

9.2.1 Overview

We consider the use of the OSPF protocol in a scenario that consists of network segments con-nected by routers. The OSPF protocol is responsible for supplying enough information to the rout-ers so that they can decide on the shortest path along which to forward incoming IP packets,considering the intended destination of the packets.

Figure 9.1 Case study structure

OSPF RFCdesign implementation

structurestructure

analysismapping onsupported

design model

section 9.4 section 9.5

40.1.1.1 40.1.1.2

40.1.1.4

40.1.1.3

Figure 9.2 Point-to-point Network topology

Page 192: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

174

Chapter 9: OSPF Protocol Implementation

OSPF belongs to a category of routing protocols called link-state protocols, which are based onthe link state algorithm. The core function of the link-state algorithm is to keep a distributed andreplicated database, with a copy in each router. This database contains topology informationabout the routing domain, i.e., the collection of routers in the routing domain and how they areinterconnected. The database is used to calculate the IP routing table for correct forwarding IPpackets. Changes in the network topology are communicated by the protocol to all routers in areliable way. The process of synchronizing distributed parts of the database is called convergence.One of the goals of OSPF is to minimize the time of convergence, while consuming only a smallpercentage of link bandwidth for control traffic and little CPU time for routing calculation.

Each router is responsible for keeping information of its view on the topology in link-state adver-tisement (LSA) data structures. This view consists of the set of routers to which the router isdirectly connected. Directly connected routers are called neighbours. A router is connectedthrough an interface to one of its attached network segments. The collection of all LSAs from allrouters compose a protocol database called link-state database (LSD). OSPF defines a procedureto detect any changes in the topology concerning its neighbour routers. This procedure is calledthe Hello protocol. When any change is detected by the Hello protocol, the updated informationin the corresponding LSA is advertised by the router using a procedure called reliable flooding.Figure 9.4 shows the OSPF protocol architecture in terms of its functions and information.

In Figure 9.4, a shadowed element means that several instances of that element are possiblewithin the protocol entity. The interface and neighbour elements represent protocol functions thathave associated data structures to store state information and related operations.

When the OSPF starts executing, it waits for indications from the lower level protocols that theinterfaces are operational. For each operational interface the Hello protocol is executed to acquireneighbours. A router dynamically detects its neighbours by sending a Hello packet to a multicastaddress. The Hello protocol runs continuously to detect broken links with neighbours. For eachacquired neighbour, the OSPF protocol tries to synchronize its database. When synchronized, theneighbours are said to be in an adjacent state. Routing updates are only sent to neighbours in anadjacent state. Updates are sent to refresh information in the neighbours or due to LSA changes.

OSPF

IP

MAC layer

id

router interfaces

IP protocol 89

IP 40.2.1.1IP 40.3.1.3IP 40.4.1.5

OSPF id = 40.3.1.3

physical links

router

Figure 9.3 OSPF LLS

Page 193: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.2 OSPF Protocol

175

OSPF routes IP packets based solely on the destination address of the IP packet header. The OSPFprotocol does not encapsulate IP packets in any further protocol headers. The OSPF protocol enti-ties exchange control information by exchanging the following packets (PDUs):

• Hello packet - Discover and maintain neighbours

• Database Description (DD) packet - Summarize database contents

• Link State Request (LSR) packet - Database download

• Link State Update (LSU) packet - Database update

• Link State Acknowledgment (LSA) packet - Flooding acknowledgment

9.2.2 Interface Function Operation

In our simplified version of the OSPF protocol, the operation of an instance of the interface func-tion of the protocol has two states: down and point-to-point. In the down state, the interface functionwaits for an indication from the lower level service that the network interface is operational. Suchan event is called interfaceUp. Upon the receipt of an interfaceUp event, the interface goes to thepoint-to-point state. When an interface is in the point-to-point state, the OSPF protocol activates atimer that triggers the periodic sending of Hello packets. In the point-to-point state, the interfacemay receive Hello packets. Hello packets are then identified and dispatched to the appropriateinstance of the neighbour function of the protocol. If the appropriate instance of the neighbour func-tion does not exist, it must be created. If the lower level service indicates a link break with the net-work, i.e., an interfaceDown event, the interface function goes back to the down state. Figure 9.5illustrates the state machine for this behaviour.

9.2.3 Neighbour Function Operation

There is an instance of the neighbour function in the OSPF protocol for each connected neighbourrouter. A neighbour function uses a set of data structures and procedures to handle the relatedneighbour router. The neighbour function’s data structures are:

• state: the functional state of the neighbour;

OSPF entity link-statedatabase

interface

neighbour

interface

routingtable

Figure 9.4 OSPF protocol elements

function

function

Page 194: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

176

Chapter 9: OSPF Protocol Implementation

• master-slave flag: neighbours establish a master-slave relationship when synchronizingdatabases. Only the master is allowed to retransmit. Slaves only respond to packets of themasters. The establishment of the master-slave relationship is explained later on;

• dd sequence number: sequential number identification of the database being sent;

• last received database packet: records the last received packet to detect packet duplications;

• neighbour id: OSPF id of the neighbour router;

• neighbour IP address: IP address of the neighbouring router’s interface to the attached net-work;

• link state retransmission list: list of LSAs that have been advertised using flooding but havenot been acknowledged;

• database summary list: the complete list of LSAs that make up the area LSD at the momentthe neighbours start synchronizing the databases;

• link state request list: the list of LSAs that need to be received from this neighbour in orderto synchronize the two neighbours’ LSD.

The procedures that manipulate these data structures are the Hello Protocol and the Initial Data-base Synchronization, which are both discussed below.

Hello Protocol

The Hello protocol is an auxiliary protocol within the OSPF that is responsible for establishingand maintaining the connection between neighbours, and ensuring that the communicationbetween the neighbours is bidirectional. This is done by sending hello packets periodically fromrouter interfaces and monitoring the arrival of such packets. A router knows that a communica-tion is bidirectional when it sees its name in a neighbour hello packet. Figure 9.6 describes theHello protocol behaviour, which is a partial representation of the behaviour of neighbour func-tion.

The Hello protocol behaviour starts in a down state, where no Hello packet has been received.From the down state, the protocol goes to the init state when it receives a Hello packet without itsidentification, or goes to the exStart state if the Hello packet contains its identification. The timeelapsed after receiving a Hello packet (inactivity time) is monitored by the protocol. The inactiv-ity time is set to a predefined value whenever a Hello packet is received. If the inactivity time

down point-to-point

interface Up

interface Down

Receive Hello Packet

Send Hello packet

Figure 9.5 Interface function behaviour

Page 195: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.2 OSPF Protocol

177

elapses, the related neighbour is considered inactive. If a DD packet is received in the init state orin the exStart state, the protocol executes a procedure called master-slave negotiation.

Entering in the exStart state, the Hello protocol executes the master-slave negotiation. During thisnegotiation, the router updates the dd sequence number. If that is the first time it tries to enter theadjacent state, it sets the dd sequence number to a unique value, declares itself as master and startssending DD packets with master flag set to on. If it is not the first attempt to become adjacent, thedd sequence number is increased and the router starts sending empty DD packets to its neigh-bours. The protocol waits for DD packets in order to settle or acknowledge the master-slave rela-tionship. DD packets are transmitted at configurable time intervals, called RxmtInterval, until thestate is changed. The router with the greater neighbour id gets the master role and the protocolgoes to the exchange state.

Initial Database Synchronization

The initial database synchronization procedure consists of two parallel tasks: exchange of DDpackets and exchange of LSU packets. This procedure starts when an instance of the neighbourprotocol function reaches the exchange state. The entire LSD is copied into the Database Sum-mary List. LSAs that are as old as the value MaxAge are added to the neighbour’s Link StateRetransmission List instead of being copied to the Database Summary List. The LSA age is keptin a LSA field called LS age. Figure 9.7 presents the FSM for the database synchronization behav-iour.

In this synchronization phase, the LSAs in the Database Summary List of the adjacency, i.e.,neighbours in the adjacent state, are exchanged. LSAs are transmitted in DD packets. Each packettransmitted must be acknowledged or it is retransmitted after a RxmtInterval time interval haselapsed. Master routers send packets and update the dd sequence number used to identify thepacket in transit. Slave routers send DD packets in reply to master packets and use the last ddsequence number received.

A bit (M) in the DD packet identifies the end of packets to be transmitted. After receiving the lastpacket, a neighbour instance goes to one of two states: loading or full. It goes to loading if theLink State Retransmission List is empty, and to full otherwise. DD packets received in the loadingor full states are duplicates and are acknowledged as in previous states.

down init exStart exchange

H2: Hello packet with its id

H1: Hello packet without its id

H1

H2

H1

H2

DD

H2/DD/RT

IT: inactivity timer fired

IT

IT

RT: RxmtInterval elapsedDD: settling slave, or slave acknowledgment

DD

Figure 9.6 Hello protocol behaviour

Page 196: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

178

Chapter 9: OSPF Protocol Implementation

Neighbours request LSAs in the Link State Retransmission List by sending of LSR Packets. Areply to this request is expected by means of LSU packets. LSR packets are retransmitted if noreply is received after RxmtInterval has elapsed. When the Link State Retransmission List isempty, the neighbour goes to the full state. Each neighbour has to reply to LSR packets. LSRpackets can be received in the states exchange, loading and full.

When receiving DD packets, duplicate DD packets are discarded and cause the slave to retransmitthe last DD packets. Irregularities in the packet fields cause the neighbour to restart the initialsynchronization process, changing its state back to exStart. We call such an irregularity a ValueMismatch events (VM).

9.2.4 Updating the Link-State Database

There are three events that cause the LSD to be updated:

• A new or newer instance of a LSA is brought by the Flooding procedure. In this case, newLSAs arrive through LSU packets in the states exchange and states above of the neighbourfunction. Each LSA in a LSU packet is processed separately. LSAs’ fields are validated, e.g.,LS checksum, LS type and LS age. Based on the LSA’s age, the OSPF entity decides if it isappropriate to install it in the LSD. The LSA is then acknowledged using an LSA packet.The Link State Request List or Link State Retransmission List of associated neighbours mayneed some update. The OSPF entity may have to retransmit the LSA packet back to the send-ing neighbour using an LSU packet;

• The LSA expires and is flushed from the routing domain. The LS age field of an LSA isincreased while it is in a router’s database up to the value MaxAge. When an LSA reachesMaxAge, it is ignored for the routing calculation and the LSA is reflooded in order to beflushed from the routing domain. A MaxAge LSA must be removed from the LSD as soon asit is no longer in any neighbour Link State Retransmission List and none of the router neigh-bours are in states exchange or loading;

• A new or newer LSA is originated by the router itself. Whenever an interface changes itsstate, an LSA describing the router interfaces (router-LSA) must be created or updated. The

exchange loading full

DD

DD-c1

DD-c2c1: last DD and LSRL not emptyc2: last DD and LSRL is empty

AT

AT: acknowledge timeout

exStart

VMVM

VMLSR

LSR

LSR

LU: last LSUP

LU

DDDD

Figure 9.7 Exchange database summary behaviour

Page 197: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.2 OSPF Protocol

179

same happens when one of the router neighbours changes from or to the full state. Self-orig-inated LSAs are periodically checked to see if their LS age field reached the limit of LSRe-freshTime. In this case, a new instance of the LSA is created and replaces the LSA in thedatabase.

New instances of the an LSA can not be originated within the time period MinLSInterval. This maydelay the generation of a new LSA instance.

9.2.5 Reliable Flooding

LSU packets are used to flood the network with LSAs. A LSU packet may contain several distinctLSAs, and floods each LSA one hop further from its point of origin. To make the flooding proce-dure reliable, each LSA must be acknowledged separately. Acknowledgments are transmitted inLSA packets. Many separate acknowledgments can be grouped into a single packet.

When a new LSA has been installed in the LSD, it must be flooded to the adjacent neighbours.The flooding process must check each neighbour to decide whether the neighbour should partici-pate in the flooding process. This is done by examining the neighbour state, to check the existenceof a more updated version of the LSA in the Link State Request List of that neighbour. If theneighbour must participate in the flooding process, the LSA is included in its Link State Retrans-mission List. After analysing all neighbours, the flooding procedure sends an LSU packet with theLSA to be flooded out of all interfaces that have at least one neighbour with the same LSA on itsLink State Retransmission List.

LSAs in the Link State Retransmission Lists are retransmitted each RxmtInterval seconds. SeveralLSAs can be packed in a single LSU packet. LSAs are removed from the Link State Retransmis-sion List when acknowledged. Figure 9.8 illustrates the reliable flooding procedure.

The flooding in Figure 9.8 starts with router 40.1.1.4 flooding its LSAs to its neighbours at timet1. At time t2 LSU packets (u) are forwarded by these neighbour routers (40.1.1.1, 40.1.1.2,40.1.1.3) to all their neighbours except to the one from where they received the LSU packet. Attime t3 the LSU packet (a) is sent. Receiving an LSA in a LSU from a neighbour to which thesame LSA was sent, but which was not yet acknowledged by that neighbour, is considered as animplicit acknowledgement of that LSA.

9.2.6 Routing-Table Calculation

The routing task of a router consists of determining the next hop router an IP packet has to followin order to reach its destination. The LSD contains information about all the router connectionsand their associated transmission costs in the routing domain. This information can be used to cal-culate the paths and to decide on the next router. However, calculation should not be performed atevery routing request. The router maintains a routing table containing the result of the routing cal-culation for all possible destinations. Each router has a different routing table since the IP packet’scurrent position is different in each case.

The algorithm to calculate paths is based on the Dijkstra algorithm [49]. This algorithm incremen-tally calculates a tree of shortest paths in which the router itself is the root of the tree. All neigh-

Page 198: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

180

Chapter 9: OSPF Protocol Implementation

bours are added to a candidate list together with the transmission cost. At each iteration,information on the router with the smallest cost is copied from the candidate list to the routingtable. This router is placed in the shortest path tree and its neighbour routers are then examinedfor inclusion or modification of the candidate list. The algorithm continues until the candidate listis empty. Figure 9.9 presents a network topology used to exemplify the Dijkstra algorithm.

The reader can infer by applying this algorithm that router 40.1.1.4 in Figure 9.9 would determinethe routing table show in Table 9.1.

9.3 Protocol Design Structure

We propose a structure for the OSPF protocol based on the functions identified in section 9.2.Alternatively we could structure the protocol based on its data structures. However this wouldresult in a monolithic structure, because most data structures is manipulated in different phases of

40.1.1.1 40.1.1.2

40.1.1.4

40.1.1.3

a a aTime t3

40.1.1.1 40.1.1.2

40.1.1.4

40.1.1.3u

u

u

u

Time t2

40.1.1.1 40.1.1.2

40.1.1.4

40.1.1.3

u u uTime t1

Figure 9.8 Reliable Flooding starting at router 40.1.1.4

40.1.1.1 40.1.1.2

40.1.1.4

40.1.1.35 3

110

1

Figure 9.9 Transmission costs

Page 199: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.3 Protocol Design Structure

181

the protocol. Therefore, the data centred structuring approach is unsuitable. We however keep thedata structures suggested in the OSPF RFC in order to keep the implementation familiar to thosereaders that are familiar with this protocol.

In the global design structure of the protocol we use the component design concept to decomposethe protocol according to its main functions. A component encapsulates a protocol function and itsrequired data structures, in such a way that information is only shared between componentsthrough interactions. This technique provides a high level of independency between the decom-posed parts. Components are connected through value-passing synchronous interaction points inorder to cooperate in the execution of their task.

Figure 9.10 shows the protocol structure using a graphical representation of the design concepts.We use a rectangle to represent a component and arrows to represent interaction means. Shadowsindicate the possibility of many instances of the related concept. The protocol entity is representedas a dashed rectangle. As suggested by the RFC, the components are:

• Interface: performs the interface behaviour discussed in section 9.2.2.

• Neighbour: performs the neighbour-related procedures discussed in section 9.2.3.

• Database maintenance: groups the procedures discussed in sections 9.2.4, 9.2.5 and 9.2.6.

Instances of components neighbour and interface are created dynamically as soon as physicalneighbours and interfaces are detected by the protocol. Interaction points are connected dynami-cally, as soon as interface and neighbour components are instantiated. The interaction point im4supports the connection of many instances of the interface component to the evironment of theOSPF entity. Figure 9.10 presents our structure for the OSPF protocol.

The main functions of the OSPF protocol that are performed by components are further structuredas monolithic behaviours. Monolithic behaviours within the same component may share data andare, together with behaviour composition relations, a strategy to structure behaviour using con-structs of a higher level of abstraction. Below we present the internal structure of each compo-nent. We use rectangles with rounded corners to represent monolithic behaviours. We identifybehaviour composition relations by placing the monolithic behaviours in a tree where intermedi-ate nodes are relations and the leaves are monolithic behaviours. We have used the following rela-tions: sequence (S), choice (C) and interleaving (I). We place the most important data structureswithin the components that handle these structures. Some behaviours use timers (T) to determinewhether a timeout period has been elapsed.

Destination Next Hop Cost

40.1.1.1 40.1.1.1 1

40.1.1.2 40.1.1.2 1

40.1.1.3 40.1.1.2 4

Table 9.1 Router 40.1.1.4 routing table

Page 200: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

182

Chapter 9: OSPF Protocol Implementation

A design construct called routine (R) is also used to compose behaviours. The routine design con-cept relates a monolithic behaviour to a calling behaviour. The monolitic behaviour is enabled ina certain state of execution of the calling behaviour. After being enabled, the routine’s behavioursubstitutes the calling behaviour in the composition tree until the routine exits. The calling behav-iour then gets the control, resuming its execution from the same execution state from which theroutine was activated. The routine shares the context information used by the calling behaviour.Such construction avoids duplication of parts of the specification which are performed at differentpoints of the protocol.

The behaviour of the database maintenance component is structured as the composition of the fol-lowing monolithic behaviours: routing calculation, LSA flushing and LSA update. This componentalso makes use of a routine called Flooding. The three monolithic behaviours are interleaved. LSAflushing and LSA update make use of timers and the Flooding routine. The timers are used for peri-odically incrementing LSAs MaxAge in the Link State Database, and for periodically refreshing self-originated LSAs, respectively. The most important data structures in this component are the Rout-ing table and the Link State Database, which are shared by the monolithic behaviours and the rou-tine. Figure 9.11 shows the graphical representation of the database maintenance component.

OSPF Entity

database maintenance neighbour

interface

im1

im2im3

im4

Figure 9.10 Global Structure of the Design

database maintenance

UpdateLSA

FlushingRouting

Calculation

Routing tableLink State Database

I

TT

Flooding

LSA

R

im1

im3

Figure 9.11 Database Maintenance Component

R

Page 201: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.3 Protocol Design Structure

183

Figure 9.12 shows the graphical representation of the neighbour component. The behaviour of theneighbour component is structured as the composition of the following monolithic behaviours:summary exchange, loading, hello protocol and LSA retransmission. These monolithic behaviours arecomposed in interleaving. The most important data structures belonging to the neighbour compo-nent are listed in Figure 9.12 inside the component’s representation. The timers required by eachmonolithic behaviour are also indicated. The summary exchange and loading monolithic behavioursare the two parallel tasks performed in the Initial Database Synchronization, as discussed in section9.2.3. The hello protocol has also been explained in section 9.2.3. The monolithic behaviour LSAretransmission performs the reliable transmission of LSAs in the Link State Retransmission List.

The timer used in the summary exchange monolithic behaviour concerns the TxmtInterval secondsthe behaviour waits for the acknowledgement of DD packets. The timer used by the Loading mon-olithic behaviour concerns the acknowledgment of LSR packets and indicates that LSR packetsshould be retransmitted. The timers used by the Hello Protocol are concerned with neighbour inac-tivity and the interval for retransmiting DD packets for negotiation of master-slave roles. Thetimer used by LSA Retransmission concerns the timeout for receiving an acknowledgment.

Table 9.2 presents the communication primitives (CP) sent through each interaction point. CPsintroduced for inter-component communication are written in italics.

The directions of CP flow are identified by the first letter of each component. Some of the com-munication primitives required by the OSPF protocol, mostly those exchanged between the proto-col and its environment, have already been introduced when explaining the protocol. Othercommunication primitives are required due to the proposed structure, for cooperation between thecomponents of the protocol. These CPs are listed below:

• Copy database: requests a summary of the entire LSD and receives the summary as response;

• LSA update: delivers LSAs to be installed in the LSD;

• LSA retransmission: includes a LSA in the neighbour’s Link State Retransmission List;

• Consult retransmission list: checks if a given LSA is in a neighbour’s Link State Retransmis-sion List. This CP triggers an positive or a negative answer from the communicating partner;

neighbour

Link State Retransmission ListLink State Request ListDatabase Summary List

HelloProtocol

LSAtransmissionExchange Loading

I

T TT TT

Summaryim1

im2

Figure 9.12 Neighbour Component

Page 202: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

184

Chapter 9: OSPF Protocol Implementation

• Consult neighbour state: requests the current state of a neighbour. This CP triggers an answercontaining the state as response;

• Inform neighbour state: informs that neighbour changed from or to the full state;

• Interface status: informs when the interface goes down or up;

• Consult Request List: examines the existence of a more updated version of a given LSA inthe Link State Request List of the receiving neighbour;

• Next hop: requests for the route to be taken for a given IP destination. This CP triggers ananswer informing the next hop IP;

• IP Data Request: OSPF protocol delivers control packets to IP;

• IP Data Indication: IP delivers control packets to OSPF protocol.

9.4 Protocol Implementation Structure

The structure shown in section 9.3 for the OSPF protocol is mostly based on design constructsthat are directly supported by the Advanced Event Manager Framework. Some design or imple-mentation requirements, however, are not directly supported or require some coding effortbesides the systematic mapping indicated in the framework usage information. In the following,we discuss to what extent the chosen framework directly supports the designed protocol and theeffort required to cope with the existing limitations. We also propose a new structure that isdirectly supported by the chosen framework.

Table 9.2 OSPF Communication Primitives

Interaction Point Communication Primitive Direction

IM1 Copy databaseLink state update packetLSA updateLSA retransmissionConsult retransmission listConsult neighbour stateInform neighbour stateConsult Request List

n => dn => dn => dn <= dn <= dn <= dn => dn <= d

IM2 Hello packet Database description packetLink state request packetLink state update packetLink state acknowledgment packet

i => ni <=> ni <=> ni <=> ni <=> n

IM3 Interface statusLink state update packetNext hop

d <= id => i d <=> i

IM4 IP Data ResquestIP Data IndicationInterface statusNext hop

i => ei <= ei <= ei <=> e

Page 203: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.4 Protocol Implementation Structure

185

9.4.1 Interaction Point

The interaction point IM4 is used by the OSPF protocol to interact with its environment. Thecharacteristics of the environment and of the OSPF protocol that influence the implementation ofthis interaction point are captured by specializations of a framework class, as part of the procedurefor applying the framework.

Some characteristics of the interaction point IM4 that should be implemented in the framework,however, are not directly supported by the Advanced Event Manager Framework. This interactionpoint requires dynamic connection of multiple communication parties, while the framework onlysupports two-party interaction points.

A solution for this problem is to include a dispatcher component in the protocol structure to com-municate with the environment and dispatch the incoming CPs to the appropriate instances of theinterface component.

The dispatcher component is also responsible for detecting the need for a new instance of the inter-face component and creates this instance when necessary. The dispatcher component supports theconnection of dynamic interaction points to communicate with the instances of the interface com-ponent. Figure 9.13 shows the refined implementation structure.

The remaining interaction points defined in the previous protocol structure of Figure 9.10 can bedirectly supported by the Advanced Event Manager Framework.

9.4.2 Behaviour

The Advanced Event Manager Framework does not support the routine design construct applied inthe design structure we have proposed for the OSPF protocol. A possible solution for this problemis to replicate the behaviour defined in the routine in the respective calling behaviours.

Figure 9.13 OSPF protocol implementation structure

OSPF Entity

database maintenance neighbour

interface

im1

im2im3

im4

dispatcher

im5

Page 204: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

186

Chapter 9: OSPF Protocol Implementation

The concept of timer used by the behaviours of the proposed components is directly supported bythe chosen framework and therefore it can be systematically mapped onto the correspondingimplementation construct.

Each monolithic behaviour within the proposed components has been defined using finite statemachines. Consequently, these behaviours can be easily mapped onto the state tables applied inthe framework usage procedure in order to capture the information required to fill in the templatesfor protocol implementation.

9.4.3 Dynamic Structuring

Another design requirement in the specification of the OSPF protocol is the dynamic change ofstructure. For example, instances of the interface component are created by the dispatcher compo-nent whenever new interfaces become operational, and instances of the neighbour component arecreated when new neighbours are detected by the Hello Protocol. Interfaces and neighbours mayalso be destroyed whenever physical interfaces are down or contact is lost with neighbour routers.

These design requirements are supported by the Advanced Event Manager Framework, whichallows creation and destruction of components, as well as connection and disconnection of inter-action points, which can be performed as operations of a unit of behaviour. The framework alsosupports a variable number of connections to a component and supplies templates for the consist-ent implementation of a component’s behaviour that is capable of handling a variable number ofinteraction points.

The consistency rules of this framework concerning the dynamic changes in the protocol struc-ture, however, impose some constraints on the freedom to perform these changes. For example,the configuration of internal connections proposed in Figure 9.10 can not be achieved if instancesof the component neighbour are created by a component interface, as it is informally specified insection 9.3.1. The consistency rules of the supplied design model determine that only a fathercomponent can connect its child components. A neighbour has a connection (im1) to the databasemaintenance component, which is not a child of interface. The same limitation applies to the con-nection of im3 between database maintenance and interface, if the first component is expected to becreated statically, together with the dispatcher component. The dispatcher would not be able toconnect its child interface components to the database maintenance component.

There are two ways to cope with these restrictions: 1) communication primitives should flowthrough alternative connections that are allowed by the current design model, 2) the relationbetween father and the children should be changed in order to allow the required connections tobe established. Defining that the component dispatcher is the father of all remaining componentswould allow the configuration of connections displayed in Figure 9.10. Both solutions for the lim-itations on dynamic structuring imply on changes in the specified behaviour of the protocol,because components are no longer able to directly interact as initially specified. In case the dis-patcher is made the father of all other components, the interface component has to ask the dis-patcher to create new neighbours when necessary, instead of performing this task itself.

The decision on which solution to take depends on strategic requirements of the protocol develop-ment process, e.g., implementation efficiency and maintainability. We chose the second solution

Page 205: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.5 OSPF Implementation

187

because it is closer to our goal of demonstrating the capability of the framework for preservingdesign structure. The changes in the flow of messages through the interaction points of this proto-col imposed by this refinement are displayed in Table 9.3.

9.4.4 Coding Functions

The coding functions required by the OSPF protocol, i.e., coding and decoding of PDUs, have notbeing considered in the proposed design structure. These functions are spread over the protocolcomponents whenever they interact with the lower level service.

We followed the implementation strategy of separating the coding functions from the remainingprotocol functions in the implementation structure. This strategy could have been applied at thedesign level, justifying the need for a fourth component in an earlier stage of the protocol devel-opment. We place the coding functions in the dispatcher component.

9.5 OSPF Implementation

This section discusses the steps described in the framework usage information to perform a proto-col implementation. The main steps in applying the Advanced Event Manager Framework,according to its usage information, are:

• definition of constants (step 1);

• specialization of the external class (step 2);

• specialization of the eventHandler class (step 3);

• definition of initialization class (step 4).

9.5.1 Constant Definitions (step 1)

The identification of the constants in the case of OSPF is straightforward. Table 9.4 presents thestates that are represented as constants in the implementation. The communication primitives,

Table 9.3 Changes in OSPF’s CPs flow

Interaction Means Communication Primitive Direction

IM4 Hello packet Database description packetLink state request packetLink state update packetLink state acknowledgment packetInterface stateNext hop

i <=> di <=> di <=> di <=> di <=> di <= di <=> d

IM5 IP Data RequestIP Data IndicationInterface stateNext hop

d => ed <= ed <= ed <=> e

Page 206: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

188

Chapter 9: OSPF Protocol Implementation

which must also be represented in the implementation code by constants, has been presented inTable 9.2 and Table 9.3.

9.5.2 Specialization of External Class (step 2)

Interaction point IM5 (see Figure 9.13) requires some coding effort, in terms of specialization ofthe external class . The required specializations are intended to capture some environment-specific(step 2.1) and protocol-specific (step 2.2) characteristics of this implementation.

The environment for this implementation is the IP service, which uses the routing service pro-vided by the OSPF protocol. Steps 2.1.1 to 2.1.4 of the implementation process capture the partic-ular characteristics of the IP implementation when implementing the conceptual interaction pointdefined in the framework. We refer from now on to this specialization as the ip class.

The final implementation of IM5 consists of a specialization of the ip class applying restrictions tothe communication primitives that can flow through this interaction point. The primitives arelisted in Table 9.2. To perform this task we fill in the appropriate framework templates with theconstants defined in step 1 for the valid communication primitives.

9.5.3 Specialization of eventHandler class (step 3)

The implementation structure of the OSPF protocol contains four components. Each of the fourcomponents of the protocol requires a specialization of the eventHandler class. Figure 9.14 showsthe class diagram for the required specializations.

The internal structure of the proposed components consists mainly of interleaved behaviours, as itcan be seen in Figure 9.11 and Figure 9.12. Figure 9.15 shows the tree of terms to implement thebehaviour structure of each component.

Table 9.4 Behaviours’ states

Component Monolithic behaviour States

DB Maintenance Routing Calculation waiting, informing

Neighbour all down, init , exSart , exchange, loading , full

Interface X down, point-to-point

dispatcher X X

database maintenance neighbour interface dispatcher

eventHandler

Figure 9.14 EventHandler specializations

Page 207: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

9.6 Conclusions

189

The state table for the routing calculation monolithic behaviour is shown in Table 9.5. The routingcalculation behaviour of Table 9.5 consists of two units of behaviour. In the state Waiting, thebehaviour accepts routing consults (NextHop communication primitive), updates the routing tableif necessary and checks the appropriate next hop. In state Informing, the behaviour sends the calcu-lated next hop address.

9.5.4 Definition of the Initialization Class (step 4)

The last step of the implementation process is the procedure for static initialization of the proto-col. If we assume that the dispatcher is the father of all components, the initialization procedureconsists of treating possible protocol configuration parameters, e.g., timeout values, the instantia-tion of the dispatcher class and the interaction point im5. The code template for the implementationof protocol initialization contains fixed code to perform the other tasks of the protocol.

9.6 Conclusions

With minor adjustments of the design structure we could generate an implementation structurethat can be directly implemented using the framework. Only two design requirements were spot-ted in this case study that are not directly supported by the chosen framework. They are routineand a more flexible set of consistency rules for connecting interaction points. The requiredchanges in the protocol design to accommodate such limitations and the consequences of thechanges were discussed.

Considering that almost all design concepts used in the abstract model of OSPF can be supportedby our framework in this case study, we claim that the design model supported by the AdvancedEvent Manager Framework is suitable enough to build a well-structured specification of a realis-tic protocol.

Figure 9.15 Trees of terms for behaviour composition

DB Maintenance Neighbour Interface Dispatcher

I I B Broot root root root

B B B B B B B

State IP CP Action Condition Type

Waiting im3 NextHop if (new LSA) {recalculaterouting table};consult table;

Informing im3 NextHop state=Waiting

state=Informing;

accept

offer

Table 9.5 State table of Routing Calculation

Page 208: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

190

Chapter 9: OSPF Protocol Implementation

New design requirements, such as design concepts or constraints, are expected to appear as ourimplementation approach is applied to the development of different classes of protocols. Thisshould not be seen as a drawback of our method, since our method allows frameworks to beimproved at low cost if necessary.

Page 209: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

191

Chapter 10

Correctness Assessment

This chapter presents a systematic approach to assess the correctness of our frameworks for proto-col implementation. The objective of correctness assessment is to evaluate whether a frameworkcorrectly implements the semantics of the design concepts supported by this framework.

The structure of this chapter is: section 10.1 introduces the correctness assessment problem; sec-tion 10.2 presents our approach for framework correctness assessment; section 10.3 discusses thetechniques we use to specify the semantics of design concepts for the purpose of correctnessassessment; section 10.4 discusses the coverage of this correctness assessment approach; section10.5 describes the tool we developed to automate the assessment approach; section 10.6 presentsa case study that illustrates the application of our correctness assessment approach and section10.7 presents our conclusions.

10.1 Introduction

So far, in this work, frameworks have been used to provide maintainability and fast implementa-tion process. In this chapter we address the implementation correctness issue. Although ourframework development approach contribute to the correct implementation of frameworks in ourdomain, these contributions on implementation correctness still leave some room for errors. Ourframework development approach still requires a more systematic technique to ensure correct-ness.

Preserving the semantics of design concepts in the protocol implementation process is a crucialissue in the context of this work. This preservation is important to guarantee that protocol proper-ties that have been formally specified and analysed in the design step are not jeopardised in theimplementation.

Enforcing implementation correctness, however, is a protocol development goal that, consideringthe current state-of-the-art in software engineering, is in a trade-off with other development goals,as discussed in our introductory chapter (section 1.5), such as, e.g., software maintainability andimplementation process efficiency.

Page 210: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

192

Chapter 10: Correctness Assessment

Most protocol development processes provide little flexibility on performing this trade-off, defin-ing a process that focus on one or another development goal. For example, when using specifica-tion language compilers [20] the trade-off between implementation goals tends to be rigid, in thesense that the freedom is determined by the options made available by the compiler. Compilersautomatically transform the design structure into a flattened design specification, with a straight-forward implementation, by means of transformation rules. This approach provides implementa-tion efficiency and correctness, but compromises software maintainability. Maintainability iscompromised because this approach often yields code that is difficult to understand, compromis-ing implementation maintainability when adaptations or optimization are required [41].

Another example of protocol development approach that emphasises a particular choice in thetrade-off between development requirements is presented in [63] (see section 1.7). This approachis an effort to provide portable, maintainable and high-level implementation building blocks,however, they do not provide a link to formal design techniques. Therefore, this approach contrib-utes to implementation efficiency but provide little support to ensure that the protocol require-ments have been correctly implemented.

We have initially considered in our investigation two approaches to address implementation cor-rectness: correctness proof and tests. Correctness proof have been discarded due to the lack offormalism in the available implementation meta-models, as discussed in section 2.3.5. Therefore,we apply the second approach, using tests to address implementation correctness.

A possible approach for performing tests is the use of available testing techniques for protocolssuch as, e.g., the techniques presented in [37][79]. These techniques can be applied here by test-ing protocols implemented using a framework. The important requirement of the protocol to beused in this testing procedure is to make use of the concepts whose implementation we want totest. The service provided by the protocol is not relevant and should be simple to do not compro-mise the efficiency of the testing process. A proper behaviour in the execution of the protocolimplementation indicates that the framework implementation properly supports the combinationof concepts used in the chosen protocol.

Applying testing techniques as described above, however, have well-known drawbacks regardingthe coverage of the possible execution paths. Missing execution paths can hide possible errors.Another problem that rises here is that these techniques may largely decrease the efficiency of theprotocol development as a whole, since the implementation may need to be coupled to a testerprogram and test sequences must be provided. We propose a testing approach different from theone described above, that minimizes the impact to these drawbacks.

In our implementation approach, once frameworks are available and a technique for data manipu-lation is added, the implementation of specific protocols is an entirely systematic procedure. Theimplementation decisions required in the protocol implementation process have already beentaken while developing the framework. Since frameworks are built to provide implementationconstructs that directly relate to design concepts, the procedure to apply a framework (see section2.3.4) is straightforward. Due to these characteristics of our implementation approach, the cor-rectness of protocols implemented using frameworks rely strongly on the correctness of theframework.

Page 211: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.2 Testing Approach

193

In order to test our frameworks we propose a white box testing that is tailored to be applied toframeworks. In white box testing developers performing tests need to have access to the internalstructure of the implementation. Our testing approach improves the coverage and efficiency of thetesting process compared to approaches intended to test the protocol implementation. Our testingapproach can be used taking in consideration different numbers of scenarios (see section 10.4).This characteristic of our approach provides flexibility on the trade-off between the efficiency ofthe implementation process and the effort necessary to assess implementation correctness.

10.2 Testing Approach

We can classify the concepts we have identified in chapter 3 in two categories: basic and com-posed concepts. Each basic design concepts is mapped onto a corresponding implementationbuilding block. The semantics of composed concepts can be defined in terms of compositions ofbasic concepts.

We have identified in our application domain a small set of simple basic concepts. Therefore, theevaluation of the correctness of the mapping of these concepts to implementation constructs canbe done by inspection. Some basic concepts are:

• the creation of a component, which is mapped onto the instantiation of an eventHandlerobject;

• the connection of an interaction means, which is mapped onto a method of the eventPointclass that stores in the eventPoint object the reference to the connected component;

• an operation, which is mapped onto data manipulation functions.

Our testing approach was inspired by the traditional debugging procedure used in software imple-mentation, where check-points are established to keep track of the implementation’s behaviour.Check-points are assumed to be instantaneous events and, therefore, when recorded, provide apicture of the behaviour in terms of sequential events.

This testing approach is applied here to test the implementation of composed design concepts.Due to the assumption above on the characteristic of the monitored events i.e., to be instantane-ous, this approach only allows us to test composed design concepts that can be defined in terms ofa sequential ordering of basic concepts. All the concepts in the scope of our investigation complyto this requirement.

An example of composed concept defined in terms of basic concepts is the execution of a unit ofbehaviour. This execution starts with an event, followed by a guarding condition evaluation and,eventually, the execution of an action. Furthermore, a unit of behaviour must be executed atomi-cally. This means that no other basic concepts, belonging to other units of behaviour of the samecomponent, should be executed before the sequence of basic events of the current unit of behav-iour has being executed.

A building block implementing a basic concept is executed atomically, allowing us to considerthis execution as a single event in time. We call the execution of a basic concept in the frameworkimplementation a pseudo-event. The test of the correct implementation of composed concepts can

Page 212: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

194

Chapter 10: Correctness Assessment

be done by monitoring the order of occurrence of the related pseudo-events. We perform thismonitoring task in our testing approach by making the framework record a log of the occurrenceof pseudo-events related to the concept we want to test, during its execution. Afterwards, to test aspecific concept, we check whether the order of the pseudo-events in the log, obeys the orderdefined in the semantics of this concept.

We use EFSMs to specify the semantics of composed concepts. The language of the EFSM usedto specify a design concept defines all sequences of pseudo-events that can be produced by theimplementation of this concept. For example, assuming that a pseudo-event Aip represents theconnection of an interaction point ip to a component, and assuming that a pseudo-event Bip repre-sents an interaction-offer executed in ip. Figure 10.1 depicts the EFSM specifying that interactionoffers in a certain interaction point are only possible after its connection.

According to the specification in Figure 10.1, the first pseudo-event in the log-file must be an Aip,followed by any number of occurrences of Bip. Sequences of pseudo-events like (Bip,Aip,Aip) or(Aip,Bip,Aip) would mean that this concept has been implemented incorrectly.

The formal specification of concepts allows the testing procedure to be performed automatically.In our approach, a Tester program reads the log-file and a file containing the EFSM description,and verifies whether the recorded sequence of pseudo-events belongs to the language of theEFSM. If a certain pseudo-event is not expected in a certain state of the EFSM, the Tester pro-gram informs its user that the concept has been implemented incorrectly. Figure 10.2 shows thearchitecture of this testing approach.

Our testing approach is also applicable to assess the correctness of the implementation of the con-sistency rules supported by a framework. Consistency rules can also be defined in terms ofsequences of basic concepts and, therefore, they can be tested in the same way as composed con-cepts. The implementation of these rules define the level of robustness of the framework (section4.6.3). Consistency rules tests assess whether the procedures intended to provide robustness to the

Figure 10.1 Concept specification using EFSM

Aip Bipdisconnected connected

Framework

TesterLog-File

Design Concepts

FSMs

implementation specification

Diagnostic

pseudo-events

Figure 10.2 Testing approach architecture

Page 213: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.3 Design Concepts Specification

195

protocol implementation have been properly implemented. Figure 10.1 presents a simple exampleof specification of a consistency rule, establishing restrictions to the use of interaction points.

In our approach, the test to evaluate each concept or consistency rule is performed separately. OneEFSM is defined for each concept or rule to be tested. The Tester program analyses each EFSM inturn, using the same log-file for the test of all concepts. This separation of concerns in the test pro-cedure provides three main benefits:

1. flexibility for performing the testing task, allowing us to regulate the effort applied in this development step;

2. simplification of the specification of the concepts for tests. An approach that requires a sin-gle specification of all concepts to be tested would lead to a complex specification. This com-plex specification would be a source of errors on its own during the development process, since it would not be trivial to assess whether this specification properly specifies the design model;

3. simplification of the test procedure. We can focus on specific concepts or on particular sets of related consistency rules, in turn.

Implementation correctness should also be investigated in terms of the preservation of structuraldesign concepts at the implementation level. Some criteria for this evaluation has been presentedin section 10.7. The testing technique presented in this chapter is not applicable to the assess thepreservation of structural design concepts. We perform this evaluation by code inspection, basedon the criteria mentioned above.

In the context of our protocol implementation process, tests are only required when changes aremade in the frameworks. Once tested, frameworks can be applied in the implementation of differ-ent protocols without need for further testing.

10.3 Design Concepts Specification

The basic meta-model introduced in chapter 2 contains the fundamental concepts of a designmodel in our domain, i.e., component, interaction means, behaviour and interaction. Design models inour domain are mostly a specialization of these fundamental concepts, together with the rules tocombine them.

The specification of a design concept consists of defining which pseudo-events are allowed tooccur at each state of the implementation’s execution, regarding the set of pseudo-events relatedto this concept. The information needed for specifying design concepts is:

• the possible states of the concept’s behaviour;

• the pseudo-events expected in each possible state;

• the conditions guarding each possible state transition;

• the actions associated with a transition that update the FSM’s variables;

• the resulting state of a given transition;

• the condition that evaluates if an instance of a pseudo-event relates to a transition;

Page 214: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

196

Chapter 10: Correctness Assessment

• the initial and final state of the FSM.

The finite state machine we use to describe concepts behaviour applies variables, guarding condi-tions and input events. The are two types of conditions in our state machines. The first type ofcondition that appears in the list above is used to guard the triggering of transitions. This type ofcondition is applied in state machines to decrease the number of possible states in the behaviourdefinition. The second type of condition is used to identify the instances of pseudo-events whichare related to a certain transition. This allows simultaneous test of different instances of the sameconcept.

The definition of the initial and final states of a EFSM is necessary to initialize the Tester andcheck if the execution of a concept’s behaviour has been completed successfully. The Tester alsouses the initial state to identify when new instances of the EFSM have to be created. This is doneeach time an instance of a pseudo-event allowed in the EFSM’s initial state is found that is notrelated to any instance of the EFSM already instantiated.

The specification of each design concept in our testing approach must be generic, deterministicand self-contained. To be generic implies that we have to specify all possible scenarios in whichthe concept being specified can appear (see section 10.4). For example, a behaviour can make useof zero, one or more timers, and a choice relation may compose two or more behaviours, which canbe monolithic or composed behaviours. A deterministic state machine is characterized by the factthat at any of its states an instance of a pseudo-event is associated to the triggering of at most onetransition. The specification must be self-contained in that the semantics of the concept beingspecified is totally contained in the specification.

When specifying design concepts we should not introduce unnecessary or undesirable restrictionsto the occurrence of pseudo-events. This case happens for example because it is sometimes easierto define when a pseudo-event is disabled than to specify when it is enabled in the behaviour of acertain concept. For example, if in the specification of a certain concept (C1), the only concernregarding a certain pseudo-event PE1 is that PE1 should not happen in a certain state (S1) of thebehaviour of C1, it is not enough to disable PE1 in S1. In this case, it is also necessary to enablePE1 in the remaining states although the occurrence of PE1 is not relevant to the behaviour of C1

in these states.

Assume that the concepts of a design model that require testing have been specified, and the sup-porting framework has been tested regarding these concepts. New specifications or tests are onlyrequired in case:

• a new implementation solution is provided for a concept already defined in the design modeland this solution has been implemented. In this case, the formal specification of the conceptbeing implemented is available and should be used to test the new implementation;

• a new concept or rule is added to the framework. In this case, the concept or rule must bespecified in order to be tested;

• a concept already supported by the framework is changed together with its implementation.In this case, the specification must be updated and the implementation must be tested.

Page 215: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.4 Test Coverage

197

In this thesis we do not provide the specification of all concepts and consistency rules we haveidentified, but limit ourselves to the presentation of two examples that illustrate the application ofthe technique. Based on these examples, framework developers can specify of other concepts andtest their implementation. Therefore, framework developers are responsible for the correctness ofconcepts’ specification relies on . The technique to specify concepts is rather simple and intuitive,since it is based on execution traces of the system.

10.4 Test Coverage

The behavioural concepts in the basic meta-model presented in chapter 2, consist of behaviour andinteraction. Behaviours can be monolithic or composed. Monolithic behaviours are defined in ourapproach in terms of FSMs, and since we consider the implementation of a FSM well-known (seesection 4.3), we assume that this implementation does not need to be tested. Composed behavioursand interaction are not systematically implemented. We apply the general solutions proposed inchapter 4, however, some implementation effort is necessary to integrate those ideas with otherimplementation solutions. The final solution, therefore, is ad-hoc and need to be tested.

When testing each concept supported by a framework, it is necessary to consider all different pos-sible scenarios, i.e., the different situations in which a concept can be applied. The test of a con-cept implementation requires the provision of a protocol that uses the possible scenarios in whichthis concept can appear. However, providing a large number of protocols for testing would com-promise the efficiency of the testing approach. In the sequel we analyse the potential number ofscenarios necessary in the test of a concept’s implementation, to evaluate whether the multitude ofscenarios can compromise efficiency.

In order to discuss the coverage of all possible scenarios, we classify scenarios into three majorcategories: 1) scenarios that differ in the behaviour context information of the concept, e.g., themessages being exchanged in an interaction. 2) scenarios that differ in the number of instances ofsome elements forming the concept, e.g., the number of behaviours being composed by a compo-sition relation; the number of dynamic interaction points connected to a component. 3) scenariosin which a concept must be able to handle various different interfaces, e.g., components can beconnected to static and dynamic interaction points; composition relations may compose mono-lithic and composed behaviours.

The number of scenarios in the first category is, in principle, infinite. Exhaustive testing in thiscase is impossible. However, testing the different possible scenarios in this category is usually notnecessary, because the implementation constructs that handle the different scenarios are simpleand consolidated. For example, operations on strings, integers and reals are usually handled byconsolidated code libraries or operating system functions. Therefore, the correct behaviour of theimplementation considering one scenario in this category strongly indicates the correctness of theimplementation. Scenarios in this category are usually related to data manipulation procedures,which is outside the scope of this investigation.

Scenarios in the second category are also potentially infinite. In this case, assuming that an algo-rithm used in the framework to handle this category of scenarios applies dynamic allocation ofresources to handle the undefined number of instances of the repetitive element, or use a safe limit

Page 216: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

198

Chapter 10: Correctness Assessment

for the number of instances, the following strategy can be adopted. As a pragmatic attitude to han-dle the infinite number of scenarios, the implementation can be tested, using scenarios which rep-resent border situations and some scenarios representing the common situations. Examples ofborder situations are the minimum and maximum number of instances of the repetitive element.This strategy is based on our testing experience but whether it is enough remains to be proved.

Tests on the third category of scenarios must be performed for each possible scenario. Each possi-ble interface requires a distinct treatment that should be evaluated. In our application domain, sce-narios in this category are limited to a few cases for all concepts and, therefore, do notcompromise the efficiency of the testing procedure.

Each specification of design concepts used in a protocol can be seen as a constraint applied to thebehaviour of a protocol that uses these concepts. These constraints are applied simultaneously.Since we have tested concepts separately, we should assess whether our approach also covers thesimultaneous application of these constraints. Considering that behaviours in this context arespecified in terms of independent and deterministic EFSMs, the issue here is to evaluate whethertesting concepts’ implementations separately corresponds to testing the implementation by con-sidering the simultaneous operation of the EFSMs of each concept. The simultaneous operationof state machines implies that all pseudo-events produced by the execution of the frameworkmust be simultaneously enabled by all state machines that apply restrictions to that pseudo-event.

Two characteristics of our testing approach must be considered to demonstrate that our testingapproach complies to the coverage requirement above: 1) the definition of different concepts mayinvolve different sets of events, also called the alphabet of the EFSM; 2) the tests of the imple-mentation of all concepts are performed using the same log, also called trace.

Our demonstration is based in the following law applicable to EFSMs and their languages. Pro-vided that A and B are independent and deterministic finite state machines, the set of all traces (t)such that t restricted to the alphabet of A belongs to the language of A, and t restricted to the alpha-bet of B belongs to the language of B, and t belongs to the conjunction of the languages of A and B,equals to the language of A fully synchronized with B [28]. A trace t restricted to a language Xresults in omitting all pseudo-events in t outside X. The conjunction of the languages X and Y is alanguage where all elements belong to X or belong to Y. This trace can be defined as:

The operator in this equation are:

A is fully synchronized with B s restricted to P the alphabet of A s is a member of P logical andP conjunction Qset of traces with elements in P

where, being P and Q sets of events, s a trace and A and B behaviours, xand y logical expressions,

traces A B||( ) t tΓαA( )( traces A( ) ) tΓαB( )( traces B( ) ) t αA αB∪( )Θ∈( )∧∈∧∈( ){ }=

A B||sΓPαA

s P∈x y∧P Q∪

Page 217: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.5 The Tester Program

199

This law guarantees that, assuming traces where all pseudo-events are related to at least one of theconcepts being tested, if tests applied to separated concepts C1 and C2, using a trace t, indicate acorrect implementation, then a test applied to the full synchronization of C1 and C2, using t, wouldalso indicate a correct implementation, and vice-versa.

10.5 The Tester Program

The Tester program automates our testing approach. This program is protocol-independent, con-cept-independent, and allows one to process the log file in a flexible way.

The Tester to test a framework independently of the protocol-specific code used to obtain an exe-cutable implementation. Different protocols use a different number of instances of concepts, com-bined in different ways. The Tester must be able to identify the different instances of the conceptbeing tested and their related pseudo-events. The Tester can be applied to test different designconcepts. In order to allow the flexible processing of a log-file, the Tester identifies in any log thepseudo-events that are relevant to a particular test.

10.5.1 Log and Pseudo-Events

A log consists of a sequence of recorded pseudo-events that happened during a certain period ofthe execution of a protocol that makes use of a framework. Each pseudo-event in this log consistsof a pseudo-event identifier and some parameters. Figure 10.3 shows the format used to recordpseudo-events of a log entry. The number of parameters in a log entry can vary. Our testing toolallows a maximum of five parameters, which has been defined based on the requirements of ourexperiments.

In Figure 10.3, pseudo_event_name is a string that uniquely identifies a pseudo-event, such as,e.g., component instantiation. The parameters are required to uniquely identify different instancesof the same pseudo-event. If a pseudo-event needs less than five parameters, the remainingparameters are ignored. The Tester program reads one pseudo-event per line and expects theparameters of a pseudo-event to be separated by spaces. Figure 10.4 shows how the pseudo-events in Figure 10.1 are defined to be manipulated by our Tester. Both pseudo-events contain asingle parameter corresponding to the identifier of the related interaction point.

pseudo_event_name parameter_1 parameter_2 parameter_3 parameter_4 parameter_5

Figure 10.3 Log format

Aip ip-id

Figure 10.4 Pseudo-event examples

Bip ip-id

Page 218: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

200

Chapter 10: Correctness Assessment

10.5.2 FSM Description

In order to be useful for testing the implementation of different concepts, the Tester reads thespecification of the concept to be tested from an FSM file. In this way, when we want to changethe concept to be tested, it is enough to provide a new FSM file, without having to recompile theTester program.

The notation to describe FSMs has been designed to comply with the following requirements: itshould be powerful enough, unambiguous and easy to process. The syntax of our notation isshortly described below.

Table 10.1 illustrates the notation used in the FSM-file to describe design concepts.

Table 10.1 shows the representation of the behaviour presented graphically in Figure 10.1, usingour notation,. The notation consists of a table where each line defines one transition of the statemachine and each column contains a particular information necessary in the definition of a transi-tion. The information in each column is identified in the heading. States and events are identifiedby strings of characters. We use capital letters for the identifiers of states and a capital letter fol-lowed by lower case for the identifiers of events. The transition related to the initial state definedin the first line of the table and the transition related to the final state is defined in the last line ofthe table. Other transitions can be defined in between. Information in column cond1 defines thecondition that guards a transition. In this example, no conditions guard the defined transitions.Information in column cond2 defines a condition to select pseudo-event instances. In this exam-ple, only instances of pseudo-events with ip-id equal to 1 would be tested. All the required infor-mation for a concept specification can be defined using this notation.

10.5.3 Tester Algorithm

This section describes how the Tester detects errors in the implementation of a design concept.Figure 10.5 summarises the data structures used by the testing algorithm.

The main data structures of the Tester program are FSM and conceptInstances. These structurescapture the FSM information and the state of execution of different instances of the concept beingtested, respectively. Most fields in the data structures correspond to the elements of the FSM fileand have already been discussed. The additional fields are:

• FSMVet: contains a list with the definition of each transition of the FSM data structure;

• FSMEvents: contains the list of pseudo-events controlled by the behaviour described inFSM;

• id: value that uniquely identifies an instance of a concept. This value is retrieved from the

Table 10.1 FSM-file syntax example

fromState event cond1 toState action cond2DISCONNECTED Aip CONNECTED (#1=1)CONNECTED Bip CONNECTED (#1=1)

Page 219: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.5 The Tester Program

201

first parameter of the pseudo-event that triggers a transition in the initial state of the FSM.

The algorithm for testing frameworks first loads the FSM-file into the FSM data-structure. At thismoment, FSMEvent is also filled with all pseudo-events that appear in the concept definition.Subsequently, the Tester starts reading the log-file.

Since a log may contain pseudo-events that are not related to any of the instances of the conceptbeing tested, for each pseudo-event in the log the Tester program verifies whether or not thispseudo-event concerns the concept being tested. The algorithm identifies these pseudo-events byverifying if they are in FSMEvents. If a pseudo-event is not found in FSMEvents it is discarded.

For each pseudo-event related to the concept being tested, the Tester evaluates whether thispseudo-event is allowed to happen in the current state of the system’s execution. Since the proto-col used in testing may use many instances of the concept being tested, the Tester evaluatespseudo-events considering each concept instance. Pseudo-events related to a certain concept arenot necessarily related to all instances of this concept, but must be related to at least one of itsinstances.

A pseudo-event is related to a concept instance when it is accepted by one of the transitions of theEFSM of this concept instance, i.e., the pseudo-event matches the field pseudo-event and theguarding condition cond2 of that transition. Whenever there is an occurrence of an instance of theinitial pseudo-event related to the concept being analysed and there is no entrance in conceptIn-stances corresponding to this instance, the Tester algorithm creates new items in conceptInstances.

A pseudo-event is allowed by the behaviour of a given concept instance if this pseudo-event trig-gers at least one transition in the FSMVet, using the context of this concept instance. A pseudo-event triggers a transition when it is the pseudo-event indicated in the field pseudo-event, and sat-isfies the conditions cond1 and cond2 of an item of the FSMVet.

An error is detected in the following circumstances:

fromState pseudo-event cond1 toState action cond2

id currentState vetVar vetSet

vector

FSMVet FSMInitialState FSMFinalState FSMEvents

FSM

conceptInstances

Figure 10.5 Tester data-structures

setlegend:

Page 220: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

202

Chapter 10: Correctness Assessment

1. an instance of a pseudo-event concerns a particular instance of the concept being tested, but does not trigger any one of the transitions of its FSM;

2. when the end of execution of the protocol is reached, i.e., at the end of the log, and a concept instance has not reached its final state.

The second error condition above is detected by testing if for all items of conceptInstances the cur-rentState is equal to the finalState of the concept’s specification. An error is indicated the first timethis condition is not satisfied.

Figure 10.6 presents the functioning of the Tester program using the UML Activity Diagram.

10.5.4 Tester Interface

In this section we discuss the interfaces we have developed for the Tester program. The purposeof these interfaces is to allow the user to monitor intermediary steps of the testing activity, allow-ing for debugging.

Figure 10.7 shows the main window, where the diagnosis is displayed. In this windows, the usercan choose to perform the test in a single step, by using the Execute button, or step by step, usingthe Step button. Messages are displayed in the bottom part of the window to inform the status ofthe testing process.

Figure 10.8 shows the window to manipulate the specification of the design concept, i.e., its FSM.This interface can be used as an editor since an FSM can also be create and saved using this inter-face. The name of the concept being described is displayed at the top of the window. The informa-tion fields Initial_state, Final_state and FSM events, are automatically derived from the FSMdefinition. The testing process can be controlled using the buttons Step and Resume. Messages aredisplayed at the bottom of the window to inform the status of the testing process and the opera-tions performed by the FSM.

Figure 10.9 shows the Log window, which displays the pseudo-events that have been treated bythe testing procedure. The name of the log-file must be entered in the Log file field. The testingprocess can be controlled using the buttons Step and Resume. Messages are displayed at the bot-tom of the window to inform the status of the testing process and operations with the log-file (sav-ing, loading).

Figure 10.10 shows the window used to check the values of the state variables for each instanceof the concept being tested. The concept instance intended to be closely examined is selected inthe Concept instance (id) field. Figure 10.11 shows the window that allows one to inspect sets.The testing process can be controlled using the buttons Step and Resume. Messages are displayedat the bottom of the window to inform the status of the testing process.

In these interfaces, all conditions are stated without space and fully parenthesized. Within theconditions we have operands and operators. Operands can be constants, variables, pseudo-eventsparameters, logic operations on sets, or a condition. Variables are identified by an “$” plus anumber. Pseudo-events parameters are identified by an “#” plus a number. Our sets contain inte-gers and are identified by an “@” plus a number.

Page 221: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.5 The Tester Program

203

Operators may be the logical operators “^”, “=”, “>”, and “<“, and are used to compare constants,variables and pseudo-events parameters. Operators may also be the boolean operators “|” (or) and“&” (and), operating conditions and set operations B and N. Operation “B[set_id, operand]”returns true if operand is in set_id; operation “N[set_id, operand]”, that returns true if operanddoes not belong to set_id; and operation L[set_id] return a constant corresponding to the length ofset_id.

load concept

read log item

[end of log]

prepare Testerget item of

[end of concept instances]

[pseudo-event related

[ transition triggered ]

[otherwise]

printdiagnosis

get item from conceptInstances

[concept instance

[end of concept instances]

final state]

[otherwise]

[ otherwise ]

specification

to monitor newconcept instance

conceptInstances

to concept instance but

error

currentState=

Figure 10.6 Tester’s Algorithm

get item ofFSMVet

[end of items]

[pseudo-eventbelongs to the current instanceof the concept]

evaluatetransition

set pseudo-eventas related to thisconcept instance

[otherwise]

[pseudo-eventnot related to this transition]

does not trigger a transition]

[otherwise]

[initial event][ otherwise ]

[pseudo-event contained in FSMEvents]

Page 222: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

204

Chapter 10: Correctness Assessment

Figure 10.7 Tester Main Window

Figure 10.8 Tester’s FSM Window

Page 223: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.6 Testing Case Study

205

The possible actions are: variable_id “+”, that increases 1 to the value of variable_id. variable_id“-”, which decreases 1 from variable_id; variable_id “=” operand, which sets the value ofvariable_id to the value of operand; “A( set_id,operand)”, which adds the value of operand toset_id; and “R(set_id,operand)”, which removes the value of operand from set_id. Multipleactions are allowed and are separated by a “;”.

10.6 Testing Case Study

In this section we apply our testing approach to two design concepts: choice behaviour compositionrelation and synchronous interaction. For each concept, we present the format of the pseudo-eventsrequired by the Tester to test the implementation of this design concept. This format is determinedby how we want to specify this concept in terms of a FSM. The concepts to be tested are firstintroduced informally. Afterwards we present the concept’s formal specification using a graphicalrepresentation for FSMs. Finally, we present the FSM specification using the syntax required bythe Tester program.

10.6.1 Choice Relation

The choice design concept illustrated in this section is a simpler form of the concept used in thedesign models supported by our framework examples, in the sense that only compositions ofmonolithic behaviours are supported. This simplification has been done to allow us to focus onthe specification process, without being distracted by the details of the concept’s semantics.

Figure 10.9 Tester’s Log Window

Page 224: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

206

Chapter 10: Correctness Assessment

Figure 10.10 Tester’s Variable Debugging Window

Figure 10.11 Tester’s Set Debugging Window

Page 225: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.6 Testing Case Study

207

The semantics of the deterministic choice relation can be defined as follows (see section 3.4.6): Ifn behaviours are in a choice composition, at the moment that one of them executes its first unit ofbehaviour, the remaining n-1 behaviours should no longer be performed, i.e., they are disabled.

We want to specify this behaviour in terms of conditional and ordered pseudo-events. Thesepseudo-events must provide enough information to monitor the behaviour of the implementationconsidering that different instances of the choice relation may be in use in the protocol implemen-tation being tested. The pseudo-events must provide the information that allows us to relate thepseudo-event to an instance of the behaviour concept. This is necessary in order to evaluatewhether or not pseudo-events are relevant in a given context.

Informal Description

Defining a pseudo-event UBE as being the execution of a unit of behaviour, a possible specifica-tion of the behaviour of the choice relation is:

Given that an instance of the choice relation (CR) composes a certain number of behav-iours, if a UBE happens, related to a unit of behaviour that belongs to one of the behav-iours (B) composed by CR, afterwards, only UBEs related to units of behaviour belongingto B can happen, regarding UBEs related to units of behaviour belonging to behaviourscomposed by CR.

Figure 10.12 shows the format of a pseudo-event that contains the information required by thespecification above. The parameters UB-id, behaviour-id and choice-id, identify the unit of behav-iour, the behaviour and the choice relation, respectively, that are associated to this pseudo-event.

Formal Description

The choice concept can be specified in terms of an FSM as shown in Figure 10.13. In the graphicalnotation for FSMs, a transition (tn) consists of a pseudo-event (e) that triggers the transition, acondition (c1) guarding the transition, a condition (c2) for the pseudo-event to be associated to aparticular instance of a concept, and an action (a) that must be executed when the transition istriggered. id is a field of the conceptInstances data-structure and its initialization is explained insection 10.5.3.

UBE UB-id behaviour-id choice-id

Pseudo-event

Figure 10.12 Format of the pseudo-event UBE

afterchoice

t0 t1

Figure 10.13 FSM for the choice behaviour

Page 226: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

208

Chapter 10: Correctness Assessment

The transitions shown in Figure 10.13 are detailed in Table 10.2.

The pseudo-event presented in Figure 10.12 has some drawbacks. The gathering of the informa-tion necessary to record this pseudo-event is not straightforward, e.g., it is difficult to identifywhich instance of the choice relation is associated to the behaviour to which the UBE belongs.This would require new methods in the framework to allow us to navigate through differentobjects. Besides that, the pseudo-event UBE is likely to require other attributes in other specifica-tions, such as, e.g., interaction means and communication primitive. In this case, too manyparameters being assigned to the same pseudo-event would produce redundant information, diffi-cult to be manipulated.

To solve these drawbacks, we distribute the required information over these pseudo-events. Apseudo-event can be used to identify the instantiation of a behaviour. We call this pseudo-eventpseudo-behaviour. This pseudo-event records the association with the choice relation through theparameter relation-id. The specification in Figure 10.13 abstracts from the identification of the dif-ferent instances of the choice concept possible in a protocol. A unique initial event must be pro-vided for that purpose. We define a pseudo-event pseudo-choice as being the initial pseudo-eventof this concept definition. A pseudo-choice contains as parameter a unique identifier for a choiceinstance. Figure 10.14 shows the format of these pseudo-events.

Figure 10.14 Pseudo-events format

Table 10.2 Transitions of the choice specification

t0 e : UBE

c1 : no restriction

c2 :(choice-id EQ id) {UBE is associated with a unit of behaviour that belongsto a behaviour B1, and B1 is related the choice relation id}

a : (chosen-behaviour = behaviour-id) {assigns the value of the parameterbehaviour_id to a variable called chosen_behaviour}

t1 e :UBE

c1 : (behaviour-id EQ chosen-behaviour) {UBE belongs to the behaviour whoseidentification is equal to chosen_behaviour}

c2 :(choice-id EQ id) {UBE is associated with a unit of behaviour that belongsto a behaviour B1, and B1 is related the choice relation R1}

a :no action

UBE UB-id behaviour-id

Behaviour behaviour-id relation-id

Pseudo-event Format

UBE

pseudo-behaviour

pseudo-choice Choice choice-id

Page 227: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.6 Testing Case Study

209

Figure 10.15 shows the specification of the choice behaviour using these additional pseudo-events.

Figure 10.15 Improved choice behaviour specification

This definition uses the following variables: id contains the identification of the concept instancebeing tested, relBehaviours is the set of behaviours related by choice id, and chosen is the identifica-tion of the chosen behaviour. The meaning of the transitions in Figure 10.15 are explained inTable 10.3:

Figure 10.8 shows the choice concept specification as seen with the Tester program using ourFSM notation. Figure 10.9 shows a log example of the execution of a protocol with one instanceof the choice relation composing two instances of behaviour. After both behaviours are instantiated,an UBE happens in one of the components and the execution finishes.

Table 10.3 Transitions of the improved choice specification

t0 e : Choice

c1 : no restriction

c2 : (choice-id EQ id)

a : no action

t1 e : Behaviour

c1 : no restriction

c2 : (relation-id EQ id)

a : A[relBehaviours,behaviour-id] {add behaviour-id to set of related behav-iours}

t2 e : UBE

c1 : no restriction

c2 : (B[relBehaviours,behaviour-id]) {behaviour-id belongs to the set of relatedbehaviours}

a : chosen=behaviour-id {assigns the value of behaviour-id to variable chosen}

t3 e : UBE

c1: (behaviour-id EQ chosen)

c2 : (choice-id EQ id)

a : no action

afterchoice

t2

t3behaviourt0

t1

instantiation

Page 228: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

210

Chapter 10: Correctness Assessment

Diagnosis

Since the sequence of pseudo-events shown in Figure 10.8 complies to the expected behaviourdefined in the FSM, the diagnosis given by the Tester program indicates a correct behaviour ofthe implementation, as illustrated in Figure 10.7. Figure 10.10 and Figure 10.11 show the Testerinterfaces for inspection of the context of the FSMs of each concept instance at any moment ofthe testing procedure.

We assume that a new pseudo-event UBE happens at the end of the execution scenario just pre-sented, with the following parameters:

UBE 137088 172605

This means that an UBE has happened in a behaviour that should have been disabled. Thispseudo-event concerns the design concept being analysed, since the pseudo-event is in the list ofevents (FSMEvents). It also concerns the concept instance being tested, since it matches theexpected pseudo-event and the cond2 of the fourth line of the FSM. The event, however, does nottrigger any transition of the FSM and this corresponds to one of the error conditions monitored bythe Tester. A message error as follows is displayed:

>> Execution error: UBE 137088 not expected in the current stateof execution of concept instance 166616.

In case an unexpected pseudo-event is found, the testing process finishes and the context varia-bles of the FSM associated to each concept instance are made available for inspection.

10.6.2 Synchronous Interaction

The type of synchronous interaction we want to test is the two-party value-passing interactionmechanism, which is the interaction mechanism supported by our frameworks. This mechanismis a specialization of the synchronous interaction introduced in chapter 3, where the interactionparticipation consists of an offer atomically followed by a corresponding acceptance. Due to thegap in abstraction level between this concept and the building blocks available in our implemen-tation environment, the implementation solution for this concept is not trivial. Therefore, the for-mal specification of this concept is particularly relevant in our work, besides being appropriate toillustrate the testing approach.

The characteristics of this concept that are relevant to be described are synchronism and atomic-ity. Synchronism implies that units of behaviour involved in an interaction are triggered simulta-neously. Atomic interactions consists of extending the atomicity of a unit of behaviour to the twounits of behaviour participating in the interaction.

The pseudo-events used in the definition of the interaction concept are based in the followingconcepts: component, unit of behaviour, interaction point instantiation, interaction offer, interactionacceptance, condition and action. Figure 10.16 illustrates the relation between these concepts. Weillustrate a value-passing from component A to component B. An interaction involves two units ofbehaviour belonging to each one of the communicating components. The triggering event in theseunits of behaviour are an interaction offer and an interaction acceptance in the send and receiving

Page 229: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.6 Testing Case Study

211

components, respectively. The interaction point IP is the conceptual element that performs theinteraction.

Informal Specification

Suppose C represents a component, IP represents an interaction point, UB represents an unit ofbehaviour, A represents an action, IO(IP) represents an interaction offer executed in IP and IA(IP)represents an interaction acceptance executed in IP. Assuming that C1 and C2 are two componentsconnected by an interaction point IP1, UB1 belongs to C1 and UB2 belongs to C2, A1 and A2 belongto UB1 and UB2, respectively. A possible specification for the interaction concept is:

At least one IO(IP1) must happen before an IA(IP1) can happen. Many IO(IP1) can happenbefore an IA(IP1) happens. In between the occurrence of the last IO(IP1) and the occur-rence of the corresponding IA(IP1), no other IO(IPx), IA(IPx) or A related to C1 or C2 (for xdifferent from 1) can happen (synchronism). Once IA(IP1) has happened, other IO(IPx),IA(IPx) or Az related to C1 or C2 (for any x and for any z different from 1 and 2) can onlyhappen after A1 and A2 have been performed in any order (atomicity).

Below we illustrate two cases of incorrect behaviour according to the specification above:

• {IO(IP1), IO(IP2), IO(IP1), A3, IA(IP1)} where A3 belongs to C1 and IP2 is related to C1, is a viola-tion of the synchronization characteristic;

• {IO(IP1), IA(IP1), A1,A3,A2} where A3 belongs to C1, is a violation of the atomicity characteristic.

Formal specification

The pseudo-events required in this specification are presented in Figure 10.17.

In Figure 10.17, the pseudo-event interaction-participation is used to represent interaction-offersand interaction acceptances. comp1-id, comp2-id and comp-id identify the communicating compo-

component Aunit of behaviour

IP(int-offer,condition,action)

component Bunit of behaviour(int-accept,condition,action)

Figure 10.16 Conceptual elements in the definition of an interaction

PA PA-id comp-id IP-id UB-id type

Pseudo-event Format

interaction-participation

ip-instantiation IP IP-id comp1-id comp2-id

pseudo-action Action PA-id comp-id UB-id

Figure 10.17 Interaction related pseudo-events

Page 230: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

212

Chapter 10: Correctness Assessment

nents. IP-id identifies the interaction point being used in the interaction. PA-id identifies the relatedinteraction participation. type identifies the interaction participation as being an interaction-offer,an interaction acceptance or a timeout.

The variables used in this specification identify:

• id : the instance of the concept being tested (see section 10.5.3);

• last-io : the UB related to the last interaction offer ;

• current-ia : the UB related to the last interaction acceptance;

• comp1 : one communicating component;

• comp2 : another communicating component;

• first-action : the first action belonging to the interaction.

Figure 10.18 shows the FSM that specifies the behaviour of the interaction concept.

The transitions shown in Figure 10.18 are explained in Table 10.4:

Table 10.4 Transitions of the interaction specification

t0 Initialization of a new instance of IP

e : IP

c1 : no restriction

c2 : (IP-id EQ id)

a : comp1=comp1-id;comp2=comp2-id;last-io=0;current-ia=0;first-action=0 {ini-tialization of the required variables}

t1 Interaction offer in the current IP instance

e : IA

c1 : (type EQ “offer”)

c2 : (IP-id EQ current-ip)

a :last-io = UB-id {records the UB related to the last interaction offer}

t2 Interaction participations not related to the current interaction point

t0

t4

t5

t6

acting2acting1

Figure 10.18 Interaction concept’s behaviour

t2 | t3

t1idle

synchro t1t2 | t3

Page 231: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.6 Testing Case Study

213

Figure 10.19 shows the specification of the interaction concept using the Tester notation. The var-iables of this specification are: comp1 ($1), comp2 ($2), last-io ($3), current-ia ($4) and first-action($5).

e : IA

c1 : no restriction

c2 : (((comp-id EQ comp1) OR (comp-id EQ comp2)) AND (IP-id NE current-ip))

a : no action

t3 Pseudo-actions not related to the current interaction

e : Action

c1 : no restriction

c2 : (((comp-id EQ comp1) OR (comp-id EQ comp2)) AND (IP-id NE current-ip))

a : no action

t4 Interaction acceptance related to the current interaction

e : IA

c1 : ((last-io NE 0) AND (type EQ “accept”))

c2 : (ip EQ current-ip)

a : current-ia = UB-id

t5 Pseudo-action related to one of the components involved in the currentinteraction

e : Action

c1: ((UB-id EQ last-io) OR (UB-id EQ current-ia))

c2 : ((comp-id EQ comp1) OR (comp-id EQ comp2))

a : (first-action = PA-id)

t6 Pseudo-action related to one of the components involved in the currentinteraction

e : Action

c1 : (((UB-id EQ last-io) OR (UB-id EQ current-ia)) AND (PA-id NE first-action))

c2 : ((comp-id EQ comp1) OR (comp-id EQ comp2))

a : last-io=0;current-ia=0;first-action=0

Table 10.4 Transitions of the interaction specification

Page 232: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

214

Chapter 10: Correctness Assessment

10.7 Conclusions

We have presented in this chapter a testing approach for the frameworks used in our protocolimplementation approach. The testing approach presented here is applicable to assess the correct-ness of the implementation of behavioural concepts and consistency rules of the design modelsupported by a framework.

We have addressed the testing of design constructs at a fine level of granularity that are muchsimpler than the behaviour of complete protocols. This simplicity allows us to improve the cover-age and efficiency of the testing process compared to the behaviour of complete protocols. Wehave also presented some guidelines to select the concepts to be tested and to select the scenariosin which concepts should be tested, in order to improve the efficiency of the testing process. Thistesting approach also contributes to the efficiency of the protocol development process as awhole, in the sense that the testing effort is reused in the development of particular protocols.

In the examples of tests presented in this chapter, the definition of pseudo-events in term of theirparameters only considers the requirements of these particular test. Consistency rules applicableto the implementation level of our application domain could also have a specification to allowsome testing. For example, the implementation of buffers manipulation must obey some rules inorder to be consistent. An study to improve this aspect of this testing approach remains as subjectfor further research. Another issue in our method approach that requires further investigation is anmethod to limit or handle the framework code intrusion due to code for log generation.

The results we have reached here on framework testing are within the goal of these thesis of pro-viding a flexible approach to address the requirements of the protocol development process. Theapproach is flexible in the sense that it can be tuned to enforce specific strategic requirements of

fromState p-event cond1 toState action cond2

INICIAL IP () IDLE $1=#2;$2=#3; (#1=id)$3=#0;$4=#0;$5=#0;

IDLE Action () SYNCHRO ; (((#2=$1)|(#2=$2))&(#3^id))

SYNCHRO Action () IDLE ; (((#2=$1)|(#2=$2))&(#3^id))

IDLE IA () SYNCHRO ; (((#2=$1)|(#2=$2))&(#3^id))

SYNCHRO IA () IDLE ; (((#2=$1)|(#2=$2))&(#3^id))

IDLE IA (#5=1) SYNCHRO $3=#4; (#3=id)SYNCHRO IA (#5=1) SYNCHRO $3=#4; (#3=id)SYNCHRO IA (($3^0)&(#5=2)) ACTING1 $4=#4; (#3=id)ACTING1 Action ((#4=$3)|(#4=$4)) ACTING2 $5=#1; ((#2=$1)|(#2=$2))ACTING2 Action (((#4=$3)|(#4=$4)) SYNCHRO $3=#0;$4=#0; ((#2=$1)|(#2=$2))

&(#1^$5)) $5=#0;

Figure 10.19 Interleaving specification

Page 233: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

10.7 Conclusions

215

the protocol development process. For example, coping with more or less strict requirements oncorrectness assessment can be reached varying the coverage of the test in terms of the number ofconcepts and scenarios being tested.

Page 234: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

216

Chapter 10: Correctness Assessment

Page 235: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

217

Chapter 11

Conclusions

This chapter summarizes the most important conclusions reached throughout our research. Thechapter also evaluates the extent to which our goals have been accomplished, and gives ideas forfuture work.

The structure of this chapter is the following: section 11.1 presents our general conclusions; sec-tion 11.2 presents an evaluation of our results and section 11.3 enumerates some possible itemsfor future work.

11.1 General Conclusions

In this thesis we show that the use of frameworks is suitable as a basic implementation techniqueto support a model-based approach to implement protocols. In order to apply frameworks effi-ciently in the protocol implementation process, the frameworks should capture the design con-cepts used in the specification of these protocols. Furthermore, one has to define techniques thatallow protocol-specific functionality to be added to the frameworks, generating specific protocolimplementations.

The use of frameworks according to the approach advocated in this thesis provides elegant imple-mentations and efficient implementation processes. The elegance of the implementations resideson the clear mapping between the specification structure and the implementation structure, withbenefits for maintenance. The efficiency of the implementation process is boosted by ourapproach, since, once a framework is available, one can quickly develop correct implementationcode for a specific protocol.

Our major contribution to the implementation process has been the integration of formal designtechniques with software techniques, which has been possible by using frameworks in this partic-ular way. We have defined a method to develop frameworks that results in frameworks thatenforce the desired increase in flexibility and efficiency of the protocol implementation process.

In this work we considered two design approaches: protocol design based on formal models andobject-oriented software design. Our contribution has been in the integration of these two

Page 236: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

218

Chapter 11: Conclusions

approaches and their proper positioning in an overall design and implementation strategy for pro-tocols. Frameworks have formed the bridge between these two approaches, since they support thedesign models in the software architecture. This allows a smooth transition from one approach tothe other, making them complementary as desired.

Our method has been validated though a number of actual implementations of the proposed solu-tions, which have been made publicly available at the Web site of our research group. Theseimplementations can be inspected and evaluated for performance and code complexity.

Inevitably, due to the vast diversity of formal models for protocol design and software develop-ment techniques, our study had to be limited to a couple of techniques of both domains. Thesetechniques have been selected by considering the current state-of-the-art and the relevance of thetechniques in the development trajectory for protocols. In this way we believe we have produced,introduced and worked out practical ideas that can be used in practice in a large number of proto-col implementation projects.

11.2 Evaluation of Results

We have investigated in our research the potential benefits of the use of frameworks by consider-ing three major goals of the protocol implementation process:

1. support to different design models for protocol specification in the implementation process;

2. development of solutions that are applicable in different implementation environments;

3. flexibility in the choice of trade-offs between requirements such as implementation correct-ness, speed of the implementation process and other aspects of software quality.

Each one of these potential benefits is evaluated in the sequel.

11.2.1 Various Design Models

In theory one could build a single framework to support a variety of design models. However,this increases substantially code complexity, proportionally to the number of concepts and theirvariations supported by the framework. Such increase in complexity is more critical in case theframework also has to support the choice between conflicting variations of concepts. For exam-ple, a framework may have to be parameterized in order to support choices between different con-sistency rules for different sets of slightly varying of design concepts.

Although one is forced to build a framework for each design model, the use of frameworks stillsimplifies the implementation of complex protocols, making it much simpler than implementingthese protocols from scratch. Furthermore, a framework implementation can be seen as a reusableprogramming effort.

Our contribution in this aspect has been our method to develop frameworks, which prescribes asystematic way to analyse design models and build implementation solutions for the functionalrequirements imposed by these models.

Page 237: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

11.3 Future Work

219

11.2.2 Different Implementation Environments

Using an implementation method based on frameworks, once a framework for a design model in acertain implementation environment is available, any protocol implementation derived from aspecification in this design model would be automatically ported to that environment. This makesit necessary to build the implementation code of the frameworks with portability in mind, whichcould be done, e.g., by using pre-compilation macros.

The initial steps of our method to develop frameworks results in a software architecture thatabstracts from implementation details. This software architecture can be coded in subsequentdevelopment steps by using different implementation languages running in different implementa-tion environments. In this sense our method takes into account of implementation environmentindependence. However, in our experiments we have not considered code portability and ratherconcentrated on the most relevant functional issues.

11.2.3 Flexibility of Requirements

The availability of a catalogue of frameworks in which each framework supports a different trade-off between requirements, enables a flexible protocol implementation method. Developers canchoose between different implementation solutions that give implicitly higher priority to somerequirements and lower priority to others. In case available frameworks fail to satisfy the systemrequirements, e.g., due to unsatisfactory trade-off between requirements, one may decide toimplement a new framework. The trade-off among requirements in this case is largely defined bythe framework development method applied.

Our method to develop frameworks apply software engineering techniques to produce code thatcomplies to software quality requirements. The domain analysis and software architecture defini-tion steps of our method have been discussed in detail and properly illustrated in this thesis, and assuch they can be used as example in the development of other frameworks. We have also devel-oped a tool to perform tests on frameworks in order to assess their correctness. Furthermore, wehave made some framework implementations publicly available. These frameworks can beapplied to implement protocols or can be reused in the prototyping of new enhanced frameworks.

Our method for developing frameworks partlies relies on heuristics when building implementa-tion solutions. Although our framework development method gives guidelines for the develop-ment process, creativity is still essential and plays an important role in the development ofimplementation solutions.

11.3 Future Work

Although we have striven to cover a large number of issues in the protocol implementation proc-ess, this problem domain is quite complex and extensive. Below we point out some issues thatcould be addressed in order to improve the completeness and consistency of our work.

Our protocol development method could be extended in order to support more strict real-timerequirements. Techniques for implementing data types and their manipulations could also be

Page 238: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

220

Chapter 11: Conclusions

incorporated in our method. These techniques are particularly important in the implementation ofcoding and decoding functions for protocol data units.

Some work could be done in order to fill in the catalogue of frameworks introduced in Chapter 2.This implies in the development of frameworks for other design models, and considering otherimplementation solutions. A particularly interesting design model that could be supported by aframework has been described in [58] and [23].

Our testing strategy could be improved in the following ways:

• some theory could be developed to define a formal mapping between design concepts andtheir implementations in terms of pseudo-events in the frameworks. This theory could beused to improve the correctness of the testing strategy;

• the generation of execution logs could be improved by using a more systematic approach;

• the testing process of individual protocols (e.g., in terms of abstract test cases) could be inte-grated with our testing strategy.

The general purpose implementation components could be implemented to supply coarse granu-larity building blocks for protocol implementation. These components could implement typicalprotocol functions, such as the ones discussed in Chapter 4. The use of such components wouldpotentially improve even more the implementation process.

The trade-off between the performance of the resulting protocol implementations and the preser-vation of specification structure in the implementation could be evaluated using analythic models.This evaluation could give objective indications on the benefits and drawbacks of structure pres-ervation in implementations, which could then help in the choice of implementation structure.

It would also be interesting to evaluate the applicability of the techniques developed in this thesisto build applications on top of middleware platforms like, for example, CORBA.

Page 239: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

221

References

[1] M. Abadi and L. Cardelli. A theory of objects. David Gries and Fred B. Schneider (eds.), Monographs in Computer Science, Springer-Verlag, Inc, New York, 1996.

[2] A. Ananthaswamy. Data communications using object-oriented Design and C++. McGraw-Hill, USA, 1995.

[3] C. B. Barbosa, L. Ferreira Pires and M. van Sinderen. Frameworks for protocol im-plementation. In Simpósio Brasileiro de Redes de Computadores, Rio de Janeiro, 16th, May 1998.

[4] C. B. Barbosa and L. Ferreira Pires. Developing frameworks for protocol implemen-taiton, In Proceedings of the IEEE - International Conference on Software in Tele-communications and Computer Networks, 3rd, Split, Croatia, 1999.

[5] F. Belina, D. Hogrefe and A. Sarma. SDL with applications from protocol specifica-tion. Prentice Hall International, UK, 1991.

[6] P.A. Bernstein. Middleware: A model for distributed system services. Communica-tion of the ACM, 39(2):86-98, February 1996.

[7] G.V. Bochmam. Finite state description of communication protocols. Computer Net-works 2, 361-378, October 1978.

[8] T. Bolognesi, D. Frutos, R. Langerak and D. Latella. Correctness preserving trans-formations for the early phases of software development. In [9].

[9] T. Bolognesi, J. van de Lagemaat and C.A. Vissers (ed.). LOTOSphere: Software de-velopment with LOTOS. Kluwer Academic Publishers, the Netherlands, 1995.

[10] G. Booch. Object-oriented analysis and design with applications. The Benjamin/Cummings Publishing Company, Inc., California, USA, 1994.

[11] R. Booth, K. Turner and V. Jones. Formal methods for communications systems de-velopment-the ESPRIT Project LOTOSphere, BT Technology Journal, 10(2), Appril 1992.

[12] D.F. Box, D.C. Schmidt and T. Suda. ADAPTIVE - An object-oriented Framework for flexible and adaptive communication protocols. In Proceedings of IFIP confer-ence on high performance networking, Liège, Belgium, 4th, December 1992.

[13] S. Budkowski. Estelle development toolset (EDT). Computer Networks and ISDN Systems 25, pages 63-82, 1992.

[14] D. W. Bustard, A. C. Winstanley, M. T. Norris, R. A. Orr and S. Patel. Graphical views of process-oriented specifications. In K. J. Turner, (ed.), Formal Description Techniques, Proceedings of the International Conference on Formal Description Techniques, 1st, North-Holland, 1989.

[15] CCITT. Specification and Description Language (SDL). Recommendation Z.100, March 1993.

Page 240: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

222

References

[16] D.D. Clark. The design philosophy of the DARPA Internet protocols. In Proceedings of the SIGCOMM’88 Symposium, August 1988.

[17] H. Custer. Inside Windows NT. Microsoft Press, Redmond, Washington, 1993.

[18] P. Dembinski and S. Budkowski. The specification language Estelle. North Holland, 1989.

[19] H. Ehrig and B. Mahr. Fundamentals of algebraic specification 1. EATCS Mono-graphs on Theoretical Computer Science, 6, Springer-Verlag, Berlin, 1985.

[20] P. van Eijk. The LOTOSphere integrated tool environment: Lite. In K. Parker and G. Rose, (eds.). Formal Description Techniques, North-Holland Publishing Company, 4th, 1992.

[21] M.E. Fayad and R.E. Johnson. Domain-specific application frameworks. John Wiley & Sons, Inc., 2000.

[22] L. Ferreira Pires. Protocol design. Lecture notes, University of Twente, Enschede, the Netherlands, March 1998.

[23] L. Ferreira Pires. Architectural notes: a framework for distributed systems develop-ment. Ph.D. Thesis, University of Twente, Enschede, The Netherlands, 1994.

[24] M. Fowler and K. Scott. UML distilled - applying the standard object modeling lan-guage. Addison-Wesley, 1997.

[25] E. Gama, R. Helm, R. Jonson and J. Vlissides. Design patterns: elements of reusable object-oriented software. Addison-Wesley Publishing Company, 1994.

[26] C.A. Gunter and J.C. Mitchell. Theoretical aspects of object-oriented programing: types, semantics, and language design. The MIT Press, USA, 1994.

[27] D. Harel. Statecharts: a visual formalism for complex systems. Science of Computer Programming 8, 231-274, 1987.

[28] C.A.R. Hoare. Communicating sequencial processes. Prentice-Hall International, Englewood Cliffs, 1985.

[29] G.J. Holzmann. Design and validation of computer protocols. Prentice-Hall Inter-national Editions, London, 1991.

[30] G.J. Holzmann. Tracing protocols. AT&T Technical Journal 64, pages 2413-2434, December 1985.

[31] http://www.informatik.hu-berlin.de/Institut/struktur/systemanalyse/SITE/SDL-tools.html

[32] N. C. Hutchinson and L. L. Peterson. The x-Kernel: an architecture for implementing network protocols. IEEE Transactions on Software Engineering, 17(1):64-76, Janu-ary 1991.

[33] International Organization for Standardization. Guidelines for the application of Es-telle, LOTOS and SDL. ISO/IEC TR 10167. Geneva, Switzerland, 1990.

[34] International Organization for Standardization. Basic reference model. ISO/IEC 7498, 1984.

Page 241: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

223

[35] International Organization for Standardization. Estelle - a formal description tech-nique based on an extended state transition model. ISO/IEC 9074, Geneva, 1989.

[36] International Organization for Standardization. LOTOS - a formal description tech-nique based on the temporal ordering of observational behaviour. ISO/IEC 8807, Geneva, 1989.

[37] International Organization for Standardization. OSI conformance testing methodolo-gy and framework, 1990. International Standard 9646.

[38] ISO/IEC JTC1/SC21/WG7. Enhancements to LOTOS. December 1997.

[39] I. Jacobson, G. Booch and J. Rumbaugh. UML - the unified software development process. Addison-Wesley, Reading, Massachusetts, 1999.

[40] R.E. Johnson. Frameworks = (components+patterns). Communications of the ACM, 40(10):39-42, October 1997.

[41] V. Jones. Realization of CCR in C. In [9].

[42] P. W. King. Formalization of protocol engineering concepts. IEEE transactions on computers, 40(4):387–403, April 1991.

[43] H. Kremer. Protocol implementation. Ph.D. Thesis, University of Twente, Ensch-ede, The Netherlands, 1995.

[44] M. Kusick, K. Bostic, M. J. Karels and J. S.Quarterman. The design and implemen-tation of the 4.4BSD operating system. Addison-Wesley, 1996.

[45] L. Leonard and G. Leduc. An introduction to ET-LOTOS for the description of time-sensitive system. Computer Networks and ISDN Systems, 29(3):271-292, 1997.

[46] J.A. Mañas. Getting to use the LOTOSPhere Integrated Tool Environment (LITE). In [9].

[47] R. Milner. A Calculus of Communicating Systems. Lecture Notes in Computer Sci-ence, Springer-Verlag, 1980.

[48] T. J. Mowbray and R. Zahavi. The essential CORBA: systems integration using dis-tributed objects. New York [ect.]:Wiley, 1995.

[49] J. T. Moy. OSPF-anatomy of an Internet routing protocol. Addison-Wesley, Massa-chusetts, 1998.

[50] G. W. Neufeld and Y. Yang. The design and implementation of an ASN.1 - C com-piler. IEEE Transactions of Software Engineering, 16(10):1209-1220, October 1990.

[51] C. J. Northrup. Programming with Unix threads. John Wiley & Sons, Inc., New York, 1996.

[52] S. Oaks and H. Wong. Java Threads. O’Reilly & Associates, Inc., 1997.

[53] ONC+ developers’s guide. Solaris 2.5 Software Developer AnswerBook.

[54] OSPF Version 2, RFC 2178. (http://www.landfield.com/rfcs/rfc2178.html)

[55] T. Plagemann, B. Plattner, M. Vogt and T. Walter. A model for dynamic configura-tion of light-weight protocols. In Proceedings of IEEE Workshop on Future Trends

Page 242: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

224

References

of Distributed Computing Systems, Taipei, Taiwan, 3th, April 1992.

[56] T. Plagemann. A framework for dynamic protocol configuration. PhD Thesis, Swiss Federal Institute of Technology Zurich (Diss. ETH No. 10830), Zurich, Switzerland, September 1994.

[57] IEEE POSIX Threads. IEEE Std 1003.1c-1995

[58] D. A .C. Quartel. Action relations - basic design concepts for behaviour modelling and refinement. Ph.D. Thesis, University of Twente, Enschede, The Netherlands, 1998.

[59] S. Rago. Unix System V network programing. Addison-Wesley, Reading, MA, 1993.

[60] Rational UML Web-site. http://www.rational.com/uml/index.jtmpl

[61] J. Rumbaugh, M. Blaha, W. Premerlani, F. Eddy and W. Lorensen. Object-oriented modeling and design. Prentice Hall, New York, 1991.

[62] D. C. Schmidt. The Reactor - An Object-Oriented Interface for Event-Driven UNIX I/O Multiplexing. C++ Report 5, February 1993.

[63] D. C. Schmidt. ACE: an object-oriented framework for developing distributed appli-cations. In USENIX Association USENIX C++ Technical Conference. Cambridge, Massachusetts, April 1994.

[64] D. C. Schmidt and M. E. Fayal. Lessons learned building reusable OO frameworks for distributed software. Communications of the ACM, 40(10):85-87, October 1997.

[65] R. Schreiber. Middleware demystified. Datamation 1, pages 41-45, April 1995.

[66] R. Sharp. Principes of protocol design. Prentice-Hall, Great Britain, 1994.

[67] R. Sijelmassi. An object-oriented model for Estelle and its Smaltalk implementation. Technical Report NCSL/SNA-89/7, National Institute of Standard and Technology (NIST), Gaithersburg, MD 20899, USA, February 1989.

[68] R. Sijelmassi and B. Strausser. The distributed implementation generator: an over-view and user guide. Technical Report NCSL/SNA, Gaithersburg, USA, 1991.

[69] M. van Sinderen, L. Ferreira Pires, C. A. Vissers and J.-P. Katoen. A design model for open distributed processing systems. Computer Networks and ISDN Systems 27, pages 1263-1285, 1995.

[70] R. Sisto, L. Ciminiera and A. Valenzano. A protocol for multirendezvous of LO-TOS processes. IEEE Transactions on Computers, 40 (1):437-447, April 1991.

[71] Sun Microsystems. Solaris X Windows System Developer’s Guide.

[72] W.R. Stevens. Unix network programming. Prentice Hall, Englewood Cliffs, NJ, Second Edition, 1997.

[73] M. Subramanian. Network managment: principles and practice. Addison-Wesley, New York, 2000.

[74] Sun Microsystems. Network interfaces programmer’s guide. Chapter 6, TLI Inter-face, 1992.

Page 243: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

225

[75] C. Szyperski. Component software: beyond object-oriented programming. Addison-Wesley, England, 1997.

[76] A. S. Tanenbaum. Operating systems: design and implementation. Prentice-Hall, Inc., New Jersey, 1987.

[77] Telelogic Tau SDL Suite. http://www.telelogic.se/SDL/default.asp

[78] S. A. Thomas. IPng and the TCP/IP protocols. Wiley Computer Publishing, New York, 1996.

[79] J. Tretmans. A formal approach towards conformance testing. PhD thesis, University of Twente, Enschede, The Netherlands, December, 1992.

[80] Frameworks for Protocol Implementation. http://wwwtss.cs.utwente.nl/~arch/bar-bosa/thesis

[81] K. J. Turner (ed.). Using formal description techniques: an introduction to Estelle, LOTOS and SDL. John Willey & Sons, 1993.

[82] C. A.Vissers, et al. The architectural design of distributed systems. Lecture Notes, University of Twente, Enschede, The Netherlands, 1995.

[83] G.R. Wright, W. R. Stevens. TCP/IP illustrated, Volume 2: the implementation. Ad-dison Wesley, Massachusetts, October, 1997.

[84] F. Xia. What’s wrong with software engineering reseach methodology. ACM SIG-SOFT, 23(1):62-65, January 1998.

Page 244: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

226

References

Page 245: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

A.1 Global Structure

227

Appendix A

This Appendix presents the protocol we use as example in chapters 5 to 7. It is a symmetric sendand receive protocol. The receiving of a message is confirmed and the message is retransmitted incase the confirmation do not arrive within a certain period of time. This protocol is intentionallysimple, in order to be easily understood and to allow us to focus on its implementation process,which is our final goal. Although simple, this protocol has been designed making use of all designconcepts we want to support in our frameworks.

The structure of this appendix is: section A.1 presents the service description; section A.2presents the protocol description, section A.3 describes the lower level service definition, sectionA.4 describes the flow of messages in the interaction points, section A.5 describes the lower leverservice use by the send/receive protocol, and section A.6 describes the protocol configurationinformation.

A.1 Global Structure

In Figure A.1 we show the global structure of our protocol example.

The protocol structure in Figure A.1 shows the two symmetric entities that communicate througha lower level service. The internal structure of a protocol entity consists of three functions: send,receive and pduHandler. These three functions execute in parallel and synchronize through internalinteraction points.

lower level service

send receive

user 1 user 2

entity entity

SRSAP - send/receive service access point

SRSAP

LLSAP

LLSAP - lower level service access point

ip1

ip2

ip3 ip4pduhandler

Figure A.1 Protocol global structure

Page 246: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

228

Appendix A

A.2 The Send/Receive Service

The Send/Receive service has got two service primitives:

• Data Request: this primitive is used by the service user to send a message to the partner pro-tocol entity. It has as parameter the user message.

• Data Indication: this primitive is used by the service to deliver messages sent by the partner protocol entity. Its parameter is the sent message.

The service guarantees the delivery of messages at least once and in the same order the messagesare sent.

A.3 The Send/Receive Protocol

The protocol data units used by this protocol are:

• data_pdu: used to send data.

• answer_pdu: used to confirm the receiving of a message.

Figure A.2, Figure A.3 and Figure A.4 describe the behaviour of each element of this protocol,i.e., the Send, Receive and pduHandler functions, respectively. Behaviour descriptions are basedon the principle of finite state machines.

pdu_id pdu_size data

1 octet 1 octed max 255 octets

pdu_id

1 octet

send

dataReq

data

wait

to

ack/a1

Send

Figure A.2 Behaviour of Send protocol element

idle

Page 247: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

A.3 The Send/Receive Protocol

229

The meaning of the events triggering transitions in Figure A.2 to Figure A.3 are:

• dataReq: Send/Receive Service data request

• dataInd: Send/Receive Service data indication

• udp-DI: LLS data indication

• udp-DR: LLS data request

• data: internal data forward

• ack: communication acknowledgement

The meaning of the actions related to transitions in Figure A.2 to Figure A.3 are:

• a1: release information buffer

• a2: decode PDU

• a3: code PDU

• a4 release PDU buffer

normal

receive

data

ack

Receive

sen-ack

dataInd

Figure A.3 Behaviour of Receive protocol element

waiting

sending

pduHandler

udp-DI /a2

ack

data

ack/a3

data/a3

udp-DR /a4

Figure A.4 Behaviour of PduHandler protocol element

receiving

Page 248: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

230

Appendix A

A.4 Messages Flow

The communication primitives that can be exchanged through each interaction points and theirallowed direction are described in the sequel:

• IP1: dataReq (user->send); dataInd (receive->user)

• IP2: udp-DR (pduHandler->LLS); udp-DI (LLS->pduHandler)

• IP3: data (send->pduHandler); ack (receive<->pduHandler)

• IP4: data (pduHandler->receive)

A.5 Lower Level Service

The lower level service provides a connectionless and unreliable communication service. Mes-sages may be lost, but not corrupted. Source and destination addresses are configured in the LLSinitialization. The service primitives are:

• Data Request (message): sending of a message.

• Data Indication (message): message delivery.

A.6 Configuration Information

The Send/Receive protocol entities receive its LLS address, the LLS address of the partner entityand the host name of the partner entity as parameter when the entity is initialized.

Page 249: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.1 Basic Event Manager Framework

231

Appendix B

This appendix presents the implementation templates used with each one of the framework exam-ples presented in chapter 5 to 7. Each template consists of a header file and a body file. The imple-mentation language used in these templates is C++. The parts of the template that must bereplaced with protocol specific code are enclosed by the characters “< >”.

B.1 Basic Event Manager Framework /* * Templates for Implementing Protocols Using the * Basic Event Manager Framework * Header file */

// Constants Definition (1)// States#define <SIMBOLO> <CONSTANT>

// Service Primitives#define <SIMBOLO> <CONSTANT>

/*------------------------------------------------------*/// Including framework header #include "/<framework path>/pienv.h"

/*------------------------------------------------------*/ // Specialization of eventPoints (2)// Environment specific specializations (2.1)// Header of specialization classes (2.1.1)

class <class_name> : public external{public: <class_name>(int,eventsManager*); int ReadData(); int SendData(int,char*); virtual int CallEH(){return 0;}private: <required attributes>};

/ Protocol specific specializations (2.2)// Event Point header (2.2.1) class <interaction point name>: public <external specialization>

{ public:

<interaction point name>(<required parameters>, eventsManager* em):

<abstract eventPoint specialization>(<required parameters>,em){} virtual int CallEH();

};

Page 250: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

232

Appendix B

*------------------------------------------------------*/

/ Specialization of required eventHandlers (3)// EventHandler Header (3.1)

class <component> : public eventHandler { public:

<component>(<required parameters>, <references to connected interaction points>,

eventsManager*); ~<component>(){} int Interact(eventPoint*,int,int);

private: <interaction points references>;

char *_msg; <other behaviour context attributes>;

}; /*------------------------------------------------------*/

// Definition of initialization class (4)// Class Header (4.1)

class ENTITY { public:

ENTITY (<required parameters>); ~ENTITY (){}

}; /* * Template for protocol implementation using de * Basic Event Manager Framework * Body file */

#include "<header file name>"

*------------------------------------------------------*/

// Specialization of external class for the required interaction points (2)// Environment specific specializations (2.1)

// Class Construct (2.1.2)<external_specialization>::<external_specialization>(<required parameters>,eventsManager* em):exter-

nal(em){

<store configuration parameters>; <open interface handler>; _waitSynchr=1;}

// Overload of ReadData Method (2.1.3)int <external_specialization>::ReadData()

{if (!_msg)

{

Page 251: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.1 Basic Event Manager Framework

233

_msg=new char[80];<get data from buffer>;_cp=<communication primitive>;_msg=<data>;};

if (!CallEH()){_waitSynchr=0;return 0;}

else{_eh->InterInd();_msg=NULL;_cp=0;return 1;};

}

// Overload of SendData (2.1.4)int <external_specialization>::SendData(int cp,char *d){ char aux[BUFFERSIZE]; <send cp and d as a single string through the interface>; return 1;}

// Protocol Specific Specializations (2.2)// CallEH Method definition (2.2.2)

int <interaction Point name>::CallEH() { if (_cp==<communication primitive>)

return (_eh->Interact(this,_cp,ACCEPT)); else

{ printf("Wrong communication primitive\n"); delete _msg; _cp=0; return 1; };

} /*------------------------------------------------------*/

/ EventHandler construct (3.2) <component>::<component>(<parameters>, <connected interaction points>,

eventsManager* em):eventHandler(em)

{ <interaction point reference>=<connected interaction points><interaction point reference>->Connect(this); _state=<initial state>; _msg=new char[80]; }

*------------------------------------------------------*/

Page 252: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

234

Appendix B

// Definition of Interact method (3.3) int <component>::Interact(eventPoint* ep, int cp, int act)

{

// timers// -------------------------------------------------------

if(<timer ep>->Active()){// guarding conditionif (! (<guarding condition>))

<timer ep>->Idle();}

// -------------------------------------------------------

switch (<state>) { case <state name>:

// -------------------------------------------------------// unit of behaviour template (accept)

if (act==OFFER) // indicate enabled condition<interaction point reference>->InterInd();

else { if ((ep==<interaction point reference>)

&&(cp==<communication primitive>)

) { // get information<interaction point reference>->GetData(&_msg); // guarding conditionif (<guarding condition>)

{ // action<action>; return SUCCESS;}

}; };

// -------------------------------------------------------// unit of behaviour template (offer)

if (act==OFFER) {// guarding conditionif ( <guarding condition> )

{// execute interaction offerif(<interaction point reference>->SendData(<communication primitive>,_msg))

{// action<action>

return SUCCESS; };

Page 253: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.1 Basic Event Manager Framework

235

};};

// -------------------------------------------------------// unit of behaviour template (timeout)

if ( act==OFFER){ if(!<timer ep>->Active())

if ( <guarding condition> )<timer ep>->SetTimeout(<time in seconds.>);

}else

if (ep==<timer ep>) { // action <action>;return SUCCESS; };

// -------------------------------------------------------break;

case END:; break;

default :; };

return FAIL; }

/*------------------------------------------------------*/

/ Initialization Class// Class Constructor (4.2)

ENTITY :: ENTITY (<required parameters>) { // Event Manager instantiation eventsManager* _em = new eventsManager; // treat possible parameters

// instantiate required interaction points<interaction Point name> <interaction point reference> = new <interaction Point name>(<parame-ters>,em);

// settle internal partners<internal interaction point left reference>->SetPartner(<internal interaction point right reference>); <internal interaction point right reference>->SetPartner(<internal interaction point left reference>);

// instantiate componentsnew <component>(<required parameters>,

<references to connected interaction points>,em);

// start Event Manager event monitoring cycle_em->WaitEvents(); }

/*------------------------------------------------------*/ main(int argc, char *argv[])

{

Page 254: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

236

Appendix B

cout << "\n Protocol Entity Initialized.\n" << flush; new ENTITY(<parameters>); }

B.2 Basic Multi-thread Framework/** Templates for Implementing Protocols Using the * Basic Multi-thread Framework* Header file*/

// Constants Definition (1)// States// define END 0#define <SIMBOLO> <CONSTANT>

// Service Primitives#define <SIMBOLO> <CONSTANT>

/*------------------------------------------------------*/// Including framework header#include "/<framework path>/pienv.h"

/*------------------------------------------------------*/ // Specialization of eventPoints (2)// Environment specific specializations (2.1)// Specialization class’s header (2.1.1)

class <external specialization> : public external{public:

<external specialization>(<requered parameters>);int ReadData(); int SendData(int,char*);virtual int CallEH(){return 0;}

private:<required attributes>

};

/ Protocol specific specializations (2.2)// Event Point header (2.2.1)

utex_t _mp<N>;cond_t _cv<N>;class <interaction point name>: public <external specialization>

{ public:

<interaction point name>(<required parameters>, mutex_t* m, cond_t* c):

<abstract eventPoint specialization>(<required parameters>,m,c){} virtual int CallEH();

};

*------------------------------------------------------*/

/ Specialization of required eventHandlers (4)// EventHandler Header (4.1)

Page 255: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.2 Basic Multi-thread Framework

237

// component’s mutexes and conditions variablesmutex_t _mp<N>, _mp<N+1>;cond_t _cv<N>;// timers’ mutexes and conditions variablesmutex_t _mp<N+2>;cond_t _cv<N+1>;

class <component> : public eventHandler { public:

<component>(<required parameters>,<references to connected interaction points>,<timers’ mutex and condition variable>,mutex_t*, mutex_t*,cond_t*);

~<component>(){} int Interact(eventPoint*,int,int);

private: <interaction points references>;

timer <timers references>;char *_msg; int fail; <other behaviour context attributes>;

};

/*------------------------------------------------------*/

// Definition of initialization class (5)// Class Header (5.1)

class ENTITY { public:

ENTITY (<required parameters>); ~ENTITY (){}

};

/** Template for protocol implementation using de * Basic Multi-thread Framework* Body file*/

#include "<header file name>"

/*------------------------------------------------------*/ // Data manipulation functions (e.g., pdu coding)

*------------------------------------------------------*/

// Specialization of external class for the required interaction points (2)// Environment specific specializations (2.1)

// Class Construct (2.1.2)<external_specialization>::<external_specialization>(<required parameters>,eventsManager* em):exter-

nal(em){

<store configuration parameters>;<open interface handler>;

Page 256: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

238

Appendix B

_waitSynchr=1;}

// Overload of ReadData Method (2.1.3)int <external_specialization>::ReadData()

{if (!_msg)

{_msg=new char[80];<get data from buffer>;_cp=<communication primitive>;_msg=<data>;};

if (!CallEH()){_waitSynchr=0;return 0;}

else{_eh->InterInd();_msg=NULL;_cp=0;return 1;};

}

// Overload of SendData (2.1.4)int <external_specialization>::SendData(int cp,char *d){

char aux[BUFFERSIZE];<send cp and d as a single string through the interface>;return 1;}

// Protocol Specific Specializations (2.2)// CallEH Method definition (2.2.2)

int <interaction Point name>::CallEH() { if (_cp==<communication primitive>)

return (_eh->Interact(this,_cp,ACCEPT)); else

{ printf("Wrong communication primitive\n"); delete _msg; _cp=0; return 1; };

}

/*------------------------------------------------------*/

/ EventHandler construct (3.2)

component>::<component>(<parameters>, <connected interaction points>,

<timers’ mutexes and condition variables>, mutex_t* m1, mutex_t* m2,cond_t* c) :eventHandler(m1,m2,c)

Page 257: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.2 Basic Multi-thread Framework

239

{ <interaction point reference>=<connected interaction points><interaction point reference>->Connect(this); _state=<initial state>; }

*------------------------------------------------------*/

// Definition of Interact method (3.3)

nt <component>::Interact(eventPoint* ep, int cp, int act) {

// timers deactivation// --------------------------------------if (<timer reference>->Active())

// condition does not holdif (!(<condition>))

<timer reference>->Idle();// --------------------------------------

mutex_lock(_mut);switch (_state)

{ case <state name>:

// -------------------------------------------------------// unit of behaviour template (accept)

if (act==ANY) // indicate enabled condition<interaction point reference>->InterInd();

else { if ((ep==<interaction point reference>)

&&(cp==<communication primitive>)) { // get information<interaction point reference>->GetData(&_msg); if (<guarding condition>)

{ // action// ----------------------------<action>; // ----------------------------mutex_unlock(_mut); return SUCCESS;}

};};

// ------------------------------------------------------- // unit of behaviour template (offer)

if ((act==OFFER)||(act==ANY)) {// execute interaction offerif(<interaction point reference>->SendData(<communication primitive>,_msg))

Page 258: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

240

Appendix B

{// action// ----------------------------<action>// ----------------------------mutex_unlock(_mut); return SUCCESS; };

}; // -------------------------------------------------------// unit of behaviour template (timeout)

if ( (act==ANY) || (act==OFFER)){ if(!(<timer reference>->Active()))

// guarding conditionif ( <condition> )

<timer reference>->SetTimeout(<timeout valuer>);}

elseif (ep == <timer reference>)

{// action // ----------------------------<action>;// ----------------------------mutex_unlock(_mut);return SUCCESS;

};// -------------------------------------------------------break;

case END:; break;

default :; };

mutex_unlock(_mut); return FAIL; }

/*------------------------------------------------------*/

/ Initialization Class// Class Constructor (4.2)

ENTITY :: ENTITY (<required parameters>) { void *status;// treat possible parameters

// instantiate required external interaction points<interaction Point name> *<interaction point reference> = new <interaction Point name>(<parame-ters>,&_mp<N>,&_cv<N>);

// instantiate required internal interaction points<interaction Point name> *<interaction point reference> = new <interaction Point name>();

// settle internal partners<internal interaction point left reference>->SetPartner(<internal interaction point right reference>); <internal interaction point right reference>->SetPartner(<internal interaction point left reference>);

Page 259: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.3 Advanced Event Manager Framework

241

// instantiate componentsnew <component>(<required parameters>,

<references to connected interaction points>,<timers’ mutexes and condition varialbes>,&_mp<N>, &_mp<N+1>,&_cv<N>);

// synchronize threadsthr_join(<an interaction point reference>->GetThread(),NULL,&status);}

/*------------------------------------------------------*/

main(int argc, char *argv[]) { cout << "\n Protocol Entity Initialized.\n" << flush; new ENTITY(<parameters>); }

B.3 Advanced Event Manager Framework/** Templates for Implementing Protocols Using the * Advanced Event Manager Framework* Header file*/

// Constants Definition (1)// States#define <SIMBOLO> <CONSTANT>

// Service Primitives// Timeout 0 #define <SIMBOLO> <CONSTANT>

/*------------------------------------------------------*/// Including framework header#include "/<framework path>/pienv.h"

/*------------------------------------------------------*/ // Specialization of eventPoints (2)// Environment-specific specializations (2.1)// Specialization classes header (2.1.1)

class <class_name> : public external{public:

<class_name>(int,eventsManager*);int ReadData(); int SendData(int,char*);virtual int CallEH(){return 0;}

private:<required attributes>

};

// Protocol-specific specializations (2.2)// Event Point header (2.2.1)

class <interaction point name>: public <external specialization> {

Page 260: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

242

Appendix B

public: <interaction point name>(<required parameters>,

eventsManager* em):<abstract eventPoint specialization>(<required parameters>,em){} virtual int CallEH();

};

/*------------------------------------------------------*/

// Specialization of required eventHandlers (3)// EventHandler Header (3.1)

class <component> : public eventHandler { public:

<component>(<required parameters>,<references to connected interaction points>,eventsManager*);

~<component>(){} int DynUB<n>(eventPoint*,eventPoint*,int,int);int Handler(int,eventPoint*,int,int); void Destroy() {delete this;}

private: <interaction points references>;

char *_msg; int fail; int state<identity ofmonolitic behaviour>;<other behaviour context attributes>;

};

/*------------------------------------------------------*/

// Definition of initialization class (4)// Class Header (4.1)

class ENTITY { public:

ENTITY (<required parameters>); ~ENTITY (){}

};

/** Template for protocol implementation using de * Basic Event Manager Framework* Body file*/

#include "<header file name>"

/*------------------------------------------------------*/

// Specialization of external class for the required interaction points (2)// Environment specific specializations (2.1)

// Class Construct (2.1.2)<external_specialization>::<external_specialization>(<required parameters>,eventsManager* em):external(em){

Page 261: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.3 Advanced Event Manager Framework

243

<store configuration parameters>;<open interface handler>;_waitSynchr=1;}

// Overload of ReadData Method (2.1.3)int <external_specialization>::ReadData()

{if (!_msg)

{_msg=new char[80];<get data from buffer>;_cp=<communication primitive>;_msg=<data>;};

if (!CallEH()){_waitSynchr=0;return 0;}

else{_eh->InterInd();_msg=NULL;_cp=0;return 1;};

}

// Overload of SendData (2.1.4)int <external_specialization>::SendData(int cp,char *d){

char aux[BUFFERSIZE];<send cp and d as a single string through the interface>;return 1;}

// Protocol Specific Specializations (2.2)// CallEH Method definition (2.2.2)

int <interaction Point name>::CallEH() { if (_cp==<communication primitive>)

return (_eh->Interact(this,_cp,ACCEPT)); else

{ printf("Wrong communication primitive\n"); delete _msg; _cp=0; return 1; };

}

/*------------------------------------------------------*/

// EventHandler construct (3.2)

<component>::<component>(<parameters>, <connected interaction points>,

eventsManager* em)

Page 262: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

244

Appendix B

:eventHandler(em) { <interaction point reference>=<connected interaction points>

<interaction point reference>->Connect(this); _state=<initial state>; _msg=new char[80];

_root=new <composition class> (NULL,<behaviour identification>,this);}

/*------------------------------------------------------*/

// EventHandler destructor (3.3)

<component>::~<component>(){<interaction point reference>->Disconnect();}

/*------------------------------------------------------*/

// Definition of Handler method (3.4)

int <component>::Handler(int id, eventPoint* ep, int cp, int act) { // ---- Timers -------------------------------------------

if (<timer reference>->Active()){// guarding condition doesn’t holdif ( !(<guarding condition>))

<timer reference>->Idle();}

// -------------------------------------------------------switch (id) {

case <behaviour id>:switch (<state>)

{ case <state name>:

// -------------------------------------------------------// unit of behaviour template (accept)

if (act==OFFER) // indicate enabled condition<interaction point reference>->InterInd();

else { if ((ep==<interaction point reference>)

&&(cp==<communication primitive>)) { // get information<interaction point reference>->GetData(&_msg); // guarding conditionif (<guarding condition>){ <action>; return <SUCCESS|EXIT>; }};

};

Page 263: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

B.3 Advanced Event Manager Framework

245

// -------------------------------------------------------// unit of behaviour template (offer)

if (act==OFFER) {// guarding conditionif (<guarding condition>)

// execute interaction offerif(<interaction point reference>->SendData(<communication primitive>,_msg)) {<action>return <SUCCESS|EXIT>; };

};

// ------------------------------------------------------- // unit of behaviour template (timeout)

if(act==OFFER) {// guarding conditionif ((<guarding condition>))

<timer reference>->SetTimeout(<timeout>);}

else // act==ACCEPTif (ep==<timer reference>){// action<action>return <SUCCESS|EXIT>; };

// -------------------------------------------------------

break; case END:;

break; default :; };

break;default:;

} // switch id return FAIL;

}

/*------------------------------------------------------*/

// Initialization Class// Class Constructor (4.2)

ENTITY :: ENTITY (<required parameters>) { // Event Manager instantiation eventsManager* _em = new eventsManager;

// treat possible parameters

// instantiate required interaction points<interaction Point name> <interaction point reference> = new <interaction Point name>(<parame-ters>,em);

Page 264: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

246

Appendix B

// settle internal partners<internal interaction point left reference>->SetPartner(<internal interaction point right reference>); <internal interaction point right reference>->SetPartner(<internal interaction point left reference>);

// instantiate componentsnew <component>(<required parameters>,

<references to connected interaction points>,em);

// start Event Manager monitoring cycleem->WaitEvent(); }

/*------------------------------------------------------*/

main(int argc, char *argv[]) { cout << "\n Protocol Entity Initialized.\n" << flush; new ENTITY(<parameters>); }

Page 265: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

C.1 Protocol Specification

247

Appendix C

This appendix presents the LOTOS specification of the Sliging Window protocol.

C.1 Protocol Specificationspecification Protocol[mt, mr, ut, ur] : noexitlibrary Boolean, OctetString, Element, NaturalNumber, FBoolean, NatRepresentationsendlib

(* SubNatNumbers *)type SubNatNumbersis NaturalNumberopns Prev : Nat -> Nat _-_ : Nat, Nat -> Nateqnsforall m, n : Natofsort Nat Prev(succ(m)) = m; Prev(0) = 0; m - 0 = m; m gt n and (n ne 0) => m - n = Prev(m) - Prev(n); m eq n => m - n = 0; m lt n => m - n = 0;endtype (* SubNatNumbers *)

(* Module NatNum *)type ModuleNatNumbersis SubNatNumbersopns _mod_ : Nat, Nat -> Nateqnsforall x, y : Natofsort Nat y gt x => x mod y = x; y lt x => x mod y = x - y mod y; y eq x => x mod y = 0;endtype (* ModuleNatNumbers *)

(* TPEParameters *)type TPEParameters is NatRepresentationsopns BufferSize : ->Nateqnsofsort Nat BufferSize = NatNum(9 of DecDigit); endtype (*TPEParameters *)

(* FIFO Queue *)type FIFOQueue

Page 266: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

248

Appendix C

is Elementsorts FIFOQueueopns EmptyQueue : -> FIFOQueue Enqueue : Element, FIFOQueue -> FIFOQueue Dequeue : FIFOQueue -> FIFOQueue Top : FIFOQueue -> Element IsEmpty, NotEmpty : FIFOQueue -> FBooleqnsforall e1, e2 : Element, q : FIFOQueueofsort Element Top(Enqueue(e1, EmptyQueue)) = e1; Top(Enqueue(e1, Enqueue(e2, q))) = Top(Enqueue(e2, q));ofsort FIFOQueue Dequeue(Enqueue(e1, EmptyQueue)) = EmptyQueue; Dequeue(Enqueue(e1, Enqueue(e2, q))) = Enqueue(e1, Dequeue(Enqueue(e2, q)));ofsort FBool IsEmpty(EmptyQueue) = true; IsEmpty(Enqueue(e1, q)) = not(true); NotEmpty(q) = not(IsEmpty(q));endtype (* FIFOQueue *)

(* Extended FIFO Queue *)type ExtFIFOQueueis FIFOQueue, NaturalNumberopns Remove, PutOnTop : Element, FIFOQueue -> FIFOQueue _IsTopOf_ : Element, FIFOQueue -> FBool Length : FIFOQueue -> Nateqnsforall e1, e2, e3 : Element, q : FIFOQueueofsort FIFOQueue Remove(e1, EmptyQueue) = EmptyQueue; e1 eq e2 => Remove(e1, Enqueue(e2, q)) = q; e1 ne e2 => Remove(e1, Enqueue(e2, q)) = Enqueue(e2, Remove(e1, q)); PutOnTop(e1, EmptyQueue) = Enqueue(e1, EmptyQueue); PutOnTop(e1, Enqueue(e2, q)) = Enqueue(e2, PutOnTop(e1, q));ofsort FBool e1 IsTopOf EmptyQueue = not(true); e1 IsTopOf Enqueue(e2, EmptyQueue) = e1 eq e2; e1 IsTopOf Enqueue(e2, Enqueue(e3, q)) = e1 IsTopOf Enqueue(e3, q);ofsort Nat Length(EmptyQueue) = 0; Length(Enqueue(e1, q)) = Succ(Length(q));endtype (* ExtFIFOQueue *)

(* PDUId *)type PDUId

is ModuleNatNumbers, NatRepresentationssorts PDUIdopns

Page 267: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

C.1 Protocol Specification

249

DUId : Nat -> PDUId NextId : PDUId -> PDUID PrevId : PDUId -> PDUId Id0 : -> PDUId MaxId : -> PDUId TotalIds : -> Nat Nat : PDUId -> Nateqnsforall a : PDUId, x : Natofsort PDUId Id0=PDUId(0); x lt Prev(TotalIds) => NextId(PDUId(x)) = PDUId(Succ(x)); x ge Prev(TotalIds) => NextId(PDUId(x)) = PDUId(0); MaxId = PDUId(Prev(TotalIds)); PrevId(PDUId(0)) = MaxId; PrevId(NextId(a)) = a;ofsort Nat Nat(PDUId(0)) = 0; Nat(PDUId(Succ(x))) = Succ(x); TotalIds = NatNum(8 of DecDigit);endtype (* PDUId *)

(* PDU *)type PDUis Boolean, PDUId, Octetstringsorts PDUopns _eq_, _ne_ : PDU, PDU -> Bool DataPDU : PDUId, Octetstring -> PDU AckPDU : PDUId -> PDU IsDataPDU : PDU -> Bool IsAckPDU : PDU -> Bool PDUId : PDU -> PDUId _IsAckFor_ : PDU, PDU -> Bool PDUData : PDU -> OctetStringeqnsforall id : PDUId, o : Octetstring, pdu1, pdu2 : PDUofsort Bool IsDataPDU(DataPDU(id, o)) = true; IsAckPDU(DataPDU(id, o)) = false; IsDataPDU(AckPDU(id)) = false; IsAckPDU(AckPDU(id)) = true;ofsort PDUId PDUId(DataPDU(id, o)) = id; PDUId(AckPDU(id)) = id;ofsort Bool pdu1 IsAckFor pdu2 = IsAckPDU(pdu1) and (Nat(PDUId(pdu1)) eq Nat(PDUId(pdu2)));ofsort OctetString PDUData(DataPDU(id, o)) = o;endtype (* PDU *)

(* PDUQueue *)

Page 268: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

250

Appendix C

type PDUQueueis ExtFIFOQueue actualizedby PDU, Boolean usingsortnames PDU for Element PDUQueue for FIFOQueue Bool for FBoolopnnames NoPDU for EmptyQueueendtype (* PDUQueue *)

(* DataQueue *)type DataQueueis ExtFIFOQueue actualizedby OctetString, Boolean usingsortnames OctetString for Element DataQueue for FIFOQueue Bool for FBoolopnnames NoData for EmptyQueueendtype (* DataQueue *)

(* ExtPDUQueue *)type ExtPDUQueueis PDU, PDUQueue, PDUId, Booleanopns _IsAckFor_ : PDU, PDUQueue -> Bool PDUtoDeliver : PDUQueue, PDUId -> Booleqnsforall p1, p2 : PDU, q : PDUQueue, id : PDUIdofsort Bool p1 IsAckFor Enqueue(p2, q) = p1 IsAckFor p2 or (p1 IsAckFor q); p1 IsAckFor NoPDU = false; PDUtoDeliver(q, id) = NotEmpty(q) and (Nat(PDUId(top(q))) eq Nat(id));endtype (* ExtPDUQueue *)

(* Window checks *)type WindowChecksis PDUId, NaturalNumber, ModuleNatNumbersopns Received : Nat, Nat, Nat, Nat -> Bool InWindow : Nat, Nat, Nat, Nat -> Bool NotFull : Nat, Nat, Nat, Nat -> Booleqnsforall id, sid, ws, M : Natofsort Bool InWindow(id, sid, ws, M) = ( ((id + M - sid) mod id) gt Succ(0)) and (ws gt ((id+M-sid) mod id)); Received(id, sid, ws, M) = ( ((sid + M - id) mod M) gt Succ(0)) and (ws gt ((sid+M-id) mod M)); NotFull(sid, id, ws, M) = (((sid+M)-id) mod M) le ws;endtype (* WindowChecks *)

(* RSP *)type RSPis PDU, PDUId, Boolean

Page 269: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

C.1 Protocol Specification

251

sorts RSPopns RS_DaInd, RS_DaReq : OctetString -> RSP IsRSDaReq, IsRSDaInd : RSP -> Bool RSPData : RSP -> OctetStringeqnsforall o : OctetStringofsort Bool IsRSDaReq(RS_DaReq(o)) = true; IsRSDaInd(RS_DaInd(o)) = true; IsRSDaReq(RS_DaInd(o)) = false; IsRSDaInd(RS_DaReq(o)) = false;ofsort OctetString RSPData(RS_DaReq(o)) = o; RSPData(RS_DaInd(o)) = o;endtype (* RSP *)

(* USP *)type USPis PDU, Booleansorts USPopns US_DaInd, US_DaReq : PDU -> USP PDU : USP -> PDU IsUSDaInd : USP -> Booleqnsforall p : PDUofsort Bool IsUSDaInd(US_DaInd(p)) = true; IsUSDaInd(US_DaReq(p)) = false;ofsort PDU PDU(US_DaInd(p)) = p; PDU(US_DaReq(p)) = p;endtype (* USP *)

behaviourchoice ws : Nat [][(ws gt 0) and (TotalIds ge (Succ(Succ(0))*ws))] -> ((TPE [ut, mt] (ws) ||| RPE [ur, mr] (ws) ) || Medium [mt, mr] )where process TPE[ut, mt](ws : Nat) : noexit:= RSConstraints [ut] |[ut]| Transmitter [ut, mt] (NoData, NoPDU, Id0, PrevId(Id0), ws, false) where process RSConstraints[ut] : noexit:= ut?usp : RSP [IsRSDaReq(usp)] ; RSConstraints [ut] endproc (* RSConstraints *)

process Transmitter[ut, mt] (tq : DataQueue, rtq : PDUQueue, sid, lu : PDUId, ws : Nat, to:Bool) : noexit:= ( AcceptData [ut] (tq) >> accept newtq : DataQueue in Transmitter [ut, mt] (newtq, rtq, sid, lu, ws, to) ) []

Page 270: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

252

Appendix C

( SendData [mt] (tq, rtq, lu, sid, ws) >> accept newtq : DataQueue, newrtq : PDUQueue in Transmitter [ut, mt] (newtq, newrtq, NextId(sid), lu, ws,to) ) [] ( RecFromUS [mt] (rtq, sid, lu) >> accept newrtq : PDUQueue, newlu : PDUId in Transmitter [ut, mt] (tq, newrtq, sid, newlu, ws, to) ) [] ( [NotEmpty(rtq)]-> i(* timeout *); Transmitter [ut, mt] (tq, rtq, sid, lu, ws, true) ) [] ( [to] -> Retransmit[mt] (Top(rtq)) >> Transmitter [ut, mt] (tq, rtq, sid, lu, ws, false) ) where process AcceptData[ut](tq : DataQueue) : exit(DataQueue):= [BufferSize gt Length(tq)] -> ut?usp : RSP [IsRSDaReq(usp)] ; exit(Enqueue(RSPData(usp), tq)) endproc (* AcceptData *)

process SendData[mt] (tq:DataQueue, rtq:PDUQueue, lu:PDUId, sid:PDUId, ws:Nat) : exit(DataQueue, PDUQueue):= [NotFull(Nat(sid), Nat(lu), ws, TotalIds) and (Length(rtq) gt 0)] -> (let pdu : PDU = DataPDU(sid, Top(tq)) in mt!US_DaReq(pdu) ; exit(Dequeue(tq), Enqueue(pdu, rtq)) ) endproc (* SendData *)

process RecFromUS[mt](rtq : PDUQueue, lu : PDUId, sid : PDUId) : exit(PDUQueue, PDUId):= mt?msp : USP [IsUSDaInd(msp)] ; (let pdu : PDU = PDU(msp) in [pdu IsAckFor rtq] -> (let newq : PDUQueue = Remove(pdu, rtq) in [IsEmpty(newq)] -> exit(newq, PrevId(sid)) [] [IsEmpty(newq)] -> exit(newq, PrevId(PDUId(Top(rtq)))) ) [] [not(pdu IsAckFor rtq)] -> exit(rtq, lu) ) endproc (* RecFromUS *)

process Retransmit[mt] (pdu:PDU) : exit := mt!US_DaReq(pdu) ; exit endproc (* Retransmit *) endproc (* Transmitter *) endproc (* TPE *)

process RPE[ur, mr](ws: Nat) : noexit:= RSConstraints [ur] |[ur]| Receiver [ur, mr] (NoPDU, Id0, ws) where process RSConstraints[ur] : noexit:= ur?usp : RSP [IsRSDaInd(usp)] ; RSConstraints [ur] endproc (* RSConstraints *)

process Receiver[ur, mr](pq : PDUQueue, la : PDUId, ws: Nat) : noexit:= ( AcceptData [ur, mr] (pq, la, ws) >> accept newpq : PDUQueue, newla : PDUId in Receiver [ur, mr] (newpq, newla, ws) )

Page 271: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

C.1 Protocol Specification

253

[] ( DeliverData [ur, mr] (pq, la) >> accept newpq : PDUQueue, newla : PDUId in Receiver [ur, mr] (newpq, newla, ws) ) where process AcceptData[ur, mr](pq : PDUQueue, la : PDUId, ws : Nat) : exit(PDUQueue, PDUId):= mr?msp : USP [IsUSDaInd(msp)] ; (let pdu : PDU = PDU(msp) in [Nat(PDUId(pdu)) eq Nat(NextId(la))] -> (* expected Data_PDU *)ur!RS_DaInd(PDUData(pdu)) ; mr!US_DaReq(AckPDU(PDUId(pdu))) ; exit(pq, NextId(la)) [] [Received(Nat(PDUId(pdu)), Nat(la), ws, TotalIds)] -> (* old Data-PDU *)mr!US_DaReq(AckPDU(PDUId(pdu))) ; exit(pq, la) [] [InWindow ( Nat(PDUId(pdu)), Nat(la), ws, TotalIds)] -> (* pdu in rec. window *)exit(Enqueue(pdu, pq), la) [] [Nat(PDUId(pdu)) ne Nat(NextId(la)) and not(Received(Nat(PDUId(pdu)), Nat(la), ws, TotalIds)) and not(InWindow(Nat(PDUId(pdu)), Nat(la), ws, TotalIds))] -> (* none of the above*)exit(pq, la) ) endproc (* AcceptData *)

process DeliverData[ur, mr](pq : PDUQueue, la : PDUId) : exit(PDUQueue, PDUId):= [PDUtoDeliver(pq, la)] -> (* next pdu on top of queue *) (let pdu : PDU = Top(pq) in ur!RS_DaInd(PDUData(pdu)) ; mr!US_DaReq(AckPDU(PDUId(pdu))) ; exit(Remove(pdu, pq), NextId(la)) ) endproc (* DeliverData *) endproc (* Receiver *) endproc (* RPE *)

process Medium[mt, mr] : noexit:= ( mt? u:USP; ( Medium [mt, mr] ||| (mr! u; stop [] i; stop))) [] ( mr? u:USP; ( Medium [mt, mr] ||| (mt! u; stop [] i; stop))) endproc (* Medium *)endspec (* Protocol *)

Page 272: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

254

Appendix C

Page 273: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

D.1 Transmitter Process

255

Appendix DThis appendix presents the implementation code of the implementation example in chapter 8.

D.1 Transmitter Process // unit of behaviour template (accept) (1) if (act==OFFER) // indicate enabled condition _ut->InterInd(); else { if ((ep==_ut)&&(cp==RS_DaReq)) { // get information _ut->GetData(&msg); // guarding condition if (tq.Length()<=BufferSize) { // action Enqueue( msg, &tq); return SUCCESS; } }; };

// unit of behaviour template (accept) (2) if (act==OFFER) // indicate enabled condition _mt->InterInd(); else { if ((ep==_mt)&&(cp==US_DaInd)){ // get information _mt->GetData(&msg); _pdu=DecodePDU(msg); // guarding condition if (IsAckFor(_pdu,rtq)){ printf("Acknow. received\n"); RemovePDU(_pdu,&rtq); if (!rtq.Length()) lu=PrevId(sid,TotalIds); else lu=PrevId(PDUId(TopOfQueue(&rtq)),TotalIds); delete _pdu; return SUCCESS;} }; };

// unit of behaviour template (accept) (3) if (act==OFFER) // indicate enabled condition _mt->InterInd(); else { if ((ep==_mt)&&(cp==US_DaInd)){ // get information _mt->GetData(&msg); _pdu=DecodePDU(msg); // guarding condition if (!IsAckFor(_pdu,rtq)){ printf("Invalid Acknow.\n"); delete _pdu; return SUCCESS; } }; };

// unit of behaviour template (timeout) (4) if(act==OFFER) { if (!(_timer->Active())) // guarding condition if (_pduWaitingRet==TopOfQueue(&rtq)) _timer->SetTimeout(5); } else // act==ACCEPT if (ep==_timer) { // action _timeout=TRUE; return SUCCESS; };

// unit of behaviour template (offer) (6) if (act==OFFER) { // guarding condition if (NotFull(sid,lu,ws,TotalIds) && tq.Length()) { // execute interaction offer if(_mt->SendData(US_DaReq, CodePDU(_pdu=PDU(sid,TopOfQueue(&tq))))) { // action printf("Sending PDU\n"); Enqueue (_pdu,&rtq); sid=NextId(sid,TotalIds); Dequeue(&tq); return SUCCESS; }; }; };

// unit of behaviour template (offer) (5) if (act==OFFER) { // guarding condition if (_timeout) // execute interaction offer if(_mt->SendData(US_DaReq, CodePDU(_pduWaitingRet))) { // action printf("Retransmiting PDU\n"); _timeout=FALSE; return SUCCESS; }; };

Page 274: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

256

Appendix D

D.2 Receiver Process // unit of behaviour template (accept) (1) if (act==OFFER) // indicate enabled condition _mr->InterInd(); else { if ((ep==_mr)&&(cp==US_DaInd)) { // get information _mr->GetData(&msg); _pdu1 = DecodePDU(msg); // expected Data-PDU if (PDUId(_pdu1)==NextId(a,TotalIds)){ printf("Receiving PDU\n"); state1=SENDING; return SUCCESS; } }; };

// unit of behaviour template (accept) (2) if (act==OFFER) // indicate enabled condition _mr->InterInd(); else { if ((ep==_mr)&&(cp==US_DaInd)) { // get information _mr->GetData(&msg); _pdu1 = DecodePDU(msg); // old Data-PDU if (Received(PDUId(_pdu1),la,ws,TotalIds)){ printf("old Data-PDU\n"); state1=ACKNOW2; return SUCCESS; } }; };

// unit of behaviour template (accept) (3) if (act==OFFER) // indicate enabled condition _mr->InterInd(); else { if ((ep==_mr)&&(cp==LDaInd)) { // get information _mr->GetData(&msg); _pdu1 = DecodePDU(msg); // Data-PDU in rec. window if (InWindow(PDUId(_pdu1),la,ws,TotalIds)) { printf("Data-PDU in rec. window\n"); Enqueue(_pdu1,&pq); return EXIT; } }; };

// unit of behaviour template (offer) (5) if (act==OFFER) { // execute interaction offer if(_ur->SendData(RS_DaInd,DataOf(_pdu1))) { state1=ACKNOW1; return SUCCESS; }; };

// unit of behaviour template (offer) (6) if (act==OFFER) { // execute interaction offer if(_mr->SendData(US_DaReq, CodeAckPDU(PDUId(_pdu1)))) { printf("Sending Acknow.\n"); la=NextId(la,TotalIds); state1=IDLE; return SUCCESS; }; };

// unit of behaviour template (offer) (7) if (act==OFFER) { // execute interaction offer if(_mr->SendData(US_DaReq,CodeAckPDU(PDUId(_pdu1)))) { printf("Re-Sending Acknow.\n"); delete _pdu1->msg; delete _pdu1; state1=IDLE; return EXIT; }; };

// unit of behaviour template (accept) (4) if (act==OFFER) // indicate enabled condition _mr->InterInd(); else { if ((ep==_mr)&&(cp==LDaInd)) { // get information _mr->GetData(&msg); _pdu1 = DecodePDU(msg); if (!((InWindow(PDUId(_pdu1),la,ws,TotalIds)) || (Received(PDUId(_pdu1),la,ws,TotalIds)) || (PDUId(_pdu1)==NextId(la,TotalIds)) )) { printf("Data-PDU invalid\n"); return EXIT; } }; };

Page 275: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

D.2 Receiver Process

257

// unit of behaviour template (offer) (8) if (act==OFFER) { // guarding condition // next pdu in top of queue if (PDUtoDeliver(&pq, NextId(la,TotalIds))) // execute interaction offer { _pdu2=TopOfQueue(&r); if(_ur->SendData(RS_DaInd,DataOf(_pdu2))) { state2=SENDING; return SUCCESS; }; }; };

// unit of behaviour template (offer) (9) if (act==OFFER) { // execute interaction offer if(_mr->SendData(US_DaReq, CodeAckPDU(PDUId(_pdu2)))) { RemovePDU(_pdu2,&pq); la=NextId(la,TotalIds); state2=WAITING; return EXIT; }; };

Page 276: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

258

Appendix D

Page 277: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

259

Index

Aaction 38alphabet 198

Bbasic design concept 193basic meta-model 20behaviour 21, 33behaviour composition relations 43behaviour context 38blackbox 28blocking interaction 48boundary conditions 25, 70

Cchild component 124class diagram 20coding 20communication primitive 37component 21, 32component class 53component object 53composed behaviour 43composed design concept 193composition 69condition 38CRC Cards 25

Ddata dictionary 20design concepts 2design culture 2design model 3documentation 20domain analysis 19dynamic initialization 71dynamic interaction point 125dynamic termination 71

Eentity 97event 38event dispatcher 54event evaluation cycle 60, 80external interaction point 65external interactions 61

Ffather component 124firing policy 39formal semantics 3formal specification languages 3frameworks 7FSM language 194

Ggeneral component 73general purpose components 51

HHello protocol 174

Iimplementation 4implementation building blocks 4implementation constructs 4implementation environment 4implementation process 4implementation techniques 51information 37interaction 21interaction acceptance 38interaction means 21interaction offer 38interaction participation 37internal interactions 61

Llanguages 198LSA 174LSD 174

Mmodelling 2monitoring cycle 78monolitic behaviour 43multi-thread 25

Nnon-blocking interaction 48

OOOMM 23OSPF 172

Pparallel behaviour 33, 52protocol design 2pseudo-event 193

Rreliable flooding 174router neighbour 174

Sscheduler 54selected term 128software architecture 19software quality requirements 51specification languages 3spontaneous event 38stable state 60state pattern 59static initialization 71static interaction point 125static termination 71

Tthread 25timeout 38timer 67trace 198

Page 278: Framework for Implementing Protocols: a model … for Implementing Protocols: a Model Based Approach ... FRAMEWORKS FOR IMPLEMENTING PROTOCOLS: A MODEL BASED APPROACH ... presents

260

Index

Uunit of behaviour 38

Vvalue checking 47value generation 47value passing 47

Wwhitebox 28