Ruturaj DS
Ruturaj DS
Distributed Systems
(3170719)
Certificate
Place:
Date:
CERTIFICATE
This is to certify that RUTURAJ HARENDRASINH SOLANKI bearing
enrollment number 220183107024 has satisfactorily completed the term work under
Date of Submission
/ /
Sign of Faculty
Distributed System (3170719)
Preface
Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain. By keeping in view, GTU has designed competency
focused outcome- based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-based curriculum that every practical is keenly designed to serve
as a tool to develop and enhance relevant competency required by the various industry among
every student. These psychomotor skills are very difficult to develop through traditional chalk
and board content delivery method in the classroom. Accordingly, this lab manual is designed to
focus on the industry defined relevant outcomes, rather than old practice of conducting practical
to prove concept and theory.
By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.
This manual also provides guidelines to faculty members to facilitate student centric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.
A distributed system is a computing environment in which various components are spread across
multiple computers (or other computing devices) on a network. These devices split up the work,
coordinating their efforts to complete the job more efficiently than if a single device had been
responsible for the task. Distributed systems facilitate sharing different resources and
capabilities, to provide users with a single and integrated coherent network.
Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal of
errors if an
Distributed System (3170719)
The following industry relevant competency are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to develop web application using Netbeans/Ecllipse IDE
2. Will be able to do Network and distributed programming.
Index
(Progressive Assessment Sheet)
Total
Distributed System (3170719) 220183107024
Experiment No: 1
Theory:
A chat server application is a computer program that enables users to communicate with
each other over the internet or a network. Client-Server Model: A chat server application typically
follows a client-server model, where one or more clients connect to a central server. The server
manages the connections and the communication between the clients.
Procedure:
Implementing a chat server application in Java requires several steps, including setting up a server,
establishing client connections, handling client requests, and sending and receiving messages.
Here's a high-level algorithm for implementing a basic chat server application in Java:
3. Create a server socket that listens for incoming connections on a specific port number.
4. When a client connects, create a new socket to handle the client's requests and establish
input and output streams for sending and receiving messages.
5. Create a thread to handle each client connection so that multiple clients can connect and
communicate simultaneously.
4. Implement the logic for receiving and processing client requests, such as sending messages
to other clients or retrieving a list of currently connected clients.
5. Use synchronization to ensure that multiple threads do not modify shared resources (e.g. a
list of connected clients) at the same time.
6. When a client disconnects, remove it from the list of connected clients and close its socket.
6
Distributed System (3170719) 220183107024
Program Code:
//Server
import java.net.*;
import java.io.*;
public class
servertcp {
public static void main(String args[]) throws IOException
{ ServerSocket ss = new ServerSocket(5678);
System.out.println("Server is waiting for a connection...");
Socket s = ss.accept();
System.out.println("Connection from " + s);
s.close();
ss.close();
}
} //server ends
// Client
import java.net.*;
import java.io.*;
public class
clienttcp{
public static void main(String args[]) throws IOException
{ Socket cc = new Socket(InetAddress.getLocalHost(), 5678);
PrintWriter pw = new PrintWriter(cc.getOutputStream(), true);
BufferedReader br1 = new BufferedReader(new InputStreamReader(cc.getInputStream()));
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
cc.close();
}
} //client ends
Conclusion:
Exercise:
1. What is the role of socket class in Java for client server programing?
Ans: In Java, the Socket class plays a crucial role in client-server programming by enabling
communication between two endpoints over a network. Specifically, it is used for establishing a
connection from a client to a server or from one server to another.
Socket Creation:
The Socket class is responsible for creating a socket, which is a combination of an IP address and a
port number. It represents one endpoint of a network communication channel.
Connecting to a Server:
In a client-server scenario, the client uses a Socket to initiate a connection with a server. The client
provides the IP address and port number of the server it wants to connect to.
Data Transfer:
Once a connection is established, the Socket provides input and output streams (InputStream and
OutputStream) that allow for data transfer between the client and the server.
Blocking and Non-blocking Operations:
8
Distributed System (3170719) 220183107024
Sockets can be used for both blocking and non-blocking I/O operations. In blocking mode, operations
on the socket will block until they can complete. In non-blocking mode, operations may not complete
immediately, allowing for more flexibility in handling multiple connections.
Socket Types:
Java supports both TCP and UDP protocols, and the Socket class can be used for both. For TCP, you'd
use Socket for reliable, connection-oriented communication. For UDP, you'd use DatagramSocket for
connectionless communication.
Closing the Connection:
Once communication is complete, both the client and server should close their respective sockets
using the close() method. This releases system resources associated with the socket.
Error Handling:
The Socket class also provides methods to handle various exceptions that might occur during socket
operations, such as IOException.
In summary, the Socket class in Java is fundamental for establishing network connections between
clients and servers. It facilitates data exchange between endpoints and offers flexibility in terms of
blocking and non-blocking operations, as well as support for both TCP and UDP protocols.
2. What method in Java can be used by a client program to establish a connection to a server
program?
a. Socket.accept()
b. ServerSocket.bind()
c. Socket.connect()
d.ServerSocket.accept()
Ans: Socket.connect()
Suggested References:
3. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
4. "TCP/IP Sockets in Java: Practical Guide for Programmers" by Kenneth L. Calvert and Michael J.
Donahoo.
3. Distributed Computing and application by M L Liu, Pearson Education Inc.
References References
Correct answer
to all
questions
9
Distributed System (3170719) 220183107024
Experiment No: 2
Implement Remote Method Invocation (RMI) in java to find whether number is odd or
even
Theory:
Remote Method Invocation (RMI) is a Java-based technology that enables communication
between different Java Virtual Machines (JVMs) running on different hosts in a network. RMI
provides a mechanism for invoking methods on objects that reside in different JVMs, making it
possible to implement distributed applications in Java.
The basic idea behind RMI is that a Java object running in one JVM can invoke methods
on a Java object running in another JVM. To achieve this, the Java objects that can be accessed
remotely must implement a special interface, called a Remote interface, which extends the
java.rmi.Remote interface. This interface serves as a marker, indicating that the object can be
accessed remotely.
To use RMI, the client needs to know the name or reference of the remote object it wants to
invoke. This can be done by registering the object with a naming service, such as the Java Naming
and Directory Interface (JNDI). Once the client has obtained a reference to the remote object, it
can invoke methods on the object as if it were a local object.
Using RMI you have to implement a program which will find whether the number is odd
or even.
Procedure:
3. Define the Remote Interface: Create a remote interface, let's call it OddEvenInterface,
which declares the method signatures that will be used to determine if a number is even or
odd. This interface should extend Remote.
5. Create the RMI Registry: Start the RMI registry on the host where the remote object will
be running. This can be done using the rmiregistry command.
10
Distributed System (3170719) 220183107024
4. Register the Remote Object: Register the remote object with the RMI registry using the
Naming.rebind() method. The name of the object that is used in the Naming.rebind()
method is the name that the client will use to access the remote object.
5. Create the RMI Client: Create a client program that will use the remote object to determine
if a number is even or odd. The client must look up the remote object in the RMI registry
using the Naming.lookup() method.
6. Compile and Run: Compile both the server and client classes and run the server first,
followed by the client. The output should indicate whether the number is even or odd.
Program Code:
Interface:-
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
@Override
public boolean isEven(int number) throws RemoteException {
return number % 2 == 0;
}
}
Server:-
// NumberCheckerServer.java
import java.rmi.Naming;
import
java.rmi.registry.LocateRegist
ry;
System.out.println("NumberChecker Server is
ready.");
} catch (Exception e) {
System.err.println("NumberChecker Server exception: " + e.toString());
e.printStackTrace();
} 11
}
}
Distributed System (3170719) 220183107024
Client:-
// NumberCheckerClient.java
import java.rmi.Naming;
if (checker.isEven(number))
{ System.out.println(number + " is
even.");
} else {
System.out.println(number + " is odd.");
}
} catch (Exception e) {
System.err.println("NumberCheckerClient exception: " + e.toString());
e.printStackTrace();
}
}
}
Conclusion:
Exercise :
Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Java RMI" by William Grosso.
3. Distributed Computing and application by M L Liu, Pearson Education Inc.
References References
Correct answer
to all
questions
13
Distributed System (3170719) 220183107024
Experiment No: 3
Theory:
Remote Method Invocation (RMI) is a Java-based technology that enables communication
between different Java Virtual Machines (JVMs) running on different hosts in a network. RMI
provides a mechanism for invoking methods on objects that reside in different JVMs, making it
possible to implement distributed applications in Java.
The basic idea behind RMI is that a Java object running in one JVM can invoke methods
on a Java object running in another JVM. To achieve this, the Java objects that can be accessed
remotely must implement a special interface, called a Remote interface, which extends the
java.rmi.Remote interface. This interface serves as a marker, indicating that the object can be
accessed remotely.
To use RMI, the client needs to know the name or reference of the remote object it wants to
invoke. This can be done by registering the object with a naming service, such as the Java Naming
and Directory Interface (JNDI). Once the client has obtained a reference to the remote object, it
can invoke methods on the object as if it were a local object.
A Timer server is a type of server that provides time synchronization services to clients. It
is often used in distributed systems where it is important for all machines to have a consistent view
of time.
To implement a Timer server in Java, you can use the Java Timer class and the RMI
(Remote Method Invocation) framework.
Procedure:
3. Define the remote interface: Define a remote interface that extends the java.rmi.Remote
interface and declares the methods that the server will provide. In this case, you need to
define a method that returns the current time.
4. Implement the remote interface: Implement the remote interface in a server class that
14
Distributed System (3170719) 220183107024
extends the java.rmi.server.UnicastRemoteObject class. This class should provide an
implementation of the getTime() method.
3. Create the server: Create a server class that creates an instance of the TimeServerImpl class
and binds it to the RMI registry.
4. Create the client: Create a client class that looks up the TimeServer object in the RMI
registry and calls its getTime() method.
5. Run the server and client: Start the server class first and then start the client class. The
client should display the current time obtained from the server.
Program Code:
Interface:
// TimerServerImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;
@Override
public long getCurrentTime() throws RemoteException {
return new Date().getTime();
}
}
Server:
// TimerServerServer.java
import java.rmi.Naming;
import
java.rmi.registry.LocateR
egistry;
public class
TimerServerServer {
public static void main(String[] args) {
try {
TimerServer timer = new TimerServerImpl();
LocateRegistry.createRegistry(1234); // Default RMI registry port
System.out.println("TimerServer Server is
ready.");
} catch (Exception e) {
System.err.println("TimerServer Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client: 15
// TimerServerClient.java
import java.rmi.Naming;
Distributed System (3170719) 220183107024
public class TimerServerClient {
public static void main(String[] args) {
try {
TimerServer timer = (TimerServer) Naming.lookup("rmi://localhost/TimerServer");
Conclusion:
Exercise:
1. What is skeleton in RMI?
Ans: In RMI (Remote Method Invocation), a skeleton is a server-side object responsible for
dispatching incoming remote method invocations to the actual remote object's implementation.
It acts as an intermediary between the client and the actual remote object.
When a client makes a remote method call, it creates a stub (client-side proxy) for the remote
object. This stub resides on the client-side and is used to invoke methods on the remote object.
The stub, being on the client-side, communicates with the server-side skeleton.
The skeleton receives the method call from the stub and then forwards it to the actual remote
object that resides in the server's memory.
The remote object executes the method, and the result (if any) is returned back to the skeleton.
The skeleton sends the result back to the client via the network.
The purpose of the skeleton is to manage the communication between the client and the server,
allowing the client to invoke methods on the remote object as if it were a local object.
It's important to note that the concept of a skeleton was more significant in earlier versions of
Java RMI (prior to Java 5). In modern Java RMI, stubs and skeletons are generated
dynamically
16
Distributed System (3170719) 220183107024
at runtime, so developers typically don't need to deal with the specifics of skeleton
implementation.
The RMI registry provides a way to associate a name with a remote object. This allows clients
to look up the object using its name rather than its network address.
Centralized Service:
The RMI registry is a centralized service that runs on a designated host and a specific port
(usually port 1099 by default).
Registration:
Remote objects must be explicitly registered with the RMI registry by binding them to a name.
This is typically done by the server program.
Lookup:
Clients can then look up the remote object by its name using the registry's lookup method.
Unbinding:
If a remote object is no longer needed, it can be unbound from the registry, effectively
removing its association with the name.
Rebinding:
The RMI registry can serve multiple clients simultaneously, allowing different programs to
register and look up remote objects.
Registry Creation:
The RMI registry can be configured with access control policies to control which clients are
allowed to bind and look up objects.
Alternative Naming Services:
While the RMI registry is the most common naming service, it's also possible to use alternative
naming services, such as LDAP or custom naming services.
In summary, the RMI registry provides a convenient way for remote objects to be located by
their names rather than requiring clients to know their network details. It acts as a directory
service for remote objects in an RMI application.
3. How does RMI enable remote invocation of methods?
a) By creating a proxy object that implements the remote interface of the remote object
17
Distributed System (3170719) 220183107024
b) By sending a serialized copy of the remote object to the client
c) By opening a socket connection between the client and server
d) By invoking methods on the remote object directly
Ans: By creating a proxy object that implements the remote interface of the remote object
Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. Distributed Computing and application by M L Liu, Pearson Education Inc.
References References
Correct answer
to all
questions
18
Distributed System (3170719) 220183107024
Experiment No: 4
Implement a program which print Hello Message using Remote Procedure Call (RPC)
Objectives: (a)To understand the concept of Remote Procedure Call (RPC) and its
implementation in Java.
(b) To create a simple Java program that demonstrates the use of RPC.
Theory:
Remote Procedure Call (RPC) is a technique used to enable programs to call procedures on
remote computers as if they were local procedures. It allows a program to invoke a procedure on a
remote computer using the same syntax as for local procedure calls. The RPC program consists of
a client program that sends a request to a server program to execute a procedure, and the server
program executes the procedure and sends a response back to the client.
Procedure:
Here's a steps for printing a "Hello" message using Remote Procedure Call (RPC) in Java:
Install the latest version of Java Development Kit (JDK) and NetBeans IDE (or
your preferred IDE).
Create a new Java project in NetBeans.
6. Define the interface for the remote procedure:
Create a new Java interface called HelloService.
Define a single method in the interface called sayHello() that returns a String.
Annotate the method with the @Remote annotation from the javax.ejb package to
indicate that it is a remote method.
Save the interface.
7. Implement the remote procedure:
Create a new Java class called HelloServiceImpl.
Implement the sayHello() method by returning the string "Hello, world!".
Annotate the class with the @Stateless annotation from the javax.ejb package to
indicate that it is a stateless session bean.
Save the class.
8. Deploy the remote procedure:
Right-click on the project in NetBeans and select "Clean and Build".
Right-click on the project again and select "Deploy".
9. Create the client application:
19
Distributed System (3170719) 220183107024
Program Code:
Interface:
// HelloServiceImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
@Override
public String getHelloMessage() throws RemoteException {
return "Hello from Server!";
}
}
Server:
// HelloServer.java
import java.rmi.Naming;
System.out.println("HelloService Server is
ready.");
} catch (Exception e) {
System.err.println("HelloService Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client:
//public class HelloClient {
HelloClient.java
public
import static void main(String[] args) {
java.rmi.Naming;
try {
HelloService = (HelloService)
20
helloService
Distributed System (3170719) 220183107024
Naming.lookup("rmi://localhost/HelloService");
Conclusion:
Exercise:
1. What is Remote Procedure Call (RPC)?
Ans: Remote Procedure Call (RPC) is a protocol that allows a program to execute procedures or
functions on a remote server as if they were local. It enables distributed computing by allowing
programs to invoke methods or procedures on remote servers over a network.
RPC hides the complexities of network communication, allowing developers to call remote
methods in a manner similar to local method calls.
Client-Server Model:
RPC follows a client-server model where a client program makes a procedure call that gets
executed on a remote server.
Stubs and Skeletons:
In early implementations of RPC, stubs (client-side) and skeletons (server-side) were manually
coded to handle the communication details. Modern RPC frameworks generate these components
automatically.
Serialization and Deserialization:
Parameters and return values of remote method calls are typically serialized (converted to a format
suitable for transmission over a network) and then deserialized on the receiving end.
Synchronous Communication:
Traditional RPC systems are synchronous, meaning the client blocks until the remote procedure
call is completed. Some advanced RPC systems support asynchronous communication as well.
Error Handling:
21
Distributed System (3170719) 220183107024
RPC mechanisms include provisions for handling errors and exceptions that occur during remote
method invocation.
Transparency:
RPC aims to provide transparency to the calling program, making it unaware that it is invoking a
remote procedure rather than a local one.
Language Independence:
RPC systems are designed to work across different programming languages, allowing programs
written in one language to call procedures written in another.
Interoperability:
RPC allows programs running on different platforms and operating systems to communicate and
work together seamlessly.
Examples of RPC implementations include Java RMI (Remote Method Invocation), Microsoft's
DCOM (Distributed Component Object Model), and ONC RPC used in the NFS (Network File
System) protocol.
Overall, RPC is a powerful mechanism for building distributed applications, enabling components
on different machines to work together as if they were part of a single program.
Java RMI is seamlessly integrated into the Java language and platform, making it a natural choice
for Java-based distributed applications.
Automatic Stub and Skeleton Generation:
Java RMI automatically generates stubs (client-side proxies) and skeletons (server-side
dispatchers) for remote objects, which simplifies the development process.
Support for Object Serialization:
Java RMI handles the serialization and deserialization of objects, allowing complex data structures
to be passed between the client and server.
Garbage Collection:
Java RMI supports automatic garbage collection of remote objects, making memory management
more convenient for distributed systems.
Dynamic Class Loading:
Java RMI allows for dynamic class loading, which enables the server to send class definitions to
the client if needed.
Security and Access Control:
Java RMI provides mechanisms for authentication, authorization, and access control, allowing
developers to secure their distributed applications.
Exception Handling:
22
Distributed System (3170719) 220183107024
Java RMI handles exceptions that occur during remote method invocation, allowing for graceful
error handling.
Asynchronous Invocation:
While Java RMI is primarily designed for Java-to-Java communication, it's possible to integrate
with other languages using technologies like CORBA (Common Object Request Broker
Architecture).
Overall, Java RMI is a powerful and widely used framework for building distributed applications
in Java. It provides the necessary tools and abstractions to facilitate remote method invocation
between Java objects on different machines.
3. What are some important factors to consider when implementing RPC in Java?
Ans: A popular choice for implementing Remote Procedure Call (RPC) in Java is the Java RMI
(Remote Method Invocation) framework. Java RMI is a built-in feature of the Java programming
language and provides a straightforward way to invoke methods on remote objects.
Java RMI is seamlessly integrated into the Java language and platform, making it a natural choice
for Java-based distributed applications.
Automatic Stub and Skeleton Generation:
Java RMI automatically generates stubs (client-side proxies) and skeletons (server-side
dispatchers) for remote objects, which simplifies the development process.
Support for Object Serialization:
Java RMI handles the serialization and deserialization of objects, allowing complex data structures
to be passed between the client and server.
Garbage Collection:
Java RMI supports automatic garbage collection of remote objects, making memory management
more convenient for distributed systems.
Dynamic Class Loading:
Java RMI allows for dynamic class loading, which enables the server to send class definitions to
the client if needed.
Security and Access Control:
Java RMI provides mechanisms for authentication, authorization, and access control, allowing
developers to secure their distributed applications.
Exception Handling:
Java RMI handles exceptions that occur during remote method invocation, allowing for graceful
error handling.
Asynchronous Invocation:
While Java RMI is primarily designed for Java-to-Java communication, it's possible to integrate
with other languages using technologies like CORBA (Common Object Request Broker
Architecture).
Overall, Java RMI is a powerful and widely used framework for building distributed applications
in Java. It provides the necessary tools and abstractions to facilitate remote method invocation
between
Java objects on different machines.
User
3. What are some important factors to consider when implementing RPC in Java?
ChatGPT
When implementing Remote Procedure Call (RPC) in Java, there are several important factors to
consider to ensure the successful development and deployment of distributed applications. Here
are
some key considerations:
Interface Definition:
Define clear and well-documented interfaces for your remote objects. This includes specifying the
methods that can be invoked remotely and any exceptions that may be thrown.
Object Serialization:
Ensure that the objects being passed between the client and server are serializable. This allows
them to be converted to a format suitable for transmission over the network.
Error Handling:
Implement appropriate error handling and exception management for remote method invocations.
This includes handling network errors, server-side exceptions, and other potential issues.
Security:
Consider security measures such as authentication, authorization, encryption, and access control.
Implement security mechanisms to protect sensitive data and prevent unauthorized access.
Garbage Collection and Object Lifetime:
Understand how remote objects are managed in terms of garbage collection. Consider whether
objects should be kept alive on the server or whether they can be garbage collected.
Concurrency and Thread Safety:
Design your remote objects to be thread-safe if they will be accessed by multiple clients
concurrently. Implement synchronization or other concurrency control mechanisms as needed.
Performance Optimization:
Optimize the performance of your RPC system by minimizing network round-trips, reducing
object serialization overhead, and considering the use of batched or asynchronous invocations
where appropriate.
Stub and Skeleton Generation:
Familiarize yourself with how stubs (client-side proxies) and skeletons (server-side dispatchers) are
generated and how they interact with your remote objects.
Versioning and Compatibility:
Consider how changes to the interfaces of your remote objects may impact existing clients. Plan
for versioning and backward compatibility strategies.
24
Distributed System (3170719) 220183107024
Timeouts and Retries:
Implement timeouts to handle situations where a remote call takes too long. Consider adding retry
logic for robustness in the face of network or server failures.
Testing and Debugging:
Develop a robust testing strategy, including unit tests for individual components, as well as
integration tests for the entire distributed system. Use debugging tools and techniques to
troubleshoot issues.
Monitoring and Logging:
Implement logging and monitoring to track the behavior of your distributed system. This includes
recording remote method invocations, tracking performance metrics, and monitoring for errors or
exceptions.
By considering these factors, you can design and implement an effective RPC system in Java that
meets the requirements of your distributed application while ensuring reliability, security, and
performance.
Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. Distributed Computing and application by M L Liu, Pearson Education Inc.
References References
Correct answer
to all
questions
25
Distributed System (3170719) 220183107024
Experiment No: 5
Theory:
Remote Procedure Call (RPC) is a technique used to enable programs to call procedures on
remote computers as if they were local procedures. It allows a program to invoke a procedure on a
remote computer using the same syntax as for local procedure calls. The RPC program consists of
a client program that sends a request to a server program to execute a procedure, and the server
program executes the procedure and sends a response back to the client.
In this experiment, we will use RPC to implement a simple calculator program that
performs basic arithmetic operations such as addition, subtraction, multiplication, and division.
Procedure:
Here's a step-by-step procedure to implement a simple calculator using Remote Procedure Call
(RPC) in Java:
3. Set up your development environment:
Install the latest version of Java Development Kit (JDK) and NetBeans IDE (or
your preferred IDE).
Create a new Java project in NetBeans.
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;
}
@Override
public int multiply(int a, int b) throws RemoteException {
return a * b;
}
@Override
public int divide(int a, int b) throws RemoteException {
if (b != 0) {
return a / b;
} else {
throw new ArithmeticException("Division by zero");
}
} 27
}
Server:
Distributed System (3170719) 220183107024
public class CalculatorServer {
public static void main(String[] args) {
try {
Calculator calculator = new
CalculatorImpl();
// Bind the remote object's stub in the registry
Naming.rebind("Calculator", calculator);
System.out.println("Calculator Server is
ready.");
} catch (Exception e) {
System.err.println("Calculator Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client:
// CalculatorClient.java
import java.rmi.Naming;
public class
CalculatorClient {
public static void main(String[] args) {
try {
Calculator calculator = (Calculator)
Naming.lookup("rmi://localhost/
Calculator");
int a = 10;
int b = 5;
Conclusion:
28
Distributed System (3170719) 220183107024
Exercise:
29
Distributed System (3170719) 220183107024
RPC encourages modularization of code, as services can be implemented as separate modules
or services, making it easier to manage and update individual components.
Fault Tolerance:
Some advanced RPC systems provide mechanisms for fault tolerance, allowing for the
recovery from errors or failures in the network or server.
Overall, RPC provides a powerful and flexible mechanism for building distributed systems,
enabling programs on different machines to work together seamlessly. It simplifies the
development process and allows for the integration of components written in different
languages, making it a valuable tool for building modern distributed applications.
In an RPC system, there are typically two components: the client and the server. The client
makes a procedure call that gets executed on a remote server.
Interface Definition:
RPC requires the definition of interfaces that specify the methods or procedures that can be
invoked remotely. These interfaces serve as contracts between the client and server.
Marshalling and Unmarshalling:
Before sending parameters to the remote server, RPC systems serialize (marshal) them into a
format suitable for network transmission. On the server side, the parameters are deserialized
(unmarshaled) back into their original form.
Stubs and Skeletons:
In early implementations of RPC, stubs (client-side proxies) and skeletons (server-side
dispatchers) were manually coded to handle the communication details. Modern RPC
frameworks generate these components automatically.
Network Transport:
RPC mechanisms handle the network transport, including establishing connections, sending
data packets, and managing sockets. This allows the client and server to communicate over a
network.
Remote Procedure Invocation:
30
Distributed System (3170719) 220183107024
When the client makes a remote procedure call, it appears as a regular method call in the
client's code. The RPC system takes care of packaging the method parameters and sending
them to the server.
Server Execution:
The server receives the remote procedure call, looks up the corresponding procedure
implementation, and executes it as if it were a local method.
Result Transmission:
After the server executes the procedure, it sends back the result to the client using the same
RPC mechanism. The result is then unmarshaled and made available to the client program.
Transparency:
RPC aims to provide transparency to the calling program, meaning that the client is unaware
that it is invoking a remote procedure rather than a local one. This simplifies the development
process.
Error Handling:
RPC systems include provisions for handling errors and exceptions that occur during remote
method invocation. This ensures that the client can gracefully handle failures or unexpected
conditions.
Language Neutrality:
While RPC is commonly used in environments where both the client and server are written in
the same language, it can also be used to facilitate communication between programs written in
different languages.
By providing a high-level abstraction for remote communication, RPC enables developers to
build distributed applications more easily, allowing components on different machines to work
together seamlessly.
31
Distributed System (3170719) 220183107024
Establishing Network Connections:
The client program is responsible for establishing network connections with the remote server.
This may involve creating and managing sockets or using higher-level network communication
protocols.
Transmitting RPC Requests:
Once the parameters are marshaled and the connection is established, the client sends the RPC
request to the server. This request includes information about the remote method to be invoked
and the associated parameters.
Managing Timeouts and Retries:
The client may implement mechanisms to handle timeouts in case the server takes too long to
respond. Additionally, the client may implement retry logic to resend the request in case of
network failures.
Handling Error Responses:
The client is responsible for handling any error responses or exceptions that may occur during
the remote procedure call. This includes network errors, server-side exceptions, and other
potential issues.
Unmarshalling Results:
Once the server processes the RPC request and returns a result, the client unmarshals
(deserializes) the result to obtain the return values of the remote method.
Providing Callbacks (if applicable):
In certain cases, the client may need to provide callback functions or methods that the server
can use to notify the client of events or updates.
Implementing Business Logic:
In addition to managing RPC-related tasks, the client program also contains the business logic
and application-specific code that determines when and how to initiate remote calls.
Coordinating Multiple RPCs (if applicable):
In some scenarios, the client may need to coordinate multiple RPCs, possibly in a specific
order or as part of a larger transaction.
Ensuring Security (if applicable):
The client may be responsible for implementing security measures, such as encryption,
authentication, and access control, depending on the requirements of the application.
Overall, the client program acts as the initiator and manager of remote procedure calls,
enabling it to interact with remote services provided by the server. It plays a central role in the
communication between the client and the server in an RPC system.
32
Distributed System (3170719) 220183107024
Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Java RMI" by William Grosso
3. Distributed Computing and application by M L Liu, Pearson Education Inc.
References References
Correct answer
to all
questions
33
Distributed System (3170719) 220183107024
Experiment No: 6
Theory:
The Lamport algorithm is a logical clock algorithm that allows ordering of events in a
distributed system. The algorithm was proposed by Leslie Lamport in 1978.
The algorithm works by assigning a logical clock value to each event in the system. The
logical clock is a virtual clock that is incremented each time an event occurs in the system. The
logical clock value of an event is the timestamp of the event.
The Lamport algorithm ensures that the events are ordered based on their logical clock
values. If event A has a lower logical clock value than event B, then event A occurred before event
B.
The algorithm is implemented using a message passing mechanism. When a process sends
a message to another process, it includes its current logical clock value in the message. When the
receiving process receives the message, it updates its own logical clock value to the maximum of
its current value and the value received in the message. This ensures that the logical clock values
of events are monotonically increasing.
Safety and necessary Precautions: Handle all necessary compile time Exceptions.
Procedure:
1. Define the Event class: Define an Event class that stores the timestamp and the process id
of an event.
2. Define the Process class: Define a Process class that simulates a process in the distributed
system. The Process class should contain a logical clock value and a queue of events that
have occurred in the process.
3. Implement the Lamport algorithm: Implement the Lamport algorithm in the Process class.
When a process sends a message to another process, it should include its current logical
clock value in the message. When the receiving process receives the message, it should
update its own logical clock value to the maximum of its current value and the value
received in the message. When an event occurs in the process, it should be assigned a
timestamp that is the current logical clock value of the process.
4. Test the Lamport algorithm: Create a main class that creates a set of processes in the
34
Distributed System (3170719) 220183107024
distributed system. Each process should send messages to other processes and generate
events. The main class should display the events in the order determined by the Lamport
algorithm.
When a message is sent from one process to another, the sender includes its current logical
clock value as the timestamp of the message.
When a process receives a message, it sets its logical clock to the maximum of its current
value and the timestamp of the received message plus 1. This ensures that the logical clock
of the receiving process is always greater than the logical clock of the sending process.
The logical clock values assigned to events by each process can be used to determine the
ordering of events in the system.
Program Code:
import java.util.ArrayList;
import java.util.List;
class Event {
int timestamp;
int processId;
class Process {
int logicalClock;
int processId;
List<Event>
eventQueue;
processes[0].sendEvent(processes[1]);
processes[1].sendEvent(processes[2]);
processes[2].sendEvent(processes[0]);
processes[1].sendEvent(processes[0]);
Exercise:
In a distributed system, where multiple processes or nodes communicate with each other, it's
important to establish a consistent ordering of events. However, due to the lack of a global
clock that synchronizes all processes, this can be challenging.
Lamport's algorithm provides a partial ordering of events based on timestamps. Each process in
the system maintains its own logical clock, which is essentially a counter that is incremented
whenever an event occurs. These timestamps are used to determine the relative ordering of
events.
36
Distributed System (3170719) 220183107024
The key principle of Lamport's algorithm is that if event A happened before event B, then the
timestamp of event A will be less than the timestamp of event B. However, it's important to
note that events that are concurrent (i.e., they don't have a causal relationship) may have the
same timestamp.
This algorithm allows processes in a distributed system to establish a consistent, albeit partial,
ordering of events, which is crucial for tasks like distributed databases, file systems, and other
distributed applications.
It's worth noting that Lamport's logical clocks are an example of a causality-tracking
mechanism, and they are often used in conjunction with other algorithms for achieving a more
complete ordering of events in distributed systems.
2. How does the Lamport algorithm ensure that events are ordered based on their logical clock
values?
Ans: The Lamport algorithm ensures that events are ordered based on their logical clock values
through the following mechanisms:
Timestamp Assignment: Each process in a distributed system maintains its own logical clock.
This clock is essentially a counter that gets incremented whenever an event occurs. The logical
clock values are assigned based on the order of events in each process.
Timestamp Comparison: When a process sends a message to another process, it includes its
current logical clock value in the message. When the receiving process receives the message, it
updates its own logical clock value to be greater than the maximum of its current value and the
received value plus one. This step ensures that the receiving process's clock reflects a time after
the sending process's clock.
However, it's important to note that the algorithm does not provide an absolute ordering of all
events in the system, only a partial ordering based on causality.
In summary, the Lamport algorithm uses logical clocks and timestamp comparisons to
establish a partial ordering of events in a distributed system. It ensures that events are ordered
based on their logical clock values, providing a way to track causality in a distributed
environment where there is no global clock.
3. How can the Lamport algorithm be implemented using Java programming language?
Ans: public class Process implements Runnable {
private int processId;
private LamportClock clock;
@Override
public void run()
{ sendEvent();
sendMessage(otherProcess);
}
Create separate instances of the program, each representing a process or node in the distributed
system. These processes can be run on different machines or on the same machine with 38
different ports.
Establish Communication:
Distributed System (3170719) 220183107024
Implement a communication mechanism between the processes. This could be done using
sockets, message queues, or any other suitable method for inter-process communication.
Initialize Lamport Clocks:
Each process should have its own instance of Lamport's logical clock.
Simulate Events:
In each process, simulate events that occur locally. This involves incrementing the logical
clock whenever an event occurs.
Send and Receive Messages:
Implement message sending and receiving functionalities in each process. When a process
sends a message, it includes its current logical clock value.
Update Logical Clocks on Message Receipt:
When a process receives a message, it updates its logical clock based on the received
timestamp and the local clock value.
Verify Event Ordering:
Print out or log the events and messages along with their timestamps. Verify that the ordering
of events and messages is consistent with the Lamport algorithm.
Test for Concurrent Events:
Create scenarios where events are concurrent (i.e., they do not have a causal relationship).
Verify that their timestamps do not strictly order them.
Perform Multiple Runs:
Test the system with various event sequences and message exchanges to ensure that the
Lamport algorithm consistently produces the expected results.
Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. Distributed Computing and application by M L Liu, Pearson Education Inc.
3. "Distributed Systems: Principles and Paradigms" by Andrew S. Tanenbaum and Maarten van Steen
References References
Correct answer
to all
questions
39
Distributed System (3170719) 220183107024
Experiment No: 7
Theory:
Lamport Vector clock is a logical clock used in distributed systems. It is an extension of the
Lamport Logical Clock algorithm. In a distributed system, different processes execute
independently and communicate with each other by exchanging messages. In order to keep track of
the order of events in a distributed system, each process maintains a vector clock.
A vector clock is a list of integer values, where each value represents the number of events
that have occurred in each process up until that point in time. Each process increments its own
value in the vector clock whenever an event occurs, and sends the updated vector clock along with
the message to the other processes. When a process receives a message, it updates its own vector
clock by taking the maximum value of each element in its own vector clock and the vector clock
received in the message.
The Lamport Vector clock algorithm ensures that if event A happened before event B, then
the vector clock of A is less than the vector clock of B.
Procedure:
Create a Java project in Eclipse or NetBeans.
Create a Process class that implements Runnable interface. The Process class should have
the following:
o A name for the process.
o A vector clock to keep track of events.
o A method to update the vector clock when an event occurs.
o A run() method that simulates the process.
o A method to send messages to other processes.
In the main() method, create an array of Process objects.
Start each process in the array by calling the start() method.
In the run() method of each Process object, simulate the occurrence of events and update
the vector clock accordingly.
When a process sends a message to another process, it should update its own vector clock
and send the updated vector clock along with the message.
When a process receives a message, it should update its own vector clock by taking the
maximum value of each element in its own vector clock and the vector clock received in
the message.
Test the implementation of the Lamport Vector clock algorithm by running the program
and
observing the vector clocks of each process. 40
Distributed System (3170719) 220183107024
Program Code:
import java.util.Arrays;
42
Distributed System (3170719) 220183107024
Exercise:
1. What is the purpose of Lamport Vector Clocks in distributed systems?
Ans: Lamport Vector Clocks are an extension of Lamport's logical clocks designed to address
the limitations of the original algorithm in scenarios where more information about causality is
needed. They serve the following purposes in distributed systems:
Lamport Vector Clocks allow for a more precise representation of causality between events in
a distributed system. Unlike logical clocks, vector clocks can capture the partial ordering of
events in a more detailed manner.
Determining Causality of Events:
They provide a way to determine whether two events are causally related or concurrent. This is
crucial for tasks like consistency management in distributed databases or maintaining the order
of operations in distributed systems.
Detecting Concurrent Events:
Vector clocks can identify events that occur concurrently. If two vector clocks have no relation
(neither is less than the other), it means the events are concurrent.
Ensuring Consistent State in Replicated Systems:
In systems with replicated data across multiple nodes, Lamport Vector Clocks can be used to
track updates and resolve conflicts. This helps ensure that each replica is in sync and maintains
a consistent state.
Ordering Messages and Events:
They can be used to order messages in a distributed system accurately. This is especially
important in scenarios where messages need to be processed in a specific order to maintain
correctness.
Distributed Algorithms:
Many distributed algorithms, like distributed consensus protocols (e.g., Paxos, Raft), rely on
vector clocks to make decisions about the state of the system.
Detecting Anomalies or Inconsistencies:
In scenarios where concurrent updates may occur (e.g., in distributed databases), vector clocks
can be used to resolve conflicts and ensure that updates are applied in a consistent manner.
Overall, Lamport Vector Clocks play a crucial role in achieving a more comprehensive
understanding of causality in distributed systems. They provide a powerful tool for managing
the ordering of events and messages in a way that can lead to more robust and reliable
distributed applications.
43
Distributed System (3170719) 220183107024
Representation:
44
Distributed System (3170719) 220183107024
3. Can two events have the same Lamport timestamp in a distributed system?
Ans: Yes, two events can have the same Lamport timestamp in a distributed system. This
occurs when the events are considered concurrent, meaning there is no direct causal
relationship between them. In Lamport's logical clocks, events with the same timestamp are
treated as having occurred simultaneously or in an indeterminate order with respect to each
other.
Suppose we have two processes, A and B, in a distributed system. Both processes have their
own Lamport logical clocks:
Process A:
Event X: Timestamp = 10
Event Y: Timestamp = 11
Process B:
Event Z: Timestamp = 10
In this scenario, events X and Z have the same timestamp (10) because there is no causal
relationship between them. The clocks of processes A and B are independent, and they do not
communicate or influence each other's timestamps directly. Therefore, events X and Z are
considered concurrent.
It's important to note that even though events may have the same Lamport timestamp, they can
still be causally related if there is a chain of causality through other events. Lamport's logical
clocks provide a partial ordering of events based on causality, but they may not capture all
possible causal relationships in a distributed system. Lamport Vector Clocks are a more
advanced tool that can capture additional causality information in such cases.
4. How do you update a Lamport Vector Clock when a process receives a message from
another process?
Ans: When a process receives a message from another process in a distributed system, it needs
to update its Lamport Vector Clock to reflect the new information about causality. Here are the
steps to update a Lamport Vector Clock:
Receiving a Message:
When a process receives a message, it extracts the sender's vector clock from the message.
Updating the Vector Clock:
For each element in the vector, the process takes the maximum value between its own
timestamp for that process and the timestamp received in the message from the sender. Then, it
increments its own timestamp for itself.
Example:
Let's say process P2 receives a message from process P1. Their vector clocks are as follows:
P1: [3, 1, 2]
P2: [2, 4, 5]
After receiving the message, P2 updates its vector clock as follows:
The process then processes the message using its updated vector clock.
Sending Messages with Updated Vector Clock:
If the process sends further messages, it includes its updated vector clock in the message to
ensure that causality is correctly tracked for subsequent events.
By following these steps, a process ensures that its Lamport Vector Clock accurately reflects
the causality of events in the distributed system, taking into account information from received
messages. This allows for a more precise ordering of events and a better understanding of
causality relationships in the system.
5. How can you detect causality violations using Lamport Vector Clocks?
Ans: Causality violations can occur in a distributed system when events are ordered incorrectly,
potentially leading to incorrect behavior or results. Lamport Vector Clocks can be used to
detect these violations. Here's how you can do it:
To detect causality violations, compare the vector clocks associated with events to ensure they
are in accordance with the happened-before relationship. Specifically, check if the vector clock
of one event is less than or equal to the vector clock of another event.
Identify Causality Violations:
If you find a pair of events A and B where the vector clock of A is not less than or equal to the
vector clock of B, then this indicates a causality violation. This means that event B is being
considered to have happened before event A, which is not consistent with the actual causal
relationship.
Example:
Let's consider two events, A and B, with their associated vector clocks:
Event A: [1, 0, 3]
Event B: [2, 1, 2]
If [1, 0, 3] ≤ [2, 1, 2], then causality is preserved. However, if [1, 0, 3] > [2, 1, 2], it indicates a
causality violation.
Once a causality violation is detected, investigate the events, message exchanges, and
processing logic to understand why the ordering is incorrect. This could be due to issues in
message delivery, incorrect vector clock updates, or other factors.
Debug and Correct the Code:
Review the code and logic related to event handling, message passing, and vector clock
updates. Identify and fix any bugs or logic errors that may be causing the causality violation.
Retest and Validate:
After making corrections, retest the system to ensure that causality is correctly maintained. Use
test cases that cover various scenarios to validate that the issue has been resolved.
By using Lamport Vector Clocks to compare the vector clocks associated with events, you can
systematically detect and address causality violations in a distributed system. This helps ensure
46
Distributed System (3170719) 220183107024
that events are correctly ordered according to their causal relationships.
6. Can Lamport Vector Clocks handle clock drifts between different processes?
Ans: Lamport Vector Clocks are not designed to handle clock drifts between different
processes. They assume that clocks across processes are synchronized, and any significant
clock drift can lead to inaccuracies in tracking causality.
Clock drift refers to the discrepancy in timekeeping between different clocks in a system. In a
distributed system, processes may have their own local clocks that may not be perfectly
synchronized. Over time, these clocks may drift apart due to factors such as hardware
variations, temperature changes, or clock inaccuracies.
If significant clock drift occurs, it can lead to incorrect ordering of events and potentially cause
causality violations when using Lamport Vector Clocks. For example, events that are actually
causally related may be assigned incorrect timestamps.
To handle clock drifts in a distributed system, more advanced clock synchronization techniques
and algorithms may be used. For instance, protocols like the Network Time Protocol (NTP) or
the Precision Time Protocol (PTP) can be employed to ensure more accurate time
synchronization across processes.
Additionally, more sophisticated logical clocks, like Hybrid Logical Clocks (HLC) or Google's
TrueTime, are designed to handle clock drifts and provide a more accurate representation of
time in distributed systems. These clocks incorporate mechanisms to account for both physical
time and logical ordering of events, allowing for better handling of scenarios involving clock
drift.
Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Distributed Systems: Principles and Paradigms" by Andrew S. Tanenbaum and Maarten
van Steen.
3. Distributed Computing and application by M L Liu, Pearson Education Inc.
References References
Correct answer
to all
questions
47
Distributed System (3170719) 220183107024
Experiment No: 8
Theory:
The Bully Algorithm is a leader election algorithm that is used in distributed systems. It is a
way to elect a leader node among a group of nodes, with the assumption that the leader node will
be responsible for coordinating and managing the system.
The Bully Algorithm is a fault-tolerant algorithm that is designed to handle node failures.
When a node fails, the other nodes will detect the failure and start a new election process to elect a
new leader. The Bully Algorithm is designed to elect a leader with the highest priority among all
the nodes in the system.
Procedure:
1. Create a Java class for the Node object that represents a node in the distributed system. The class
should have fields for the node ID and the priority of the node.
2. Implement a method for sending an election message to all the other nodes in the system.
3. Implement a method for receiving and processing messages from other nodes.
6. Create a main class for the distributed system that creates and initializes the nodes, and starts the
election process.
7. Test the system by simulating node failures and observing how the algorithm handles them.
Algorithm:
Each process in the network has a unique ID number.
If a process P detects that the coordinator has failed, it sends an ELECTION message to all
processes with higher ID numbers.
If a process Q receives an ELECTION message from P, it sends an OK message to P, indicating
that it is still alive.
48
Distributed System (3170719) 220183107024
If a process Q does not receive a message from a higher-ID process within a certain time period,
it assumes that the higher-ID process has failed and initiates an election process.
When a process R receives an OK message from all higher-ID processes, it becomes the new
coordinator and sends a COORDINATOR message to all other processes to inform them of the
new leader.
Program Code:
import java.util.ArrayList;
import java.util.List;
public class
BullyAlgorithm {
public static void main(String[] args)
{ List<Node> nodes = new
ArrayList<>();
nodes.get(3).setCoordinator(true);
Conclusion:
Exercise :
Leader Election:
49
Distributed System (3170719) 220183107024
The primary purpose of the Bully Algorithm is to elect a leader or coordinator among a group
of processes. This leader is responsible for making decisions and coordinating the activities
of the processes in the system.
Fault Tolerance:
The algorithm is designed to handle failures in a distributed system. If the current leader fails
or becomes unresponsive, the Bully Algorithm ensures that a new leader is elected to take
over the coordinator role.
Scalability:
The algorithm allows for scalability in distributed systems. As new processes join the network
or existing ones leave, the Bully Algorithm can re-elect a leader to maintain the coordination
and organization of the system.
Avoidance of Conflicts:
By designating a single coordinator, the Bully Algorithm helps prevent conflicts or race
conditions that may occur if multiple processes attempt to perform the same task
simultaneously.
Synchronization:
Having a designated leader allows for synchronized execution of tasks in the distributed
system. The leader can ensure that processes carry out their tasks in a coordinated manner.
Resource Allocation:
The coordinator, elected by the Bully Algorithm, is often responsible for managing shared
resources, allocating tasks, and ensuring that processes have access to the necessary resources.
Reduced Communication Overhead:
By designating a leader, the system can reduce the need for processes to communicate with
every other process in the network when making decisions. Instead, they can communicate
directly with the leader.
Decentralized Decision-Making:
The Bully Algorithm enables a decentralized system to autonomously elect a leader without
relying on a central authority or external intervention.
Overall, the Bully Algorithm plays a critical role in maintaining the stability and functionality
of distributed systems by ensuring that a single, reliable process is designated as the
coordinator to oversee the system's operations
When a node detects that the current leader has failed or is unresponsive, it initiates a leader
election process.
Election Message:
The node that detects the leader's failure sends an election message to all nodes with higher
ranks than itself.
50
Distributed System (3170719) 220183107024
Election Process:
Each higher-ranked node that receives the election message responds by either:
Acknowledging the election request and announcing its own candidacy.
Ignoring the request if it is not interested in becoming the leader.
Higher-Ranked Node Takes Over:
If no higher-ranked node responds, the initiating node declares itself as the new leader and
takes over the coordinator role.
Coordinator Propagation:
If a higher-ranked node responds and announces its candidacy, it then initiates its own
election process by sending election messages to nodes with even higher ranks. This process
continues until a node with the highest rank is identified.
Highest-Ranked Node Becomes Leader:
The highest-ranked node that successfully completes the election process becomes the new
leader and takes over the coordinator role.
Recovery and Resumption of Normal Operations:
Once a new leader is elected, normal operations in the distributed system can resume under
the coordination of the newly elected leader.
It's important to note that the Bully Algorithm assumes that nodes have unique ranks, and
higher-ranked nodes are considered more "powerful" or capable of taking on the coordinator
role. Additionally, the algorithm assumes that nodes are aware of each other's status and can
communicate reliably.
The Bully Algorithm provides fault tolerance by ensuring that a new leader is elected in the
event of a failure, helping to maintain the stability and functionality of the distributed system.
3. What happens when a node receives an election message from a node with a higher
priority?
Ans: When a node receives an election message from a node with a higher priority (rank) in
the Bully Algorithm, it must respond according to the protocol to ensure a proper leader
election process. Here are the steps a node takes when it receives an election message from a
higher-priority node:
Acknowledgment of Election:
The receiving node acknowledges the election message, indicating that it recognizes the
higher-priority node's candidacy for the leader position.
Announcement of Candidacy:
After acknowledging the election message, the receiving node announces its own candidacy
for the leader position. This means that it is willing to take on the role of leader if it is elected.
Initiation of Its Own Election Process:
The receiving node, now a candidate for the leader position, initiates its own election process
by sending election messages to nodes with even higher ranks than itself. This allows the
process to continue until a node with the highest rank is identified.
Propagation of the Election Process:
If the receiving node is the highest-ranked node that responded, it may become the new
leader. However, if it receives acknowledgment from an even higher-ranked node, it
acknowledges
51
Distributed System (3170719) 220183107024
that node's candidacy and initiates its own election process.
Highest-Ranked Node Becomes Leader:
The highest-ranked node that successfully completes the election process becomes the new
leader and takes over the coordinator role.
By following these steps, the receiving node ensures that the election process continues until
the highest-ranked node is identified and elected as the new leader. This allows for a reliable
leader election process in the event of a failure or unresponsiveness of the current leader.
Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest
Wiley Publication
2. "Distributed Systems: Principles and Paradigms" by Andrew S. Tanenbaum and
Maarten van Steen.
References References
Correct answer
to all
questions
52
Distributed System (3170719) 220183107024
Experiment No: 09
Objectives:
Theory:
To use CORBA, you need to define an interface for your objects using the Interface
Definition Language (IDL). The IDL defines the methods and attributes that the objects will
expose to clients. The IDL compiler generates stub and skeleton code for the client and server
objects respectively. The stub and skeleton code provide the necessary marshaling and
unmarshaling of method arguments and results between the client and server.
The steps involved in implementing a simple client-server application using CORBA are:
Define the IDL interface
Compile the IDL interface using the IDL compiler
Implement the server object
Start the ORB
Register the server object with the ORB
Implement the client object
Compile the client object
Run the client object
Procedure:
Define the IDL interface: Define the interface for your objects using the Interface
Definition Language (IDL). The interface should include the methods and attributes
that the server object will expose to clients.
53
Distributed System (3170719) 220183107024
Compile the IDL interface using the IDL compiler: Use the IDL compiler to
generate stub and skeleton code for the client and server objects respectively.
Implement the server object: Implement the server object in Java using the skeleton
code generated by the IDL compiler. The server object should implement the
methods defined in the IDL interface.
Start the ORB: Start the ORB by running the orb.run command.
Register the server object with the ORB: Register the server object with the ORB
using the Naming Service.
Implement the client object: Implement the client object in Java using the stub code
generated by the IDL compiler. The client object should invoke the methods
defined in the IDL interface.
Compile the client object: Use the Java compiler to compile the client object.
Run the client object: Run the client object and observe the results.
Program Code:
Server:
from omniORB import CORBA, PortableServer
import Example, Example POA
ei = Example.StringManipulator
im = StringManipulator_i()
eo = im._this()
poaManager = poa._get_the_POAManager()
poaManager.activate()
ns = orb.resolve_initial_references("NameService")
nc = ns._narrow(CORBA.NamingContext)
if nc is None:
print("This is not a valid NamingContext")
sys.exit(1)
orb.run()
54
Distributed System (3170719) 220183107024
Client:
Conclusion:
In this practical, we implemented a basic CORBA (Common Object Request Broker Architecture)
application using Python. The application consists of a client and a server, communicating through
CORBA's middleware.
The server provides a simple interface StringManipulator with a single method toUpperCase,
which takes a string as input, converts it to uppercase, and returns the result.
The client establishes a connection to the server using CORBA's naming service. It then calls the
toUpperCase method on the server, passing a string. The server processes the request and sends
back the uppercase version of the string to the client.
This practical demonstrates the power of CORBA in enabling communication between distributed
objects in a platform-independent manner. CORBA allows objects written in different
programming languages to interact seamlessly, making it a valuable tool for building complex,
distributed systems.
Keep in mind that this example is simplified for educational purposes and lacks robust error
handling and security measures that would be necessary in a production environment. Additionally,
CORBA itself may not be the most modern or widely used technology for distributed systems, and
alternatives like RESTful APIs, gRPC, or more recent middleware technologies might be preferred
depending on the specific requirements of a project.
Suggested Reference(s):
1. "CORBA: Architecture and Programming with Java" by John Siegel and Thomas
Mowbray
55
Distributed System (3170719) 220183107024
Rubric wise marks obtained:
Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked
References References
Correct answer
to all
questions
56
Distributed System (3170719) 220183107024
Experiment 10
Competency and Practical Skills: Web development, programming skills, and knowledge of
web services.
Objectives:
Theory:
A web service is a software system designed to support interoperable machine-to-machine
interaction over a network. It has an interface described in a machine-processable format,
specifically WSDL (Web Service Description Language). Other systems interact with the web
service in a manner prescribed by its description using SOAP messages, typically conveyed using
HTTP with an XML serialization in conjunction with other web-related standards.
Apache Axis is one of the popular implementations of web services that is built on top of the
Apache SOAP project. It is an open-source, XML-based web service framework that provides a
means to generate WSDL and create client applications in various programming languages,
including Java.
Procedure:
Create a Java project in Eclipse or NetBeans.
Define the web service interface using the JAX-WS (Java API for XML Web Services)
annotations. This interface should declare the methods that will be exposed as web
service operations. Annotate the interface with @WebService and @WebMethod
annotations.
Implement the web service interface in a Java class. Annotate the class with
@WebService and @WebServiceProvider annotations. Implement the methods
declared in the interface. 57
Distributed System (3170719) 220183107024
Create a web application project in Eclipse or NetBeans. Add the Java class created in
step 3 to the project.
Create a web service deployment descriptor (web.xml) file. This file should specify the
location of the web service implementation class and the URL mapping for the web
service endpoint.
Deploy the web service to a web server such as Apache Tomcat. Publish the web
service by deploying the web application project created in step 4.
Create a client application that will consume the web service. The client application can
be created in any programming language that supports SOAP messages. For this lab,
create a Java client application using the JAX-WS API.
Generate the client artifacts using the wsimport tool provided by the JDK. This tool
generates Java classes that correspond to the WSDL of the web service.
Use the generated Java classes to invoke the web service operations in the client
application.
Run the client application and observe the results of invoking the web service
operations.
Program Code:
@WebService
public class
SimpleWebService {
@WebMethod
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
Web Service Endpoint Interface (SEI):
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface
SimpleWebServiceInterface {
@WebMethod
String sayHello(String name);
}
Conclusion:
Web services provide a means for different applications to interact with each other
over a network.
Apache Axis is a popular implementation of web services that provides a means to
generate WSDL and create client applications in various programming languages.
Web services can be published on a web server and consumed by client applications in
a secure and efficient manner.
58
Distributed System (3170719) 220183107024
Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Java Web Services: Up and Running" by Martin Kalin
References References
Correct answer
to all
questions
59
Distributed System (3170719) 220183107024
Experiment 11
Theory:
A Business Process Execution Language (BPEL) process is an executable process that
describesthe behavior of a business process based on a set of activities, including receiving and
sending messages, invoking services, and manipulating data.
In this lab, we will use Oracle JDeveloper to create a BPEL process and a composite
application that integrates multiple services.
Procedure:
Open Oracle JDeveloper and create a new application by selecting File > New > Application
from the menu.
Select the "SOA Application" template and click "OK".
In the "Create SOA Application" wizard, enter the application name and click "Next".
In the "Select Template" page, select "Composite with BPEL" and click "Next".
Enter the composite name and click "Finish".
In the "composite.xml" file, drag and drop a "BPEL Process" component from the
Component Palette onto the design canvas.
Double-click the "BPEL Process" component to open the "BPEL Process Editor".
In the "BPEL Process Editor", add the required activities to define the business process,
such as "Receive", "Invoke", "Assign", and "Reply".
Save the BPEL process by selecting File > Save from the menu.
In the "composite.xml" file, drag and drop the required components from the
Component Palette onto the design canvas to create the composite application.
Use the "Service Component Architecture" (SCA) editor to wire the components
together by creating "references" and "bindings".
Save the composite application by selecting File > Save from the menu.
60
Distributed System (3170719) 220183107024
Deploy the composite application to the Oracle WebLogic Server by right-clicking the
"composite.xml" file and selecting "Deploy".
Test the composite application by accessing the services provided by the components.
Observations:
During the BPEL process creation, we observed that it is possible to add different activities to
the process to define the business logic.
In the composite application, we observed that the components can be easily wired together
using the SCA editor.
During deployment, we observed that the composite application is deployed as a single unit to
the Oracle WebLogic Server.
Conclusion:
Creating a BPEL process and composite module in Oracle SOA Suite is a powerful way to
model, orchestrate, and manage business processes. It provides a structured approach to
integrating various services and applications, allowing organizations to automate complex
workflows and improve operational efficiency.
Remember that this practical is a high-level overview, and actual implementation may involve
more detailed steps, including configuring service endpoints, defining data transformations,
implementing security measures, and conducting thorough testing in a controlled
environment. Additionally, documentation and version control are crucial aspects of real-
world development to ensure maintainability and scalability of your SOA projects.
Suggested Reference(s):
1. "Service-Oriented Architecture: Concepts, Technology, and Design" by Thomas Erl
References References
Correct answer
to all
questions
61
Distributed System (3170719) 220183107024
Experiment 12
Theory:
Conclusion:
The study of open-source Key Management tools demonstrates their vital role in securing
digital communications, transactions, and sensitive data. Selecting the right tool depends on
various factors, including the organization's size, compliance requirements, technology stack, and
specific security needs. Thorough evaluation, testing, and ongoing community support are
essential for successful implementation and maintenance of these tools. It's recommended that
organizations consider consulting with security experts or leveraging community forums to ensure
the chosen tool aligns with their unique requirements.
62
Distributed System (3170719) 220183107024
Suggested References:
1. OpenSSL - https://www.openssl.org/
2. GnuPG - https://gnupg.org/
3. Bouncy Castle - https://www.bouncycastle.org/
4. Keyczar - https://github.com/google/keyczar
5. Vault - https://www.vaultproject.io/
6. HashiCorp - https://www.hashicorp.com/
7. Apache Ranger - https://ranger.apache.org/
References References
Correct answer
to all
questions
63