Documente Academic
Documente Profesional
Documente Cultură
programming
Openresty later
@ntavish
Resources:
●
● 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
● 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
Where?
Luajit
● a very high performance JIT compiler for Lua (compared to lua.org one)
Openresty is standard nginx core + luajit bundled with (non-blocking) lua libraries
and 3rd party nginx modules
● 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
● 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
Example of access control with lua
location / {
access_by_lua_block {
local res = ngx.location.capture("/auth")
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
}
}
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)
● lua-resty-redis
● lua-resty-mysql
● lua-resty-memcached
● lua-resty-string
● lua-resty-websocket etc.
Nginx stream module
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...")
}