Download Java.rmi.Remote - 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 work of 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
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