1 java rmi g53acc chris greenhalgh. 2 contents l java rmi overview l a java rmi example –overview...
TRANSCRIPT
1
Java RMIJava RMI
G53ACCG53ACC
Chris Greenhalgh Chris Greenhalgh
2
ContentsContents
Java RMI overviewJava RMI overview A Java RMI exampleA Java RMI example
– Overview Overview – Walk-throughWalk-through
Implementation notesImplementation notes– Argument passingArgument passing– File requirementsFile requirements
RPC issues and RMIRPC issues and RMI Other problems with RMIOther problems with RMI
See also RMI tutorial, Farley p.71-83See also RMI tutorial, Farley p.71-83
3
Java RMIJava RMI
Distributed Object SystemDistributed Object System– Allows objects in one process to invoke Allows objects in one process to invoke
methods on objects in another process.methods on objects in another process. Supports bind/find/execute service-oriented Supports bind/find/execute service-oriented
interactioninteraction– RMI registry is naming serviceRMI registry is naming service
Java-specificJava-specific Optional CORBA interoperabilityOptional CORBA interoperability
4
Java RMI system elementsJava RMI system elements
RMI infrastructure = base classes and interfaces: RMI infrastructure = base classes and interfaces: – provides communication and naming.provides communication and naming.
RMI compiler:RMI compiler:– generates client stubs, to translate client generates client stubs, to translate client
requests to standard form.requests to standard form.– generates (optional) server stub (“skeleton”) to generates (optional) server stub (“skeleton”) to
translate standard form to server translate standard form to server implementation form.implementation form.
5
Building an example distributed Building an example distributed applicationapplication
A “ticket” issuing serviceA “ticket” issuing service– E.g. next customer to be served, or first-come-E.g. next customer to be served, or first-come-
first servedfirst served– Managed resource = next ticket numberManaged resource = next ticket number
Centralised to control allocation, e.g. ensure no Centralised to control allocation, e.g. ensure no duplicatesduplicates
Client: Client: – Locates serverLocates server– Requests the next ticketRequests the next ticket– Prints it on the screenPrints it on the screen
6
Example application Example application processes/machinesprocesses/machines
TicketServerobject
Process/Application BClientobject
Process/Application A
RMI objectsand classes
RMI objectsand classes
RemoteMethod
Invocations(over TCP/IP connections)
RMI registry
Server machine
Client stub
Find
Bind
Use
Client machine
7
1. Specify the common interface1. Specify the common interface
Define the interface as a Java interfaceDefine the interface as a Java interface
– Like a normal local interfaceLike a normal local interface Set of methods with name, arguments, return type and exceptionsSet of methods with name, arguments, return type and exceptions
But…But…
– must extend must extend java.rmi.Remotejava.rmi.Remote interface interface Hint to marshalling codeHint to marshalling code
– all methods throw all methods throw java.rmi.RemoteExceptionjava.rmi.RemoteException NOTE: unavoidable complications - network-related errors (e.g. NOTE: unavoidable complications - network-related errors (e.g.
server unavailable or unreachable, timed out)server unavailable or unreachable, timed out)
– All types must be primitive (All types must be primitive (intint etc.), implement etc.), implement java.io.Serializablejava.io.Serializable or implement or implement java.rmi.Remotejava.rmi.Remote
8
Example interfaceExample interface
import java.rmi.*;import java.rmi.*;public interface TicketServer extends Remote public interface TicketServer extends Remote {{ public int getNextTicket (String name) public int getNextTicket (String name) throws RemoteException;throws RemoteException;}}
9
Notes on defining the interfaceNotes on defining the interface
What distinct requests can a client make?What distinct requests can a client make?
– Each request = 1 methodEach request = 1 method How can each request by concisely described?How can each request by concisely described?
– = method name= method name What information does the client have that the server What information does the client have that the server
needs to perform the request?needs to perform the request?
– = arguments – types and names= arguments – types and names What might be anticipated to go wrong?What might be anticipated to go wrong?
– = exceptions= exceptions If it works, what information does the client need back?If it works, what information does the client need back?
– = return type= return type
10
2. Implement the service2. Implement the service
Implement the service as a Java classImplement the service as a Java class– extend extend java.rmi.server.UnicastRemoteObjectjava.rmi.server.UnicastRemoteObject
Inherits server support, networking, etc.Inherits server support, networking, etc.
– Implement the define interface and its methodImplement the define interface and its method The “business logic”The “business logic”
– (Typically) Implement a main method to:(Typically) Implement a main method to: Create a new instance of the serverCreate a new instance of the server Register (bind) this with the naming service Register (bind) this with the naming service
(rmiregistry) so that clients can find it(rmiregistry) so that clients can find it
11
Example server implementationExample server implementation
– import java.rmi.*;import java.rmi.*;import import java.rmi.server.UnicastRemoteObject;java.rmi.server.UnicastRemoteObject;
public class TicketServerImpl public class TicketServerImpl extends UnicastRemoteObject extends UnicastRemoteObject implements TicketServer implements TicketServer {{ // cons throws RemoteException // cons throws RemoteException TicketServerImpl() TicketServerImpl() throws RemoteException throws RemoteException { }; { };
// cont… // cont…
12
– // service state/resource// service state/resource int nextTicket=0; int nextTicket=0;
// business logic - implementation // business logic - implementation public int getNextTicket(String name) public int getNextTicket(String name) throws RemoteException { throws RemoteException { return nextTicket++; return nextTicket++; } }
// cont… // cont…
13
– // app – start server// app – start server public static void main(String [] args) { public static void main(String [] args) { // install RMI security manager // install RMI security manager System.setSecurityManager System.setSecurityManager (new RMISecurityManager()); (new RMISecurityManager()); try { try { String name = args[0]; String name = args[0]; //create new instance //create new instance TicketServerImpl server = TicketServerImpl server = new TicketServerImpl(); new TicketServerImpl(); // register with nameserver // register with nameserver Naming.rebind(name, server); Naming.rebind(name, server); } } catch(Exception e) { catch(Exception e) { // errors... // errors... } } } }
– }//end}//end
14
3. Implement client3. Implement client
ClientClient– installs appropriate security manager (and installs appropriate security manager (and
security policy) for client stubssecurity policy) for client stubs– looks up server in name servicelooks up server in name service
like URL: “like URL: “rmi://machine:port/namermi://machine:port/name”” defaults are “defaults are “rmi://localhost:1099/rmi://localhost:1099/”” ““localhostlocalhost” = “this machine”” = “this machine”
– obtains handle (client stub) which implements obtains handle (client stub) which implements interfaceinterface
– performs remote operationsperforms remote operations– Handles errors (exceptions)Handles errors (exceptions)
15
import java.rmi.*;import java.rmi.*;public class TicketClient {public class TicketClient { public static void main(String [] args) { public static void main(String [] args) { // install RMI security manager // install RMI security manager System.setSecurityManager System.setSecurityManager (new RMISecurityManager()); (new RMISecurityManager()); try { try { // look up in nameserver // look up in nameserver String fullname = args[0]; String fullname = args[0]; TicketServer server = TicketServer server = (TicketServer)Naming.lookup(fullname);(TicketServer)Naming.lookup(fullname);
// cont… // cont…
16
// get ticket - remote method!// get ticket - remote method! int ticket = server. int ticket = server. getNextTicket("TicketClient"); getNextTicket("TicketClient"); System.out.println("Got ticket "+ System.out.println("Got ticket "+ ticket); ticket); } catch (Exception e) { } catch (Exception e) { /* error… */ /* error… */ } } } }}}
17
4. Compile & Generate stubs4. Compile & Generate stubs
Compile server implementation (javac) and Compile server implementation (javac) and process with RMI compiler (rmic)process with RMI compiler (rmic)– generates client stub class generates client stub class
(TicketServerImpl_Stub.class)(TicketServerImpl_Stub.class) Required by client (only)Required by client (only)
– generates server stub (skeleton) classgenerates server stub (skeleton) class Optionally required by server (only) (if not using Optionally required by server (only) (if not using
reflection-based despatcher - see RPC notes)reflection-based despatcher - see RPC notes)
– See RMI Tutorial for details, e.g. command line See RMI Tutorial for details, e.g. command line optionsoptions
18
5. Run the server5. Run the server
Run naming service (rmiregistry):Run naming service (rmiregistry):rmiregistry [<port>]rmiregistry [<port>]
– Must be on the same machine as the serverMust be on the same machine as the server Run server application, whichRun server application, which
– creates a server object instance and creates a server object instance and – registers with naming serviceregisters with naming service
See Tutorial for command line optionsSee Tutorial for command line options– E.g. security policy fileE.g. security policy file
19
6. Run the client6. Run the client
Run client whichRun client which– Looks up the server in the specified registryLooks up the server in the specified registry– Invokes operations on the server…Invokes operations on the server…
See Tutorial for command line optionsSee Tutorial for command line options
20
Argument Passing in Java RMI (i)Argument Passing in Java RMI (i)
All arguments must be one of:All arguments must be one of:– basic types basic types
Serialised, passed by valueSerialised, passed by value E.g. int, long, short, byte, char, boolean, float, E.g. int, long, short, byte, char, boolean, float,
doubledouble
– implement implement java.io.Serializablejava.io.Serializable serialised, passed by value serialised, passed by value i.e. an identical copy of the object is made at the i.e. an identical copy of the object is made at the
other endother end Exact class must be found remotelyExact class must be found remotely operations will be local to each copyoperations will be local to each copy
21
Serializable exampleSerializable example
E.g. E.g. java.lang.Stringjava.lang.String, or your own custom , or your own custom classesclasses– E.g.E.g.public class MyPersonClass public class MyPersonClass implements java.io.Serializable { implements java.io.Serializable { public String firstName; public String firstName; public String lastName; public String lastName; public int ageYears; public int ageYears; public MyPersonClass children[]; public MyPersonClass children[]; // sample (local) method // sample (local) method public int getAge() public int getAge() { return ageYears; } { return ageYears; }}}
22
Argument Passing in Java RMI (ii)Argument Passing in Java RMI (ii)
or:or:– implement implement java.rmi.Remote java.rmi.Remote
be passed as a network referencebe passed as a network reference i.e. a network i.e. a network handlehandle (copy of a client proxy object) (copy of a client proxy object)
is serialised and sent, not the object data itselfis serialised and sent, not the object data itself client stub class must be located by receiving client stub class must be located by receiving
processprocess operations on the received proxy object will operations on the received proxy object will
themselves be remotethemselves be remote– i.e. forwarded to the original objecti.e. forwarded to the original object
– e.g. “callbacks”e.g. “callbacks”
23
Unmarshalling serialized objectsUnmarshalling serialized objects For Serializable objects and stubs of For Serializable objects and stubs of
Remote objects the receiving process JVM Remote objects the receiving process JVM needs to find the same class (class file)needs to find the same class (class file)– Could already be present at receiving Could already be present at receiving
end, in class pathend, in class path– Can be downloaded from a remote web server Can be downloaded from a remote web server
via HTTPvia HTTP server is run with server is run with java.rmi.server.codebasejava.rmi.server.codebase property property pointing to webserver URL where class files are putpointing to webserver URL where class files are put
Value is included in marshalled informationValue is included in marshalled information Used by receiving process IF ALLOWEDUsed by receiving process IF ALLOWED
– This is why RMI security manager is installedThis is why RMI security manager is installed
24
Which files, where?Which files, where?
Client needs:Client needs:– Client implementationClient implementation
(must be local)(must be local)
– InterfaceInterface And any Serializable classes it usesAnd any Serializable classes it uses (must be local if directly used in the client (must be local if directly used in the client
implementation code)implementation code)
– Client stub Client stub (can be downloaded since not directly referenced in (can be downloaded since not directly referenced in
client implementation class)client implementation class)
25
Server needs:Server needs:– Server implementationServer implementation
(must be local)(must be local)
– Interface Interface And any Serializable classes it usesAnd any Serializable classes it uses (must be local since server implements the interface (must be local since server implements the interface
and methods)and methods)
– Server skeleton Server skeleton (if used, must be local)(if used, must be local)
– Client stub (to send to registry)Client stub (to send to registry)
26
Rmiregistry needs:Rmiregistry needs:– InterfaceInterface
And any Serializable classes it usesAnd any Serializable classes it uses
– Client stub Client stub (can all be downloaded since the registry code does (can all be downloaded since the registry code does
not explicitly refer to any of these classes)not explicitly refer to any of these classes)
27
RPC issues in RMI (ii)RPC issues in RMI (ii)
TransparencyTransparency– Pretty good – normal Java interfacePretty good – normal Java interface– But implements Remote and methods throw But implements Remote and methods throw
RemoteExceptionsRemoteExceptions– Also no (easy) way to identify client or link Also no (easy) way to identify client or link
client requests in “sessions”…client requests in “sessions”…
28
Client/session tracking in RMI interfacesClient/session tracking in RMI interfaces
Client is not identified to server codeClient is not identified to server code– No automatic link between successive calls by the same No automatic link between successive calls by the same
client (cf. “sessions”)client (cf. “sessions”) Not like using TCP or UDP directlyNot like using TCP or UDP directly
– Implications for security, e.g. when authentication must Implications for security, e.g. when authentication must be done (each method)be done (each method)
Options:Options:– Explicit client identification per messageExplicit client identification per message
From client, e.g. user id, orFrom client, e.g. user id, or Returned by initial server operation (cf. “login”/”start”) Returned by initial server operation (cf. “login”/”start”)
session idsession id
– Client-specific server returned by initial server Client-specific server returned by initial server operation (second interface, server object & stub)operation (second interface, server object & stub)
29
RPC issues in RMI (ii)RPC issues in RMI (ii)
HeterogeneityHeterogeneity– Java is cross platform :-)Java is cross platform :-)– Java is not cross language…Java is not cross language…– However additional tool and runtime support However additional tool and runtime support
allowsallows RMI interfaces to be translated to CORBA IDL RMI interfaces to be translated to CORBA IDL
interfaces and interfaces and RMI to use CORBA IIOP protocolRMI to use CORBA IIOP protocol Allowing interoperability with any CORBA Allowing interoperability with any CORBA
client/serverclient/server
30
RPC issues in RMI (iii)RPC issues in RMI (iii)
ConcurrencyConcurrency– Client requests are always blockingClient requests are always blocking
Needed to link RemoteException to call contextNeeded to link RemoteException to call context
– Server threads are provided by server runtimeServer threads are provided by server runtime Pool of despatcher threadsPool of despatcher threads Server can handle multiple remote requests Server can handle multiple remote requests
concurrentlyconcurrently BindingBinding
– Distributed object model, supported by Distributed object model, supported by rmiregistry and Remote argumentsrmiregistry and Remote arguments
– See naming notesSee naming notes
31
Problems with RMIProblems with RMI
Problems with class versioning Problems with class versioning (e.g. in the rmiregistry)(e.g. in the rmiregistry)– May not unload old versions of classes if May not unload old versions of classes if
interfaces are changedinterfaces are changed No asynchronous invocationsNo asynchronous invocations No reply-less invocations (c.f. CORBA ‘oneway’)No reply-less invocations (c.f. CORBA ‘oneway’) => Blocking invocations=> Blocking invocations
– Failure of server can take 30s to several minutes Failure of server can take 30s to several minutes to detect!to detect!
– May need extra worker threads to ‘push’ May need extra worker threads to ‘push’ invocationsinvocations