Download RMI

Document related concepts
no text concepts found
Transcript
CIS007-3 Comparative Integrated
Systems
Java Remote Method Invocation (RMI)
Dr Marc Conrad
Sue Brandreth
1
Outline
• Introduction to RMI
• RMI architecture
• RMI naming service
2
Introduction to RMI
3
The Network is the Computer
• Consider the following program organisation:
method call
SomeClass
computer 1
AnotherClass
returned object
computer 2
• If the network is the computer, we ought to be able to
put the two classes on different computers
• RMI is ONE technology that makes this possible
4
RMI Introduction
• RMI stands for Java Remote Method Invocation, RMI
allows you to write distributed objects using Java.
• At the most basic level, RMI is Java's remote
procedure call (RPC) mechanism.
• Traditional RPC systems (Corba, DCOM) are
language-neutral, and therefore are essentially leastcommon-denominator systems. They cannot provide
functionality that is not available on all possible target
platforms.
Dr M. E. AYDIN / Dr M. CONRAD
5
RMI Introduction
• RMI is focused on Java, with connectivity to existing
systems using native methods. This means RMI can
take a natural, direct, and fully-powered approach to
provide a distributed computing technology that lets
you add Java functionality throughout your system in
an incremental, yet seamless way.
• RMI provides a simple model for distributed
computing with Java objects. These objects can be
new Java objects, or can be simple Java ‘wrappers’
around an existing API.
• Because RMI is centred around Java, it brings the
power of Java safety and portability to distributed
computing.
Dr M. E. AYDIN / Dr M. CONRAD
6
RMI and other technologies
• CORBA (Common Object Request Broker
Architecture) has long been king
– CORBA supports object transmission between virtually any
languages
– Objects have to be described in IDL (Interface Definition
Language), which looks a lot like C++ data definitions
– CORBA is complex and flaky
• Microsoft supported CORBA, then COM, now .NET
• RMI is purely Java-specific
– Java to Java communications only
– As a result, RMI is much simpler than CORBA
7
RMI Basics
• RMI is the Java Distributed Object Model for facilitating
communications among distributed objects.
• RMI is a higher-level API built on top of sockets.
• Socket-level programming allows you to pass data
through sockets among computers. RMI enables you
not only to pass data among objects on different
systems, but also to invoke methods in a remote object.
8
The Differences between RMI and RPC
• RMI is similar to Remote Procedure Calls (RPC) in the
sense that both RMI and RPC enable you to invoke
methods, but there are some important differences.
• With RPC, you call a standalone procedure. With RMI,
you invoke a method within a specific object. RMI can
be viewed as object-oriented RPC.
9
The Differences between RMI and
Traditional Client/Server Approach
• A RMI component can act as both a client and a server,
depending on the scenario in question.
• A RMI system can pass functionality from a server to a
client and vice versa.
• A client/server system typically only passes data back
and fourth between server and client.
10
How does RMI work?
An object that
resides on the
client host and
serves as a
surrogate for
the remote
server object.
A program that
invokes the
methods in the
remote server
object.
A subinterface of
java.rmi.Remote
that defines the
methods for the
server object.
Client Host
Server Host
Server Object
Interface
Client
Program
(4) Data
Communication
Server
Stub
(3) Return
Server Stub
(2) Look for Server Object
(1)
(2)
(3)
(4)
Server Object
Interface
Server
Skeleton
RMI Registry Host
An object that
resides on the
server host,
communicates
with the stub
and the actual
server object.
Server
Object
(1) Register Server Object
An instance of
the server
object
interface.
RMI
Registry
RMI works as follows:
A server object is registered with the RMI
registry;
A client looks through the RMI registry for the
remote object;
Once the remote object is located, its stub is
returned in the client;
The remote object can be used in the same
way as a local object. The communication
between the client and the server is handled
11
through the stub and skeleton.
A utility that
registers remote
objects and
provides
naming services
for locating
objects.
Passing Parameters
• When a client invokes a remote method with
parameters, passing parameters are handled under
the cover by the stub and the skeleton.
12
RMI and other technologies
• Java makes RMI (Remote Method Invocation)
fairly easy, but there are some extra steps
• To send a message to a remote “server
object,”
– The “client object” has to find the object
• Do this by looking it up in a registry
– The client object then has to marshal the
parameters (prepare them for transmission)
• Java requires Serializable parameters
– The server object has to unmarshal its parameters, do
its computation, and marshal its response
– The client object has to unmarshal the response
13
Terminology
• A remote object is an object on another computer
• The client object is the object making the request
(sending a message to the other object)
• The server object is the object receiving the request
• As usual, “client” and “server” can easily trade roles
(each can make requests of the other)
• The rmiregistry is a special server that looks up
objects by name
– Hopefully, the name is unique!
• rmic is a special compiler for creating stub (client)
and skeleton (server) classes
14
Processes
• For RMI, you need to be running three
processes
– The Client
– The Server
– The Object Registry, rmiregistry, which is like a
DNS service for objects
• You also need TCP/IP active
15
Interfaces
• Interfaces define behavior
• Classes define implementation
• Therefore,
– In order to use a remote object, the client must know its
behavior (interface), but does not need to know its
implementation (class)
– In order to provide an object, the server must know both its
interface (behavior) and its class (implementation)
• In short,
– The interface must be available to both client and server
– The class should only be on the server
16
Remote Interfaces and Classes
• A Remote class has two parts:
– The interface (used by both client and server):
• Must be public
• Must extend the interface java.rmi.Remote
• Every method in the interface must declare that it
throws java.rmi.RemoteException (other
exceptions may also be thrown)
– The class itself (used only by the server):
• Must implement a Remote interface
• Should extend
java.rmi.server.UnicastRemoteObject
• May have locally accessible methods that are not in
its Remote interface
17
Security
• It isn’t safe for the client to use somebody else’s code
on some random server
– Your client program should use a more conservative security
manager than the default
– System.setSecurityManager(new RMISecurityManager());
• Most discussions of RMI assume you should do this
on both the client and the server
– Unless your server also acts as a client, it isn’t really
necessary on the server
18
The Server Class
• The class that defines the server object should
extend UnicastRemoteObject
– This makes a connection with exactly one other computer
– If you must extend some other class, you can use
exportObject() instead
– Sun does not provide a MulticastRemoteObject class
• The server class needs to register its server object:
– String url = "rmi://" + host + ":" + port + "/" + objectName;
• The default port is 1099
– Naming.rebind(url, object);
• Every remotely available method must throw a
RemoteException (because connections can fail)
• Every remotely available method should be
synchronized
19
Hello World server: Interface
• import java.rmi.*;
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}
20
Hello World server: Class
• import java.rmi.*;
import java.rmi.server.*;
public class Hello extends UnicastRemoteObject
implements HelloInterface {
private String message; // Strings are serializable
{
public Hello (String msg) throws RemoteException
}
}
message = msg;
public String say() throws RemoteException {
return message;
}
21
Registering the Hello World server
• class HelloServer {
public static void main (String[] argv) {
try {
Naming.rebind("rmi://localhost/HelloServer",
new Hello("Hello, world!"));
System.out.println("Hello Server is ready.");
}
catch (Exception e) {
System.out.println("Hello Server failed: " + e);
}
}
}
22
The Hello World client program
• class HelloClient {
public static void main (String[] args) {
HelloInterface hello;
String name = "rmi://localhost/HelloServer";
try {
hello =
(HelloInterface)Naming.lookup(name);
System.out.println(hello.say());
}
catch (Exception e) {
System.out.println("HelloClient exception: " +
e);
}
}
23
}
rmic
• The class that implements the remote object should
be compiled as usual
• Then, it should be compiled with rmic:
– rmic Hello
• This will generate the file Hello_Stub.class
– The “Stub” class must be copied to the client area
24
Trying RMI
•
In three different terminal windows:
1. Run the registry program:
• rmiregistry
2. Run the server program:
• java HelloServer
3. Run the client program:
• java HelloClient

If all goes well, you should get the “Hello, World!”
message
25
Using RMI
A working RMI system is composed of several
parts.
• Interface definitions for the remote services
• Implementations of the remote services
• Stub and Skeleton files
• A server to host the remote services
• An RMI Naming service that allows clients to find the
remote services
• (A class file provider (an HTTP or FTP server) )
• A client program that needs the remote services
26
Using RMI
You take the following steps to build a system:
• Write and compile Java code for interfaces
• Write and compile Java code for implementation
classes
• Generate Stub and Skeleton class files from the
implementation classes
• Write Java code for a remote service host program
• Develop Java code for RMI client program
• Install and run RMI system
27
RMI Introduction
• RMI has several advantages over traditional RPC
systems.
Object Oriented: RMI can pass full objects as arguments and
return values, not just predefined data types.
– This means that you can pass complex types as a single
argument. You don’t have to have the client decompose an
object into primitive data types (as in existing RPC systems),
ship those data types, and then recreate on the server. RMI
lets you ship objects directly across the wire with no extra
client code.
30
RMI Introduction
– Mobile Behaviour: RMI can move behaviour (class
implementations) from client to server and server to client.
– For example, you can define an interface for examining
employee expense reports to see whether they conform to
current company policy. When an expense report is created,
an object that implements that interface can be fetched by
the client from the server. When the policies change, the
server will start returning a different implementation of that
interface that uses the new policies. The constraints will
therefore be checked on the client side - providing faster
feedback to the user and less load on the server - without
installing any new software on user's system. This gives you
maximal flexibility. Changing policies requires you to write
only one new Java class and install it once on the server
host.
Dr M. E. AYDIN / Dr M. CONRAD
31
RMI Introduction
32
RMI Introduction
• A client displays a GUI (graphical user interface) to a
user, who fills in the fields of the expense report.
Clients communicate with the server using RMI. The
server stores the expense reports in a database
using JDBC. So far this may look like any multi-tier
system, but there is an important difference-RMI can
download behaviour.
33
RMI Introduction
• Suppose that the company's policies about expense
reports change. For example, today the company
requires receipts only for expenses over £20.
Tomorrow the company decides this is too lenient. It
wants receipts for everything, except for meals that
cost less than £20. Without the ability to download
behaviour, what alternatives are there for designing
your system for change?
34
RMI Introduction
• With RMI you can have the client upload behaviour
from the server with a simple method invocation,
providing a flexible way to offload computation from
the server to the clients while providing users with
faster feedback.
• When a user is ready to write up a new expense
report, the client asks the server for an object that
embodies the current policies for expense reports as
expressed via a Policy interface written in Java.
Dr M. E. AYDIN / Dr M. CONRAD
35
RMI Introduction
• If this is the first time that the client's RMI runtime has
seen this particular implementation of the policy, RMI
will ask the server for a copy of the implementation.
• This means that policy is always dynamic. You can
change the policy by simply writing a new
implementation of the general Policy interface,
installing it on the server, and configuring the server
to return objects of this new type. From that point on,
any new expense reports will be checked against the
new policy by every client.
Dr M. E. AYDIN / Dr M. CONRAD
36
RMI Introduction
• This is a better approach than any static approach
because:
• All clients don't need to be halted and updated with
new software-software is updated on the fly as
needed.
• The server is not burdened with entry checking that
can be done locally.
• Allows dynamic constraints because object
implementations, not just data, are passed between
client and server.
• Lets users know immediately about errors.
Dr M. E. AYDIN / Dr M. CONRAD
37
RMI Introduction
– Design Patterns: Passing objects lets you use the full
power of object oriented technology in distributed computing
- such as two- and three-tier systems.
– When you can pass behaviour, you can use object oriented
design patterns in your solutions. All object oriented design
patterns rely upon different behaviours for their power
Without passing complete objects - both implementations
and type - the benefits provided by the design patterns
movement are lost.
Dr M. E. AYDIN / Dr M. CONRAD
38
RMI Introduction
– Safe and Secure: RMI uses built-in Java security
mechanisms that allow your system to be safe when users
downloading implementations.
– RMI uses the security manager defined to protect systems
from hostile applets to protect your systems and network
from potentially malicious downloaded code.
– In severe cases, a server can refuse to download any
implementations at all.
Dr M. E. AYDIN / Dr M. CONRAD
39
RMI Introduction
– Easy to Write/Easy to Use: RMI makes it simple to write remote
Java servers and Java clients that access those servers.
– A remote interface is an actual Java interface. A server has roughly
three lines of code to declare itself a server, and otherwise is like
any other Java object.
– This simplicity makes it easy to write servers for full-scale
distributed object systems quickly, and to rapidly bring up
prototypes and early versions of software for testing and evaluation.
– And because RMI programs are easy to write they are also easy to
maintain.
Dr M. E. AYDIN / Dr M. CONRAD
40
RMI Introduction
– Connects to Existing/Legacy Systems: RMI interacts with
existing systems (other platforms/programming languages) through
Java's native method interface JNI.
– Using RMI and JNI you can write your client in Java and use your
existing server implementation. When you use RMI/JNI to connect
to existing servers you can rewrite any parts of you server in Java
when you choose to, and get the full benefits of Java in the new
code.
– Similarly, RMI interacts with existing relational databases using
JDBC without modifying existing non-Java source that uses the
databases.
– JNI = Java Native Interface (JNI) is a standard programming
interface for writing Java native methods and embedding the Java
virtual machine into native applications. The primary goal is binary
compatibility of native method libraries across all Java virtual
machine implementations on a given platform.
– See http://docs.oracle.com/javase/7/docs/technotes/guides/jni/
Dr M. E. AYDIN / Dr M. CONRAD
41
RMI Introduction
– Write Once, Run Anywhere: RMI is part of Java's "Write Once,
Run Anywhere" approach.
– Any RMI based system is 100% portable to any Java Virtual
Machine*, as is an RMI/JDBC system.
– If you use RMI/JNI to interact with an existing system, the code
written using JNI will compile and run with any Java virtual
machine.
42
RMI Introduction
– Distributed Garbage Collection: RMI uses its distributed garbage
collection feature to collect remote server objects that are no longer
referenced by any clients in the network.
– Analogous to garbage collection inside a Java Virtual Machine,
distributed garbage collection lets you define server objects as
needed, knowing that they will be removed when they no longer
need to be accessible by clients.
43
RMI Introduction
– Concurrent Processing: RMI is multi-threaded, allowing
your servers to exploit Java threads for better concurrent
processing of client requests.
• Disadvantages?
44
Java RMI Architecture
45
The Design Goal for the RMI
Architecture
• The primary goal for the RMI designers was to allow
programmers to develop distributed Java programs
with the same syntax and semantics used for nondistributed programs.
• Therefore, they had to make the Java distributed
object model integrate naturally into the Java
programming language and the local object model, to
make the use of distributed Java objects similar to
using local Java objects
46
The Design Goal for the RMI
Architecture
• To do this, they had to carefully map how Java
classes and objects work in a single Java Virtual
Machine (JVM) to a new model of how classes and
objects would work in a distributed (multiple JVM)
computing environment.
Dr M. E. AYDIN / Dr M. CONRAD
47
The Design Goal for the RMI
Architecture
• RMI architects have succeeded; creating a system
that extends the safety and robustness of the Java
architecture to the distributed computing world.
• In the following slides, we will see how this is
achieved.
Dr M. E. AYDIN / Dr M. CONRAD
48
Interfaces: The Heart of RMI
• The RMI architecture is based on one important
principle:
– The definition of behaviour and the implementation of that
behaviour are separate concepts.
– RMI allows the code that defines the behaviour and the code
that implements the behaviour to remain separate and to run
on separate JVMs.
• This fits nicely with the needs of a distributed system
where clients are concerned about the definition of a
service and servers are focused on providing the
service.
• Specifically, in RMI, the definition of a remote service
is coded using a Java interface. The implementation
of the remote service is coded in a class.
49
Interfaces: The Heart of RMI
• Therefore, the key to understand RMI is to remember
that interfaces define behaviour and classes define
implementation.
• The following diagram illustrates this separation,
Dr M. E. AYDIN / Dr M. CONRAD
50
Interfaces: The Heart of RMI
• Remember that a Java interface does not contain
executable code.
• RMI supports two classes that implement the same
interface.
– The first class is the implementation of the behaviour, and it
runs on the server.
– The second class acts as a proxy for the remote service and
it runs on the client.
Dr M. E. AYDIN / Dr M. CONRAD
51
Interfaces: The Heart of RMI
Dr M. E. AYDIN / Dr M. CONRAD
52
Interfaces: The Heart of RMI
How RMI works?
• A client program makes method calls on the proxy
object. RMI sends the request to the remote JVM,
and forwards it to the implementation. Any return
values provided by the implementation are sent back
to the proxy and then to the client's program.
• This is similar to an RPC system
Dr M. E. AYDIN / Dr M. CONRAD
53
RMI Architecture Layers - Diagram
In the Java 2 SDK SE an additional stub protocol was
introduced that eliminates the need for skeletons. Generic
code is used to carry out the duties performed by skeletons.
Stubs are generated by the rmic compiler.
54
RMI Architecture Layers
• The RMI implementation is essentially built from
three abstraction layers.
• The first is the Stub and Skeleton layer, which lies
just beneath the view of the developer. This layer
intercepts method calls made by the client to the
interface reference variable and redirects these calls
to a remote RMI service.
• The next layer is the Remote Reference Layer. This
layer understands how to interpret and manage
references made from clients to the remote service
objects.
Dr M. E. AYDIN / Dr M. CONRAD
55
RMI Architecture Layers
• The transport layer is based on TCP/IP connections
between machines in a network. It provides basic
connectivity, as well as some firewall penetration
strategies.
• What are the advantages to use a layered
architecture?
Dr M. E. AYDIN / Dr M. CONRAD
56
RMI Architecture Layers
• The transport layer is based on TCP/IP connections
between machines in a network. It provides basic
connectivity, as well as some firewall penetration
strategies.
• What are the advantages to use a layered
architecture?
• By using a layered architecture each of the layers
could be enhanced or replaced without affecting the
rest of the system. For example, the transport layer
could be replaced by a UDP/IP layer without affecting
the upper layers.
Dr M. E. AYDIN / Dr M. CONRAD
57
Stub and Skeleton Layer
• The stub and skeleton layer of RMI lie just beneath the view of
the Java developer. In this layer, RMI uses the Proxy design
pattern in which an object in one context is represented by
another (the proxy) in a separate context. The proxy knows how
to forward method calls between the participating objects.
Dr M. E. AYDIN / Dr M. CONRAD
58
Remote Reference Layer (RRL)
• The RRL defines and supports the invocation
semantics of the RMI connection. This layer provides
a RemoteRef object that represents the link to the
remote service implementation object.
• The stub objects use the invoke() method in
RemoteRef to forward the method call. The
RemoteRef object understands the invocation
semantics for remote services.
Dr M. E. AYDIN / Dr M. CONRAD
60
Remote Reference Layer (RRL)
• Other types of connection semantics are possible. For
example, with multicast, a single proxy could send a
method request to multiple implementations
simultaneously and accept the first reply (this improves
response time and possibly improves availability).
• In the future, Sun may add additional invocation
semantics to RMI.
Dr M. E. AYDIN / Dr M. CONRAD
62
Transport Layer
• The Transport Layer makes the connection between
JVMs. All connections are stream-based network
connections that use TCP/IP.
Dr M. E. AYDIN / Dr M. CONRAD
64
Transport Layer
66
Transport Layer
• On top of TCP/IP, RMI uses a wire level protocol
called Java Remote Method Protocol (JRMP).
JRMP is a proprietary, stream-based protocol that is
only partially specified. In two versions:
• The version of RMI, called RMI-IIOP, was available
with Java 2 SDK Version 1.3. Instead of using JRMP,
it uses the OMG Internet Inter-ORB Protocol (IIOP),
to communicate between clients and servers.
67
Naming Remote Objects
• How does a client find an RMI remote service?
– Clients find remote services by using a naming or directory
service.
– A naming or directory service is run on a well-known host
and port number. (Well-known meaning everyone in an
organisation knowing what it is).
• RMI can use many different directory services,
including the Java Naming and Directory Interface
(JNDI).
• RMI itself includes a simple service called the RMI
Registry, rmiregistry. The RMI Registry runs on
each machine that hosts remote service objects and
accepts queries for services, by default on port 1099.
69
Naming Remote Objects
• Server side:
– On a host machine, a server program creates a remote
service by first creating a local object that implements that
service.
– Next, it exports that object to RMI.
– When the object is exported, RMI creates a listening service
that waits for clients to connect and request the service.
– After exporting, the server registers the object in the RMI
Registry under a public name.
• Client side:
– The RMI Registry is accessed through the static class
Naming.
70
Naming Remote Objects
– The Naming class provides the method lookup() that a
client uses to query a registry.
– The method lookup( ) accepts a URL that specifies the
server host name and the name of the desired service. The
method returns a remote reference to the service object.
The URL takes the form:
rmi://<host_name>[:<name_service_port>]/<service_name>
– where the host_name is a name recognized on the local
area network (LAN) or a DNS name on the Internet. The
name_service_port only needs to be specified only if the
naming service is running on a different port to the default
1099.
71
Naming Remote Objects
– The following illustration depicts an RMI distributed
application that uses the RMI registry to obtain a reference
to a remote object.
– The server calls the registry to associate (or bind) a name
with a remote object. The client looks up the remote object
by its name in the server's registry and then invokes a
method on it.
– The illustration also shows that the RMI system uses an
existing web server to load class definitions, from server to
client and from client to server, for objects when needed.
72
Naming Remote Objects
73