Download LAB - Università degli Studi di Parma

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
AOT
LAB
Agent and Object Technology Lab
Dipartimento di Ingegneria dell’Informazione
dell Informazione
Università degli Studi di Parma
Distributed and Agent Systems
RMI
P f Agostino
Prof.
A
ti
Poggi
P
i
AOT
LAB
What is RMI?
Š Supports communication between different Java
virtual machines, potentially across the network
Š All
Allows an object
bj t running
i iin one JJava virtual
it l
machine to invoke methods on an object running in
another
th Java
J
virtual
i t l machine
hi
Š Its acronym means Remote Method Invocation
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
d return
t
remote
t object
bj t references
f
as partt off
other remote invocations
Š Communicate
C
i t with
ith remote
t objects
bj t
ƒ Details of communication handled by RMI
ƒ To the programmer, remote communication looks similar
to regular Java method invocations
Š Load
L d class
l
d
definitions
fi i i
ffor remote objects
bj
ƒ RMI provides mechanisms for loading an object's class
d fi iti
definitions
as wellll as ffor ttransmitting
itti an object's
bj t' d
data
t
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
java rmi RemoteException exception
4
AOT
LAB
Remote Class
Š A class to be a remote class needs to implement a
remote interface
ŠM
Mostt often
ft a remote
t class
l
also
l extends
t d the
th library
lib
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
R
t objects
bj t
6
AOT
LAB
Parameter Passing
Atomic Type
Local Object
Remote Object
Local Call
Call by
y 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
jjava.io.Serializable interface or must extend a
class that extends it
Š Primitive data are serializable,
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
i t string
t i name;
private float price;
private Geometry geo;
private transient Image image;
}
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
Cl
file
fil and
d Obj
ObjectOutputStream
O
S
oos.close();
os.close();
10
AOT
LAB
Read an Object
Š Open the file that stores the object
ƒ InputStream is = new FileInputStream(“c:\myClass”);
Š Create
C t Obj
ObjectInputStream
tI
tSt
ƒ ObjectInputStrem ois = new ObjectInputStream(is);
Š Read the object into the file
ƒ MyClass instance = (MyClass) ois.readObject();
Š Close file and ObjectOutputStream
ƒ ois.close();
ƒ is.close();
i l
()
11
AOT
LAB
RMIC
Š It is the compiler that generates stubs used to
connect remote objects
ƒ Its input is a remote implementation class
ƒ Its output is a new class that implements the same
remote interfaces as the input class
Š Such
Suc new
e class
c ass supports
suppo s the
e interaction
e ac o with a
remote object whose Internet address is stored in
the stub instance through
g a set of methods for
ƒ Sending arguments to the remote object
ƒ Receiving results from the remote object
12
AOT
LAB
Application Components
Proxy makes
RMI transparent Communication module
i l
implements
t th
the requestt
to clients by
behaving like a reply protocol
local object
Dispatcher receives request
message
essage from
o co
communication
u cat o
module and select the method
in the skeleton
Request
q
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
13
AOT
LAB
Remote Object Binding
Š Explicit by using static methods in the
java.rmi.Naming class
ƒ Server binds/rebinds name with the rmiregistry
ƒ Client looks up name with the rmiregistry
Š Implicit by receiving a remote object reference
ƒ Client can invoke methods on it as if it were a local
interface
14
AOT
LAB
RMI Registry
Š Runs on each machine, which hosts remote objects
and accepts requests for services
Š Clients use the registry to find the remote objects
MyClass
y
instance =
(Myclass) Naming.lookup(“rmi://localhost/myclass”);
MyClass instance =
(Myclass)
Naming.lookup( rmi://localhost:2001/myclass );
Naming.lookup(“rmi://localhost:2001/myclass”);
Š Its default TCP/IP port is 1099
15
AOT
LAB
RMI Registry
Š void rebind (String name, Remote obj)
ƒ Registers the identifier of a remote object by name
Š void bind ((String
g name,, Remote obj)
j)
ƒ Registers a remote object by name, but if the name is
already in the registry an exception is thrown
Š void unbind (String name, Remote obj)
ƒ Removes a binding
Š Remote lookup(String name)
ƒ Looks up a remote object by name
Š String [] list()
ƒ Returns
R t
the
th names bound
b
d iin th
the registry
i t
16
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
17
AOT
LAB
Reflection
Š Get a class
Class c = Class.forName("com.example.MyClass")
Š Get fields and methods
Field[]
e d[] fss
= cc.getFields();
get e ds();
Method[] ms = c.getMethods();
Š Get
G t parameters
t
and
d return
t
type
t
Class<?>[]
[] p
pts = ms[0].getParameterTypes();
[ ]g
yp ();
Class<?> rt
= ms[0].getReturnType();
18
AOT
LAB
Remote Call Execution
Š Proxy 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
19
AOT
LAB
Remote Object Code
import java.rmi.Remote;
p jjava.rmi.RemoteException;
p
;
import
public interface MessageWriter extends Remote {
void writeMessage(String s) throws RemoteException;
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
ja a rmi ser er U i tR
t Obj t
public class MessageWriterImpl
extends UnicastRemoteObject
implements MessageWriter {
public MessageWriterImpl() throws RemoteException { … }
public void writeMessage(String s) throws RemoteException {
System.out.println(s);
}
}
20
AOT
LAB
Server Program Code
creates a remote
object
bj t with
ith llocall
name server
import java.rmi.Naming;
public class HelloServer {
public
bli static
t ti void
id main(String
i (St i [] args)) throws
th
Exception
E
ti {
MessageWriter server = new MessageWriterImpl();
Naming.rebind(“MessageWriter”,
Naming.rebind(
MessageWriter , server);
}
}
Publishes a remote reference to that
object with external name MessageWriter
21
AOT
LAB
Client Program Code
Looks up a reference to a remote object with
external
t
l name MessageWriter,
M
W it and
d stores
t
the
th
returned reference with local name server
import java.rmi.Naming;
public class HelloClient {
public
bli static
t ti void
id main(String
i (St i [] args)) throws
th
Exception
E
ti {
MessageWriter server =
(MessageWriter) Naming.lookup(“rmi://localhost/MessageWriter”);
Naming.lookup( rmi://localhost/MessageWriter );
server.writeMessage(“Hello, other world”) ;
}
}
Invokes the remote method, writeMessage(), on server
22
AOT
LAB
Compiling and Running
Š javac *.java
Š rmic MessageWriterImpl
Š start rmiregistry
Š java HelloServer
Š java HelloClient
23
AOT
LAB
Distributed Garbage Collection
Š 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
ƒ S
Server maintain
i t i processes sett th
thatt h
hold
ld remote
t object
bj t
references to it
ƒ Client
Cli t notify
tif server tto modify
dif th
the process sett
ƒ When the process set becomes empty, server local
garbage collector reclaims the space
24
AOT
LAB
Explicit Notification
import java.rmi.server.UnicastRemoteObject;
Import java.rmi.server.Unreferenced;
public class RemoteServerImpl
extends UnicastRemoteObject
i l
implements
t M
MyRemoteInterface,
R
t I t f
Unreferenced
U f
d{
public RemoteServerImpl() {
super();
...
//allocate resources
}
...
public void unreferenced() {
//deallocate resources here
}
E.g., network and
database connections
can be
b released
l
d
}
25
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
onlyy 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
26
AOT
LAB
Dynamic Class Loading
Š Remote object's codebase is specified by setting
th java.rmi.server.codebase
the
j
i
d b
property
t
java –Djava.rmi.server.codebase=http://www/ HelloServer
j
java
–Djava.rmi.server.codebase=http://www/myStub.jar
Dj
i
d b
htt //
/ St b j HelloServer
H ll S
Š 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
client s CLASSPATH
ƒ Then it loads the class definition
ƒ Else it retrieves the class definition from the remote
object's codebase
27
AOT
LAB
Security Manager and Policies
Š Security is a serious concern since executable
code is being downloaded from a remote location
g of code only
y from
Š RMI normallyy allows the loading
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
d practice
ti tto install
i t ll it anyway
28
AOT
LAB
Security Manager and Policies
Š A security manager can be set as follows:
System.setSecurityManager(new RMISecurityManager()) ;
Š A security policy can be defined in a plain text file:
grant { permission java.security.AllPermission
java security AllPermission “”, “” ; } ;
Š And
A d assigned
i
d to the
h client
li
as ffollows:
ll
java –Djava.security.policy=rmi.policy HelloClient
29
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 theyy are used few times
30
AOT
LAB
Remote Object Code
import java.rmi.Remote;
p jjava.rmi.RemoteException;
p
;
import
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);
}
}
31
AOT
LAB
Server Main Method Duties
Š Install security manager for the ActivationGroup of
the Java virtual machine.
policy
y
Š Set a securityy p
Š Create an ActivationGroupDesc instance
Š Register it and get an ActivationGroupID
Š Create an ActivationDesc instance
Š Register it with rmid
j
instance with its
Š Bind or rebind the remote object
name
Š Exit the system
32
AOT
LAB
Server Main Method Code
public static void main(String[] args) throws Exception {
System setSecurityManager(new RMISecurityManager());
System.setSecurityManager(new
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);
ActivationGroup getSystem() registerGroup(eg);
String location = "file:/myrmi/";
MarshalledObject data = null;
ActivationDesc desc =
new ActivationDesc(agi, “MessageWriter“, location, data);
MessageWriter server = (MessageWrite) Activatable.register(desc);
Activatable register(desc);
Naming.rebind(“messageservice”, server);
System.exit(0);
}
33
AOT
LAB
Compiling and Running
Š javac *.java
Š rmic MessageWriterImpl
Š start rmiregistry
Š start rmid –J-Djava.security.policy=rmi.policy
Š java
j
-Djava.security.policy=rmi.policy
Dj
it
li
i li HelloServer
H ll S
Š java -Djava.security.policy=rmi.policy
-Djava security policy=rmi policy HelloClient
34
AOT
LAB
Callbacks
Š A callback server’s action of notifying clients about
an event implementation
ƒ Improve
p
p
performance by
y avoid constant p
polling
g
ƒ 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
35