Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural...

73
Dynamic Architectural Adaptation Using Ontologies José Luis Pastrana 1 , Ernesto Pimentel 1 and Miguel Katrib 2 1 Departamento de Lenguajes y Ciencias de la Computación, Universidad de Málaga ETSI Informática, Campus Teatinos. 29071 Malaga, Spain {pastrana, ernesto}@lcc.uma.es 2 Departamento de Computación I, Universidad de la Habana, Facultad de Matemática y Computación. San Lázaro y L, Vedado. 10400 C.Habana, Cuba [email protected] Abstract. Software Adaptation promotes the use of specific computational entities called adaptors that guarantee software components will interact in the right way, not only at the signature level, but also at the behavioral, semantic and service levels. Adaptation techniques have proceeded by computing adaptors for closed systems made up of a fixed set of components. This is not satisfactory when the systems may evolve, with components entering or leaving it at any time. To enable adaptation on such systems, we propose one implementation of adaptors under .NET platform and we show how using an ontology one adaptor can be improved in order to achieve a runtime adaptation at service level in a developed system when a component is missing or replaced by other. This capability will increase the Quality of Service (QoS), making the system be Fault Tolerant. Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering (CBSE) receives a great interest from the software engineering community. The aim is to create a collection of reusable components that can be used for component-based application development. Application development then becomes the selection, adaptation and composition of components rather than implementing the application from scratch. The development of such a market of software components (similar to the market of hardware components and electronic devices) has always been one of the myths of Software Engineering, but it has never become a reality. The reason is that unlike what happens with hardware components, software is never reused ―as it is‖, but a certain degree of adaptation is always required. In such a situation, an adaptor is necessary in order to overcome compositional mismatches and to make components which otherwise cannot be plugged together composable. We can see that gluetechniques are required to adapt components that do not fit the compositional requirements of a system. However, it is not always possible to interconnect components in a desired way: the plugs of two (or more) components may not be plug-compatible. Consider the known problem of travelers which are unable to plug the razor they use at home into the plugs of various other countries. In such a situation, adaptors are needed to bridge the different interfaces. These kinds of problems are often referred to as architectural mismatch [1]. Successful composition of components does not necessarily imply successful interoperation: Interoperability is the ability of software components to communicate and cooperate with each Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008 ISSN 1988–3455 SISTEDES, 2008 1

Transcript of Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural...

Page 1: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Dynamic Architectural Adaptation Using Ontologies

José Luis Pastrana1, Ernesto Pimentel1 and Miguel Katrib2

1 Departamento de Lenguajes y Ciencias de la Computación, Universidad de Málaga

ETSI Informática, Campus Teatinos. 29071 Malaga, Spain {pastrana, ernesto}@lcc.uma.es

2 Departamento de Computación I, Universidad de la Habana,

Facultad de Matemática y Computación. San Lázaro y L, Vedado. 10400 C.Habana, Cuba [email protected]

Abstract. Software Adaptation promotes the use of specific computational entities called

adaptors that guarantee software components will interact in the right way, not only at the

signature level, but also at the behavioral, semantic and service levels. Adaptation techniques

have proceeded by computing adaptors for closed systems made up of a fixed set of

components. This is not satisfactory when the systems may evolve, with components entering

or leaving it at any time. To enable adaptation on such systems, we propose one

implementation of adaptors under .NET platform and we show how using an ontology one

adaptor can be improved in order to achieve a runtime adaptation at service level in a

developed system when a component is missing or replaced by other. This capability will

increase the Quality of Service (QoS), making the system be Fault Tolerant.

Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET.

1 Introduction

Component Based Software Engineering (CBSE) receives a great interest from the software

engineering community. The aim is to create a collection of reusable components that can be used

for component-based application development. Application development then becomes the

selection, adaptation and composition of components rather than implementing the application

from scratch.

The development of such a market of software components (similar to the market of hardware

components and electronic devices) has always been one of the myths of Software Engineering,

but it has never become a reality. The reason is that unlike what happens with hardware

components, software is never reused ―as it is‖, but a certain degree of adaptation is always

required. In such a situation, an adaptor is necessary in order to overcome compositional

mismatches and to make components which otherwise cannot be plugged together composable.

We can see that ―glue‖ techniques are required to adapt components that do not fit the

compositional requirements of a system. However, it is not always possible to interconnect

components in a desired way: the plugs of two (or more) components may not be plug-compatible.

Consider the known problem of travelers which are unable to plug the razor they use at home into

the plugs of various other countries. In such a situation, adaptors are needed to bridge the different

interfaces. These kinds of problems are often referred to as architectural mismatch [1].

Successful composition of components does not necessarily imply successful interoperation:

Interoperability is the ability of software components to communicate and cooperate with each

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 1

Page 2: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

other [2]. Reconsider the problem with the razor: in some countries, different voltages are used and

prohibit compatibility even with an adaptor: composition is possible, but interoperability is not.

These situations require a transformer to transform the incompatible voltage. We will denote these

kinds of problems as interaction or interoperability mismatch.

Both architectural and interoperability mismatch are part of a problem domain which can be

denoted as compositional mismatch [3]. A compositional mismatch occurs whenever it is

impossible to successfully interconnect components with existing connectors. Based on the

discussion and the observations of the example, we define one Adaptor (as well called glue code)

as follow: One Adaptor is the part of an application which overcomes compositional mismatches.

This proposal is based on the assumption of the components in the system are black boxes and

conceptually distributed. So, the objective of this proposal is to solve the problem existing when

the system is already developed and the adaptors needed are generated (automatically or ad hoc)

and one (or more) component in the system is replaced dynamically and then an architectural

mismatch occurs.

We show how architectural mismatch occurred when replacing a component can be solved adding

an ontology of the domain of the problem to the adaptor. So, the adaptor can solve the architectural

mismatch automatically, and transparent to the system, at runtime. We are presenting, as well, the

implementation of this technique using C# under .NET platform.

This paper is organized as follows. In Section 2 we give a presentation of the ontologies and the

semantic web. Next, Section 3 shows how ontologies can be used for architectural mismatch

adaptation at runtime. Section 4 uses an example about rectangle triangles to illustrate the details

about implementation. Section 5, is a discussion about related works, and, finally, Section 6

presents the conclusions and future work.

2 The Semantic Web

The objective of the Semantic Web is to provide languages to express the content of Web pages

and to make accessible to agents and computer programs the information that those pages contain.

More precisely, the Semantic Web is based on a set of languages such as RDF and OWL that can

be used to markup the content of Web pages. These languages have a well-defined semantics and a

proof theory that allows agents to draw inferences over the statements of the language.

The second element of the Semantic Web is a set of ontologies, which provide a conceptual model

to interpret the information provided. For example, an ontology of weather may contain concepts

such as temperature, snow, cloudy, sunny and so on. It may also contain information on the

relation between the different terms; for instance, it may say that cloudy and sunny are two types

of weather conditions. The vision of the Semantic Web is the transformation of the Web into an

Internet wide knowledge representation system, in which web pages provide information and

ontologies provide the conceptual framework needed to interpret that information.

Semantic Web technology [4], [5] helps us in managing information in our business, personal

space, or employment. The Semantic Web initiative aims to build a Web to be consumed by

software, instead of humans as the traditional WWW does. Thanks to formal and semantic

specification of the content, new applications such as product catalogues integration, advanced

search and retrieval applications, knowledge inferences become possible. Even if the vision of the

Semantic Web is still at its beginning the number of businesses that take benefit is rapidly

increasing.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 2

Page 3: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

In the context of computer and information sciences, an ontology defines a set of representational

primitives with which to model a domain of knowledge or discourse. An ontology specifies a

vocabulary with which to make assertions, which may be inputs or outputs of knowledge agents

(such as a software program).

Ontologies [6] can, therefore, be shared and reused among different applications. An ontology

describes the subject matter using notions of concepts, instances, relations, attributes, and axioms.

Concepts in the ontology are organized in taxonomies through which inheritance mechanisms can

be applied.

Ontology description languages such as RDF and OWL [7] are built on top of XML and add

semantics to the model representation. Those languages are now standards of the W3C with a large

support of applications and infrastructure for their storage, manipulation and overall management.

3 Using Semantic Web for Architectural Mismatch Adaptation

The web semantic technique used for the dynamic component adaptation of architectural mismatch

is based on a formal specification of the semantic information, and, this specification is expressed

using ontologies.

Ontologies have already been used in the context of translation. The idea of using ontologies to

solve the adaptation problem is born from the fact that the only knowledge we have to make that

adaptation is the component interface: service names, parameters, etc.

The grammar used in natural language is wide and complex; however, programming languages

have a well defined grammar. In our particular case, we only have to keep in mind the invocation

grammar which is as shown in Fig. 1.

Fig. 1. This figure shows the grammar used for the invocation of a service of a component

That allows us to adapt the call to a "not found" service by other one which is semantically

equivalent. Adaptation works as follow: the adaptor catches the "not found service" exception and

looks for an equivalent one in the current server using the unification algorithm of prolog machine

between the request service and the knowledge set in the ontology and then invokes the new

service.

There are many ontology languages but we have chosen the Ontology Web Language (OWL)

because it is a W3C recommendation. OWL is a language for defining and instantiating Web

ontologies. An OWL ontology may include descriptions of classes, along with their related

properties and instances. OWL is designed for use by applications that need to process the content

of information instead of just presenting information to humans. It facilitates higher machine

interpretability because it is written in XML.

Looking at the features found in OWL, we find the subClassOf relationship and the equality and

inequality properties. The equality properties allow us to set which concepts are equivalent to other

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 3

Page 4: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

ones. In the current proposal, we will use the following features: equivalentClass,

equivalentProperty and sameAs.

Using the mentioned before features it is possible to set what can be replaced by what. So, the call

to a service S1 made by a component C1 with the parameters P1 (C1.S1(P1)) can be replaced by

the call to a service S2 made by a component C2 with the parameters P2 (C2.S2(P2)) when C1 can

be replaced by C2, S1 can be replaced by S2 and P1 and P2 are equivalent parameters.

Now, we have the problem to define when a component, a service or a list of parameters can be

replaced by other and we define the following rules for components, services and parameters

replacement:

A component C1 can be replaced by itself (trivial), by a sameAs component or by a component

of an equivalentClass or by a component of a subClassOf.

A service S1 can be replaced by itself (trivial), by a sameAs service or by an

equivalentProperty service.

A list of parameters P1 can be replaced by the list P2 when for all parameter in P1 it can be

replaced by other one in P2 (it is the same, equivalent or a subclass).

4 Implementation Details

In order to a better illustration of the implementation details we are going to use a simple example

implemented in C#. Suppose we are developing an application for solving rectangle triangles. We

find and select a component that provides services for solving that kind of triangles which presents

the following interface:

Fig. 2. This figure shows the interface provided by the RectangleTriangle Component.

There is only one problem with that component: it works in radians and our application has to

work in degrees. So we have to develop one adaptor in order to solve that interoperability

mismatch. The adaptor can be developed ad hoc or using any existing tool [8], [9], [10] and it

basically has to transform degrees into radians before calling the service of the RectangleTriangle

component and transform radians into degrees after the service has returned an angle. It could be

as shown in the following code:

class RectangleTriangleAdaptor

{

const double PI = 3.1416;

RectangleTriangle server;

...

public double getAdjacentSide(double angle, double hypothenuse)

{ double angle2 = Degree2Radian(angle);

result = server.getAdjacentSide(angle2, hypothenuse);

return result;

}

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 4

Page 5: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

public double getAngle(double oppositeSide, double adjacentSide)

{ double result;

result = server.getAngle(oppositeSide,adjacentSide);

result = Radian2Degree(result);

return result;

}

...

}

The system works properly until we get a new version of the server component (or it is changed

without our knowledge, for example RectangleTriangle could be a webservice or a remote

component). Now, the new server component has modified some services and their names or

parameters have changed. Then, when we call the old service we get a ―not found service‖

exception because there is an architectural mismatch that has to be solved and the call has to be

adapted at run-time.

Our proposal is based on using an ontology to express which classes (components or parameters),

and services are equivalent, are the same one or are a subclass. This knowledge can be used to

determine the new call to be done to the new component.

Let us show how the following ontology (only a fragment shown), written in OWL, can be used to

adapt a ―not found‖ service in our example. . . .

<owl:Class rdf:ID="RectangleTriangle"> </owl:Class>

<owl:Class rdf:ID="double"></owl:Class>

<owl:Class rdf:ID="string"></owl:Class>

<owl:Class rdf:ID="int"> <rdfs:subClassOf rdf:resource="#double"/> </owl:Class>

<owl:Class rdf:ID="float"> <owl:equivalentClass rdf:resource="#double"/>

</owl:Class>

<owl:Class rdf:ID="rectangle_triangle">

<owl:equivalentClass rdf:resource="#RectangleTriangle"/>

</owl:Class>

. . .

<owl:ObjectProperty rdf:ID="getAngle(double,double)">

<rdfs:domain> <owl:Class rdf:about="#RectangleTriangle"></owl:Class>

</rdfs:domain>

</owl:ObjectProperty>

<owl:ObjectProperty rdf:ID="getHypothenuse(double,double)">

<rdfs:domain> <owl:Class rdf:about="#RectangleTriangle"></owl:Class>

</rdfs:domain>

</owl:ObjectProperty>

. . .

<owl:ObjectProperty rdf:ID="PythagorasTheorem(double,double)">

<owl:equivalentProperty rdf:resource="#getHypothenuse(double,double)"/>

</owl:ObjectProperty>

<owl:ObjectProperty rdf:ID="CalculateAngle(double,double)">

<owl:sameAs rdf:resource="#getAngle(double,double)"/>

</owl:ObjectProperty>

</rdf:RDF>

The first step taken is to translate the ontology into a list of PROLOG facts where we show the

inherence relationships, what (classes, services, etc) are equivalent (or same as) to what, etc. That

is not hard, it is only necessary to take classes, subclasses, properties, equivalences, and equalities.

This way, the OWL file shown before is translated to the following PROLOG facts:

We set the classes defined in the ontology: owlClass(rectangletriangle).

owlClass(double).

owlClass(string).

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 5

Page 6: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

We set the subclasses defined in the ontology: owlSubClassOf(double, int).

We set the equivalent classes defined in the ontology: equivalentClass(float, double).

equivalentClass(rectangle_triangle, rectangletriangle).

We set the services defined in the ontology (component, service and list of parameters): objectProperty(rectangletriangle,getadjacentside,[double,double]).

objectProperty(rectangletriangle,getangle,[double,double]).

objectProperty(rectangletriangle,gethypothenuse,[double,double]).

objectProperty(rectangletriangle,getside,[double,double]).

We set the services which are equivalent defined in the ontology: equivalentProperty(pythagorastheorem, gethypothenuse).

And finally, we set which symbol is the same to other symbol defined in the ontology: sameAs(calculateangle, getangle).

Following, some rules are added to express some properties, such as the reflexive, symmetric and

transitive properties of equality (same as), etc. Finally, replacement rules are included. This way, a

class can be replaced by a subclass or by a ―same as‖ class or by an equivalent class and a service

can be replaced by a ―same as‖ service or by an equivalent service. Therefore, we can invoke a

different service (different name and/or parameters) which is equivalent to the requested one.

canBeReplaced(C1,S1,P1,C2,S2,P2):- owlClass(C1), canBeReplacedClass(C1,C2),

objectProperty(C1,S1,P1), canBeReplacedProperty(S1,S2),

equivalentParam(P1,P2).

canBeReplacedClass(C,C).

canBeReplacedClass(C1,C2):- sameAsReflexiva(C1,C2).

canBeReplacedClass(C1,C2):- owlSubClassOf(C2,C1).

canBeReplacedClass(C1,C2):- equivalentClassReflexiva(C1,C2).

canBeReplacedProperty(S,S).

canBeReplacedProperty(S1,S2):- sameAsReflexiva(S1,S2).

canBeReplacedProperty(S1,S2):- equivalentPropertyReflexiva(S1,S2).

equivalentParam([],[]).

equivalentParam([X|R1],[X|R2]):- owlClass(X), equivalentParam(R1,R2).

equivalentParam([X|R1],[Y|R2]):- owlClass(X),owlClass(Y),

canBeReplacedClass(X,Y), equivalentParam(R1,R2).

This way, it is possible to establish who and what can be replaced by who or what. And then, we

can solve the architectural mismatch and to invoke an existing service using reflection in the

following method:

public object adapt(object server, string serviceName, object[]param)

{

Type serverType = server.GetType();

MethodInfo service = serverType.GetMethod(serviceName);

try

{

return service.Invoke(server,param);

}

As you can see, we try first to invoke the method requested, and we do nothing if it goes well.

However, when it fails and an exception is raised. We catch it and adapt the service as it shows in

the following code:

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 6

Page 7: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

catch (Exception)

{

. . .

SymbolTerm C = SymbolTerm.MakeSymbol(getClassName(server));

SymbolTerm S1 = SymbolTerm.MakeSymbol(serviceName.ToLower());

Term P1, P2;

. . .

P1 = list_param(typeParamList);

foreach (MethodInfo m in serverType.GetMethods())

{

SymbolTerm S2 = SymbolTerm.MakeSymbol(m.Name.ToLower());

bool ok;

PrologInterface sharp = new PrologInterface();

sharp.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly());

. . .

P2 = list_param(typeParamList2);

sharp.SetPredicate(new Can_Be_Replaced_6(C, S1, P1,C, S2, P2,

new ReturnCs(sharp)));

ok = sharp.Call();

if (ok)

{

return m.Invoke(server, param);

}

}

return null;

}

As can be seen in the previous code we get all the methods given by the current server using

reflection and test if someone of them (service and parameters) can replace to the ―not found‖

service.

This test is done by the PROLOG machine offered P# [11], invoking the predicate

Can_Be_Replaced with the server name, service name and service parameters of the ―not found‖

service and the candidate service to replace it.

Of course, all the code for the adaptation as well as the translation from owl to PROLOG is

automatically generated by our tool.

Finally, our tool modifies the original adaptor (like shown in the following code) in order to call

the adapt method instead of calling directly to the server.

public double getAdjacentSide(double angle, double hypothenuse)

{

object[] parametres = new object[2];

double result;

parametres[0] = Degree2Radian(angle);

parametres[1] = hypothenuse;

result = (double)adapt(server, "getAdjacentSide", parametres);

return result;

}

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 7

Page 8: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

5 Related Work

Since [12], adaptation techniques have been proposed to correct component mismatch building

adaptors. [13] makes significant advances with an approach supporting name mismatch, system

wide adaptation (more than two components) and event reordering. But, all these approaches

require the computation of a global adaptor, which is costly, and none supports open systems,

which prevents application to pervasive systems.

Much previous work has dealt with the problems of component adaptation and evolution as a

programming language problem, and several language features have been proposed that can

address some (but not all) problems. Descriptive classes [14] allowed the programmer to create

supertypes after the fact, solving part of the integration problem. However, this adaptation is static

(not at run time) and does not keep the idea of components as black boxes.

In [15], Senivongse and Utting propose a model for evolution of services in distributed systems

based on the Reference Model for Open Distributed Processing (RM-ODP). They introduce

mapping operators that can bridge the difference between two different versions of the same

service. Although mapping operators are restricted on service versions they support a wide range

of changes to an interface type that makes them rather similar to the adapters of our framework. In

contrast to our proposal, the mapping operators are not generated at run time. Their code is

generated (automatically or not), compiled and introduced in the system.

Much of the works on Semantic web techniques for web services (OWL-S [16], METEOR-S [17]

and WISMO [18]) are oriented to the discovery process. They are used for finding the component

(web service) offering the service we need but they do not solve the problem of the adaptation.

Product-Line software engineering [19] is an approach that adapts components when a family of

related software systems is to be developed. This adaptation can be static (conditional compiling)

or dynamic (using one skeleton object). However, the adaptation done develops a new system but

does not solve the problem of a ‗not found‘ request service at a run-time due to the system has

evolved or a component has been updated.

Works on adaptation of open component system and services [20], [21] are very interesting. They

are based on putting in or taking out services in a pool and those services implements a known

interface. However, they do not work when the interface of the new component is unknown.

6 Conclusions and Future Work

The integration of software components often requires a certain degree of adaptation. Adaptation

approaches have addressed closed systems and the distribution of global adaptors but to our

knowledge, none supports open systems. Thus, they are not well suited to systems where

components or services may enter and leave at any time, such as pervasive ones.

To address this issue, as well as component evolution problem, current work shows the

implementation in C# of a solution to the dynamic adaptation for the architectural mismatch at run

time problem using an ontology to express which components and which services can be replaced,

a PROLOG machine for inference and the capability of reflection provided by the .NET platform

for component examination and service invocation.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 8

Page 9: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

The idea proposed does not exclude the use of other adaptation techniques, even more; we think

our work can be complementary. In addition, the adaptors generated are middleware between

components what allows to compose local components as well as distributed components.

As future work we want to improve the tool developed in order to integrate architectural and

interoperability adaptation in a single framework. As well, we are thinking on improving services

with a .NET attribute to express the semantic of the service and improving classes in the same way

to express the semantic of the parameters of a service. This way, we avoid doing the supposition of

service and class name is significant of its semantic.

References

1. Garlan, D., Allen, R., Ockerbloom, J.: Architectural Mismatch: Why Reuse Is So Hard. IEEE Software.

12(6), 17--26 (1995).

2. Konstantas, D.: Interoperation of Object-Oriented Applications. In: Nierstrasz, O., Tsichritzis D. (eds)

Object-Oriented Software Composition. pp 69--95. Prentice Hall, (1995).

3. Sametinger, J.: Software Engineering with Reusable Components. Springer, (1997).

4. Berners-Lee, T. Hendler, J., Lassila, O: The Semantic Web. Scientific American. 284(5), 34--43 (2001).

5. Hendler, J. Berners-Lee, T., Miller, E.: Integrating applications on the Semantic Web. Journal IEEE

Japan. 122(10), 676--680 (2002).

6. Gruber, T.: Toward Principles for the Design of Ontologies Used for Knowledge Sharing. International

Journal Human-Computer Studies. 43(5-6), 907—928 (1993).

7. OWL Web Ontology Language Use Cases and Requirements, http://www.w3.org/TR/webont-req/

8. Reussner, R.H.: Automatic Component Protocol Adaptation with the CoCoNut Tool Suite. Future

Generation Computer Systems 19, 627—639 (2003).

9. Kent, S.D., Ho-Stuart, C., Roe, P.: Negotiable interfaces for components. Fourth Australasian Workshop

on Software and Systems Architectures, Melbourne, Australia (2002).

10. Vanderperren, W., Wydaeghe, B.: Towards a new component composition process. 8th Annual IEEE

International Conference and Workshop on the Engineering of Computer Based Systems, pp. 322—331.

Washington, USA (2001).

11. Cook, J.: P#: A concurrent Prolog for the .NET Framework. Software: Practice and Experience,

34(9),815--845 (2004).

12. Yellin, D.M., Strom, R.E.: Protocol Specifications and Components Adaptors. ACM Transactions on

Programming Languages and Systems 19(2), 292–333 (1997).

13. Canal, C., Poizat, P., Salaün, G.: Synchronizing Behavioural Mismatch in Software Composition. In:

Gorrieri, R., Wehrheim, H. (eds.) FMOODS 2006. LNCS, vol. 4037, Springer, Heidelberg (2006).

14. Sandberg, D. An Alternative to Subclassing. OOPSLA ‗86 Conference Proceedings, pp. 424-428,

Portland, OR, October 1986. Published as SIGPLAN Notices 21(11) (1986).

15. Senivongse T. and Utting I.A. ―A model for evolution of services in distributed systems‖ In Proceedings

of the IFIP/IEEE Int. Conference on Distributed Platforms. Schill A., Mittasch C., Spaniol O., and Popien

C. (Eds.) Distributed Platforms. Chapman & Hall (1996).

16. Martin, D. et al. OWL-S: Semantic Markup for Web Service. SUBM-OWL-S-20041122 W3C Member

Submission, Cambridge, USA (2004).

17. Verma, K. et al. METEOR-S WSDI: a scalable infrastructure of registries for semantic publication and

discovery of web services. J. Inf. Technol. Manag., 6, 17–39 (2005).

18. Domingue, J., Cabral, L., Hakimpour, F., Sell, D. and Motta, E. IRS III: a platform and infrastructure for

creating WSMO-based semantic web services. Proc. Workshop on WSMO Implementations, Frankfurt,

Germany, September 29–30, pp. 23–33. Digital Enterprise Research Institute (DERI), Innsbruck (2004).

19. Brown, T., Spence, I., Kilpatrick, P. and Crookes, D. Adaptable components for software product line

engineering. Proc. Software Product Lines: Second Int. Conf., San Diego, USA, August 19–22, pp. 154–

176. Springer, Berlin (2004).

20. Poizat, P. and Salaun, G. Adaptation of Open Component-based Systems. Proc. of Formal Methods for

Open Object-based Distributed Systems (FMOODS'07). LNCS 4468, pp. 141–156, 2007

21. Irmert, F., Fischer, T. and Meyer-Wegener,K. Runtime Adaptation in a Service-Oriented Component.

Proc. of SEAMS'08. ACM, 2008.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 9

Page 10: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Using Variability Models for DevelopingSelf-configuring Pervasive Systems ?

Carlos Cetina, Pau Giner, Joan Fons, Vicente Pelechano

Centro de Investigacion en Metodos de Produccion de SoftwareUniversidad Politecnica de ValenciaCamino de Vera s/n, E-46022, Spain

{ccetina, pginer, jjfons, pele}@dsic.upv.es

Resumen. Pervasive computing is defined as a technology that weaves itself into thefabric of everyday life until it is indistinguishable from it. To be successful, pervasiveservices should be transparent to the user. Such transparency is achievable only ifthe software frees users from having to repair and reconfigure the system when faultsor changes occur in the environment. This paper introduces an strategy for develop-ing self-configuring pervasive systems that is based on Software Product Lines (SPL)principles. Variability models of SPLs are interpreted at run-time to reconfigure per-vasive systems according to the fluctuations on the environment. We have developeda self-reconfigurable software system that manages a smart home in order to validatethis strategy by means of device plug/unplug tests.

Palabras clave: Smart Home, Self-Configuring, Software Product Lines, Model DrivenDevelopment.

1 Introduction

Increasingly, software needs to dynamically adapt its behavior at run-time in response tochanging conditions in the supporting computing infrastructure and in the surroundingphysical environment [1]. Adaptability is emerging as a necessary underlying capability,particularly for highly dynamic environments. This is the case of most Pervasive Systems.

Pervasive computing is defined as a technology that “weaves itself into the fabric of ev-eryday life until it is indistinguishable from it” [2]. To be successful, the pervasive computingfunctioning should be transparent to the user. Such transparency is achievable only if thesoftware frees users from having to repair and reconfigure the system when faults or changesoccur in the environment.

Pervasive systems are highly dynamic and fault-prone since their components are liableto appear and disappear at any time. On the one hand, new kinds of entities (devices suchas media players, light sensors or fire alarms) can be incorporated to the system. On theother hand, existing entities may fail or be disconnected from the system for a variety ofreasons: hardware faults, OS errors, software bugs, network faults, etc.

The dynamic and fault-prone nature of pervasive systems makes it necessary to providenew techniques to ensure their smooth operation. Only in this way pervasive systems canbe effectively integrated in the environment. The present work introduces a strategy fordeveloping self-configuring Pervasive Systems.

Software Product Line (SPL) defines production methods for similar products. SPL isnot only focused on the design of a particular product, but the whole family of products.? This work has been developed with the support of MEC under the project SESAMO TIN2007-

62894 and cofinanced by FEDER, in the grants program FPU.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 10

Page 11: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

In order to do so, commonalities and variability of these products are captured in terms ofsystem features. To define a particular product, features are selected and/or discarded. Forexample, defining a particular smart home for a client implies selecting the desired features(e.g., security system, lightning control, etc.) from all the available features (defined in thesmart home product family).

In addition to the demanded features, the final product can contain some “extra” fea-tures. These features are disabled initially but they can be enabled when the product isreconfigured. For example, a smart home can include the alarm software system that is ac-tivated when the user installs some alarm device. If this reconfiguration process is achievedin an autonomic way, we obtain a self-configuring system.

The main contribution of the present work is the definition of self-configuration mecha-nisms for Pervasive Systems facing the reconfiguration process from a modeling perspective.The strategy defined is based on SPL foundations and it supports the activation and deacti-vation of system features but also the inclusion of new features (i.e., support the evolution ofthe product). By facing the definition of particular systems and families from a modeling per-spective, technological details are avoided, raising the abstraction level in the developmentof such systems.

The remainder of the paper is structured as follows. Section 2 provides an overview ofthe reconfiguration scenarios that are taken into account in this work. Section 3 defines thereconfiguration strategy proposed to cope with the requirements of the identified scenarios.Section 4 illustrates the models which capture system variability in order to enable recon-figuration. Section 5 exemplifies the use of these models to perform system reconfigurationin the context of a smart home. Related work is presented in Section 6. Finally, section 7presents conclusions and further work.

2 Scenarios for Reconfiguration

There are many situations in which a pervasive system needs to be reconfigured. Through theanalysis of different reconfiguration needs we have detected several suitable reconfigurationscenarios [3]. However, we have mainly classified them in two groups:

– Involution Scenarios: in these scenarios the set of active features changes but new featuresare not included. The new configuration of a system is performed using the availablefeatures, activating or deactivating them. This kind of scenario happens whenever anadaptation is triggered from the system.

– Evolution Scenarios: the set of features is modified (by the usage of a new feature or theupdate of an existing one). The new configuration of a system can be considered a newversion.

These two kinds of scenarios can impact the system in a different degree. Involutionscenarios involve only a change in the feature state (e.g., enable or disable a feature), so thepossible combination of active features is limited. Thus, the number of involution scenariosis finite. However, evolution scenarios are difficult to be anticipated for a system as unknownfeatures may appear.

Considering the time dimension, involution scenarios occur in a more unexpected waythat evolution scenarios. Evolution scenarios commonly respond to an upgrade intent. Theseupgrading activities can be scheduled, making evolution scenarios more predictable (userscan decide when to upgrade). However, involution scenarios might arise from unpredictableevents such as a device breakdown or an unavailable service. In these cases, the fastestresponse is needed to restore an stable state of the system where functionality is at leastmaintained or reduced as few as possible.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 11

Page 12: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

3 A Reconfiguration Strategy

In the environment full of embedded services that Pervasive Computing envisions there islittle space for configuration at the user side. Users demand a minimal configuration effortto incorporate new features or repair their systems. Therefore, involution and evolutionscenarios should be supported in a sound way. In this section, an strategy defined to copewith both kinds of scenarios is described.

Fig. 1. Involution and evolution scenarios

Figure 1 illustrates an overview of this strategy for both kind of scenarios. Is worthnoting that the Software Product Line is only involved in the evolution scenarios. Whileinvolution scenarios require no connection with the product line since the features includedin the product are not augmented.

As the number of involution scenarios is finite and can be foreseen, a contingency planmay be built so that the system could know how to react in these cases, giving an optimumresponse and restoring itself quickly to the state where most of the services are correctlyworking.

We propose a self-reconfiguring strategy which addresses both evolution and involutionscenarios. Figure 2 shows the strategy steps in order to perform reconfiguration by a perva-sive system.

1. Both changes in the environment and in the system itself can trigger the adaptationprocess. These changes start the adaptation process.

2. The system calculates a new configuration to deal with the sensed change. These config-urations are calculated using the variability models which describe the system in termsof features.2.1 If there is no configuration that resolves the adaptation trigger, then the system

delegates the adaptation to the SPL. Therefore, the system sends information aboutthe adaptation to the SPL. Optionally, the system can preprocess the informationlocally and send then a more specific information to the SPL.

2.2 The SPL incorporates the acquired information to the product requirements andthen it calculates a new system variant.

2.3 If there is no variant that satisfies the product requirements, then the SPL notifiesthe system and the adaptation process fails.

2.4 The SPL generates the update for the system. The update can be the whole calcu-lated variant or the difference between the old variant and the new one.

2.5 The SPL sends the update to the system.2.6 The system updates itself using the update from the SPL and the adaptation process

ends.3. The system reconfigures itself to apply the calculated configuration. The reconfigura-

tion operation implies (1) starting/stoping components and (2) establishing connectionsbetween them.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 12

Page 13: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Fig. 2. Adaptation Strategy

This is a global strategy which addresses both evolution and involution scenarios. Next, weanalyze the strategy from either the evolution perspective or the the involution perspective.From the involution perspective, we characterize the strategy from the following points ofview:

– Autonomic degree. The system does not depend on the SPL in order to performthe adaptation because there is no connection between the SPL and the system. Theadaption depends only on the system resources.

– Adaptation capabilities. In general, the more variability knowledge the system hasabout itself and its variants, the more adaptable the system will get. This knowledge iscaptured in the variability models incorporated to the system. However, the variabilitymodels must be complemented with system components. Some components conformthe initial system configuration, while the others are used in system reconfiguration. Inconclusion, the adaptation capabilities depends on the knowledge captured in the modelsand on the number of components for system reconfiguration.

– Computational overload. The self-reconfiguring strategy introduces a computationaloverload to the system execution when the adaptation is triggered. This overload comesfrom (1) the model queries and (2) the execution of the reconfiguration (starting stoppingand linking system components).

From the evolution perspective, we characterize the strategy as follows:

– Autonomic degree. The system depends on the SPL availability to perform the adap-tation, because the system gets updates from the SPL to perform the adaptation.

– Adaptation capabilities. To address an evolution scenario, variability models indicatethe necessary components. However, some of these components are not in the system. Inthis case, the system has to get these components from the SPL. Thus, the adaptationcapabilities depends on the available components at the SPL.

– Computational overload. Compared with involution scenarios, an evolution scenariointroduces the following additional overload: 1) the communication with the SPL (to getsystem updates) and (2) the on-line installation of updates.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 13

Page 14: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

This reconfiguration strategy is supported by a (1) reconfiguration framework and aset of (2) variability models. The (1) reconfiguration framework provides the underlyinginfrastructure for adaptation and it was presented in a previous work [4]. This frameworkis based on OSGI [5] and it implements a complete and dynamic component model wherecomponents can be remotely installed, started, stopped, updated and uninstalled withoutrequiring a reboot. The (2) variability models describe the feasible combinations of thesecomponents, these models are described in next section.

4 The Variability Models for System Reconfiguration

We illustrate the proposed Variability Models for Self-Configuring Pervasive Systems bymodeling a smart home: a localized technology-augmented environment where people per-form everyday life activities. The Variability Models address automated lighting, presencedetection and security functionality for the smart homes. Models also describe all the smarthome variants which have been foreseen.

To model the smart home, we use PervML, a feature model and a realization model.PervML is Domain Specific Language to describe Pervasive Systems [6]. Feature Modelingis a technique to specify the variants of a system in terms of features [7], and the realizationmodel describes default and alternative relationships between models [8].

4.1 The Feature Model

Feature models are widely used to describe variations of a specific system in terms of features.Features are hierarchically linked in a tree-like structure with the following relationships:Alternative (white triangle), OR (black triangle), optional (white circle) and mandatory(black circle). Also, feature models specify feature constraints as dependency (dotted arrow)and exclusion (dotted double arrow). Feature modeling captures variants knowledge relatedto Evolution Scenarios.

A feature model (see the top of Figure 3) determines the initial and the potential featuresof the smart home. The grey features are the features selected to specify a member of thesmart home family. The white features represent potential variants. Initially, the smart homeprovides automated lighting and a security system. This security system relies on perimeterpresence detection (outside the home) and a visual alarm. The system can potentially beupgraded with in-home presence detection and more alarms to enhance home security.

Supporting a evolution scenario implies enabling more features. Some features can beenabled by plugging in new physical resources, while other features can be enabled becausethe constraints (mandatory, excludes or requires) are resolved. For instance, features (8) and(13) can be enabled if a volumetric detector is plugged in. Then, the requires dependencyfrom (2) to (8) can be resolved, allowing the entablement of feature (2).

4.2 The PervML Model

Pervasive Modeling Language (PevML) [6] is a DSL for describing pervasive systems usinghigh-level abstraction concepts. This language is focused on specifying heterogeneous servicesin concrete physical environments such as the services of a smart home. The main conceptsof PervML are: (1) a Service coordinates the interaction between suppliers to accomplishspecific tasks (these suppliers can be hardware o software systems); and (2) Binding Provider(BP) is a supplier adapter that embeds the issues of dealing with heterogeneous technologies.

The PervML Model describes the pervasive system itself, providing knowledgeabout both services and resources. The BP concept is the key element for managing new

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 14

Page 15: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

<<Service>>

(a) Presence

Simulation

<<Service>>

(b) Presence

Detection

<< Service>>

(c) Alarm

<<Trigger>>

(e) Random

Simulation

Starter

<< Trigger>>

(f) Presence

Detected

<< BP>>

(j) Perimeter

Detector

<< BP>>

(l) Infrared

Detector

<< BP>>

(n) Visual Alarm

<< Interaction>>

(g) Security

<< BP>>

(m) Silent

Alarm

<< BP>>

(h) Automated

Lighting

<< BP>>

(i) Volumetric

Detector

1

<< BP>>

(k) Blink

Lighting

2

<< BP>>

(o) Buzzer

<< Service>>

(d) Automated

Lighting

(1) Smart Home

(7) Perimeter Detection

(2) Presence Simulation

(6) Alarm

(11) Visual Alarm

(3) Security

(10)

Siren

(4) Automated Illumination

(5) Presence Detection

(13) Volumetric 360

degree Detection

(8) In home Detection (9) Silent

Alarm

(12) Infrared 160 degree

Detection

2

1

Requires

Fea

ture

Mod

el

Evolu

tio

n S

cen

ari

o K

now

led

ge

Per

vM

LM

od

el

Sy

stem

Its

elf

Kn

ow

led

ge

(3) <<Default>> (g)

(5) <<Default>> (f)

(5) <<Default>> (b)

(12) <<Default>> (l)

(2) <<Default>> (a)

(6) <<Default>> (c)

(9) <<Default>> (m)

(10) <<Default>> (o)

(2) <<Default>> (e)

(2) <<Default>> (h)

(2) <<Default>> (i)

(7) <<Default>> (j) (11) <<Alternative>> (k)(4) <<Default>> (a)

(4) <<Default>> (h)

Security

Presence Detection Alarm

Presence Simulation

Automated Illumination

2

(11) <<Default>> (n)

(13) <<Default>> (i)1

Rea

liza

tio

n M

od

el

Invo

luti

on

Sce

nari

o K

now

led

ge

Fig. 3. Variability Modeling for System Reconfiguration

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 15

Page 16: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

resources. BPs provide a level of indirection between Services and Resources. Resource oper-ations interact with the environment (sensors and actuators) and provide functionality fromexternal software systems. Services coordinate these resource operations to offer high-levelfunctionality. If the resource operations do not match the Service expectations, then a BP isused to adapt these operations. Hence, the BPs decouple Services from resource operations.This property is essential for introducing extensibility to new devices and avoids having tomodify existing Services to support the operations presented by new devices.

This model (see the bottom of Figure 3) describes the building blocks for the assemblyof a pervasive system. The grey blocks are deployed in the system and the implement thefunctionality of the selected features. The (a), (k) and (e) blocks implement the functionalityfor the unselected Presence Simulation feature. The (i), (l), (m), and (o) blocks would benecessary for new resources that can become available.

4.3 The Realization Model

The Realization Model is an extension that we have incorporated to Atlas Model Weaving(AMW) [8]. AMW is a model for establishing relationships between models. Our extensionaugments the AMW relationship with the default and alternative tags. This augmentedrelationship is applied between features and PervML elements (BPs and Services). In thecontext of a BP, the default relationship means that the BP is selected for the initial con-figuration of the system. The alternative relationship means that the BP is considered as aquiescent element that should be incorporated to the SPL product, but it does not partic-ipate in the initial configuration. Quiescent BPs provide an alternative BP to replace thedefault BP in case of fault. The more quiescent BPs that can be identified, the more flexiblethe adaptation will be.

The Realization Model provides knowledge related to Involution Scenarios. The levelof indirection introduced by the BPs facilitates the use of alternative resources, and theRealization Model determines the applicability of the BPs. Self-reconfiguration is performedby applying a quiescent BP to a suitable resource. Quiescent elements and the RealizationModel enable the Autonomic Reconfiguator to establish a dynamic binding at run-time.

This model (see the middle of Figure 3) establishes the relationships between the featuresand the PervML elements. Section 4.3 introduced the alternative relationship in order toidentify BPs and Services that mitigate system faults. For instance, the visual alarm featureis related to a BP (n) for visual alarms, but, alternatively, it can be replaced with a BP (k)that emulates the visual alarm by using the general lighting.

The knowledge from all these models supports the Model-Based strategy presented inSection 3 in order to establish a dynamic binding between the system components.

5 Exemplifying the System Reconfiguration

Reconfiguration models enable the system to identify which PervML elements must be activeto satisfy a system feature. In foreseen involution scenarios, these PervML elements arealready in the system and the system just has to active them. However in evolution scenarios,the system has to get the PervML elements from the SPL. We have extended a previouslydeveloped case study [10] with reconfiguration capabilities following the presented approach.In order to validate the proposal for evolution and involution scenarios we have appliedplug/unplug tests as follows:

5.1 Plug Test for Evolution Scenario

In the smart home example, the security system relies on a presence detection service.This service integrates the functionality of several sensors. Hence, the more coverage the

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 16

Page 17: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

sensors have, the more reliable the service will be. We can improve the security coverage byincorporating a new in-home volumetric detector. When the volumetric detector is plugged,the Presence Detection Service needs to be aware of its notifications.

Following our strategy, plugging the device is the trigger to establish a new relationshipbetween resources and services using the models knowledge. The Feature Model (see Figure3) shows that the presence service can be extended with in-home detection such as thevolumetric detector. However, these models also indicate that the volumetric detector driveris not in the system (the model element (13) is filled in white color). Therefore, the systemhas first to get the Binding Provider from the SPL in order to perform the reconfiguration.Once the system gets the update, the Binding Provider is activated and linked with thepresence service. We presented in a previous work [4] the underling infrastructure to performactivation and linking by means of the OSGI framework.

5.2 Unplug Test for Involution Scenario

In a security service, the alarm is a key element. A fault (or manipulation) of this devicecan invalidate the entire security service. The aim of this device is to alert the neighbors ofan unexpected situation in the house. This unplug test focuses on a backup alarm, whichconsists on a fast and constant blinking of all the home lights.

When the Visual Alarm fails, the Alarm Service needs an alternative supplier. The re-alization model enables the strategy to identify alternative components of a system feature.The realization model of Figure 3 shows that Automated Lights can be adapted to simulatea visual alarm. The BP (k) is selected to adapt the behavior of the Automated Lights byperforming a continuous blinking. The relevant model elements of this example are denotedwith the number 2 in Figure 3. In this case, the system already has the driver for blinkinglighting because this is a foreseen scenario.

The system can reconfigure itself in both evolution and involution scenarios, howeverin the case of evolution scenarios the system needs a confection with the SPL to get theupdates.

6 Related Work

Several SPL-based approaches that focus their efforts on developing configurable systems.An overview of these SPL is presented next:

– Gomaa. Reconfigurable Product Line UML Based Environment (RPLUSEE) [11] wasproposed by Gomaa et al. Their main contribution is provisioning software dynamicreconfiguration patterns. Depending on the location of dynamic reconfiguration infor-mation, these patterns are classified into master-slave, centralized, client-server and de-centralized. This method also provides reconfiguration Statechart and reconfigurationtransaction models for the dynamic reconfiguration. This approach focuses on high-levelspecifications of dynamic reconfigurable units; however, it does not describe techniquesand guideline for for reconfigurable component identification, design and implementa-tion detail.Adaptation Trigger. Users specify runtime configuration changes so that executablesystem is dynamically changed from the old configuration to the new configuration.

– Lemlouma. Lemlouma et al. [12] present Negotiation and Adaption Core architecturefor adapting and customizing content before delivering it to a mobile device. Theirstrategy takes into account device preferences and capabilities which are specified usinga device independent model. These models are queried using the XQuery language andthe adaptation is achieved by means of client repositories and SOAP services.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 17

Page 18: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Adaptation Trigger. There is a real time evaluation of the context dimensions. Lem-louma explicitly identifies the following context dimensions: user preferences, networkspeed and current confection protocol.

– Lee. Lee et al. proposed a systematic method to developing dynamically reconfigurablecore assets and a reconfigurator that monitors and manages product configuration atrun-time [13]. The method first analyzes a product line in terms of features and theirbinding time. Then, core assets are developed with the analysis results as key designdriver. Finally, the developed reconfigurator addresses reconfiguration contexts, recon-figuration strategies and reconfiguration actions (what to do to reconfigure).Adaptation Trigger. The configuration plane is in charge of detecting contextualchanges. The plane consists of two components: Master Configurator and Local Con-figurator. Master Configurator collects information from Local Configurators and/orexternal probes to detect contextual changes. Each Local Configurator monitors localmessages within the product.

– Hallsteinsen. The MADAM approach [14] was developed by Hallsteinsen et al. Thisapproach builds adaptive systems as component based systems families with the vari-ability modeled explicitly as part of the family architecture. MADAM uses propertyannotations on components to describe their Quality of Service. For example a VideoStreaming component may have properties such as start up time, jitter and frame drop.At run-time, the adaptation is performed using these properties and a utility functionfor selecting the component that best fits the current context.Adaptation Trigger. The Context Manager is responsible for managing and monitor-ing a set of contexts in the system environment relevant for the adaptation. Contextincludes execution platform context elements such as network and memory resources,the environment context elements such as light and noise, and user context elementslocation and stress level.

– White. The Scatter tool [15] was developed by White et atl. to address efficient onlinevariant selection. Scatter captures the requirements of the product line architecture andthe resources of a mobile device and then quickly constructs a custom variant for thedevice. This tool also ensures that variant selection is optimal with regard to a config-urable cost function.Adaptation Trigger. A mobile device discovery service obtains the non-functionalproperties of a devices such as JVMVersion or Position. This service is implementedusing SOAP-based web service and a CORBA remoting mechanism for remotely com-municating device characterizations as they are discovered.

– Trinidad. Trinidad et al [16] present a process to automatically build a componentmodel from a feature model based on the assumption that a feature can be modeled asa component. This process focuses on enabling a dynamic SPL to dynamically changinga product by activating or deactivating its features at run-time.Adaptation Trigger. One o more users set the requirements of the product.

On the one hand, some approaches –Lemlouma, White– produce highly adaptable sys-tems. However, adaptation implies that systems must stay connected with their SPL. On theother hand, the other approaches –Gomaa, Lee, Hallsteinsen, Trinidad– produce autonomicsystems which have a shorter adaptation range, but they do not need to stay connected witha SPL in order to adapt itself.

Our model-based strategy bridges the gap between these highly adaptive approaches –butno autonomic– and autonomic approaches –but no highly adaptive–. In involution scenarios,our strategy provide highly adaptivity while, in evolution scenarios our strategy providesautonomic behavior.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 18

Page 19: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

7 Conclusions

In order to allow a seamlessly integration of Pervasive Systems in the environment, weconsider essential to free the user from configuration tasks. In this context, the present workintroduces an approach to develop self-configuring Pervasive Systems.

We have defined a strategy for the reconfiguration of pervasive systems based on solidengineering approaches of both fields, pervasive systems and SPL. PervML and Fama featuremodel allowed us to work at modelling level providing a high level perspective of pervasivesystem families. Thanks to these techniques we can capture the variability of PervasiveSystems by means of models. These models can be later used by the system to decide howto adapt itself in both evolution and involution scenarios. In this way, when some resourcesare incorporated or missing from the system, the system can keep providing its services inthe best available way.

As further work, the application of the proposal to more real scenarios (out of the lab),can provide valuable feedback. By the study of a heterogeneous group of users, user experi-ence can be evaluated to check in which degree the system behaves as expected.

Referencias

1. P.K. McKinley, S.M. Sadjadi, E.P. Kasten, and B.H.C. Cheng. Composing adaptive software.Computer, 37(7):56–64, July 2004.

2. Mark Weiser. The computer for the 21st century. SIGMOBILE Mob. Comput. Commun. Rev.,3(3):94–104, 1999.

3. Carlos Cetina, Joan Fons, and Vicente Pelechano. Applying Software Product Lines to BuildAutonomic Pervasive Systems. Software Product Line Conference, 2008. SPLC 2008. 12thInternational, 8-12 Sept. 2008.

4. Pau Giner, Carlos Cetina, Joan Fons, and Vicente Pelechano. A framework for the reconfigura-tion of ubicomp systems. 3rd Symposium of Ubiquitous Computing and Ambient Intelligence(UCAmI), 2008.

5. D. Marples and P. Kriens. The open services gateway initiative: an introductory overview.Communications Magazine, IEEE, 39(12):110–114, Dec 2001.

6. Javier Munoz and Vicente Pelechano. Building a software factory for pervasive systems devel-opment. In CAiSE, pages 342–356, 2005.

7. K. Czarnecki, S. Helsen, and U. Eisenecker. Staged configuration using feature models. InProceedings of the Third Software Product Line Conference 2004, pages 266–282. Springer,LNCS 3154, 2004.

8. Marcos Didonet Del Fabro, Jean Bzivin, and Patrick Valduriez. Weaving models with theeclipse amw plugin. In Eclipse Modeling Symposium, Eclipse Summit Europe 2006, Esslingen,Germany, 2006.

9. Javier Munoz and Vicente Pelechano. Applying software factories to pervasive systems: Aplatform specific framework. In ICEIS (3), pages 337–342, 2006.

10. Javier Munoz, Vicente Pelechano, and Carlos Cetina. Implementing a pervasive meeting room:A model driven approach. In IWUC, pages 13–20, 2006.

11. Hassan Gomaa and Mohamed Hussein. Dynamic software reconfiguration in software productfamilies. Software Product-Family Engineering, pages 435 – 444, 2004.

12. T. Lemlouma and N. Layaida. Context-aware adaptation for mobile devices. Mobile DataManagement, 2004. Proceedings. 2004 IEEE International Conference on, pages 106–111, 2004.

13. Jaejoon Lee and Kyo C. Kang. A feature-oriented approach to developing dynamically recon-figurable products in product line engineering. splc, 0:131–140, 2006.

14. S. Hallsteinsen, E. Stav, A. Solberg, and J. Floch. Using product line techniques to buildadaptive systems. Software Product Line Conference, 2006 10th International, pages 10 pp.–,21-24 Aug. 2006.

15. Jules White, Douglas C. Schmidt, Egon Wuchner, and Andrey Nechypurenko. Automatingproduct-line variant selection for mobile devices. Software Product Line Conference, 2007.SPLC 2007. 11th International, pages 129–140, 10-14 Sept. 2007.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 19

Page 20: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

16. P. Trinidad, , A. Ruiz-Cortes, and J. Pe na. Mapping feature models onto component models tobuild dynamic software product lines. International Workshop on Dynamic Software ProductLine, 2007.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 20

Page 21: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Soporte a la Evolución Dinámica de Tipos Arquitectónicos

Cristóbal Costa-Soria1, Jennifer Pérez2, Jose A. Carsí1

1 ISSI, Departamento de Sistemas Informáticos y Computación, Universidad Politécnica de Valencia, Camino de Vera s/n, 46022 Valencia

{ccosta, pcarsi}@dsic.upv.es

2 E.U. Informática, Universidad Politécnica de Madrid, Ctra. Valencia km 7, 28051 Madrid

[email protected]

Resumen. Los sistemas software con una fuerte naturaleza dinámica suponen un reto para la ingeniería del software. Este tipo de sistemas requieren de mecanismos que les permitan modificar tanto estructura como comportamiento en tiempo de ejecución, para adaptarse a las distintas situaciones que puedan presentarse. El área de arquitecturas software, que permite describir la estructura de los sistemas complejos a un alto nivel de abstracción, proporciona dos grados de dinamismo para la construcción de sistemas dinámicos, dependiendo de si lo que evoluciona es la configuración de la arquitectura o los tipos que componen dicha arquitectura. El primer tipo de evolución, denominado reconfiguración dinámica, permite a una arquitectura software cambiar su configuración en tiempo de ejecución, creando/destruyendo instancias de elementos arquitectónicos y/o las conexiones entre ellas. El segundo tipo de evolución, que denominamos evolución dinámica de tipos arquitectónicos, permite cambiar completamente la especificación arquitectónica de un sistema dinámicamente, bien introduciendo nuevos tipos arquitectónicos, modificando tipos e instancias en ejecución, o bien introduciendo nuevas conexiones. Este artículo presenta cómo soportar este último grado de dinamismo desde un punto de vista independiente de plataforma. Para ello, se han identificado los diferentes asuntos de interés implicados en el proceso y se han encapsulado en aspectos.

Palabras Clave: runtime evolution, types evolution at runtime, reflection, self-star systems, software architectures, CBSD, AOSD.

1. Introducción

En la actualidad, los sistemas software cada vez son más complejos, lo que conlleva que con frecuencia dichos sistemas deban someterse a revisiones posteriores para incorporar funcionalidades no previstas inicialmente o corregir errores. Sin embargo, la propia naturaleza de determinados sistemas, como aquellos que desempeñan misiones críticas y por tanto deben ejecutarse continuamente e ininterrumpidamente, hace inviable su detención para su adaptación o evolución. En este tipo de sistemas es donde surge la necesidad de incorporar capacidades que les permitan ser evolucionados en tiempo de ejecución, sin ser detenidos.

Las arquitecturas software [17] permiten describir sistemas complejos en términos de elementos arquitectónicos (componentes y conectores) y las interacciones entre sí (conexiones). Las propuestas para describir y especificar arquitecturas software, con el objetivo de dotar de mayor flexibilidad a los sistemas construidos, ofrecen algún tipo de soporte para la evolución dinámica. Ésta puede ser de dos tipos, dependiendo de si lo que se modifica es la configuración de la arquitectura o los tipos que componen dicha arquitectura. El primer tipo de evolución, la reconfiguración dinámica (también llamada dinamismo estructural [9]), permite a una arquitectura

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 21

Page 22: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

software cambiar su configuración en tiempo de ejecución, creando o destruyendo dinámicamente instancias de elementos arquitectónicos y sus enlaces. El segundo tipo de evolución, la evolución dinámica de tipos arquitectónicos (o también llamado dinamismo arquitectónico [9]), permite a una arquitectura software cambiar completamente su tipo (i.e., su especificación) en tiempo de ejecución, introduciendo nuevos tipos de elementos arquitectónicos y conexiones, eliminando tipos existentes, o cambiando la forma en que los tipos interaccionan, cambiando de este modo tanto la composición como el comportamiento de la arquitectura software.

En este artículo se presenta una propuesta para soportar este último grado de dinamismo, la evolución dinámica de tipos arquitectónicos, refiriéndonos al proceso de evolucionar un tipo que ya se encuentra instanciado en un determinado sistema software, y la migración o evolución, en tiempo de ejecución, de todas sus antiguas instancias a la estructura y comportamiento definida por el nuevo tipo. Esta propuesta se presenta desde un punto de vista independiente de la plataforma. Para ello, se han identificado los diferentes asuntos de interés implicados en el proceso de evolución dinámica y se han encapsulado en aspectos. Con el objetivo de ilustrar nuestra propuesta, se describirá cómo se ha aplicado para un ADL concreto, aunque es extrapolable a cualquier otro. En particular, se mostrará cómo proporcionar evolución dinámica a tipos arquitectónicos PRISMA.

En este trabajo sólo se ha considerado la evolución interna del tipo, es decir, no se ha tenido en cuenta cómo dicha evolución puede afectar a las interacciones del tipo evolucionado con el resto de tipos del sistema. Así ocurre cuando las interfaces públicas del tipo son modificadas, con lo que para mantener la consistencia del sistema, deberán adaptarse las conexiones existentes para que el resto de elementos arquitectónicos puedan comunicarse con las instancias del nuevo tipo. Esta problemática ya ha sido abordada por otros autores, como en el trabajo de Cámara et al. [5], mediante la introducción dinámica de adaptadores que actúan de intermediarios entre las instancias existentes y las nuevas instancias, por lo que no ha sido considerada en este trabajo.

La estructura del artículo es la siguiente: en el apartado 2 se introduce el modelo PRISMA, modelo sobre el cual se ha aplicado esta propuesta. En el apartado 3 se describe nuestra propuesta, describiendo tanto los mecanismos utilizados a nivel de tipos como los utilizados a nivel de instancias. En el apartado 4 se discute la propuesta, comparándola con otros trabajos relacionados y, finalmente, en el apartado 5 se presentan las conclusiones y los trabajos futuros.

2. PRISMA

PRISMA es un enfoque para el desarrollo de arquitecturas software orientadas a aspectos independientes de tecnología [18, 19], concebido en el grupo de investigación ISSI. El modelo PRISMA tiene tres tipos de elementos arquitectónicos: componentes, conectores y sistemas. Externamente, los tres tipos son idénticos: encapsulan su funcionalidad como cajas negras y publican un conjunto de servicios que ofrecen a otros elementos arquitectónicos (ver Figura 1-A). Estos servicios, agrupados en interfaces, son publicados a través de los puertos, que son los puntos de interacción entre elementos arquitectónicos. Sin embargo, internamente se diferencian en que los componentes y conectores son elementos arquitectónicos simples, mientras que los sistemas son elementos arquitectónicos complejos.

Un elemento arquitectónico simple puede verse como un prisma, donde cada lado del prisma es un aspecto importado por el elemento arquitectónico (ver Figura 1-B). Un aspecto representa un comportamiento específico de un asunto (concern) -seguridad, coordinación, distribución, etc.- que se encuentra disperso por la arquitectura software. PRISMA se caracteriza por seguir un enfoque simétrico [12], en el cual los aspectos no están restringidos a especificar únicamente requerimientos no funcionales, sino que también pueden describir la propia funcionalidad del sistema. De esta forma, los elementos arquitectónicos simples son representados como un conjunto de aspectos. Los aspectos son sincronizados entre sí a través de relaciones de weaving. Un

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 22

Page 23: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

weaving indica que la ejecución del servicio de un aspecto puede activar la ejecución de servicios en otros aspectos.

Por su parte, la vista interna de un elemento arquitectónico complejo (sistema) incluye un conjunto de elementos arquitectónicos (componentes, conectores y otros sistemas) y las conexiones entre ellos (ver Figura 1-C). Estas conexiones pueden ser de dos tipos: attachments, que modelan las comunicaciones realizadas dentro del sistema (entre elementos arquitectónicos); y bindings, que modelan las comunicaciones desde o hacia el exterior del sistema.

Fig. 1. Vistas de un elemento arquitectónico PRISMA

3. Evolución Dinámica de Tipos Arquitectónicos

De este modo, en PRISMA tendremos dos clases de tipos arquitectónicos que pueden ser evolucionados: los elementos arquitectónicos simples y los elementos arquitectónicos complejos (sistemas). Por motivos de espacio, sólo describiremos aquí cómo se evolucionan los elementos arquitectónicos complejos, aunque puede fácilmente extrapolarse a la evolución de elementos arquitectónicos simples. Puede encontrarse más información en un trabajo previo [8].

El objetivo perseguido es el de dotar, a cada tipo arquitectónico del sistema software, de las capacidades necesarias para que sea capaz de cambiar dinámicamente tanto su especificación (el tipo), como sus instancias de forma autónoma. De este modo, cada tipo arquitectónico podrá evolucionar independientemente del resto de tipos, favoreciendo así la construcción de sistemas distribuidos, heterogéneos y autónomos. Para ello, cada tipo arquitectónico debe estar dotado de una infraestructura que le permita evolucionar en tiempo de ejecución. En nuestra propuesta, esta infraestructura está integrada como parte del propio tipo y como parte de cada una de las instancias. Existen dos razones por las cuales se ha distribuido la infraestructura de evolución entre el tipo arquitectónico y sus instancias, y están relacionadas con que, al igual que el tipo, cada instancia debe ser capaz de evolucionar de forma autónoma. La primera razón es que cada instancia es la única que puede determinar en qué momento está lista para evolucionar. En tiempo de ejecución, cada instancia tiene un estado y un conjunto de transacciones distintas al resto de instancias del mismo tipo, por lo que el instante en que cada instancia estará lista para su evolución será distinto para cada una de ellas. La segunda razón es que se ha seguido un enfoque de evolución incremental, en el cual cada instancia se descompone en las partes estructurales que la forman y mediante una serie de operaciones de evolución atómicas, son modificadas. Estas partes estructurales sólo son accesibles por cada instancia en ejecución, por lo que sólo podrán ser modificadas por mecanismos de evolución que sean ejecutados por dichas instancias.

La infraestructura de evolución está distribuida del siguiente modo. El tipo dispone de los mecanismos necesarios para: (1) devolver o generar su especificación y proporcionar los servicios para modificar dicha especificación, (2) actualizar su especificación con los cambios introducidos, de forma que nuevas instancias se creen de acuerdo al nuevo tipo, y (3) controlar el proceso de migración (o evolución) de cada una de sus instancias. Por su parte, cada instancia dispone de una serie de mecanismos para: (4) alcanzar un estado quiescente [13], en el cual las transacciones en

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 23

Page 24: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

ejecución finalizan de forma consistente, (5) modificar dinámicamente su estructura (en memoria) de acuerdo a los cambios indicados por el tipo, (6) si es posible, migrar el estado antiguo a las nuevas estructuras introducidas por el nuevo tipo.

3.1 Evolución del tipo

Nuestra propuesta se caracteriza por dotar a cada tipo arquitectónico de presencia real en la aplicación software, a través de una entidad que representa al tipo arquitectónico y que está en ejecución junto al resto de las instancias de dicho tipo. Esta entidad, a la que nos referiremos como M, puede ser vista desde dos puntos de vista diferentes. Por una parte, se comporta como clase, en el sentido de que proporciona servicios para la creación y destrucción de instancias del tipo arquitectónico que representa, así como también se encarga de mantener la población de instancias que han sido creadas. Por otra parte, esta entidad se comporta como objeto, pues tiene un estado y unos servicios que lo modifican. Sin embargo, dicho estado es una descripción editable del tipo que representa y, por tanto, los servicios que modifican dicho estado son en realidad servicios de evolución, pues al cambiar la descripción editable del tipo se está realmente modificando al tipo y sus instancias. Usando los conceptos del campo de la reflexión computacional [14], esta entidad M es en realidad una meta-instancia (o meta-componente), pues contiene la reificación del tipo (esto es, una descripción editable), que está causalmente conectada al tipo: todos los cambios que se hagan en dicha reificación serán reflejados en el tipo y en sus respectivas instancias.

La estructura interna de una meta-instancia se compone de cuatro módulos o áreas funcionales: (1) Builder, responsable de crear y destruir instancias del tipo arquitectónico; (2) TypeDescription, que encapsula la reificación del tipo arquitectónico y la población de instancias; (3) EvolutionPlanning, que proporciona los servicios de evolución; y (4) EvolutionMonitoring, que supervisa el proceso de migración de instancias desde el tipo antiguo al nuevo tipo.

Las meta-instancias han sido incorporadas en PRISMA utilizando los conceptos del propio modelo PRISMA: una meta-instancia es un componente simple PRISMA, formado por un conjunto de aspectos. Dichos aspectos son cada una de las áreas funcionales identificadas arriba, pues identifican un asunto de intéres distinto del proceso de evolución, y que es compartido por cada meta-instancia que incorpore mecanismos para la evolución de tipos (a excepción del módulo Builder, que es diferente para cada tipo). Por compartido nos referimos a que el tipo de dichos aspectos es común a todas las meta-instancias, y tan sólo se diferencian en el estado que adoptan cuando son instanciados en una meta-instancia particular. Las relaciones entre cada uno de estos aspectos se han definido mediante weavings, aunque por razones de espacio no se detallarán aquí.

El aspecto Builder proporciona los servicios para la creación y destrucción de instancias del tipo que representa la meta-instancia. Sus servicios son publicados a través de un puerto de la meta-instancia, que es bloqueado mientras dura el proceso de evolución, ya que dichos servicios también deben modificarse para que futuras instanciaciones sean acordes al nuevo tipo.

El aspecto TypeDescription contiene el estado de la meta-instancia, formado por la población de instancias y la descripción del tipo. Por un lado, la población de instancias es actualizada cada vez que se crea una instancia nueva, añadiendo una referencia a ella, o cada vez que se destruye una instancia, borrando la referencia correspondiente. Por otro lado, la descripción del tipo indica qué elementos constituyen el tipo arquitectónico y las relaciones entre dichos elementos. Por ejemplo, en el caso de especificaciones de sistemas PRISMA, esta estructura de datos almacena los tipos de componentes que componen el sistema, los tipos de conexiones que pueden establecerse entre los componentes, y las cardinalidades correspondientes. Este aspecto codifica las relaciones entre conceptos independientes de plataforma (i.e. el metamodelo PRISMA) y los conceptos dependientes de tecnología (i.e. la implementación del modelo de componentes orientado a aspectos en .NET). Por tanto, contiene también los patrones de generación automática de código que deben utilizarse para regenerar el tipo.

El aspecto EvolutionPlanning proporciona los servicios de evolución dinámica de tipos. Tan sólo ofrece dos servicios al exterior: el servicio Reify, que devuelve un objeto de tipo

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 24

Page 25: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

<Type>Spec, y el servicio Reflect, que requiere como parámetro de entrada un objeto de tipo <Type>Spec. <Type>Spec es una forma genérica de nombrar al tipo del objeto, ya que su tipo dependerá de cuál sea el meta-tipo del tipo representado por la meta-instancia. Por ejemplo, sea el tipo S un sistema PRISMA (esto es, un componente complejo), y cuyo meta-tipo es System, que describe la estructura y características de los elementos arquitectónicos complejos en PRISMA. Siendo MS la meta-instancia que representa al tipo S en tiempo de ejecución, el objeto devuelto por MS.Reify será del tipo SystemSpec.

Un objeto de tipo <Type>Spec tiene como estado (privado) la descripción de un tipo y proporciona un conjunto de servicios que permiten consultar y cambiar dicho estado (los servicios de evolución). Los servicios de evolución sólo permiten modificar la especificación del tipo de acuerdo a su meta-tipo respectivo, que es <Type>. Siguiendo con el ejemplo PRISMA, el objeto de tipo SystemSpec devuelto por MS.Reify contendrá como estado la descripción del tipo S, y como servicios de evolución ofrecerá aquellos definidos en el metamodelo de PRISMA [21]: addComponent, addConnector, addAttachment, addPort, removeComponent, etc. De este modo, el actor del proceso de evolución -que puede ser tanto externo al sistema (un actor humano) como interno al sistema (otro elemento arquitectónico)-: (1) mediante el servicio Reify() obtendrá la reificación editable del tipo, (2) modificará la especificación del tipo a través de los servicios de evolución proporcionados por el objeto <Type>Spec devuelto, y (3) devolverá dicho objeto a través del servicio Reflect(), con lo que se iniciará el proceso de evolución del tipo.

El aspecto EvolutionPlanning coordina el proceso de evolución. Cuando el servicio Reify es invocado, a partir de la descripción del tipo almacenada en el módulo TypeDescription, construye el objeto <Type>Spec (que dependerá del meta-tipo del tipo almacenado en TypeDescription), y lo devuelve. Sin embargo, el proceso de evolución no empieza hasta que el servicio Reflect no es invocado. El proceso de evolución consta de varias etapas, que son llevadas a cabo de forma distribuida: es iniciado por EvolutionPlanning, después es realizado localmente por cada instancia, y es supervisado por el aspecto EvolutionMonitoring.

Las tareas de evolución llevadas a cabo por EvolutionPlanning son las siguientes. En primer lugar se bloquea el aspecto Builder, para evitar la creación/destrucción de instancias mientras se está actualizando el tipo. Esto se realiza deteniendo el puerto de la meta-instancia que exporta los servicios del aspecto Builder. En segundo lugar, se actualiza la descripción del tipo almacenada en el aspecto TypeDescription, utilizando la información del objeto <Type>Spec proporcionado al invocar el servicio Reflect. En tercer lugar, el aspecto Builder es regenerado completamente de acuerdo con la descripción del tipo del aspecto TypeDescription, mediante técnicas de generación de código. Finalizado este paso, el aspecto Builder ya está capacitado para crear instancias del nuevo tipo, por lo que es desbloqueado y se permite la creación de nuevas instancias. Por último, se recorre la población de instancias (almacenadas en TypeDescription) y para cada una de ellas se invoca el servicio ReflectToInstance. Dicho servicio inicia el proceso de evolución de cada instancia a nivel local, adaptando su estructura interna a la del nuevo tipo. Finalmente, se pasa el control al aspecto EvolutionMonitoring, con lo que el aspecto EvolutionPlanner podrá admitir nuevas evoluciones de tipos.

El aspecto EvolutionMonitoring define las políticas de migración de instancias que deben llevarse a cabo en el proceso de evolución de tipos: si sólo las nuevas instancias deben crearse de acuerdo al nuevo tipo, o por el contrario, deben evolucionarse todas las instancias al nuevo tipo. En este último caso hay que definir el tiempo que tienen las instancias para evolucionar y las medidas correctoras para el caso en que dichas instancias no hayan evolucionado (como forzar la evolución obligando a perder el estado actual, posponer la evolución otro intervalo adicional, o cancelar la evolución de dicha instancia).

De esta forma, cualquier elemento arquitectónico podrá evolucionar un tipo arquitectónico sin más que conectarse al puerto de evolución de la meta-instancia deseada, solicitar la reificación del tipo. Acto seguido, mediante los servicios de evolución proporcionados, podrá modificar dicha reificación adecuadamente y al reflejarla, desencadenar el proceso de evolución tanto del tipo como de sus respectivas instancias en ejecución.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 25

Page 26: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

3.2 Evolución de las instancias

La mayoría de los enfoques para la evolución dinámica de tipos realizan la evolución de instancias a través de la migración del estado [22]: se crea una instancia del nuevo tipo y se le transfiere el estado de la instancia antigua. Para ello, el nuevo tipo debe proporcionar funciones para transformar las estructuras de datos del tipo antiguo a las estructuras de datos del nuevo tipo. Esto requiere que la meta-instancia (o el tipo) tome parte activa en el proceso de evolución de sus instancias.

Sin embargo, esto puede optimizarse si se conoce cuál es la especificación del tipo que está siendo evolucionado: el tipo puede descomponerse en entidades más pequeñas y las relaciones entre ellas, lo que permite aislar las entidades que van a ser evolucionadas mediante el bloqueo temporal de sus relaciones con el resto de entidades. Esto se ve más claro con los tipos arquitectónicos: un sistema PRISMA está formado por varias entidades (elementos arquitectónicos y puertos) y relaciones entre ellas (attachments y bindings). El proceso de evolución consiste entonces en dotar a cada instancia de mecanismos para aislar las partes estructurales que la constituyen (es decir, las entidades y relaciones que constituyen el tipo) y que van a sufrir cambios, mecanismos para que puedan reemplazarlas y para que sean capaces de volver a ensamblarlas de nuevo con el resto de partes de la instancia. De esta forma, pueden reemplazarse solamente las entidades a modificar mientras el resto de entidades siguen en ejecución. La ventaja de descomponer así las instancias, frente a las propuestas en las que se migra el estado las instancias, es más notable cuando lo que se evolucionan son tipos constituidos por entidades que se ejecutan concurrentemente y son altamente independientes entre sí, como es el caso de las arquitecturas software y el caso de los componentes integrados por aspectos, como en el enfoque PRISMA.

Los mecanismos para evolucionar las instancias son proporcionados por tres módulos o áreas funcionales: InstanceEvolutionPlanning, EvolutionSensor y EvolutionEffector. Estos módulos identifican distintos asuntos de interés del proceso de evolución de instancias, por lo que para su implementación en PRISMA también han sido encapsulados en aspectos.

El aspecto EvolutionSensor proporciona servicios para obtener las referencias (en memoria) a cada una de las partes estructurales que componen la instancia (y poder así manipularlas), así como servicios para monitorizar el status de cada una de dichas partes estructurales. El status indica si una parte estructural está lista para ser evolucionada: no tiene transacciones pendientes en ejecución que puedan alterar su estado, es decir, es quiescente [13] o tranquila [23].

El aspecto EvolutionEffector proporciona los servicios que realmente efectúan la modificación de la estructura de la instancia, en términos del meta-tipo de la instancia. Por ejemplo, en sistemas PRISMA, el EvolutionEffector proporciona los servicios addComponent, addConnector, addAttachment, addPort, removeComponent, etc. Es decir, ofrece los mismos servicios que proporcionaba el objeto SystemSpec, sólo que mientras este último sólo actualizaba una especificación (datos), el EvolutionEffector está aplicando los cambios a estructuras en memoria (código en ejecución). Además, el aspecto EvolutionEffector también proporciona los servicios para detener o reiniciar a cada una de las partes estructurales, es decir, que alcancen el estado quiescente o lo abandonen, respectivamente. Estos servicios en PRISMA son: StartComponent, StartAttachment, StopComponent, StopAttachment, etc.

Sin embargo, el aspecto EvolutionEffector no tiene en cuenta las dependencias entre las partes estructurales al aplicar los cambios, ni si estaban listas para ser evolucionadas. Esto es realizado por el aspecto InstanceEvolutionPlanning, que coordina el proceso de evolución a nivel de instancias. El aspecto InstanceEvolutionPlanning recibe el conjunto de cambios a aplicar en la estructura de la instancia a través del objeto <Type>Spec. Internamente, el objeto <Type>Spec almacena los cambios realizados a la especificación del tipo como diferencias respecto a la especificación original. De esta forma, el proceso de evolución de tipos se realiza como un proceso de evolución incremental, a través de operaciones atómicas que van modificando la estructura original de la instancia en ejecución, bien introduciendo nuevos elementos, bien eliminándolos. El aspecto InstanceEvolutionPlanning extrae el conjunto de operaciones atómicas de evolución a

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 26

Page 27: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

realizar. Cada operación de evolución implica que la parte estructural a ser modificada alcance previamente un estado quiescente (esto es, finalice primero sus transacciones de forma segura), a excepción de las conexiones, en cuyo caso son sus extremos quien tienen que alcanzar dicho estado. Además, puede que para alcanzar un estado quiescente, también deban ser detenidas las partes estructurales directamente conectadas, lo que también es tenido en cuenta. Sin embargo, no se describirá aquí cómo se alcanza la quiescencia, por quedar fuera del ámbito de este artículo. Para llevar a cabo todo este proceso, el aspecto InstanceEvolutionPlanning va coordinando los distintos servicios ofrecidos por los aspectos EvolutionSensor y EvolutionEffector, utilizando los servicios del primero para obtener referencias y el estado de las partes estructurales de la instancia y los servicios del segundo para ir aplicando los cambios.

Es importante señalar que mientras la meta-instancia sí que genera nuevo código y lo persiste en disco, a nivel de instancias sólo se alteran estructuras en memoria, para adaptarlas al nuevo tipo.

3.3 La Evolución Dinámica de Tipos como un Crosscutting Concern

De acuerdo con el enfoque de Desarrollo de Software Orientado a Aspectos (AOSD), un aspecto representa un comportamiento específico de un asunto (concern) –seguridad, coordinación, distribución, etc.- que se encuentra disperso (crosscutting concern) en un sistema software complejo. La evolución dinámica de tipos puede considerarse también un asunto de interés del sistema, pues está presente en todos aquellos tipos que sean evolucionables y en sus respectivas instancias.

Además, un concern puede ser representado por varios aspectos, y es efectivamente como se ha materializado en nuestra propuesta, desarrollando cada aspecto una parte de la funcionalidad de la evolución de tipos. Algunos aspectos proporcionan la funcionalidad independiente de plataforma, describiendo el proceso de evolución en términos del metamodelo utilizado (PRISMA) y coordinando las acciones a realizar a un alto nivel de abstracción, como es el caso de los aspectos EvolutionPlanning, EvolutionMonitoring y InstanceEvolutionPlanning. Por otro lado, otros aspectos, como Builder, TypeDescription, EvolutionSensor y EvolutionEffector son los que realizan el puente entre los conceptos independientes de plataforma (los de PRISMA) y los conceptos dependientes de tecnología (la implementación del modelo de componentes en una determinada plataforma). Los servicios ofrecidos por estos últimos aspectos son dependientes del metamodelo PRISMA, pero su implementación es realizada en la tecnología en la que las arquitecturas PRISMA se ejecuten (actualmente .NET [20]). De este modo, esta separación de aspectos facilita la portabilidad de la implementación PRISMA a otras plataformas, en las que los cambios a realizar en el modelo de evolución están localizados en estos cuatro últimos aspectos, mientras que el resto de aspectos sólo utilizan conceptos independientes de plataforma.

Por otro lado, otra ventaja derivada de los modelos orientados a aspectos es que un mismo aspecto puede ser importado por más de un elemento arquitectónico que necesite tener en cuenta el comportamiento del concern que dicho aspecto define. En el caso del concern de evolución dinámica, todos los tipos arquitectónicos PRISMA que incorporen soporte a la evolución dinámica de tipos importarán este conjunto de aspectos, favoreciendo la reutilización y el mantenimiento del código de evolución de toda la aplicación.

4. Discusión

Muchos trabajos han abordado el problema de la evolución dinámica de sistemas software [4, 15]. Wang [24] describe cómo soportar la evolución dinámica de componentes (simples) en Java. Para ello, modifica el classLoader de Java para que para nuevas instanciaciones usen el nuevo tipo modificado. Respecto a las instancias, sólo son migradas sino están ejecutando ningún servicio, y la transferencia de estado se realiza mediante los mecanismos de reflexión de Java. El bloqueo de

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 27

Page 28: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

las peticiones entrantes se realiza a través de un gestor de instancias de componentes, que intercepta todas las conexiones dirigidas a las instancias. Es un enfoque más dirigido a arquitecturas orientadas a servicios, pues las instancias son creadas bajo petición y tienen una vida más corta, lo que garantiza que en algún momento dejen de procesar servicios y puedan ser migradas al nuevo tipo. Sin embargo, la migración del estado se realiza para estructuras muy sencillas. En [22], Vandewoude aborda cómo tratar la migración de estructuras de datos complejas entre distintas versiones de tipos, y en [23], cómo alcanzar un estado tranquilo, menos restrictivo que la quiescencia, para evolucionar las instancias en ejecución de forma segura.

Estos trabajos son bastante interesantes, aunque todos ellos llevan a cabo el proceso de evolución de forma centralizada: la infraestructura de ejecución (esto es, el middleware) proporciona los mecanismos para evolucionar todos los tipos presentes en el sistema. Sin embargo, este enfoque no es adecuado, pues no es escalable para sistemas distribuidos, y tan sólo es aceptable para sistemas homogéneos (todos los elementos del sistema son de la misma tecnología). En nuestra propuesta, la evolución de tipos es proporcionada de forma independientemente para cada tipo del sistema software en ejecución. La escalabilidad es proporcionada por los aspectos, ya que todos los tipos que utilicen la misma tecnología (nuestro enfoque) importarán los mismos aspectos, que están definidos una sola vez en todo el código.

En el área de las arquitecturas software hay numerosos trabajos que abordan la adaptabilidad en tiempo de ejecución [3], aunque en su mayoría abordan sólo la reconfiguración dinámica. Esto es debido a que numerosos autores no han establecido la distinción entre reconfiguración dinámica y evolución de tipos que se ha descrito en este trabajo: con frecuencia se refiere a la evolución de tipos cuando se evolucionan dinámicamente elementos arquitectónicos simples (componentes), y se refiere a la reconfiguración dinámica cuando lo que se modifican son arquitecturas software, que no están restringidas a la especificación de un tipo arquitectónico, como sí lo están en el enfoque PRISMA. La mayor parte de ADLs que incorporan soporte para el dinamismo arquitectónico, como LEDA [6], PiLaR [9], Plastik [1] o SOFA [2], no describen cómo darle soporte a dicho dinamismo, ya que se centran en cómo describir dicho dinamismo, dejando para la fase de implementación la decisión de cómo llevar a cabo dicho proceso evolutivo. Nuestra propuesta sigue un enfoque mixto: se describen a alto nivel los cambios a realizar (en términos del ADL elegido, PRISMA) y se han identificado y ubicado los mecanismos que lo hacen posible, con el objetivo de que las entidades definidas en el ADL puedan también interactuar con dichos mecanismos (i.e., un tipo arquitectónico puede invocar servicios de la meta-instancia de otro tipo para evolucionarlo). El uso de la reflexión de este trabajo es similar a la propuesta en el ADL PiLaR, en la que cada sistema tiene acceso a la representación editable de sí mismo.

Los trabajos de Dashofy [10] y Garlan [11] sí que describen la infraestructura necesaria para describir sistemas software auto-reparables y auto-adaptables, respectivamente, basándose en modelos que describen la arquitectura válida del sistema. El inconveniente de estos trabajos es precisamente la no descentralización de los mecanismos de evolución, bajo la suposición de que todos los subsistemas deben ser reconfigurables y accesibles. Morrison et al. [16] describe a un sistema evolucionable como aquel compuesto por dos procesos: Producer, que proporciona la funcionalidad del sistema, y Evolver, que es capaz de evolucionar al otro proceso. La evolución se realiza descomponiendo el proceso Producer en los elementos que lo constituyen y siendo detenidas todas las conexiones entre ellos, aunque hubiera elementos que no fueran afectados por la evolución del tipo. Su propuesta es bastante cercana a la desarrollada en este trabajo, ya que el proceso encargado de evolucionar a un sistema está embebido dentro de él (aunque separado para facilitar su mantenimiento), y sigue un proceso de descomposición del sistema para evolucionar el tipo en ejecución. La propuesta de Morrison sigue un enfoque completamente orientado a procesos, mientras que nuestro trabajo se centra en el área de arquitecturas software, utilizando aspectos para separar los mecanismos de evolución respecto al resto de funcionalidad del sistema.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 28

Page 29: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

5. Conclusiones y trabajos futuros

En este trabajo se ha presentado una propuesta para soportar la evolución dinámica de tipos, aplicada al campo de las arquitecturas software, y al enfoque PRISMA en particular. Esta propuesta describe una infraestructura para dotar a cada tipo arquitectónico (simple o complejo) de la capacidad de ser evolucionado en tiempo de ejecución de forma independiente, sin necesidad de definir una entidad centralizada para evolucionar todos los tipos de un sistema. De esta forma, los tipos así construidos pueden integrarse en sistemas heterogéneos y distribuidos. Además, también se preserva el principio de encapsulación: un tipo arquitectónico es una caja negra, y como tal, su evolución sólo puede realizarse por los mecanismos internos del tipo, que son los que conocen la estructura interna del tipo y cómo cambiarla. Desde un punto de vista externo, un tipo evolucionable proporciona capacidades reflexivas para obtener su reificación y un conjunto de servicios de evolución para modificar su especificación de forma consistente. Desde un punto de vista interno, el proceso de evolución de tipos está separado en distintos asuntos o áreas de interés, que se encuentran distribuidos entre la reificación del tipo y sus instancias en ejecución. Estos asuntos o concerns han sido encapsulados en aspectos, favoreciendo así su reutilización y mantenimiento. Los aspectos a nivel del tipo se encargan de evolucionar la especificación y los servicios de creación y destrucción de instancias, mientras que los aspectos a nivel de instancias se encargan de evolucionar la estructura interna de cada instancia. Otra contribución de este trabajo es que la evolución a nivel de instancias se realiza a través de la descomposición de la estructura interna de la instancia y mediante un proceso de desarrollo incremental, añadiendo/eliminando las entidades que se han añadido/eliminado del tipo.

Actualmente, estamos incorporando los conceptos descritos en este trabajo al middleware PRISMANET [20], que soporta la ejecución de arquitecturas PRISMA y su reconfiguración dinámica [7]. Una vez finalizada la implementación, se llevará a cabo un estudio para estimar los tiempos de respuesta del proceso de evolución y compararlos con otras propuestas. Otro de los trabajos que esperamos realizar a corto plazo es la definición de restricciones en el proceso de evolución de tipos: por ejemplo, para limitar qué partes del tipo pueden ser evolucionadas y cuáles no.

Agradecimientos

Este trabajo ha sido financiado por el CICYT (Comisión Interministerial de Ciencia y Tecnología), proyecto META TIN2006-15175-C05-01, y cofinanciado por la Comunidad de Madrid y la Universidad Rey Juan Carlos dentro del proyecto IASOMM URJC-CM-2007-CET-1555. También ha sido financiado parcialmente gracias a una beca FPI de la Conselleria d'Educació i Ciència (Generalitat Valenciana) concedida a C. Costa.

Referencias

1. Batista, T., Joolia, A., Coulson, G.: Managing Dynamic Reconfiguration in Component-Based Systems. In 2nd European Workshop on Software Architectures (EWSA'05). LNCS, vol. 3527. Springer (2005)

2. Bures, T., Hnetynka P., Plasil F.: SOFA 2.0: Balancing Advanced Features in a Hierarchical Component Model. In: 4th Int. Conference on Software Engineering Research, Management and Applications (SERA'06). Seattle, Washington, USA (2006) 40-48

3. Bradbury, J.S., Cordy, J.R., Dingel, J., Wermelinger, M.: A Survey of Self-Management in Dynamic Software Architecture Specifications. In proc. of 1st ACM SIGSOFT Workshop on Self-Managed Systems (WOSS’04). Newport Beach, California (2004) 28-33

4. Buckley, J., Mens, T., Zenger, M., Rashid, A., Kniesel, G.: Towards a taxonomy of software change. Journal on Software Maintenance and Evolution, vol. 17(5). Wiley (2005)

5. Cámara, J., Canal, C., Cubo, J., and Murillo, J. M. An Aspect-Oriented Adaptation Framework for Dynamic Component Evolution. Electron. Notes Theor. Comput. Sci. 189 (2007) 21-34

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 29

Page 30: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

6. Canal, C., Pimentel, E., Troya, J.M.: Specification and Refinement of Dynamic Software Architectures. In: First Working IFIP Conf. on Software Architecture (WICSA'99). San Antonio, Texas, USA (1999)

7. Costa, C., Ali, N., Pérez, J., Carsí, J.A., Ramos, I.: Dynamic Reconfiguration of Software Architectures Through Aspects. In: 1st Europ. Conf. on Software Architecture (ECSA’07). LNCS, vol. 4758 (2007)

8. Costa, C., Pérez, J., Carsí, J.A: Dynamic Adaptation of Aspect-Oriented Components. In: 10th Int. ACM Symp. on Component-Based Software Engineering (CBSE'07). LNCS, vol. 4608. Springer (2007) 49-65

9. Cuesta, C.E., Fuente, P.d.l., Barrio-Solárzano, M.: Dynamic Coordination Architecture through the use of Reflection. In: ACM Symposium on Applied Computing. Las Vegas, Nevada, USA (2001) 134-140

10. Dashofy, E.M., van der Hoek, A., Taylor, R.N.: Towards Architecture-Based Self-Healing Systems. In proc. of First Workshop on Self-Healing Systems (WOSS'02). Charleston, South Carolina (2002) 21-26

11. Garlan, D., Cheng, S., Huang, S., Schmerl, B., Steenkiste, P.: Rainbow: Architecture-Based Self-Adaptation with Reusable Infrastructure. In: Computer, Vol. 37. IEEE Computer Society (2004) 46-54

12. Harrison, W. H., Ossher, H. L., Tarr, P. L.: Asymmetrically vs. Symmetrically Organized Paradigms for Software Composition. Tech. Rep. RC22685 (W0212-147), T. J. Watson Research Centre, IBM (2002)

13. Kramer, J., Magee, J.: The Evolving Philosophers Problem: Dynamic Change Management. In: IEEE Transactions on Software Engineering, Vol. 16, No.11 (1990), 1293-1306

14. Maes, P.: Concepts and Experiments in Computational Reflection. In: SIGPLAN Not., Vol. 22, No. 12. ACM Press, New York, NY, USA (1987) 147-155

15. McKinley, P. K., Sadjadi, S. M., Kasten, E. P. and Cheng, B. H. C.: Composing Adaptive Software. In: Computer, vol. 37(7). IEEE Computer Society (2004) 56-64

16. Morrison, R., Balasubramaniam, D., Kirby,G., et al: A Framework for Supporting Dynamic Systems Co-Evolution. In: Autom. Software. Eng, Vol. 14(3). Springer (2007) 261-292

17. Perry, D. E., & Wolf, A. L.: Foundations for the Study of Software Architecture. In: ACM SIGSOFT Software Engineering Notes, Vol. 17, No. 4 (1992) 40-52

18. Pérez, J. PRISMA: Aspect-Oriented Software Architectures. PhD Thesis, Department of Information Systems and Computation, Polytechnic University of Valencia (2006).

19. Pérez, J., Ali, N., Carsí, J.A, Ramos, I.: Designing Software Architectures with an Aspect-Oriented Architecture Description Language. In proc. of the 9th Int. Symp. on Component-Based Software Engineering (CBSE06). Lecture Notes on Computer Science, Vol. 4063. Springer (2006) 123-138

20. Pérez, J., Ali, N., Costa, C., Carsí, J.A, Ramos, I.: Executing Aspect-Oriented Component-Based Software Architectures on .NET Technology. In proc. of 3rd International Conference on .NET Technologies. Pilsen, Czech Republic (2005) 97-108

21. Pérez, J., Ali, N., Carsí, J.A, Ramos, I.: Dynamic Evolution in Aspect-Oriented Architectural Models. In 2nd European Workshop on Software Architecture (EWSA'05). LNCS, Vol. 3527. Springer (2005) 59-76

22. Vandewoude, Y., Berbers, Y.: Component state mapping for runtime evolution. In proc. of Int. Conf. on Programming Languages and Compilers. Las Vegas, Nevada, USA (2005)

23. Vandewoude, Y., Ebraert, P., et al.: Tranquillity: A low Disruptive Alternative to Quiescence for Ensuring Safe Dynamic Updates. IEEE Transactions on Soft. Eng., Vol. 33, No. 12. (2007) 856-868

24. Wang, Q., Shen, J., Wang, X., Mei, H.: A component-based approach to online software evolution. Journal of Software Maintenance and Evolution:Research and Practice, Vol.18, pp.181-205. Wiley (2006)

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 30

Page 31: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Arquitecturas Adaptativas y Autonómicas:una Perspectiva Reflexiva *

Carlos E. Cuesta1 y M. Pilar Romay1

Escuela Superior de Ingeniería InformáticaUniversidad Rey Juan Carlos, 28933 Móstoles, Madrid (Spain)

[email protected], [email protected]

Resumen. El estudio de sistemas adaptativos y autonómicos ha adquirido una gran importan-cia, y para ello el uso de un enfoque arquitectónico parece especialmente adecuado. Por defi-nición, la arquitectura dinámica de un sistema self-? es además reflexiva; así pues, se planteael uso de un enfoque reflexivo para su descripción. En primer lugar se consideran los distintosgrados de adaptatividad, para después identificar los tipos de elementos de una arquitectura au-tonómica. A continuación se examinan sus propiedades específicas, al tiempo que se justifica lacoherencia del enfoque composicional. Finalmente, se describe un ejemplo concreto de sistemaautonómico utilizando PiLar, un ADL reflexivo, y se concluye debatiendo futuras extensiones.

Palabras clave: Adaptatividad, Autonomía, Self-?, Reflexión, Composición, PiLar.

It is not the strongest of the species that survives, nor the most intelligent,but the one most responsive to change.

CHARLES DARWIN (1809-1882)

1. Introducción

La creciente complejidad de los sistemas software ha llevado a plantear la necesidad de que éstosrealicen una parte significativa de sus funciones por sí mismos, sin necesidad de asistencia externa.Esto ha llevado a la definición de mecanismos para la definición de los sistemas denominados comoadaptativos, autonómicos o auto-gestionados, así como sus versiones más específicas, que recibenel nombre colectivo de sistemas self-?.

El desarrollo de estos sistemas tiene tal importancia y complejidad, y afecta a tantos de loscampos en desarrollo, que se ha llegado a afirmar que define muchos de los aspectos críticos enel futuro de la Ingeniería de Software [12]. En muchos sentidos, este planteamiento está ocupandoparte del lugar que una década antes asumió la arquitectura de software. No resulta sorprendenteque, de hecho, se haya afirmado que, entre todos los enfoques utilizados, uno de los que tiene mayorpotencial es precisamente el arquitectónico [12]. Uno de los objetivos de este trabajo consiste enmostrar que, efectivamente, esta afirmación está justificada.

Ahora bien, una vez que se considera una arquitectura autonómica (o en un sentido más general,adaptativa), se tiene que concluir que se trata en cualquier caso de una arquitectura dinámica, yprobablemente también reflexiva, al menos desde un punto de vista conceptual.

El primer punto es obvio, ya que se parte de que un sistema adaptativo debe ser capaz de cambiarpara adaptarse a su entorno, y ésto le exige, como mínimo, tener la capacidad de reconfigurarse (laauto-configuración es una de las propiedades consideradas en un sistema self-?). Más aún teniendo

* Este trabajo ha sido parcialmente financiado por el Proyecto TIN2006-15175-C05-01 (META/MOMENT)del Ministerio de Ciencia e Innovación, y por el Proyecto URJC-CM-2007-CET-1555 (IASOMM) de la Co-munidad de Madrid y la Universidad Rey Juan Carlos.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 31

Page 32: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

en cuenta que la propia suposición de que el entorno es dinámico exige que la arquitectura seatambién capaz de hacerlo. No es extraño, por tanto, que la mayoría de las soluciones planteadas seande este tipo. De hecho, la conocida revisión de Bradbury [1] del estado del campo surge en origende una revisión similar de propuestas para la especificación de arquitecturas dinámicas.

Respecto a la reflexión, se debe considerar que todo sistema que se gestiona a sí mismo es,por definición, reflexivo. Autores como Huang [9] o McKinley [14] ya apuntaron a la posibilidadde utilizar un enfoque reflexivo, pero en su caso la propuesta era esencialmente tecnológica. Elsegundo objetivo de este artículo es, precisamente, mostrar que el enfoque reflexivo puede plantearsedirectamente a nivel arquitectónico. En este sentido, se utilizará el lenguaje PiLar [3], un ADLdinámico y reflexivo, como base para una demostración conceptual, en la que se pretende demostrarla viabilidad de este planteamiento, utilizando para ello un ejemplo bien conocido.

2. Grados de Adaptatividad

En la última década, el término adaptatividad1 ha ido adquiriendo mayor importancia, y sudefinición se ha ido haciendo a un tiempo más genérica y más confusa. Inicialmente, se tratabasimplemente de la adaptación [2], un concepto más simple que describía los mecanismos que podíaadoptar un sistema para ser capaz de interactuar con diferentes elementos y en diferentes contextos.Pero ese significado se ha extendido luego para describir, globalmente, a todas las características quedefinen la capacidad de un sistema para adaptarse a cambios en su entorno.

Asociados a esta misma idea, en los últimos años se han identificado toda una serie de conceptosrelacionados. La mayoría de ellos se puede entender en un sentido genérico, intuitivo, o en un sentidomás específico. Los límites y las relaciones entre estos enfoques son en general difusos.

Con el fin de aclarar estos términos, al menos dentro de los límites de este trabajo, se muestra enla Figura 1 una clasificación tentativa de los mismos. La clasificación toma la forma de una pirámide,en la que cada nivel se construye sobre el anterior, es decir, en la que cada concepto se consideramás específico a medida que se asciende. No obstante, esta organización no se ha de entender enun sentido demasiado rígido, puesto que varios de los términos, en su sentido más amplio, puedenabarcar varios de los niveles simultáneamente.

Por ejemplo, el nivel inferior, sensibilidad al contexto, se entiende en su sentido intuitivo, yaque es la propiedad mínima que se exige a todo sistema adaptativo. Si ha de adaptarse a sus cam-bios, en primer lugar ha de percibirlos. En cambio, en su sentido más específico, este término tieneconnotaciones asociadas a cierto hardware.

En los niveles intermedios se desarrollan las diversas propiedades-self, esto es, las distintaspropiedades en las que un sistema self-? se ocupa de sí mismo. Su forma más simple es la auto-monitorización (el sistema se observa a sí mismo) y la más compleja es la auto-gestión (el sistemaes capaz de gestionarse por completo, o al menos respecto a varios de sus aspectos). Entre ellas,el espectro adopta formas tales como la auto-organización, esencialmente estructural, o la auto-reparación, que afecta simultáneamente a varios aspectos.

La cúspide de la pirámide es la propia adaptatividad, cuando el término se utiliza en sentidoespecífico. En un sentido general, todo sistema capaz de cambiar para reaccionar a alteraciones delentorno es adaptativo, y todos los niveles indicados en la Figura 1 describen distintos grados de estapropiedad. Pero en un sentido específico, este término describe a un sistema con comportamientoemergente, y es este comportamiento el que de manera espontánea o controlada reacciona a dichoscambios. Por tanto, a adaptatividad es aquí un tipo concreto de emergencia.

1 En este trabajo se introducen como neologismos dos términos directamente basados en su morfología inglesa,cuya traducción al español puede considerarse dudosa. Así, se introduce “adaptatividad” como cualidad de“adaptativo” (que sí existe en español) para distinguirlo de “adaptabilidad” como cualidad de “adaptable”.Del mismo modo se usa “autonómico” en un sentido distinto al habitual, ya que la traducción más correcta,ligada al sustantivo “autonomía” (“autónomo”) tiene una connotación diferente en nuestro contexto.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 32

Page 33: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Adaptativity

Swarming

Emergence

Self-managing Autonomy

Self-healing Self-protection

Self-optimization

Self-configuration Self-tuning

Self-organization

Self-monitorization

Context adaptativity Ambient intelligence

Context sensibility

Fig. 1. Pirámide Adaptativa: Grados de Adaptatividad

La propia emergencia es una propiedad realmente compleja, cuya difusión actual trasciende alconcepto de software [10]. Sin embargo, no se va a tratar en este trabajo de los sistemas emergen-tes, en los que el comportamiento aparece por sí mismo, sino de aquéllos en los que éste se haprogramado previamente; hablaremos por ello de adaptatividad programada.

En realidad, a nivel arquitectónico la decisión de centrarse en sistemas no-emergentes no resultaespecialmente importante, salvo en lo relativo a comportamiento. Por el contrario, las estructurasespontáneas y las programadas deberían ser, en principio, similares; sus mayores diferencias habríande ser de escala (el comportamiento emergente se identifica a nivel macro).

Resulta especialmente significativo el lugar que ocupa la autonomía, considerada al mismo nivelque la auto-gestión porque ambas se definen como la combinación sinérgica de varias propiedades-self. Se dice que un sistema es autonómico cuando es capaz, hasta cierto grado, de encargarse de símismo. En definitiva, en un sentido general su significado se identifica con la idea de un subsistemacompuesto pero autónomo, sin la connotación de atomicidad que suele tener este último término.En sentido estricto, la autonomía define el auto-control de varias propiedades que varían según lasdiversas definiciones [13], siendo la más conocida probablemente la de Kephart [11].

En las secciones siguientes, por tanto, nos referimos de manera preferencial a los niveles de laparte central de la pirámide, utilizando los adjetivos adaptativo, autonómico o auto-gestionado parareferirnos a todos ellos de manera indistinta.

3. Elementos de una Arquitectura Adaptativa

A la hora de abordar la concepción de una arquitectura adaptativa, resulta esencial identificarcuáles son las características que, de manera general, la distinguen de un sistema convencional. Anivel estructural, esto implica la existencia de una serie de elementos con funciones específicas,directamente ligados a sus capacidades de auto-gestión.

En este apartado se presenta una taxonomía tentativa de dichos elementos, en la que se identificanlos cinco roles que puede tomar un componente en una arquitectura de este tipo. La taxonomía estádirectamente inspirada en la realizada anteriormente por Cuesta et al. [4] para arquitecturas dinámi-

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 33

Page 34: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

cas, que cumple una función similar. De hecho, dado que todo sistema adaptativo es necesariamentedinámico, existe relación entre ellas, si bien ambas tienen matices esencialmente diferentes.

Dado que se quiere aplicar esta taxonomía a una gran variedad de sistemas, referidos a distintaspropiedades-self o sus combinaciones, se han elegido nombres “neutros”, basados en el alfabetogriego, para las distintas categorías de elementos. Éstas son las siguientes:

Alfa (α). Todo elemento que está a cargo de sí mismo, es decir, que respecto a la propiedad-self elegida es autocontenido y no necesita apoyarse en un control externo. Por ejemplo, en unsistema autogestionado, un alfa será todo componente capaz de gestionarse a sí mismo.

Se trata, en resumen, de un elemento autónomo, en el sentido clásico. No obstante, estetérmino suele tener la connotación de referirse a un elemento simple, incluso atómico. Ahorabien, en una arquitectura adaptativa la mayoría de los elementos-α serán compuestos, como eslógico, ya que habrán de constar al menos de un componente controlador (un elemento-γ) yun componente controlado (un elemento-ε). De hecho, cuando el que alcanza el estatus de αes un fragmento con cierto tamaño y estructura, se podría decir que se trata de un subsistemaautonómico (en el sentido más general 2 utilizado en la sección anterior).

El objetivo final, en este caso, es que el sistema completo, considerado como un componentecomplejo, sea en sí mismo un alfa; es decir, que sea un sistema autonómico.

Beta (β). Todo elemento que es parcialmente autónomo, esto es, que realiza actividades de auto-control sin asistencia externa, pero que no es totalmente autocontenido respecto a la propiedad-self elegida. La parcialidad, en este contexto, puede referirse tanto a aspectos estructurales (βS)como de comportamiento (βB). En el primer caso, significa que el elemento sólo gestiona unaparte de sí mismo. En el segundo caso, significa que la propiedad-self considerada no se cubrepor completo. Por supuesto, también puede serlo simultáneamente en ambos sentidos.

Por ejemplo, en un sistema auto-monitorizado, un beta sería un elemento, en principio com-puesto, que monitoriza sólo a una parte de sus componentes (βS), o bien que sólo observa unaparte de su propia actividad, o de sus efectos (βB). Esta distinción es similar a la que existeentre un sistema auto-organizado (que lo es esencialmente en un sentido estructural) y uno auto-gestionado (que lo es en lo relativo a comportamiento); en ambos casos, el segundo concepto esmás específico, y se apoya en el primero (βB ⊂ βS).

En toda arquitectura adaptativa que no sea completamente autonómica, los elementos-β seránmayoría, en especial si son compuestos. La evolución natural de todo beta debería llegar a serun alfa, esto es, extender su control hasta hacerse autosuficiente. En cualquier caso, los límitesentre ambos son difusos, ya que es difícil decidir cuándo un ámbito queda cerrado. En general,se considera que los alfas no son sino un caso particular de los betas (α ⊂ β).

Gamma (γ). Todo elemento que está a cargo de otro, es decir, que respecto a la propiedad-selfconsiderada ejerce un control sobre otro. En resumen, se trata de un controlador. Por ejemplo,en un sistema auto-monitorizado, un gamma sería un monitor, y en un sistema auto-configurado,un configurador. Ambos describen casos bien conocidos a nivel arquitectónico.

Todo gamma lo es con respecto a otro: todo controlador tiene un elemento controlado (enprincipio, un ε). Por tanto, su existencia implica siempre la creación de un elemento compuesto.Esta composición se realiza típicamente por interacción, aunque también existen otras posi-bilidades menos evidentes (p.e., reificación o superposición). Los gammas están en la mismaesencia del planteamiento de los sistemas autonómicos. Son el clásico elemento de control ex-terno, una vez que queda integrado dentro del sistema. Se puede asumir que todo beta (y portanto, todo alfa) procede de la composición de un gamma con otro elemento.

Delta (δ). Todo elemento que realiza actividades de control, necesarias para la auto-gestión delsistema, pero que no controla directamente a ningún otro elemento. Es decir, un elemento au-xiliar o de soporte del subsistema autonómico. Desde otro punto de vista, puede verse también

2 Para ser “autonómico” en el sentido específico tendría que asegurarse que el subsistema es “autónomo” (α) almenos con respecto a las propiedades-self mínimas, si bien estas varían según la definición [13]. Por ejemplo,siguiendo [11] debería ser un elemento-α respecto a configuración, optimización, reparación y protección.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 34

Page 35: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

como un elemento que ejerce un control indirecto; su actividad siempre complementa a la de unelemento-γ, por lo que en cierto modo afecta a los componentes controlados por éste.

Cualquier elemento en un sistema autonómico que realice una actividad específica relativa alpropio sistema es un ejemplo de elemento-δ. Así, un enrutador, un broker o incluso un elementode cálculo pueden ser deltas cuando forman parte del subsistema adecuado.

Aunque su función los hace esenciales para la autogestión, son los elementos menos com-plejos de esta taxonomía, ya que a menudo ni siquiera necesitan ser conscientes del papel queejercen; de hecho, su importancia en la arquitectura deriva sólo de su ubicación.

Epsilon (ε). Todo elemento que carece por completo, o al menos a un nivel observable, de auto-gestión. Esto es, se trata un componente convencional, que igualmente podría formar parte deun sistema no-autonómico. En principio, todo épsilon es un candidato a ser controlado, directao indirectamente, por algún gamma.

Por supuesto, esta clasificación no pretende ser definitiva o absoluta. Es probable que todo ele-mento de un sistema autonómico pueda ser integrado en una de estas cinco categorías; pero estambién posible que resulte relevante refinar alguna de éstas, identificando alguna más, o inclusoalgunos casos particulares. Por otra parte, se debe tener en cuenta que el enfoque arquitectónico esinheremente composicional, por lo que cualquiera de estos elementos puede ser compuesto, y de he-cho en el caso más general lo será. En este contexto, las categorías se mezclan: un beta puede estarcompuesto por un número variable de gammas, deltas y epsilones, e incluso alfas.

Una taxonomía de este tipo permite razonar sobre la estructura y la complejidad de una arquitec-tura adaptativa. Sin embargo, para ser realmente útil, tendría que poder aplicarse de modo que ayudea extraer ciertas conclusiones de dicho razonamiento, comenzando por considerar si el enfoque uti-lizado es realmente consistente. A este fin se dedica, específicamente, el apartado siguiente.

3.1. ¿Es composicional una arquitectura adaptativa?

Ante el uso de un enfoque arquitectónico, cabe preguntarse si se está aplicando la abstracciónadecuada; no sólo porque varios de los aspectos que se abstraen podrían resultar relevantes, sino másaún porque antes debe de decidirse si un sistema adaptativo es composicional.

Preguntarse si un sistema cualquiera es composicional equivale a preguntarse si una operaciónde composición dentro de este sistema tiene las características constructivas adecuadas. En ese casopodrá constituirse en la base de una estructura modular, en la que se respetará el principio de separa-ción de asuntos. Para ello, la propiedad esencial consiste en que la operación se comporte igual conlos elementos simples que con aquéllos que ya han sido compuestos; es decir, que no sea necesariosaber si un elemento es simple o no para poder componerlo. Esta propiedad es la razón por la queun componente cualquiera (incluso cuando se trata de un elemento compuesto) puede tratarse comoun módulo aislado, ya que para incluirlo en un sistema mayor, la composición no necesita conocersu estructura interna, sino sólo su interfaz externa.

Se puede resumir esta propiedad, según la cual la composición es una operación que se puedeaplicar de manera reiterada sobre un conjunto de elementos, diciendo que tiene una estructura al-gebraica. Por contraposición, cuando esto no ocurre, es decir, cuando para componer un elementocomplejo es preciso tener en cuenta su estructura interna, se dice que la estructura es predicativa,ya que implícitamente se establece un vínculo entre los elementos internos y las construccionescompuestas que los contienen, sin respetar fronteras ni crear jerarquías de composición3.

Por ejemplo, en un sistema composicional tradicional, expresar el carácter algebraico resultacasi trivial. Dado que no se considera a priori más que un tipo de módulo, al que denominaremoscomponente (c), basta con proporcionar una operación de composición “pura”, a la que podremos

3 Por supuesto ninguna de ambas definiciones pretende ser precisa ni rigurosa en un sentido matemático.Ambos términos se usan únicamente con su significado intuitivo.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 35

Page 36: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

denominar suma (⊕). Se tiene, entonces:

(c⊕ c) = c

Esto es, como regla general, “la composición de dos componentes siempre da como resultadootro componente”. Al componente resultante se le puede aplicar la misma regla, creando de maneraconstructiva una jerarquía de composición, tal como se acaba de explicar. En este caso, la naturalezaalgebraica del sistema resulta evidente.

Al elegir un enfoque arquitectónico, se está asumiendo implícitamente que los sistemas self-?son composicionales, ya que de otro modo dicho enfoque no podría funcionar. Es decir, se estáasumiendo que una arquitectura adaptativa, aunque tenga sus características propias –tal como seacaba de describir en el apartado anterior– sigue siendo apta para un análisis arquitectónico, esto es,esencialmente algebraico.

Ahora bien, todo sistema self-? es inherentemente reflexivo, por definición. Por ejemplo, si unsistema es auto-gestionado, necesariamente una parte del sistema se dedica a gestionar al propiosistema. Utilizando la terminología del apartado anterior, dentro de todo alfa tiene que haber al me-nos un gamma. Esto no significa, por supuesto, que deban ser reflexivos en términos de niveles deabstracción, niveles-meta o mecanismos de reificación. Pero sí significa que su carácter es aparente-mente predicativo, lo que contradice claramente la suposición anterior4.

Para encontrar la respuesta a esta disyuntiva, basta con comprobar si se puede definir, siquiera demanera intuitiva, un “álgebra” de sistemas adaptativos. Es decir, si todas las propiedades arquetípicasde un sistema self-?, precisamente las que le dan el carácter de auto-gestionado, se pueden expresarde manera algebraica, entonces se podrá afirmar que el sistema es composicional, lo que justificaríael uso de un enfoque arquitectónico.

Ahora bien, las características específicas de los sistemas self-? se han resumido en las defini-ciones de los elementos identificados en la sección anterior. Todo detalle propio de una arquitecturaadaptativa ha de poder explicarse como un desarrollo de dichas definiciones. Ése ha de ser, por tan-to, el punto de partida del álgebra, que por tanto constará de cinco tipos de elementos (α, β, γ, δy ε). Las propiedades relativas a sus combinaciones se podrán describir como reglas (axiomas) quedefinen, a su vez, las operaciones del álgebra.

La composición pura (la suma, ⊕) expresaría la yuxtaposición de dos componentes, esto es, laoperación que reúne dos componentes y los conecta entre sí, devolviendo un elemento compuesto.En el caso ideal, un componente compuesto sería similar a los componentes origen (los sumandos).Pero en un sistema autonómico, esta intuición sólo permite establecer la regla siguiente:

(ε⊕ ε) = ε (1)

Es decir, la unión de dos componentes no-autogestionados (dos epsilones) siempre produce uncompuesto sin autogestión (otro épsilon). Pero aunque este resultado es inmediato, no se puedetrasladar a las categorías restantes. Se puede plantear una regla similar tanto en los gammas (γ ⊕ γ,la unión de controladores produce un controlador) como en los deltas (δ ⊕ δ, la unión de auxiliaresproduce un auxiliar); pero en ambos casos el componente resultante puede tener muy baja cohesión,y no comportarse, de hecho, como un compuesto.

Aún más paradójico sería el caso de los betas y alfas. En el primer caso, la regla se cumple,pero no de la manera intuitiva; en el otro, puede llegar a ocurrir lo contrario de lo que se estaríaenunciando. En realidad, lo que ocurre es más bien lo siguiente:

(β ⊕ β) = β (2)(α⊕ α) 6⊃ α (3)

4 No se debe interpretar, no obstante, que un sistema no pueda ser composicional y reflexivo a la vez. El propioADL PiLar [5] es una prueba de lo contrario.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 36

Page 37: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Es decir, según (2), la unión de dos betas siempre resulta en un beta, lo que es también lo indicadopor la intuición: la unión de dos sistemas con control parcial normalmente produce otro cuyo controltambién es parcial. Pero también puede ocurrir que los betas sean complementarios, de modo queconjuntamente definan un control total, resultando ocasionalmente en un alfa (β ⊕ β → α). Sinembargo esto no contradice la regla, ya que por definición se tiene que α ⊂ β, esto es, que todosistema que se gestiona totalmente también se gestiona por partes.

Aún más significativa es la inecuación (3), que se puede enunciar como el que se denomina-rá Principio de Composición Autonómica: la unión de elementos autónomos no necesariamenteproduce un sistema autonómico. Aunque esto resulta evidente (considérese qué ocurre cuando loselementos autónomos no cooperan entre sí), de hecho contradice una intuición muy extendida.

No obstante, la suma no basta; la especificidad de los sistemas self-? exige un segundo operadorde composición, que define una unión más directa entre dos componentes. Este operador, el pro-ducto (⊗), define el efecto de un controlador-γ sobre un componente-ε controlado. Esta operaciónpuede producir dos resultados diferentes, que se describen en las reglas siguientes:

(γ ⊗ ε) = β (4)(γ ⊗ ε) → α (5)

Denominaremos a la primera (4) Condición Débil, y a la segunda (5) Condición Fuerte delcontrol autonómico. Podría pensarse que ambas reglas se contradicen; obsérvese sin embargo que laprimera se cumple siempre, mientras que la segunda sólo se cumple en ocasiones (de ahí el símbolo→). Por otra parte ambas son perfectamente compatibles si se tiene en cuenta, de nuevo, que α ⊂ β.

A partir de estas reglas, y de sus propiedades (conmutatividad, asociatividad, etc.), se puededesarrollar un álgebra completa en la que se describan las características de un sistema self-?. Dentrode este álgebra se pueden plantear todas las cuestiones que parezcan conflictivas, y en las que sepudiera contradecir la naturaleza composicional que se ha asumido. No se pretende aquí desarrollareste álgebra, sino tan sólo plantear el modo en que podría utilizarse. A mero título de ejemplo, sedescriben a continuación dos de las cuestiones mencionadas.

La primera de ellas plantea, ¿qué ocurre al añadir una capa de control adicional a un elementoautónomico? Es decir, ¿sería cierta o no la regla siguiente?

(γ ⊗ α) = α

La respuesta es ambigua; aparentemente añadir un controlador adicional no debería comprometerla autonomía de un sistema. Pero de hecho esto puede ocurrir; puede afectar a su comportamiento,incluso alterarlo por completo. Por ejemplo, basta considerar un caso en el que el elemento-γ fueraun envolvente (wrapper) que alterase los datos recibidos. En resumen, esta regla no es cierta.

La segunda pregunta es aún más elaborada, ya que se pueden considerar varios matices. De ladefinición se debería asumir que:

(α⊕ ε) = β

Esto es, que la inserción de un elemento no controlado en un sistema autonómico produce unsistema con control parcial. Esto es siempre cierto; pero puede resultar insuficiente. En primer lugar,por un problema de escala. Considérese que si el sistema no controlado es lo bastante grande, y elautónomo lo bastante pequeño, su efecto sobre el sistema global puede resultar prácticamente nulo(es decir, α ⊕ ε = ε). Esto no es incompatible, si se considera que, a partir de cierto umbral detamaño relativo, todo beta ha de ser visto como un épsilon.

Pero, en este caso, resulta aún más paradójico considerar que, ocasionalmente, el resultado puedeser un alfa (es decir, α⊕ ε → α). Este ejemplo parece contradecir el carácter algebraico del sistema,ya que al asumir el control del nuevo elemento, no parece respetarse la modularidad del α. Sinembargo, lo que podría ocurrir es algo similar a lo siguiente:

(α⊕ ε) = ((γ ⊗ ε)⊕ ε) → ((γ ⊗ (ε⊕ ε)⊕ ε) B (γ ⊗ ((ε⊕ ε)⊕ ε)) = α

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 37

Page 38: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Esto es, se desarrolla el alfa según la Condición Fuerte (que en este sentido siempre es cierta);suponiendo que la parte controlada (ε) sea compuesta, ésta se puede combinar con el nuevo elementode modo que el controlador (γ) asume también control sobre él. Esta operación (que se ha indica-do como B) sí que puede describirse de manera algebraica, concretamente como una extrusión oextensión de ámbito (similar a la que existe, por ejemplo, en el cálculo-π). Esto puede ocurrir, porejemplo, cuando uno de los ε internos sea un conector al que se unen todos los demás, y el γ estéactuando específicamente sobre éste. A partir de este punto, dada la asociatividad de la suma y laregla (1), puede verse que se obtiene un elemento-α.

En resumen, de este análisis se deduce que un álgebra de este tipo parece capaz de describirtodas las hipótesis asociadas a un sistema adaptativo. En consecuencia, se puede concluir que sunaturaleza es efectivamente compositiva, lo que justifica el uso de un enfoque arquitectónico.

4. Ejemplo: Actualización en una Arquitectura Autonómica

En todas las secciones anteriores se ha señalado que el propio concepto de sistema self-? apuntaa una naturaleza reflexiva. Por otra parte, muchas de las soluciones propuestas se basan en el usode mecanismos reflexivos, tanto a nivel tecnológico [9] como conceptual [8,14]. Por otra parte, seha justificado el uso de un enfoque arquitectónico; pero apenas se ha planteado, en lugar de aplicararquitecturas reflexivas concretas, hacer reflexiva la propia definición de la arquitectura.

En esta sección se utiliza un ADL con reflexión, PiLar, definido originalmente en [4], ya desa-rrollado plenamente en [3,5], y posteriormente extendido en [6,7], entre otros. El lenguaje fue con-cebido originalmente como una construcción teórica, que permitía demostrar una hipótesis doble, asaber: que era posible integrar el concepto de reflexión en el nivel arquitectónico, y que este concep-to era suficiente para describir todo tipo de dinamismo. Cumplidos estos objetivos, el lenguaje hademostrado posteriormente su utilidad para describir arquitecturas en distintos ámbitos.

El objetivo de este artículo es mostrar quePiLar, sin nuevas extensiones, es apto para la descrip-ción de arquitecturas autonómicas; al lograrlo, se habrá demostrado al mismo tiempo la viabilidaddel enfoque reflexivo para la especificación de sistemas adaptativos. Con el fin de mostrarlo de ma-nera intuitiva, en esta sección se presentará el desarrollo de un ejemplo concreto.

Fig. 2. Configuración Inicial de la Arquitectura

La arquitectura presentada se inspira directamente en un ejemplo del conocido artículo de Kep-hart y Chess [11] sobre computación autonómica. Se trata de un sistema autonómico de actuali-zación; esto es, la arquitectura constará de un subsistema capaz de soportar y regular de maneraautonómica la actualización de componentes. Específicamente, es un ejemplo de auto-reparación(self-healing), integrado dentro de un sistema autonómico, que describe adaptatividad programada.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 38

Page 39: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Globalmente, se puede resumir el comportamiento que se desea de este sistema autonómico dela manera siguiente. El sistema debe soportar la posibilidad de actualizar componentes dinámica-mente; esto es, de recibir una nueva versión de un componente, y sustituir todas sus instancias en laarquitectura, sin detener su ejecución. En este momento, interviene el subsistema autonómico, queaplicará una batería de pruebas de regresión sobre los nuevos componentes, para comprobar que elcomportamiento del sistema sigue siendo consistente. Los resultados de estas pruebas serán exami-nados por un analizador, que determinará si los resultados son satisfactorios o, por el contrario, seidentifica (y localiza) algún problema.

\component A (\ interface ( port P )\constraint (

Emisor def= rep ( tau(m); P!(m) ) ) )

\component B (\ interface ( port Q | port P )\constraint (

Filter def= rep ( Q?(m); tau(m,d);P!(d) ) ) )

\component C (\ interface ( port Q )\constraint (

Consumer def= rep ( Q?(d); tau(d) ) ) )

\component K (\ interface ( port M )\constraint (

Synth def= tau(h);rep ( loop d ( bound(M) )

( tau(d,h) ) ) ) )

\component L (\ interface ( port R | port P )\constraint (

Adder def= rep ( tau(g); loop m ( bound(R) )( tau(m,g) ); P!(g) ) ) )

\component System (\config (

A1, A2: A | B1, B2: B | C1: C |K1, K2: K | L1: L |\bind (

A1.P = B1.Q | A1.P = K1.M | A1.P = L1.R |B1.P = C1.Q | B1.P = K1.M |A2.P = L1.R | A2.P = B2.Q |L1.P = K2.M | B2.P = K2.M ) ) )

Fig. 3. Configuración Inicial de la Arquitectura en PiLar

La Figura 2 muestra gráficamente la arquitectura inicial del sistema, en la que no se muestratodavía el subsistema autonómico. La misma estructura se especifica en la Figura 3 usando PiLar.Incluso sin conocer el lenguaje, resulta bastante evidente que lo que se hace es definir los distintostipos de componente ( A, B, C, K y L), para luego crear e interconectar sus instancias ( System).

La descripción en PiLar añade unos matices sobre su comportamiento. Brevemente, los ele-mentos A son fuentes de datos; los B, filtros que alteran dichos datos; los K, integradores de datosprocedentes de distintas fuentes, de manera similar al L, que se presenta como un sumador; y final-mente, el C es un consumidor (sumidero) de estos datos.

La versión original de este ejemplo [11] asume, siguiendo el modelo de Kephart, que todos loscomponentes son autónomos, es decir, que todos son elementos-α. Nuestra presentación parte de unsupuesto diferente; los componentes básicos descritos en las Figuras 2 y 3 son módulos convencio-nales (elementos-ε); el sistema se transforma en una arquitectura autonómica mediante la adición deuna “capa” de autogestión, que se describirá a continuación (Figura 4). Esta capa se introduce pormedios reflexivos, justificando la tesis de este trabajo. Esto es, se muestra que la adaptatividad puedeser descrita a nivel arquitectónico, siempre que se disponga de las abstracciones necesarias a estenivel, en este caso las propias de la reflexión.

En la Figura 4, por tanto, se describe la mencionada capa de autogestión, que implementa lafuncionalidad autonómica descrita en PiLar. La arquitectura original queda inalterada: tan sólose introduce un conjunto de elementos nuevos en el nivel meta. Como puede verse, todos ellos seespecifican de manera similar a los componentes convencionales anteriores; lo único que hace elsoporte reflexivo de PiLar es colocarlos en el nivel de abstracción adecuado.

No se entrará aquí a describir en detalle la base teórica en la que se fundamenta la reflexiónen PiLar, pues probablemente sólo dificultaría la comprensión del ejemplo. Baste decir que, co-mo todo sistema reflexivo, se distinguen dos niveles de abstracción: el base, donde se realizan las

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 39

Page 40: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

\component System (\metaface ( port U | port RT | port DA )\config ( \bind (

self .U = Updater.S | self .RT = Tester.S |self .DA = Analyzer.S |Tester.T = Analyzer.T ) )

\constraint (SelfUp def= rep ( U?(nomT,defT);

loop i ( avatarSet(nomT) )( loop b ( bound(i) )

( new(j:defT); link ( j ,b);del( i ) ) ) )

SelfTest def= rep ( RT?(nomT,rtest);for ci ( avatarSet(nomT) )

( tau(ci , rtest ,res ); cons(res,VRes) );RT!(VRes);DA!(avatarSet(nomT)); SelfConn )

SelfConn def= rep ( DA?(ci);DA!(bound(ci)) ) ) )

\component Updater (\metaface ( port S | import OT | import NT )\constraint (

Updating def= rep ( OT?(nomT);NT?(defT); S!(nomT,defT) ) ) )

\component Tester (\metaface ( port S | export T | import RT )\constraint (

Testing def= rep ( RT?(nomT,rtest);S!(nomT,rtest); S?(VRes); T!(VRes) ) ) )

\component Analyzer (\metaface ( port S | port T | export D )\constraint (

Analyzing def= rep ( S?(vComp);loop ci ( vComp )( S!(ci ); S?(vBnd);T?(VRes); tau(vBnd, VRes, ok);if ( not(ok) ) ( D!(ci ) ) ) ) ) )

Fig. 4. Nivel Meta: Sistema Autonómico de Actualización

operaciones convencionales, y el meta, donde se realizan las operaciones reflexivas, esto es, queafectan al propio sistema. En PiLar se denomina reificación a la relación que liga ambos sistemasa nivel arquitectónico; aunque puede hacerse explícita, se define siempre de manera implícita entreun componente y su tipo. Así pues, para todo componente se puede describir comportamiento-base,asociado a la instancia y exportado a través de una interface, o comportamiento-meta, asociado altipo y exportado a través de una metaface. Dicho esto, es obvio que el lugar adecuado para lasfunciones de autogestión es el nivel meta.

La estructura que se define en la Figura para System es obviamente de nivel meta. Básicamente,se asume que presenta una meta-interfaz hacia los nuevos componentes-meta ( Updater, Tester yAnalyzer), y que los puertos respectivos son controlados por nuevas restricciones (procesos concu-rrentes, según la semántica de PiLar) que proporcionan el comportamiento esperado.

Brevemente, se puede resumir el comportamiento del modo siguiente. En primer lugar, se recibeen Updater el nombre de un componente y la definición de una nueva versión; ambos datos se trans-miten al sistema, ordenándole actualizarse. Al recibir esta información, el proceso SelfUp localizaa todas las instancias de ese componente e identifica sus conexiones; crea instancias de la nuevaversión, las conecta del mismo modo, y destruye la versión anterior.

Se recibe entonces en Tester una batería de pruebas para el nuevo componente, y éste se locomunica al sistema. El proceso SelfTest ejecuta estas pruebas en todas las instancias, y acumula elresultado en una estructura, que envía de nuevo al Tester, que a su vez se las comunica al Analyzer.Al mismo tiempo, el sistema indica al Analyzer la ubicación de todas las instancias afectadas.

Finalmente, el Analyzer recibe ambos bloques de datos; solicita al sistema (SelfConn) la lista deconexiones de cada instancia, y las examina una a una. De este modo, se analiza el origen de cadafallo detectado en las pruebas, identificando el lugar de la arquitectura en el que se ha producido, yse comunica la conclusión. Por ejemplo, en el caso original de Kephart, se detectaban problemas enlos componentes K y L, y se terminaba por deducir que la actualización de L1 había sido incorrecta.

En la Figura 5 puede verse claramente, sin necesidad de mayor explicación, el lugar que ocupantodos los componentes del sistema en la taxonomía de la sección 3. Así, como se ha dicho, todos loscomponentes básicos ( A, B, C, K y L) son epsilones. Los componentes-meta Updater y Tester sondeltas, aunque indirectamente actúan como gammas, mientras que el componente-meta Analyzer esclaramente un delta. Finalmente, el propio System, considerando ambos niveles, es un beta (su nivelmeta, por definición, es un gamma). Si se considerase a la actualización como una propiedad-self,sería un más bien un alfa, ya que es totalmente autónomo respecto a ella.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 40

Page 41: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Fig. 5. Arquitectura Reflexiva con Actualización Autonómica

En resumen, partiendo de una arquitectura totalmente convencional, se han utilizado las capa-cidades reflexivas de PiLar para añadir todos los elementos estructurales y de comportamientonecesarios para definir un subsistema autonómico de actualización, sin necesidad de alterar la des-cripción original. Dado que estos elementos se añaden en un nivel de abstracción superior, la autono-mía se convierte en un elemento inherente al propio sistema, de modo que todo nuevo componenteque pudiera incorporarse queda igualmente cubierto por ella (es decir, que (α ⊕ ε) = α). Ésta es,precisamente, la principal ventaja de un enfoque reflexivo.

5. Conclusiones y Trabajo Futuro

A lo largo de este trabajo se ha justificado tanto la consistencia del enfoque arquitectónico parala definición de sistemas adaptativos, como la viabilidad de combinarlo con un enfoque reflexivo, talcomo se ha hecho en el ejemplo del apartado anterior.

Probablemente la consecuencia más significativa, e incluso aparentemente paradójica de esteplanteamiento, sea comprobar que incluso algo tan ligado al comportamiento y estructura internas deun sistema como la adaptatividad, se pueda concebir y describir desde un punto de vista estrictamentemodular. En cualquier caso, esto resulta especialmente adecuado, pues muestra que incluso en estecontexto se puede mantener la separación de asuntos.

Teniendo en cuenta este detalle, y la existencia de un soporte aspectual en PiLar [6], basado asu vez en el modelo reflexivo pero independiente de éste, se plantea como trabajo futuro la posibili-dad de describir las propiedades-self como aspectos superpuestos a una arquitectura. Este enfoqueresultaría especialmente flexible si se combina con el soporte de propiedades temporales definidoen [7], que permitiría plantearlo de manera totalmente autonómica.

Referencias

1. J. S. Bradbury, J. R. Cordy, J. Dingel, and M. Wermelinger. A Survey of Self-Management in DynamicSoftware Architecture Specifications. In Proc. 2nd Workshop Self-healing Systems (WOSS’04), pages 28–33. ACM Press, Nov. 2004.

2. C. Canal, J. M. Murillo, and P. Poizat. Software Adaptation. L’Objet, 12(1):9–31, 2006.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 41

Page 42: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

3. C. E. Cuesta. Reflection-based Dynamic Software Architecture. ProQuest Inf. & Lrn., May 2003.4. C. E. Cuesta, P. de la Fuente, M. Barrio-Solórzano, and E. Beato. Dynamic Coordination Architecture

through the use of Reflection. In Proceedings 16th ACM Symposium on Applied Computing (SAC2001),pages 134–140, Mar. 2001.

5. C. E. Cuesta, P. de la Fuente, M. Barrio-Solórzano, and M. E. Beato. Introducing Reflection in ArchitectureDescription Languages. In Software Architecture: System Design, Development and Maintenance, pages143–156. Kluwer Academic Publishers, 2002.

6. C. E. Cuesta, M. P. Romay, P. de la Fuente, M. Barrio, and H. Younessi. Coordination in ArchitecturalConnection: Reflective and Aspectual Introduction. L’Objet, 12(1):127–151, 2006.

7. C. E. Cuesta, M. P. Romay, P. de la Fuente, and M. Barrio-Solórzano. Temporal Superimposition of As-pects for Dynamic Software Architecture. In Formal Methods for Open Object-Based Distributed Systems,volume 4037 of Lecture Notes in Computer Science, pages 93–107, 2006.

8. P. Grace, G. Coulson, G. S. Blair, and B. Porter. A distributed architecture meta-model for self-managedmiddleware. In Proc. 5th Workshop on Adaptive and Reflective Middleware (ARM’06), page 3, 2006.

9. G. Huang, T. Liu, H. Mei, Z. Zheng, Z. Liu, and G. Fan. Towards Autonomic Computing Middleware viaReflection. In Proc. 28th Annual Intl. Computer Software and Applications Conference (COMPSAC’04),pages 135–140, 2004.

10. S. Johnson. Emergence. The Connected Lives of Ants, Brains, Cities and Software. The Free Press, Simon& Schuster, 2001. Ed. esp.: Sistemas Emergentes, Turner, 2003.

11. J. O. Kephart and D. M. Chess. The Vision of Autonomic Computing. IEEE Computer, 36(1):41–50, Jan.2003.

12. J. Kramer and J. Magee. Self-Managed Systems: an Architectural Challenge. In Intl. Conf. Sw. Enginee-ring, Future of Software Engineering (FOSE’2007), pages 259–268. IEEE CS Press, May 2007.

13. P. Lin, A. MacArthur, and J. Leaney. Defining Autonomic Computing: A Software Engineering Perspec-tive. In Proc. IEEE Australian Conf. Software Engineering (ASWEC 2005), pages 88–97. IEEE CS Press,Apr. 2005.

14. P. K. McKinley, S. M. Sdjadi, P. Kasten, Eric, and B. H. Cheng. Composing Adaptive Software. IEEEComputer, 37(7):56–64, July 2004.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 42

Page 43: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Dynamic Composition and Adaptation in

Adapt-Medium

An Phung-Khac, Maria-Teresa Segarra, Jean-Marie Gilliot, andAntoine Beugnard

Department of Computer Science, TELECOM BretagneTechnopole Brest-Iroise - CS 83818 - 29238 Brest Cedex 3 - France

{an.phungkhac,mt.segarra,jm.gilliot,antoine.beugnard}@enst-bretagne.fr

Abstract. In the presence of operational context changes, many applications mustuse dynamic adaptations in order to meet requirements. When an application has aset of distributed objects that collaborates to offer a particular function, adaptationsinvolving simultaneous distributed processes may affect such collaborations, planningdistributed adaptations is thus a complex task for developers. This paper presentsAdapt-Medium, an architecture of adaptive distributed components. In the archi-tecture, adaptations are realized by performing dynamic compositions of distributedcomponents. We introduce a model-based process for 1) specifying architecture vari-ants of such distributed components and 2) automatically generating adaptation plansthat are performed at runtime to switch between architecture variants.

1 Introduction

Increasingly, applications must support runtime adaptations and in response to changes inexecution environment. Such adaptation require applications to change behaviors or evenchange their internal structures dynamically in maintaining continuous availability [1]. Whenan application has a set of distributed objects that collaborates to offer a particular function,adaptations involving simultaneous distributed processes may affect such collaborations.Supporting runtime adaptations of this class of applications can be challenging. In this paper,we introduce an architecture-based approach to dynamic adaptation of such applications.

Architecture-based adaptation is mainly concerned with structural changes at the levelof software components [2]. In the context of applications having distributed functionalcollaborations, building runtime adaptations features requires some challenging tasks:

– Specifying consistent architecture variants: Through an adaptation, an application movesfrom a consistent architecture variant to another consistent architecture variant. Spec-ifying such consistent architecture variants of the application is thus critical to ensurethe correctness of the collaboration after adaptations.

– Supporting runtime transitions: Runtime transitions of architectures are also critical inorder to preserve states and data through adaptations. Such transitions involve simulta-neous distributed processes having dependencies between them. Planning adaptations isthus a complex task for developers. Moreover, an important class of applications requirescontinuous availability, adaptations must be transparent to users.

Addressing these issues, we propose Adapt-Medium, an architecture of adaptive dis-tributed collaborations. From a collaboration abstraction called medium, we can build ar-chitecture variants and embed these variants into a platform that can dynamically select aproper running variant. Thanks to a design process, all the architecture variants are consis-tent. Moreover, because all the variants are embedded in the platform at design time, dataof a replaced variant can be transferred to the new one during runtime variant transitions.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 43

Page 44: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

In our approach, we specify transition actions within the refinement process (of thecollaboration abstraction into architecture variants). Then, by using model-based techniques,we can automatically generate the target adaptive distributed application with adaptationplans.

The remainder of this paper is organized as follows. Section 2 presents the originalmedium that was proposed previously in our project [3]. Section 3 introduces the designprinciples of Adapt-Medium that is based on the medium architecture. Section 4 illustrateshow our refinement process can build consistent architecture variants and how we can gen-erate adaptation plans by an example. Section 5 presents related work. Finally, Section 6summarizes the paper and discusses future work.

2 Medium

A medium is a collaboration abstraction represented as a software entity. An applicationis built by interconnecting some functional components with a medium that represents thecollaboration of the functional components [3].

Agency 1

Agency 2

Reservation medium

Companyid

Agency 2

Logical medium

CompanyMiddleware

Agency 1

Physical medium

id Data

RoleManagers

(a)

Abstraction

(b)

Deployment

reserve or cancel

initialize

id

id

id

Legend

Fig. 1. Medium deployment architecture

For example, consider an airplane seats reservation application of an airline companywith travel agencies located worldwide. As shown in Figure 1 (a), we can specify a reser-

vation medium managing seats’ identifiers (IDs) and offering medium services to initializeinformation about seats, to reserve seats and to cancel reservations. The reservation appli-cation can then be built by interconnecting the reservation medium and local functionalcomponents representing the airline company and the agencies.

Figure 1 (b) shows the deployment architecture of the reservation medium that splits intophysical role managers. Each role manager is associated with a local functional componentand implements the medium services used by this functional component. As shown in thefigure, the seats’ IDs set may be distributed between role managers. Depending on the datadistribution architecture (e.g., distributed, centralized) or the data type chosen for datamanagement, the medium at the deployment level may be different.

3 Adapt-Medium

3.1 Design Principle

Our approach is to generalize the refinement process in order to obtain all planned evolu-tionary architecture variants from a collaboration abstraction, then compose these variants

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 44

Page 45: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

into an adaptable medium that can dynamically select a proper running variant at runtime.The architecture meta-model also allows to build and integrate new variants at runtime.

* 1

Collaboration abstraction

1 11

arch. variant 1

11

1 1* 1 11

arch. variant n

1 1*

1 11

Adapt-medium

1 1*

Refinement

CompositionSource

adapt-manager

Design decision model

Reserver

local func. componentSource

local func. component

Fig. 2. Adapt-Medium design principle

Figure 2 briefly shows our development approach in building adaptable and evolvablereservation medium (called reservation adapt-medium). This adapt-medium can be used inreservation applications that can dynamically switch the data type and the data managementalgorithm used for managing seats’ IDs when the execution context changes (e.g., the numberof agencies increases, evolution of database systems).

– Refinement. From the collaboration abstraction, we specify design decision models. Eachof these models contains a sequence of design alternatives that lead the refinement ofthe abstraction to an architecture variant. All the architecture variants conform to theabstraction.

– Composition. All the role managers corresponding to a functional component are com-posed into an adapt-manager. A generic implementation of adapt-managers is introducedin this step. Models of the architecture variants, the adapt-medium model, and designdecision models are preserved in the adapt-medium.

3.2 Planning Transitions

Because the adapt-medium contains all the implementations of the medium architecturevariants at runtime, the data of a replaced architecture variant can be transferred to thenew architecture variant.

Transition plans can be built by analyzing the two design decision models correspondingto the current running variant and the target variant to determine which data from whichmanagers of the current variant should be read, and then, should be write in which managersof the target variant. The result is then a plan of Read and Write actions. Each of theseactions is refined into some coordinated distributed actions by top-down goal decompositions[4].

3.3 Adapt-Medium Architecture

Figure 3 shows the global view of a distributed application using an adapt-medium. Thisapplication is deployed on two sites, on each site, a functional component is associated

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 45

Page 46: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

with an adapt-manager. The adapt-medium is then the logical aggregation of two adapt-managers, one per site. Each adapt-manager consists of a composite manager, an adaptation

controller and a medium logic component. The composite manager contains all the manager

variants of the corresponding role manager and an adaptor.

Adaptationcontroller

Functionalcomponent A

control

Medium logic

AdaptationcontrollerManager B2

Functionalcomponent B

control

Medium functions Medium functions

Middleware

Adapt-Medium

A medium variant

Adaptation coordination

Functional communication

Medium logic

Manager B1 Manager A1

Manager A2

Adapt-manager

Fig. 3. Adapt-Medium architecture

The adaptor refers called medium services to the running variant by a parameter thatcan be changed by the executor. The adaptation controller receives context information,makes adaptation decisions, selects a proper running variant, generates adaptation plansand executes the plans. The medium logic sub-component manages medium’s meta-data(information about structures of all architecture variants and design decision models) andadapt-managers’ instances information. Functional collaboration between composite man-agers and adaptation coordination between adaptation controllers are performed through themedium logic layer. In addition, adaptation controllers use medium information managedby medium logic sub-components to schedule adaptations.

4 Example: Reservation Adapt-Medium

4.1 Building Architecture Variants

<<interface>>ISourceMediumServices

/source

ReservationMedium

1..*

1

initialize(ReserveId[], Boolean)

Boolean usable = false Boolean cancelerIsReserver

<<interface>>IReserverMediumServices

ReserveId reserve() Cancel(ReserveId)

/reserver

ReserveId

reserved *

+ available

0..1

*

Fig. 4. Abstract specification of the reservation adapt-medium

This section illustrates the refinement process in the Adapt-Medium design principlepresented in the previous section by the example of the reservation adapt-medium. Thefollowing are some class diagrams of the reservation application in some steps the refinementprocess.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 46

Page 47: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Abstraction. Figure 4 shows the class diagram of the reservation application at theabstract level. Class ReservationMedium represents the logical medium that implements theISourceMediumServices interface used by the Source class and the IReserverMediumServicesinterface used by the Reserver class. Class ReserveId represents a seat’s ID. The mediummanages the (available) set of available seats’ IDs. Each instance of the Reserver classhas a (reserved) set of seats’ IDs reserved by the corresponding agency.

<<interface>>ISourceMediumServices

SourceManager

ReservationMedium

1..*

1

initialize(ReserveId[ ], Boolean)

Boolean usable = false Boolean cancelerIsReserver

<<interface>>IReserverMediumServices

ReserveId reserve() Cancel(ReserveId)

ReserverManager

ReserveId

+ reserved

+ available

0..1

/source

/reserver

1 1

1 1

*

*

Fig. 5. Managers introduction

Introducing role managers. In order to identify and separate design alternatives,role managers are introduced, one per functional component. Figure 5 shows the class di-agram of the application after the role managers introduction. The SourceManager andReserverManager classes are introduced. These two classes implement the medium services,but the available data are still managed by the ReservationMedium class representing thelogical medium. The reserved data of the Reserver class in the abstract specification isnow managed by the ReserverManager class.

Medium

AbstractType AbstractType

Algorithm Manager DataFormat

ProtocolObjectAlgorithm

+ data format + storage nodes+ data structure

+ implementation algorithm

+ distributed protocol + protocol roles

1 *

1

1

1 1..*1 1

1

1

1

1..*

1 1..*

1 1

1 1Protocol ProtocolObject

Property

ReservationMedium

ListListDefaultAlgorithm

ReserverManager

HashTableFormat

MITAlgorithm

+ data format + storage nodes+ data structure

+ implementation algorithm

+ distributed protocol + protocol roles

1 *

1

1

1 1..*1 1

1

1

1

1..*

1 1..*

1 1

1 1Chord ChordObject

Available

(a)

(b)

Fig. 6. (a) Generic design decision model and (b) a design decision model

Identifying and separating design alternatives. Generally, the logical medium atthis level has data or services that need to be distributed on role managers. In the reservationmedium, there is only the available seats’ IDs set that needs to be distributed. In thisexample, we have identified seven design concerns of the seats’ IDs distribution: the abstract

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 47

Page 48: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

type used to represent distributed data, the abstract type implementation, the data format

used to represent local data, the data distribution topology specifying role managers thatcan participate to the distribution, the role of role managers in the distribution (e.g., client,server, peer), the distributed protocol used to implement the data distributed strategy (e.g.,Chord [5]), the distributed protocol implementation algorithm that specifies the protocolimplementation (e.g., OpenChord [6] or MIT Chord implementation [7]). For each designconcern, there are several design alternatives (e.g., Chord, Pastry design alternatives for thedistributed protocol design concern).

From the identified design alternatives, we create design decision models. These designdecision models guide a refinement that transforms the abstraction into some medium archi-tecture variants. With each design decision model, a medium architecture variant’s modelis built.

Figure 6 shows the generic design decision model (a) and a design decision model forthe distribution of seats’ IDs (b). For example, the available set can be distributed onReserverManager role managers by using the Chord algorithm implemented by MIT. Theavailable distributed data can be accessed via proxies as List data. Primitives of theList data are implemented by ListDefaultAlgorithm. With this design decision model,the implementation class diagram of the corresponding architecture variant is shown inFigure 7.

1

<<interface>>ISourceMediumServices

SourceManager

ReserverManager

<<interface>>IReserverMediumServices

ListDataManager

HashTableScheme

<<interface>>IHashTableSchemeServices

ChordObject MITAlgorithm

<<interface>>IChordObjectServices

ListDefaultAlgorithm

<<interface>>IListServices ListObject

+ available

+ available

+ reserved

1 1

1 1

0..1

*

1

1

11

11

1 1

1 1

1

1 1

ListDataProxy

ReserveId

Source

Reserver

Fig. 7. An architecture variant of the reservation medium

By this refinement process with design decision models, all the medium architecturevariants conform to the medium abstraction. Thereby, these medium architecture variantsare consistent from the viewpoint of distributed functional collaboration and the distributedfunctional components of the application using the adapt-medium can correctly collaborateafter switching variants.

4.2 Generating Adaptation Plans

Figure 8 shows another viewpoint of the refinement process. Design alternatives refine acollaboration abstraction (medium) into architecture variants through several internal vari-ants. A sequence of design alternatives forms a design decision model. For example, thesequence of design alternatives corresponding to the internal variants {(1),(2),(3),(4),(5)} isthe design decision model in Figure 6 (b).

In order to automatically generate adaptation plans, we aim to specify transition actionswithin the steps of the refinement process. Along every sequence of variants, from the ab-straction to the architecture variant through internal variants, we specify 1) actions that

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 48

Page 49: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Collaboration Abstraction

Managers Introduction

Distributed List CentralizedHash Table

Participants:ReserverManagers

Data need to be managed:

Available IDs set

Local data format: List

Local data format: Hash Table

CentralizedAlgorithm X

ListDefaultAlgorithm

ChordObjects

ServerObject

ClientObject

Server:ReserverManagerX

Clients: Other ReserverManagers

6

3

5

Impl:MITAlgorithm

4

Chord

Impl:ImplementationA

HashTableDefault Algorithm

1

27

8

9

0

Fig. 8. Specifying architecture variants transitions

need to be executed to transfer data from a variant to the next one and 2) actions that areneeded to restore data of this variant from the next variant.

For example, with the sequence {(1),(2),(3),(4),(5)}, the actions are described as follows:

From (0) to (1):

for item in (0).Available

(1).ListDefaultAlgorithm.Write(item)

Restore (0) from (1):

(1).Available = null

Do

item = (1).ListDefaultAlgorithm.Read()

if item <> null then (0).Available.add(item)

Until item = null

From (1) to (2):

No data to be transferred

From (1) to (3):

(1).ListDefaultAlgorithm.Write(item) = {

(a ReserverManager).ChordObject.Write(item)

}

Restore (1) from (3):

(1).ListDefaultAlgorithm.Read() = {

(a ReserverManager).ChordObject.Read()

}

From (3) to (4):

No data to be transferred

From (3) to (5):

No data to be transferred

Consider another design decision model corresponding an architecture variant (call vari-ant B) in which the Available set is organized in a centralized way. This design decision

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 49

Page 50: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

model corresponds to the sequence of internal variants: {(6),(7),(8),(9)}. With this sequence,we can specify the following transition actions:

From (0) to (6):

for item in (0).Available

(1).HashTableDefaultAlgorithm.Write(item)

Restore (0) from (6):

(1).Available = null

Do

item = (1).HashTableDefaultAlgorithm.Read()

if item <> null then (0).Available.add(item)

Until item = null

From (6) to (7):

No data to be transferred

From (6) to (8):

(1).HashTableDefaultAlgorithm.Write(item) = {

(ReserverManager X).ServerObject.Write(item)

}

Restore (6) from (8):

(1).HashTableDefaultAlgorithm.Read() = {

(ReserverManager X).ServerObject.Read()

}

From (8) to (9):

No data to be transferred

From these actions, we can automatically generate adaptation plans for switching be-tween two architecture variants corresponding two design decision models.

In our approach presented in this section, we focus only on transitions of functional data(seats’ ID). In order to optimize transitions, other data can be also transferred betweenarchitecture variants. For example in the internal variant (4), routing data can be transferredto other implementations of the Chord algorithm.

5 Related Work

Many research projects have been investigating techniques to support runtime adaptation ofdistributed applications. But currently, to the best of our knowledge, there does not exist anapproach that supports automatically planning runtime adaptations of applications havingdistributed functional collaboration.

In the field of robotic, some work supported automatically planning adaptation. Forexample, in [8], Daniel Sykes et al proposed a three-layer model in which adaptation plansare generated from goal models expressed in temporal logic. The plans are executed byselecting alternative components. In the context of distributed collaboration, e.g., two robotscollaborate to perform a task, this work does not ensure the correctness of the collaborationbetween alternatives components of the robots.

A number of approaches supports adaptation mechanisms by replacing or rebinding com-ponents [9] or by customizable frameworks to developing adaptable component-based appli-cations [10, 11]. In these approaches, the authors did not focus on the distributed functionallogic of applications.

In [12], Gautier Bastide et al proposed an approach to create composite componentsfrom monolithic ones by restructuring the latter. A composite component consists of sub-components that are deployed on distributed hosts in order to adapt to deployment poli-cies (e.g., when the monolithic component cannot be deployed on a host). Compared withAdapt-Medium, the monolithic component corresponds to the abstraction and a composite

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 50

Page 51: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

component corresponds to an architecture variant. However, because the goal of [12] is toadapt the application deployment, this approach does not support mechanism to switchcomposite components. Moreover, as concluded in [12], this work does not allow runtimeadaptations.

A few approaches support multiple distributed adaptations. In ACEEL [13], an adap-tive distributed application has some distributed coordinators that coordinate multiple dis-tributed adaptation in order to maintain the cooperation of distributed components. Thecoordinators collaborate by using an adaptation policy provided by developers. In [14], KurtGeihs et al proposed an approach to develop component-based distributed applications thatincludes a framework for selecting proper variants based on the current state of the exe-cution context. In this work, the creation of the application variants is also based on somecomponent plans describing the components composition defined by developers. By allowingdevelopers define the adaptation policy [13] and the component plans [14], these approachessupport a large class of applications, but the capability to maintain distributed collaborationthus depends on developers.

From the viewpoint of distributed components connection, mediums have a similarity toexplicit software connectors [15] used in ArchStudio [1] to supporting runtime evolution. Butthey differ in many aspects: In contrary to mediums being reusable components, connectorsare built by compilers that analyze interfaces specifications of distributed components thatneed to be connected. Moreover, mediums implement functional collaboration, but connec-tors implement non-functional interaction of distributed components.

6 Conclusion

In this paper, we presented Adapt-Medium, an architecture of adaptive distributed compo-nents. In the architecture, adaptations are realized by performing dynamic compositions ofdistributed components. We introduced a model-based process for 1) specifying architecturevariants of such distributed components and 2) automatically generating adaptation plansthat are performed at runtime to switch running architecture variant. The context includesapplications having distributed functional collaborations. In this class of applications, adap-tations involving distributed processes may affect the collaborations, planning adaptationsis thus a complex task for developers.

In our approach, a distributed application is firstly specified using a collaboration ab-straction called medium. Then we presented a refinement process that transforms this ab-straction into many architecture variants. These architecture variants are then composedinto an adapt-medium that can select a proper running variant and dynamically switchbetween variants in order to adapt to context changes. We proposed to specify adaptationactions within the refinement process, thus automatically generate plans for performingadaptations.

We have automated the refinement process by model transformations [16]. Our futurework includes defining an action meta-model, integrating specifications of transition actionsinto the model-based process, thus validate our approach to automatically generating dis-tributed adaptation plans, reducing development tasks of developers.

Our current architecture does not support continuous availability [1]. An adapt-mediumenables the application using it to move from a consistent architecture to another consistentarchitecture at runtime without loss of data, but during the data transfer, the mediumservices must be stopped. Our ongoing work includes specifying local data as shared objectsbetween manager variants by analyzing common design alternatives of the design decisionmodels. Thus we could replace the Read and Write actions in transitions by rebindingcomponents.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 51

Page 52: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Our future work investigates an integrated tool suite that 1) enables developers to specifydistributed collaborations, 2) automatically generates runtime adaptable collaborations ascomponents, and 3) automatically generates coordination models for executing distributedadaptation processes.

References

1. Oreizy, P., Medvidovic, N., Taylor, R.N.: Architecture-based runtime software evolution. In:ICSE ’98: Proceedings of the 20th international conference on Software engineering, Washing-ton, DC, USA, IEEE Computer Society (1998) 177–186

2. Cheng, B.H.C., et al: Software Engineering for Self-Adaptive Systems: A Research Road Map.(In: Dagstuhl Seminar, http://drops.dagstuhl.de/opus/volltexte/2008/1500/)

3. Cariou, E., Beugnard, A., Jezequel, J.M.: An architecture and a process for implementingdistributed collaborations. In: Proceedings of the 6th IEEE International Enterprise DistributedObject (EDOC 2002), Lausanne, Switzerland, IEEE Computer Society (2002) 132–143

4. Malone, T.W., Crowston, K.: The interdisciplinary study of coordination. ACM ComputingSurveys 26(1) (1994) 87–119

5. Stoica, I., Morris, R., Karger, D., Kaashoek, M.F., Balakrishnan, H.: Chord: A Scalable Peer-to-Peer Lookup Service for Internet Applications. In: ACM SIGCOMM Conference, San Diego(2001)

6. Bamberg University, Distributed System Group: Openchord. http://www.uni-bamberg.de/projects/openchord (2007)

7. Massachusetts Institute of Technology: lsd. http://www.pdos.lcs.mit.edu/chord/ (2004)8. Sykes, D., Heaven, W., Magee, J., Kramer, J.: From goals to components: a combined ap-

proach to self-management. In: SEAMS ’08: Proceedings of the 2008 international workshopon Software engineering for adaptive and self-managing systems, ACM (2008) 1–8

9. David, P.C., Ledoux, T.: Towards a framework for self-adaptive component-based applications.In Stefani, J.B., Demeure, I., Hagimont, D., eds.: Proceedings of Distributed Applications andInteroperable Systems 2003 DAIS2003). Volume 2893 of Lecture Notes in Computer Science.,Paris, Federated Conferences, Springer-Verlag (2003) 1–14

10. Segarra, M.T., Andre, F.: A framework for dynamic adaptation in wireless environments.In: TOOLS ’00: Proceedings of the Technology of Object-Oriented Languages and Systems(TOOLS 33), Washington, DC, USA, IEEE Computer Society (2000) 336

11. Ben-Shaul, I., Holder, O., Lavva, B.: Dynamic adaptation and deployment of distributed com-ponents in hadas. IEEE Trans. Softw. Eng. 27(9) (2001) 769–787

12. Bastide, G., Seriai, A., Oussalah, M.: Adaptation of Monolithic Software Components byTheir Transformation into Composite Configurations Based on Refactoring. In: Proceedings ofThe 9th International ACM SIGSOFT Symposium on Component-Based Software Engineering.Lecture Notes in Computer Science, Springer-Verlag (2006) 368–375

13. Chefrour, D.: Developing component-based adaptive applications in mobile environments. In:SAC ’05: Proceedings of the 2005 ACM symposium on Applied computing, New York, NY,USA, ACM Press (2005) 1146–1150

14. Geihs, K., Khan, M.U., Reichle, R., Solberg, A., Hallsteinsen, S., Merral, S.: Modeling ofcomponent-based adaptive distributed applications. In: Proceedings of the 2006 ACM sympo-sium on Applied Computing (SAC’06), ACM Press (2006) 718–722

15. Shaw, M., Garlan, D.: Software architecture: perspectives on an emerging discipline. Prentice-Hall, Inc., Upper Saddle River, NJ, USA (1996)

16. Phung-Khac, A., Beugnard, A., Gilliot, J.M., Segarra, M.T.: Model-Driven Development ofComponent-based Adaptive Distributed Applications. In: Proceeding of the 23rd ACM Sym-posium on Applied Computing (SAC’2008), track on Dependable and Adaptive DistributedSystems (DADS), Fortaleza, Ceara, Brazil, ACM Press (2008)

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 52

Page 53: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Towards Self-Adaptation in Dynamic ServiceEcosystems

Javier Camara, Carlos Canal, y Gwen Salaun

Department of Computer Science, University of Malaga, Spain{jcamara,canal,salaun}@lcc.uma.es

Resumen. Self-adaptive software systems are those able to manage changing op-erating conditions dynamically and autonomously. Currently, most proposals in thisfield rely on an explicit representation of the components and goals of the system.This approach is suitable for closed systems, where constituent components are wellknown at design time. However, there are many situations in which software systemsare open, and new components or services may dynamically join or leave the contextof the system at any given moment. This results in a lack of a predefined descrip-tion of the system’s architecture and goals. In such open systems, new adaptabilityproblems arise, such as the connection and disconnection of unforeseen componentsto an already running system; interoperability issues among third-party componentsnot specifically designed to interact with each other; and ensuring properties of thecomposition among services, which cannot be addressed at static verification timesince the state space of the system is not closed anymore. In this paper, we presentour approach for the composition and resolution of interface mismatch among servicesin open systems, dynamically reconfiguring the system whenever services are addedto or removed from it.

Palabras clave: Service Composition, Run-time Adaptation, Open Systems, Be-havioural Interface

1 Introduction

The proliferation of software services and ubiquituous computing, as well as other factors,such as the increasing need of communicating systems spanning across both organizationaland physical boundaries, are shaping a panorama where the flow of information and connec-tivity between previously unacquainted systems and devices is desirable –if not necessary.However, in most cases software services are not designed to interoperate with each other,since the different scenarios in which a particular service may be used cannot be envisioneda priori by their designers. The need to discover and access services as users move from onelocation to another and the conditions of the environment change quickly over time, is onecrucial requirement in the design of the system, its constituent components, and also theservices they are accessing and using during their operation. Hence, all these elements mustbe able to achieve a certain degree of adaptation in order to successfully interoperate witheach other.

Software Adaptation [10, 34] provides the abstractions and mechanisms to enable serviceswith mismatching interfaces to interoperate at different levels (i.e., signature, protocol, ser-vice and semantics). Continuous change and short-term association among software entitiesdemand the automation of this adaptation process.

Self-adaptive software systems are those able to manage changing operating conditionsdynamically and autonomously. Currently, most proposals in this field rely on an explicitrepresentation of the components and goals of the system (usually following a top-down

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 53

Page 54: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

approach), or on the definition of local rules for the different elements of the system, whichresults in an emergent self-organizing behaviour (hence following a bottom-up approach).Both these approaches are suitable for closed systems, that is, those whose constituent com-ponents are well known at design time, or where there is no need to explicitly represent thegoals of the system. Industrial control systems, robotics, or autonomous aircrafts are typicaldomains in which software systems are inherently closed, due to their close dependency tohardware parts.

However, there are many situations in which software systems are open, and the changesin their execution environment are directly subject to the availability of a particular service,which may join or leave the context of the system at any given moment. These systemslack a predefined description of its architecture and components, and even of its goals.Paradigmatical examples of such open systems can be found in ubiquitous computing, orin dynamic web service discovery and composition. In such open systems, new adaptabilityproblems arise, such as the connection and disconnection of a new software componentto an already running system; or how to solve interoperability issues among third-partycomponents not specifically designed to interact with each other, just to name a few.

In this paper we present our approach for the composition and resolution of potentialinteroperability issues among services —as those presented above—, dynamically reconfigur-ing the system whenever services are added to or removed from it. Particularly, we focus onthe protocol or behavioral level, currently acknowledged as one of the most relevant researchdirections in software adaptation [2–4, 6, 23, 34]. Mismatch at this level involves undesirablesystem behavior such as deadlock, or incorrect termination states, mainly derived from theorder of the messages exchanged.

The rest of this paper is structured as follows. Section 2 presents our service model,including the definitions of behavioral signatures, (consisting of roles and operations, anddescribed by means of symbolic transition systems) and vectors for stating correspondencesbetween service signatures. Then, Section 3 describes how to achieve self-adaptation ofservice-based systems based on our model, including analysis of stable state reachabilityand a description of the run-time execution platform required. Finally, Section 4 comparesour approach with the related work in the field, and Section 5 recalls the contributions ofthis paper and draws up its conclusions.

2 Model of Services

First of all, we assume the existence of a common language with constructs for describingthe properties and capabilities of services in unambiguous, computer-interpretable form.Specifically, we focus on the description of the different operations available in the differentservice interfaces. We assume that services available in the system’s environment are exposedusing this common language, which will be used as a reference to relate service behaviourusing elements of the specific domain. Instead of using any of the emerging standards forthe semantic description of services, we will use a notation for this common language whichabstracts away specific notations for service descriptions such as OWL-S1 in Web services,or the Rosettanet2 common standards in the case of e-business.

Definition 1 (Role). We define a role as a set of operations associated with a particulartask or goal in the context of a service interface. In the case of a set of abstract operationsassociated with a common task in the context of our common language, we will refer to it asan abstract role.1 http://www.daml.org/services/owl-s/1.0/2 http://www.rosettanet.org/

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 54

Page 55: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Definition 2 (Operation Signature). An Operation Signature is the name of an op-eration, together with its arguments and return types. If the operation signature is definedwithin the context of an abstract role, rather than on a service interface, we will refer to itas an abstract operation signature.

Service interfaces are equipped with both a set of required and provided operationssignatures, and a behavioural interface. The behavioural interface includes: (i) a protocoldescription; (ii) a set of generic correspondences between operations or vectors; and insome cases, (iii) a set of constraints, expressed as temporal formulas, to be satisfied by thecomposition of the service with the rest of the system.

Protocols are represented by means of Symbolic Transition Systems (STSs) [16]. Thisformal model has been chosen because it is simple, and it can be easily derived from existingimplementation platforms’ languages, see for instance [13, 30, 12] where such abstractions forWeb services were used for verification, composition or adaptation purposes. Communicationbetween services is represented using events relative to the emission (denoted using !) andreception (denoted using ?) of messages which correspond to operation calls. Events maycome with a set of data terms whose types respect the operation signatures. In our model, alabel is either the internal action tau or a tuple (M, D, PL) where M is the message name, Dstands for the direction (!,?), and PL is either a list of data terms if the message correspondsto an emission, or a list of variables if the message is a reception.

Definition 3 (STS). An STS is a tuple (A, S, I,B, T ) where: A is an alphabet that corre-sponds to message events relative to the service’s provided and required operations, S is aset of states, I ∈ S is the initial state, B ∈ S are stable states, and T ∈ S × A × S is thetransition function. A stable state is one in which the execution of the service terminatescorrectly.

Furthermore, interfaces contain generic correspondences on how their labels (messages)are related with abstract operation signatures described on abstract roles. To do so, we relyon synchronization vectors [5] (or vector for short), which denotes communication betweendifferent services, where each event appearing in one vector is executed by one service andthe overall result corresponds to an interaction between all the involved services. A vectordoes not require interactions to occur on the same names of events3.

Definition 4 (Vector). A vector for a service STS (A, S, I, B, T ) and an abstract role is acouple 〈el, er〉 where el is a label term for A, and er is an abstract label term for an abstractoperation signature. A label term t contains the name of the operation, a direction, and asmany untyped fresh names as elements in the argument type list. To identify messages in avector, label terms are prefixed by a service identifier. An abstract label term correspondsto an abstract role instead of a service interface, and it is prefixed by its name.

Definition 5 (Vector Instance). A vector instance for a pair of service STSs (Al, Sl, Il, Bl, Tl)and (Ar, Sr, Ir, Br, Tr) is a couple 〈el, er〉 where el, er are label terms in Al and Ar, re-spectively. To identify messages in a vector instance, label terms are prefixed by a serviceidentifier, e.g., 〈s1 :comm!x, s2 :comm?y〉.

Vectors express correspondences between messages, like bindings between ports, or con-nectors, in architectural descriptions [15]. Furthermore, variables are used as placeholdersin message parameters. The same variable name appearing in different labels (possibly indifferent vectors) enables the relation of sent and received arguments of messages. Vectors

3 It is worth noticing that since interactions are expressed using vectors, the interaction semanticsof STS is not used within our model.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 55

Page 56: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

can be either written by hand, obtained from a graphical description of the architecturebuilt by the designer, or automatically generated in some specific cases [24].

Example. In order to illustrate our approach, we describe a running example which consistsof a set of services described within the context of an airport. A traveler walks into the airportcarrying a handheld device with a client containing a task specification based on the differentservices which may be required while staying at the airport. In Figure 1, we can observe thatthe user first needs to checkin! with the airline in order to obtain a seat on the flight. Thisis achieved by approaching a kiosk which provides a local check-in service available to thehandheld device and prints a boarding card for the passenger. Next the user may enter anyof the duty-free shops located at the airport, and locally search! for different items whichcan be purchased (buy!). The different shops are able to access the airport informationsystem, which features a listing service able to check whether a passenger is checked-in on aparticular flight, applying a tax exemption on the sale if this is the case. For space reasons,we describe service interfaces only with their STSs. Signatures will be left implicit, yet theycan be inferred from the typing of arguments (made explicit here) in STS labels.

T A S K S P E C I F I C A T I O N

checkin!

(passport,idflight)

search?(result)

A I R L I N E C H E C K - I N K I O S K

checkin?

(flight,id)checkin!

(seat)

checkin?(seat)

search!(string)

search!string

quit!

buy!(result)

buy?

(success)

A I R P O R T I N F O R M . S Y S T E M

checkedin?

(id,flight)

checkedin!

(result)

D U T Y - F R E E S H O P

search!res

search?(query)

idbuy?(id,f,r)

checkedin!(id,f)

checkedin?(res)

ack!

buy?(r)

ack!

B o a r d i n g p a s s

i s p r i n t e d b y t h e

k i o s k .blueSkyCheck:

checkInPoint

flightList:

flightInfo

bookStore:retailer

Fig. 1. Service protocols for our running example. Initial and stable states are respectively notedin STSs using bullet arrows and darkened states.

Table 1 lists the abstract roles fulfilled by each of the services in our example, along withthe abstract operation signatures they contain. It is worth observing in Figure 1 that eachservice makes explicit the set of abstract roles they fulfill (only one on each service in ourexample). For instance, all check-in kiosks at the airport fulfill the checkInPoint abstractrole. In particular, the kiosk in our example contains a role blueSkyCheck which fulfills theaforementioned abstract role.

Table 2 includes the correspondences between STS labels in each of the services, andabstract operations defined in abstract roles. For instance, vcheckin in the airport informationsystem, establishes that any requests for passenger information passengerInFlight in theabstract role flightInfo, will be received by checkedin in the service protocol.

3 Self-Adaptation with Vectors

In this section, we present our approach to build dynamically a system with services enteringand leaving at run-time (see an overview in Figure 2). Our proposal is completely automated,

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 56

Page 57: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Abstract Role Operation Argument Types Return Val.

checkInPoint checkIn passportId, flightId seatCode

flightInfo passengerInFlight passportId, flightId boolean

retailer search searchString itemId, price

sale itemId boolean

taxFreeSale passportId, flightId, itemId boolean

..

Tabla 1. Abstract role definitions in the airport example.

USER TASK SPECIFICATION (U)

vcheckin = 〈checkin!(pid,fid); checkInPoint.checkIn?(pid,fid)〉vcheckinResponse = 〈checkin?(sid); checkInPoint.checkIn!(sid)〉vsearch = 〈search!(str); retailer.search?(str)〉vsearchResponse = 〈search?(iid); retailer.search!(iid,p)〉

vsale = 〈buy!(iid); retailer.sale?(iid)〉vtaxFreeSale = 〈buy!(iid); retailer.taxFreeSale?(pid,fid,iid)〉vsaleResponse = 〈buy?(r); retailer.sale!(r)〉...

AIRLINE CHECK-IN KIOSK (K)

vcheckinRequest = 〈checkin?(fid,pid); checkInPoint.checkIn!(pid,fid)〉vcheckinResponse = 〈checkin!(sid); checkInPoint.checkIn?(sid)〉AIRPORT INFORMATION SYSTEM (F)

vinfoRequest = 〈checkedin?(pid,fid); flightInfo.passengerInFlight!(pid,fid)〉vinfoResponse = 〈checkedin!(sid); flightInfo.passengerInFlight?(sid)〉DUTY-FREE SHOP (S)

vsearch = 〈search?(s); retailer.search!(s)〉vsearchResponse = 〈search!(r); retailer.search?(r,p)〉vpurchase = 〈buy?(iid); retailer.purchase!(iid)〉vtaxFreePurchase = 〈idbuy?(pid,fid,iid); retailer.taxFreeSale?(pid,fid,iid)〉vcheckin = 〈hascheckedin!(pid,fid); flightInfo.passengerInFlight?(pid,fid)〉vcheckinResponse = 〈hascheckedin?(sid); flightInfo.passengerInFlight!(sid)〉vack = 〈ack!; retailer.taxFreeSale?(r)〉vtaxFreeAck = 〈ack!; retailer.sale?(r)〉

Tabla 2. Service vector definitions for the airport example.

and guided by a user requirements description. Three main tasks have to be fulfilled everytime a new entity appears or leaves: (i) instantiation of vectors, (ii) checking stable statesreachability, (iii) run-time execution of involved services. Note that reachability of globalstable states conditions (point (ii) above) the execution launching, and is also used at run-time to execute only interactions for which such (global stable) states exist.

3.1 Vector Instantiation

In this section, we describe how a set of vectors from several service interfaces are instantiatedby using abstract operation signatures. For each vector v, we extract all the other vectorsincluding abstract label terms corresponding to the same abstract operation signatures.A vector is instantiated as many times as there are possible combinations wrt. the set ofavailable vectors.

More concretely, an instantiation of v is obtained in two steps: (i) finding a set of match-ing vectors Vm (sharing abstract label terms with v, although with opposite direction incommunication), and (ii) aggregating in a new set of vector instances Vinst the non-abstract

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 57

Page 58: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

U s e r R e q u i r e m e n t s

Y e l l o w P a g e s

S e r v i c e s

A d d / R e m o v e S e r v i c e I n s t a n t i a t e V e c t o r s

O p e r a t i o n P r o f i l e s

S t a b l e S t a t e s R e a c h a b i l i t y

V a l i d a t i o n

E x e c u t i o n

S t o p E x e c u t i o n

( s t a b l e s t a t e s c o n f i g u r a t i o n )

Fig. 2. Overview of our approach

label term of v with all the non-abstract label terms appearing in each of the vectors in Vm.The algorithm keeps track on already instantiated vectors to avoid repeating instantiations.

Example. We consider a scenario in our running example where the user enters the airportand walks into the check-in area. Once there, the airline check-in kiosk service becomesavailable, and vectors both on the user task specification and the check-in service interfacemust be used in order to instantiate the vectors which will make the interaction of bothpartners possible. As it can be observed in Table 2, the only abstract label terms shared byboth partners correspond to checkInPoint.checkIn:

USER TASK SPECIFICATIONvcheckin = 〈checkin!(pid,fid); checkInPoint.checkIn?(pid,fid)〉vcheckinResponse = 〈checkin?(sid); checkInPoint.checkIn!(sid)〉...AIRLINE CHECK-IN KIOSKvcheckinRequest = 〈checkin?(fid,pid); checkInPoint.checkIn!(pid,fid)〉vcheckinResponse = 〈checkin!(sid); passenger.checkIn?(sid)〉VECTOR INSTANCESvinsta = 〈u:checkin!(p,f); k:checkin?(f,p)〉vinstb = 〈u:checkin?(s); k:checkin!(s)〉

As it can be observed above, each vector instance includes a set of STS label termsprefixed by an identifier of the service. In this case, vcheckin on the task specification hasbeen matched with vcheckinRequest on the kiosk, resulting on vinsta. Vector instance namesare not relevant, since they are only used for run-time execution of the system. It is worthnoticing that fresh names p,f, and s are used as placeholders for parameter values. Thesenames are placed in the vector instance taking as reference the order of parameters in theshared abstract label term. Notice the inverted order of these names in the different labelterms of vinsta.

3.2 Stable State Reachability

Once we have described interfaces and the process of vector instantiation, in this section wesketch two solutions to compute the reachability analysis of stable states being given a setof service protocols, and a set of instantiated vectors. A stable state of the system is one,where each of the services in the system is on a stable state. It is only at this point thatservices can be incorporated or removed, and the system properly reconfigured.

A first solution is an ad-hoc search algorithm. In [8], we presented a depth-first searchalgorithm which seeks correct termination states, and stops as soon as a final state for the

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 58

Page 59: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

whole system has been found. The main idea is that vectors belonging to the compositionspecification are applied going in depth until either a final state is reached (end of thealgorithm), or a deadlock state is found. In the latter case, the algorithm backtracks andtries a different path. We keep track of the already traversed states and use Floyd’s cycle-finding algorithm [20]4 in order to avoid reach already visited states and remain indefinitelyin cyclic paths. This solution is appropriate for systems of a moderate size (see [8] for details).

However, in the context of pervasive systems where a large number of services have tointeract or feature protocols with a large number of states and transitions, a second solutionis to use an informed search algorithm in order to find potential solutions efficiently. In [9]we presented a best-first search strategy which determines the mimimum cost path from agiven state of the system to a global stble state by expanding the most promising candidatepaths first.

3.3 Run-time Execution

Once vectors instantiated and validation achieved to be sure that the system can be runand will reach a correct termination state (global stability), execution of the system can belaunched. In this section, we present a run-time engine that executes a system involving a setof services using vectors as their interaction constraints. We promote a dynamic executionof vectors instead of the execution of an adaptor generated statically from vectors, becauseadaptor generation is costly and algorithms are exponential [11, 28].

The application of the composition specification (vectors) can lead the system constitutedof the involved services into deadlocking situations. This can be caused by a missing service,a missing interaction, or a possible execution scenario that makes the system fail. Indeed,the composition specification is an abstract description of how services work together, anddoes not take into account all the possible execution scenarios of the system. Removing theseremaining spurious interactions is required to let the system reach a final state.

Since the composition specification is applied at run-time, it is not possible to applythe removal of deadlocks as a pre-processing as it is the case in static composition andadaptation approaches [17, 25]. Therefore, before applying a vector which belongs to thecomposition specification, we check that after the application of this vector, there exists atleast one reachable stable state for the whole system (i.e., all services and the compositionspecification are in a final state). Thus, our dynamic composition engine will prevent thesystem to end up in deadlocking situations, and will run only interactions that will makethe system terminate. This check is achieved using techniques presented in Section 3.2.

We sketch in Figure 3 the main steps on which rely the dynamic composition engine.More details about that and ideas of how these techniques can be implemented in practiceusing Dynamic-AOP (Aspect-Oriented Programming) can be found in [8].

Example. The passenger walks into the airport and reaches the check-in kiosk. At thispoint vectors for the handheld device client and the kiosk check-in service are instanced. InFigure 4 we can observe how the check-in process is executed (vinsta,vinstb) and the systemreaches a stable state. At this point, services can be added to or removed from the system.The user walks towards the shopping area and enters a duty free shop. The check-in serviceis no longer accessible, but the shop’s service (connected to the airport information system)becomes available. The vector instantiation process is performed again. It is worth noticingthat this time no vectors for non-tax free sales are instanced, since the user task specificationon the client does not contain any vector definitions for that kind of transaction. The usersearchs the catalog (one or more times) for products (vinstc,vinstd), and then performs a

4 Floyd never published his cycle-finding algorithm. It was first presented by Knuth in the refer-enced book.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 59

Page 60: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

select applicable vector v

interact ions withservice emissions

interact ions withservice receptions

stablestates?

false

true

execution of vector v

Fig. 3. Dynamic Composition Engine Overview

purchase(vinste). The shop contacts the airport information system to confirm that thepassenger is checked-in on a flight (vinstf ,vinstg), and then acknowledges the end of thetransaction (vinsth). u:checkin ! vinstcvinsta vinstbvinsta = <u:checkin!(p,f); k:checkin?(f,p)>vinstb = <u:checkin ?(s); k:checkin !(s)> k:checkin ? u:checkin ?k:checkin !(USER, KIOSK)vinstc = <u:search!(s); s:search ?(s)>vinstd = <u:search?(r); s:search !(r)>vinste = <s:hascheckedin !(p,f); f:checkedin ?(p,f)>vinstf = <f:checkedin !(sid); s:hascheckedin ?(sid)>vinstg = <u:buy!(r); s:idbuy ?(p,f,r)>vinsth = <u:buy?(res); s:ack!>

u:search!s:search?(USER,SHOP,INFO.SYSTEM) vinstdu:search?s:search!vinstevinstfvinstgvinsth s:hascheckedin !f:checkedin ?f:checkedin !s:hascheckedin ?u:buy!s:idbuy ?u:buy?s:ack! vinstcFig. 4. Execution trace of the airport example.

4 Related Work

In this section, we will compare successively our approach with some proposals in relatedareas, namely software adaptation, dynamic reconfiguration of software, and self-adaptivesystems.

Software adaptation is a promising topic in software composition. Indeed, compositionassumes that components will successfully interact when combined, whereas most of thecomponents reused out of their original context cannot be integrated as is, requiring somedegree of adaptation. Many proposals [31, 17, 6, 7, 11] in this area focus on the behaviouralinteroperability level, and advocate abstract notations (e.g., correspondences between mes-sages, vector regular expressions, or LTL formulae) and state-of-art algorithms to deriveadaptor protocols. However, all these approaches assume that all the components involvedin the system are known at design-time, and no new entity can be added or removed dy-namically. A recent work aims at building adaptors incrementally [29]. The authors presenta description of open component systems. Thus, software components distinguish in theirdescription internal and external bindings, the latter ones being used for further connections

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 60

Page 61: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

with components or services to be added in the future. Moreover, they propose an incremen-tal process for the integration and adaptation of open software components, enabling theconstruction of systems step-by-step (by adding or removing components), and to reconfig-ure them if necessary. Here, this incremental construction of the system-to-be takes place atdesign-time or off-line.

Dynamic reconfiguration [27] is not a new topic and many solutions have already beenproposed dealing with distributed systems and software architectures [21, 22], graph trans-formation [1, 33] or metamodelling [19, 26]. For instance, Kramer and Magee [22] studied howchanges are applied dynamically to system composed of components and their interconnec-tions. To preserve the integrity of the system, they propose a notion of quiescent portionsduring which changes can be performed. Analysis techniques (animation and reachability)are used in this approach to check that changes do not violate properties to be ensured bythe system. In our proposal, we do not allow the modification of the components at hand,but permit to add and remove them at run-time. In addition, we assume the architecturenot defined by the designer but inferred automatically from the service interfaces. However,the notion of stable states we defined in this paper is very similar to the quiescent portionsintroduced in [22].

Self-adaptive systems and self-adaptation are emerging and very promising topics for sys-tems running in dynamically changing environments. Several recent proposals tackle differentissues in this area, such as software architecture self-adaptation [32], service replacement atrun-time [18], or adaptive systems modelling issues [14]. In [32] for instance, the authorspropose using planning techniques to build new configurations of a system. Reactive plansare generated with a planning tool from high-level goals given by the user. Each plan definesa set of conditional rules that indicate what components are required to execute the plan.Our solution based on vectors can be considered as an alternative to use planning techniques.The main difference is that this approach requires pre-defined global goal given by a designerwhereas in our proposal such goals are dynamically determined by service interfaces.

5 Concluding Remarks

In this paper, we have presented our proposal to self-adaptation of services specified withrich interfaces (protocols and vectors). The high expressiveness of service interfaces allowto completely automate the reconfiguration of the system at run-time (removal or arrival ofnew services). We have explained in this paper how the various steps of our approach apply,and how correctness of the execution is ensured by using stable state reachability evaluationat run-time. We have illustrated these ideas on a real-world example.

As far as future works are concerned, our main goal is to extend our ITACA toolbox5 toextend our model of service interfaces with abstract vectors and temporal formulas statingspecific service goals for their composition, implement techniques to instantiate vectors froma set of interfaces, and implement an execution engine that would apply instantiated vectorswhile ensuring stable state reachability and formula validity.

Acknowledgements. This work has been partially supported by the CAReSS project(TIN2007-67134), funded by the Spanish Ministry of Innovation and Science, and projectP06-TIC-02250 funded by the Andalusian local Government.5 ITACA is a toolbox we are implementing at the University of Malaga dedicated to the automatic

composition and adaptation of services accessed through their behavioural interfaces.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 61

Page 62: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Referencias

1. N. Aguirre and T. Maibaum. A Logical Basis for the Specification of Reconfigurable Component-Based Systems. In Proc. of FASE’03, volume 2621 of LNCS, pages 37–51. Springer, 2003.

2. L. Alfaro and T.A. Henzinger. Interface Automata. In Proc. of ESEC/FSE’01, pages 109–120.ACM Press, 2001.

3. T. Andrews et al. Business Process Execution Language for Web Services (WSBPEL). BEASystems, IBM, Microsoft, SAP AG, and Siebel Systems, Feb. 2005.

4. F. Arbab., F. S. de Boer, M. M. Bonsangue, and J. V. Guillen Scholten. A Channel-basedCoordination Model for Components. In Proc. of FOCLASA’02, volume 68(3) of ENTCS,2002.

5. A. Arnold. Finite Transition Systems. International Series in Computer Science. Prentice-Hall,1994.

6. A. Bracciali, A. Brogi, and C. Canal. A Formal Approach to Component Adaptation. Journalof Systems and Software, 74(1):45–54, 2005.

7. A. Brogi, C. Canal, and E. Pimentel. Component Adaptation Through Flexible Subservicing.Science of Computer Programming, 63(1):39–56, 2006.

8. J. Camara, G. Salaun, and C. Canal. Composition and Run-time Adaptation of MismatchingBehavioural Interfaces. Journal of Universal Computer Science, 2008. To appear.

9. Javier Camara, Gwen Salaun, and Carlos Canal. Multiple concern adaptation for run-timecomposition in context-aware systems. In Proceedings of the 4th International Workshop onFormal Aspects of Component Software (FACS’07), volume 215 of Electronic Notes in Theoret-ical Computer Science, pages 111–130. Elsevier, 2008.

10. C. Canal, J.M. Murillo, and P. Poizat. Software Adaptation. L’Objet, 12(1), 2006. Special Issueon WCAT’04.

11. C. Canal, P. Poizat, and G. Salaun. Synchronizing Behavioural Mismatch in Software Compo-sition. In Proc. of FMOODS’06, LNCS 4037. Springer.

12. H. Foster, S. Uchitel, and J. Kramer. LTSA-WS: A Tool for Model-based Verification of WebService Compositions and Choreography. In Proc. of ICSE’06, pages 771–774. ACM Press,2006.

13. X. Fu, T. Bultan, and J. Su. Analysis of Interacting BPEL Web Services. In Proc. of WWW’04,pages 621–630. ACM Press, 2004.

14. H. Goldsby, P. Sawyer, N. Bencomo, B. H. C. Cheng, and D. Hughes. Goal-Based Modelingof Dynamically Adaptive System Requirements. In Proc. of ECBS’08, pages 36–45. IEEEComputer Society, 2008.

15. S. Haddad and P. Poizat. Transactional Reduction of Component Compositions. In Proc. ofFORTE’07, volume 4574 of LNCS, pages 341–357. Springer, 2007.

16. A. Ingolfsdottir and H. Lin. A Symbolic Approach to Value-passing Processes, pages 427–478.Handbook of Process Algebra. Elsevier, 2001.

17. P. Inverardi and M. Tivoli. Deadlock Free Software Architectures for COM/DCOM Applica-tions. Journal of Systems and Software, 65(3):173–183, 2003.

18. F. Irmert, T. Fischer, and K. Meyer-Wegener. Runtime Adaptation in a Service-OrientedComponent Model. In Proc. of SEAMS’08 (held with ICSE’08). ACM Press, 2008.

19. A. Ketfi and N. Belkhatir. A Metamodel-Based Approach for the Dynamic Reconfigurationof Component-Based Software. In Proc. of ICSR’04, volume 3107 of LNCS, pages 264–273.Springer, 2004.

20. D. E. Knuth. The Art of Computer Programming, Volume II: Seminumerical Algorithms.Addison-Wesley, 1969.

21. J. Kramer and J. Magee. The Evolving Philosophers Problem: Dynamic Change Management.IEEE Transactions on Software Engineering, 16(11):1293–1306, 1990.

22. J. Kramer and J. Magee. Analysing Dynamic Change in Distributed Software Architectures.IEE Proceedings - Software, 145(5):146–154, 1998.

23. J. Magee, J. Kramer, and D. Giannakopoulou. Behaviour Analysis of Software Architectures,pages 35–49. Kluwer Academic Publishers, 1999.

24. J.A. Martın and E. Pimentel. Automatic Generation of Adaptation Contracts. In Proc. ofFOCLASA’08, ENTCS, 2008. To appear.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 62

Page 63: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

25. R. Mateescu, P. Poizat, and G. Salaun. Behavioral Adaptation of Component Compositionsbased on Process Algebra Encodings. In Proc. of ASE’07. IEEE Computer Society, 2007.

26. J. Matevska-Meyer, W. Hasselbring, and R. Reussner. Software Architecture Description Sup-porting Component Deployment and System Runtime Reconfiguration. In Proc. of WCOP’04,2004.

27. N. Medvidovic. ADLs and Dynamic Architecture Changes. In SIGSOFT 96 Workshop, pages24–27. ACM Press, 1996.

28. P. Poizat and G. Salaun. Adaptation of Open Component-based Systems. In Proc. of the 9thIFIP International Conference on Formal Methods for Open Object-Based Distributed Systems(FMOODS’07), volume 4468 of LNCS, pages 141–156. Springer, 2007.

29. P. Poizat and G. Salaun. Adaptation of Open Component-based Systems. In Proc. ofFMOODS’07, volume 4468 of LNCS. Springer, 2007.

30. G. Salaun, L. Bordeaux, and M. Schaerf. Describing and Reasoning on Web Services us-ing Process Algebra. International Journal of Business Process Integration and Management,1(2):116–128, 2006.

31. H. W. Schmidt and R. H. Reussner. Generating Adapters for Concurrent Component ProtocolSynchronization. In Proc. of FMOODS’02. Kluwer.

32. D. Sykes, W. Heaven, J. Magee, and J. Kramer. Plan-Directed Architectural Change for Au-tonomous Systems. In Proc. of SAVCBS’07 (held with FSE’07). ACM Press, 2007.

33. M. Wermelinger, A. Lopes, and J. L. Fiadeiro. A Graph Based Architectural (Re)configurationLanguage. In Proc. of ESEC / SIGSOFT FSE 2001, pages 21–32. ACM Press, 2001.

34. D. M. Yellin and R. E. Strom. Protocol Specifications and Components Adaptors. ACMTransactions on Programming Languages and Systems, 19(2):292–333, 1997.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 63

Page 64: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Supporting Context-Awareness in

Adaptive Service Composition

Javier Cubo, Carlos Canal, and Ernesto Pimentel

Department of Computer Science, University of MalagaCampus de Teatinos, 29071, Malaga, Spain

{cubo,canal,ernesto}@lcc.uma.es

Abstract. Context-awareness features involve that the adaptive service compositionhas to take dependencies of contexts into account. In any other case, such compositionmay reach inconsistent states. Therefore, we need to manage not only the explicitcontexts given by the user as parameters, but also the implicit context information. Weobtain such implicit contexts from the message of the user, making more independentour system, since the user does not have to provide such information. We proposeto extend the STS model including those context-awareness features. In addition, weneed to verify that the adaptive service composition is free of inconsistence problemsby controlling the context changes depending on the conditions, user preferences,services capabilities or type of device used by the user.

Keywords: Context-Awareness, Adaptive Service, Components, Composition, Model-Based Methodologies, Pervasive Computing.

1 Introduction

Adaptive service composition is emerging as a technology that allows the integration betweenpre-existing software entities (components and Web services; in the sequel we use services torefer both components and Web services). These services are equipped with external inter-faces giving information about their functionality, due to their black-box nature. However,it is frequent to find out interaction problems when we compose pre-existing services, so isrequired a process of adaptation in order to avoid these mismatching behaviours. They isdue to that the interfaces of the constituent components of a system do not always fit oneanother.

Context-aware computing focus on building adaptive systems sensitive to their context(location, identity, time and activity) [10].

The increasing using of mobile and portable devices is giving rise to a new market of mo-bile and pervasive applications. Context-aware computing is incorporated into these systems,with the inclusion of certain context-awareness features. So they are different from tradi-tional distributed applications, since a mobile system is able to change location allowing thecommunication via mobile devices with some limitations which need to be resolved (connec-tivity, bandwidth, local resources, etc.). Due to the contextual nature of these systems, it isimportant the improvement from the user experience, as well as to provide connectivity andservices all the time, by being capable of adapting the composition with respect to changesin context. In such a way, the possible inconsistence situations generated in these systemscould be avoided.

Our work aims to develop software adaptors capable of acting as a third-party componentbetween the services to interoperate taking their contexts into account. We make use of amodel-based methodology [35] to avoid mismatching behaviours, and we plan use validationtechniques to solve inconsistences or faults. Therefore, this paper focuses on extend the

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 64

Page 65: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

concept of software adaptors [5, 7] by modeling explicitly context dependencies of alreadyexisting services, and using them in the component composition.

In case we reuse services without taking the contexts into account, then some inconsistentstates will be achieved due to the contextual nature of the mobile and pervasive systems,and the service composition will not be correct. However, our model pretend to formalisethe context-awareness features in these systems, which will allow us to detect and avoidmismatching behaviours, as well as faults or inconsistencies.

An overview of our proposal is presented in Figure 1. Firstly, different kinds of user,using different devices, request one or more services. We get (implicit) context informationfrom the message. This info can be such as user language, type of device, user preferences,and so on. We should have this information without asking the user for it. In such a way, forinstance, the user could travel with his/her own laptop and request services by obtaining theresult in his/her language, currency, and so on, independently his/her location. Even the wayto show the result could change depending on if the user is using a laptop or a cell-phone. Adiscovery process finds the pre-existing services (in our research work we use services imple-mented using WF or BPEL; see Section 2), and the service descriptions (AWF/ABPEL) areabstracted to obtain the behavioural service model (CA-STS is an extension, presented inSection 4.1, of Symbolic Transition Systems, STSs [18]). Next, being given a set of CA-STSs,mismatch detection is computed to check whether the services involved need adaptation ornot. If a mismatch exists, we apply adaptation techniques that aim at generating a CA-STS adaptor model from a contextual mapping. Validation techniques are then helpful tocheck that the adaptor is as expected by preventing inconsistences or faults. If not, anothermapping may be proposed. Finally, once the adaptor passes the test, the corresponding ab-stract adaptor service (AWF/ABPEL) is generated making use of a formal model. Last, thedeveloper can complete this adaptor service (WF/BPEL) by including the abstracted in-formation previously. So we generate an intermediate piece to make possible the contextualcomposition and adaptation of those services requested by the user.

The remainder of the paper is organised as follows. Firstly, in Section 2, is presented abackground to adaptive service composition, context-aware computing and validation tech-niques, and is discussed about some related works. Section 3 briefly presents a motivatingscenario of a rent-a-car system, by illustrating the need to generate a transformation modelcapable of adapting components and services requested in a context-aware application. InSection 4, we present the proposal introducing our behavioural model, as well as describingbriefly the contextual composition. Finally, Section 5 concludes this paper with a summaryand a discussion about the improvements getting using this new model in the context-awareapplications, as well as a plan for future work.

2 Background

Most of the current systems are developed as a selection, adaptation and composition ofpre-existing components and services rather than as a programming of applications fromscratch. The use of Commercial-Off-The-Shelf (COTS) components and services is promotedby Component-Based Software Engineering (CBSE) [32] and Service-Oriented Architecture(SOA) [11, 22] respectively. They require a certain degree of adaptation in order to avoidmismatching behaviours, since the interfaces of the constituent components of a system donot always fit one another.

This adaptation is performed by adaptors which are automatically built from an abstractdescription (i.e. adaptation mapping) of how the mismatch can be solved with respect to thecomponent behavioural interfaces. Software Adaptation (SA) [5] focuses on the automationof the adaptation process, by enabling components with mismatching behaviours to inter-operate. It supports run-time features that occur as devices and applications move from

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 65

Page 66: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Fig. 1. Context-Aware Adaptive Service Composition Model

network to network, modifying or extending their behaviour, and enhancing the flexibilityand maintainability of systems.

Mismatch among services can be presented at four different levels: signature, behavioural,service and semantic levels [8]. The most common mismatches occur at the behaviourallevel. It is due to an incompatibility in the order of the exchanged messages among services,which can lead to deadlock situations. But industrial platforms only deal suitably withthe signature level (e.g. CORBA’s IDL [28]). In addition, the nature of pervasive systemsproduces inconsistent situations, which must be dealt.

Our proposal focuses on the behavioural interoperability level, extending interfaces witha description of their protocol and dealing with the different compositional issues betweenthem taking context-dependencies into account. Windows Workflow Foundation (WF) [30]which belongs to .NET Framework 3.5 and is supported by Visual Studio 2008, as wellas BPEL [1] and Netbeans Enterprise, are using to relate our transformation contextualmodel with realistic and complex examples. Theirs workflow-based graphical support andthe automation of the code generation make the implementation of services easier. Besides,they have capabilities for developing workflows in different scenarios, from simple sequentialworkflows to realistic and complex workflows with human interactions. It has been demon-strated that services implemented on existing platforms can be modeled using our behavioralformal model [13, 14].

There exist different approaches tackling model-based adaptation at the behaviouralinteroperability level, and aim at generating adaptors which are used to solve mismatch in anon-intrusive way. However, only a few of them have been carried out using some particularplatform [2, 4, 17, 19, 25].

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 66

Page 67: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Bastide et al. [2] show that the OMG’s style to specify services in CORBA does not guar-antee interoperable and substitutable implementations. Gaspari and Zavattaro [17] illustratehow CORBA models for requesting invocation can be mapped into a message passing archi-tecture using the base of a process algebra.

The work presented by Brogi and Popescu [4] outlines a methodology for the automatedgeneration of adaptors capable of solving behavioural mismatches between BPEL processes.They use YAWL workflow [33] as an intermediate language, and once the adaptor workflow isgenerated, they use lock analysis techniques to check if a full adaptor has been generated oronly a partial one (some interaction scenarios cannot be resolved). Our adaptation approachmay reorder messages in between services when required [8]. This ability is needed to ensurea correct interaction when communicating entities have messages which are not ordered asrequired.

Inverardi and Tivoli [19] tackle the automatic synthesis of connectors in COM/DCOMenvironments, by guaranteeing deadlock-free interactions among components. Compared tothis proposal, we may match different name messages using our correspondences, whichis very useful within context-aware systems. In addition, this approach does not use anymapping language for the adaptor specification, so restrict the adaptor to possible non-deadlocking.

Finally, Benatallah et al. [25] present techniques, as well as a tool providing semi-automated support for identification and resolution of mismatches between service inter-faces and protocols, and generate adaptation behavioural specifications. They deal withdata, and base on SCA architecture implementing the services and the generated adapteras SCA components.

In general, respect to the aforementioned works, we focus on modeling the behaviouralcomposition, not only preventing mismatch problems, but also taking into account depen-dencies of contexts in order to control states of inconsistence.

On the other hand, recently, some works are researching about context-aware comput-ing, as well as built pervasive applications [24, 26, 27] to demonstrate the usefulness of thistechnology. There have even been significant achievements in the architectural support ofcontext-aware applications [6, 29]. However, at the behavioural level, the composition andadaptation of software entities within the context-aware pervasive systems has only brieflybeen dealt within some of these works.

We focus on a formal model that transforms services (implemented in specific platforms)in a standard notation (CA-STS) to be able to compose and adapt them when required. Inthis sense, we use the Software Adaptation approach, which reuses services and tackles theinteroperability issues which exist at the different levels of component interaction.

Related to our motivating scenario (presented in Section 3), in [31] the authors havedesigned and implemented a Tourist Guide system that is mobile and context sensitive.However, they focus on the design and usability issues, and not about service composition.

Last, different works propose validation techniques in the service composition field [12,15, 16, 36]. Even, some of them use semantic ontology languages to compose the services.However, any of them tackle the context-aware composition.

Kim and Choi [20] suggest a context infrastructure to provide semantic interoperabilityin a ubiquitous computing environment. They only evaluate the performance of the contextinfrastructure, not controlling possible inconsistent situations nor faults. With our proposalwe are planning to solve these problems by providing context dependencies.

A model to compose services and validate theirs correctness using Petri nets is presentedby Luo et al. [21]. They check behavioral properties based on simulation of the model.Compared to our idea, we model the service composition with a strategy by means of CA-STS that may be easily validated. In addition, their model currently doesn’t control thechanges of contexts at run-time.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 67

Page 68: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Vukovic presents in [34] a complete approach focus on the recomposition of the compositeservice during its execution, according to changes in the context. This proposal provides afailure-tolerant solution. But it has still some limitations about the control of user prefer-ences, as well as the control of independent requests, which we pretend to support using ourmodel.

3 Motivation

This section introduces a scenario illustrating realistic and complex problems used in thereal-world by end-users, whose purpose is to give information requested by the client bytaking into account context information likely changing without intervention of the user.These daily life applications may give rise to inconsistent behaviours. So these problemshave motivated our research in this field and in this work we propose a model (Section 4)to solve problems emerged in those systems.

We present a rent-a-car system that consists of services giving information to the userabout different cars to be rented, depending on the user preferences, as well as the conditionsof the environment where the user is requesting the services, and the capabilities of theservices and device used by the user. These conditions will make the system contexts change,so our model should be able to control possible inconsistence problems generated by thewrong interpretations of the contexts.

Multiple contextual information is used in real world services to improve their features.In our simple scenario, a user is requesting information about renting a car and the serviceshave to give the response by using explicit and implicit contextual information. Ideallya response should include details of car rental companies closest to the user and use theuser preferences, not only using the explicit parameters given by the user (model of car,renting duration or authentication), but also capturing implicit context information (typeof device, location, language or currency) to obtain explicit data through it and know whenthe composition has to change.

Therefore, our goal consist of modeling these systems to make easier the interactionbetween user and services, but maintaining the features of the context-aware systems. Soa user could request a service giving only some common parameters called explicit contextinformation. Thus, the services will have to control the implicit context information using anadaptor service modeled in CA-STS. Our previous proposal [7] tackles only explicit contextinformation given by parameters, but here we pretend to infer implicit context dependenciesfrom requesting message of the user.

Real services of pervasive applications can be aware of some context information, but inaddition, they can support this information in different ways. So we need to extend the notionof a third-party connector with context-awareness features. In such a way our contextualadaptor could give the most suitable and consistent responses depending on both contextand possibilities of interconnected services.

Returning to our scenario, between the services that constitutes it, we can find a cardescription service composed by an explanation about each car, as well as a picture andthe price for each one. In addition, there exists a car rental location service, which indicateswhere is the nearest car rental center, by means of a street plan or simply textual indicationaccording to the device used for the requesting.

If the user is traveling and requests a car in a country different to his/her country, weshould control possible inconsistence problems due to different ways of interpretation of thecontext information. Each service should use the context information to generate a suitableresponse according to theirs features.

For instance, the car description service will use the language and currency of the userto generate a response, and the location service will use the user location information to

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 68

Page 69: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

localise the nearest center. But if the user language, captured as a implicit context, is notsupported by our description service, then this service will have to return the explanationin a default language defined. In addition, this service should show the price using thecurrency corresponding to the user’s country. The currency forms part of the implicit contextinformation. On the other hand, the location service will respond by using the language ofthe user’s location, which is different to the default one and to the language of the countrywhere is being requested the service. This service is going to show the result in differentways depending on the device. So at the same time in the service composition is needed totake into account different values related to a context, depending on the conditions, the userpreferences, and the features of the services and device.

In Section 4, we present briefly our model where we add context-awareness features tothe STS model trying to solve the problems expose here, and sketch the steps to perform inthe adaptive service composition.

4 Model based on Context-Awareness

Here we describe our approach to compose services depending on the explicit and implicitcontexts. Services are equipped with external interfaces (signature and behaviour), givinginformation about their functionality. We represent the behaviour of the services by means ofa Symbolic Transition System (STSs) [18], which provides an expressive and graphical nota-tion to specify adaptation policies. Any formalism to describe dynamic contextual behaviourmay be expressed in terms of an standard notation like STS.

We propose an extension of STS, called Context-Aware Symbolic Transition System (CA-STS), to support context-awareness features.

4.1 Adding Context-Awareness to STSs

A Context-Aware Symbolic Transition System (CA-STS) is a tuple (A,S , I ,F ,C ,T ) where:A is an alphabet (set of messages), S ⊆ Id is a set of states (Id stands for a set of identifiers),I ∈ S is the initial state, F ⊆ S are final states, C is a set of conditions depending on thecontext, and T ⊆ S × A × S is the transition function.

In our model, a label corresponding to a transition of a CA-STS, is either the internalaction (tau) or a tuple (SI ,M ,C ,D ,PL,CL) where: SI is a service identifier, M is themessage name, C are the conditions of the message, D stands for the direction of messages(! and ? represent emission and reception respectively), PL is either a list of data terms foremissions, or a list of variables for receptions, both of them given explicitly (it can includeexplicit contexts), and CL is a list of implicit contexts obtained from the message, and whichwill be had as information making such contexts explicit.

Events relative to the emission and reception of messages represent the service composi-tion. They may come with a set of data terms whose types respect the operation signatures,as well as conditions depending on which context the system is in.

We assume the services of our motivating scenario presented in Section 3 have beenimplemented on existing platforms, such as WF or BPEL, and apply our model on theseservices by obtaining the corresponding CA-STSs. In Figure 2 we depict our scenario toa general list of parameters, conditions and implicit contexts, and receiving as result thedescription of the cars (description) as well as the location of the nearest center to rentsome of those cars (location).

Specifically, params indicates the parameters as well as the explicit contexts; context info

is the implicit context obtained from the message; conditions are the conditions of themessage; and context params are the contextual parameters returned as result dependingon the conditions, the user preferences (context information) and the capabilities of the

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 69

Page 70: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Client

c : rentACar !( params )( context _ info )

c : infoRentACar ? ( description , location )

d , l : getRentACar .( conditions ) ? ( params )( context _ info )

d , l : sendRentACarDescription / Location .( conditions )!( context _ params )

Description & Location Services

Fig. 2. CA-STS for the motivating example of renting a car

services and device used by the user. Note we only use one CA-STS representation to showboth description and location services, since we are representing our scenario in a generalcase without going into any further details respect to the parameters, conditions or implicitcontext information for each one.

4.2 Context-Aware Service Composition

This section describes briefly the process of our approach to define correspondences in be-tween service messages of a system taking contextual information into account. To completeour approach, we explain the generation of an adaptor protocol which will work as an inter-mediate piece connecting services.

When there exist services which cannot be directly used together due to mismatchingproblems, a mapping or contract have to be given to work the cases of mismatch out. Ourcontract is called contextual mapping, and it is made up of several constituents as is explainedin [8], besides of including the implicit context information in the mapping.

We generate a CA-STS adaptor model from the descriptions of service interfaces (CA-STSs behavioural models) and the contract. The adaptor acts as a third-party componentthat is in charge of coordinating all the services involved in the system with respect to a setof correspondences defined in the contract. To obtain the adaptor we will use an extensionwith value-passing protocols of the algorithm presented in [23], and using this new modelwe need to control the implicit contexts.

Once we have generated the adaptor model (CA-STS adaptor model), we need to ap-ply validation techniques. We are working on checking our composition model to prove theusefulness of supporting context dependencies in adaptive service composition. As we havealready mentioned, the incorporation of context-awareness features gives rise to inconsis-tence situations. These situations have to be controlled by performing validation respect toproperties such as determinism, deadlock or liveliness.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 70

Page 71: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

Finally, if our adaptor model is validated correctly, then we have to generate an abstractadaptor following the guidelines presented in [9]. Otherwise, we will need to generate otheradaptor model, using a different contextual mapping. The final abstract adaptor has to berefined, by requiring intervention of the designer, to add the information that was initiallyabstracted.

5 Conclusion and Future Work

This work presents a proposal to model adaptive service composition taking into accountcontext-awareness features. The main improvement respect to our previous work [7] consistsof inferring the implicit context dependencies from the user’s requesting message. To do thatwe need to extend the STS model making using of such implicit context information.

We have described the problem of modeling composition of context-aware pervasive sys-tems without taking the context-dependencies into account. Thus, in such a case, the servicecomposition of those systems may reach inconsistent states. So we need to detect not onlymismatching problems, but also the inconsistence situations or faults.

Once we have defined our transformation model, we need to validate the compositionwith respect to a set of properties such as determinism, deadlock or liveliness. We plan toapply validation and assessment techniques, which it is needed to evaluate our proposal.

In addition, we pretend to extend our model by incorporating contextual ontologies [3],so that we will get to enrich the semantic of our model.

Acknowledgements

We would like to acknowledge to our colleagues of University College London, with whowe are working on validating the model here presented, since in our discussions we haveobtained some ideas to improve our proposal. This paper has been partially supported byproject TIN2007-67134 funded by the Spanish Ministry of Innovation and Science, andproject P06-TIC-02250 funded by Junta de Andalucıa.

References

1. T. Andrews et al. Business Process Execution Language for Web Services (WSBPEL). BEASystems, IBM, Microsoft, SAP AG, and Siebel Systems, 2005.

2. R. Bastide, O. Sy, D. Navarre, and P. A. Palanque. A Formal Specification of the CORBAEvent Service. In Proc. of FMOODS’00, pages 371–396. Kluwer, 2000.

3. P. Bouquet, F. Giunchiglia, F. van Harmelen, L. Serafini, and H. Stuckenschmidt. Contextual-izing Ontologies. Journal of Web Semantics, 1(4):325–343, 2004.

4. A. Brogi and R. Popescu. Automated Generation of BPEL Adapters. In Proc. of ICSOC’06,volume 4294 of LNCS, pages 27–39, 2006.

5. C. Canal, J.M. Murillo, and P. Poizat. Software Adaptation. L’Objet, 12(1):9–31, 2006. SpecialIssue on Coordination and Adaptation Techniques for Software Entities.

6. H. Chen, T. Finin, and A. Joshi. An Intelligent Broker for Context-Aware Systems. In Proc.of UbiComp’03, 2003.

7. J. Cubo, C. Canal, and E. Pimentel. Towards a Model-Based Approach for Context-AwareComposition and Adaptation: A Case Study using WF/.NET. In Proc. of MOMPES’08, pages3–13. IEEE Computer Society, 2008.

8. J. Cubo, G. Salaun, J. Camara, C. Canal, and E. Pimentel. Context-Based Adaptation ofComponent Behavioural Interfaces. In Proc. of COORDINATION’07, volume 4467 of LNCS,pages 305–323, 2007.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 71

Page 72: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

9. J. Cubo, G. Salaun, C. Canal, E. Pimentel, and P. Poizat. A Model-Based Approach to theVerification and Adaptation of WF/.NET Components. In Proc. of FACS’07, ENTCS, 2007.To appear.

10. A.K. Dey and G.D. Abowd. Towards a Better Understanding of Context and Context-Awareness. In Proc. of Workshop on the What, Who, Where, When and How of Context-Awareness 2000, pages 304–307, 2000.

11. T. Erl. Service-Oriented Architecture (SOA): Concepts, Technology, and Design. Prentice Hall,2005.

12. H. Foster, W. Emmerich, J. Kramer, J. Magee, D. Rosenblum, and S. Uchitel. Model CheckingService Compositions under Resource Constraints. In Proc. of ESEC/FSE’07, pages 3–7. ACMPress, 2007.

13. H. Foster, S. Uchitel, and J. Kramer. LTSA-WS: A Tool for Model-based Verification of WebService Compositions and Choreography. In Proc. of ICSE’06, pages 771–774. ACM Press,2006.

14. X. Fu, T. Bultan, and J. Su. Analysis of Interacting BPEL Web Services. In Proc. of WWW’04,pages 621–630. ACM Press, 2004.

15. C. Gao, R. Liu, Y. Song, and H. Chen. A Model Checking Tool Embedded into ServicesComposition Environment. In Proc. of GCC’06, pages 355–362. IEEE Computer Society, 2006.

16. J. Garcia-Fanjul, C. de la Riva, and J. Tuya. Generation of Conformance Test Suites forCompositions of Web Services Using Model Checking. In Proc. of TAIC-PART’08, pages 127–130. IEEE Computer Society, 2006.

17. M. Gaspari and G. Zavattaro. A Process Algebraic Specification of the New AsynchronousCORBA Messaging Service. In Proc. of ECOOP’99, volume 1628 of LNCS, pages 495–518,1999.

18. A. Ingolfsdottir and H. Lin. A Symbolic Approach to Value-passing Processes. Handbook ofProcess Algebra, Elsevier, 2001.

19. P. Inverardi and M. Tivoli. Deadlock-Free Software Architectures for COM/DCOM Applica-tions. Journal of Systems and Software, 65(3):173–183, 2003.

20. E. Kim and J. Choi. A Semantic Interoperable Context Infrastructure using Web Services. InProc. of ICCSA’07, volume 4706 of LNCS, pages 839–848, 2007.

21. N. Luo, J. Yan, M. Liu, and S. Yang. Towards Context-Aware Composition of Web Services.In Proc. of GCC’06, pages 494–499. IEEE Computer Society, 2006.

22. B. Margolis. SOA for the Business Developer: Concepts, BPEL, and SCA . Mc Press, 2007.23. R. Mateescu, P. Poizat, and Gwen Salaun. Behavioral Adaptation of Component Compositions

Based on Process Algebra Encodings. In Proc. of ASE’07, IEEE Computer Society Press, 2007.To appear.

24. S.B. Mokhtar, D. Fournier, N. Georgantas, and V. Issarny. Context-Aware Service Compositionin Pervasive Computing Environments. In Proc. of RISE’05, volume 3943 of LNCS, pages 129–144, 2006.

25. H. Motahari, B. Benatallah, A. Martens, F. Curbera, and F. Casati. Semi-Automated Adap-tation of Service Interactions. In Proc. of WWW’07, pages 993–1002. ACM Press, 2007.

26. J. Munoz, V. Pelechano, and J. Fons. Model Driven Development of Pervasive Systems. ERCIMNews, 58(0):50–51, 2004.

27. A. Nicoara and G. Alonso. PROSE - A Middleware Platform for Dynamic Adaptation. Demopresented at AOSD’05, 2005.

28. OMG. CORBA Component Model Specification, v. 4.0.www.omg.org/technology/documents/formal/components.htm, Object Management Group,2006.

29. D. Salber, A.K. Dey, and G.D. Abowd. The Context Toolkit: Aiding the Development ofContext-Enabled Applications. In Proc. of CHI’99, pages 434–441. ACM, 1999.

30. K. Scribner. Microsoft Windows Workflow Foundation: Step by Step. Microsoft Press, 2007.31. T. Simcock, S. Peter Hillenbrand, and Bruce H. Thomas. Developing a location based tourist

guide application. In ACSW Frontiers’03, pages 177–183. Australian Computer Society, Inc.,2003.

32. C. Szyperski. Component Software: Beyond Object-Oriented Programming. Adisson-Wesley,2nd edition, 2003.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 72

Page 73: Dynamic Architectural Adaptation Using Ontologies · Keywords: Ontology, Dynamic Architectural Adaptation, Component Composition, .NET. 1 Introduction Component Based Software Engineering

33. W.M.P. van der Aalst and A.H.M. ter Hofstede. YAWL: Yet Another Workflow Language.Information Systems, 30(4):245–275, 2005.

34. M. Vukovic. Context Aware Service Composition. Technical Report UCAM-CL-TR-700, Uni-versity of Cambridge, 2007.

35. www.omg.org/docs/omg/03-06-01.pdf. Object Management Group, MDA Guide version 1.0.1,2003.

36. H. Q. Yu and S. Reiff-Marganiec. Semantic Web Services Composition via Planning as ModelChecking. Technical Report CS-06-003, University of Leicester, 2006.

Actas de los Talleres de las Jornadas de Ingeniería del Software y Bases de Datos, Vol. 2, No. 5, 2008

ISSN 1988–3455 SISTEDES, 2008 73