SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
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...")
}

Contenu connexe

Tendances

HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleHTTP::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-goirandOpenstack overview thomas-goirand
Openstack overview thomas-goirand
OpenCity Community
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
Christian Horsdal
 
Socket Programming using Java
Socket Programming using JavaSocket Programming using Java
Socket Programming using Java
Rahul Hada
 

Tendances (20)

H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
H2020 finsec-ibm- aidan-shribman-finsec-skydive 260820
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJSJugando con websockets en nodeJS
Jugando con websockets en nodeJS
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
 
Campus days 2014 owin
Campus days 2014 owinCampus days 2014 owin
Campus days 2014 owin
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyAsynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with Netty
 
DSSH: Innovation in SSH
DSSH: Innovation in SSHDSSH: Innovation in SSH
DSSH: Innovation in SSH
 
Dssh @ Confidence, Prague 2010
Dssh @ Confidence, Prague 2010Dssh @ Confidence, Prague 2010
Dssh @ Confidence, Prague 2010
 
Network concepts
Network conceptsNetwork concepts
Network concepts
 
Inside debian-installer
Inside debian-installerInside debian-installer
Inside debian-installer
 
My journey from PHP to Node.js
My journey from PHP to Node.jsMy journey from PHP to Node.js
My journey from PHP to Node.js
 
Practical Glusto Example
Practical Glusto ExamplePractical Glusto Example
Practical Glusto Example
 
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
Meetup RomaJS - introduzione interattiva a Node.js - Luca Lanziani - Codemoti...
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleHTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
 
Openstack overview thomas-goirand
Openstack overview thomas-goirandOpenstack overview thomas-goirand
Openstack overview thomas-goirand
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
 
PSR-3 logs using Monolog and Graylog
PSR-3 logs using Monolog and Graylog PSR-3 logs using Monolog and Graylog
PSR-3 logs using Monolog and Graylog
 
Coredns nodecache - A highly-available Node-cache DNS server
Coredns nodecache - A highly-available Node-cache DNS serverCoredns nodecache - A highly-available Node-cache DNS server
Coredns nodecache - A highly-available Node-cache DNS server
 
RPC in Smalltalk
 RPC in Smalltalk RPC in Smalltalk
RPC in Smalltalk
 
Socket Programming using Java
Socket Programming using JavaSocket Programming using Java
Socket Programming using Java
 

Similaire à Socket programming, and openresty

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 

Similaire à Socket programming, and openresty (20)

Multiple django applications on a single server with nginx
Multiple django applications on a single server with nginxMultiple django applications on a single server with nginx
Multiple django applications on a single server with nginx
 
Monkey Server
Monkey ServerMonkey Server
Monkey Server
 
03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
 
BaseX user-group-talk XML Prague 2013
BaseX user-group-talk XML Prague 2013BaseX user-group-talk XML Prague 2013
BaseX user-group-talk XML Prague 2013
 
Node.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scaleNode.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scale
 
Go 1.8 'new' networking features
Go 1.8 'new' networking featuresGo 1.8 'new' networking features
Go 1.8 'new' networking features
 
Varnish - PLNOG 4
Varnish - PLNOG 4Varnish - PLNOG 4
Varnish - PLNOG 4
 
Elasticsearch on Kubernetes
Elasticsearch on KubernetesElasticsearch on Kubernetes
Elasticsearch on Kubernetes
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
Load testing in Zonky with Gatling
Load testing in Zonky with GatlingLoad testing in Zonky with Gatling
Load testing in Zonky with Gatling
 
"Swoole: double troubles in c", Alexandr Vronskiy
"Swoole: double troubles in c", Alexandr Vronskiy"Swoole: double troubles in c", Alexandr Vronskiy
"Swoole: double troubles in c", Alexandr Vronskiy
 
0507 057 01 98 * Adana Klima Servisleri
0507 057 01 98 * Adana Klima Servisleri0507 057 01 98 * Adana Klima Servisleri
0507 057 01 98 * Adana Klima Servisleri
 
Shall we play a game
Shall we play a gameShall we play a game
Shall we play a game
 
Shall we play a game?
Shall we play a game?Shall we play a game?
Shall we play a game?
 
Using NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content CacheUsing NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content Cache
 
NGINX Installation and Tuning
NGINX Installation and TuningNGINX Installation and Tuning
NGINX Installation and Tuning
 
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
 
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
ITB2019 NGINX Overview and Technical Aspects - Kevin JonesITB2019 NGINX Overview and Technical Aspects - Kevin Jones
ITB2019 NGINX Overview and Technical Aspects - Kevin Jones
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Kubernetes @ Squarespace: Kubernetes in the Datacenter
Kubernetes @ Squarespace: Kubernetes in the DatacenterKubernetes @ Squarespace: Kubernetes in the Datacenter
Kubernetes @ Squarespace: Kubernetes in the Datacenter
 

Plus de Tavish Naruka (6)

Makefiles
MakefilesMakefiles
Makefiles
 
Zephyr RTOS workshop
Zephyr RTOS workshopZephyr RTOS workshop
Zephyr RTOS workshop
 
a pcb badge
a pcb badgea pcb badge
a pcb badge
 
Internet of things - with routers
Internet of things - with routersInternet of things - with routers
Internet of things - with routers
 
Embedded platform choices
Embedded platform choicesEmbedded platform choices
Embedded platform choices
 
Hardware hacking
Hardware hackingHardware hacking
Hardware hacking
 

Dernier

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

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...") }