Agent and Object Technology Lab Dipartimento di Ingegneria dell Informazione Università degli Studi di Parma. Distributed and Agent Systems RMI

Similar documents
Java RMI Activation: A running example We have the following classes: MyRemoteInterface: the remote interface. Client: the client that invokes a

Activation of remote objects

Activation of remote objects

JAVA RMI. Remote Method Invocation

Generic architecture

Object Interaction. Object Interaction. Introduction. Object Interaction vs. RPCs (2)

5.4. Events and notifications

JAVA RMI Java, summer semester

SUMMARY INTRODUCTION REMOTE METHOD INVOCATION

RMI. (Remote Method Invocation)

Remote Method Invocation

CS555: Distributed Systems [Fall 2017] Dept. Of Computer Science, Colorado State University

RMI (Remote Method Invocation) Over the year, there have been 3 different approaches to application development:

Remote Objects and RMI

DISTRIBUTED OBJECTS AND REMOTE INVOCATION

IBD Intergiciels et Bases de Données

CS 5523 Operating Systems: Remote Objects and RMI

Distributed Systems. 02r. Java RMI Programming Tutorial. Paul Krzyzanowski TA: Long Zhao Rutgers University Fall 2017

RPC and RMI. 2501ICT Nathan

RMI. Remote Method Invocation. 16-Dec-16

Distributed object component middleware I - Java RMI

Contents. Java RMI. Java RMI. Java RMI system elements. Example application processes/machines Client machine Process/Application A

Outline. EEC-681/781 Distributed Computing Systems. The OSI Network Architecture. Inter-Process Communications (IPC) Lecture 4

Distributed object component middleware I - Java RMI

Questions and Answers. A. RMI allows us to invoke a method of java object that executes on another machine.

Written by: Dave Matuszek

RMI Case Study. A Typical RMI Application

The UNIVERSITY of EDINBURGH. SCHOOL of INFORMATICS. CS4/MSc. Distributed Systems. Björn Franke. Room 2414

Distributed Systems. 5. Remote Method Invocation

Lecture 18 Inside Java RMI

Distributed Objects SPL/ SPL 201 / 0 1

Distributed Systems. 6. Remote Method Invocation. Werner Nutt

Distributed Systems. Distributed Object Systems 2 Java RMI. Java RMI. Example. Applet continued. Applet. slides2.pdf Sep 9,

How are classes loaded into the Java Virtual Machine (JVM)? from the local file system (CLASSPATH). by an instance of ClassLoader

Verteilte Systeme (Distributed Systems)

RMI Example RMI. CmpE 473 Internet Programming RMI

Remote Method Invocation Benoît Garbinato

Remote Method Invocation. Benoît Garbinato

Last Class: Network Overview. Today: Distributed Systems

presentation DAD Distributed Applications Development Cristian Toma

Introduction & RMI Basics. CS3524 Distributed Systems Lecture 01

A Typical RMI Application

Chapter 5 Distributed Objects and Remote Invocation

Distributed Computing

A Typical RMI Application. Case Study

Remote Method Invocation

Distributed Software Systems

Distributed Programming in Java. Distribution (2)

Lecture VI: Distributed Objects. Remote Method Invocation

Distributed Systems COMP 212. Lecture 10 Othon Michail

CSci Introduction to Distributed Systems. Communication: RPC In Practice

55:182/22C:182. Distributed Application Frameworks Java RMI, CORBA, Web Services (SOAP)

Desarrollo de Aplicaciones en Red RMI. Introduction. Considerations. Considerations. RMI architecture

03 Remote invocation. Request-reply RPC. Coulouris 5 Birrel_Nelson_84.pdf RMI

Java. Java. Java. Java. java. java. test.java. smalltalk. java. static. java virtual machine. java. C++ virtual

Java. Java. Java. Java. java. smalltalk. java. java virtual machine. java. C++ virtual. interface C++ Operator overloading Template C++ test.

Remote Method Invocation

JAC444 - Lecture 11. Remote Method Invocation Segment 2 - Develop RMI Application. Jordan Anastasiade Java Programming Language Course

REMOTE METHOD INVOCATION INTRODUCTION TO RMI, A JAVA API FOR RPC-STYLE INVOCATION OF REMOTE OBJECT METHODS

Applications. RMI, RPC and events. Request reply protocol External data representation. Operating System

Remote Procedure Call

Info 408 Distributed Applications programming 2 nd semester of Credits: 5 Lecturer: Antoun Yaacoub Ph.D.

Modulo II Socket, RMI e Corba

COMP 6231: Distributed System Design

Course Snapshot. The Next Few Classes. Parallel versus Distributed Systems. Distributed Systems. We have covered all the fundamental OS components:

Grid Computing. Java Remote Method Invocation (RMI) RMI Application. Grid Computing Fall 2006 Paul A. Farrell 9/5/2006

Course Snapshot. The Next Few Classes

Chapter 4: Processes. Process Concept. Process State

RPC flow. 4.3 Remote procedure calls IDL. RPC components. Procedure. Program. sum (j,k) int j,k; {return j+k;} i = sum (3,7); Local procedure call

Communication Basics, RPC & RMI. CS403/534 Distributed Systems Erkay Savas Sabanci University

DISTRIBUTED COMPUTING

Are Sockets a Good Programming Paradigm? EDA095 Remote Method Invocation. The Remote Procedure Call Model. The Remote Procedure Call Architecture

Network. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Distributed Objects and Remote Invocation. Programming Models for Distributed Applications

Remote Method Invocation in Java

Are Sockets a Good Programming Paradigm? EDA095 Remote Method Invocation. The Remote Procedure Call Model. The Remote Procedure Call Architecture

Chapter 15: Distributed Communication. Sockets Remote Procedure Calls (RPCs) Remote Method Invocation (RMI) CORBA Object Registration

Lab 2 : Java RMI. request sayhello() Hello interface remote object. local object. response "Hello world"

Java Remote Method Invocation Specification

CC755: Distributed and Parallel Systems

Distributed Systems. The main method of distributed object communication is with remote method invocation

Firewall Issues. The possible scenarios: the RMI client, the server, or both can be operating from behind a firewall

EDA095 Remote Method Invocation

EDA095 Remote Method Invocation

Object-Oriented Distributed Technology

Distributed Systems. Communication (2) Lecture Universität Karlsruhe, System Architecture Group

Serialisa(on, Callbacks, Remote Object Ac(va(on. CS3524 Distributed Systems Lecture 03

Distributed Information Systems

Distributed Systems. Communication (2) Schedule of Today. Distributed Objects. Distributed Objects and RMI. Corba IDL Example

Remote Procedure Calls

Lecture 5: RMI etc. Servant. Java Remote Method Invocation Invocation Semantics Distributed Events CDK: Chapter 5 TVS: Section 8.3

What is Serialization?

Chapter 4 Remote Procedure Calls and Distributed Transactions

Communication and Distributed Processing

Programming with RMI Reminder

4:40pm - 6:10pm (90 min)

Agent and Object Technology Lab Dipartimento di Ingegneria dell Informazione Università degli Studi di Parma. Distributed and Agent Systems

Distributed Objects. Remote Method Invokation

Reflection/RMI 4/28/2009

CSE 331. Memento Pattern and Serialization

Transcription:

Agent and Object Technology Lab Dipartimento di Ingegneria dell Informazione Università degli Studi di Parma Distributed and Agent Systems RMI Prof. Agostino Poggi

What is RMI? Its acronym means Remote Method Invocation Supports communication between different Java virtual machines, potentially across the network Allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine Uses the same syntax and semantics used for non-distributed programs 2

RMI Features Locate remote objects Applications either can obtain references to remote objects from a naming facility, the RMI registry, or can pass and return remote object references as part of other remote invocations Communicate with remote objects Details of communication handled by RMI To the programmer, remote communication looks similar to regular Java method invocations Load class definitions for remote objects RMI provides mechanisms for loading an object's class definitions as well as for transmitting an object's data 3

Remote Interface RMI does not have a separate IDL RMI is used between Java virtual machines Java already includes the concept of interfaces An Interface to be a remote interfaces needs to extend the interface Java.rmi.Remote All methods in a remote interface must be declared to throw the java.rmi.remoteexception exception 4

Remote Class A class to be a remote class needs to implement a remote interface Most often a remote class also extends the library class java.rmi.server.unicastremoteobject This class includes a constructor that exports the object to the RMI system when it is created, thus making the object visible to the outside world A common convention is to name the remote class appending Impl to the name of the corresponding remote interface 5

Remote Method A client can request the execution of all those methods that are declared inside a remote interface A client request can contain some parameters Parameters can be of three types: Atomic types Objects Remote objects 6

Parameter Passing Atomic Type Local Object Remote Object Local Call Call by Value Call by Reference Call by Reference Remote Call Call by Value Call by Value Call by Reference 7

Serialization Take any object and turns it into a sequence of bytes that can be stored into a file and later can be fully restored into the original object A serializable object either must implement the java.io.serializable interface or must extend a class that extends it Primitive data are serializable, but static and transient data are not serialized Static data are not in the object state Transient data are data of which serialization is not wanted 8

Serialization public class ProductDescription implements Serializable { public static int counter; private string name; private float price; private transient Image image; private Geometry geo; } Geometry must be serializable 9

Write an Object Create a file to store the object OutputStream os = new FileOutputStream( c:\myclass ); Create ObjectOutputStream ObjectOutputStream oos = new ObjectOutputStream(os); Write object into the file MyClass instance = new MyClass();. oos.writeobject(instance); Close file and ObjectOutputStream oos.close(); os.close(); 10

Read an Object Open the file that stores the object InputStream is = new FileInputStream( c:\myclass ); Create ObjectInputStream ObjectInputStrem ois = new ObjectInputStream(is); Read the object into the file MyClass instance = (MyClass) ois.readobject(); Close file and ObjectOutputStream ois.close(); is.close(); 11

Reflection Reflection enables Java code to: Discover information about the fields, methods and constructors of loaded classes Use reflected fields, methods, and constructors to operate on the corresponding class instances RMI uses reflection for the execution of a remote call 12

java.lang.class Get a class Class c = Class.forName( class qualified name") ; Get its interfaces and superclass Class[] is = c.getinterfaces(); Class s = c.getsuperclass(); Get its public constructors Constructor[] cs = c.getconstructors(); Get its (public and inherited) fields and methods Field[] fs = c.getfields(); Method[] ms = c.getmethods(); Create an instance c.newinstance(); 13

java.lang.constructor Get its name String n = c.getname(); Get the classes declaring the constructor Class[] cs = c.getdeclaringclass(); Get its modifiers int[] ms = c.getmodifiers(); // see java.lang.reflect.modifier Get its parameter types Class[] ps = c.getparametertypes(); Create a class instance Object[] args = new Object[] { } ; c.newinstance(args); 14

java.lang.field Get itsname String n= f.getname(); Get its type Class c = f.gettype(); Get the classes declaring the field Class[] cs = t.getdeclaringclass(); Get its modifiers int[] ms = t.getmodifiers(); // see java.lang.reflect.modifier Get and set its value (v) for an object (o) Object v = f.get(o) ; // getboolean, getint, f.set(o, v); // setboolean, setint, 15

java.lang.method Get its name String n = m.getname(); Get the classes declaring the method Class[] cs = m.getdeclaringclass(); Get its modifiers int[] ms = m.getmodifiers(); // see java.lang.reflect.modifier Get its parameter types Class[] ps = m.getparametertypes(); Class[] r = m.getreturntype(); Get the method of an object (o) Object[] args = new Object[] { } ; c.invoke(o, args); 16

Application Components Stub makes RMI transparent to clients by behaving like a local object Communication module implements the request reply protocol Dispatcher receives request message from communication module and select the method in the skeleton Request Reply Servant Client Server Remote reference module translates between local and remote object references and creates remote object references Skeleton implements the remote interface of the servant 17

Remote Call Execution Stub has to marshal information about a method and its arguments into a request message An object of class Method An array of objects for the method s arguments The dispatcher Obtains the remote object reference Unmarshals the Method object and its arguments Calls the invoke method on the object reference and array of arguments values Marshals the result or any exceptions into the reply message 18

RMI Stack Client Server Stub Remote Reference Transport Skeleton Remote Reference Transport 19

Stub and Skeleton Layer Stub Marshals call parameters Sends them to the server Unmarshals return parameters Returns them to the client program Skeleton Reads the parameters for the method call from the link Makes the call to the remote service implementation object Accepts the return value Writes the return value back to the stub 20

Remote Reference Layer Client Side Knows if the remote object (still) exists Knows where to locate server holding the remote object Server Side Knows if the local object exists Knows where to locate the local implementation 21

Transport Layer Manages connection between Java Virtual Machines Used over the network and on the local host There is a messaging protocol implemented over TCP/IP 22

Application Components Registry Server Client Web Server 23

RMI Registry Runs on each machine, which hosts remote objects and accepts requests for services Allows registration operations and retrieval of remote objects Registration operation are only possible through servers running on the same machine of the registry Its default TCP/IP port is 1099 24

java.rmi.registry.registry void bind (String name, Remote obj) Registers a remote object by name, but if the name is already in the registry an exception is thrown void rebind (String name, Remote obj) Registers the identifier of a remote object by name void unbind (String name, Remote obj) Removes a binding Remote lookup(string name) Looks up a remote object by name String [] list() Returns the names bound in the registry 25

java.rmi.registry.locateregistry Registry createregistry (int port) Creates and returns an embedded RMI registry listening on a specific port Registry getregistry () Returns a reference to a local registry running listening on the default registry port (1099) Registry getregistry (int port) Returns a reference to a local registry running listening on a specific port Registry getregistry (int port, String host) Returns a reference to a registry running on a specific host and listening on a specific port 26

Remote Object Binding Explicit by using registry methods Server binds/rebinds name with the rmiregistry Client looks up name with the rmiregistry Implicit by receiving a remote object reference 27

Remote Object Code import java.rmi.remote; import java.rmi.remoteexception; public interface MessageWriter extends Remote { void writemessage(string s) throws RemoteException; } import java.rmi.remoteexception; import java.rmi.server.unicastremoteobject; public class MessageWriterImpl extends UnicastRemoteObject implements MessageWriter { public MessageWriterImpl() throws RemoteException { } public void writemessage(string s) throws RemoteException { System.out.println(s); } } 28

Server Program Code import java.rmi.naming; creates a remote object public class HelloServer { public static void main(string [] args) throws Exception { MessageWriter service = new MessageWriterImpl(); MessageWriter stub = (MessageWriter) UnicastRemoteObject.exportObject(service); Registry registry = LocateRegistry.getRegistry(); registry.rebind( messagewriter, stub); } } Publishes a remote reference to that object with external name MessageWriter 29

Client Program Code import java.rmi.naming; Looks up a reference to a remote object with external name MessageWriter public class HelloClient { public static void main(string [] args) throws Exception { Registry registry = LocateRegistry.getRegistry(); MessageWriter service = (MessageWriter) registry.lookup( MessageWriter ); service.writemessage( Hello, other world ) ; } } Invokes the remote method writemessage on server 30

Compiling and Running javac *.java rmic MessageWriterImpl MessageWriterImp_Skel.class MessageWriterImp_Stub.class start rmiregistry java HelloServer java HelloClient 31

Distributed Garbage Collection In Java, unused objects are garbage collected Java Virtual Machine automatically destroys objects that are not referenced by anyone RMI implements a distributed garbage collector The aim of a distributed garbage collector are: Retain the local and remote objects when it is still be referenced Collect the objects when none holds reference to them RMI garbage collection algorithm is based on reference counting 32

Distributed Garbage Collection (2/2) Server Counts the number of remote references to each remote object it exports When there are no more local and remote references to the object, the object is destroyed Client should notify when it no longer uses remote references Each remote reference has an associated lease time Client renews the lease on the used references When all leases expire, the object can be destroyed Client must be prepared to deal with disappeared objects 33

Explicit Notification import java.rmi.server.unicastremoteobject; Import java.rmi.server.unreferenced; public class RemoteServerImpl extends UnicastRemoteObject implements MyRemoteInterface, Unreferenced { public RemoteServerImpl() { super();... //allocate resources }... public void unreferenced() { //deallocate resources here } } E.g., network and database connections can be released 34

Remote Class RMI can exchange objects through serialization, but serialized objects do not contain the code of the class they implement In fact, de-serialization process can be completed only if the client has available the code of the class to be de-serialized Class code can be provided by manually copy implementation class files to the client A more general approach is to publish implementation class files on a Web Server 35

Dynamic Class Loading Remote object's codebase is specified by setting the java.rmi.server.codebase property java Djava.rmi.server.codebase=http://www/ HelloServer java Djava.rmi.server.codebase=http://www/myStub.jar HelloServer Client requests a reference to a remote object Registry returns a reference (the stub instance) to the requested class If the class definition for the stub instance is found locally in the client's CLASSPATH Then it loads the class definition Else it retrieves the class definition from the remote object's codebase 36

Security In Java a security manager checks if an untrusted code may have access to some system resources A policy defines which class has the right to do what depending on the class identity (i.e., its URL and its certificates) A protection domain is a set of permissions established by the current policy A security manager delegates all decisions to an access controller that decides according to: the permissions of the protection domain the checking of the sequence of call for resource grant/denial 37

Security in RMI Systems (1/2) Security is a serious concern since executable code is being downloaded from a remote location RMI normally allows the loading of code only from the local CLASSPATH RMI allows the loading of code from a remote location only if a suitable security manager is set and an appropriate security policy is defined RMI clients usually need to install security manager because they need to download stub files RMI servers usually do not need it, but it is still good practice to install it anyway 38

Security in RMI Systems (2/2) A security manager can be set as follows: System.setSecurityManager(new RMISecurityManager()) ; A security policy can be defined in a plain text file: grant codebase { permission java.security.allpermission }; grant codebase http://www/ { permission java.security.allpermission }; And assigned to the client as follows: java Djava.security.policy=rmi.policy HelloClient 39

Activatable Objects Activatable objects are remote objects that are created and execute "on demand", rather than running all the time Activatable objects are important Remote objects could fail or could be shut down inadvertently or intentionally Remote objects use a set of resources for all their life even if they are used few times 40

Remote Object Code import java.rmi.remote; import java.rmi.remoteexception; public interface MessageWriter extends Remote { void writemessage(string s) throws RemoteException; } import java.rmi.remote; import java.rmi.activation.activatable; public class MessageWriterImpl extends Activatable implements MessageWriter { public MessageWriterImpl(ActivationID id, MarshalledObject data) throws RemoteException { super(id, 0); } public void writemessage(string s) throws RemoteException { System.out.println(s); } } 41

Setup Main Method Duties Install security manager for the ActivationGroup of the Java virtual machine. Set a security policy Create an ActivationGroupDesc instance Register it and get an ActivationGroupID Create an ActivationDesc instance Register it with rmid Bind or rebind the remote object instance with its name Exit the system 42

Setup Main Method Code public static void main(string[] args) throws Exception { System.setSecurityManager(new RMISecurityManager()); Properties props = new Properties(); props.put("java.security.policy", "/myrmi/rmi.policy"); ActivationGroupDesc.CommandEnvironment ace = null; ActivationGroupDesc eg = new ActivationGroupDesc(props, ace); ActivationGroupID agi = ActivationGroup.getSystem().registerGroup(eg); String location = "file:/myrmi/"; MarshalledObject data = null; ActivationDesc desc = new ActivationDesc(agi, MessageWriterImpl, location, data); MessageWriter server = (MessageWrite) Activatable.register(desc); Naming.rebind( messageservice, server); System.exit(0); } 43

Compiling and Running javac *.java rmic MessageWriterImpl start rmiregistry start rmid J-Djava.security.policy=rmi.policy java -Djava.security.policy=rmi.policy HelloSetup java -Djava.security.policy=rmi.policy HelloClient 44

Callbacks A callback server s action of notifying clients about an event implementation Improve performance by avoid constant polling Delivery information in a timely manner In a RMI based system callbacks are implements as follows: Client create a remote object Client pass the remote object reference to the server Whenever an event occurs, the server calls the client via the remote object 45