© Mourad Elhadef, Ph. D. CSI408-Distributed Information Systems Chapters 4 & 5 Interprocess...
-
Upload
todd-fowler -
Category
Documents
-
view
215 -
download
2
Transcript of © Mourad Elhadef, Ph. D. CSI408-Distributed Information Systems Chapters 4 & 5 Interprocess...
© Mourad Elhadef, Ph. D.
CSI408-Distributed Information Systems
Chapters 4 & 5 Interprocess Communication
Presentation of the characteristics of protocols for communication between processes:
Client-Server or group communication, RPC, RMI, …
Communication between distributed objects and remote invocation
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-2
2nd Part: Types of Interprocess Communication (Client-Sever, Group)
Themes
1st Part: Means of Interprocess Communication (RPC, RMI, …)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-3
Layered Protocols
Means of Interprocess Communication
RMI (Remote Method Invocation)
Introduction
Readings
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-4
Request-Reply ProtocolMarshalling and external data
representation
RMI, RPC and events
Operating System
UDP and TCP
Applications, services
Introduction (1)
Middleware layers
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-5
Introduction (2)
Characteristics of middleware layers: Location transparency (definition)
Independent: protocols that support the middleware abstractions are independent of the underlying transport protocols (example)
Heterogeneous hardware: hide the difference due to hardware architectures (big-endian, little-endian, …) (mean)
Use of several programming languages: allow distributed applications to use more than one programming language (example)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-6
RMI/INTERFACE:Import java.rmi.*;package EXAMPLES;public interface RAND_VERS extends Remote{ public void INITIALIZE_RANDOM(long arg) throws RemoteExceptions; public double GET_NEXT_RANDOM(void) throws RemoteExceptions;};
RPC/IDL :program RAND_PROG{ version RAND_VERS { void INITIALIZE_RANDOM(long) = 1; double GET_NEXT_RANDOM(void) = 2; } = 1;} = 0x31111111;
CORBA/IDL :module EXAMPLES{ interface RAND_PROG { void INITIALIZE_RANDOM(in long arg); double GET_NEXT_RANDOM(void); };};
RPC/IDL:program RAND_PROG{ version RAND_VERS { void INITIALIZE_RANDOM(long) = 1; double GET_NEXT_RANDOM(void) = 2; } = 1;} = 0x31111111;
Introduction (3)
Definition of remote
procedure using
different IDL
CORBA/IDL:module EXAMPLES{ interface RAND_PROG { void INITIALIZE_RANDOM(in long arg); double GET_NEXT_RANDOM(void); };};
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-7
Introduction (4)
Characteristics of interprocess communication:
Types of communication:
Synchronous: the sending and receiving processes synchronize at every message
Asynchronous: no synchronization between the sending and receiving processes
Send and Receive: blocking operations
Send: non-blocking operation
Receive: non-blocking or blocking operation
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-8
Introduction (5)
Characteristics (continued): Message destinations:
Messages sent to <Internet address, Local port > Processes may use multiple ports from which to
receive messages
Communication reliability: Integrity (definition)
Validity (definition)
Ordering: some applications require that messages be delivered in sender order
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-9
Introduction (6)
Characteristics (continued) : Sockets: used by UDP and TCP as endpoint for
communication between processes Must be bound to a local port and one of the Internet
addresses Each socket is associated to one protocol: UDP or TCP
216 possible ports
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-10
Layered Protocols (1)
Multiple layers intervene during interprocess communication
Internetwork layers (Internet)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-11
Layered Protocols (2)
Types of communication:
UDP Datagram Communication
TCP Stream Communication
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-12
UDP Datagram Communication Datagrams transmitted by UDP: without
acknowledgments or retries
Blocking: UDP use a non-blocking send and a blocking receive
Failure model: UDP suffers from Omission failures: messages dropped (causes)
Ordering: messages can sometimes be delivered out of sender order
UDP advantage: do not suffer from the overheads associated with guaranteed message delivery
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-13
Datagram Communication: Java API (1)
Manipulating Internet addresses: Class InetAddress: represents Internet addresses
(example)
InetAddress ( string address ): multiple forms of the constructor exist
short int getPort () const bool setPort ( short int port ) string getAddress () const bool setAddress ( string address ) bool setAddress ( unsigned long int address ) string getHostName () string getHostByIP ( string ip ) string getIPByName ( string host ) …
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-14
Sender:
DatagramPacket( byte buffer[], int length, InetAddress address, int
port)
Number of bytes to readbuffer for holding the incoming datagram
Datagram Communication: Java API (2)
Manipulating datagrams: Class DatagramPacket : creates packets containing data to be
transmitted or received and the address of destination or source of the datagrams Port
NumberInternet Address
Message’s length
Message’s bytesDatagram packet
Constructors: Receiver: DatagramPacket(byte buffer[], int length)
UDP Port
Data packet Length of data packet
Destination address
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-15
Datagram Communication: Java API (3)
Manipulating datagrams (continued): main methods of the class DatagramPacket
InetAddress getAddress ()
int getPort ()
void setAddress(InetAddress iaddr)
byte[] getData ()
void setData(byte ibuf[])
void setPort(int iport)
int getLength ()
void setLength(int ilength)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-16
Constructors:
DatagramSocket () throws SocketException
DatagramSocket (int port) throws SocketException
DatagramSocket(int port, InetAddress laddr) throws
SocketException
Datagram Communication: Java API (4)
Manipulating sockets: Class DatagramSocket: represents a socket for sending
and receiving datagram packets
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-17
Datagram Communication: Java API (5)
Manipulating sockets (continued): main methods of the class DatagramSocket void send(DatagramPacket data) throws IOException
void receive(DatagramPacket data) throws IOException void setSoTimeout(int timeout) throws SocketException Enable/disable SO_TIMEOUT with the specified timeout. 0 = no timeout
void close ()
int getLocalPort ()
int getSoTimeout() throws SocketException
void connect (InetAddress address, int port)
void disconnect()
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-18
Datagram Communication: Java API (6)
Example: Client sends a request import java.net.*; import java.io.*; public class UDPClient{ public static void main(String args[]) { // args[0] = message to be sent to the server; args[1] = IP address of the server
DatagramSocket aSocket = null; try {
aSocket = new DatagramSocket(); byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);int serverPort = 6789;DatagramPacket request = new DatagramPacket(m,
args[0].length(), aHost, serverPort);aSocket.send(request);
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-19
Datagram Communication: Java API (7)
Example (continued): Client waits for a reply
byte[] buffer = new byte[1000];DatagramPacket reply = new DatagramPacket(buffer,
buffer.length);aSocket.receive(reply);System.out.println("Reply: " + new String(reply.getData()));
}catch (SocketException e){System.out.println("Socket: " +
e.getMessage()); }catch (IOException e){System.out.println("IO: " +
e.getMessage()); }finally {if(aSocket != null) aSocket.close();}}}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-20
Datagram Communication: Java API (8)
Example (continued): Server waits continually for a request
import java.net.*; import java.io.*; public class UDPServer{ public static void main(String args[]) { DatagramSocket aSocket = null; try{
aSocket = new DatagramSocket(6789); byte[] buffer = new byte[1000]; while(true){ DatagramPacket request = new DatagramPacket(buffer,
buffer.length); aSocket.receive(request);
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-21
Datagram Communication: Java API (9)
Example (continued): Server sends the response to the client
DatagramPacket reply = new DatagramPacket( request.getData(), request.getLength(),
request.getAddress(), request.getPort());
aSocket.send(reply);} }catch (SocketException e){System.out.println("Socket: " +
e.getMessage()); }catch (IOException e) {System.out.println("IO: " + e.getMessage()); }finally {if(aSocket != null) aSocket.close();}}}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-22
TCP Stream Communication (1)
Use of input or output streams
Characteristics: Message sizes (size)
Lost messages: use of an acknowledgment scheme
Flow control: TCP protocol attempts to match the
speeds of the processes that read and write to a stream (how?)
Message duplication and ordering: (How?)
Message destinations: (how?)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-23
TCP Stream Communication (2)
Characteristics (continued):
Matching of data items: processes need to agree as to the contents of the data transmitted over a stream (example)
Blocking: (When?)
Use of threads: (How?)
Server: accepts a connection
A thread is created for the new client
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-24
TCP Stream Communication (3)
Failure model: must satisfy
Integrity property: (How?)
Validity property: (How?)
TCP limits: does not guarantee to deliver messages in the face of all possible difficulties
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-25
Stream Communication: Java API (1)
Client: Class Socket: used by a client to establish a connection
with the server
public Socket (String Host, int Port) throws UnknownHost…
public Socket (InetAddress Host, int Port) throws Unknown…
public Socket (InetAddress Host, int Port, InetAddress LocalAddress, int LocalPort) throws UnknownHost…
…
Constructors: creates a TCP socket by specifying the DNS hostname and a port of a server
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-26
Stream Communication: Java API (2)
Client (continued): main methods of class Socket
close() throws IOException InetAddress getInetAddress () int getPort () InetAddress getLocalAddress () int getLocalPort () int getSoTimeout() throws SocketException void setSoTimeout(int timeout) throws SocketException InputStream getInputStream() throws IOException OutputStream getOutputStream() throws IOException …
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-27
import java.net.*; import java.io.*;public class Ports1 { public static void main(String[] args) { Socket s; String host = "localhost"; if(args.length > 0) host=args[0] ; for(int i = 0 ; i < 1024; i++) {
try { s=new Socket(host,i); System.out.println("Server " + " attached to port "+ i);} catch (ConnectException e) { ; } catch (UnknownHostException e) {
System.err.println(e+" --> "+i) ;} catch (IOException e)
{ System.err.println(e); }}}}
Stream Communication: Java API (3)
Example 1: list all services of ports 0-1023 on a local machine
arlequin{elhadef}102: java Ports1Server attached to port 7 Server attached to port 9 Server attached to port 13 Server attached to port 19 Server attached to port 22 Server attached to port 23 Server attached to port 37 Server attached to port 79 Server attached to port 111 Server attached to port 512 Server attached to port 513 Server attached to port 514 Server attached to port 515
Execution results:
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-28
Stream Communication: Java API (4)
Example 2: manipulating InetAddress addressesimport java.net.*; import java.io.*;public class Ports2 { public static void main(String[] args) { Socket s; String host = "www.dmi.usherb.ca"; if(args.length > 0) hote=args[0] ; try {
InetAddress address = InetAddress.getByName(host); for(int i = 1 ; i < 1024; i++) { try { s=new Socket(address,i);
System.out.println("Server attached to port "+ i + " of " + address);
} catch (ConnectException e) { ; } catch (IOException e) { System.err.println(e); }}
} catch (UnknownHostException e) { System.err.println(e) ; }}}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-29
Stream Communication: Java API (4)
Example 2: manipulating InetAddress addressesarlequin{elhadef}120: java Ports2Server attached to port 7 of www.dmi.usherb.ca/132.210.40.10Server attached to port 9 of www.dmi.usherb.ca/132.210.40.10Server attached to port 13 of www.dmi.usherb.ca/132.210.40.10Server attached to port 15 of www.dmi.usherb.ca/132.210.40.10Server attached to port 19 of www.dmi.usherb.ca/132.210.40.10Server attached to port 25 of www.dmi.usherb.ca/132.210.40.10Server attached to port 37 of www.dmi.usherb.ca/132.210.40.10Server attached to port 53 of www.dmi.usherb.ca/132.210.40.10Server attached to port 79 of www.dmi.usherb.ca/132.210.40.10Server attached to port 80 of www.dmi.usherb.ca/132.210.40.10Server attached to port 109 of www.dmi.usherb.ca/132.210.40.10Server attached to port 110 of www.dmi.usherb.ca/132.210.40.10Server attached to port 111 of www.dmi.usherb.ca/132.210.40.10Server attached to port 113 of www.dmi.usherb.ca/132.210.40.10Server attached to port 143 of www.dmi.usherb.ca/132.210.40.10
Ex
ecu
tio
n r
es
ult
s
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-30
Stream Communication: Java API (5)
Example 3: manipulating socket’s attributesimport java.net.*; import java.io.*;public class Attributes { public static void main(String[] args) { Socket s; for(int i = 0 ; i < args.length ; i++) {
try { s=new Socket(args[i],80); System.out.println("\nConnect to "+ s.getInetAddress() + " on port " + s.getPort() + "\nfrom port "+ s.getLocalPort() + " of "+ s.getLocalAddress()) ; } catch (ConnectException e) { ;
} catch (IOException e) { System.err.println(e); } } }}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-31
Stream Communication: Java API (5)
Example 3: manipulating socket’s attributesimport java.net.*; import java.io.*;public class Attributes { public static void main(String[] args) { Socket s; for(int i = 0 ; i < args.length ; i++) {
try { s=new Socket(args[i],80); System.out.println("\nConnect to "+ s.getInetAddress() + " on port " + s.getPort() + "\nfrom port "+ s.getLocalPort() + " of "+ s.getLocalAddress()) ; } catch (ConnectException e) { ;
} catch (IOException e) { System.err.println(e); } } }}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-32
Stream Communication: Java API (6)
Manipulating data streams:
Get I/O stream: functions
public InputStream getInputStream() throws IOException publi OutputStream getOutputStream() throws IOException
Manipulate streams with the following classes that offer many functionalities
DataInputStream
DataOutputStream
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-33
Stream Communication: Java API (7)
Example 4: read the date and the time from the Unix’ daytime server (port 13) on the host arlequin.dmi.usherb.ca
import java.net.*; import java.io.*;public class DateAndTime { public static void main(String[] args) { Socket s; String host; DataInputStream timeStream; host="arlequin.dmi.usherb.ca"; try { InetAddress address = InetAddress.getByName(host);
try { s=new Socket(address,13); timeStream = new DataInputStream(s.getInputStream());
String DateTime= timeStream.readLine(); System.out.println("Date and time on: "+host+" are "+DateTime); } catch (ConnectException e) { System.err.println(e);
} catch (IOException e) { System.err.println(e); } } catch (UnknownHostException e) { System.err.println(e); } }}
arlequin{elhadef}131: java DateAndTime.javaDate and time on: arlequin.dmi.usherb.ca are Sun Sep 22 17:18:23 2002
Execution results:
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-34
Constructors: create a TCP socket at a server port for listening for connect requests from clients
public ServerSocket(int port) throws IOException, … public ServerSocket(int port, int backlog) throws IOExcept… public ServerSocket(int port, int backlog, InetAddress
bindAddr) throws IOException, … port: the specified port, or 0 to use any free port bindAddr: the local InetAddress the server will bind to backlog: the maximum length of the queue
Stream Communication: Java API (8)
Server: Class ServerSocket: used by a server to establish a connection
with a client
Method used to establish the communication: accept a connection
socket accept() throws IOException
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-35
import java.net.*; import java.io.*;public class TCPClient {public static void main (String args[]) { // arguments supply message and hostname
Socket s = null; try{ int serverPort = 7896; s = new Socket(args[1], serverPort); DataInputStream in = new DataInputStream( s.getInputStream()); DataOutputStream out =new DataOutputStream( s.getOutputStream()); out.writeUTF(args[0]); // UTF is a string encoding see Sn. 4.4
String data = in.readUTF(); // read a line of data from the stream
System.out.println("Received: "+ data) ; }catch (UnknownHostException e) {System.out.println("Socket:"+e.getMessage()); }catch (EOFException e){System.out.println("EOF:"+e.getMessage()); }catch (IOException e){System.out.println("readline:"+e.getMessage()); }finally {if(s!=null) try {s.close();
}catch (IOException e) {System.out.println ("close:" + e.getMessage());}}}}
Stream Communication: Java API (9)
Example 5: TCP Client connects to a server, sends a request and waits for a response
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-36
import java.net.*;import java.io.*;public class TCPServer {public static void main (String args[]) { try{
int serverPort = 7896; // the server portServerSocket listenSocket = new ServerSocket(serverPort);while(true) {
Socket clientSocket = listenSocket.accept();Connection c = new Connection(clientSocket);
} } catch(IOException e) {System.out.println("Listen socket:"+e.getMessage());}}}
class Connection extends Thread { DataInputStream in; DataOutputStream out; Socket clientSocket;
Stream Communication: Java API (10)
Example 5 (continued): TCP Server establishes a connection with each client and displays its request
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-37
public Connection (Socket aClientSocket) { try {
clientSocket = aClientSocket;in = new DataInputStream( clientSocket.getInputStream());out =new DataOutputStream( clientSocket.getOutputStream());this.start();
} catch(IOException e) {System.out.println("Connection:"+e.getMessage());}}
public void run(){ try { // an echo server
String data = in.readUTF(); // read a line of data from the streamout.writeUTF(data);
}catch (EOFException e){System.out.println("EOF:"+e.getMessage()); } catch(IOException e) {System.out.println("readline:"+e.getMessage()); } finally{ try {clientSocket.close();}catch (IOException e){/*close failed*/}}}}
Stream Communication: Java API (11)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-38
RMI (Remote Method Invocation) (1)
Distributed object model: allow objects at different processes to communicate with each other using calls to remote methods
B and F: distant objects
C must have a reference to object E so that it can invoke
one of its methods
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-39
Before Studying RMI
External Data Representation
CORBA’s CDR
JAVA’s Object Serialization
Remote Object Reference
Remote Interface
RMI (continued)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-40
External Data Representation and Marshalling (1)
Different representations:
Floating-point numbers: different ways
Different coding to represent characters
Different formats: Little-endian, big-endian
converted into sequences of bytes Receiving process
Rebuild the data structures
Sending processInformation to be
transmitted = data structures (set of
interconnected objects)External data Representation
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-41
External Data Representation and Marshalling (2)
Different tools:
Form suitable for transmission into a message (binary, ASCII, e.g., HTTP)
Data collection
Marshalling
Unmarshalling
Carried out by a middleware layer
CORBA’s Common Data Representation (CDR)
JAVA’s Object Serialization
SUN’s XDR Standard: exchange of messages between clients et servers SUN NFS (Network File System)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-42
Defined with CORBA 2.0 [Object Management Group, 1998]
Binary format: arguments and results of the invocations
CORBA’s CDR (1)
Can represent all data types: short, long, unsigned short, unsigned long, float, double, char, boolean, octet, any (tout type simple or composed : string, array, struct, enumerated, union, …)
CDR (CORBA) & XDR (SUN): types not included, suppose that the sender and the receiver both know the order and the field types
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-43
Example:
CORBA’s CDR (2)
unsigned long (32 bits)
{‘Smith’, ‘London’, 1934} struct Person { string name; string place; long year;};
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-44
JAVA’s Object Serialization (1)
Binary format: messages are build from an object or hierarchy of objects
Java RMI: objects are passed as parameters or results to method invocations
Class ObjectOutputStream: writing the contents of the instance variables
Class ObjectInputStream: reconstructing the original message
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-45
JAVA’s Object Serialization (2)
Example: Class PersonPublic class Person implements Serializable { private String name; private String place; private int year; public Person (String aName,
String a Place, int aYear) {name = aName;place = aPlace;year = aYear;
} … }
Person p= new Person("Smith", "London",
1934);
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-46
JAVA’s Object Serialization (3)
Class ObjectOutputStream ObjectOutputStream(OutputStream) ObjectOutputStream(void) write(byte[]) write(int) writeByte(int) writeChar(int) writeFloat(float) writeLong(long) writeShort(int) writeUTF(String) writeBytes(String) writeObject(Object) writeDouble(double) writeBoolean(boolean) …
Person p= new Person("Smith", "London", 1934);
// SerializationObjectOutputStream SP = new ObjectOutputStream();SP.writeObject(p);
// DeserializationObjectInputStream DSP = new ObjectInputStream();Person aPerson = DSP.readObject();
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-47
Remote Object Reference
Server Process
Client ProcessInvokes one method of a remote object
Invocationmessage
Unique identifierof the process
Remote Object Reference: remote object identifier valid in a distributed system
(local) incremented when the process creates an object
Unicity: space
Unicity: time
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-48
Remote Interface (1)
Specify which method can be remotely invoked
Remote object: can invoke only the methods m1-m3 published in the remote interface
Local object: can invoke all methods m1-m6
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-49
Remote Interface (2)
Example: CORBA’s Interface Definition Language (IDL)
// In file Person.idlstruct Person {
string name; string place;long year;
} ;interface PersonList {
readonly attribute string listname;void addPerson(in Person p) ;void getPerson(in string name, out Person p);long number();
};
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-50
No Not applicable
Not applicable MaybeCORBA
RMI (Remote Method Invocation) (2)
RMI invocation semantics:
Retransmit request message
Duplicate filtering
Re-execute procedure or retransmit reply
Yes Yes retransmit reply At-most-oneJava RMI, CORBA
Yes No Re-execute procedure At-least-oneSUN/RPC
Fault tolerance measures
Invocation semantics
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-51
RMI (Remote Method Invocation) (3)
Architecture:
RMI Client RMI Server
Stub Skeleton
Remote Reference Layer (RRL)
Transport Layer
Remote Reference Layer (RRL)
Transport Layer
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-52
RMI (Remote Method Invocation) (4)
Programming with RMI: steps to follow
1) Define the interfaces of all distant classes
2) Create and compile the implementations of these classes
3) Create stub and skeleton classes: RMIC
4) Create and compile a server application
5) Start RMIREGISTRY and execute the server application
6) Create and compile a client program that invokes the distant methods
7) Start client application
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-53
RMI (Remote Method Invocation) (5)
Case study: A bank’s application capable of managing multiples
accounts
It’ll be placed on a distant machine, interrogated and manipulated by clients
1) Define the interfaces of all distant classes Class CreditManager : search or create a bank account
Class CreditCard: make purchases, set up signature, or get the account’s state
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-54
RMI (Remote Method Invocation) (6)
Class CreditManager:
package credit;import credit.*;import java.rmi.*;
public interface CreditManager extends Remote {
public CreditCard findCreditAccount(String Customer) throws UnknownAccountException, RemoteException;
public CreditCard newCreditAccount(String newCustomer)
throws DuplicateAccountException, RemoteException;}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-55
RMI (Remote Method Invocation) (7)
Class CreditCard:
package credit;import credit.*;import java.rmi.*;
public interface CreditCard extends Remote {
public float getCreditLine() throws RemoteException;
public void makePurchase(float amount, int signature) throws InvalidSignatureException, RemoteException,
CreditLineExceededException;
public void setSignature(int pin) throws RemoteException;}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-56
RMI (Remote Method Invocation) (8)
2) Create and compile the implementations of these classes
package credit;import java.rmi.*;import java.rmi.server.*;import java.util.Hashtable;
public class CreditManagerImpl extends UnicastRemoteObject implements CreditManager {
private static transient Hashtable accounts = new Hashtable();
public CreditManagerImpl() throws RemoteException { }…
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-57
RMI (Remote Method Invocation) (9)
2) Create and compile the implementations of these classes (continued) public CreditCard newCreditAccount(String customerName)
throws DuplicateAccountException, RemoteException { CreditCardImpl newCard = null; if (accounts.get(customerName) == null)
newCard = new CreditCardImpl(customerName); else throw new DuplicateAccountException();
accounts.put(customerName, newCard); return newCard;} …
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-58
RMI (Remote Method Invocation) (9)
2) Create and compile the implementations of these classes (continued)public CreditCard findCreditAccount(String customer)
throws UnknownAccountException, RemoteException {
CreditCardImpl account = (CreditCardImpl)accounts.get(customer);
if (account == null) throw new UnknownAccountException();
elsereturn account;
}}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-59
RMI (Remote Method Invocation) (10)
2) Create and compile the implementations of these classes (continued)package credit;import java.rmi.*;import java.rmi.server.*;import java.io.Serializable;
public class CreditCardImpl extends UnicastRemoteObject implements CreditCard, Serializable
{private float creditLine = 5000f;private int signature = 0;private String accountName;
…
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-60
RMI (Remote Method Invocation) (11)
2) Create and compile the implementations of these classes (continued)public CreditCardImpl(String customer)
throws RemoteException { accountName = customer;}
public float getCreditLine() throws RemoteException { return creditLine;}
public void setSignature(int pin) throws RemoteException { signature = pin;}…
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-61
RMI (Remote Method Invocation) (12)
2) Create and compile the implementations of these classes (continued)public void makePurchase(float amount, int signature)
throws InvalidSignatureException, RemoteException, CreditLineExceededException {
if (signature != this.signature) throw new InvalidSignatureException();
if (amount > creditLine) throw new CreditLineExceededException();
else creditLine -= amount;
}}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-62
class Naming void rebind (String name, Remote obj) void bind (String name, Remote obj) void unbind (String name, Remote obj) Remote lookup(String name) String [] list()
RMI (Remote Method Invocation) (13)
4) Create and compile a server application
//computerName:port/objectName
Where to find RMIregistry
RMIregistry (binder): maintains a table containing mapping from textual names to remote object references
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-63
package credit;import java.util.*;import java.rmi.*;
public class ServerBank { public static void main (String args[]) { System.setSecurityManager(new RMISecurityManager()); try {
CreditManagerImpl cmi = new CreditManagerImpl(); Naming.rebind("cardManager", cmi);
} catch (Exception e) { System.out.println(e.getMessage());
}}}
RMI (Remote Method Invocation) (13)
4) Create and compile a server application
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-64
RMI (Remote Method Invocation) (14)
6) Create and compile a client program that invokes the distant methods
package credit;import java.rmi.*;public class ClientBank { public static void main(String args[]) {
CreditManager cm = null;CreditCard account = null;if (args.length < 3) { System.err.println("Usage : java ClientBank" +
" <server> <name1> <name2>");System.exit (1);
}…
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-65
RMI (Remote Method Invocation) (15)
6) Create and compile a client program that invokes the distant methods (continued)
System.setSecurityManager(new RMISecurityManager());try { String url = new String ("rmi://" + args[0] + "/cardManager"); cm = (CreditManager)Naming.lookup(url);} catch (Exception e) { System.out.println(“ Error while accessing the bank manager" + e);}try { account = cm.newCreditAccount(args[1]);} catch (Exception e) { System.out.println(“ Error during creation " + args[1] + " : " + e);} …
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-66
RMI (Remote Method Invocation) (16)
6) Create and compile a client program that invokes the distant methods (continued)
try { System.out.println(" Avail credit : " + account.getCreditLine()); account.setSignature(1234); account.makePurchase(100.00f, 1234); System.out.println(" Avail. credit : " + account.getCreditLine()); account.makePurchase(160.00f, 1234); System.out.println(" Avail. credit : "+ account.getCreditLine());} catch (Exception e) { System.out.println("Error " + args[1]);}try { account = cm.findCreditAccount(args[2]);} catch (Exception e) { System.out.println(“ Error while seeking for" + args[2] + e);}}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-67
RMI (Remote Method Invocation) (17)
7) Start client application javac -d . -classpath . *.java rmic -d . -classpath . credit.CreditCardImpl credit.CreditManagerImpl
CreditCardImpl_Skel.class CreditCardImpl_Stub.class CreditManagerImpl_Skel.class CreditManagerImpl_Stub.class
start java -Djava.security.policy=c:\BankRMI\permit.policy -Djava.rmi.server.codebase=file:///c:/BankRMI/ -classpath . credit.ServerBank
start rmiregistry
java -Djava.security.policy=c:\BankRMI\permit.policy -Djava.rmi.server.codebase=file:///c:/BankRMI/
-classpath . credit.ClientBank 209.197.157.169 Pierre Marie
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-68
RMI (Remote Method Invocation) (17)
7) Start client application
Execution results: Avail. credit: 5000.0Setting up signatureFirst purchase of 100 $Avail. credit: 4900.0Second purchase of 160 $Avail. credit: 4740.0Error while seeking for Marie
credit.UnknownAccountException
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-69
Readings
Tutorial: Getting Started Using RMI, http://java.sun.com/j2se/1.3/docs/guide/rmi/getstart.doc.html
Jim Waldo, Remote procedure calls and Java Remote Method Invocation, IEEE Concurrency, 6(3), pages 5-7, Sept 1998
A.D. Birrell and B.J. Nelson, Implementing Remote Procedure Calls (RPC), ACM Trans. on Computer Systems, 1984, pp 39-54
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-70
Group Communication
Types of Interprocess Communication
Client-Server Communication
Readings
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-71
Client-Server Communication(1)
Synchronous communication: Client process is blocked until the response is received from the server
Reliable: Server’s reply = acknowledgment
Client ServerRequest
getRequestdoOperation
(Wait)
..
Request-Reply Communication
(continuation)
Execute method
Select object
ReplysendReply
..
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-72
Int : generated by doOperation and copied by the server (message number + address + port)
RemoteObjectRef : a reference to a remote object encapsulated in a packet
Interface of remote object
Object Number
TimePort Number
Internet Address
32 bits32 bits32 bits32 bits
messageType
requestId
methodId
objectReference
arguments Array of bytes
Client-Server Communication(2)
Request-Reply message structure:
Int (0=Request, 1=Reply)
Int or Method
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-73
Client-Server Communication(3)
Primitives:
public byte [] doOperation (RemoteObjectRef o, int methodId,
byte[] arguments);
public byte[] getRequest();
public void sendReply(byte[] reply, InetAddress
clientHost, int clientPort);
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-74
Failure model for the RR protocol: primitives doOperation, getRequest and sendReply suffer from
Omission Faults Message delivery not guaranteed
Solutions: Timeouts
Client-Server Communication(4)
Enable servers to recognize two identical messages
Lost reply messages: the server re-execute only idempotent operations
History: save the results of the last executed request of each client
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-75
Client-Server Communication(5)
Depends on the application, one of these protocols will be used
RPC exchange Protocols:
Messages sent by
Client Server Client
R Request
RRA Request Reply Acknowledgment reply
RR Request Reply
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-76
Group Communication (1)
Multicast communication: sends one message to each member of the group
Multicast messages provide a useful infrastructure for distributed systems with the following characteristics:
Fault tolerance based on replicated services
Replicated data: data are replicated to increase the performance of service
Propagation of event notifications (example)
Applications types: (examples)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-77
Group Communication (2)
IP multicast:
In practice only UDP is used for multicast
IP
IP multicast
UDP
Packet
Group(details)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-78
Group Communication (3)
API Java : class MulticastSocket
void joinGroup(InetAddress groupe)
void leaveGroup(InetAddress groupe)
synchronized void send(DatagramPacket dp, byte TTL) (TTL : definition)
synchronized void receive(DatagramPacket dp)
InetAddress getInterface() Retrieve the address of the network interface used for multicast packets
setInterface(InetAddress nt) Set the outgoing network interface for multicast packets on this
socket, to other than the system default
MulticastSocket() MulticastSocket(int port)
byte getTTL() void setTTL(byte TTL)
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-79
Group Communication (4)
Example : a member joins the group, sends and receives datagrams
import java.net.*; import java.io.*;
public class MulticastPeer{
public static void main(String args[]){
// args[0] = message to multicast to the group
// args[1] = IP address of the group (e.g. "228.5.6.7")
MulticastSocket s =null;
try {
InetAddress group =
InetAddress.getByName(args[1]);
s = new MulticastSocket(6789);
s.joinGroup(group);
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-80
Group Communication (5)
Example (continued):
byte [] m = args[0].getBytes();
DatagramPacket msgOut = new DatagramPacket(m,
m.length, group, 6789);
s.send(msgOut);
byte[] buffer = new byte[1000]; // get messages from others in group
for(int i=0; i< 3;i++) {
DatagramPacket msgIn = new DatagramPacket(buffer,
buffer.length);
s.receive(msgIn);
System.out.println("Rec. :" + new String(msgIn.getData())); }
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-81
Group Communication (6)
Example (suite):
s.leaveGroup(group);
} catch (SocketException e){System.out.println("Socket: " +
e.getMessage());
} catch (IOException e){System.out.println("IO: " +
e.getMessage());
} finally {if(s != null) s.close();}
}}
© Mourad Elhadef, Ph. D.CSI408-Distributed Information Systems 4&5-82
Readings
MBone and Multicast Informations, http://www.infres.enst.fr/~dax/network/multicast.html
Ian Brown et al., Internet Multicast Tomorrow, Internet Protocol Journal, Vol 5(4), Dec. 2002 http://www.isoc.org/pubs/int/cisco-1-6.html