Transcript DOBS

Distributed Objects and
Remote Invocation
Chapter 5
B.Ramamurthy
4/11/2016
B.Ramamurthy
1
Remote Method Invocation
Remote Method Invocation (RMI) is Java’s
implementation of object-to-object
communication among Java objects to realize
a distributed computing model.
RMI allows us to distribute our objects on
various machines, and invoke methods on the
objects located on remote sites.
Source code for the demo is a modified
version of code in Chapter 20 of Deitel &
Deitel’s text Java : How to Program.
4/11/2016
B.Ramamurthy
2
The Object Model
1. Object references

Objects are first-class values, meaning that
they may be assigned to variables, passed as
arguments and returned as results of
methods.
2. Interfaces


Interfaces provide signatures of the set of
methods
Signature is the type of arguments, return
value and exceptions)
4/11/2016
B.Ramamurthy
3
The Object model (contd.)
3. Action: Action is initiated by an object invoking
a method in another object.
4. Exceptions: These provide clean way to deal
with error conditions without complicating the
code.



4/11/2016
Each method heading explicitly lists the exceptions
or error conditions that may occur allowing users of
the method to deal with them
A block of code may be defined to throw an
exception when an error occurs.
The control passes to another block of code that
catches the exception
B.Ramamurthy
4
The Object Model
5. Garbage Collection: it is necessary to
provide means for freeing the space
occupied by objects when they are no
longer needed.
4/11/2016
B.Ramamurthy
5
The Distributed Object Model
The invoker and the invoked are separated and
remote to each other.
Foundations of distributed systems
Distributed objects may adopt client-server
architecture.
It may assume other architectural model – objects
may be replicated for fault-tolerance and
performance.
Distributed object model allows for real
encapsulation, heterogeneous systems, distribution.
The concept of remote interfaces.
4/11/2016
B.Ramamurthy
6
RMI-based Distributed System
4.
5.
3.
XYZ
Client
3.
1.
XYZ
interface
Client Host
4/11/2016
XYZ
Implementation
Stub
Stub
uses
2.
implements
Server Host
B.Ramamurthy
7
Steps in RMI-based
Application
1. Design the interface for the service.
2. Implement the methods specified in
the interface.
3. Generate the stub, skeletons, and
dispatchers (for enabling distributed
access to the service).
4. Register the service by name and
location.
5. Use the service in an application.
4/11/2016
B.Ramamurthy
8
Compile and Register
Commands
Finds object by name
5.
rmiregistry
rmic
3.
XYZ
Client
3.
1.
XYZ
interface
Client Host
4/11/2016
2.
Skeleton
Stub
uses
Stores object by name
XYZ
Implementation
implements
Server Host
B.Ramamurthy
9
More Details
Once the object (or service) is registered, a
client can look up that service.
A client (application) receives a reference that
allows the client to use the service (call the
method).
Syntax of calling is identical to a call to a
method of another object in the same
program.
4/11/2016
B.Ramamurthy
10
Parameter Marshalling
Transfer of parameters (or marshalling)
is done by the RMI.
Complex objects are streamed using
Serialization.
RMI model of networking for distributed
system involves only Java.
No need to learn IDL or any other
language.
4/11/2016
B.Ramamurthy
11
Case Study : Temperature
Service
Lets create a distributed system using
RMI model for networking (remote
access).
Basically this program will download the
weather (temperature) information
from the site:
http://iwin.nws.noaa.gov/iwin/us/traveler.html
4/11/2016
B.Ramamurthy
12
Temperature Client/Server
Distributed Application
rmic
4
compiles
5.
3.
TempClient
TempImpl_Stub
uses
generates
uses
3.
2.
TempImpl_Stub
TempServerImpl
1.
implements
TempServer
Client Host
4/11/2016
Server Host
B.Ramamurthy
13
Defining Remote Interface
import java.rmi.*;
// the interface extends Remote interface
// any class implementing Remote can be
accessed remotely security permitting
public interface TemperatureServer extends
Remote
{ // specify methods that can be called
remotely
// each method “throws RemoteException”
}
4/11/2016
B.Ramamurthy
14
RemoteException
Any time you depend on outside entities
there is a potential for problems in
communication, networking, server crash etc.
Any exception due to these should be
handled by the services.
This feature imparts robustness to the
application.
Java mandates this feature for any RMI
service.
4/11/2016
B.Ramamurthy
15
Implementing the Remote
Interface
import java.rmi.*;
import java.rmi.server.*;
import java.net.*;
// others as needed
TemperatureServerImpl
extends UnicastRemoteObject
implements TemperatureServer {
4/11/2016
B.Ramamurthy
16
TemperatureServerImpl
This class’s constructor calls a private method
which in turn:
1. Connects to the url specified
2. Streams into a buffer the page referenced.
3. Parses the buffer to get the required data.
4. Creates an array of weather information.
4/11/2016
B.Ramamurthy
17
TemperatureServerImpl
(contd.)
It implements the service method
getWeatherInfo which simply returns
the weather data gathered.
The main method instantiates an object
for the service, and registers it with
rmiregistry.
4/11/2016
B.Ramamurthy
18
Streaming URLs
Using the openStream of java.net.URL class
you can stream in the file spefied by an
universal resource locator(url).
It can be streamed into a buffer where it can
be analyzed for information.
Any number of urls can be streamed in.
Unicast Communication : When you are
interested in a particular remote site you will
direct your net connection to that particular
site using unicast.
4/11/2016
B.Ramamurthy
19
Server Object Name
Syntax for the server object name is:
//host:port/remoteObjectName
Default port number for rmiregistry is 1099
For local host the object name:
//localhost/TempServer
For a remote host
//127.0.0.1/TempServer
4/11/2016
B.Ramamurthy
20
Name Binding
rebind method binds a server’s object
name to the object’s name as it is in the
registry.
Clients use the name in the registry.
There is also a bind() method.
But rebind is better since it binds the
most recently registered object.
4/11/2016
B.Ramamurthy
21
WeatherInfo class
It is very traditional class for keeping
the information about the temperature
at a single location.
It has data fields : cityName,
temperature, and description and get
methods for these.
An array of objects of this class is used
in the server implementation.
4/11/2016
B.Ramamurthy
22
Temperature Client
import java.rmi.*;
// import other packages
constructor calls a private method
getRemoteTemp which takes care of
lookup of remote object and access.
In this application it also displays the
information.
4/11/2016
B.Ramamurthy
23
Temperature Client (contd.)
The main method in this client can get
the IP address of the remote host as a
command line argument.
Command line argument is an array of
String of items in the command line
after the name of the application.
4/11/2016
B.Ramamurthy
24
Client Details
The name of the server object along with the
IP of the remote location is used in Naming
class’s lookup method to get an object
reference.
This object reference is then used for remote
method calls.
Observe that there is no difference between
the local and remote call.
WeatherItem class used in the Graphical
display of the weather information.
4/11/2016
B.Ramamurthy
25
Preparing the Application
1. Compile all the class using javac.
2. Generate the stub and the skeleton:
rmic -v1.2 TemperatureServerImpl
3. Then start the registry (this will be
running as a daemon)
rmiregistry &
4/11/2016
B.Ramamurthy
26
Preparing the Application
4. Run the server which will register with the
RMI registry.
Java TemperatureServerImpl &
5. Run the client.
Java TemperatureClient &
or
java TemperatureClient {IPAddress}
java TemperatureClient 192.168.0.150
4/11/2016
B.Ramamurthy
27
Inside RMI
http://java.sun.com/j2se/1.5.0/docs/index.html
Basic RMI classes: /usr/java1.1/src/java/rmi
 java.rmi.registry.*
 java.rmi.Naming class (static/class methods)
 java.rmi.Remote interface (marker interface)
 java.rmi.server.*
 Default RMI port 1099
 Both lookup from local and remote are acceptable.
4/11/2016
B.Ramamurthy
28
Implementation of RMI (5.2.5)
AccessException.java
RemoteException.java
AlreadyBoundException.java
ConnectException.java
ServerException.java
ConnectIOException.java
ServerRuntimeException.java
MarshalException.java
StubNotFoundException.java
UnexpectedException.jav
ServerError.java
UnknownHostException.java
NoSuchObjectException.java
UnmarshalException.java
NotBoundException.java
RMISecurityException.java
RMISecurityManager.java
4/11/2016
Remote.java
MarshalledObject.java
Naming.java
activation
dgc
Registry
server
B.Ramamurthy
29
The role of proxy and skeleton
in remote method invocation
server
client
object A proxy for B
Request
skeleton
& dispatcher
for B’s class
remote
object B
Reply
Remote Communication
reference module module
servant
CommunicationRemote reference
module
module
Object A invokes a remote object in Object B for which it holds a remote object
reference.
“System Model”
4/11/2016
B.Ramamurthy
30
RMI Internals: Communication
Module
Carries out request-reply protocol;
On the client side {message type, message
id, remote reference to object} are gathered
and sent out. At most once invocation
semantics;
On the server side, it gets local reference for
remote reference from remote reference
module, invokes a dispatcher with this
reference.
See UnicastRemote (implements
UnicastRemote)
4/11/2016
B.Ramamurthy
31
RMI Internals: Remote
Reference module
Responsible for translating between
local and remote object references and
for creating remote object references.
A remote object table has a mapping
between local and remote references. A
table at server (entry for object ref for
B) and a table at client (entry for object
ref for proxy B).
4/11/2016
B.Ramamurthy
32
RMI Internals: Remote
References
Action of remote reference module: See
RemoteRef.java interface


4/11/2016
When a remote object is to be passed as
argument or result for the first time, the remote
ref is asked to create a remote ref object which is
added to the table.
When a remote object reference arrives in a
request or reply, the remote ref module is asked
for corresponding local object ref, which may
either a proxy or remote object. If it is not in the
table RMI runtime creates it and asks remote ref
module to add it to the table.
B.Ramamurthy
33
RMI Internals: RMI software
Layer of software between application level objects and communication and
remote reference modules: “Middleware”
Proxy: provides remote access transparency. One proxy for every remote
object in the client.
Dispatcher: A server has one dispatcher and skeleton for each class
representing a remote object.
It receives request message from comm. Module
 It used MessageId to select appropriate method in skeleton.
 Proxy and dispatcher use same MessageId.
Skeleton: A class of remote object has a skeleton that implements of the
remote interface. All the access dependencies are hidden in this class. A remote
object has a servant that directly implements the methods. Java 5 creates this

dynamically.
Proxies, dispatcher and skeleton are automatically generated by interface
compiler.
Binder: binds textual names to remote object references. RMIRegistry is a
binder; Naming class; see fig.5.13
Server Threads: one thread per invocation
Distributed garbage collection: See Andrew Birell’s paper [1995].
4/11/2016
B.Ramamurthy
34
RMI Internals: Distributed
Garbage Collection
Based on reference counts.
Local garbage collectors and a distributed support.
Each server holds the list of processes that hold remote object references: for
example, B.Holders
When a client C first receives a remote reference to a particular remote object,
say B, it makes a addRef(B) invocation to server of that remote object and then
creates proxy; server adds C to B.Holders.
When client C’s garbage collector finds that proxy is no longer reachable (ref
count), it makes a removeRef(B) invocation to server and then deletes proxy;
the server removes C from B.Holders.
When B.Holders is empty, server’s local garbage collector will reclaim the space
occupied B unless there are any local holders.
These extra calls for updates occur during proxy creation and deletion and do
not affect normal opertion.
Tolerates communication failures: addRef() and removeRef() are idempotent:
effects of N > 0 identical requests is the same as for a single request.
If addRef() fails with an exception, proxy is not created, removeRef() is
transmitted; removeRef() failures are dealt with by “leases” (Jini kind).
4/11/2016
B.Ramamurthy
35
RMI Internals: Use of
Reflection
What is reflection? See Reflection package
Reflection enables Java code to discover information
about the fields, methods and constructors of loaded
classes, and
To use reflected fields, methods, and constructors to
operate on their underlying counterparts on objects,
within security restrictions.
http://java.sun.com/docs/books/tutorial/reflect/class/index.html
Reflection feature allowed for dynamic creation of skeleton and proxy
in Java 2 version onwards.
Read more about reflection model of computing.
4/11/2016
B.Ramamurthy
36
A Little bit of Reflection
Method class, invoke method
Invoke method requires two
parameters: first the object to receive
invocation, second an array of Object
parameters.
Invoke executes the method on the
object and returns result as Object.
Method m;
Object result = m.invoke(String ObjRef,
4/11/2016
B.Ramamurthy
37
Args);
Reflection
Java Reflection is a mechanism for inspecting
the variables and methods of an unknown
class at runtime. Reflection allows for
• –finding methods, variables, constructors
• –analyzing their types, parameters, results,
modifiers
• –changing variables
• –calling methods or constructors
4/11/2016
B.Ramamurthy
38
Reflection (contd.)
• Reflection uses methods of java.lang.Class(and
java.lang.reflect.*) e.g.
• java.lang.ClassforName(StringclassName)
• java.lang.reflect.Contructor[] getConstructors()
• java.lang.reflect.Field[] getFields()
• java.lang.reflect.Method[] getMethods()
4/11/2016
B.Ramamurthy
39
Reflection (contd.)
Java Reflection: Example...
Class clazz = Class.forName("MyClass");
Object myObject= clazz.newInstance();
Method[] methods= clazz.getMethods();
Method firstMethod= methods[0];
Objectresult= null;// try to invoke a method on myObject
if("testMethod".equals(firstMethod.getName()))
result= firstMethod.invoke(myObject, null);
//...obtain class of specified name; create a new instance;
obtain all public methods; obtain a method's name; invoke the
method with no parameters on the class instance
J2EE implementations use immense amounts of reflection!
4/11/2016
B.Ramamurthy
40
Using Reflection in RMI
Proxy (on the client side) marshals info. about a
method and its arguments into a request message.
For a method it marshals an object of class Method
into the request. It then adds an array of objects for
the method’s arguments.
The dispatcher unmarshals the Method object and its
arguments from request message.
The remote object reference is obtained from remote
ref. table.
The dispatcher then calls the “invoke” method on the
object reference and array of arguments values.
After the method execution the dispatcher marshals
the result or any exceptions into the reply message.
4/11/2016
B.Ramamurthy
41
Figure 5.1
Middleware layers
Applications
RMI, RPC and events
Request reply protocol
External data representation
Operating System
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
Middleware
layers
Remote and local method
invocations
local
remote
invocation
A
B
C
E
invocation local
invocation
local
invocation
D
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
remote
invocation
F
A remote object and its
remote interface
remoteobject
Data
remote
interface
{
m1
m2
m3
implementation
of methods
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
m4
m5
m6
Instantiation of remote
objects
L
C
remote
invocation
instantiate instantiate
M
N
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
remote
invocation
K
Invocation semantics
Fault tolerance measures
Retransmit request Duplicate
message
filtering
Invocation
semantics
Re-execute procedure
or retransmit reply
Maybe
No
Not applicable Not applicable
Yes
No
Re-execute procedureAt-least-once
Yes
Yes
Retransmit reply
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
At-most-once
Role of client and server stub procedures in RPC
in the context of a procedural language
client process
server process
Request
Reply
client stub
procedure
client
program
Communication
module
server stub
procedure
Communication
dispatcher
module
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
service
procedure
Dealing room system
Dealer’s computer
Dealer
Dealer’s computer
External
source
Notification
Notification
Notification
Information
provider Notification
Notification
Notification
Dealer
Notification
Dealer’s computer
Dealer’s computer
Notification
Information
provider
Notification
Dealer
Notification
Dealer
External
Instructor’s Guide
for Coulouris,
source
Dollimore and
Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
Architecture for distributed
event notification
Event service
subscriber
object of interest
1.
notification
object of interest
2.
object of interest
observer
notification
subscriber
notification
observer
3.
subscriber
notification
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
Java Remote interfaces Shape
and ShapeList
import java.rmi.*;
import java.util.Vector;
public interface Shape extends Remote {
int getVersion() throws RemoteException;
GraphicalObject getAllState() throws RemoteException; 1
}
public interface ShapeList extends Remote {
Shape newShape(GraphicalObject g) throws RemoteExcept
Vector allShapes() throws RemoteException;
int getVersion() throws RemoteException;
}
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
The Naming class of Java
RMIregistry
void rebind (String name, Remote obj)
This method is used by a server to register the identifier of a
remote object by name, as shown in Figure 15.13, line 3.
void bind (String name, Remote obj)
This method can alternatively be used by a server to register a
remote object by name, but if the name is already bound to a
remote object reference an exception is thrown.
void unbind (String name, Remote obj)
This method removes a binding.
Remote lookup(String name)
This method is used by clients to look up a remote object by
name, as shown in Figure 15.15 line 1. A remote object
reference is returned.
String [] list()
Instructor’s Guide for Coulouris,
This method returns anDollimore
array and
of Kindberg
Strings containing the names
Distributed Systems: Concepts
bound in the registry.
and Design Edn. 4
© Pearson Education 2005
Java class ShapeListServer
with main method
import java.rmi.*;
public class ShapeListServer{
public static void main(String args[]){
System.setSecurityManager(new RMISecurityManager());
try{
ShapeList aShapeList = new ShapeListServant();
Naming.rebind("Shape List", aShapeList );
System.out.println("ShapeList server ready");
}catch(Exception e) {
System.out.println("ShapeList server main " + e.getMessage());}
}
}
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
Java class ShapeListServant implements
interface ShapeList
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;
public class ShapeListServant extends UnicastRemoteObject implements Sha
private Vector theList;
// contains the list of Shapes
private int version;
public ShapeListServant()throws RemoteException{...}
public Shape newShape(GraphicalObject g) throws RemoteException {
version++;
Shape s = new ShapeServant( g, version);
theList.addElement(s);
return s;
}
public Vector allShapes()throws
Instructor’s Guide RemoteException{...}
for Coulouris,
Dollimore RemoteException
and Kindberg
public int getVersion()Distributed
throws
{ ... }
Systems: Concepts
}
and Design Edn. 4
© Pearson Education 2005
Java client of ShapeList
import java.rmi.*;
import java.rmi.server.*;
import java.util.Vector;
public class ShapeListClient{
public static void main(String args[]){
System.setSecurityManager(new RMISecurityManager());
ShapeList aShapeList = null;
try{
aShapeList = (ShapeList) Naming.lookup("//bruno.ShapeList")
Vector sList = aShapeList.allShapes();
} catch(RemoteException e) {System.out.println(e.getMessage());
}catch(Exception e) {System.out.println("Client: " + e.getMessage());
}
}
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
Classes supporting Java RMI
RemoteObject
RemoteServer
Activatable
UnicastRemoteObject
<servant class>
Instructor’s Guide for Coulouris,
Dollimore and Kindberg
Distributed Systems: Concepts
and Design Edn. 4
© Pearson Education 2005
Summary
We discussed designing a distributed
system using RMI
We also looked at RMI internal
We also learned about marker interface,
distributed garbage collection, object
marshalling, registry, server-port
binding, Naming class of RMI, …
4/11/2016
B.Ramamurthy
56