1. Web Services 2. Concurrency and threads. Web History 1989: Tim Berners-Lee (CERN) writes...

70
1. Web Services 2. Concurrency and threads

Transcript of 1. Web Services 2. Concurrency and threads. Web History 1989: Tim Berners-Lee (CERN) writes...

Page 1: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

1. Web Services

2. Concurrency and threads

Page 2: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Web History

1989: Tim Berners-Lee (CERN) writes internal proposal to develop a

distributed hypertext system. Connects “a web of notes with links.” Intended to help CERN physicists in large projects share and

manage information 1990:

Tim BL writes a graphical browser for Next machines.

Page 3: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Web History (cont) 1992

NCSA server released 26 WWW servers worldwide

1993 Marc Andreessen releases first version of NCSA Mosaic browser Mosaic version released for (Windows, Mac, Unix). Web (port 80) traffic at 1% of NSFNET backbone traffic. Over 200 WWW servers worldwide.

1994 Andreessen and colleagues leave NCSA to form “Mosaic

Communications Corp” (predecessor to Netscape).

Page 4: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Internet Hosts

Page 5: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Web Servers

Webserver

HTTP request

HTTP response(content)

Clients and servers communicate using the HyperText Transfer Protocol (HTTP) Client and server establish TCP

connection Client requests content Server responds with

requested content Client and server close

connection (eventually) Current version is HTTP/1.1

RFC 2616, June, 1999.

Webclient

(browser)

http://www.w3.org/Protocols/rfc2616/rfc2616.html

IP

TCP

HTTP

Datagrams

Streams

Web content

Page 6: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Web Content Web servers return content to clients

content: a sequence of bytes with an associated MIME (Multipurpose Internet Mail Extensions) type

Example MIME types text/html HTML document text/plain Unformatted text application/postscript Postcript document image/gif Binary image encoded in GIF

format image/jpeg Binary image encoded in JPEG

format

Page 7: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Static and Dynamic Content

The content returned in HTTP responses can be either static or dynamic. Static content: content stored in files and retrieved in response to

an HTTP request Examples: HTML files, images, audio clips. Request identifies content file

Dynamic content: content produced on-the-fly in response to an HTTP request

Example: content produced by a program executed by the server on behalf of the client.

Request identifies file containing executable code Bottom line: All Web content is associated with a file that

is managed by the server.

Page 8: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

URLs Each file managed by a server has a unique name called a URL

(Universal Resource Locator) URLs for static content:

http://reed.cs.depaul.edu:80/index.html http://reed.cs.depaul.edu/index.html http://reed.cs.depaul.edu

Identifies a file called index.html, managed by a Web server at reed.cs.depaul.edu that is listening on port 80.

URLs for dynamic content: http://riely373.cdm.depaul.edu:8000/cgi-bin/adder?15000&213

Identifies an executable file called adder, managed by a Web server at riely373.cdm.depaul.edu that is listening on port 8000, that should be called with two argument strings: 15000 and 213.

Page 9: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

How Clients and Servers Use URLs Example URL: http://www.depaul.edu:80/index.html Clients use prefix (http://www.depaul.edu:80) to infer:

What kind of server to contact (Web server) Where the server is (www.depaul.edu) What port it is listening on (80)

Servers use suffix (/index.html) to: Determine if request is for static or dynamic content.

No hard and fast rules for this. Convention: executables reside in cgi-bin directory

Find file on file system. Initial “/” in suffix denotes home directory for requested content. Minimal suffix is “/”, which all servers expand to some default

home page (e.g., index.html).

Page 10: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Anatomy of an HTTP Transaction$ telnet reed.cs.depaul.edu 80Trying 140.192.39.42...Connected to reed.cti.depaul.edu.Escape character is '^]'.GET / HTTP/1.1host: reed.cs.depaul.edu

HTTP/1.1 200 OKServer: Apache-Coyote/1.1Accept-Ranges: bytesETag: W/"2285-1357855910000"Last-Modified: Thu, 10 Jan 2013 22:11:50 GMTContent-Type: text/htmlContent-Length: 2285Date: Mon, 04 Mar 2013 04:01:00 GMT

<html><head><META http-equiv="Content-Type" content="text/html; charset=UTF-8”>...

Page 11: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

HTTP Requests

HTTP request is a request line, followed by zero or more request headers

Request line: <method> <uri> <version> <version> is HTTP version of request (HTTP/1.0 or HTTP/1.1)

<uri> is typically URL for proxies, URL suffix for servers. A URL is a type of URI (Uniform Resource Identifier) See http://www.ietf.org/rfc/rfc2396.txt

<method> is either GET, POST, OPTIONS, HEAD, PUT, DELETE, or TRACE.

Page 12: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

HTTP Requests (cont) HTTP methods:

GET: Retrieve static or dynamic content Arguments for dynamic content are in URI Workhorse method (99% of requests)

POST: Retrieve dynamic content Arguments for dynamic content are in the request body

OPTIONS: Get server or file attributes HEAD: Like GET but no data in response body PUT: Write a file to the server! DELETE: Delete a file on the server! TRACE: Echo request in response body

Useful for debugging. Request headers: <header name>: <header data>

Provide additional information to the server.

Page 13: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

HTTP Versions

Major differences between HTTP/1.1 and HTTP/1.0 HTTP/1.0 uses a new connection for each transaction. HTTP/1.1 also supports persistent connections

multiple transactions over the same connection Connection: Keep-Alive

HTTP/1.1 requires HOST header Host: www.depaul.edu Makes it possible to host multiple websites at single Internet

host HTTP/1.1 supports chunked encoding (described later)

Transfer-Encoding: chunked HTTP/1.1 adds additional support for caching

Page 14: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

HTTP Responses HTTP response is a response line followed by zero or more

response headers. Response line: <version> <status code> <status msg>

<version> is HTTP version of the response. <status code> is numeric status. <status msg> is corresponding English text.

200 OK Request was handled without error 301 Moved Provide alternate URL 403 Forbidden Server lacks permission to access file 404 Not found Server couldn’t find the file.

Response headers: <header name>: <header data> Provide additional information about response Content-Type: MIME type of content in response body. Content-Length: Length of content in response body.

Page 15: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

GET Request From Chrome Browser

GET / HTTP/1.1\r\nHost: reed.cs.depaul.edu\r\nConnection: keep-alive\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\nCookie:__utma=114012434.756988690.1360702406.1360702406.1360874291.2; __utmz=114012434.1360874291.2.2.utmcsr=cdm.depaul.edu|utmccn=(referral)|utmcmd=referral|utmcct=/academics/Pages/bs%20computerscience%20standard.aspx\r\n\r\n

URI is just the suffix, not the entire URL

Page 16: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

GET Response From Apache Server

HTTP/1.1 200 OKServer: Apache-Coyote/1.1\r\nAccept-Ranges: bytes\r\nETag: W/”2285-1357855910000”\r\nLast-Modified: Thu, 10 Jan 2013 22:11:50 GMT\r\nContent-Type: test/html\r\nContent-Length: 2285\r\nDate: Mon, 04 Mar 2013 04:58:40 GMT\r\n\r\n<html>\n<head>\n...

Page 17: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Tiny Web Server Tiny Web server described in text

Tiny is a sequential Web server. Serves static and dynamic content to real browsers.

text files, HTML files, GIF and JPEG images. 226 lines of commented C code. Not as complete or robust as a real web server

Page 18: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Tiny Operation Read request from client Split into method / uri / version

If not GET, then return error If URI contains “cgi-bin” then serve dynamic content

Fork process to execute program Otherwise serve static content

Copy file to output

Page 19: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Tiny Serving Static Content

Serve file specified by filename Use file metadata to compose header “Read” file via mmap Write to output

/* Send response headers to client */ get_filetype(filename, filetype); sprintf(buf, "HTTP/1.0 200 OK\r\n"); sprintf(buf, "%sServer: Tiny Web Server\r\n", buf); sprintf(buf, "%sContent-length: %d\r\n", buf, filesize); sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, filetype); Rio_writen(fd, buf, strlen(buf));

/* Send response body to client */ srcfd = Open(filename, O_RDONLY, 0); srcp = Mmap(0, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0); Close(srcfd); Rio_writen(fd, srcp, filesize); Munmap(srcp, filesize);

From tiny.c

Page 20: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content

Client Server

Client sends request to server.

If request URI contains the string “/cgi-bin”, then the server assumes that the request is for dynamic content.

GET /cgi-bin/env.pl HTTP/1.1

Page 21: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content (cont)

Client Server The server creates a child

process and runs the program identified by the URI in that process

env.pl

fork/exec

Page 22: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content (cont)

Client Server The child runs and generates

the dynamic content. The server captures the

content of the child and forwards it without modification to the client

env.pl

Content

Content

Page 23: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Issues in Serving Dynamic Content

How does the client pass program arguments to the server?

How does the server pass these arguments to the child?

How does the server pass other info relevant to the request to the child?

How does the server capture the content produced by the child?

These issues are addressed by the Common Gateway Interface (CGI) specification.

Client Server

Content

Content

Request

Create

env.pl

Page 24: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

CGI

Because the children are written according to the CGI spec, they are often called CGI programs.

Because many CGI programs are written in Perl, they are often called CGI scripts.

However, CGI really defines a simple standard for transferring information between the client (browser), the server, and the child process.

Page 25: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

The cdmlinux addition portalinput URL

Output page

host port CGI program args

Page 26: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content With GET Question: How does the client pass arguments to the server? Answer: The arguments are appended to the URI Can be encoded directly in a URL typed to a browser or a URL

in an HTML link http://cdmlinux.cdm.depaul.edu/cgi-bin/adder?n1=4&n2=7

adder is the CGI program on the server that will do the addition. argument list starts with “?” arguments separated by “&” spaces represented by “+” or “%20”

URI often generated by an HTML form

<FORM METHOD=GET ACTION="cgi-bin/adder"><p>X <INPUT NAME="n1"><p>Y <INPUT NAME="n2"><p><INPUT TYPE=submit></FORM>

Page 27: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content With GET

URL: cgi-bin/adder?4&7

Result displayed on browser:

Welcome to THE Internet addition portal.

The answer is: 4+7=11

Thanks for visiting!

Page 28: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content With GET Question: How does the server pass these arguments to

the child? Answer: In environment variable QUERY_STRING

A single string containing everything after the “?” For add: QUERY_STRING = “4&7”

Page 29: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Additional CGI Environment Variables General

SERVER_SOFTWARE SERVER_NAME GATEWAY_INTERFACE (CGI version)

Request-specific SERVER_PORT REQUEST_METHOD (GET, POST, etc) QUERY_STRING (contains GET args) REMOTE_HOST (domain name of client) REMOTE_ADDR (IP address of client) CONTENT_TYPE (for POST, type of data in message body, e.g., text/html)

CONTENT_LENGTH (length in bytes)

Page 30: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Even More CGI Environment Variables

In addition, the value of each header of type type received from the client is placed in environment variable HTTP_type Examples (any “-” is changed to “_”) :

HTTP_ACCEPT HTTP_HOST HTTP_USER_AGENT

Page 31: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content With GET Question: How does the server capture the content produced by the child? Answer: The child generates its output on stdout. Server uses dup2 to

redirect stdout to its connected socket. Notice that only the child knows the type and size of the content. Thus the child

(not the server) must generate the corresponding headers.

/* Make the response body */ sprintf(content, "Welcome to add.com: "); sprintf(content, "%sTHE Internet addition portal.\r\n<p>", content); sprintf(content, "%sThe answer is: %s\r\n<p>",

content, msg); sprintf(content, "%sThanks for visiting!\r\n", content); /* Generate the HTTP response */ printf("Content-length: %u\r\n", (unsigned) strlen(content)); printf("Content-type: text/html\r\n\r\n"); printf("%s", content);

From adder.c

Page 32: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Serving Dynamic Content With GET

HTTP request sent by client

HTTP response generated by the server

HTTP response generated bythe CGI program

$ telnet riely373.cdm.depaul.edu 8000Trying 140.192.39.11...Connected to riely373.cdm.depaul.edu.Escape character is '^]'.GET /cgi-bin/adder?4&7 HTTP/1.0

HTTP/1.0 200 OKServer: Tiny Web ServerContent-length: 97Content-type: text/html

Welcome to THE Internet addition portal.<p>The answer is: 4 + 7 = 11<p>Thanks for visiting!Connection closed by foreign host.$

Page 33: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Tiny Serving Dynamic Content

Fork child to execute CGI program Change stdout to be connection to client Execute CGI program with execve

/* Return first part of HTTP response */ sprintf(buf, "HTTP/1.0 200 OK\r\n"); Rio_writen(fd, buf, strlen(buf)); sprintf(buf, "Server: Tiny Web Server\r\n"); Rio_writen(fd, buf, strlen(buf)); if (Fork() == 0) { /* child */

/* Real server would set all CGI vars here */setenv("QUERY_STRING", cgiargs, 1); Dup2(fd, STDOUT_FILENO); /* Redirect stdout to client */Execve(filename, emptylist, environ);/* Run CGI prog */

} Wait(NULL); /* Parent waits for and reaps child */

From tiny.c

Page 34: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Proxies A proxy is an intermediary between a client and an origin

server. To the client, the proxy acts like a server. To the server, the proxy acts like a client.

Client ProxyOriginServer

1. Client request 2. Proxy request

3. Server response4. Proxy response

Page 35: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Why Proxies? Can perform useful functions as requests and responses pass

by Examples: Caching, logging, anonymization, filtering, transcoding

ClientA

Proxycache

OriginServer

Request foo.html

Request foo.html

foo.html

foo.html

ClientB

Request foo.html

foo.html

Fast inexpensive local network

Slower more expensiveglobal network

Page 36: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

For More Information Study the Tiny Web server described in your text

Tiny is a sequential Web server. Serves static and dynamic content to real browsers.

text files, HTML files, GIF and JPEG images. 220 lines of commented C code. Also comes with an implementation of the CGI script for the add.com

addition portal.

See the HTTP/1.1 standard: http://www.w3.org/Protocols/rfc2616/rfc2616.html

Page 37: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

2. Concurrency and threads

Page 38: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Client / ServerSession

Iterative Echo ServerClient Serversocket socket

bind

listen

rio_readlineb

rio_writenrio_readlineb

rio_writen

Connectionrequest

rio_readlineb

close

closeEOF

Await connectionrequest fromnext client

open_listenfd

open_clientfd

acceptconnect

Page 39: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Iterative Servers Iterative servers process one request at a time

client 1 server client 2

connect

accept connect

write read

call read

close

accept

write

read

close

Wait for Client 1

call read

write

ret read

writeret read

Page 40: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Creating Concurrent Flows Allow server to handle multiple clients simultaneously

1. Processes Kernel automatically interleaves multiple logical flows Each flow has its own private address space

2. Threads Kernel automatically interleaves multiple logical flows Each flow shares the same address space

3. I/O multiplexing with select() Programmer manually interleaves multiple logical flows All flows share the same address space Relies on lower-level system abstractions

Page 41: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Concurrent Servers: Multiple Processes Spawn separate process for each client

client 1 server client 2

call connectcall accept

call read

ret connectret accept

call connect

call fgetsforkchild 1

User goesout to lunch

Client 1 blockswaiting for user to type in data

call acceptret connect

ret accept call fgets

writefork

call read

child 2

write

call read

end readclose

close

...

Page 42: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Review: Iterative Echo Serverint main(int argc, char **argv) { int listenfd, connfd; int port = atoi(argv[1]); struct sockaddr_in clientaddr; int clientlen = sizeof(clientaddr);

listenfd = Open_listenfd(port); while (1) {

connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);echo(connfd);Close(connfd);

} exit(0);}

Accept a connection request Handle echo requests until client terminates

Page 43: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

int main(int argc, char **argv) { int listenfd, connfd; int port = atoi(argv[1]); struct sockaddr_in clientaddr; int clientlen=sizeof(clientaddr);

Signal(SIGCHLD, sigchld_handler); listenfd = Open_listenfd(port); while (1) {

connfd = Accept(listenfd, (SA *) &clientaddr, &clientlen);if (Fork() == 0) { Close(listenfd); /* Child closes its listening socket */ echo(connfd); /* Child services client */ Close(connfd); /* Child closes connection with client */ exit(0); /* Child exits */}Close(connfd); /* Parent closes connected socket (important!) */

}}

Process-Based Concurrent Server

Fork separate process for each client

Does not allow any communication between different client handlers

Page 44: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Process-Based Concurrent Server(cont)

void sigchld_handler(int sig) { while (waitpid(-1, 0, WNOHANG) > 0)

; return;}

Reap all zombie children

Page 45: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Process Execution Model

Each client handled by independent process No shared state between them Both parent & child have copies of listenfd and connfd

Parent must close connfd Child must close listenfd

Client 1Server

Process

Client 2Server

Process

ListeningServer

Process

Connection Requests

Client 1 data Client 2 data

Page 46: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Concurrent Server: accept Illustratedlistenfd(3)

Client1. Server blocks in accept, waiting for connection request on listening descriptor listenfd

clientfd

Server

listenfd(3)

Client

clientfd

Server2. Client makes connection request by calling and blocking in connect

Connectionrequest

listenfd(3)

Client

clientfd

Server3. Server returns connfd from accept. Forks child to handle client. Client returns from connect. Connection is now established between clientfd and connfd

ServerChild

connfd(4)

Page 47: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Implementation Must-dos With Process-Based Designs

Listening server process must reap zombie children to avoid fatal memory leak

Listening server process must close its copy of connfd Kernel keeps reference for each socket/open file After fork, refcnt(connfd) = 2 Connection will not be closed until refcnt(connfd) == 0

Page 48: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Pros and Cons of Process-Based Designs

+ Handle multiple connections concurrently + Clean sharing model

descriptors (no) file tables (yes) global variables (no)

+ Simple and straightforward – Additional overhead for process control – Nontrivial to share data between processes

Requires IPC (interprocess communication) mechanisms FIFO’s (named pipes), System V shared memory and semaphores

Page 49: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Approach #2: Multiple Threads

Very similar to approach #1 (multiple processes) but, with threads instead of processes

Page 50: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Traditional View of a Process Process = process context + code, data, and stack

shared libraries

run-time heap

0

read/write data

Program context: Data registers Condition codes Stack pointer (SP) Program counter (PC)Kernel context: VM structures Descriptor table brk pointer

Code, data, and stack

read-only code/data

stackSP

PC

brk

Process context

Page 51: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Alternate View of a Process Process = thread + code, data, and kernel context

shared libraries

run-time heap

0

read/write dataThread context:

Data registers Condition codes Stack pointer (SP) Program counter (PC)

Code and Data

read-only code/data

stackSP

PC

brk

Thread (main thread)

Kernel context: VM structures Descriptor table brk pointer

Page 52: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

A Process With Multiple Threads Multiple threads can be associated with a process

Each thread has its own logical control flow Each thread shares the same code, data, and kernel context

Share common virtual address space (inc. stacks) Each thread has its own thread id (TID)

shared libraries

run-time heap

0

read/write dataThread 1 context: Data registers Condition codes SP1 PC1

Shared code and data

read-only code/data

stack 1

Thread 1 (main thread)

Kernel context: VM structures Descriptor table brk pointer

Thread 2 context: Data registers Condition codes SP2 PC2

stack 2

Thread 2 (peer thread)

Page 53: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Logical View of Threads Threads associated with process form a pool of peers

Unlike processes which form a tree hierarchy

P0

P1

sh sh sh

foo

bar

T1

Process hierarchyThreads associated with process foo

T2T4

T5 T3

shared code, dataand kernel context

Page 54: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Thread Execution

Single Core Processor Simulate concurrency

by time slicing

Multi-Core Processor Can have true

concurrency

Time

Thread A Thread B Thread C Thread A Thread B Thread C

Run 3 threads on 2 cores

Page 55: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Threads vs. Processes How threads and processes are similar

Each has its own logical control flow Each can run concurrently with others (possibly on different cores) Each is context switched

How threads and processes are different Threads share code and some data

Processes (typically) do not Threads are somewhat less expensive than processes

Process control (creating and reaping) is twice as expensive as thread control

Linux numbers:– ~20K cycles to create and reap a process– ~10K cycles (or less) to create and reap a thread

Page 56: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Posix Threads (Pthreads) Interface Pthreads: Standard interface for ~60 functions that

manipulate threads from C programs Creating and reaping threads

pthread_create() pthread_join()

Determining your thread ID pthread_self()

Terminating threads pthread_cancel() pthread_exit() exit() [terminates all threads] , RET [terminates current thread]

Synchronizing access to shared variables pthread_mutex_init pthread_mutex_[un]lock pthread_cond_init pthread_cond_[timed]wait

Page 57: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

/* thread routine */void *thread(void *vargp) { printf("Hello, world!\n"); return NULL;}

The Pthreads "hello, world" Program/* * hello.c - Pthreads "hello, world" program */#include "csapp.h"

void *thread(void *vargp);

int main() { pthread_t tid;

Pthread_create(&tid, NULL, thread, NULL); Pthread_join(tid, NULL); exit(0);}

Thread attributes (usually NULL)

Thread arguments(void *p)

return value(void **p)

Page 58: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Execution of Threaded“hello, world”main thread

peer thread

return NULL;main thread waits for peer thread to terminate

exit() terminates

main thread and any peer threads

call Pthread_create()

call Pthread_join()

Pthread_join() returns

printf()

(peer threadterminates)

Pthread_create() returns

Page 59: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Thread-Based Concurrent Echo Serverint main(int argc, char **argv) { int port = atoi(argv[1]); struct sockaddr_in clientaddr; int clientlen=sizeof(clientaddr); pthread_t tid;

int listenfd = Open_listenfd(port); while (1) {

int *connfdp = Malloc(sizeof(int));*connfdp = Accept(listenfd,

(SA *) &clientaddr, &clientlen);Pthread_create(&tid, NULL, echo_thread, connfdp);

}}

Spawn new thread for each client Pass it copy of connection file descriptor Note use of Malloc()!

Without corresponding Free()

Page 60: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Thread-Based Concurrent Server (cont)/* thread routine */void *echo_thread(void *vargp) { int connfd = *((int *)vargp); Pthread_detach(pthread_self()); Free(vargp); echo(connfd); Close(connfd); return NULL;}

Run thread in “detached” mode Runs independently of other threads Reaped when it terminates

Free storage allocated to hold clientfd “Producer-Consumer” model

Page 61: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Threaded Execution Model

Multiple threads within single process Some state between them

File descriptors

Client 1Server

Client 2Server

ListeningServer

Connection Requests

Client 1 data Client 2 data

Page 62: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Potential Form of Unintended Sharing

main thread

peer1

while (1) {int connfd = Accept(listenfd, (SA *) &clientaddr, &clientlen);Pthread_create(&tid, NULL, echo_thread, (void *) &connfd);

}}

connfd

Main thread stack

vargp

Peer1 stack

vargp

Peer2 stackpeer2

connfd = connfd1

connfd = *vargpconnfd = connfd2

connfd = *vargp

Race!

Why would both copies of vargp point to same location?

Page 63: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Could this race occur?

int i;for (i = 0; i < 100; i++) { Pthread_create(&tid, NULL, thread, &i);}

Race Test If no race, then each thread would get different value of i Set of saved values would consist of one copy each of 0 through 99.

Main

void *thread(void *vargp) { int i = *((int *)vargp); Pthread_detach(pthread_self()); save_value(i); return NULL;}

Thread

Page 64: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Experimental Results

The race can really happen!

No Race

Multicore server

0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 990

1

2

0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 990

2

4

6

8

10

12

14

Single core laptop

0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 990

1

2

3

Page 65: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Issues With Thread-Based Servers Must run “detached” to avoid memory leak.

At any point in time, a thread is either joinable or detached. Joinable thread can be reaped and killed by other threads.

must be reaped (with pthread_join) to free memory resources. Detached thread cannot be reaped or killed by other threads.

resources are automatically reaped on termination. Default state is joinable.

use pthread_detach(pthread_self()) to make detached. Must be careful to avoid unintended sharing.

For example, passing pointer to main thread’s stack Pthread_create(&tid, NULL, thread, (void *)&connfd);

All functions called by a thread must be thread-safe Stay tuned

Page 66: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Pros and Cons of Thread-Based Designs

+ Easy to share data structures between threads e.g., logging information, file cache.

+ Threads are more efficient than processes.

– Unintentional sharing can introduce subtle and hard-to-reproduce errors! The ease with which data can be shared is both the greatest strength

and the greatest weakness of threads. Hard to know which data shared & which private Hard to detect by testing

Probability of bad race outcome very low But nonzero!

Future lectures

Page 67: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Event-Based Concurrent Servers Using I/O Multiplexing

Use library functions to construct scheduler within single process

Server maintains set of active connections Array of connfd’s

Repeat: Determine which connections have pending inputs If listenfd has input, then accept connection

Add new connfd to array Service all connfd’s with pending inputs

Details in book

Page 68: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

I/O Multiplexed Event Processing

10

clientfd

7

4

-1

-1

12

5

-1

-1

-1

0

1

2

3

4

5

6

7

8

9

Active

Inactive

Active

Never Used

listenfd = 3

10

clientfd

7

4

-1

-1

12

5

-1

-1

-1

listenfd = 3

Active Descriptors Pending Inputs

Read

Page 69: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Pros and Cons of I/O Multiplexing

+ One logical control flow. + Can single-step with a debugger. + No process or thread control overhead.

Design of choice for high-performance Web servers and search engines.

– Significantly more complex to code than process- or thread-based designs.

– Hard to provide fine-grained concurrency E.g., our example will hang up with partial lines.

– Cannot take advantage of multi-core Single thread of control

Page 70: 1. Web Services 2. Concurrency and threads. Web History 1989:  Tim Berners-Lee (CERN) writes internal proposal to develop a distributed hypertext system.

Approaches to Concurrency

Processes Hard to share resources: Easy to avoid unintended sharing High overhead in adding/removing clients

Threads Easy to share resources: Perhaps too easy Medium overhead Not much control over scheduling policies Difficult to debug

Event orderings not repeatable I/O Multiplexing

Tedious and low level Total control over scheduling Very low overhead Cannot create as fine grained a level of concurrency Does not make use of multi-core