CORBA (Common Object Request Broker Architecture) Denivaldo LOPES 1
CORBA Table de matières Middleware CORBA Introduction à IDL Java et CORBA (JDK 1.4) C et CORBA (ORBit2) L interopérabilité entre JDK-CORBA et ORBit2 Conclusions 2
CORBA Middleware 3
1.1 Introduction au Middleware Application Application Application APIs (Application Programming Interface) Middleware (Distributed System Services) Interface de la Plateforme Interface de la Plateforme Interface de la Plateforme Plateforme SO hardware Plateforme SO hardware Plateforme SO hardware Figure 1 Fonctionnement d un middleware 4
1.1 Introduction au Middleware Comme exemple de middleware, on peut citer: - Distributed Computing Environment (DCE); -CORBA; - Distributed Component Object Model (DCOM); - Java Remote Method Invocation (Java RMI); - Simple Object Access Protocol (SOAP). 5
CORBA CORBA 6
2. Common Object Request Broker Architecture - CORBA est une spécification et architecture standard (i.e. généraliste) pour Object Request Brokers (ORBs). - ORB est une infrastructure de communication par laquelle les objets accèdent aux services et aux facilités, et communiquent les uns avec les autres. 7
2. Common Object Request Broker Architecture L OMG (Object Management Group) a présenté sa première version du modèle de CORBA en juillet 1992, dans une révision du document de 1990 qui avait créé le Object Management Architecture (OMA) Guide. Application Objects ORB CORBA Services CORBA Facilities Figure 2 Object Management Architecture (OMA) 8
2. Common Object Request Broker Architecture L OMA est constitué de : Application Objets; ORB; CORBA Services; CORBA Facilites. 9
2. Common Object Request Broker Architecture Le projet initial de CORBA a été conçu théoriquement selon les pré réquisits suivants: Le modèle orienté à objet; L environnement de traitement ouvert et distribué; L intégration de composants et réutilisation. 10
2. Common Object Request Broker Architecture CORBA fournit : L accès aux services de manière uniforme; La découverte des ressources et des noms d objets uniformes; Des méthodes de détection d erreurs uniformes; Une politique de sécurité uniforme. 11
2. Common Object Request Broker Architecture Les ORBs CORBA peuvent être considérés comme des mécanismes RPC optimisés, avec: Plus d abstraction du langage de définition d interface; Un support direct pour une variété de concepts orientés à objets; Un support pour d autres services (CORBA Facility et CORBA Services) et standards (IDL). 12
2. Common Object Request Broker Architecture CORBA présente des avantages importants pour les systèmes distribués comme: La transparence; La portabilité; L interopérabilité; L adaptabilité; La disponibilité; La stabilité. 13
2. Common Object Request Broker Architecture Il présente aussi des désavantages comme par exemple: La complexité; Le prix élevé; Une formation spécialisée pour les développeurs. 14
2. Common Object Request Broker Architecture Les implémentations les plus diffusées de produits basés en CORBA sont: Visibroker de Borland ; Orbix de l Iona ; JDK-CORBA de Sun Microsystems ; ORBit2 de GNOME; OpenORB de sourceforge.net. 15
2.1 Notions sur CORBA Un élément important et crucial pour comprendre CORBA est la conception et l utilisation de l IDL (Interface Definition Language). Ce langage permet de définir les objets CORBA indépendamment du langage de programmation qui sera utilisé pour implémenter les objets CORBA ou les clients. 16
2.1 Notions sur CORBA Figure 3 - Structure de l Interface de Réquisition de Objet 17
2.1 Notions sur CORBA Le modèle d objet de CORBA consiste en: des Objets; des Types; des Interfaces; des Opérations; une Requête; une Création et une Destruction d Objets; 18
2.1 Notions sur CORBA short long unsigned short unsigned long Valeur Types simples long long float char string boolean unsigned long long double wchar wstring long double octet Types complexes Types dynamiques Types d objets Figure 4 Les types de donnés de IDL-CORBA 19
2.1 Notions sur CORBA Types simples enum struct Types complexes union array Valeur sequence Types dynamiques TypeCode Any Types d objets Figure 4 Les types de donnés de IDL-CORBA (cont.) 20
2.1 Notions sur CORBA De plus, le modèle d implémentation des objets est organisé en: un modèle d exécution - décrit comment les services exécutent une action; un modèle de construction - décrit comment les services sont définis. 21
La communication entre le client et le server. Client 2.1 Notions sur CORBA Invocation Dynamique Stubs IDL Interface identique pour toutes implémentations de ORB Il y a de Stubs et de Skeleton pour chaque type de l objet Interface dépendent de l ORB Figure 5 (a) L appel d un objet en CORBA 22
2.1 Notions sur CORBA Implémentation de l Objet (Serveur) Interface de l ORB Skeleton Statique Skeleton Dynamique Adaptateur de l Objet Interface identique pour toute implémentation de ORB Multiples adaptateurs de l objet Il y a de Stubs et de Skeleton pour chaque type de l objet Appel d une interface de niveau supérieur Appel normal d une interface Interface dépendente de l ORB Figure 5 (b) L appel d un objet en CORBA 23
2.1 Notions sur CORBA IDL Compilateur(s) IDL Stubs/Skeletons (langage cible) Mapping C -Header du Client -Stub -Implémentation du header -Skeleton Mapping C++ -Header du Client -Stub -Implémentation du header -Skeleton Mapping SmallTalk -Implémentation de template Autres mappings - Java, Ada 95, Commom Lisp, etc. Figure 6 La transcription (mapping) de IDL vers un langage spécifique 24
2.2 La pile de CORBA Tableau 1 La pile de CORBA Fonction Définition de service Annuaire de service Activation du Client/Serveur Composant de la Pile de CORBA IDL CORBA Services (Trade Service) Stubs/Skeletons Electronique Data Interchange CDR protocole de bas-niveau GIOP/IIOP 25
2.3 L objet Web Figure 7 Interaction HTTP, CORBA et Java 26
CORBA Introduction à IDL 27
3. Introduction à IDL Les commentaires Les commentaires en IDL se font de deux façons: les commentaires d une ligne sont précédés par le symbole //; et les commentaires de plusieurs lignes sont délimitées par les symboles /* et */, comme montré dans l exemple suivant: // This is a simple line /* This is a commentary with two lines */ 28
3. Introduction à IDL Les Identificateurs Chaque de déclarations de types a un identificateur unique, une construction syntaxique spécifique qui se termine par un point virgule. Une formalisation pour un identificateur peut être exprimée par : <identifier>::= <letter> {<character>}* <character>::= <letter> <number> _ <letter> ::= a z A Z <number>::= 0 9 29
3. Introduction à IDL Les types simples Tableau 2 Types simples et ses valeurs valides en IDL Types de base Valeurs short Entiers 16 bits signés unsigned short Entiers 16 bits non signés long Entiers 32 bits non signés unsigned long Entiers 32 bits non signés long long Entiers 64 bits signés unsigned long long Entiers 64 bits non signés float Nombres flottantes 32 bits au format standard IEEE double Nombres flottantes 64 bits au format standard IEEE long double Nombres flottantes 128 bits boolean Valeurs booléennes FALSE ou TRUE octet Octets 8 bits char Caractères 8 bits ISO Latin-1 wchar Caractères au format international string Chaînes de caractères wstring Chaînes de caractères au format international 30
3. Introduction à IDL Constantes IDL IDL permet la définition de valeurs constantes. Par exemple: const unsigned long kilometers_per_mile = 2.2; const char separador = / ; const char carriage_return = / ; const boolean tautology = TRUE; const float pi = 3.1415926; const double avagodro = 6.02e25; typedef string LastName; const LastName my_lastname = Mowbray ; const float days_per_month= 364.5 / 12; 31
3. Introduction à IDL Les définitions de type Pour définir un nouveau type, il suffit d employer le mot-clé typedef suivi d un type existant et du nouveau type. La formalisation pour déclarer un nouveau type est : <define> ::= typedef <type> <identifier> typedef unsigned long PhoneNumber; // Rename type unsigned long typedef string GuestName, Address; // Rename types of strings // Enumeration Types enum ChargeCard { MasterCard, Visa, AmericanExpress, Diners}; // A Structure Type struct GuestRecord{ GuestName name; Address address; PhoneNumber number; ChargeCard card_kind; unsigned long card_number, expiration; }; 32
3. Introduction à IDL Les types complexes Les types simples ne sont pas suffisants pour résoudre à tous les besoins d un contrat IDL. Ainsi, le langage IDL offre des constructions pour créer à partir des types simples de nouveaux types de données complexes : les énumérations; les structures; les unions; les tableaux; les séquences. 33
3. Introduction à IDL les énumérations Les énumérations permettent de définir un ensemble de constantes symboliques regroupées sous un même type. La déclaration des énumérations peut être formalisé comme : <an_enumeration> ::= enum <identifier> { <identifier> {, <identifier> }* } Un exemple d énumération peut être exprimé par : enum Month{ January, February, March, April, May, June, July, August, September, October, November, December }; 34
3. Introduction à IDL les structures Les structures peuvent être décrites avec le formalisme suivant : <a_structure> ::= struct <identifier> { { <a_camp> }+ } <a_camp> ::= <type> <identifier> ; Un exemple de structure est donné ci-dessous : struct Date{ unsigned short month ; unsigned short day_of_week ; unsigned short year ; } 35
3. Introduction à IDL les unions Une union IDL contient un discriminant et un ensemble de champs. L exemple suivant montre la création d une union. Union DatesMultiForm switch (long) { case 1 : Date format_date ; case 2 : string format_string ; default : unsigned short number_of_days ; }; 36
3. Introduction à IDL les tableaux Le langage IDL permet la définition de tableaux de taille fixe pour regrouper un ensemble de valeurs d un même type. Un tableau respect la formalisation suivante : <an_array> ::= <type> <a_size> { <a_size> }* <a_size> ::= [ <positive_int_const> ] Le code suivant illustre la déclaration d un table de 10.000 éléments (i.e. 100 x 100). float result [100] [100] ; 37
3. Introduction à IDL les séquences. La séquence est essentiellement un tableau de taille dynamique et de valeurs homogènes. La déclaration d une séquence peut être formalisée par : <a_sequence> ::= sequence < <type> > sequence < <type>, <taille_maximale> > L exemple suivant montre comment déclarer une séquence : sequence <long> array_dynamic ; 38
3. Introduction à IDL Types Dynamiques - Le type Any Le langage IDL est fortement typé, mais il permet aussi la création de types faiblement typés grâce à un type spécial appelé any. Le type any est employé dans tous les contextes où: il est nécessaire de transporter des valeurs dont le type n est pas encore connu au moment de la phase de conception IDL; pour définir des opérations dont un des paramètres est polymorphe. 39
3. Introduction à IDL Types Dynamiques - Le type Any Les exemples IDL suivants illustrent l utilisation du type any : typedef any DynamicallyTypedValue; struct RunTimeValue{ string description; any run_time_value; }; exception UserError { string explanation; any exception_value; }; 40
3. Introduction à IDL Attributs IDL La formalisation d un attribut peut être décrite par : <a_attribut> :: = <mode> attribute <type> <identificateur> <mode> ::= [readonly] L exemple suivant montre la définition d attributs : Interface CensusData { attribute unsigned short age; readonly attribute string birth_date; attribute string last_name, first_name; struct HouseHold { string address; unsigned short number_of_occupants; }; attribute HouseHold house_hold; }; 41
3. Introduction à IDL Les exceptions CORBA assure que si un client fait un appel, il recevra toujours un retour avec succès ou une exception. Les exceptions jouent un rôle important dans la spécification d une interface. Les exceptions définissent une valeur retournée par les opérations en cas d erreur. Une exception peut être formalisée par : <except_dcl> ::= exception <identifier> { <member> } 42
Les exceptions 3. Introduction à IDL Les exemples suivants aident à comprendre les exceptions. exception CardExpired { string expiration_date; }; exception CreditLimitExceeded { unsigned long credit_limit; }; exception CardReportedStolen { string reporting_instructions; unsigned long hotline_phone_number; }; Une exception est associée à une opération d interface, comme l exemple suivant : Exception Error_data{ String motif ; } string get_name (in string code_personel) raises (Error_data) ; 43
Les exceptions Les exceptions peuvent être définies par : l utilisateur ; la spécification de CORBA. 3. Introduction à IDL Les exceptions définies par la spécification de CORBA sont appelées Standard Exceptions, comme par exemple : UNKNOWN, BAD_PARAM, NO_MEMORY, IMP_LIMIT et COMM_FAILURE. 44
Les espaces de définition (les modules) 3. Introduction à IDL Les modules IDL créent des espaces de nommage. Les modules n héritent pas d autres modules. Seulement les interfaces IDL sont capables d hériter de spécifications. Le module peut être spécifié comme la formalisation : <module> ::= module <identifier> { <définition>+ } 45
Les espaces de définition (les modules) 3. Introduction à IDL L exemple suivant montre une déclaration de module. // module module Math{ const double E=2.7182818; const double PI = 3.1415926; typedef long Value; // other declarations } 46
Les espaces de définition (les modules) L exemple suivant montre l utilisation de plusieurs modules : module M{ module Inner1{ typedef string S1; }; module Inner2{ typedef string S1; }; }; 3. Introduction à IDL La déclaration de Inner1::S1 et Inner2::S2 sont correctes parce que l identificateur S1 se trouve dans deux modules différents. 47
Interfaces IDL 3. Introduction à IDL Une interface IDL décrit l ensemble des opérations et des attributs offerts par un type d objets. Cette description présente uniquement la partie publique des objets et cache les détails des implémentations. La signature d une opération est l essence de l interface. Elles sont des points d entrée pour réquisitionner les services fournis par un objet CORBA. On déclare une interface de la maniaère suivante : <interface> :: = interface <identifier> { <declarations> } 48
Interfaces IDL Les interfaces IDL peuvent hériter d autres interfaces. L exemple suivant définit trois interfaces: interface Account{ // declarations of Account (operations and attributes) }; 3. Introduction à IDL interface Checking: Account{ // inherit all declarations of Account (operations and attributes) // and add declarations of Checking (operations and attributes) }; interface Saving: Account{ // inherit all declarations of Account(operations and attributes) // add declarations of Savings (operations and attributes) }; 49
Les opérations IDL 3. Introduction à IDL La spécification du contrat d opérations définit les manières adéquates pour accéder à un objet CORBA. Toute définition d opérations est déclarée dans l interface IDL spécifique. Voici un exemple d opération : Interface Hospital { typedef string PatientId; // An Operation Signature PatientId admit_patient( ); }; // Another Signature void release_patient (in PatientId patient); 50
3. Introduction à IDL Les opérations IDL La signature d une opération en IDL est formalement définie comme : in, out, inout [oneway] <op_type_spec> <identifier> (param1,..., paraml) [raises(except1,...,exceptn)] [context(name1,..., namem)] Des exemples de déclarations d opérations. boolean is_vacation(in Date d) ; void what_are_vacations (in Year year_arg, out Days vacations) ; void the_next_day(inout Date day) ; oneway void send_a_message(in string msg) ; void print () context( PRINTER ) ; 51
Directives de Pré compilateur L exemple suivant montre l utilisation de la directive include: // Naming Service #include <CosNaming.idl> // Event Service #include <CosEventComm.idl> #include <CosEventChannelAdmin.idl> // Persistence Service #include <CosPersistencePID.idl> #include my_file.idl 3. Introduction à IDL Les directives de pré-compilation du langage IDL sont identiques à celles du C++ pour permettre la définition de macro instructions (#define) et la compilation conditionnelle (#if, #else, et #endif). 52
CORBA Java et CORBA (JDK 1.4) 53
4. Java et CORBA (JDK 1.4) Nous étudierons et utiliserons uniquement le Portable Object Adapter (POA). Un adaptateur d objet est un mécanisme qui connecte un appel et une référence d objet pour le code spécifique du service. POA donne les avantages suivants: la portabilité des implémentations d objets entre différents produits ORB ; identificateurs d objets persistants ; transparence d activation d objets CORBA. 54
4. Java et CORBA (JDK 1.4) Pour implémenter le côté serveur avec POA, le JDK 1.4 fournit deux modèles: Modèle d héritage l interface IDL est implémentée avec l utilisation d une classe qui spécialise aussi (extend) le skeleton généré par le compilateur de IDL; Modèle de délégation l interface IDL est implémentée par deux classes. Une classe spécifiée par le Tie qui spécialise (extend) le skeleton généré par le compilateur, mais délègue tous les appels à une autre implémentation de la classe qui contient les opérations définies dans l interface. 55
4. Java et CORBA (JDK 1.4) L API de Java pour CORBA (JDK1.4) présente les paquets suivants: org.omg.corba fournit la transcription des APIs de OMG CORBA pour le langage de programmation Java; org.omg.portableserver fournit les classes et les interfaces pour construire le côté serveur d une application portable entre plusieurs vendeurs de ORBs ; org.omg.cosnaming fournit un service de nommage pour Java IDL; org.omg.cosnaming.namingcontextpackage ce paquet contient des classes d Exception pour le paquet org.omg.cosnaming. 56
1 IDL (fichier *.idl) 4. Java et CORBA (JDK 1.4) 2 Pré-compilateur IDL Stub **Stub Interface** **Helper extend **POA Skeleton **POA **Operation **Helper 3 Implémentation du client 5 Implémentation du service 4 compilation 6 Implémentation du serveur Classe du client 7 compilation Fichier d entrée Fichier de sortie référence héritage compilation fichier *.classe Classe du serveur Implémentation fichier *.java Figure 8 Étapes de la création d un programme avec CORBA (POA) en JDK 57
4.1 La correspondance entre les types de données en CORBA vers Java Tableau 4 La transcription de IDL vers Java IDL Type Java Type module package boolean boolean char, wchar char octet byte string, wstring java.lang.string short, unsigned short short long, unsigned long int long long, unsigned long long long float float double Double long double non disponible fixed java.math.bigdecimal 58
IDL Type 4.1 La correspondance entre les types de données en CORBA vers Java enum, struct, union sequence, array interface (non-abstract) interface (abstract) Java Type class array constant (not within an interface) public interface constant (within an interface) exception Any type declarations nested within interfaces typedef pseudo objects readonly attribute readwrite attribute operation signature interface and an operations interface, helper class, holder class signature interface, helper class, holder class fields in the Java signature interface for nonabstract, or the sole Java interface for abstract class org.omg.corba.any "scoped" package helper classes pseudo interface accessor method accessor and modifer methods method 59
4.2 Exemple de programme en Java avec l utilisation de CORBA Programme 4.2.1 Programme Hello World en Java avec CORBA Fichier: Hello.idl // to create the stubs and other files use the following command: // idlj -fall Hello.idl module HelloWorld { interface Interface_Hello { }; string get_msg(); }; 60
4.2 Exemple de programme en Java avec l utilisation de CORBA Fichier: Hello_service.java package corba.sample_a; //Implementation the service import HelloWorld.*; import java.util.*; public class Hello_service extends Interface_HelloPOA { private Calendar cal; public Hello_service() { cal = Calendar.getInstance(); } 61
4.2 Exemple de programme en Java avec l utilisation de CORBA Fichier: Hello_service.java public String get_msg() { String msg="hello world! my time is: " + cal.get(cal.hour_of_day) + ":" + cal.get(cal.minute)+":"+cal.get(cal.second)+":«+ cal.get(cal.millisecond); System.out.println("Server>server is returning the following message to client:"+msg); } } return msg; 62
4.2 Exemple de programme en Java avec l utilisation de CORBA Fichier: Server_hello.java *** System.out.println("Server>creating and initializing the ORB"); ORB orb = ORB.init(args, null); //or ORB orb = ORB.init(args, properties); System.out.println("Server>getting reference to rootpoa"); POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); System.out.println("Server>activating the POA Manager"); rootpoa.the_poamanager().activate(); // System.out.println("Server>Creating the servant"); Hello_service hello_service = new Hello_service(); // System.out.println("Server>obtain the reference from the servant"); org.omg.corba.object service_ref = rootpoa.servant_to_reference(hello_service); Interface_Hello service_href= Interface_HelloHelper.narrow(service_ref); 63
Fichier: Server_hello.java 4.2 Exemple de programme en Java avec l utilisation de CORBA // System.out.println("Server>getting the root naming context"); org.omg.corba.object objref = orb.resolve_initial_references("nameservice"); // System.out.println("Server>using NamingContextExt to provides interoperability"); NamingContextExt ncref = NamingContextExtHelper.narrow(objRef); // System.out.println("Server>binding the object reference in naming with name "+name_service); NameComponent nc = new NameComponent(name_service, ""); NameComponent path[] = {nc}; ncref.rebind(path, service_href); *** 64
4.2 Exemple de programme en Java avec l utilisation de CORBA Fichier: Client_hello.java *** String name_service="hello_server"; // System.out.println("Client>Creating and initializing the ORB"); ORB orb = ORB.init(args, null); //or ORB orb = ORB.init(args, properties); System.out.println("Client>getting the root naming context"); org.omg.corba.object objref = orb.resolve_initial_references("nameservice"); // it uses NamingConetExt Interoperable Naming Service NamingContextExt ncref = NamingContextExtHelper.narrow(objRef); // System.out.println("Client>Resolving the object reference in naming ["+name_service+"]"); NameComponent nc = new NameComponent(name_service, ""); NameComponent path[] = {nc}; // Interface_Hello hello= Interface_HelloHelper.narrow(ncRef.resolve(path)); 65
4.2 Exemple de programme en Java avec l utilisation de CORBA Fichier: Client_hello.java System.out.println("Client>calling the Hello service..."); String msg_received = hello.get_msg(); // System.out.println("Client>server returned the following message: "+msg_received); *** 66
4.2 Exemple de programme en Java avec l utilisation de CORBA L exécution Exécution de orbd : C:\Prog_CORBA\POA>orbd -ORBInitialPort 4000 Exécution de Server_hello java -cp c:\prog_corba\poa corba.sample_a.server_hello - ORBInitialPort 4000 Server>starting server... Server>creating and initializing the ORB Server>getting reference to rootpoa Server>activating the POA Manager Server>Creating the servant Server>obtain the reference from the servant Server>getting the root naming context Server>using NamingContextExt to provides interoperability Server>binding the object reference in naming with name Hello_server Server>Server was started... Server>enter with quit command to shutdown the server... Server>server is returning the following message to client: Hello world! my time is: 19:16:52:534 *** 67
L exécution 4.2 Exemple de programme en Java avec l utilisation de CORBA Exécution de Client_hello java -cp c:\prog_corba\poa corba.sample_a.client_hello -ORBInitialPort 4000 Client>Creating and initializing the ORB Client>getting the root naming context Client>Resolving the object reference in naming [Hello_server] Client>calling the Hello service... Client>server returned the following message: Hello world! my time is: 19:16:52:534 68
CORBA C et CORBA (ORBit2) 69
5. C et CORBA (ORBit2) ORBit2 est une révision de ORBit. ORBit2 a les avantages suivants par rapport à ORBit: il utilise CORBA 2.4 ; il travaille avec linc, qui permet l utilisation de plusieurs protocoles de transport ; il utilise l URL pour trouver un IOR, i.e., il permet trouver un IOR via HTTP. il a été complètement réécrit pour être plus optimisé et fiable. 70
5. C et CORBA (ORBit2) L API de l ORBit est organisé en plusieurs fichiers d entête (*.h) ; les plus importants sont : <include>/orbit/orbit.h <include>/orbitservices/cosnaming.h <include>/orbitservices/cosnaming_impl.h 71
5. C et CORBA (ORBit2) Les structures et les pointeurs les plus importants sont : PortableServer_POA; CosNaming_NamingContext; CORBA_ORB; CosNaming_NameComponent; CosNaming_Name; CORBA_Environment est une structure pour récupérer les messages d erreur. Il y a trois variables : CORBA_char *_id spécifique au type d erreur (minor) ; CORBA_unsigned_long _major identifie le type d erreur (major) ; CORBA_any _any est un type any de CORBA pour recevoir un type de donnée valide en CORBA ; 72
1 IDL (fichier *.idl) 5. C et CORBA (ORBit2) 2 Pré-compilateur IDL Stub **-stubs.c **.h **- common.c **-skelimpl.c 5 Skeleton **-skels.c utilise #include <?> #include <?> utilise utilise 3 Implémentation du client (**-client.c) 6 Implémentation du serveur (**-server.c) 4 compilation 7 compilation (exécutable) Programme client (exécutable) Programme serveur Fichier d entrée Fichier de sortie Implémentation référence héritage fichier *.c compilation fichier *.exe Figure 9 Étapes de la création d un programme avec CORBA (POA) en ORBit2 73
5.1 La correspondance entre les types de données en IDL-CORBA et C Tableau 5 La transcription de IDL vers C IDL Type C Type module it uses the name of modules, interfaces and operations to create the scope For example: //IDL module Test{ interface A{ void op1(in boolean flag); } } //C typedef CORBA_Object Test_A; void Test_A_op1( Test_A object, CORBA_boolean flag, CORBA_Environment *ev); boolean char, wchar octet CORBA_boolean CORBA_char, CORBA_wchar CORBA_octet string, wstring CORBA_char *, CORBA_wchar * short, unsigned short CORBA_short, CORBA_unsigned_short 74
5.1 La correspondance entre les types de données en IDL-CORBA et C Tableau 5 La transcription de IDL vers C (cont.) IDL Type long, unsigned long long long, unsigned long long float double, long double C Type CORBA_long, CORBA_unsigned_long CORBA_long_long, CORBA_unsigned_long_long CORBA_float CORBA_double, CORBA_long_double fixed voir la bibliographie [] struct union enum sequence C structs (IDL structs are directly mapped onto C structs) C structs Unsigned integer type capable of representing 2 32 enumerations a specialized C structure with information : maximum length ; length ; pointer for the specified type //IDL Typedef sequence<float,15> vec ; //C typedef struct{ CORBA_unsigned_long _maximum ; CORBA_unsigned_long _length ; CORBA_float *_buffer ; } vec ; 75
5.1 La correspondance entre les types de données en IDL-CORBA et C Tableau 5 La transcription de IDL vers C (cont.) IDL Type array C Type array C (IDL arrays are directly mapped onto C arrays) //IDL typedef long array_a[5][7] ; //C Typedef CORBA_long array_a[5][7] ; Typedef CORBA_long array_a_slice[7] ; interface constant In C, the concept of interface is not existent, then it is used an artifice // IDL interface example1{ long op1(in long arg1) ; } ; //C typedef CORBA_Object example1 ; extern CORBA_long example1_op1( example1 o, CORBA_long arg1, CORBA_Environment *ev ) ; It is created using #define //IDL const wstring ws= Hello World //C #define ws Hello World 76
5.1 La correspondance entre les types de données en IDL-CORBA et C Tableau 5 La transcription de IDL vers C (cont.) IDL Type exception any C Type C struct and a typedef typedef struct CORBA_any { CORBA_TypeCode _type ; void *_value ; } CORBA_any ; type declarations nested within interfaces typedef C typedef pseudo objects voir la reference [OMG 99]. readonly attribute readwrite attribute operation acessor functions acessor and modifier functions C functions 77
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Programme 5.2.1 Programme Hello World en C avec CORBA Fichier: Hello.idl (le même fichier que de l exemple 4.2.1) // to create the stubs and other files use the following command: // xxxxx module HelloWorld { interface Interface_Hello { string get_msg(); }; }; 78
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Fichier: Hello-skelimpl.c **** static CORBA_string impl_helloworld_interface_hello_get_msg( impl_poa_helloworld_interface_hello * servant, CORBA_Environment * ev) { CORBA_string retval= CORBA_string_alloc(512); /* ------ insert method code here ------ */ strcpy(retval,"hello World! I am Linux running this service written in C using ORBIT2..."); g_print("\nserver>server is returning: %s",retval); /* ------ ---------- end ------------ ------ */ return retval; } 79
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Fichier: hello-server_ns.c *** PortableServer_POA poa; HelloWorld_Interface_Hello servant = CORBA_OBJECT_NIL; CosNaming_NamingContext ns =CORBA_OBJECT_NIL; CORBA_ORB orb=corba_object_nil; CORBA_char name_service[]="hello_server"; CosNaming_NameComponent path[1]={name_service,""}; CosNaming_Name name={1,1,path,corba_false}; CORBA_Environment ev; // g_print("\nserver>starting server..."); g_print("\nserver>creating and initializing the ORB"); CORBA_exception_init(&ev); abort_if_exception(&ev, "CORBA_exception_init failed"); // orb=corba_orb_init(&argc,argv,"orbit-local-orb",&ev); abort_if_exception(&ev, "CORBA_ORB_init failed"); // g_print("\nserver>getting reference to RootPOA"); poa= (PortableServer_POA) CORBA_ORB_resolve_initial_references(orb,"RootPOA",&ev); abort_if_exception(&ev, "CORBA_ORB_resolve_initial 'RootPOA' failed"); 80
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Fichier: hello-server_ns.c // g_print("\nserver>activating the POA Manager"); PortableServer_POAManager_activate(PortableServer_POA get_the_poamanager(po a, &ev),&ev); abort_if_exception(&ev, "POA_activate failed"); // g_print("\nserver>creating the servant"); servant = impl_helloworld_interface_hello create (poa, &ev); abort_if_exception(&ev, "Interface_Hello create failed"); // CORBA_char filename[] = "name_service.ior"; FILE *file = NULL; // g_print("\nserver>reading the file '%s'",filename); if ((file=fopen(filename, "r"))==null) g_error ("could not open '%s'\n", filename); gchar *objref=null; fscanf (file, "%as", &objref); /* FIXME, handle input error */ g_print("\nserver>getting the root naming context 'NameService' - from the file '%s'",filename); ns = (CosNaming_NamingContext) CORBA_ORB_string_to_object (orb, objref, &ev); free (objref); abort_if_exception(&ev, "CORBA_ORB_string_to_object 'NameService IOR' failed"); 81
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Fichier: hello-server_ns.c // g_print("\nserver>binding the object reference in naming with name '%s'",name_service); CosNaming_NamingContext_rebind(ns,&name,servant,&ev); abort_if_exception(&ev, "rebind failed"); // g_print("\nserver>running the orb..."); CORBA_ORB_run(orb,&ev); abort_if_exception(&ev, "ORB_run failed"); // g_print("\nserver>executing the release"); CORBA_Object_release(servant,&ev); abort_if_exception(&ev, "Object_release failed"); // g_print("\nserver>executing the shutdown"); CORBA_ORB_shutdown(orb,CORBA_FALSE, &ev); abort_if_exception(&ev, "shutdown failed"); *** 82
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Fichier: hello-client_ns.c *** CORBA_ORB orb=corba_object_nil; CORBA_Environment ev; CosNaming_NamingContext ns =CORBA_OBJECT_NIL; HelloWorld_Interface_Hello service = CORBA_OBJECT_NIL; CORBA_char name_service[]="hello_server"; CosNaming_NameComponent path[1]={name_service,""}; CosNaming_Name name={1,1,path,corba_false}; // g_print("\nclient>starting client..."); g_print("\nclient>creating and initializing the ORB"); CORBA_exception_init(&ev); abort_if_exception(&ev, "CORBA_exception_init failed"); // orb=corba_orb_init(&argc,argv,"orbit-local-orb",&ev); abort_if_exception(&ev, "CORBA_ORB_init failed"); 83
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Fichier: hello-client_ns.c CORBA_char filename[] = "name_service.ior"; FILE *file = NULL; g_print("\nclient>reading the file '%s'",filename); if ((file=fopen(filename, "r"))==null) g_error ("could not open %s\n", filename); gchar *objref=null; fscanf (file, "%as", &objref); /* FIXME, handle input error */ g_print("\nclient>getting the root naming context 'NameService' - from the file '%s'",filename); ns = (CosNaming_NamingContext) CORBA_ORB_string_to_object (orb, objref, &ev); // free (objref); abort_if_exception(&ev, "CORBA_ORB_string_to_object 'NameService IOR' failed"); 84
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) Fichier: hello-client_ns.c g_print("\nclient>resolving the object reference in naming '%s'",name_service); service=cosnaming_namingcontext_resolve(ns,&name,&ev); abort_if_exception(&ev, "resolve failed"); // g_print("\nclient>calling the Hello service..."); CORBA_char *msg=helloworld_interface_hello_get_msg(service,&ev); abort_if_exception(&ev, "HelloWorld_Interface_Hello_get_msg failed"); /* prints results to console */ g_print("\nclient>server returned the following message: %s\n", msg); CORBA_Object_release(service, &ev); abort_if_exception(&ev, "release failed"); if (orb!= CORBA_OBJECT_NIL) { /* going to destroy orb.. */ CORBA_ORB_destroy(orb, &ev); abort_if_exception(&ev, "destroy failed"); } *** 85
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) L exécution Exécution de orbit-name-server-2 : orbit-name-server-2 > name_service.ior Exécution de hello-server_ns :./hello-server_ns Server>starting server... Server>creating and initializing the ORB Server>getting reference to RootPOA Server>activating the POA Manager Server>creating the servant Server>reading the file 'name_service.ior' Server>getting the root naming context 'NameService' - from the file 'name_service.ior' Server>binding the object reference in naming with name 'Hello_server' Server>running the orb... 86
5.2 Exemple de programme en C avec l utilisation de CORBA (ORBit2) L exécution Exécution de hello-client_ns :./hello-client_ns Client>starting client... Client>creating and initializing the ORB Client>reading the file 'name_service.ior' Client>getting the root naming context 'NameService' - from the file 'name_service.ior' Client>Resolving the object reference in naming 'Hello_server' Client>calling the Hello service... Client>server returned the following message: Hello World! I am Linux running this service written in C using ORBIT2... 87
CORBA L interopérabilité entre JDK-CORBA et ORBit2 88
6. L interopérabilité entre JDK-CORBA et ORBit2 La spécification de CORBA détermine que tous les ORB- CORBA doivent être interopérables, en utilisant le protocole GIOP-IIOP. Les implémentations de JDK-CORBA et de ORBit2 de GNOME sont interopérables, puisqu ils obéissent à la spécification de GIOP-IIOP. Cependant, il faut utiliser le service de nommage de l ORBit2 v2.7.6. Il faut aussi utiliser l Interoperable Object Reference (IOR) générer par l exécution de orbit-name-server-2. 89
6. L interopérabilité entre JDK-CORBA et ORBit2 L IOR est semblable aux lignes suivantes : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Object ID: IDL:omg.org/CosNaming/NamingContextExt:1.0 IOP_TAG_GENERIC_IOP: GIOP 1.2[UNIX] linux:/tmp/orbit-dlopes/linc-10d7-0-4bfff34723811 IOP_TAG_INTERNET_IOP: GIOP 1.2 linux:32802 object_key (28) '00000000310c6b200ce205073e81e60603d2abcb01000000f09a4ce0' IOP_TAG_ORBIT_SPECIFIC: usock /tmp/orbit-dlopes/linc-10d7-0-4bfff34723811 IPv6 port 0 object_key (28) '00000000310c6b200ce205073e81e60603d2abcb01000000f09a4ce0' IOP_TAG_MULTIPLE_COMPONENTS: IOP_TAG_COMPLETE_OBJECT_KEY: object_key (28) '00000000310c6b200ce205073e81e60603d2abcb01000000f09a4ce0' Unknown component 0x1 90
6.1 L utilisation de IOR avec JDK et ORBit Le serveur Fichier: Server_hello_ns.java *** System.out.println("Server>starting server..."); System.out.println("Server>creating and initializing the ORB"); ORB orb = ORB.init(args, null); // System.out.println("Server>getting reference to rootpoa"); POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); // System.out.println("Server>activating the POA Manager"); rootpoa.the_poamanager().activate(); // System.out.println("Server>Creating the servant"); Hello_service hello_service = new Hello_service(); 91
6.1 L utilisation de IOR avec JDK et ORBit Le serveur (cont.) Fichier: Server_hello_ns.java System.out.println("Server>obtain the reference from the servant"); org.omg.corba.object service_ref = rootpoa.servant_to_reference(hello_service); Interface_Hello service_href = Interface_HelloHelper.narrow(service_ref); // System.out.println("Server>getting the NameService IOR..."); String separator=system.getproperty("file.separator"); String filename = "."+ separator + "name_service.ior"; System.out.println(filename); FileInputStream fis = new FileInputStream(filename); java.io.datainputstream dis = new java.io.datainputstream(fis); String ior_name_service = dis.readline(); org.omg.corba.object objref = orb.string_to_object(ior_name_service); 92
6.1 L utilisation de IOR avec JDK et ORBit Le serveur (cont.) Fichier: Server_hello_ns.java NamingContextExt ncref = NamingContextExtHelper.narrow(objRef); NameComponent nc = new NameComponent(name_service, ""); NameComponent path[] = { nc }; ncref.rebind(path, service_href); System.out.println("Executing server...\n"); orb.run(); *** 93
Le client Fichier: Client_hello_ns.java *** 6.1 L utilisation de IOR avec JDK et ORBit System.out.println("Client>Creating and initializing the ORB"); ORB orb = ORB.init(args, null); // System.out.println("Client>getting the root naming context"); // String filename = "."+ System.getProperty("file.separator") + "name_service.ior"; System.out.println(filename); FileInputStream fis = new FileInputStream(filename); java.io.datainputstream dis = new java.io.datainputstream(fis); String ior = dis.readline(); org.omg.corba.object objref = orb.string_to_object(ior); // it uses NamingConetExt Interoperable Naming Service NamingContextExt ncref = NamingContextExtHelper.narrow(objRef); 94
Le client 6.1 L utilisation de IOR avec JDK et ORBit Fichier: Client_hello_ns.java System.out.println( "Client>Resolving the object reference in naming ["+ name_service+ "]"); NameComponent nc = new NameComponent(name_service, ""); NameComponent path[] = { nc }; Interface_Hello hello = Interface_HelloHelper.narrow(ncRef.resolve(path)); // System.out.println("Client>calling the Hello service..."); String msg_received = hello.get_msg(); // System.out.println("Client>server returned the following message: "+ msg_received); *** 95
6.1 L utilisation de IOR avec JDK et ORBit L exécution «serveur écrit en Java et du client écrit en C» Exécution de orbit-name-server-2 : orbit-name-server-2 > name_service.ior Exécution de Server_hello_ns (Programme écrit en Java): make -f Makefile_java_hello_ns run_server java -classpath. corba.sample_a.server_hello_ns Server>starting server... Server>creating and initializing the ORB Server>getting reference to rootpoa Server>activating the POA Manager Server>Creating the servant Server>obtain the reference from the servant Server>getting the NameService IOR..../name_service.ior Executing server... 96
6.1 L utilisation de IOR avec JDK et ORBit L exécution «serveur écrit en Java et du client écrit en C» Exécution de client_hello_ns (Programme écrit en C):./hello-client_ns Client>starting client... Client>creating and initializing the ORB Client>reading the file 'name_service.ior' Client>getting the root naming context 'NameService' - from the file 'name_service.ior' Client>Resolving the object reference in naming 'Hello_server' Client>calling the Hello service... Client>server returned the following message: Hello world! my time is: 14:45:46:621 97
CORBA Conclusions 98
7. Conclusions CORBA est basé sur: Le modèle orienté objet; Un environnement de traitement ouvert et distribué; Une intégration de composants et la réutilisation. CORBA fournit : L accès aux services de manière uniforme; La découverte des ressources et des noms d objets uniformes; Des méthodes de détection d erreurs uniformes; Une politique de sécurité uniforme. 99
7. Conclusions CORBA présente des avantages importants pour les systèmes distribués comme: La transparence; La portabilité; L interopérabilité; L adaptabilité; La disponibilité; La stabilité. Il présente aussi des désavantages comme par exemple: La complexité; Le prix élevé; Une formation spécialisée pour les développeurs. 100
CORBA 101 Bibliographie
102 8. Bibliographie Livres: [Jean-Marc Geib 99] Jean-Marc Geib, Christophe Gransart, Philippe Merle, CORBA Des concepts à la pratrique, 2 édition, Dunod, Paris, 1999. [Robert Orfali 99] Robert Orfali, Dan Harkey et Jeri Edwards, Client/Serveur Guide de Survie, 3 édition, John Wiley&Sons, 1999. Spécifications : [OMG 02a] Common Object Request Broker Architecture : Core Specification, version 3.0.2, formal 02-12-02, December 2002. [OMG 99] OMG, C Language Mapping Specification, formal 99-07-35, June 1999. [OMG 02b] OMG, IDL to Java Language Mapping, v 1.2, formal 02-08-05, August 2002. Rapport Techniques: [CMU 97a] Carnegie Mellon University, Middleware1, CMU/SEI-97-HB-001, Software Engineering Institute Carnegie Mellon University 2, USA, 1997, pages 251-254. [CMU 97b] Carnegie Mellon University, Object Request Broker 2, CMU/SEI-97-HB-001, Software Engineering Institute Carnegie Mellon University, USA, 1997, pages 291-295. Sites Web : [DLopes] La page Web de LOPES (http://www.eseo.fr/~dlopes/course) 1,2, On-line available at: http://www.sei.cmu.edu/pub/documents/97.reports/pdf/97hb001.pdf Les specifications de l OMG are on-line available at: http://www.omg.org/technology/documents/spec_catalog.htm
MERCI de votre Attention! 103