Practical Session 12 Reactor Pattern. Disadvantages of Thread per Client It's wasteful – Creating a new Thread is relatively expensive. – Each thread.

Slides:



Advertisements
Similar presentations
Categories of I/O Devices
Advertisements

TP4: S TATE M ACHINE D ESIGN P ATTERN  Definition  Infrastructure  Transition Code  Conclusion.
Data Communications and Networking (Third Edition)
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
1 L55 Networking (4). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
I/O Hardware n Incredible variety of I/O devices n Common concepts: – Port – connection point to the computer – Bus (daisy chain or shared direct access)
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Server Architecture Models Operating Systems Hebrew University Spring 2004.
System Programming Practical session 12 Reactor.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
RPC Project Using either sockets or TLI, implement Remote Procedure Calls between two distinct machines that are communicating over an Ethernet network.
A Chat Server DBI – Representation and Management of Data on the Internet.
CSCE 515: Computer Network Programming TCP Details Wenyuan Xu Department of Computer Science and Engineering.
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
P2P Project Mark Kurman Nir Zur Danny Avigdor. Introduction ► Motivation:  Firewalls may allow TCP or UDP connections on several specific ports and block.
Fundamentals of Python: From First Programs Through Data Structures
Basic Concepts of Computer Networks
Server Design Discuss Design issues for Servers Review Server Creation in Linux.
Practical Session 11 Multi Client-Server Java NIO.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
Socket Programming References: redKlyde ’ s tutorial set Winsock2 for games (gamedev.net)
Programming Network Servers Topic 6, Chapters 21, 22 Network Programming Kansas State University at Salina.
Institute of Computer and Communication Network Engineering OFC/NFOEC, 6-10 March 2011, Los Angeles, CA Lessons Learned From Implementing a Path Computation.
Firewall and Internet Access Mechanism that control (1)Internet access, (2)Handle the problem of screening a particular network or an organization from.
By Lecturer / Aisha Dawood 1.  You can control the number of dispatcher processes in the instance. Unlike the number of shared servers, the number of.
CHAPTER 2: COMPUTER-SYSTEM STRUCTURES Computer system operation Computer system operation I/O structure I/O structure Storage structure Storage structure.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
ICOM 6115©Manuel Rodriguez-Martinez ICOM 6115 – Computer Networks and the WWW Manuel Rodriguez-Martinez, Ph.D. Lecture 26.
Concurrent Programming. Concurrency  Concurrency means for a program to have multiple paths of execution running at (almost) the same time. Examples:
1 Web Based Programming Section 8 James King 12 August 2003.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
The Alternative Larry Moore. 5 Nodes and Variant Input File Sizes Hadoop Alternative.
Practical Session 11 Multi Client-Server Java NIO.
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 14 Threads 2 Read Ch.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Lecture 4 Mechanisms & Kernel for NOSs. Mechanisms for Network Operating Systems  Network operating systems provide three basic mechanisms that support.
Prepared by:Ronnel P. Agulto, CpE Objectives Different types of topologies; Their advantages & disadvantages How to choose an appropriate topologies in.
Networks, Part 2 March 7, Networks End to End Layer  Build upon unreliable Network Layer  As needed, compensate for latency, ordering, data.
Silberschatz, Galvin, and Gagne  Applied Operating System Concepts Module 12: I/O Systems I/O hardwared Application I/O Interface Kernel I/O.
Netprog: Client/Server Issues1 Issues in Client/Server Programming Refs: Chapter 27.
SPL/2010 Reactor Design Pattern 1. SPL/2010 Overview ● blocking sockets - impact on server scalability. ● non-blocking IO in Java - java.niopackage ●
The Echo Server Problem. Contents  Basic Networking Concepts  The Echo Server Problem.
The Echo Server Problem. Contents  Basic Networking Concepts  The Echo Server Problem.
Fast Retransmit For sliding windows flow control we waited for a timer to expire before beginning retransmission of a packet TCP uses an additional mechanism.
Module 12: I/O Systems I/O hardware Application I/O Interface
Thread Pools (Worker Queues) cs
Thread Pools (Worker Queues) cs
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Lecture 21 Concurrency Introduction
Java Byte IPC: Part 6-Summary
CSCI 315 Operating Systems Design
Reactor Design Pattern
Operating Systems Chapter 5: Input/Output Management
Operating System Concepts
13: I/O Systems I/O hardwared Application I/O Interface
CS703 - Advanced Operating Systems
Multithreaded Programming
Issues in Client/Server Programming
Threaded Programming in Python
Server-side Programming CSE 333 Autumn 2018
Server-side Programming CSE 333 Summer 2018
Chapter 13: I/O Systems I/O Hardware Application I/O Interface
Processes Creation and Threads
Chapter 13: I/O Systems I/O Hardware Application I/O Interface
Exceptions and networking
Module 12: I/O Systems I/O hardwared Application I/O Interface
The reactor design pattern
Thread per client and Java NIO
Chapter 13: I/O Systems “The two main jobs of a computer are I/O and [CPU] processing. In many cases, the main job is I/O, and the [CPU] processing is.
Presentation transcript:

Practical Session 12 Reactor Pattern

Disadvantages of Thread per Client It's wasteful – Creating a new Thread is relatively expensive. – Each thread requires a fair amount of memory. – Threads are blocked most of the time waiting for network IO. It's not scalable – A Multi-Threaded server can't grow to accommodate hundreds of concurrent requests – It's also vulnerable to Denial Of Service attacks (an attempt to make a machine or network resource unavailable to its intended users). Poor availability – It takes a long time to create a new thread for each new client. – The response time degrades as the number of clients rises. Solution – The Reactor Pattern is another (better) design for handling several concurrent clients.

Reactor Pattern It's based on the observation that if a thread does not need to wait for Network IO, a single thread could easily handle tens of client requests alone. Uses Non-Blocking IO, so threads don't waste time waiting for Network. Have one thread in charge of the network: – Accepting new connections and handling IO. – As the Network is non-blocking, read, write and accept operations "take no time", and a single thread is enough for all the clients. Have a fixed number of threads, which are in charge of the protocol. – These threads perform the message framing (Tokenization) – Perform message processing (what to do with each message). Note that unlike the Multi-Threaded server, in this design a single thread may handle many clients.

How Is It Done? We require non-blocking network access. We talked about: – Channel (wrap a socket, decouples open and connect; supports concurrent threads, and concurrent reading and writing; only one thread reading at a time; only one thread writing at a time). – Buffer (need it to read/write to channels) We will talk about: – Selector

Selectors When we perform non-blocking IO, read(), we read currently available bytes and return the result. This means we can read or write 0 bytes, and this is what will probably happen most of the time. We would like a way for our thread to wait until any of our channels is ready, and only then perform the read(), write() or accept(), only on the ready channel. This is what the Selector class does. Tutorial:

Selector A Selector allows a single thread to handle multiple Channel's. Handy if your application has many connections (Channels) open, but only has low traffic on each connection. For instance, in a chat server.

Workflow Example: Initial State Server listens to some port. Selector registered to retrieve ACCEPT events when requested. Attachment ConnectionAcceptor used to accept incoming connection.

Client 1: Attempts to connect to server

ACCEPT Event is raised

Server selects events, handles them.

Client 1: Sends data. Client 2: Connection request.

New events raised.

Events Selected and handled.

New Events raised – Write Events are selectable!

Write event for client 1 handled. For client 2 ignored

Client 3: Connection request. Client 2/3: Write

Events raised!

And handled…

Registering Selector to Channel The Selector registers itself to a Channel. Registration means that the channel informs the Selector when some event happens. This event can be: – Channel is ready to be read from. [incoming message] – Channel can now be written to. [outgoing message] – Channel can now accept a new connection. [incoming connection request] During registration a selection key is given to the channel, and the channel is told which events to monitor: – Selector selector = Selector.open(); // a new Selector – ConnectionHandler connectionHandler = new ConnectionHandler(); Or ConnectionAccepter connectionAcceptor = new ConnectionAcceptor(); – socketChannel.register(selector, SelectionKey.OP_READ, anAttachmemt); A channel can monitor OP_READ, OP_WRITE, OP_ACCEPT, OP_CONNECT In order to support more than one command, we use bitwise or: – OP_READ | OP_WRITE Attachment: – Done when registering a selector to a channel. – An attachment is an object that we will have access to when the event occurs – Usually, this object is associated with a task that should be performed.

Registration Example Adding a selector for the server channel which accepts new connections:

register() Registers this channel with the given selector, returning a selection key. This method first verifies that this channel is open and that the given initial interest set is valid. If this channel is already registered with the given selector, the selection key representing that registration is returned after setting its interest set to the given value. Otherwise, The resulting key is added to this channel's key set before being returned.

select() Once a Selector is registered to some channels, one can use the "select()" method. This method blocks until at least one of the channels is ready for the registered event. Then, a list of SelectionKeys is returned. Each Selectionkey is associated with one channel, and holds: – The interest set (events we’re registered to) – The ready set (events the channel is ready for) – The Channel – The Selector – the attachment registered on the channel (optional).

Three Different Server Events Event is isAcceptable() – OP_ACCEPT – We retrieve ConnectionAcceptor object attached. – We run its accept() method, which accepts a new incoming connection through that channel. – Note: ConnectionAcceptor contains a reference to its channel (done upon construction). Event is isReadable() – OP_READ – We retrieve ConnectionHandler object attached. – We run its.read() method, which attempts to read data received by the channel from client. Event is isWritable() – OP_WRITE – We retrieve ConnectionHandler object attached. – We run its.write() method, which attempts to write data to the channel in order to send it from server to client.

ConnectionAcceptor Used only for ServerSocketChannel in order to accept new connections. Accept workflow: Selector now listens to OP_READ events on this channel in anticipation of new data.

Accepting a new connection ConnectionAcceptor method. In ConnectionHandler.create() we attach the ConnectionHandler to the SelectorKey. In register(): 0 indicates that initially it does not listen to any type of event. switchToReadOnlyMode() changes the Selector to listen to SelectionKey.OP_READ The “key” returned from the register() is the token [id] of this registration (one key per channel). Accessing the selector can be done via this “key”.

ConnectionHandler ConnectionHandler contains: outData: Vector - contains data to be sent to client. – SocketChannel it needs to read from and write to. read() from channel to (local) ByteBuffer. write() from outData in channel. – MessageTokenizer in order to tokenize received data. void addBytes(ByteBuffer buffer) – adds (the local) ByteBuffer to StringBuffer Boolean hasMessage() – returns true if a complete message exists in inData String nextMessage() – removes and returns a complete message from inDat – ServerProtocol in order to process message, and create response. String processMessage(String message) – processes message, creates response. Boolean isEnd(String message) – checks whether message is shutdown request. – ProtocolTask is our runnable. One runnable per one connection handler. We run the same task once per event handling. – Uses MessageTokenizer in order to retrieve a complete message. – Uses ServerProtocol in order to process message and create response. » Response stored in outData

ConnectionHandler: read()

ConnectionHandler: write() outData = Vector (). Each message to be sent is stored in ByteBuffer. All messages to be sent are stored in outData.

Reactor main loop. Scans the channels and retrieves the new events. Initiates the appropriate function of the retrieved attachment depending on event type.

The different parts The Reactor: – Our driver [main] – In charge of handling reading, writing and accepting new connection events. Reading and Writing are encapsulated in the ConnectionHandler class Accepting is encapsulated in the ConnectionAcceptor class. – Holds a thread-pool of workers (an Executor). [inside ReactorData object] These worker-threads are in charge of the protocol handling. They receive the bytes read from the network, and apply the protocol on the received data. ProtocolTask: [ our runnable] – The class which represents tasks submitted to the executor. – The ProtocolTask object is created along with the ConnectionHandler. – Task object is created once, and used every time new data is received. Checks if a complete message is found Applies protocol on received data Adds response to outData vector

Continued ConnectionHandler holds for each connection: – The SocketChannel for a specific connection – Vector outData – the data to be sent – ProtocolTask which includes MessageTokenizer which stores and handler received data. Important: – We don't have one thread per connection. – We have one ConnectionHandler object per connection. – We have one ConnectionAcceptor object for the ServerChannel. – Each channel is associated with SelectionKey – ProtocolTask is our runnable, and executed whenever new data is received, stores received data inside it and applies our MessageTokenizer on the processed data, the response generated is sent to the outData to be sent.

AsyncServerProtocol Has same functionality of ServerProtocol Has two additions: – boolean shouldClose()://like thread.shouldStop() Returns true after the terminating message has been encountered. This is used to signal the connection handler that the protocol has done its work and it's time to send all the remaining bytes and quit. – void connectionTerminated(): Used to notify the protocol the client closed the connection, or that the network connection was lost. This is called by the ConnectionHandler when it identifies a network error.