Java RMI et Applications...

108
24/03/09 P. MOLLI, MC UHP, Nancy1 1 Java RMI et Applications Distribuées Remote Method Invocation Pascal Molli, Maître de Conférence, Université Henri Poincaré, Nancy 1

Transcript of Java RMI et Applications...

24/03/09 P. MOLLI, MC UHP, Nancy1 1

Java RMI et Applications Distribuées

Remote Method InvocationPascal Molli, Maître de Conférence, Université Henri

Poincaré, Nancy 1

24/03/09 P. MOLLI, MC UHP, Nancy1 2

Applications Distribuées

● Distribution des données● Données distribuées traitement centralisé (Ex:

Syndication, Mashup, Semantic web)● Distribution du contrôle

● Données centralisées, contrôle distribué (Ex : Grid and data en NFS)

● Distribution des utilisateurs● Données et contrôle centralisé, utilisateurs

distribués (Ex : Concentrateur terminal, Browser Web)

● Ex: BD distribuées, Grid computing, P2P systems, Web, Cloud Computing, Clusters...

24/03/09 P. MOLLI, MC UHP, Nancy1 3

Problèmes généraux

● Tolérance aux pannes, Latence (reliability, fault-tolerance)● Un serveur participant à l ’application crash.. ● Un serveur raconte n ’importe quoi● Un serveur n ’est plus atteignable (mais n ’est pas

crashé) et le redevient…● Un serveur est extrémement lent● Atomicité dans les applications réparties...

24/03/09 P. MOLLI, MC UHP, Nancy1 4

Problèmes généraux

● Passage à l’échelle (scalability)● ça marche pour 1 utilisateur et pour 10000 ?● ça marche pour un objet et pour 1000000 ?● Ça marche pour 1 site et pour 1000 ??

● Ex: Construire un serveur E-Commerce résistant à 1000 000 utilisateurs simultanés ?

● Application serveur: pooling, cache, réplication, duplication, monitoring, load-balancing...

24/03/09 P. MOLLI, MC UHP, Nancy1 5

Problèmes généraux

● Nommage (naming):● Un objet = Un Id + Un état + Un

comportement● Appli non répartie = Nommage géré par le

langage (référence) ou l ’OS (addressage)● Appli répartie = nommage explicite ?

Dynamique ?● Ex: Url, DNS, JNDI, X500, LDAP, modèle à

espace de tuple, mémoires distribuées ...

24/03/09 P. MOLLI, MC UHP, Nancy1 6

Problèmes généraux

● Intégration de l ’existant (legacy)● Connexion sur toutes les ressources de

l ’entreprise● Facturation, Gestion de Stock, Workflow…● Intéropérabilité● Transactions réparties…

24/03/09 P. MOLLI, MC UHP, Nancy1 7

Problèmes généraux

● Déploiement, Administration, Monitoring● Tout est prêt : Comment j ’installe tous mes

composant logiciels sur mes différents serveurs et clients ?

● Je change mon architecture physique en exploitation

● Je change un nom de serveur, ou j ’en ajoute un… je recompile tout ? Je redéploie tout ? Ou je peux configurer le déploiement ?

24/03/09 P. MOLLI, MC UHP, Nancy1 8

Problèmes généraux

● Sécurité● Confidentialité

● Intégrité● Droits d’accès,

● Authentification

– Identification partenaire– Non-répudiation– Messages authentifiés

● Attaques, Pare-feux...

24/03/09 P. MOLLI, MC UHP, Nancy1 9

Problème généraux

● Security/Logging ● How many people use your server?● How will you know if someone is trying to hack into your

server?● How will you know what they did?● If something goes wrong in the server how will you know? How

will you determine what went wrong?● How will you know if a particular client program has trouble

connecting to your server?● Servers need to log client access

Source : Withney

24/03/09 P. MOLLI, MC UHP, Nancy1 10

Problèmes généraux

● Disponibilité (availability)● Un système occupé à faire autre chose (par exemple

gérer la tolérance aux fautes) n ’est pas disponible !● Ex : serveur mono-thread● 2 appels simultanés sur un même objet distants ?

– Sérialisé ?– Parallèle ?– Différentes politiques ?

24/03/09 P. MOLLI, MC UHP, Nancy1 11

Problèmes généraux

● Développement, génie logiciel:● Outils pour gérer

– Conception– Déploiement– Débogage !!!!

● Simuler : comment tester un système P2P avant de le lancer ??

24/03/09 P. MOLLI, MC UHP, Nancy1 12

Problèmes Généraux

● Coordination: Communication + Synchronisation+ données partagées● Synchronisation

– Mécanisme élémentaires : Messages, événements...– Transaction réparties– Workflow

● Communication– Synchrone, asynchrone, flots discrets ou continus

● Information partagées– Données centralisées, réparties, dupliquées (cohérence des

données)

Source : Krakoviac [CAR99]

24/03/09 P. MOLLI, MC UHP, Nancy1 13

Modèle d ’exécution...● Socket !● Modèle Client-Serveur (Smart Client)

● (RPC, RMI, Corba, Servlet, SOAP/REST/Web services…)● Modèle 3-Tiers (Stateless Client, Web application)

● Modèle N-Tiers (Application server, forward to enterprise Service)

● Modèle de communication par messages ● MOM, Message oriented middleware, ● Queue de messages

● Modèle de communication par événements● publish/subscribe, push/pull, JMS

● Modèle à agents mobiles● Agglet, Voyager

● Modèle à mémoire « virtuelles » partagées.● Modèle à espace de tuples(JavaSpaces)● Modèle à objets dupliqués

● Modèles P2P !!!!

24/03/09 P. MOLLI, MC UHP, Nancy1 14

Java RMI : Généralités

● Objectifs : écrire des applications distribuées.

● D’autres systèmes : Corba, Dcom, Entreprise Java Beans (EJB), Web Services...

● RMI : Conçue comme une extension du langage; Un objet sur une JVM peut avoir une référence sur un autre dans une autre JVM.

24/03/09 P. MOLLI, MC UHP, Nancy1 15

Java RMI : généralités.

MyRemoteObject o = …o.myMethod

Celui là !

24/03/09 P. MOLLI, MC UHP, Nancy1 16

Problèmes :

● Nommage !● Passage de paramêtres, valeur de retours...● Extension du langage... (Gc, Objets non

sérialisables, Passage par copie..., Type safety)● Pannes...● Sécurité... (Class Loading...)● Concurrence...

P. Molli 17

Premier Exemple..

● Une table des highscores en distant...● Coté serveur : Pattern proxy et

nommage...● Coté client : récupération du proxy par

le service de nommage...● Les paramètres sont passés par copies

(si pas remote...)

24/03/09 P. MOLLI, MC UHP, Nancy1 18

24/03/09 P. MOLLI, MC UHP, Nancy1 19

Y'a pu ka

● Je code le diagramme précédent● (en faisant toutes les bêtises possibles ;))

24/03/09 P. MOLLI, MC UHP, Nancy1 20

RMI

● RMI = Proxy + Serialization...

24/03/09 P. MOLLI, MC UHP, Nancy1 21

Stub : L'objet proxy

● Le voir :● rmic --keep...

P. Molli 22

Proxy Pattern

Provide a surrogate or placeholder for another object to control access to it.

P. Molli 23

Proxy Example

P. Molli 24

Proxy Structure

P. Molli 25

Proxy benefits

■ remote proxy can hide the fact that an object resides in a different address space.

■ A virtual proxy can perform optimizations such as creating an object on demand.

■ Both protection proxies and smart references allow additional housekeeping tasks when an object is accessed.

P. Molli 26

class ProxyExample { public static void main(String[] args) { List<Image> images = new ArrayList<Image>(); images.add( new ProxyImage("HiRes_10MB_Photo1") ); images.add( new ProxyImage("HiRes_10MB_Photo2") ); images.add( new ProxyImage("HiRes_10MB_Photo3") );

images.get(0).displayImage(); // loading necessary images.get(1).displayImage(); // loading necessary images.get(0).displayImage(); // no loading necessary; already done // the third image will never be loaded - time saved! }}

P. Molli 27

Reflection example

P. Molli 28

Reflection example

public class Main {public static void main(String args[]) throws Exception { Point p = new Point(3,4); Cercle c = new Cercle(p,6); XMLEncoder e = new XMLEncoder(new BufferedOutputStream( new FileOutputStream(args[0]))); e.writeObject(c); e.close(); System.out.println(c); }}

P. Molli 29

Reflection example<?xml version="1.0" encoding="UTF-8"?><java version="1.4.2_03" class="java.beans.XMLDecoder"> <object class="Cercle"> <void property="point"> <object class="Point"> <void property="x"> <int>3</int> </void> <void property="y"> <int>4</int> </void> </object> </void> <void property="radius"> <int>6</int> </void> </object></java>

P. Molli 30

Reflection example

public class Reread {public static void main(String args[]) throws Exception { XMLDecoder d = new XMLDecoder(new BufferedInputStream(new

FileInputStream(args[0]))); Cercle c = (Cercle)d.readObject(); d.close();

System.out.println(c); }}

P. Molli 31

Reflection example

P. Molli 32

P. Molli 33

Reflection structure

P. Molli 34

Reflection example

Primitive

Type…

P. Molli 35

SuperType

Pointer? Or not

Field…

P. Molli 36

Reflection known Uses

CLOS : generic function and generic function invocation

MIP: run-time type information system for C++

Pgen: persistence component for C++ based on MIP

Ole2.0, CORBA (dynamic invocation)…

P. Molli 37

Reflection benefits

No explicit modification of source code Changing a software is easy: no need

for visitors, factories and strategies patterns

Support for many kind of change

P. Molli 38

Reflection Liabilities

Modification at the meta-level can cause damage.

Increased number of component Lower efficiency Not all potential changes supported (only

those supported by the MOP) Not all language support reflection

P. Molli 39

Creating remote object on client

● You can create remote objects on any jvm● You can send a remote object as a

parameter of a remote call

24/03/09 P. MOLLI, MC UHP, Nancy1 40

HighScore MVC + RMI

● Refactor Previous Example with Observer Pattern...

● Remote object can be passed without binded in the Naming Service...

● Passing remote object...● Remote objects are present on both

sides...

24/03/09 P. MOLLI, MC UHP, Nancy1 41

P. Molli 42

Observer

One-to-many dependency between objects: change of one object will automatically notify observers

P. Molli 43

Observer: Applicability

A change to one object requires changing an unknown set of others

Object should be able to notify others that may not be known at the beginning

P. Molli 44

Observer: Structure

P. Molli 45

Observer: Consequences

Abstract coupling between subject and observer

Support for broadcast communication Hard to maintain

P. Molli 46

P. Molli 47

From observer to remote observer

● We can now refactor the previous application to create observer on « client ».

P. Molli 48

24/03/09 P. MOLLI, MC UHP, Nancy1 49

24/03/09 P. MOLLI, MC UHP, Nancy1 50

Create remote object...

● Cannot call 'new' on remote JVM● Need factories to create object remotely.

24/03/09 P. MOLLI, MC UHP, Nancy1 51

s

P. Molli 52

Passage des paramètres !!

● Les objets remote sont passés par référence

● Les objets non-remote sont passés par copie

● Que se passe-t-il si je met un objet remote comme variable d'instance d'un objet non-remote ??

P. Molli 53

P. Molli 54

P. Molli 55

Passage paramètres

● Voir site web pour code et démo...

P. Molli 56

Building a server...

● I want to connect...● register an account● login...● and edit my profile...● How to do that with RMI...??

P. Molli 57

Building a server

● Without « cookie » at all ● Security issues

● With « cookies »● can do better with RMI

● With Session remote object + Abstract factory...

P. Molli 58

P. Molli 59

Session factory...

● Voir site WEB pour code et demo...

P. Molli 60

Bank example… A basic bank system:

– 1 bank, n Account. – Each account belong to 1 client.– Each account is credited by an amount a money.

Bank functions– Withdrawal on a account, Credit an account,

Transfer money from one account to another…

P. Molli 61

Naive solutionBank

addAccount(String name, int amount) : Accountwithdrawal(int ida, int amount) : voiddeposit(int ida, int amout) : voidtransfer(int ida1, int ida2, int amount) : voidgetAccount(int ida) : Account

Accountint amountint ida

withdraw(int a)deposit(int a)Account(int ida)

CustomerString name;int idc

Client(String name, int idc)ida : int

11..n 1ida : int

1..n

ida : int

1

0..n

1

ida : int

0..n

1

0..n

idc : intidc : int

1

0..n

P. Molli 62

Naive Solution1 : Account : client : Bank 2 : Account

transfer( 1,2,100 )

withdrawal(1,100 )

withdraw( 100)

deposit(2,100 )

deposit( 100)

getAccount(1 )

getAccount(2 )

P. Molli 63

Applying Command Pattern…

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

P. Molli 64

Command Example

P. Molli 65

Command Example

P. Molli 66

Command Structure

P. Molli 67

Command Structure

P. Molli 68

Command Consequences

■ Command decouples the object that invokes the operation from the one that knows how to perform it.

■ Commands are first-class objects. They can be manipulated and extended like any other object.

■ It's easy to add new Commands, because you don't have to change existing classes.

P. Molli 69

Applying Command Pattern

Account

int amountint ida

withdraw(a : int)deposit(a : int)

Customer

String name;int idc

Client(String name, int idc)

ida : int11..n 1

ida : int1..n

Withdrawalida : intamount : int

do() : voidundo:void()

Command

b : banque

do() : voidundo() : voidCommand(Bank b)

Bank

getAccount(int ida) : AccountExecute(cmd : Command) : void

ida : int

1

0..n

1

ida : int

0..n

idc : int1

0..n

1idc : int

0..n

+receiver

Deposit

ida : intamount : int

do() : voidundo: void()

Transfer

ida1 : intida2 : intamount : int

do() : voidundo:void()opname()Transfer(ida1 : int, ida2 : int, int a, Bank b)

P. Molli 70

Applying Command Pattern : client t : Transfer : Bank 1 : Account 2 : Account

Transfer(1,2,100 )

Execute(t )

do( )

getAccount( 1)

withdraw( 100)

getAccount( 2)

deposit( )

P. Molli 71

Apply Command Pattern +RMI

● How to combine RMI + Command Pattern ??

● What class

P. Molli 72

Remote Bank

● Bank + RemoteObserver + Command ...● Compare Rmi+Factory vs

Rmi+Command...

P. Molli 73

P. Molli 74

P. Molli 75

P. Molli 76

DGC

● Mark and sweep vs comptage de références...

● Gérer les pannes...

24/03/09 P. MOLLI, MC UHP, Nancy1 77

Distributed Garbage Collector.

● Comment libérer les objets référencés dans le serveur par des remote-références ?

● PB : ● Le client n ’utilise plus● Le client se crash (pour une longue période● Le client se crashe et réapparait (gloups !)

24/03/09 P. MOLLI, MC UHP, Nancy1 78

Distributed Garbage Collector

● Le serveur maintient une liste de références remote.

● Cette référence remote est prêtée par le serveur au client pour un temps pré-défini (10 minutes par défaut).

● Le client peut renouveller sa période de prêt en appelant la méthode dirty() sur le serveur.

24/03/09 P. MOLLI, MC UHP, Nancy1 79

RMI + DGC

● Voir site WEB pour example...● DGC et objets session...

24/03/09 P. MOLLI, MC UHP, Nancy1 80

Loader les classes et déploiement...

● Le codebase !!● Dynamic Loading of classes...

24/03/09 P. MOLLI, MC UHP, Nancy1 81

RMI et Security Manager !

● Si des classes doivent être téléchargées par le réseau, elles doivent obéir aux politiques de sécurité

● Par ex: Pas d ’actions sensibles (accès systèmes) et téléchargement à partir de sources de confiance (applet host par exemple).

● Une politique pré-définie: le RMISecurityManager...

24/03/09 P. MOLLI, MC UHP, Nancy1 82

Security Manager

● Si aucun Security Manager n ’est installé● Tous les chargement de .class doivent se

faire à partir du CLASSPATH local.● Mauvais pour le déploiement

d ’application distribuées (problème fondamental…)

24/03/09 P. MOLLI, MC UHP, Nancy1 83

Policies

● Un fichier de policies doit être fourni:grant signedBy "signer_names", codeBase "URL" {

permission permission_class_name "target_name", "action", signedBy "signer_names";

....

permission permission_class_name "target_name", "action", signedBy "signer_names";

}; java -Djava.security.policy=policy …

24/03/09 P. MOLLI, MC UHP, Nancy1 84

Policies…grant signedBy "Duke" { permission java.io.FilePermission "/tmp/*", "read,write"; 

};

grant {

   permission java.security.AllPermission;

};

grant signedBy "sysadmin", codeBase "file:/home/sysadmin/*" { 

permission java.security.SecurityPermission "Security.insertProvider.*"; 

permission java.security.SecurityPermission "Security.removeProvider.*"; 

permission java.security.SecurityPermission "Security.setProperty.*"; }; 

24/03/09 P. MOLLI, MC UHP, Nancy1 85

Problème de typage !

● Attention : Les classes communes aux différentes machines doivent être identiques

● Vérifié par Java à l ’exécution avec des VID (version ID)

● Problème de déploiement (source d ’erreur classique)

24/03/09 P. MOLLI, MC UHP, Nancy1 86

Class Loader et Déploiement

● java -Djava.rmi.server.codebase=http://host/rmiclasses/ LoadClient

import java.rmi.RMISecurityManager;import java.rmi.server.RMIClassLoader;public class LoadClient { public static void main() { System.setSecurityManager(new RMISecurityManager()); try { Class cl = RMIClassLoader.loadClass("myclient"); Runnable client = (Runnable)cl.newInstance(); client.run(); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); e.printStackTrace(); } }}

24/03/09 P. MOLLI, MC UHP, Nancy1 87

RMI and classloading...

24/03/09 P. MOLLI, MC UHP, Nancy1 88

RMI dynamic loading

● Voir example sur site web...● rmicodebase 1

● Lancer Server● Lancer le client ailleurs...● Comment configurer ??

● rmicodebase 2● Lancer le client avec le generic loader...

24/03/09 P. MOLLI, MC UHP, Nancy1 89

RMI and Activation...

24/03/09 P. MOLLI, MC UHP, Nancy1 90

RMI and concurrent calls...

● Attention ! A priori un objet remote peut-être accédé par plusieurs client !

● Auquel cas la JVM du serveur démarre un thread par client (distant)

● Attention à vos « synchronized ».

24/03/09 P. MOLLI, MC UHP, Nancy1 91

Conclusion

● RMI● Scalability ?● Legacy ?● Security ?● Fault-tolerance ?●

P. Molli 92

Broker

Used to structure distributed software systems with decoupled components that interact by remote service invocation.

A broker component is responsible for coordinating communication, such as forwarding request, as well as for transmitting result and exception.

P. Molli 93

Broker example

P. Molli 94

Broker structure

P. Molli 95

Broker Structure

P. Molli 96

Broker Structure

P. Molli 97

Broker Structure

P. Molli 98

Broker Structure

P. Molli 99

Broker Variants

Direct Communication Broker System:– Direct link to server

Message Passing Broker System– Focus on transmission of data. Type of the

message determine the behavior of the broker… Trader System :

– service identifiers are used to access server functionality. Request can be forwarded to more than one server…

Callback broker system: event driven…

P. Molli 100

Known Uses

CORBA IBM SOM/DSOM Microsoft Ole 2.x WWW ATM-P: Message passing broker.

Telecommunication switching system based on ATM.

P. Molli 101

Broker benefits

Location transparency Changeability and extensibility of

components Portability of a broker system (Layered) Interoperability between brokers (bridge) Reusability (of services)

P. Molli 102

Broker Liabilities

Restricted efficiency (indirection layer) Lower Fault tolerance: fault a broker or a

server… replication of components… Testability:

– Of components (benefits)– Of application (liabilities)

P. Molli 103

P. Molli 104

Conclusion

● Learning path:● RMI...● Ensuite Servlets (Client/server

WEB+WebApp)● Ensuite WebServices ● Ensuite SOA (Service Oriented Architecture) ● Ensuite ESB, SCA...

P. Molli 105

Conclusion

● Aspects algorithmique distribuée● Tolérance aux fautes● Réplication● Transactions distribuées● (voir birmann et tanenbaum...)