Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CS 483 Enterprise and Web Application Programming Week 2 1 Topics Networking and Internetworking Interprocess communication Distributed objects and remote invocation UDP & TCP Java’s RMI 2 Networking Issues for Distributed Systems Previous networks had to meet simple application requirements: File transfer, remote login, e-mail and newsgroups With the growth of the Internet, more stringent requirements are necessary: New modes of use Additional and more stringent requirements 3 Current Networking Requirements & Terms Performance Speed with which individual messages can be transferred between two interconnected computers Latency – is the delay that occurs after a send operation is executed before data starts to arrive at the destination computer (network latency) Data transfer rate – is the speed at which data can be transferred between two computers in the network once the transmission has begun Bits per second Message transmission time = latency + length/data tranfer rate 4 Current Networking Requirements & Terms Scalability The potential future size of the Internet is commensurate with the population of the planet Indicates size and load of the Internet Networks must scale 5 Current Networking Requirements & Terms Reliability The degree in which an application can recover from communication failures Security Techniques for achieving security in distributed systems Firewalls – creates a protection boundary between an organization’s intranet and the rest of the Internet Distributed systems need a secure network environment with end-to-end authentication, privacy, and security Example - encryption 6 Current Networking Requirements & Terms Mobility Wireless networks provide connectivity to devices such as laptops, cell phones, PDAs Addressing and routing schemes of Internet were developed before the advent of wireless devices so are not well-adapted to their intermittent connection to many different subnets Quality of service Applications that transmit multimedia data require guaranteed bandwidth and latencies 7 Current Networking Requirements & Terms Multicasting One-to-many communication Needed in distributed systems 8 Types of Networks in Distributed Systems PAN – Personal area network Various digital devices carried by a user are connected to a low-cost, low-energy network LAN – Local area network Carry messages at high speed between computers connected by a single communication medium WAN – Wide area network Twisted copper wire, coaxial cable, fiber optics Carry messages a lower speeds between nodes that are often in different organizations and may be separated by large distances Uses routers to route the messages MAN – Metropolitan area network High speed network installed in towns/cities for transmission of data and video 9 DSL and Cable modem connections Types of Networks in Distributed Systems WLAN – Wireless local area network Used in place of wired LANs for wireless mobile devices IEEE 802.11 (WiFi) standard protocol WMAN – Wireless metropolitan area network Supercedes 802.11 IEEE 802.16 WiMAX protocol 10 Types of Networks in Distributed Systems Internetworks – communication subsystem in which several networks are linked together to provide common data communication facilities Overlay the technologies and protocols of the individual component networks and methods used for their interconnection Needed for the development of extensible, open distributed systems Example – Internet 11 Network performance Example Range Bandwidth Latency (Mbps) (ms) LAN Ethernet 1-2 kms 10-1000 WAN IP routing worldwide 0.010-600 100-500 MAN ATM 250 kms 1-150 10 Internetwork Internet worldwide 0.5-600 100-500 WPAN Bluetooth (802.15.1) 10 - 30m 0.5-2 5-20 WLAN WiFi (IEEE 802.11) 0.15-1.5 km 2-54 5-20 WMAN WiMAX (802.16) 550 km 1.5-20 5-20 WWAN GSM, 3G phone nets worldwide 0.01-02 100-500 Wired: 1-10 Wireless: Network Protocols Protocol – refers to a well-known set of rules and formats to be used for communication between processes in order to perform a given task Two parts: a specification of the sequence of messages that must be exchanged a specification of the format of the data in the messages 13 Conceptual Layering of Protocol Software Message received Message sent Layer n Layer 2 Layer 1 Sender Communication medium Recipient 14 Protocol Layers Network software is arranged in a hierarchy of layers Each layer presents an interface to the layers above it and below it Sending side – each layer (except top) accepts items of data in a specified format from the layer above it and applies transformations to encapsulate the data in the format specified for that layer Receiving side – converse transformations are applied to data items received from the layer below before being passed to layer above 15 Encapsulation as it is applied in Layered Protocols Applic ation-layer mess age Pres entation header Sess ion header Transport header Netw ork header The tags in the headers are the protocol type for the layer above, needed for the receiving protocol stack to correctly unpack the packets 16 Protocol Suites Complete set of protocol layers is referred to as a protocol suite or protocol stack Reference Model for Open Systems Interconnection (OSI) Protocol layering brings substantial benefits in simplifying and generalizing the software interfaces for access to the communication services of networks Also carries significant performance costs Why do you think this is so? 17 Protocol layers in the ISO Open Systems Interconnection (OSI) model Mess age receiv ed Mess age s ent Lay ers Applic ation Pres entation Sess ion Transport Netw ork Data link Phy sical Sender Communic ation medium Recipient 18 OSI Protocol Summary Layer Application Presentation Session Transport Network Data link Physical Description Protocols that are designed to meet the communication requirements of specific applications, often defining the interface to a service. Protocols at this level transmit data in a network representation that is independent of the representations used in individual computers, which may differ. Encryption is also performed in this layer, if required. At this level reliability and adaptation are performed, such as detection of failures and automatic recovery. This is the lowest level at which messages (rather than packets) are handled. Messages are addressed to communication ports attached to processes, Protocols in this layer may be connection-oriented or connectionless. Transfers data packets between computers in a specific network. In a WAN or an internetwork this involves the generation of a route passing through routers. In a single LAN no routing is required. Responsible for transmission of packets between nodes that are directly connected by a physical link. In a WAN transmission is between pairs of routers or between routers and hosts. In a LAN it is between any pair of hosts. The circuits and hardware that drive the network. It transmits sequences of binary data by analogue signalling, using amplitude or frequency modulation of electrical signals (on cable circuits), light signals (on fibre optic circuits) or other electromagnetic signals (on radio and microwave circuits). Examples HTTP, FTP , SMTP, CORBA IIOP Secure Sockets (SSL),CORBA Data Rep. TCP, UDP IP, ATM virtual circuits Ethernet MAC, ATM cell transfer, PPP Ethernet base- band signalling, ISDN 19 Internet Protocols TCP/IP – Transmission Control Protocol/Internet Protocol Grown now to over 60 million hosts Example application services & protocols based in TCP/IP: Web (HTTP) email (SMTP, POP) netnews (NNTP) file transfer (FTP) Telnet (telnet) 20 TCP/IP Layers Message Layers Application Messages (UDP) or Streams (TCP) Transport UDP or TCP packets Internet IP datagrams Network interface Network-specific frames Underlying network 21 TCP/IP Layers Two transport protocols Internet Protocol (IP) is the underlying ‘network’ protocol TCP – reliable connection-oriented protocol UDP – datagram protocol that does not guarantee reliable transmission IP datagrams provide the basic transmission mechanism for the Internet and other TCP/IP networks Internet protocols are usually layered over other network technologies i.e, Ethernet 22 Encapsulation in a message transmitted via TCP over an Ethernet Application message TCP header IP header port TCP Ethernet header IP Ethernet frame 23 The programmer's conceptual view of a TCP/IP Internet Applic ation Applic ation TCP UDP IP 24 IP Addressing Scheme chosen for naming and addressing hosts and routing IP packets to their destination Assigns an IP address to each host in the Internet – a 32-bit numeric identifier containing: network identifier – uniquely identifies one of the subnetworks in the Internet host identifier – uniquely identifies the host’s connection to that network 25 Internet Address Space Clas s A: Clas s B: 0 7 24 Netw ork ID Host ID 1 0 14 16 Netw ork ID Host ID 21 Clas s C: 1 1 0 8 Netw ork ID Host ID 28 Clas s D (multicast ): 1 1 1 0 Multicast address 27 Clas s E (reserved): 1 1 1 1 0 unused Class A is reserved for very large networks (i.e.,US NSFNet) Class B is used for organizations that operate networks likely to contain more than 255 computers Class C is allocated to all other network operators Class D is reserved for Internet multittask communication Class E contains a range of unallocated addresses – reserved for future use TCP and UDP Provide the communication capabilities of the Internet in a form that is useful for application programs TCP and UDP are transport protocols and must provide process-to-process communication Accomplished by using ports Port numbers are used for addressing messages to processes within a particular computer and are only valid for that computer Once an IP packet has been delivered to its destination host, the TCP- or UDP-layer software dispatches it to a process via a specific port at that host 27 UDP Features UDP datagram is encapsulated inside an IP packet Short header with source and destination port numbers, length field and a checksum UDP does NOT guarantee delivery Adds no additional reliability mechanisms except for checksum (which is optional) Use is restricted to applications and services that do not require reliable delivery of single or multiple messages 28 TCP Features TCP provides a much more sophisticated transport service Provides reliable delivery of a long sequences of bytes Guarantees the delivery to the receiving process of all the data presented to the TCP software by the sending process in the same order Provides retransmission if necessary Done when the it does not receive an acknowledgement from the receiving process within a specified timeout 29 Middleware Applic ations, services RMI and RPC reques t-reply protocol This c hapter Middlew are lay ers marshalling and ex ternal data representation UDP and TCP Looking at IPC from the Programmer’s point of view Remote Method Invocation (RMI) Remote Procedure Call (RPC) 30 Interprocess Communication (IPC) Distributed Systems rely on exchanging data and achieving synchronization amongst autonomous distributed processes Inter process communication (IPC) message passing in concurrent programming languages shared variables message passing language extensions API calls Principles of IPC (Concurrent programs: collections of two or more sequential programs executing concurrently Concurrent processes: collection of two or more sequential programs in operation, executing concurrently 31 IPC Characteristics Message passing between pairs of processes can be supported by two message communication operations: send receive In order for one process to communicate with another, one process sends a message (sequence of bytes) to a destination and another process at the destination receives the message 32 Types of Communication Synchronous Sending and receiving process synchronize at every message Both send and receive are blocking operations Whenever a send is issued, the sending process (or thread) is blocked until the corresponding receive is issued Whenever a receive is issued, the process (or thread) blocks until a message arrives 33 Types of Communication Asynchronous Send is non-blocking – sending process is allowed to proceed as soon as the message has been copied to a local buffer Receive operation can have blocking and nonblocking variants Non-blocking – receiving process proceeds with its program after issuing a receive operation which provides a buffer to be filled in the background Must separately receive notification that is buffer has been filled by polling or interrupt Today’s systems do not generally provide the nonblocking form of receive because it adds complexity to the application 34 Sockets Both UDP and TCP use socket abstraction Provides an endpoint for communication between processes Originated from BSD UNIX but in all Unix flavors (i.e., Linux) IPC consists of transmitting a message between a socket in one process and a socket in another process 35 Sockets and Ports socket any port agreed port socket message client server other ports Internet address = 138.37.94.248 Internet address = 138.37.88.249 36 Sockets and Ports For a process to receive messages, its socket must be bound to a local port and one of the Internet addresses of the computer on which it runs Messages sent to a particular Internet address and port number can be received only by a process whose socket is associated with that Internet address and port number Processes may use the same socket for sending and receiving messages 37 Moving from Interprocess to Distributed Communication A distributed system breaks up a previously monolithic application into different components and then proceeds to place them on different systems (i.e. tiers). We are decoupling the consumer and the supplier; we are spreading the activities of an application onto team players (systems) 38 Moving from Interprocess to Distributed Communication Analogy Let us imagine for a moment a small business run by a single entrepreneur. This one person, Suzette Sellers, does everything, much like a monolithic application. She sells to customers, orders new product, manages the books, pays the bills, and does anything else. Internally, she has compartmentalized her job function (much like we program in a modular fashion): selling, ordering, and administration. There is no overhead associated with external communication she does everything. When her store becomes successful, she finds that she simply cannot do it all and requires assistance. Suzette hires Henry Helpers, a capable and likeable chap. This is now similar to our two-tier architecture. Because Suzette and Henry work in the same physical location, this is a logical two-tier system. Communication is quick and easy. Think about two programs on a computer: they can communicate via files, shared memory, pipes, or other constructs. If you are familiar with processing on a UNIX- or Linix-based system, multiple commands are often strung together with pipes. 39 Moving from Interprocess to Distributed Communication Suzette’s store does so well that she moves her office into another building to increase the amount of retail floor space in her original store. Now Suzette and Henry are in different physical locations but still need to complete the same tasks of selling, ordering, and administration. We have moved into a physical two tier distributed system and things just become more complicated. Suzette and Henry still need to communicate but the previous methods will no longer work. The obvious solution is the telephone, but this changes the dynamic of the entire conversation In our computer analogy, we now have a client and a server tier where the previous solutions of files, shared memory, or pipes are no longer solutions as 40 they only work within a single system. Moving from Interprocess to Distributed Communication Suzette and Henry must now specifically locate each other (i.e. phone numbers) before communicating. Conversations will be slower (network latency). Data will need to be shared in different ways (difficult to draw a picture on the phone—the crayon keeps breaking on the handset). And finally, the phone lines can go down or have interference (network errors or corruption). 41 Moving from Interprocess to Distributed Communication Yes, we have gained some benefits by spreading out Suzette and Henry (more retail floor space) but we have introduced complexity and latency into the business. Similarly, when a distributed application is placed on different systems (whether physically or logically separated), we also introduce complexity and latency into the application. However, the ability to take advantage of multiple computers is such a powerful incentive that we have devised many ways to accommodate our new problems The stage is now set to discover how to implement this distributed communication. 42 Middleware Layer Last week, we described a distributed application as built in horizontal layers: application, middleware, and platform. We will focus on the middleware this week. By choosing Java, we are explicitly ignoring the platform because Java (in theory) runs exactly the same on any platform that has a Java-compatible runtime environment. We are not yet concerned with what capabilities an application will exhibit other than we will create a “server” component that holds the desired properties and a “client” component that requests these capabilities. Assume that our distributed Java-based application will communicate via the TCP/IP protocol 43 UDP Communication Basis of TCP/IP protocol stack is the Internet Protocol (IP) data packet IP is a connectionless and stateless protocol (“fire and forget”) Once a IP packet is sent, the sender simply does not care about it anymore IP packet can become lost, destroyed, misplaced, or corrupted on its way to its destination If multiple IP packets are sent – they can arrive out of order IP is quick to use but not reliable Think of IP as simple postal envelopes: they can be easily damaged, lost, and delivered out of order. However, IP envelopes are cheap and convenient. (The analogy to a postal service is very appropriate as the cost is low per message and the service is usually reliable but there44 is no capability to trace a wayward envelope.) UDP Communication The User Datagram Protocol (UDP) is implemented on top of IP layer. UDP is still a fairly lightweight protocol which means that most of its effort is spent on delivering data. UDP adds two important features: larger “payloads” and data integrity. If a message is larger than the size of a single IP envelope, UDP will split the message into multiple IP envelopes, taking care to remember how it split up the original message. UDP guarantees that the data in a single UDP packet in the will arrive exactly as it was sent. What happens if one of the IP packets that made up the UDP packet is lost? Then UDP discards the rest of the IP packets and thus the entire UDP packet rather than deliver a damaged UDP packet. This is analogous to sending a four page letter in separate envelopes; if envelope #3 does not arrive, then UDP will throw array the remaining envelopes that did arrive as it has no way 45 to reconstruct the original four page letter. UDP Communication UDP is also a stateless and connectionless protocol Stateless means that once a message is sent, the sender does not care about it anymore. If the message arrives, then that is fine. If it does not arrive, we do not feel any grief Connectionless means that there is no continued conversation. The message is complete in and of itself. Think about sending postcards. If we send one postcard from Europe and another from South America, neither of the postcards depend upon each other. They are separate communications 46 UDP Design Considerations For client-server applications that transfer relatively small amounts of data, UDP is acceptable For the simplest application, a client will send a single message to the server and expect a response If the client does not receive a response within a predetermined amount of time, the client may send the request again. This is similar to asking a person to repeat an answer. Of course, after asking for the answer so many times, it is likely that we (the client) will just give up. This is the approach taken by the DNS system which resolves host names (like www.regis.edu) into IP addresses. If a DNS server does not respond after a couple of seconds, a client will simply accept that no answer is forthcoming and either ask another DNS server or return 47 an error. UDP Example UDP communications can be implemented in Java quite easily However, it should be pointed out that UDP is simply a service to ferry data from point A to point B. UDP does not understand data types or other Java constructs, such as objects. (As an analogy, a postal envelope does not understand nor care about the difference between your electric bill payment and an entry into a fabulous sweapstakes.) To accommodate this understanding, we will use the capability of the String class to convert itself into an array of bytes and back. We are implicitly relying on the String class to correctly convert an array of bytes using the correct code set (that is, where a byte value represents the same letter at both the sender and receiver) given that code sets can change between platforms. We will first construct the server, as this creates the capabilities that will then be used by the client. Both the server and client will perform many of the same operations but the server has the additional task of existing in a state where it can receive requests at any time and must respond to them. A client, on the other hand, will only be executed on demand and exit as soon as it receives a response. 48 UDP Server The UDP server may look complicated but there is actually very little to it. The server first creates a socket, which is a logical construct that we may attach to an actual port. We have hard-coded the port upon which our server will listen, 7777. You may choose any port between 1024 and 65535 (assuming that it is not already in use). The server attaches to the port (“binds” to it in network parlance) and then performs an endless loop of listening for any incoming message and sending the same message (known as a datagram) back to its sender. The effect is similar to a mirror See UDPServerSimple.java 49 UDP Client The UDP client seems to be much longer in length but that is because we have added in the ability to specify the message to send, the server name, and the port on which the UDP server is listening on the command line, rather than hard-coding it. This approach should allow you to run the program as-is, even though you will run it on your system (which has a different network name and IP address than everybody else’s system). The client, similar to the server, first creates a socket that can be bound to a network port. However, we will not bind it to a particular port because we do not care—just as when you send a letter, the mailbox you use is irrelevant to the receiver. 50 UDP Client The client program then resolves the name of the server (first argument) to an IP address, which is what the UDP protocol requires. The second argument is the port that the UDP server is listening on, and the third argument is the actual message (remember to enclose it in double quotes if it contains a space). A datagram message is then created and sent to the server. Immediately after sending the message, the client then acts like the server, waiting for a reply. Although the client did not request a specific port, the port that was automatically assigned is included in the outgoing message so that the server can successfully respond back to us. See UDPClientSimple.java 51 UDP Example In Action First – set the CLASSPATH SET CLASSPATH=C:\CS483;%CLASSPATH% We first start the UDP server which opens the port and waits for the first incoming message. It will wait until the program is terminated Although not shown, the UDP server is running on a system with the name “Alpha” (as in the first Greek letter). 52 UDP Example In Action The server gets up and running quickly and then immediately starts waiting for eternity Then run the UDP client which sends a message and then itself waits for a reply. 53 UDP Example In Action Notice that the client runs and then exits. This is typical of most client-server communications where the client makes a request, receives a reply from the server and is done. 54 UDP Example In Action Meanwhile, the server has recorded the incoming message, responded to it, and begun waiting for another incoming request. 55 TCP Communication TCP network communication is similar to UDP but it “fixes” the flaws inherent in UDP by providing message delivery guarantee and concurrency. TCP promises that it will try its best to get a message delivered (barring complete network failure) and that the messages will arrive in the same order that they were sent TCP goes a step beyond UDP and is a stateful and connection-oriented protocol. Stateful means that the TCP remembers what it has sent and ensures that it arrives in the same order Connection-oriented means that each packet sent is actually part of a larger conversation, or stream. 56 TCP Communication A TCP-based server differs from a UDP-based server in that a single thread does not perform all of the communication. TCP is stateful so it needs to keep track of each conversation individually. The usual solution to handle TCP communications is to create a new thread that is dedicated to incoming requests from a particular client. A server can distinguish multiple requests from the multiple clients on the same client system because each client will be forced to use a different port The operating system, with some unrelated exceptions, only allows one application to bind to any particular port). 57 TCP Example The programs for the TCP client and server are similar in nature although the details vary a bit. Because TCP is stateful, we actually open up two streams: one inbound and one outbound These act like conveyor belts for data to flow between the client and the server. From a programming standpoint, we no longer have to use datagrams but can simply read and write a simple data type or a string object. Very convenient! 58 TCP Server For the server, the largest change is that additional of threads in order to maintain each connection as a separate conversation. However, once inside of a thread, the commands are simply reading and writing data. See TCPServer.java 59 TCP Client The TCP client is very similar to the UDP client except that instead of sending datagrams, we hook up to the streamsbased plumbing. However, the rest of the logic is pretty much the same. See TCPClient.java 60 TCP Example in Action Set CLASSPATH first! Start with the server first 61 TCP Example in Action Next we invoke the TCP client to send a simple message. We can see that the client was able to acquire a port to communicate out and received a reply that was different than what was originally sent, proving that “something” happened. 62 TCP Example in Action The server first received a connection from the remote port of 4304 (the client). It then created new clientConnection object (the two lines with the word setup in the brackets) and then went back to listening for more connection requests. Meanwhile, the new thread was run and it picked up the message sent by the client and then sent it back with the prefix “Received:”. 63 Remote Method Invocation (RMI) Provides for communication between distributed objects by means of remote method invocation RMI = objects that can receive remote method invocations are called remote objects and they implement a remote interface Is an extension of local method invocation that allows an object living in one process to invoke methods of an object living in another process 64 Middleware Layer for RMI Applications RMI, RPC and events Request reply protocol Middleware layers External data representation Operating System 65 Interfaces in Distributed Systems An interface specifies the procedures and variables that can be accessed from other modules Modules are implemented so as to hide all the information about them except that which is available through its interface. As long as the interface does NOT change, implementations may change without affecting the users of the module In a distributed program, the modules can run in separate processes. Cannot access the variables in a module in another process – not direct variable access 66 Interfaces in Distributed Systems Other differences: Parameter-passing mechanisms (i.e., call by value, call by reference) used in local procedure calls do not work in a distributed system Uses input and output parameters that are passed between processes Pointers in one process are not valid in another process on a remote computer No pointer passing allowed 67 Remote and Local Method Invocations local remote invocation A B C local E invocation invocation local invocation D remote invocation F 68 Java RMI Java RMI provides an adapter that effectively hides the network from us, instead allowing us to simply “lookup” functionality that we want (regardless of where it actually exists) and use it as if it was locally available. The level of complexity definitely increases once we decide to distribute the objects in a Java system. Assuming that we started with two Java programs, with one calling the other, we now introduce the following elements: an interface that explicitly states what functionality is remotely available a server that provides access to the remote object the RMI registry that links up requests from a client to a remote object 69 Overview of RMI Interfaces and Classes 70 Java RMI Example Foundation We will start with two Java classes that are not RMI-enabled and then adapt them to operate with RMI so we can see exactly what changes are needed. Let us imagine that we have devised an automated registration process class which, upon knowing which class for which we want to register, will tell us if we are registered or if the class is full. 71 AskTheRegistrar.java public class AskTheRegistrar { private String theClass; public AskTheRegistrar ( String in_whichClass ) { theClass = in_whichClass; } public String getRegistrationStatus() { if ( theClass.toUpperCase().indexOf( "CS483" ) >= 0 ) { return "You are registered"; } else { return "There are no positions available to be registered"; } } } If the class includes the word “CS483” (case sensitive) then the class must have some spots open. Otherwise, the class is full. Java Application to Invoke the Functionality – LocalStudent.java class LocalStudent { public static void main( String args[] ) { System.out.println(); System.out.println( "LocalStudent running..." ); System.out.println( "--------------------------" ); System.out.println(); String studentClass; In order work, both classes if ( args.length < 1 ) just need to be in a directory { the current CLASSPATH studentClass = "CS483"; } environment variable else { studentClass = args[0]; } AskTheRegistrar currentRegistrationStatus = new AskTheRegistrar(studentClass); System.out.println( "The registration status for " + studentClass + " is:"); System.out.println(" > “ + currentRegistrationStatus.getRegistrationStatus()); System.out.println(); System.out.println( "--------------------------" ); System.out.println( "LocalStudent finished." ); } within Result when run... By passing the argument “CS483”, the AskTheRegistrar service concludes that the student is registered 74 Java RMI Example (with a server) We now seek to move the AskTheRegistrar service to a remote server so that it can be accessed from multiple locations within the university. The first step is to decide what functionality should be made available. Currently, the AskTheRegistrar class has two member functions: the constructor and getRegistrationStatus. The constructor will not be available remotely and so we need to create an alternative method to set the location. These two functions, setClass and getRegistrationStatus, will be available to remote invocation and we can now create an interface detailing this decision. Need to enhance the object AskTheRegistrar so that it can be remotely used 75 RMI Server Example – Sequence Diagram 76 AskTheRegistrarInterface.java import java.rmi.*; public interface AskTheRegistrarInterface extends Remote { public void setClass( String in_whichClass ) throws RemoteException; public String getRegistrationStatus( ) throws RemoteException; } *Remember an interface is a contract that a class can choose to implement so there is no actual code in the interface itself 77 New Version of AskTheRegistrar See AskTheRegistrarRemote.java Imported java.rmi and java.rmi.server packages to enable remote invocation capability Class inherits from the UnicaseRemoteObject parent class This object means that a single instance (as opposed to one instance per request) of the AskRemoteRegistrarRemote object will be enabled to be called remotely Provides methods outlined in the interface Added an additional constructor that takes no arguments and sets the private theClass variable 78 RMI Registry A client wishing to use a remote object will need to know exactly where it is located RMI registry Coordinated “phone book” that records every object’s name and address Publishes object’s info in a well-known location rmiregistry.exe In the same directory as other java executables Can be run by itself as a background process We will run in it’s own command window 79 RMI Registry RMI Registry starts off with an empty directory Has no way of actually invoking any objects It’s only job is to provide locations to any program that asks (like directory assistance) 80 RMI Server Example We now need a Java program similar to our UDP server that accepts requests for a remote object This server progam must also communicate to the RMI registry that it exists so clients can find it 81 AskTheRegistrarServer.java import java.rmi.*; import java.rmi.server.*; class AskTheRegistrarServer { public static void main ( String[] args ) { try { Naming.rebind("//localhost/AskTheRegistrar", new AskTheRegistrarRemote()); System.out.println("AskTheRegistrar Server is ready."); System.out.println(); } catch (Exception e) { System.out.println("AskTheRegistrar Server unexpectedly quit. “ +"Exception message: " + e.getMessage()); } //end try } //end main } //end class RMI Server Example This seems like a very small amount of code compared to our previous UDP server. The magic happens on a single line: . . . Naming.rebind( "//localhost/AskTheRegistrar", new AskTheRegistrarRemote() ); . . . 83 RMI Server Example The rebind command is what actually informs the RMI registry that a remote object is now available for remote invocation. The first argument is the remote object’s name in the directory as well as which RMI registry will be informed. In our example, we are contacting the registry on the local server (i.e. localhost). If the registry was on a port other than its default 1098, this could be specified by placing a colon and the new port number directly after the server name. The identifier after the server is the name that the object will be listed as in the registry. This directory name does not have to be the same as the actual remote object. 84 RMI Server Example The second argument creates the actual remote object that will accept requests from clients. Because we are unsure of what location a client will specify, we invoke the no-argument version of the constructor which will set the internal location to an empty string (and thus require the client to specify an actual location later). Most important point to heed is that in our non-RMI setup (previous example), each instance of the client application (LocationStudent) created its own instance of the AskTheRegistrar service class. In the RMI version, we have a single instance of the AskTheRegistrar class that will be used by any and all clients. 85 RMI Server Example Before we can run the server, we need to generate a “stub” class for the remote object that will be used by the server. We use the rmic utility to do this. Server does not exit – RMI registry still has an open reference to it – continuously available to any incoming requests Now that we have a server, we run it from the command line like so: 86 Client Example Create a client that accesses the AskTheRegistrar remote object Two critical lines: . . . AskTheRegistrarInterface theRegistrar = (AskTheRegistrarInterface) Naming.lookup ( "//" + remoteServer + "/AskTheRegistrar" ); . . . System.out.println( " > " + theRegistrar.getRegistrationStatus()); . . . 87 Client Example The first uses the same class, Naming, that the server did to contact the RMI registry. In this case, we are asking the registry for the location of a remote object that should be known as “AskTheRegistrar”. Note that what is returned is a reference to the interface we initially created. This interface hides the fact that there is no code locally but simply provides some stubs that will make a call to the remote object to perform the actual work. The second line uses the resulting object reference as if it were local— which was our original intent . . . AskTheRegistrarInterface theRegistrar = (AskTheRegistrarInterface) Naming.lookup ( "//" + remoteServer + "/AskTheRegistrar" ); . . . System.out.println( " > " + theRegistrar.getRegistrationStatus()); . . . 88 Client Example We can now see the result of running the client: 89 Server Output This is the activity on the server: Server displays the caller’s (client) IP address 90 Java RMI Example (with a daemon) The previous example requires us to run a separate Java application in a server capacity to register and make a remote object available. If we wish to make multiple objects available as remote objects, we will either need to run a separate server for each or create “super-server” that registers one of each object. To solve this problem use the RMI daemon (background process), or rmid. This one process will replace all of the other server processes and allow any remote object to be dynamically invoked This easily becomes an administrative burden. remote objects are only instantiated when requested (although they live on after the first request) rather than running a server program for each object, whether or not there is any request for the object The end result, as far as the client application is concerned, is still the same—the changes we will make concern only the server side. No adjustments to the interface or the client code are required, but we are embarking on a different access method that uses an enhanced form of security. 91 Java RMI with the Daemon Sequence Diagram Java RMI Example (with a daemon) The remote object that we created in AskTheRegistrarRemote last time needs to be modified to inherit from a different, but related object—the Activatable object (which implies that the remote object may be “activated” on demand). For clarity, we will rename the class AskTheRegistrarRemote to AskTheRegistrarActivation. 93 import import import public java.rmi.*; java.rmi.server.*; AskTheRegistrarActivation.java java.rmi.activation.*; class AskTheRegistrarActivation extends Activatable implements AskTheRegistrarInterface { private String theClass; // + This constructor (which was not required when // we used the server-based form of RMI) will // be automatically called by the RMI daemon. // public AskTheRegistrarActivation( ActivationID id, MarshalledObject data ) throws RemoteException { // + Register the object with the activation system // then export it on an anonymous port // super(id, 0); // + Here is our additional code. theClass = "(No class set)"; } . . . } Java RMI Example (with a daemon) Instead of inheriting from UnicastRemoteObject, the remote object now inherits from Activatable. Both of the constructors that previously existed have been removed and replaced with one that has two arguments – Activation ID & MarshalledObject These are required parameters that will be invoked by the daemon. Any initialization code we need is placed after the parent constructor is called. Other than those changes, the code for the remote object is the same. What has changed the most is that instead of a server process, we only need to register the object as available for remote invocation and then create a stub for use with the new daemon process. 95 Java RMI Example (with a daemon) Server Application See AskTheRegistrarRMIDSetup.java The server application has undergone some dramatic change. The first statement inside the main class provides the first hint of the alterations. We are now operating with enhanced security restrictions that we will need to alter in order for our remote object to accept any connections (a remote object that communicates with nobody is not very useful). 96 Java RMI Example (with a daemon) Server Application To accomplish these alterations, we need a security manager to be available like so: . . . System.setSecurityManager( new RMISecurityManager()); . . . 97 Java RMI Example (with a daemon) Server Application Next, we need to associate a security policy file with the remote object when it is activated. The policy file simply states that the remote object is allowed to accept connections via the network from any address as long as the originating port is unprivileged (i.e. above 1023). It should be noted that although the policy file kind of looks like Java code, it is a configuration file and not compiled; it remains a text file called AskTheRegistrarActivation.policy grant { // + This allows the remote AskTheRegistrar object to accept // incoming connections from anywhere, as long as it is on // an unprivileged port (which is normally the case). // permission java.net.SocketPermission "*:1024-", "accept"; }; 98 Java RMI Example (with a daemon) The RMI registry is still operating as it was previously therefore it must be run first of all the server-based processes. The RMI daemon must be run next. However, it will default to being very restrictive with any of the remote objects that will be registered with it as available to be activated. So, we must define a security policy for the RMI daemon itself that allows future remote objects to be allowed to register their own security policy. This could potentially open the door for arbitrary permissions which is why this step is explicitly required. 99 Java RMI Example (with a daemon) Our security policy will look like the following: RMID.policy This policy has only one purpose: future remote objects that will be registered may use the security policy located in a file Z:\CS483\AskTheRegistrarActivation.policy. Any other request for elevated permissions will be expressly denied. grant { // + This allows the remote AskTheRegistrar object to // request the security policy in the file // Z:\CS483\AskTheRegistrar.policy. // + If this is not allowed, then the remote AskTheRegistrar // object will either not be allowed to registered, or // will be registered with no ability to make network // connections. // permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=Z:/CS483/AskTheRegistrarActivation.policy"; }; 100 Run the daemon By default, the RMI daemon uses a security policy of “none” (which is like selling a padlock with no key) so we must change this when running the daemon process. C:> %JAVAHOME%\rmid –J-Djava.security.policy=RMID.policy Start the daemon: 101 Java RMI Example (with a daemon) Next, we must register the AskTheRegistrar remote object with the daemon and registry. The registration program itself needs permission to contact both the daemon and the registry. Here is its policy file: grant { // + This allows the AskTheRegistrar setup to connect to // the RMI registry. // permission java.net.SocketPermission "Alpha:1098", "connect"; // + This allows the AskTheRegistrar setup to connect to // the RMI daemon (background process). // permission java.net.SocketPermission "Alpha:1099", "connect"; }; 102 Java RMI Example (with a daemon) Assuming that the remote AskTheRegistrar object will reside on the server known as “Alpha”, the policy file allows the setup program to contact the registry on the default port 1098 and the daemon on the default port of 1099 If the registration succeeds like we sincerely hope it will, we should get two status messages: C:> java -Djava.security.policy=AskTheRegistrarRMIDSetup.policy AskTheRegistrarRMIDSetup 103 Java RMI Example (with a daemon) It is worthwhile to note here that the remote object, AskTheRegistrarActivation, has not yet been instantiated and will remain so until the first request. This is one of the main benefits of the daemon implementation in that it conserves resources until they are required. 104 Java RMI Example (with a daemon) We need to make two more adjustments. First, we need to provide the client with a “stub” copy of the remote object (in addition to the compiled interface definition). After compiling the remote object (which is AskTheRegistrarActivation in our example), we employ the remote invocation compiler to whittle it down to just a stub. C:> %JAVAHOME%\rmic AskTheRegistrarActivation 105 Java RMI Example (with a daemon) This will produce a file named AskTheRegistrarActivation_stub.class that needs to be distributed with the client application (in addition to the AskTheRegistrarInterface.class and LocalStudentClient.class files). Secondly, while the client is unchanged, it now requires a security policy file in order to access the RMI daemon and registry grant { // + This allows the local client permission to use the network // and make outbound connections to the "Alpha" server on any // unprivileged port. // permission java.net.SocketPermission "Alpha:1024-", "connect,resolve"; }; 106 Java RMI Example (with a daemon) The policy file for the client says that connections may be made to any non-privileged port on the server that contains the remote object. When executing the client application, we now need to include a reference to the security policy file. C:> java -Djava.security.policy=LocalStudentClient.policy LocalStudentClient Alpha "CS483" 107 Executed Client Application with Reference to Policy File 108 LocalStudent Client Our invocation of a remote object is now functional again! That was certainly a lot of work just to learn that we are registered for CS483. If we look back at the RMI daemon, we note that the status messages are displayed, with some extra logging information about execution groups (which we did not cover). 109 RMI Daemon Again, the benefit to this setup is that we can run with just the daemon and dynamically register objects with the daemon and the object will be immediately available for use by clients. 110 Java RMI Resources http://java.sun.com/docs/books/tutori al/rmi/index.html http://java.sun.com/j2se/1.5.0/docs/g uide/rmi/index.html http://java.sun.com/j2se/1.5.0/docs/g uide/rmi/spec/rmiTOC.html http://java.sun.com/j2se/1.5.0/docs/t ooldocs/windows/rmic.html 111