SlideShare a Scribd company logo
1 of 118
Download to read offline
RMI
(Remote Method Invocation)




             Sang Shin
     Java™ Technology Evangelist
         sang.shin@sun.com
Topics

   What is RMI? Why RMI?
   Architectural components
   Serialization & Marshaled Objects
   Dynamic class loading
   Code movement
   Codebase
   ClassLoader delegation
   RMI Security
   Writing RMI Server and Client
   Activation
   HTTP Tunneling                      2
What is RMI?
What is RMI?

   RPC (Remote Procedure Call)
    between Java Objects
   General RPC behavior
     Invoke remote methods
     Pass arguments into methods
     Receive results from methods

   RPC Evolution
     Non-object-orientedRPC
     CORBA (Object-oriented)
     RMI (Object-based)
                                     4
What is RMI?

   Differences from other RPC’s
     Java-based
     Code   movement semantics
     Built-in security mechanism
     Exposure of network failures to application
      programmers through RemoteException




                                             5
Why RMI?

   Capitalizes on the Java object model
   Minimizes complexity of distributed
    programming
   Uses pure Java interfaces
     no   new interface definition language (IDL)
   Preserves safety of Java runtime
   Recognizes differences of remote call from
    local call
     partialfailure
     latency

     no global knowledge on system state
                                                     6
RMI Architectural
 Components
RMI Architectural Components

   Remote interface
   Stub and Skeleton
   Remote object




                         8
Remote Interface

   Java interface
     Specify   remotely accessible methods
   Implemented by a class, an instance
    of which becomes a remote object
   Contract between caller of the remote
    method (RMI client) and remote object
    (RMI server)
   Extends java.rmi.Remote interface
     Markup    interface
                                              9
Stub & Skeleton
Stub and Skeleton

   A tool (rmic) creates
       RMI stub
       (Optionally) RMI skeleton
   Gets created from RMI server
    implementation (not from RMI
    interface)




                                    11
Stub and Skeleton

   RMI Stub
     Resides in caller’s local address space
     Represents remote object to caller (client)
           Plays the role of proxy of remote object
           Implementation of Remote interface
           Caller invokes methods of RMI Stub locally
     Connects to the remote object
     Sends arguments to and receive results

      from remote object
           Performs marshaling and unmarshaling


                                                         12
Stub and Skeleton

   RMI Skeleton
     Resides   in server’s address space
     Receives arguments from caller (RMI

      Client's Stub) and send results back to
      caller
        Performs marshaling and unmarshaling
     Figures out which method of remote

      object to be called
     In JDK 1.3, RMI Skeleton gets created

      automatically via reflection

                                          13
Remote Object

   Implementation of remote interface
   Needs to be exported
     Inorder to be ready to receive calls from
      caller
   Can be exported in two types
     Non-activatable  (extends
      java.rmi.server.UnicastRemoteObject)
     Activatable (extends
      java.rmi.server.Activatable)

                                             14
RMI Communication Model
RMI Communication Model



                        Remote
        Caller          Object

     Remote Interface
                        Skeleton
         Stub




                                   16
RMI Control Flow




                   17
RMI Control Flow

   Caller (Client)
    1. invokes   a method of a remote object
   Stub of the remote object
    1. interceptsthe method call
    2. marshals the arguments
    3. makes calls to remote object




                                               18
RMI Control Flow

   Remote object
    1. Receives the calls via Skeleton
    2. Unmarshals the arguments
    3. Performs the call locally
    4. Marshals the result
    5. Send the result to client
   Stub
    1. Receives result
    2. Unmarshal result
    3. Return result to client
                                         19
Serialization in RMI
Marshaling and Unmarshaling

   Marshaling is a process of encoding
    objects to put them on the wire
   Unmarshaling is the process of
    decoding from the wire and placing
    object in the address space
   RMI uses Java programming
    lanaguage's serialization and
    deserialization to perform marshaling
    and unmarshaling
     These   terms are used interchangeably
                                               21
Serialization in RMI

   Arguments/Results get serialized
    before being transported by sender
   Arguments/Results get deserialized
    after being transported by receiver
   Arguments/Results in RMI can be one
    of the following two
     Remote object
     Non-remote object




                                    22
Serialization in RMI

   For remote object
     Remote    interface type
     Stub gets serialized (instead of remote
      object itself)
     “Pass by reference” semantics
          Stub is kind of a reference to remote object
   For non-remote object
     Normal serialized copy of the object
     Should be type of java.io.Serializable
     “Pass by Value” semantics
                                                      23
Example

// Arguments and Returns are non-remote objects
public interface SayHelloStringRemote extends Remote {
    public String SayHelloString (String message)
                                  throws RemoteException;
}

// Arguments has both remote and non-remote objects
public interface SayHelloObjectRemote extends Remote {
    public String SayHelloObject (String messsage,
                           SayHelloStringRemote someName)
                                  throws RemoteException;
}


                                                        24
Serialization
   Serialized copy of an object
     Stream  of bytes
     Persistently maintains state of an object
          State of non-static and non-transient variables
           of the object
     Does     NOT contain class bytecodes (*.class
      files)
          Instead maintains information on “where to get
           the class bytecodes”
            – codebase annotation
            – W ho performs the codebase annotation?
          If the class is unknown to the recipient, it will
           be downloaded automatically                  25
Serialization

   Serialized copy defines state
   Class files define behavior
   Both can be moved around over the
    network
     Collectively   this is called "Code movement"




                                               26
Marshaled Objects
What and Why Marshaled
Objects?
   Container object of serialized object
     Constructed     by passing object into
      constructor
     get() method retrieves the deserialized
      object
   Used when you want to maintain the
    serialized object without deserializing
    it immediately
     Storage    service of objects
          Lookup service
                                                28
Dynamic Class
   Loading
Dynamic Class Loading

   Class bytecodes (Class file) get
    downloaded during runtime
     When  caller does not have the class
      bytecodes in local classpath
          RMI Stub needs to be downloaded to RMI
           Caller’s address space from somewhere
     Serializedcopy of an object contains
      “where to get class bytecodes” information
          Codebase annotation



                                                    30
Who Does Provide Codebase
Annotation Information?
   By the exporter of the class
   Via Export codebase (RMI codebase)
    property
     java.rmi.server.codebase
     Typically   via HTTP URL




                                   31
When Does the Codebase
Annotation occurs?
   Whenever an object gets serialized
   For remote object
     Codebase   information of Stub class
   For non-remote object
     Codebase   information of normal class




                                               32
RMI Server and Client
Deployment Scenario
   Both client and server have RMI Remote
    interface class in their local classpaths
   Server has HelloWorld_Stub class in its
    local classpath
   Client does not have HelloWorld_Stub
    class in its localpath
     He could, but is diminishes the whole
      purpose of class downloading
   Server exports HelloWorld_Stub class via
    HTTP server
                                              33
RMI Server and Client
Deployment Scenario
   Client gets HelloWorld_Stub serialized
    object from Registry
     Client typically does not have
      HelloWorld_Stub class in its local
      classpath
     So it will read the RMI codebase
      annotation (from the serialized stub object)
      and will try to download the
      HelloWorld_Stub class from the location
      specified in codebase annotation

                                              34
Code (and Data)
  Movement
Code movement in Jini? (new
slide)
   Service proxy object gets moved
     Moved      from service provider to Lookup
      service
          In marshaled object form
     Moved from Lookup service to client
      address space
        Marshaled object gets unmarshaled into
         serialized object
        Client has to recreate an instance of that
         service proxy object
             From serialized service proxy object, client reads
              codebase annotation
             Download class
Code (and Data) Movement
(new slide)
   Performed in two phases
    1. Serialized   object (Marshalled Object) gets
       moved
    2. Class files get downloaded
   Code
     Represented      by class files
   Data
     Represented   by state captured in
      serialized object
Serialized Object (new slide)

   Contains
     Values of the fields of the object
     Name of the class
     Location of the class
        Via codebase annotation performed by the
         exporter of the class
        RMI codebase property
Codebase
What is Codebase?

   Location where class bytecodes
    (Class files) reside




                                     40
Two types of Codebase

   Import codebase
     codebase    your local VM uses to load
      classes it needs
     specified via CLASSPATH or -cp option

   Export codebase (RMI codebase)
     codebase    remote VMs use to obtain the
      class files "exported" from your local VM
     specified via java.rmi.server.codebase
      property
          Codebase annotation
                                             41
Behind the Scene Activities

   Any objects marshaled by a server will
    be annotated with RMI codebase
     Forremote object, the stub object gets
      marshaled and annotated
   When a client instantiates the object,
    the bytecodes of the class will be
    downloaded by RMIClassloader from
    the location specified as RMI
    codebase

                                               42
RMI codebase forms

   Could be in any URI form
     HTTP    (Recommended)
     FTP
     FILE   (Not recommended)
   Classes can be accessible via
     JAR
     Directory   path
         Trailing slash required



                                    43
RMI codebase
   For Jini service (as an RMI server)
     Export     classes that are needed by its client
          Stub classes for remote objects
          Interface classes of remote objects
             – If client has the classes in its local classpath, no
               downloading occurs
          Any classes that are needed by the interface and
           stub classes
   For Jini client
     Export     classes that are needed by the
      server
          Same as above

                                                               44
RMI codebase examples

   Directories need a trailing slash
       -Djava.rmi.server.codebase="file:/export/home/btm/classes/”
       -Djava.rmi.server.codebase=
        "http://daydreamer:8080/export/home/btm/root/dir/”

   Jar files do not need a trailing slash
       -Djava.rmi.server.codebase=
        "file:/export/home/btm/jars/examples-dl.jar”
       -Djava.rmi.server.codebase=
        "http://daydreamer:8080/export/home/btm/jars/examples-dl.jar”

   You can specify multiple locations
       -Djava.rmi.server.codebase=
        "http://daydreamer:8080/export/home/btm/jars/examples-dl.jar
        http://daydreamer:8080/export/home/btm/root/dir/"


                                                                  45
Jini RMI codebase examples

   Lookup service
       java -jar C:filesjini1_1libreggie.jar
        http://daydreamer:8081/reggie-dl.jar
        C:filesjini1_1policypolicy.all C:tmpreggie_log public

   Lookup browser (Client)
      java -cp C:filesjini1_1libjini-examples.jar
    -Djava.security.policy=C:filesjini1_1examplebrowserpolicy
    -Djava.rmi.server.codebase=http://daydreamer:8081/jini-examples-
       dl.jar com.sun.jini.example.browser.Browser




                                                                      46
jini-examples-dl.jar

   Lookup browser (as Lookup service client) exports
    classes needed by Lookup service
   0 .. META-INF/
  66 .. META-INF/MANIFEST.MF
2003 .. com/sun/jini/example/browser/
          Browser$Listener_Stub.class
2015 .. com/sun/jini/example/browser/
          ServiceEditor$NotifyReceiver_Stub.class
1045 .. net/jini/core/event/RemoteEvent.class
 376 .. net/jini/core/event/RemoteEventListener.class
 389 .. net/jini/core/event/UnknownEventException.class




                                                          47
Typical Causes of Problems

   The java.rmi.server.codebase (RMI codebase) property
    was not set at all
        Do not use “localhost”
   RMI codebase was set, but HTTP server is not running
   RMI codebase was set, HTTP server is running, but the
    class is not present under the proper path in HTTP
    server
   The port number on which HTTP server is listening is not
    the same as the port number in the RMI codebase
   The name of the host on which HTTP server is running is
    not the same as the hostname in the RMI codebase
   If a non-jar URL is being used in the RMI codebase, there
    is no trailing slash (if class file location is in a jar file, no
    trailing slash is required)
                                                               48
Typical RMI codebase
Symptom
java.rmi.UnmarshalException: error unmarshalling
   return; nested exception is:
    java.lang.ClassNotFoundException:
   example.testService_Stub
   Client could not download the stub class
    from the server
   The error message could be misleading in
    JDK 1.2 (Fixed in JDK 1.3)
       The problem could be that the stub class itself is
        downloadable but other classes that the stub needs
        are not downloadable
       Use “javap -classpath <path1:path2> <classname>”

                                                       49
Typical RMI codebase
Symptom
RemoteException occurred in server thread; nested
  exception is: java.rmi.UnmarshalExceptionException:
  error unmarshalling arguments; nested exception is:

    java.lang.ClassNotFoundException:test.TestClient$S
    erviceListener_Stub
   Server could not download the remote
    event listener stub class from the
    client
       See if stub was generated correctly (via RMIC)
       See if listener object was exported (via .exportObject()
        method)
       See if RMI codebase is set correctly by the client
                                                           50
Typical RMI codebase
Symptom
   Things are working fine but when
    client and server are on different
    machines, I get
    ClassNotFoundException
     Very   likely due to the fact that the class
      files are not available anymore
          Do not use CLASSPATH for downloadable
           files
            – Do use RMI codebase
          Do not use “localhost”

                                                     51
RMI Codebase FAQ
   Should client applications include mahalo-
    dl.jar or reggie-dl.jar in their CLASSPATH?
     They can. But it diminishes the whole purpose of
      dynamic class downloading during runtime. It is
      better they get exported by specific
      implementations of TxnManager and Lookup
      service (I.e. Mahalo and Reggie)
     The client apps need the following in their

      CLASSPATH (or Class-Path of manifest file)
            jini-core.jar, jini-ext.jar, sun-util.jar
   Should each service have its own embedded
    HTTP server?
       It depends
                                                         52
RMI Codebase FAQ

   The Stub file is definitely being exported.
    And HTTP server is up and running OK.
    Yet, the client still complains
    ClassNotFoundException on Stub file
    under JDK 1.2
     This is typically due to the fact that the class file
      that the stub file needs is not being exported
     Use javap command to find out which class file

      is really missing
           javap -classpath abc.jar:def.jar example.test


                                                        53
Implementation Guideline

   Client has remote interface class file in its
    local classpath (unless it uses reflection)
   The classes that are needed for
    implementation should be downloadable
    from the server
       Stub classes
       Interface classes
            Needed when client does not have interface classes
             in its local path
       Any other classes that the stub and interface
        refers to
   Make jar file in the form of xxx-dl.jar
                                                           54
Example

      eventg/buildEventGenerator & eventg/runEventGenerator
[daydreamer] java -Djava.security.policy=/home/sang/src/examples/lease/policyEventGenerator
-Djava.rmi.server.codebase=http://daydreamer:8081/EventGenerator-srvc-dl.jar
http://daydreamer:8081/EventGenerator-attr-dl.jar -jar
/home/sang/jars/EventGenerator.jar daydreamer

[daydreamer] jar -tvf EventGenerator-srvc-dl.jar
     0 Mon Mar 22 13:04:56 EST 1999 META-INF/
    66 Mon Mar 22 13:04:56 EST 1999 META-INF/MANIFEST.MF
   982 Mon Mar 22 13:04:04 EST 1999 examples/eventg/EventGenerator.class
  7933 Mon Mar 22 13:04:20 EST 1999
examples/eventg/EventGeneratorImpl_Stub.class
  1532 Mon Mar 22 13:03:52 EST 1999 examples/eventg/TestLease.class
   911 Mon Mar 22 13:03:52 EST 1999 examples/eventg/TestLeaseMap.class
  1554 Mon Mar 22 13:04:00 EST 1999 examples/eventg/TestEventLease.class
   967 Mon Mar 22 13:04:00 EST 1999 examples/eventg/TestEventLeaseMap.class
   410 Mon Mar 22 13:03:56 EST 1999 examples/eventg/TestEvent.class

[daydreamer] jar -tvf EventGenerator-attr-dl.jar
     0 Mon Mar 22 13:05:14 EST 1999 META-INF/
    66 Mon Mar 22 13:05:14 EST 1999 META-INF/MANIFEST.MF
   752 Mon Mar 22 13:05:10 EST 1999 net/jini/lookup/entry/ServiceInfo.class
  1764 Mon Mar 22 13:05:12 EST 1999
com/sun/jini/lookup/entry/BasicServiceType.class


                                                                                              55
Deployment Tips

   Run separate HTTP servers on
    different ports if possible
     One   for Jini infrastructure services
       Lookup services
       Transaction Manager

     The   other for your own service




                                               56
Trouble-shooting methods

   Run HTTP server in verbose mode (Example next slide)
      Will display all the jar or class files being downloaded

   Set “-Djava.rmi.loader.logLevel=VERBOSE” on RMI
    client (Example next slide)
      Will tell which class file is being downloaded from

        which location
   Try “javap -classpath <pathlist or jar files>
    <classname>” on command line (Example next slide)
      Will tell what is really missing

   See if you can access the jar file using a browser
      “Save as” dialog box pops up if the file is accessible

   Try FTP URL notation (instead of HTTP)
      If it works, HTTP has a problem


                                                          57
Running HTTP server in
verbose mode
[daydreamer] java -cp /files/jini1_0/lib/tools.jar com.sun.jini.tool.ClassServer
   -port 8081 -dir /home/sang/jars -verbose

java -cp /home/sang/files/jini1_0/lib/tools.jar com.sun.jini.tool.ClassServe
ort 8081 -dir /home/sang/jars -verbose
RegRemoteAndProvideLease-srvc-dl.jar from daydreamer:65296
RegRemoteAndProvideLease-srvc-dl.jar from daydreamer:33431
RegRemoteAndProvideLease-srvc-dl.jar from daydreamer:33797
DiscoveryByGroup-srvc-dl.jar from daydreamer:37616
DiscoveryByGroup-srvc-dl.jar from daydreamer:37617
DiscoveryByGroup-attr-dl.jar from daydreamer:37620
DiscoveryByGroup-attr-dl.jar from daydreamer:37621
DiscoveryByLocator-srvc-dl.jar from daydreamer:37886
DiscoveryByLocator-srvc-dl.jar from daydreamer:37887




                                                                          58
-Djava.rmi.loader.logLevel=VERBOSE

 [daydreamer] java                                               -Djava
       .security.policy=/home/sang/src/examples/client/policyLookupSrvcAndInvoke           -Dsun.rmi.loader.logLevel=VERBOSE
                                     -jar /home/sang/jars/LookupSrvcAndInvoke.jar daydreamer

 groupsWanted[0] = daydreamer
 Waiting For Discovery to Complete

 Wed Mar 17 07:43:01 EST 1999:loader:unicast discovery:LoaderHandler.loadClass: loading class "com.sun.jini.reggie.RegistrarProxy"
             from [http://daydreamer:8080/reggie-dl.jar]
 .Wed Mar 17 07:43:02 EST 1999:loader:unicast discovery:LoaderHandler.loadClass: loading class
             "com.sun.jini.reggie.RegistrarImpl_Stub" from [http://daydreamer:8080/reggie-dl.jar]
 LookupDiscoveryListener: discovered...
   Lookup on host jini://daydreamer/:
     regGroups[0] belongs to Group: myGroup
     regGroups[1] belongs to Group: daydreamer
 ...........
 Discovery of Available Lookups Complete.
 Query each Lookup for known Services, the Invoke ...
 Lookup Service on Host: jini://daydreamer/
   Belongs to Group: daydreamer
 Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "com.sun.jini.lookup.entry.BasicServiceType" from
             [http://daydreamer:8080/reggie-dl.jar]
 Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "net.jini.lookup.entry.ServiceInfo" from
             [http://daydreamer:8080/reggie-dl.jar]
 Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "com.sun.jini.lookup.entry.BasicServiceType" from
             [http://daydreamer:8080/sun-util.jar, http://daydreamer:8081/RegRemoteAndProvideLease-srvc-dl.jar,
             http://daydreamer:8081/RegRemoteAndProvideLease-attr-dl.jar]
 Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "net.jini.lookup.entry.ServiceInfo" from
             [http://daydreamer:8080/sun-util.jar, http://daydreamer:8081/RegRemoteAndProvideLease-srvc-dl.jar,
             http://daydreamer:8081/RegRemoteAndProvideLease-attr-dl.jar]


                                                                                                                        59
javap
[daydreamer:291] javap -classpath LookupSrvcAndInvoke.jar examples/lease/TestLease
Class 'examples/lease/TestLease' not found

[daydreamer:289] javap -classpath RegRemoteAndProvideLease-srvc-dl.jar examples/lease/TestLease
Error: No binary file 'AbstractLease’

[daydreamer:326] javap -classpath RegRemoteAndProvideLease.jar:sun-util.jar examples/lease/TestLease
Error: No binary file 'Lease'

[daydreamer:332] javap -classpath RegRemoteAndProvideLease.jar:sun-util.jar:jini-core.jar
     examples/lease/TestLease
Compiled from TestLease.java
public class examples/lease/TestLease extends com.sun.jini.lease.AbstractLease {
  protected final examples.lease.RegRemoteAndProvideLease server;
  protected final java.lang.String leaseID;
  protected examples/lease/TestLease(examples.lease.RegRemoteAndProvideLease,java.lang.String,long);
  public boolean canBatch(net.jini.core.lease.Lease);
  public void cancel() throws net.jini.core.lease.UnknownLeaseException, java.rmi.RemoteException;
  public net.jini.core.lease.LeaseMap createLeaseMap(long);
  public long doRenew(long) throws net.jini.core.lease.UnknownLeaseException, java.rmi.RemoteException;
  java.lang.String getLeaseID();
  examples.lease.RegRemoteAndProvideLease getRegRemoteAndProvideLease();
  void setExpiration(long);
}

                                                                                               60
javap


     admin/AdminServer registers with a lookup service without including
     OurOwnAdmin class file in its downloadable jar
       You will see unknown service on the Lookup browser
[daydreamer:230] cd ~sang/jars
[daydreamer:232] ls -lat Admin*
-rw-rw---- 1 sang jinieast 8035 Mar 22 21:19 AdminClient.jar
-rw-rw---- 1 sang jinieast 2083 Mar 21 23:44 AdminServer-attr-dl.jar
-rw-rw---- 1 sang jinieast 4953 Mar 21 23:44 AdminServer-srvc-dl.jar
-rw-rw---- 1 sang jinieast 13560 Mar 21 23:44 AdminServer.jar

[daydreamer:229] !226
javap -classpath AdminServer-srvc-dl.jar examples/admin/AdminServerImpl_Stub
Error: No binary file 'Administrable'

[daydreamer:229] javap -classpath AdminServer-srvc-dl.jar:jini-ext.jar examples/admin/AdminServerImpl_Stub
Error: No binary file 'DestroyAdmin'

[daydreamer:229] javap -classpath AdminServer-srvc-dl.jar:jini-ext.jar:sun-util.jar examples/admin/AdminServerImpl_Stub
Error: No binary file 'OurOwnAdmin'




                                                                                                             61
Review Points

   RMI codebase
     Used   for exporting class files
         Serialized object has codebase annotation
     Setvia java.rmi.server.codebase property
     Cause of most of
      ClassNotFoundException problems




                                                      62
ClassLoader
 Delegation
ClassLoader Delegation

   Introduced in JDK 1.2
     Class  files are searched based on
      classloader hierarchy
        Bootstrap classloader
        Extension classloader
        Application classloader
        RMI classloader

     Ask    parent classloader first
          Reason why a class file in local CLASSPATH
           gets picked up first before the same class file
           gets downloaded from remote location
                                                      64
Classloader Hierarchy


               Bootstrap Classloader     Bootstrap Classpath


                                         Extension Classpath
               Extension Classloader


  Delegation   Application Classloader   CLASSPATH




                 RMI Classloader         RMI codebase



                                                               65
Example

   RMI Client        RMI Server

   Local Classpath
       Interface1       Interface1



   RMI Classloader
                      Interface1Impl_Stub


                          Interface2

                      Interface2Impl_Stub




                                            66
RMI Security
Java Security

   In Java, SecurityManager handles
    security control
     Based  on security policy file
     Security policy define “permission control”
      based on
        Where the code came from
        Who signed the code
        Examples
           – All code signed by Dave can write to a particular
             directory
           – Any code downloaded from a particular HTTP
             server site has no filesystem access
                                                          68
Security Policy Example

   Give all all permission to any code
    grant {
       permission java.security.AllPermission "", "";
    };
   Use only during testing
     Never   use it in production environment




                                                        69
Security Policy Example: for
Reggie
grant codebase "file:${java.class.path}" {
   // file system dependent permissions for unix file system
   permission java.io.FilePermission "./*", "read,write,execute,delete";
   permission java.io.FilePermission "/tmp", "read,write,execute,delete";
   permission java.io.FilePermission "/tmp/-", "read,write,execute,delete";
   permission java.io.FilePermission "/var/tmp", "read,write,execute,delete";
   permission java.io.FilePermission "/var/tmp/-", "read,write,execute,delete";
   // uncomment this one if you need lookup to accept file: codebases
   // permission java.io.FilePermission "<<ALL FILES>>", "read";
   permission java.lang.RuntimePermission "modifyThreadGroup";
   permission java.lang.RuntimePermission "modifyThread";
   permission java.net.SocketPermission "*:1024-", "connect,accept";
   // for http: codebases
   permission java.net.SocketPermission "*:80", "connect";
   permission java.net.SocketPermission "224.0.1.84", "connect,accept";
   permission java.net.SocketPermission "224.0.1.85", "connect,accept";
   permission java.util.PropertyPermission "java.rmi.server.hostname", "read";
   permission java.util.PropertyPermission "com.sun.jini.reggie.*", "read";
   permission java.util.PropertyPermission "net.jini.discovery.*", "read";
   permission net.jini.discovery.DiscoveryPermission "*";
   // file system dependent permissions for windows file system
   permission java.io.FilePermission ".*", "read,write,execute,delete";
   permission java.io.FilePermission "c:temp", "read,write,execute,delete";
   permission java.io.FilePermission "c:temp-", "read,write,execute,delete";
   permission java.io.FilePermission "c:windowstemp", "read,write,execute,delete";
   permission java.io.FilePermission "c:windowstemp-", "read,write,execute,delete";
   // Deleted the rest
};

                                                                                            70
RMI/Jini Security

   Security is a serious concern since
    executable code is being downloaded
    from remote location
   In RMI/Jini, SecurityManager has to be
    installed in order to be able to download
    any code from remote location
     Without  its installation, RMI/Jini will search
      for class files only from local classpath
   The security policy file further specifies the
    “permission control”
                                                 71
RMI Security

   RMI client needs to install security
    manager because it needs to
    download Stub file of RMI object
   A simple RMI server might not need to
    install security manager if it does not
    need to download class files from
    remote location
     It   is still good practice to install it anyway


                                                    72
Writing RMI Server
Steps of Writing RMI Server

   S1: Define remote interface
   S2: Implement remote interface
   S3: Provide an implementation for
    each remote method
   S4: Write server class
     Contains  main() method
     Create and export remote object
     Create and install a security manager
     Register remote object with RMI registry

                                            74
S1: Define Remote Interface

   Defines methods that are called remotely
   Must be declared as public
   Extends the java.rmi.Remote interface
   Each method must declare
    java.rmi.RemoteException
   The data type of any remote object that is
    passed as an argument or return value
    (either directly or embedded within a local
    object) must be declared as the Remote
    interface type (for example, Hello) not the
    implementation class (HelloImpl).
                                                  75
S1: Remote Interface Example

// A remote interface for getting increasing numbers

package corejini.appendixa;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface NextNumber extends Remote {
  public int getNextNumber(int n)
                  throws RemoteException;
}

                                                   76
S2: Write the implementation
   Implement the remote interface
   Extend one of the two remote classes
     java.rmi.server.UnicastRemoteObject
     java.rmi.activation.Activatable

   Write constructor for the remote object
       By extending one of the two remote classes
        above, they are automatically exported
            You can manually export it as well
     Throw RemoteException
     Install Security Manager

     Register remote objects with RMI registry
                                                  77
S2: Server Implementation
Example
// A server object that implements the NextNumber
// remote interface

package corejini.appendixa;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.Naming;
import java.rmi.server.UnicastRemoteObject;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.MalformedURLException;



                                                    78
S2: Example -Continued
public class NextNumberImpl extends UnicastRemoteObject
implements NextNumber {

   public NextNumberImpl() throws RemoteException {

     // Install SecurityManager
    if (System.getSecurityManager() == null) {
         System.setSecurityManager(
                 new RMISecurityManager());
     }




                                                      79
S2: Example -Continued
try {
        // Bind it with RMI Registry
        String host = InetAddress.getLocalHost().getHostName();
        String url = "rmi://" + host + "/nextNumber";
        Naming.rebind(url, this);
        System.out.println("Server bound to: " + url);
} catch (UnknownHostException ex) {
        System.err.println("Couldn't get local host name");
        System.exit(1);
} catch (RemoteException ex) {
        System.err.println("Couldn't contact rmiregistry.");
              System.exit(1);
} catch (MalformedURLException ex) {
        System.exit(1);
}


                                                                  80
S3: Implement Remote Methods

   Implement service logic within the
    methods
   Do not throw RemoteException
     They are called locally (same address
      space) from RMI Skeleton




                                              81
S3: Example
 // Implement remote method
 public int getNextNumber(int n) {
     return n+1;
 }




                                     82
S4: Write Server Class

   Setup (or Wrapper) class
     Contains main() method
     Create one or more instances of remote
      objects




                                           83
S3: Example

// W rite main method
public static void main(String[] args) {
  try {
          NextNumberImpl server = new NextNumberImpl();
  } catch (RemoteException ex) {
          ex.printStackTrace();
  }
}




                                                          84
Create one or more instances
of a remote object
   Remote object gets exported during
    instantiation process
     Remote  object is ready to receive
      incoming RMI calls




                                           85
Register the remote object with
RMI Registry
   RMI Registry is a simple naming
    service
     Bootstrap   mechanism
     Typically is used by caller to get the
      remote reference of the first remote object
   Client gets reference to remote object
    - actually reference to stub object of
    the remote object


                                             86
Writing RMI Client
Steps of Writing RMI Client

   Install security manager
   Get a reference to the remote object
    implementation
     The  registry returns the Stub instance of
      the remote object bound to that name
   Invoke remote methods




                                              88
Example

// A client to test the NextNumber server
package corejini.appendixa;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.NotBoundException;
import java.rmi.Naming;
import java.net.MalformedURLException;

public class NextNumberClient {
  public static void main(String[] args) {
     if (args.length != 1) {
          System.err.println("Usage: NextNumberClient <url>");
          System.exit(1);
     }

                                                                 89
Example - Continued
if (System.getSecurityManager() == null) {
    System.setSecurityManager(
      new RMISecurityManager());
}




                                             90
Example - Continued
Remote r = null;
try {
   r = Naming.lookup(args[0]);
} catch (RemoteException ex) {
   System.err.println("Couldn't contact registry.");
   System.exit(1);
} catch (NotBoundException ex) {
   System.err.println("There is no object bound to " + args[0]);
   System.exit(1);
} catch (MalformedURLException ex) {
   System.err.println("The string " + args[0] +
      " is not a valid RMI URL");
   System.exit(1);
}


                                                                   91
Example - Continued
try {
   if (r instanceof NextNumber) {
      NextNumber nn = (NextNumber) r;
      System.out.println("Next number after 1 is " +
      nn.getNextNumber(1));
      System.out.println("Next number after 2 is " +
      nn.getNextNumber(2));
   } else {
      System.err.println("Uh oh, the name " +
            args[0] + "isn't a NextNumber");
   }
} catch (RemoteException ex) {
           ex.printStackTrace();
}

                                                       92
Building, Deploying
RMI Server and Client
Build Process

   Compile
     Compile   client and server in separate
      directories
   Generate Stub and Skeleton
     Use RMIC
     Takes fully qualified Java class name of
      Implementation class
          rmic corejini.appendixa.NextNumberImpl



                                                    94
Example: RMIC
C:filescorejiniappendixa>rmic corejini.appendixa.NextNumberImpl
error: Class corejini.appendixa.NextNumberImpl not found.

C:filescorejiniappendixa>cd files
C:files>rmic corejini.appendixa.NextNumberImpl
C:files>cd corejiniappendixa
C:filescorejiniappendixa>dir

HELLOW~1 JAV       5,260 01-04-01 1:36p HelloWorldServiceActivatable.java
NEXTNU~1 JAV        249 01-04-01 1:36p NextNumber.java
NEXTNU~2 JAV       1,802 01-04-01 1:36p NextNumberClient.java
NEXTNU~3 JAV       1,540 01-04-01 1:36p NextNumberImpl.java
NEXTNU~1 CLA        227 06-21-01 10:56p NextNumber.class
NEXTNU~2 CLA       1,719 06-21-01 10:56p NextNumberImpl.class
NEXTNU~3 CLA       2,023 06-21-01 10:56p NextNumberClient.class
NEXTNU~4 CLA       3,218 06-21-01 10:59p NextNumberImpl_Stub.class
NEXTNU~5 CLA       1,640 06-21-01 10:59p NextNumberImpl_Skel.class




                                                                            95
Server Deployment Process

   Start RMI Registry
     Has to run on the same machine that has
      RMI object
          rmiregistry
   Start HTTP server
     Root directory has to directory structure that
      is comparable to exportable class files
          C:filescorejiniappendixaNextNumberImpl_Stub.class
          c:>java -jar C:filesjini1_2libtools.jar -port 8081 -dir
           c:files -verbose


                                                               96
Server Deployment Process

   Create Security policy file
   Run the RMI server
       c:files>java -Djava.security.policy=c:filesjini1_2policypolicy.all
           -Djava.rmi.server.codebase=http://hannah:8081/
           corejini.appendixa.NextNumberImpl




                                                                         97
Client Deployment Process

   Create Security policy file
   Start HTTP server if needed
       c:>java -jar C:filesjini1_2libtools.jar -port 8082
        -dir c:files -verbose
       In this example, no need for this since client is
        not exporting any classes
   Run the RMI Client
       c:>cd files
       c:files>java -Djava.security.policy=c:filesjini1_2policypolicy.all
        corejini.appendixa.NextNumberClient rmi://hannah/nextNumber




                                                                         98
Activation
Activation
   Why activatable objects?
       Service could be shut down inadvertently or
        intentionally
       Activatable service gets restarted automatically when
        system boots up or on-demand basis
            Activatable service needs to be started (registered with
             RMID) only once

   Activation system components
       RMID (Activation system daemon)
       RMID log file
            Persistently stores all activatable objects
            Default is <Directory where RMID gets started>/log directory
       Activatable services
            They are run as child processes of RMID
                                                                        100
Control Flow of Activation

[A new activatable service with                 (1) RMID running
   running RMID]                                (2) A new service registers with RMID
                                                    and gets a special RMI reference
                                                    -RMID logs the information in
                                                    persistent storage
                                                (3) The service (actually the proxy object)
                                                    registers with the lookup service - the
                                                    proxy object contains the RMI
                                                    reference
(5) Client, via lookup operation, retrieves     (4) The service goes inactive (intentionally
    the proxy object, which contains the            or inadvertently)
    RMI reference
(6) Client Stub talks to the service directly
    and gets an exception since the
    service (as an RMI server) is inactive
(7) Client Stub then talks to RMID              (8) RMID restarts the service if necessary
                                                    in a new VM
(9) Client now can talk directly with the
    service


                                                                                    101
Control Flow of Activation

[RMID crash and reboot]                       (1) A service is registered with RMID
                                              (2) RMID crashes and reboots
                                              (3) RMID reads the log file and restarted
                                                  the services (the ones which set the
                                                  RESTART flag during the registration
                                                  with RMID)
                                              .
(5) Client, via lookup operation, retrieves
    the proxy object, which contains the
    RMI reference
(6) Client talks to the service directly .


                                              .




                                                                                102
RMID

   As long as RMID is running and RMID
    log file is persistent, a service can get
    started on “as needed” basis
   Methods of destroying a service
     Kill   RMID and remove RMID log file
        Other services will be destroyed as well
        Sledge hammer approach

     Use  com.sun.jini.admin.DestroyAdmin
      interface’s destroy() method if the service
      supports it
          Recommended approach
                                                    103
Jini Activatable Services

   Reggie (Lookup service)
   Mahalo (Transaction Manager)
   Outrigger (JavaSpace)
   Fiddler (Lookup Discovery Service)
   Norm (Lease Renewal Service)
   Mercury (Event Mailbox Service)



                                     104
Activation Trouble-shooting

   java.rmi.activation.ActivationException:
    ActivationSystem not running
       Possibly DNS lookup problem
       Try CTRL- (Solaris) and CTRL-BREAK (W in32) for stack
        trace
   Start RMID with
       -J-Dsun.rmi.server.activation.debugExec=true
   For any RMI properties you want to set for
    activatable services (child processes of RMID), start
    RMID with “-C-Dproperty=value”
       -C-Djava.rmi.server.logCalls=true



                                                         105
RMI Tunneling
RMI Tunneling

   Features
       Protocol runs over HTTP protocol
       Allows RMI client within a firewall to talk to an
        RMI server outside of the firewall
   Limitation
       RMI server cannot talk back to the RMI client
   Implications to Jini
       No multicast discovery
          Have to use Unicast
       No event notification from RMI server to RMI
        client
                                                        107
Review Points
Locating Remote Objects

                           registry
            RMI     RMI


   client
                  server




                                      109
Remote Communication

                                registry
                 RMI     RMI


  client   RMI

                       server




                                           110
Loading Classes

                                                  registry
                                 RMI     RMI


    client               RMI

                                       server        URL protocol
              URL protocol




                       URL protocol             web server
 web server




                                                                    111
Method Invocation
  caller’s VM            remote object’s VM

    stub                   remote object

       reference


                            dispatcher


           RMI runtime   RMI runtime




                                              112
RMI and Jini
RMI and Jini

   RMI Semantics is foundation of Jini
     Specified    in RMI specification
          Does not dictate implementation
     Code   movement
     Serialization
     Activation
     Marshaled Object

   RMI Implementation vs. Specification
    (Semantics)

                                             114
RMI and Jini

   Jini specification vs. implementation
   Jini specification specifies
     Service   interface definitions
        API’s and Semantics of those APIs
        Lookup service, Transaction, Remote events,
         Leasing
     RMI-like   semantics
          Runtime code movement
   Jini specification does not dictate
     Usage    of any specific wire-protocol
                                                 115
RMI Limitation

   Client and server paradigm
     Client   has to know about the server
        where the server is
        how to reach the server
        what the server can do

     Ifthe server becomes unavailable, the
      client generally fails too




                                              116
Jini Value-propositions over
RMI
   Client does not need to know where a
    particular service is located
   Client should not fail if the service is
    unavailable or becomes unavailable
    during execution
   Client and servers should be
    proactive in detecting failure
    conditions


                                         117
Summary

   RMI is for invoking methods of remote
    Java object
   Enables the movement of data and
    code
     Data  (State of object) movement via
      serialized object
     Code movement via class downloading




                                         118

More Related Content

What's hot

Distributes objects and Rmi
Distributes objects and RmiDistributes objects and Rmi
Distributes objects and RmiMayank Jain
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Sonali Parab
 
A Short Java RMI Tutorial
A Short Java RMI TutorialA Short Java RMI Tutorial
A Short Java RMI TutorialGuo Albert
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method InvocationPaul Pajo
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVAJalpesh Vasa
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMIbackdoor
 
C# 3.0 and 4.0
C# 3.0 and 4.0C# 3.0 and 4.0
C# 3.0 and 4.0Buu Nguyen
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocationashishspace
 
Java RMI(Remote Method Invocation)
Java RMI(Remote Method Invocation)Java RMI(Remote Method Invocation)
Java RMI(Remote Method Invocation)Nilesh Valva
 
Introduction to Remote Method Invocation (RMI)
Introduction to Remote Method Invocation (RMI)Introduction to Remote Method Invocation (RMI)
Introduction to Remote Method Invocation (RMI)eLink Business Innovations
 
Java RMI Presentation
Java RMI PresentationJava RMI Presentation
Java RMI PresentationMasud Rahman
 
05 rpc-case studies
05 rpc-case studies05 rpc-case studies
05 rpc-case studieshushu
 
Remote Method Innovation (RMI) In JAVA
Remote Method Innovation (RMI) In JAVARemote Method Innovation (RMI) In JAVA
Remote Method Innovation (RMI) In JAVAPrankit Mishra
 
remote method invocation
remote method invocationremote method invocation
remote method invocationRavi Theja
 

What's hot (20)

Rmi
RmiRmi
Rmi
 
Distributes objects and Rmi
Distributes objects and RmiDistributes objects and Rmi
Distributes objects and Rmi
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)
 
A Short Java RMI Tutorial
A Short Java RMI TutorialA Short Java RMI Tutorial
A Short Java RMI Tutorial
 
Java RMI
Java RMIJava RMI
Java RMI
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMI
 
Java rmi
Java rmiJava rmi
Java rmi
 
Java rmi tutorial
Java rmi tutorialJava rmi tutorial
Java rmi tutorial
 
C# 3.0 and 4.0
C# 3.0 and 4.0C# 3.0 and 4.0
C# 3.0 and 4.0
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Java RMI(Remote Method Invocation)
Java RMI(Remote Method Invocation)Java RMI(Remote Method Invocation)
Java RMI(Remote Method Invocation)
 
Introduction to Remote Method Invocation (RMI)
Introduction to Remote Method Invocation (RMI)Introduction to Remote Method Invocation (RMI)
Introduction to Remote Method Invocation (RMI)
 
Java RMI Presentation
Java RMI PresentationJava RMI Presentation
Java RMI Presentation
 
Rmi presentation
Rmi presentationRmi presentation
Rmi presentation
 
05 rpc-case studies
05 rpc-case studies05 rpc-case studies
05 rpc-case studies
 
Remote Method Innovation (RMI) In JAVA
Remote Method Innovation (RMI) In JAVARemote Method Innovation (RMI) In JAVA
Remote Method Innovation (RMI) In JAVA
 
learn design
learn designlearn design
learn design
 
remote method invocation
remote method invocationremote method invocation
remote method invocation
 

Similar to javarmi (20)

Remote Method Invocation, Advanced programming
Remote Method Invocation, Advanced programmingRemote Method Invocation, Advanced programming
Remote Method Invocation, Advanced programming
 
Javarmi 130925082348-phpapp01
Javarmi 130925082348-phpapp01Javarmi 130925082348-phpapp01
Javarmi 130925082348-phpapp01
 
#4 (Remote Method Invocation)
#4 (Remote Method Invocation)#4 (Remote Method Invocation)
#4 (Remote Method Invocation)
 
Java rmi
Java rmiJava rmi
Java rmi
 
RMI (Remote Method Invocation)
RMI (Remote Method Invocation)RMI (Remote Method Invocation)
RMI (Remote Method Invocation)
 
Distributed objects
Distributed objectsDistributed objects
Distributed objects
 
Java RMI
Java RMIJava RMI
Java RMI
 
Remote method invocatiom
Remote method invocatiomRemote method invocatiom
Remote method invocatiom
 
Rmi
RmiRmi
Rmi
 
Rmi
RmiRmi
Rmi
 
Remote method invocation
Remote method invocationRemote method invocation
Remote method invocation
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Net remoting
Net remotingNet remoting
Net remoting
 
Distributed Programming using RMI
 Distributed Programming using RMI Distributed Programming using RMI
Distributed Programming using RMI
 
DS
DSDS
DS
 
Remote method invocation
Remote method invocationRemote method invocation
Remote method invocation
 
Rmi
RmiRmi
Rmi
 
009693652.pdf
009693652.pdf009693652.pdf
009693652.pdf
 
Rmi ppt
Rmi pptRmi ppt
Rmi ppt
 
Java rmi
Java rmiJava rmi
Java rmi
 

More from Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
hibernate
hibernatehibernate
hibernate
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
servlets
servletsservlets
servlets
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 

Recently uploaded (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 

javarmi

  • 1. RMI (Remote Method Invocation) Sang Shin Java™ Technology Evangelist sang.shin@sun.com
  • 2. Topics  What is RMI? Why RMI?  Architectural components  Serialization & Marshaled Objects  Dynamic class loading  Code movement  Codebase  ClassLoader delegation  RMI Security  Writing RMI Server and Client  Activation  HTTP Tunneling 2
  • 4. What is RMI?  RPC (Remote Procedure Call) between Java Objects  General RPC behavior  Invoke remote methods  Pass arguments into methods  Receive results from methods  RPC Evolution  Non-object-orientedRPC  CORBA (Object-oriented)  RMI (Object-based) 4
  • 5. What is RMI?  Differences from other RPC’s  Java-based  Code movement semantics  Built-in security mechanism  Exposure of network failures to application programmers through RemoteException 5
  • 6. Why RMI?  Capitalizes on the Java object model  Minimizes complexity of distributed programming  Uses pure Java interfaces  no new interface definition language (IDL)  Preserves safety of Java runtime  Recognizes differences of remote call from local call  partialfailure  latency  no global knowledge on system state 6
  • 8. RMI Architectural Components  Remote interface  Stub and Skeleton  Remote object 8
  • 9. Remote Interface  Java interface  Specify remotely accessible methods  Implemented by a class, an instance of which becomes a remote object  Contract between caller of the remote method (RMI client) and remote object (RMI server)  Extends java.rmi.Remote interface  Markup interface 9
  • 11. Stub and Skeleton  A tool (rmic) creates  RMI stub  (Optionally) RMI skeleton  Gets created from RMI server implementation (not from RMI interface) 11
  • 12. Stub and Skeleton  RMI Stub  Resides in caller’s local address space  Represents remote object to caller (client)  Plays the role of proxy of remote object  Implementation of Remote interface  Caller invokes methods of RMI Stub locally  Connects to the remote object  Sends arguments to and receive results from remote object  Performs marshaling and unmarshaling 12
  • 13. Stub and Skeleton  RMI Skeleton  Resides in server’s address space  Receives arguments from caller (RMI Client's Stub) and send results back to caller  Performs marshaling and unmarshaling  Figures out which method of remote object to be called  In JDK 1.3, RMI Skeleton gets created automatically via reflection 13
  • 14. Remote Object  Implementation of remote interface  Needs to be exported  Inorder to be ready to receive calls from caller  Can be exported in two types  Non-activatable (extends java.rmi.server.UnicastRemoteObject)  Activatable (extends java.rmi.server.Activatable) 14
  • 16. RMI Communication Model Remote Caller Object Remote Interface Skeleton Stub 16
  • 18. RMI Control Flow  Caller (Client) 1. invokes a method of a remote object  Stub of the remote object 1. interceptsthe method call 2. marshals the arguments 3. makes calls to remote object 18
  • 19. RMI Control Flow  Remote object 1. Receives the calls via Skeleton 2. Unmarshals the arguments 3. Performs the call locally 4. Marshals the result 5. Send the result to client  Stub 1. Receives result 2. Unmarshal result 3. Return result to client 19
  • 21. Marshaling and Unmarshaling  Marshaling is a process of encoding objects to put them on the wire  Unmarshaling is the process of decoding from the wire and placing object in the address space  RMI uses Java programming lanaguage's serialization and deserialization to perform marshaling and unmarshaling  These terms are used interchangeably 21
  • 22. Serialization in RMI  Arguments/Results get serialized before being transported by sender  Arguments/Results get deserialized after being transported by receiver  Arguments/Results in RMI can be one of the following two  Remote object  Non-remote object 22
  • 23. Serialization in RMI  For remote object  Remote interface type  Stub gets serialized (instead of remote object itself)  “Pass by reference” semantics  Stub is kind of a reference to remote object  For non-remote object  Normal serialized copy of the object  Should be type of java.io.Serializable  “Pass by Value” semantics 23
  • 24. Example // Arguments and Returns are non-remote objects public interface SayHelloStringRemote extends Remote { public String SayHelloString (String message) throws RemoteException; } // Arguments has both remote and non-remote objects public interface SayHelloObjectRemote extends Remote { public String SayHelloObject (String messsage, SayHelloStringRemote someName) throws RemoteException; } 24
  • 25. Serialization  Serialized copy of an object  Stream of bytes  Persistently maintains state of an object  State of non-static and non-transient variables of the object  Does NOT contain class bytecodes (*.class files)  Instead maintains information on “where to get the class bytecodes” – codebase annotation – W ho performs the codebase annotation?  If the class is unknown to the recipient, it will be downloaded automatically 25
  • 26. Serialization  Serialized copy defines state  Class files define behavior  Both can be moved around over the network  Collectively this is called "Code movement" 26
  • 28. What and Why Marshaled Objects?  Container object of serialized object  Constructed by passing object into constructor  get() method retrieves the deserialized object  Used when you want to maintain the serialized object without deserializing it immediately  Storage service of objects  Lookup service 28
  • 29. Dynamic Class Loading
  • 30. Dynamic Class Loading  Class bytecodes (Class file) get downloaded during runtime  When caller does not have the class bytecodes in local classpath  RMI Stub needs to be downloaded to RMI Caller’s address space from somewhere  Serializedcopy of an object contains “where to get class bytecodes” information  Codebase annotation 30
  • 31. Who Does Provide Codebase Annotation Information?  By the exporter of the class  Via Export codebase (RMI codebase) property  java.rmi.server.codebase  Typically via HTTP URL 31
  • 32. When Does the Codebase Annotation occurs?  Whenever an object gets serialized  For remote object  Codebase information of Stub class  For non-remote object  Codebase information of normal class 32
  • 33. RMI Server and Client Deployment Scenario  Both client and server have RMI Remote interface class in their local classpaths  Server has HelloWorld_Stub class in its local classpath  Client does not have HelloWorld_Stub class in its localpath  He could, but is diminishes the whole purpose of class downloading  Server exports HelloWorld_Stub class via HTTP server 33
  • 34. RMI Server and Client Deployment Scenario  Client gets HelloWorld_Stub serialized object from Registry  Client typically does not have HelloWorld_Stub class in its local classpath  So it will read the RMI codebase annotation (from the serialized stub object) and will try to download the HelloWorld_Stub class from the location specified in codebase annotation 34
  • 35. Code (and Data) Movement
  • 36. Code movement in Jini? (new slide)  Service proxy object gets moved  Moved from service provider to Lookup service  In marshaled object form  Moved from Lookup service to client address space  Marshaled object gets unmarshaled into serialized object  Client has to recreate an instance of that service proxy object  From serialized service proxy object, client reads codebase annotation  Download class
  • 37. Code (and Data) Movement (new slide)  Performed in two phases 1. Serialized object (Marshalled Object) gets moved 2. Class files get downloaded  Code  Represented by class files  Data  Represented by state captured in serialized object
  • 38. Serialized Object (new slide)  Contains  Values of the fields of the object  Name of the class  Location of the class  Via codebase annotation performed by the exporter of the class  RMI codebase property
  • 40. What is Codebase?  Location where class bytecodes (Class files) reside 40
  • 41. Two types of Codebase  Import codebase  codebase your local VM uses to load classes it needs  specified via CLASSPATH or -cp option  Export codebase (RMI codebase)  codebase remote VMs use to obtain the class files "exported" from your local VM  specified via java.rmi.server.codebase property  Codebase annotation 41
  • 42. Behind the Scene Activities  Any objects marshaled by a server will be annotated with RMI codebase  Forremote object, the stub object gets marshaled and annotated  When a client instantiates the object, the bytecodes of the class will be downloaded by RMIClassloader from the location specified as RMI codebase 42
  • 43. RMI codebase forms  Could be in any URI form  HTTP (Recommended)  FTP  FILE (Not recommended)  Classes can be accessible via  JAR  Directory path  Trailing slash required 43
  • 44. RMI codebase  For Jini service (as an RMI server)  Export classes that are needed by its client  Stub classes for remote objects  Interface classes of remote objects – If client has the classes in its local classpath, no downloading occurs  Any classes that are needed by the interface and stub classes  For Jini client  Export classes that are needed by the server  Same as above 44
  • 45. RMI codebase examples  Directories need a trailing slash  -Djava.rmi.server.codebase="file:/export/home/btm/classes/”  -Djava.rmi.server.codebase= "http://daydreamer:8080/export/home/btm/root/dir/”  Jar files do not need a trailing slash  -Djava.rmi.server.codebase= "file:/export/home/btm/jars/examples-dl.jar”  -Djava.rmi.server.codebase= "http://daydreamer:8080/export/home/btm/jars/examples-dl.jar”  You can specify multiple locations  -Djava.rmi.server.codebase= "http://daydreamer:8080/export/home/btm/jars/examples-dl.jar http://daydreamer:8080/export/home/btm/root/dir/" 45
  • 46. Jini RMI codebase examples  Lookup service  java -jar C:filesjini1_1libreggie.jar http://daydreamer:8081/reggie-dl.jar C:filesjini1_1policypolicy.all C:tmpreggie_log public  Lookup browser (Client)  java -cp C:filesjini1_1libjini-examples.jar -Djava.security.policy=C:filesjini1_1examplebrowserpolicy -Djava.rmi.server.codebase=http://daydreamer:8081/jini-examples- dl.jar com.sun.jini.example.browser.Browser 46
  • 47. jini-examples-dl.jar  Lookup browser (as Lookup service client) exports classes needed by Lookup service 0 .. META-INF/ 66 .. META-INF/MANIFEST.MF 2003 .. com/sun/jini/example/browser/ Browser$Listener_Stub.class 2015 .. com/sun/jini/example/browser/ ServiceEditor$NotifyReceiver_Stub.class 1045 .. net/jini/core/event/RemoteEvent.class 376 .. net/jini/core/event/RemoteEventListener.class 389 .. net/jini/core/event/UnknownEventException.class 47
  • 48. Typical Causes of Problems  The java.rmi.server.codebase (RMI codebase) property was not set at all  Do not use “localhost”  RMI codebase was set, but HTTP server is not running  RMI codebase was set, HTTP server is running, but the class is not present under the proper path in HTTP server  The port number on which HTTP server is listening is not the same as the port number in the RMI codebase  The name of the host on which HTTP server is running is not the same as the hostname in the RMI codebase  If a non-jar URL is being used in the RMI codebase, there is no trailing slash (if class file location is in a jar file, no trailing slash is required) 48
  • 49. Typical RMI codebase Symptom java.rmi.UnmarshalException: error unmarshalling return; nested exception is: java.lang.ClassNotFoundException: example.testService_Stub  Client could not download the stub class from the server  The error message could be misleading in JDK 1.2 (Fixed in JDK 1.3)  The problem could be that the stub class itself is downloadable but other classes that the stub needs are not downloadable  Use “javap -classpath <path1:path2> <classname>” 49
  • 50. Typical RMI codebase Symptom RemoteException occurred in server thread; nested exception is: java.rmi.UnmarshalExceptionException: error unmarshalling arguments; nested exception is: java.lang.ClassNotFoundException:test.TestClient$S erviceListener_Stub  Server could not download the remote event listener stub class from the client  See if stub was generated correctly (via RMIC)  See if listener object was exported (via .exportObject() method)  See if RMI codebase is set correctly by the client 50
  • 51. Typical RMI codebase Symptom  Things are working fine but when client and server are on different machines, I get ClassNotFoundException  Very likely due to the fact that the class files are not available anymore  Do not use CLASSPATH for downloadable files – Do use RMI codebase  Do not use “localhost” 51
  • 52. RMI Codebase FAQ  Should client applications include mahalo- dl.jar or reggie-dl.jar in their CLASSPATH?  They can. But it diminishes the whole purpose of dynamic class downloading during runtime. It is better they get exported by specific implementations of TxnManager and Lookup service (I.e. Mahalo and Reggie)  The client apps need the following in their CLASSPATH (or Class-Path of manifest file)  jini-core.jar, jini-ext.jar, sun-util.jar  Should each service have its own embedded HTTP server?  It depends 52
  • 53. RMI Codebase FAQ  The Stub file is definitely being exported. And HTTP server is up and running OK. Yet, the client still complains ClassNotFoundException on Stub file under JDK 1.2  This is typically due to the fact that the class file that the stub file needs is not being exported  Use javap command to find out which class file is really missing  javap -classpath abc.jar:def.jar example.test 53
  • 54. Implementation Guideline  Client has remote interface class file in its local classpath (unless it uses reflection)  The classes that are needed for implementation should be downloadable from the server  Stub classes  Interface classes  Needed when client does not have interface classes in its local path  Any other classes that the stub and interface refers to  Make jar file in the form of xxx-dl.jar 54
  • 55. Example  eventg/buildEventGenerator & eventg/runEventGenerator [daydreamer] java -Djava.security.policy=/home/sang/src/examples/lease/policyEventGenerator -Djava.rmi.server.codebase=http://daydreamer:8081/EventGenerator-srvc-dl.jar http://daydreamer:8081/EventGenerator-attr-dl.jar -jar /home/sang/jars/EventGenerator.jar daydreamer [daydreamer] jar -tvf EventGenerator-srvc-dl.jar 0 Mon Mar 22 13:04:56 EST 1999 META-INF/ 66 Mon Mar 22 13:04:56 EST 1999 META-INF/MANIFEST.MF 982 Mon Mar 22 13:04:04 EST 1999 examples/eventg/EventGenerator.class 7933 Mon Mar 22 13:04:20 EST 1999 examples/eventg/EventGeneratorImpl_Stub.class 1532 Mon Mar 22 13:03:52 EST 1999 examples/eventg/TestLease.class 911 Mon Mar 22 13:03:52 EST 1999 examples/eventg/TestLeaseMap.class 1554 Mon Mar 22 13:04:00 EST 1999 examples/eventg/TestEventLease.class 967 Mon Mar 22 13:04:00 EST 1999 examples/eventg/TestEventLeaseMap.class 410 Mon Mar 22 13:03:56 EST 1999 examples/eventg/TestEvent.class [daydreamer] jar -tvf EventGenerator-attr-dl.jar 0 Mon Mar 22 13:05:14 EST 1999 META-INF/ 66 Mon Mar 22 13:05:14 EST 1999 META-INF/MANIFEST.MF 752 Mon Mar 22 13:05:10 EST 1999 net/jini/lookup/entry/ServiceInfo.class 1764 Mon Mar 22 13:05:12 EST 1999 com/sun/jini/lookup/entry/BasicServiceType.class 55
  • 56. Deployment Tips  Run separate HTTP servers on different ports if possible  One for Jini infrastructure services  Lookup services  Transaction Manager  The other for your own service 56
  • 57. Trouble-shooting methods  Run HTTP server in verbose mode (Example next slide)  Will display all the jar or class files being downloaded  Set “-Djava.rmi.loader.logLevel=VERBOSE” on RMI client (Example next slide)  Will tell which class file is being downloaded from which location  Try “javap -classpath <pathlist or jar files> <classname>” on command line (Example next slide)  Will tell what is really missing  See if you can access the jar file using a browser  “Save as” dialog box pops up if the file is accessible  Try FTP URL notation (instead of HTTP)  If it works, HTTP has a problem 57
  • 58. Running HTTP server in verbose mode [daydreamer] java -cp /files/jini1_0/lib/tools.jar com.sun.jini.tool.ClassServer -port 8081 -dir /home/sang/jars -verbose java -cp /home/sang/files/jini1_0/lib/tools.jar com.sun.jini.tool.ClassServe ort 8081 -dir /home/sang/jars -verbose RegRemoteAndProvideLease-srvc-dl.jar from daydreamer:65296 RegRemoteAndProvideLease-srvc-dl.jar from daydreamer:33431 RegRemoteAndProvideLease-srvc-dl.jar from daydreamer:33797 DiscoveryByGroup-srvc-dl.jar from daydreamer:37616 DiscoveryByGroup-srvc-dl.jar from daydreamer:37617 DiscoveryByGroup-attr-dl.jar from daydreamer:37620 DiscoveryByGroup-attr-dl.jar from daydreamer:37621 DiscoveryByLocator-srvc-dl.jar from daydreamer:37886 DiscoveryByLocator-srvc-dl.jar from daydreamer:37887 58
  • 59. -Djava.rmi.loader.logLevel=VERBOSE [daydreamer] java -Djava .security.policy=/home/sang/src/examples/client/policyLookupSrvcAndInvoke -Dsun.rmi.loader.logLevel=VERBOSE -jar /home/sang/jars/LookupSrvcAndInvoke.jar daydreamer groupsWanted[0] = daydreamer Waiting For Discovery to Complete Wed Mar 17 07:43:01 EST 1999:loader:unicast discovery:LoaderHandler.loadClass: loading class "com.sun.jini.reggie.RegistrarProxy" from [http://daydreamer:8080/reggie-dl.jar] .Wed Mar 17 07:43:02 EST 1999:loader:unicast discovery:LoaderHandler.loadClass: loading class "com.sun.jini.reggie.RegistrarImpl_Stub" from [http://daydreamer:8080/reggie-dl.jar] LookupDiscoveryListener: discovered... Lookup on host jini://daydreamer/: regGroups[0] belongs to Group: myGroup regGroups[1] belongs to Group: daydreamer ........... Discovery of Available Lookups Complete. Query each Lookup for known Services, the Invoke ... Lookup Service on Host: jini://daydreamer/ Belongs to Group: daydreamer Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "com.sun.jini.lookup.entry.BasicServiceType" from [http://daydreamer:8080/reggie-dl.jar] Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "net.jini.lookup.entry.ServiceInfo" from [http://daydreamer:8080/reggie-dl.jar] Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "com.sun.jini.lookup.entry.BasicServiceType" from [http://daydreamer:8080/sun-util.jar, http://daydreamer:8081/RegRemoteAndProvideLease-srvc-dl.jar, http://daydreamer:8081/RegRemoteAndProvideLease-attr-dl.jar] Wed Mar 17 07:43:13 EST 1999:loader:main:LoaderHandler.loadClass: loading class "net.jini.lookup.entry.ServiceInfo" from [http://daydreamer:8080/sun-util.jar, http://daydreamer:8081/RegRemoteAndProvideLease-srvc-dl.jar, http://daydreamer:8081/RegRemoteAndProvideLease-attr-dl.jar] 59
  • 60. javap [daydreamer:291] javap -classpath LookupSrvcAndInvoke.jar examples/lease/TestLease Class 'examples/lease/TestLease' not found [daydreamer:289] javap -classpath RegRemoteAndProvideLease-srvc-dl.jar examples/lease/TestLease Error: No binary file 'AbstractLease’ [daydreamer:326] javap -classpath RegRemoteAndProvideLease.jar:sun-util.jar examples/lease/TestLease Error: No binary file 'Lease' [daydreamer:332] javap -classpath RegRemoteAndProvideLease.jar:sun-util.jar:jini-core.jar examples/lease/TestLease Compiled from TestLease.java public class examples/lease/TestLease extends com.sun.jini.lease.AbstractLease { protected final examples.lease.RegRemoteAndProvideLease server; protected final java.lang.String leaseID; protected examples/lease/TestLease(examples.lease.RegRemoteAndProvideLease,java.lang.String,long); public boolean canBatch(net.jini.core.lease.Lease); public void cancel() throws net.jini.core.lease.UnknownLeaseException, java.rmi.RemoteException; public net.jini.core.lease.LeaseMap createLeaseMap(long); public long doRenew(long) throws net.jini.core.lease.UnknownLeaseException, java.rmi.RemoteException; java.lang.String getLeaseID(); examples.lease.RegRemoteAndProvideLease getRegRemoteAndProvideLease(); void setExpiration(long); } 60
  • 61. javap  admin/AdminServer registers with a lookup service without including OurOwnAdmin class file in its downloadable jar You will see unknown service on the Lookup browser [daydreamer:230] cd ~sang/jars [daydreamer:232] ls -lat Admin* -rw-rw---- 1 sang jinieast 8035 Mar 22 21:19 AdminClient.jar -rw-rw---- 1 sang jinieast 2083 Mar 21 23:44 AdminServer-attr-dl.jar -rw-rw---- 1 sang jinieast 4953 Mar 21 23:44 AdminServer-srvc-dl.jar -rw-rw---- 1 sang jinieast 13560 Mar 21 23:44 AdminServer.jar [daydreamer:229] !226 javap -classpath AdminServer-srvc-dl.jar examples/admin/AdminServerImpl_Stub Error: No binary file 'Administrable' [daydreamer:229] javap -classpath AdminServer-srvc-dl.jar:jini-ext.jar examples/admin/AdminServerImpl_Stub Error: No binary file 'DestroyAdmin' [daydreamer:229] javap -classpath AdminServer-srvc-dl.jar:jini-ext.jar:sun-util.jar examples/admin/AdminServerImpl_Stub Error: No binary file 'OurOwnAdmin' 61
  • 62. Review Points  RMI codebase  Used for exporting class files  Serialized object has codebase annotation  Setvia java.rmi.server.codebase property  Cause of most of ClassNotFoundException problems 62
  • 64. ClassLoader Delegation  Introduced in JDK 1.2  Class files are searched based on classloader hierarchy  Bootstrap classloader  Extension classloader  Application classloader  RMI classloader  Ask parent classloader first  Reason why a class file in local CLASSPATH gets picked up first before the same class file gets downloaded from remote location 64
  • 65. Classloader Hierarchy Bootstrap Classloader Bootstrap Classpath Extension Classpath Extension Classloader Delegation Application Classloader CLASSPATH RMI Classloader RMI codebase 65
  • 66. Example RMI Client RMI Server Local Classpath Interface1 Interface1 RMI Classloader Interface1Impl_Stub Interface2 Interface2Impl_Stub 66
  • 68. Java Security  In Java, SecurityManager handles security control  Based on security policy file  Security policy define “permission control” based on  Where the code came from  Who signed the code  Examples – All code signed by Dave can write to a particular directory – Any code downloaded from a particular HTTP server site has no filesystem access 68
  • 69. Security Policy Example  Give all all permission to any code grant { permission java.security.AllPermission "", ""; };  Use only during testing  Never use it in production environment 69
  • 70. Security Policy Example: for Reggie grant codebase "file:${java.class.path}" { // file system dependent permissions for unix file system permission java.io.FilePermission "./*", "read,write,execute,delete"; permission java.io.FilePermission "/tmp", "read,write,execute,delete"; permission java.io.FilePermission "/tmp/-", "read,write,execute,delete"; permission java.io.FilePermission "/var/tmp", "read,write,execute,delete"; permission java.io.FilePermission "/var/tmp/-", "read,write,execute,delete"; // uncomment this one if you need lookup to accept file: codebases // permission java.io.FilePermission "<<ALL FILES>>", "read"; permission java.lang.RuntimePermission "modifyThreadGroup"; permission java.lang.RuntimePermission "modifyThread"; permission java.net.SocketPermission "*:1024-", "connect,accept"; // for http: codebases permission java.net.SocketPermission "*:80", "connect"; permission java.net.SocketPermission "224.0.1.84", "connect,accept"; permission java.net.SocketPermission "224.0.1.85", "connect,accept"; permission java.util.PropertyPermission "java.rmi.server.hostname", "read"; permission java.util.PropertyPermission "com.sun.jini.reggie.*", "read"; permission java.util.PropertyPermission "net.jini.discovery.*", "read"; permission net.jini.discovery.DiscoveryPermission "*"; // file system dependent permissions for windows file system permission java.io.FilePermission ".*", "read,write,execute,delete"; permission java.io.FilePermission "c:temp", "read,write,execute,delete"; permission java.io.FilePermission "c:temp-", "read,write,execute,delete"; permission java.io.FilePermission "c:windowstemp", "read,write,execute,delete"; permission java.io.FilePermission "c:windowstemp-", "read,write,execute,delete"; // Deleted the rest }; 70
  • 71. RMI/Jini Security  Security is a serious concern since executable code is being downloaded from remote location  In RMI/Jini, SecurityManager has to be installed in order to be able to download any code from remote location  Without its installation, RMI/Jini will search for class files only from local classpath  The security policy file further specifies the “permission control” 71
  • 72. RMI Security  RMI client needs to install security manager because it needs to download Stub file of RMI object  A simple RMI server might not need to install security manager if it does not need to download class files from remote location  It is still good practice to install it anyway 72
  • 74. Steps of Writing RMI Server  S1: Define remote interface  S2: Implement remote interface  S3: Provide an implementation for each remote method  S4: Write server class  Contains main() method  Create and export remote object  Create and install a security manager  Register remote object with RMI registry 74
  • 75. S1: Define Remote Interface  Defines methods that are called remotely  Must be declared as public  Extends the java.rmi.Remote interface  Each method must declare java.rmi.RemoteException  The data type of any remote object that is passed as an argument or return value (either directly or embedded within a local object) must be declared as the Remote interface type (for example, Hello) not the implementation class (HelloImpl). 75
  • 76. S1: Remote Interface Example // A remote interface for getting increasing numbers package corejini.appendixa; import java.rmi.Remote; import java.rmi.RemoteException; public interface NextNumber extends Remote { public int getNextNumber(int n) throws RemoteException; } 76
  • 77. S2: Write the implementation  Implement the remote interface  Extend one of the two remote classes  java.rmi.server.UnicastRemoteObject  java.rmi.activation.Activatable  Write constructor for the remote object  By extending one of the two remote classes above, they are automatically exported  You can manually export it as well  Throw RemoteException  Install Security Manager  Register remote objects with RMI registry 77
  • 78. S2: Server Implementation Example // A server object that implements the NextNumber // remote interface package corejini.appendixa; import java.rmi.RemoteException; import java.rmi.RMISecurityManager; import java.rmi.Naming; import java.rmi.server.UnicastRemoteObject; import java.net.InetAddress; import java.net.UnknownHostException; import java.net.MalformedURLException; 78
  • 79. S2: Example -Continued public class NextNumberImpl extends UnicastRemoteObject implements NextNumber { public NextNumberImpl() throws RemoteException { // Install SecurityManager if (System.getSecurityManager() == null) { System.setSecurityManager( new RMISecurityManager()); } 79
  • 80. S2: Example -Continued try { // Bind it with RMI Registry String host = InetAddress.getLocalHost().getHostName(); String url = "rmi://" + host + "/nextNumber"; Naming.rebind(url, this); System.out.println("Server bound to: " + url); } catch (UnknownHostException ex) { System.err.println("Couldn't get local host name"); System.exit(1); } catch (RemoteException ex) { System.err.println("Couldn't contact rmiregistry."); System.exit(1); } catch (MalformedURLException ex) { System.exit(1); } 80
  • 81. S3: Implement Remote Methods  Implement service logic within the methods  Do not throw RemoteException  They are called locally (same address space) from RMI Skeleton 81
  • 82. S3: Example // Implement remote method public int getNextNumber(int n) { return n+1; } 82
  • 83. S4: Write Server Class  Setup (or Wrapper) class  Contains main() method  Create one or more instances of remote objects 83
  • 84. S3: Example // W rite main method public static void main(String[] args) { try { NextNumberImpl server = new NextNumberImpl(); } catch (RemoteException ex) { ex.printStackTrace(); } } 84
  • 85. Create one or more instances of a remote object  Remote object gets exported during instantiation process  Remote object is ready to receive incoming RMI calls 85
  • 86. Register the remote object with RMI Registry  RMI Registry is a simple naming service  Bootstrap mechanism  Typically is used by caller to get the remote reference of the first remote object  Client gets reference to remote object - actually reference to stub object of the remote object 86
  • 88. Steps of Writing RMI Client  Install security manager  Get a reference to the remote object implementation  The registry returns the Stub instance of the remote object bound to that name  Invoke remote methods 88
  • 89. Example // A client to test the NextNumber server package corejini.appendixa; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.RMISecurityManager; import java.rmi.NotBoundException; import java.rmi.Naming; import java.net.MalformedURLException; public class NextNumberClient { public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: NextNumberClient <url>"); System.exit(1); } 89
  • 90. Example - Continued if (System.getSecurityManager() == null) { System.setSecurityManager( new RMISecurityManager()); } 90
  • 91. Example - Continued Remote r = null; try { r = Naming.lookup(args[0]); } catch (RemoteException ex) { System.err.println("Couldn't contact registry."); System.exit(1); } catch (NotBoundException ex) { System.err.println("There is no object bound to " + args[0]); System.exit(1); } catch (MalformedURLException ex) { System.err.println("The string " + args[0] + " is not a valid RMI URL"); System.exit(1); } 91
  • 92. Example - Continued try { if (r instanceof NextNumber) { NextNumber nn = (NextNumber) r; System.out.println("Next number after 1 is " + nn.getNextNumber(1)); System.out.println("Next number after 2 is " + nn.getNextNumber(2)); } else { System.err.println("Uh oh, the name " + args[0] + "isn't a NextNumber"); } } catch (RemoteException ex) { ex.printStackTrace(); } 92
  • 94. Build Process  Compile  Compile client and server in separate directories  Generate Stub and Skeleton  Use RMIC  Takes fully qualified Java class name of Implementation class  rmic corejini.appendixa.NextNumberImpl 94
  • 95. Example: RMIC C:filescorejiniappendixa>rmic corejini.appendixa.NextNumberImpl error: Class corejini.appendixa.NextNumberImpl not found. C:filescorejiniappendixa>cd files C:files>rmic corejini.appendixa.NextNumberImpl C:files>cd corejiniappendixa C:filescorejiniappendixa>dir HELLOW~1 JAV 5,260 01-04-01 1:36p HelloWorldServiceActivatable.java NEXTNU~1 JAV 249 01-04-01 1:36p NextNumber.java NEXTNU~2 JAV 1,802 01-04-01 1:36p NextNumberClient.java NEXTNU~3 JAV 1,540 01-04-01 1:36p NextNumberImpl.java NEXTNU~1 CLA 227 06-21-01 10:56p NextNumber.class NEXTNU~2 CLA 1,719 06-21-01 10:56p NextNumberImpl.class NEXTNU~3 CLA 2,023 06-21-01 10:56p NextNumberClient.class NEXTNU~4 CLA 3,218 06-21-01 10:59p NextNumberImpl_Stub.class NEXTNU~5 CLA 1,640 06-21-01 10:59p NextNumberImpl_Skel.class 95
  • 96. Server Deployment Process  Start RMI Registry  Has to run on the same machine that has RMI object  rmiregistry  Start HTTP server  Root directory has to directory structure that is comparable to exportable class files  C:filescorejiniappendixaNextNumberImpl_Stub.class  c:>java -jar C:filesjini1_2libtools.jar -port 8081 -dir c:files -verbose 96
  • 97. Server Deployment Process  Create Security policy file  Run the RMI server  c:files>java -Djava.security.policy=c:filesjini1_2policypolicy.all -Djava.rmi.server.codebase=http://hannah:8081/ corejini.appendixa.NextNumberImpl 97
  • 98. Client Deployment Process  Create Security policy file  Start HTTP server if needed  c:>java -jar C:filesjini1_2libtools.jar -port 8082 -dir c:files -verbose  In this example, no need for this since client is not exporting any classes  Run the RMI Client  c:>cd files  c:files>java -Djava.security.policy=c:filesjini1_2policypolicy.all corejini.appendixa.NextNumberClient rmi://hannah/nextNumber 98
  • 100. Activation  Why activatable objects?  Service could be shut down inadvertently or intentionally  Activatable service gets restarted automatically when system boots up or on-demand basis  Activatable service needs to be started (registered with RMID) only once  Activation system components  RMID (Activation system daemon)  RMID log file  Persistently stores all activatable objects  Default is <Directory where RMID gets started>/log directory  Activatable services  They are run as child processes of RMID 100
  • 101. Control Flow of Activation [A new activatable service with (1) RMID running running RMID] (2) A new service registers with RMID and gets a special RMI reference -RMID logs the information in persistent storage (3) The service (actually the proxy object) registers with the lookup service - the proxy object contains the RMI reference (5) Client, via lookup operation, retrieves (4) The service goes inactive (intentionally the proxy object, which contains the or inadvertently) RMI reference (6) Client Stub talks to the service directly and gets an exception since the service (as an RMI server) is inactive (7) Client Stub then talks to RMID (8) RMID restarts the service if necessary in a new VM (9) Client now can talk directly with the service 101
  • 102. Control Flow of Activation [RMID crash and reboot] (1) A service is registered with RMID (2) RMID crashes and reboots (3) RMID reads the log file and restarted the services (the ones which set the RESTART flag during the registration with RMID) . (5) Client, via lookup operation, retrieves the proxy object, which contains the RMI reference (6) Client talks to the service directly . . 102
  • 103. RMID  As long as RMID is running and RMID log file is persistent, a service can get started on “as needed” basis  Methods of destroying a service  Kill RMID and remove RMID log file  Other services will be destroyed as well  Sledge hammer approach  Use com.sun.jini.admin.DestroyAdmin interface’s destroy() method if the service supports it  Recommended approach 103
  • 104. Jini Activatable Services  Reggie (Lookup service)  Mahalo (Transaction Manager)  Outrigger (JavaSpace)  Fiddler (Lookup Discovery Service)  Norm (Lease Renewal Service)  Mercury (Event Mailbox Service) 104
  • 105. Activation Trouble-shooting  java.rmi.activation.ActivationException: ActivationSystem not running  Possibly DNS lookup problem  Try CTRL- (Solaris) and CTRL-BREAK (W in32) for stack trace  Start RMID with  -J-Dsun.rmi.server.activation.debugExec=true  For any RMI properties you want to set for activatable services (child processes of RMID), start RMID with “-C-Dproperty=value”  -C-Djava.rmi.server.logCalls=true 105
  • 107. RMI Tunneling  Features  Protocol runs over HTTP protocol  Allows RMI client within a firewall to talk to an RMI server outside of the firewall  Limitation  RMI server cannot talk back to the RMI client  Implications to Jini  No multicast discovery  Have to use Unicast  No event notification from RMI server to RMI client 107
  • 109. Locating Remote Objects registry RMI RMI client server 109
  • 110. Remote Communication registry RMI RMI client RMI server 110
  • 111. Loading Classes registry RMI RMI client RMI server URL protocol URL protocol URL protocol web server web server 111
  • 112. Method Invocation caller’s VM remote object’s VM stub remote object reference dispatcher RMI runtime RMI runtime 112
  • 114. RMI and Jini  RMI Semantics is foundation of Jini  Specified in RMI specification  Does not dictate implementation  Code movement  Serialization  Activation  Marshaled Object  RMI Implementation vs. Specification (Semantics) 114
  • 115. RMI and Jini  Jini specification vs. implementation  Jini specification specifies  Service interface definitions  API’s and Semantics of those APIs  Lookup service, Transaction, Remote events, Leasing  RMI-like semantics  Runtime code movement  Jini specification does not dictate  Usage of any specific wire-protocol 115
  • 116. RMI Limitation  Client and server paradigm  Client has to know about the server  where the server is  how to reach the server  what the server can do  Ifthe server becomes unavailable, the client generally fails too 116
  • 117. Jini Value-propositions over RMI  Client does not need to know where a particular service is located  Client should not fail if the service is unavailable or becomes unavailable during execution  Client and servers should be proactive in detecting failure conditions 117
  • 118. Summary  RMI is for invoking methods of remote Java object  Enables the movement of data and code  Data (State of object) movement via serialized object  Code movement via class downloading 118