SlideShare a Scribd company logo
Some socket
programming
Openresty later
@ntavish
● http://beej.us/guide/bgnet/ Beej’s guide to network programming
● man 7 socket, man 7 ip, man 2 socket
● kernel(linux/*bsd/windows etc.) provides socket interface for IPC
○ same computer, or on different one
● Kernel handles networking stack
● We’ll only see a bit of TCP and UDP as seen by application
Resources:
TCP / UDP
● SOCK_STREAM & SOCK_DGRAM are two types of internet sockets
(AF_INET/AF_INET6)
● UDP is connectionless, you specify length and set destination address
○ No guarantee of delivery
○ No guarantee of being in order of sending
○ Used when speed is most important
● TCP is called ‘connection-oriented’, client connects to server
○ Is reliable
○ Has byte stream
Example
● Netcat
○ Like ‘cat’ but can connect/listen to TCP/UDP
● nc -l 7000 # listen to TCP port 7000 on machine
●
● nc localhost 7000 # connects to tcp port 7000 on 127.0.0.1
Sample python code
HTTP with nc
sent
TCP server socket handling
● A lot of info on http://www.kegel.com/c10k.html
● Server opens, bind()s, and listen()s to socket
● Server can now do
○ blocking accept(), which gives an fd for accepted socket
■ Not very useful for a single process server
○ Non-blocking accept()
■ On accepting it will get an fd for accepted socket, which it can add to queue
■ gathers multiple fd’s, it can use select/poll/epoll on queue of fd’s
● Architectures in some real web servers
○ Multiple processes(or single), each handling one req. at a time (Apache)
○ Multiple processes(or single), each has multiple threads, threads handle a req. (Apache)
○ Multiple processes(or single), all requests handled in a single ‘event loop’ without blocking
socket system calls (nginx)
Further reading
● C10K challenge http://www.kegel.com/c10k.html
● Architecture of open source applications, nginx
http://aosabook.org/en/nginx.html
● Digitalocean blog: Apache vs nginx, practical considerations
https://www.digitalocean.com/community/tutorials/apache-vs-nginx-practi
cal-considerations
● http://pl.atyp.us/content/tech/servers.html
Nginx
● Created to address C10k problem/challenge
○ High concurrency
○ low/predictable memory usage
○ event-driven architecture
Nginx architecture
● See infographic
https://www.nginx.com/resources/library/infographic-inside-nginx/
● Master process
○ reads configuration, binds sockets, forks worker processes
● Worker process
○ Event-driven state-machine/scheduler
○ As any socket event occurs, the state machine progresses for that particular socket/context
Lua
Lua is a powerful, efficient, lightweight, embeddable scripting language.
Where?
● Lots of video games, mediawiki, redis, netbsd kernel
Luajit
● a very high performance JIT compiler for Lua (compared to lua.org one)
io.write("Hello world, from ",_VERSION,"!n")
Openresty
Openresty is standard nginx core + luajit bundled with (non-blocking) lua libraries
and 3rd party nginx modules
● Created at taobao.com, and also supported by cloudflare
● lua-nginx-module embeds lua VM in event loop
● Aim is to run web application, gateway, etc. completely in nginx process
● Nginx asynchronous event handling plus lua allows
○ Synchronous code, but non-blocking, readable code
○ Non-blocking for the nginx process, but without callback hell unlike Node.js
Openresty cont.
● All nginx qualities (high concurrency low memory etc.) with powerful
scripting
● Api can:
○ Access HTTP request
○ Generate response (maybe by mixing/matching content from various external storage,
sub-requests etc.)
○ Use external services like databases, upstream servers, http requests without blocking
Nginx request phases
Hooks for various phases of request are exposed:
● rewrite_by_lua
● access_by_lua - ex. Usage: authentication via cookies/headers
● content_by_lua - http response
● log_by_lua
Details at https://github.com/openresty/lua-nginx-module
location / {
access_by_lua_block {
local res = ngx.location.capture("/auth")
if res.status == ngx.HTTP_OK then
return
end
if res.status == ngx.HTTP_FORBIDDEN then
ngx.exit(res.status)
end
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
}
}
Example of access control with lua
● If /auth location does not return ‘200’, access denied
Modifying requests / response
local headers = ngx.req.get_headers()
local body = ngx.req.read_body()
local method = ngx.req.get_method
local querystring_params = ngx.req.get_uri_args()
local post_params = ngx.req.get_post_args()
All the above can be modified with set_* equivalents,
before passing the request to ngx.location.capture(), which can be proxy location
res = ngx.location.capture(‘/proxy’)
Returns a Lua table with- res.status, res.header, res.body, and res.truncated. ngx.say(res.body) to forward this response.
Non-blocking redis connection (example)
local redis = require "resty.redis"
-- connect to redis
local red = redis:new()
red:set_timeout(10)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.log(ngx.STDERR, "failed to connect to redis: " .. tostring(err))
return
end
local res, err = red:publish("all", "HI!")
if not res then
ngx.log(ngx.STDERR, "failed to publish: " .. tostring(err))
return
End
Other lua-resty-* modules
● lua-resty-redis
● lua-resty-mysql
● lua-resty-memcached
● lua-resty-string
● lua-resty-websocket etc.
Nginx stream module
stream-lua-nginx-module embeds lua into nginx stream module.
● Implement arbitrary TCP/UDP server/clients/protocols with lua and nginx
core
example
content_by_lua_block {
local sock = assert(ngx.req.socket(true)) -- get request’s socket
local data = sock:receive() -- read a line from downstream
if data == "thunder!" then
ngx.say("flash!") -- output data
else
ngx.say("boom!")
end
ngx.say("the end...")
}
Ad

Recommended

IT Operations for Web Developers
IT Operations for Web Developers
Mahmoud Said
 
Node.js
Node.js
EU Edge
 
WebSockets with PHP: Mission impossible
WebSockets with PHP: Mission impossible
Yoan-Alexander Grigorov
 
OSDC 2015: Stephen Benjamin | Foreman in Your Data Center
OSDC 2015: Stephen Benjamin | Foreman in Your Data Center
NETWAYS
 
Ethernet Shield
Ethernet Shield
Tinker
 
HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009
jarfield
 
KubeCon EU 2019 - P2P Docker Image Distribution in Hybrid Cloud Environment w...
KubeCon EU 2019 - P2P Docker Image Distribution in Hybrid Cloud Environment w...
Yiran Wang
 
CloudStack In Production
CloudStack In Production
Clayton Weise
 
H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
innov-acts-ltd
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJS
Israel Gutiérrez
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011
Gianluca Padovani
 
Campus days 2014 owin
Campus days 2014 owin
Christian Horsdal
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with Netty
Ersin Er
 
DSSH: Innovation in SSH
DSSH: Innovation in SSH
Juraj Bednar
 
Dssh @ Confidence, Prague 2010
Dssh @ Confidence, Prague 2010
Juraj Bednar
 
Network concepts
Network concepts
Prajwal Panchmahalkar
 
Inside debian-installer
Inside debian-installer
Wouter Verhelst
 
My journey from PHP to Node.js
My journey from PHP to Node.js
Valentin Lup
 
Practical Glusto Example
Practical Glusto Example
Gluster.org
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Codemotion
 
Play Framework
Play Framework
Harinath Krishnamoorthy
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
Kazuho Oku
 
Openstack overview thomas-goirand
Openstack overview thomas-goirand
OpenCity Community
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
Christian Horsdal
 
PSR-3 logs using Monolog and Graylog
PSR-3 logs using Monolog and Graylog
OCoderFest
 
Coredns nodecache - A highly-available Node-cache DNS server
Coredns nodecache - A highly-available Node-cache DNS server
Yann Hamon
 
RPC in Smalltalk
RPC in Smalltalk
ESUG
 
Socket Programming using Java
Socket Programming using Java
Rahul Hada
 
Lua tech talk
Lua tech talk
Locaweb
 
Introduction to Lua Luajit Openresty Luvit
Introduction to Lua Luajit Openresty Luvit
Lionel Duboeuf
 

More Related Content

What's hot (20)

H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
innov-acts-ltd
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJS
Israel Gutiérrez
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011
Gianluca Padovani
 
Campus days 2014 owin
Campus days 2014 owin
Christian Horsdal
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with Netty
Ersin Er
 
DSSH: Innovation in SSH
DSSH: Innovation in SSH
Juraj Bednar
 
Dssh @ Confidence, Prague 2010
Dssh @ Confidence, Prague 2010
Juraj Bednar
 
Network concepts
Network concepts
Prajwal Panchmahalkar
 
Inside debian-installer
Inside debian-installer
Wouter Verhelst
 
My journey from PHP to Node.js
My journey from PHP to Node.js
Valentin Lup
 
Practical Glusto Example
Practical Glusto Example
Gluster.org
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Codemotion
 
Play Framework
Play Framework
Harinath Krishnamoorthy
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
Kazuho Oku
 
Openstack overview thomas-goirand
Openstack overview thomas-goirand
OpenCity Community
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
Christian Horsdal
 
PSR-3 logs using Monolog and Graylog
PSR-3 logs using Monolog and Graylog
OCoderFest
 
Coredns nodecache - A highly-available Node-cache DNS server
Coredns nodecache - A highly-available Node-cache DNS server
Yann Hamon
 
RPC in Smalltalk
RPC in Smalltalk
ESUG
 
Socket Programming using Java
Socket Programming using Java
Rahul Hada
 
H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
innov-acts-ltd
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJS
Israel Gutiérrez
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with Netty
Ersin Er
 
DSSH: Innovation in SSH
DSSH: Innovation in SSH
Juraj Bednar
 
Dssh @ Confidence, Prague 2010
Dssh @ Confidence, Prague 2010
Juraj Bednar
 
My journey from PHP to Node.js
My journey from PHP to Node.js
Valentin Lup
 
Practical Glusto Example
Practical Glusto Example
Gluster.org
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Codemotion
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
Kazuho Oku
 
Openstack overview thomas-goirand
Openstack overview thomas-goirand
OpenCity Community
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
Christian Horsdal
 
PSR-3 logs using Monolog and Graylog
PSR-3 logs using Monolog and Graylog
OCoderFest
 
Coredns nodecache - A highly-available Node-cache DNS server
Coredns nodecache - A highly-available Node-cache DNS server
Yann Hamon
 
RPC in Smalltalk
RPC in Smalltalk
ESUG
 
Socket Programming using Java
Socket Programming using Java
Rahul Hada
 

Similar to Socket programming, and openresty (20)

Lua tech talk
Lua tech talk
Locaweb
 
Introduction to Lua Luajit Openresty Luvit
Introduction to Lua Luajit Openresty Luvit
Lionel Duboeuf
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
Tony Fabeen
 
Devinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
Nginx - Tips and Tricks.
Nginx - Tips and Tricks.
Harish S
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUN
Cong Zhang
 
Alternative Infrastucture
Alternative Infrastucture
Marc Seeger
 
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
PROIDEA
 
Nginx dhruba mandal
Nginx dhruba mandal
Dhrubaji Mandal ♛
 
Nginx
Nginx
Dhrubaji Mandal ♛
 
Apache httpd 2.4: The Cloud Killer App
Apache httpd 2.4: The Cloud Killer App
Jim Jagielski
 
Session: A Reference Architecture for Running Modern APIs with NGINX Unit and...
Session: A Reference Architecture for Running Modern APIs with NGINX Unit and...
NGINX, Inc.
 
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger
 
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
Ortus Solutions, Corp
 
Web servers presentacion
Web servers presentacion
Kiwi Science
 
Nginx-lua
Nginx-lua
Дэв Тим Афс
 
NGINX 101 - now with more Docker
NGINX 101 - now with more Docker
sarahnovotny
 
NGINX 101 - now with more Docker
NGINX 101 - now with more Docker
Sarah Novotny
 
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
Amit Aggarwal
 
PHP projects beyond the LAMP stack
PHP projects beyond the LAMP stack
Codemotion
 
Lua tech talk
Lua tech talk
Locaweb
 
Introduction to Lua Luajit Openresty Luvit
Introduction to Lua Luajit Openresty Luvit
Lionel Duboeuf
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
Tony Fabeen
 
Devinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
Nginx - Tips and Tricks.
Nginx - Tips and Tricks.
Harish S
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUN
Cong Zhang
 
Alternative Infrastucture
Alternative Infrastucture
Marc Seeger
 
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
PROIDEA
 
Apache httpd 2.4: The Cloud Killer App
Apache httpd 2.4: The Cloud Killer App
Jim Jagielski
 
Session: A Reference Architecture for Running Modern APIs with NGINX Unit and...
Session: A Reference Architecture for Running Modern APIs with NGINX Unit and...
NGINX, Inc.
 
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger
 
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
Ortus Solutions, Corp
 
Web servers presentacion
Web servers presentacion
Kiwi Science
 
NGINX 101 - now with more Docker
NGINX 101 - now with more Docker
sarahnovotny
 
NGINX 101 - now with more Docker
NGINX 101 - now with more Docker
Sarah Novotny
 
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
Nginx A High Performance Load Balancer, Web Server & Reverse Proxy
Amit Aggarwal
 
PHP projects beyond the LAMP stack
PHP projects beyond the LAMP stack
Codemotion
 
Ad

More from Tavish Naruka (6)

Makefiles
Makefiles
Tavish Naruka
 
Zephyr RTOS workshop
Zephyr RTOS workshop
Tavish Naruka
 
a pcb badge
a pcb badge
Tavish Naruka
 
Internet of things - with routers
Internet of things - with routers
Tavish Naruka
 
Embedded platform choices
Embedded platform choices
Tavish Naruka
 
Hardware hacking
Hardware hacking
Tavish Naruka
 
Ad

Recently uploaded (20)

How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
Automated Testing and Safety Analysis of Deep Neural Networks
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 

Socket programming, and openresty

  • 2. ● http://beej.us/guide/bgnet/ Beej’s guide to network programming ● man 7 socket, man 7 ip, man 2 socket ● kernel(linux/*bsd/windows etc.) provides socket interface for IPC ○ same computer, or on different one ● Kernel handles networking stack ● We’ll only see a bit of TCP and UDP as seen by application Resources:
  • 3. TCP / UDP ● SOCK_STREAM & SOCK_DGRAM are two types of internet sockets (AF_INET/AF_INET6) ● UDP is connectionless, you specify length and set destination address ○ No guarantee of delivery ○ No guarantee of being in order of sending ○ Used when speed is most important ● TCP is called ‘connection-oriented’, client connects to server ○ Is reliable ○ Has byte stream
  • 4. Example ● Netcat ○ Like ‘cat’ but can connect/listen to TCP/UDP ● nc -l 7000 # listen to TCP port 7000 on machine ● ● nc localhost 7000 # connects to tcp port 7000 on 127.0.0.1
  • 7. TCP server socket handling ● A lot of info on http://www.kegel.com/c10k.html ● Server opens, bind()s, and listen()s to socket ● Server can now do ○ blocking accept(), which gives an fd for accepted socket ■ Not very useful for a single process server ○ Non-blocking accept() ■ On accepting it will get an fd for accepted socket, which it can add to queue ■ gathers multiple fd’s, it can use select/poll/epoll on queue of fd’s ● Architectures in some real web servers ○ Multiple processes(or single), each handling one req. at a time (Apache) ○ Multiple processes(or single), each has multiple threads, threads handle a req. (Apache) ○ Multiple processes(or single), all requests handled in a single ‘event loop’ without blocking socket system calls (nginx)
  • 8. Further reading ● C10K challenge http://www.kegel.com/c10k.html ● Architecture of open source applications, nginx http://aosabook.org/en/nginx.html ● Digitalocean blog: Apache vs nginx, practical considerations https://www.digitalocean.com/community/tutorials/apache-vs-nginx-practi cal-considerations ● http://pl.atyp.us/content/tech/servers.html
  • 9. Nginx ● Created to address C10k problem/challenge ○ High concurrency ○ low/predictable memory usage ○ event-driven architecture
  • 10. Nginx architecture ● See infographic https://www.nginx.com/resources/library/infographic-inside-nginx/ ● Master process ○ reads configuration, binds sockets, forks worker processes ● Worker process ○ Event-driven state-machine/scheduler ○ As any socket event occurs, the state machine progresses for that particular socket/context
  • 11. Lua Lua is a powerful, efficient, lightweight, embeddable scripting language. Where? ● Lots of video games, mediawiki, redis, netbsd kernel Luajit ● a very high performance JIT compiler for Lua (compared to lua.org one) io.write("Hello world, from ",_VERSION,"!n")
  • 12. Openresty Openresty is standard nginx core + luajit bundled with (non-blocking) lua libraries and 3rd party nginx modules ● Created at taobao.com, and also supported by cloudflare ● lua-nginx-module embeds lua VM in event loop ● Aim is to run web application, gateway, etc. completely in nginx process ● Nginx asynchronous event handling plus lua allows ○ Synchronous code, but non-blocking, readable code ○ Non-blocking for the nginx process, but without callback hell unlike Node.js
  • 13. Openresty cont. ● All nginx qualities (high concurrency low memory etc.) with powerful scripting ● Api can: ○ Access HTTP request ○ Generate response (maybe by mixing/matching content from various external storage, sub-requests etc.) ○ Use external services like databases, upstream servers, http requests without blocking
  • 14. Nginx request phases Hooks for various phases of request are exposed: ● rewrite_by_lua ● access_by_lua - ex. Usage: authentication via cookies/headers ● content_by_lua - http response ● log_by_lua Details at https://github.com/openresty/lua-nginx-module
  • 15. location / { access_by_lua_block { local res = ngx.location.capture("/auth") if res.status == ngx.HTTP_OK then return end if res.status == ngx.HTTP_FORBIDDEN then ngx.exit(res.status) end ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) } } Example of access control with lua ● If /auth location does not return ‘200’, access denied
  • 16. Modifying requests / response local headers = ngx.req.get_headers() local body = ngx.req.read_body() local method = ngx.req.get_method local querystring_params = ngx.req.get_uri_args() local post_params = ngx.req.get_post_args() All the above can be modified with set_* equivalents, before passing the request to ngx.location.capture(), which can be proxy location res = ngx.location.capture(‘/proxy’) Returns a Lua table with- res.status, res.header, res.body, and res.truncated. ngx.say(res.body) to forward this response.
  • 17. Non-blocking redis connection (example) local redis = require "resty.redis" -- connect to redis local red = redis:new() red:set_timeout(10) local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.log(ngx.STDERR, "failed to connect to redis: " .. tostring(err)) return end local res, err = red:publish("all", "HI!") if not res then ngx.log(ngx.STDERR, "failed to publish: " .. tostring(err)) return End
  • 18. Other lua-resty-* modules ● lua-resty-redis ● lua-resty-mysql ● lua-resty-memcached ● lua-resty-string ● lua-resty-websocket etc.
  • 19. Nginx stream module stream-lua-nginx-module embeds lua into nginx stream module. ● Implement arbitrary TCP/UDP server/clients/protocols with lua and nginx core
  • 20. example content_by_lua_block { local sock = assert(ngx.req.socket(true)) -- get request’s socket local data = sock:receive() -- read a line from downstream if data == "thunder!" then ngx.say("flash!") -- output data else ngx.say("boom!") end ngx.say("the end...") }