Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
AOT
LAB
Agent and Object Technology Lab
Dipartimento di Ingegneria dell’Informazione
Università degli Studi di Parma
Distributed and Agent Systems
RMI
Prof. Agostino Poggi
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
Application Components
Stub makes RMI
Dispatcher receives request
Communication
module
transparent to
message from communication
implements
the
request
clients by behaving
module and select the method
reply
protocol
like a local object
in the skeleton
Request
Servant
Reply
Client
Remote reference module translates
between local and remote object references
and creates remote object references
Server
Skeleton implements
the remote interface
of the servant
17
AOT
LAB
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
AOT
LAB
RMI Stack
Client
Server
Stub
Skeleton
Remote Reference
Remote Reference
Transport
Transport
19
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
Application Components
Registry
Server
Client
Web Server
23
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
Server Program Code
creates a remote object
import java.rmi.Naming;
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
AOT
LAB
Client Program Code
Looks up a reference to a remote object
with external name MessageWriter
import java.rmi.Naming;
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
AOT
LAB
Compiling and Running
javac *.java
rmic MessageWriterImpl
MessageWriterImp_Skel.class
MessageWriterImp_Stub.class
start rmiregistry
java HelloServer
java HelloClient
31
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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
AOT
LAB
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