Web Server Architecture Web Server Architecture Complex Helpful
Web Server Architecture
Web Server Architecture • Complex – Helpful to consider best design practices • Items to consider – Response Time • Use concurrency – Features • HTTP/1. 1 • CGI
Web Server Architecture use dup 2 to redirect stdin and stdout back to the web server Client http Web Server stdin stdout CGI program
Web Server Architecture Main Thread for(j=0; j<nthread; pthread_create() Con nec t() while(1) newsock = accept() en. Q(newsock) Client Connection Queue Thread Pool while(1) sock = de. Q() recv() process while(1) sock = de. Q() recv() process send() close(sock) read() process send() close(sock) write() close(sock)
Web Server Architecture • Minimize Overhead – Launch threads that stay around – Use semaphores to eliminate busy wait • Be Careful with shared data structures – Connection Queue • Producer - main thread • Consumers - connection handling threads
Web Server Architecture #include … Queue connection. Q; main() { // Use signal handlers to shut down nicely Set. Up. Signal. Handlers() void *Handle. Conn(void *args) { while(we are still running) { // This call should block until I have a connection // You will need producer-consumer code sock = connection. Q. de. Q(); Set. Up. Socket() recv(sock, message…) for(j = 0; j < nthreads; j++) pthread_create(thread[j], Handle. Conn, args) process. URL() if (cgi) Do. CGI() else { read file send(sock, response…) close(sock) } pthread_create(logthread, Log. Writer, args) for(; ; ) { sock = accept(…) connection. Q. en. Q(sock) } }
Shared Data Structures • Queue of socket connections • Strategy – Write a template queue that inherits from the STL queue class – Override the enqueue and dequeue methods init(Empty. Sem, QSIZE); init(Present. Sem, 0); init(mutex, 1); template <class Elem> void My. Queue<Elem>: : enqueue(const Elem &Item) { template <class Elem> wait(Empty. Sem) Elem My. Queue<Elem>: : dequeue(void) wait(mutex) { super. enqueue(Item) wait(Present. Sem) post(mutex) wait(mutex) post(Present. Sem) super. dequeue(Item) } signal(mutex) signal(Empty. Sem) }
Sample Exchange GET /path/file. html HTTP/1. 1 Host: www. host 1. com: 80 [blank line here] HTTP/1. 0 200 OK Date: Fri, 31 Dec 1999 23: 59 GMT Content-Type: text/html Content-Length: 1354 <html> <body> <h 1>Happy New Year!</h 1> (more fiile contents). . . </body> </html>
Web Request Processing • Receive the request GET /CS 360 HTTP/1. 1 Host: star. cs. byu. edu • Process the URL – Append URL to Document. Root – Use stat to determine if file exists or if it is a directory • Send Response HTTP/1. 1 200 OK Content-type: text/html, image/jpg or other mime type Content-length: #bytes as reported by stat Binary Data (Write a loop that reads a buffer full of data and writes it to the socket until EOF)
- Slides: 9