Skip to content

Instantly share code, notes, and snippets.

@sitano
Last active August 29, 2015 14:25
Show Gist options
  • Save sitano/12fb4a9af61015918e51 to your computer and use it in GitHub Desktop.
Save sitano/12fb4a9af61015918e51 to your computer and use it in GitHub Desktop.
openrusty nginx lua http traffic replication with multiple capture example
worker_processes 2;
events {
worker_connections 1024;
}
http {
access_log /dev/stderr combined;
keepalive_timeout 65;
resolver 8.8.8.8;
lua_package_path "$prefix/lualib/?.lua;;";
lua_shared_dict locks 1M;
lua_shared_dict cache 10M;
upstream slave1 {
server server1.com fail_timeout=10;
keepalive 32;
}
upstream slave2 {
server server2.com fail_timeout=10;
keepalive 32;
}
# see https://github.com/openresty/lua-resty-core
init_by_lua '
require "resty.core"
';
server {
listen 8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for;
location /gateway_slave1 {
internal;
rewrite /gateway_slave1(.*) $1 break;
proxy_pass http://slave1;
client_max_body_size 10m;
client_body_buffer_size 1m;
proxy_buffer_size 32k;
proxy_buffers 10 128k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 10m;
}
location /gateway_slave2 {
internal;
rewrite /gateway_slave2(.*) $1 break;
proxy_pass http://slave2;
client_max_body_size 10m;
client_body_buffer_size 1m;
proxy_buffer_size 32k;
proxy_buffers 10 128k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 10m;
}
location ~* ^/(A|B)/Insert {
default_type text/plain;
content_by_lua '
ngx.req.read_body()
local upstream = require "ngx.upstream"
local body = ngx.req.get_body_data()
local reqs = {}
for _, u in ipairs(upstream.get_upstreams()) do
if string.sub(u,1,5) == "slave" then
table.insert(reqs, { "/gateway_"..u..ngx.var.uri, { method = ngx.HTTP_POST, args = ngx.var.args, always_forward_body = true } })
end
end
if #reqs == 0 then
ngx.log(ngx.ERR, "No /Insert upstreams found on request ", ngx.var.request_uri)
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
return
end
local bad = 0
local good = 0
local resps = { ngx.location.capture_multi(reqs) }
for i, r in ipairs(resps) do
if r.status ~= 200 then
ngx.log(ngx.ERR, "Upstream ", reqs[i][1], " failed to make a POST to ", ngx.var.uri, ", status = ", r.status, ", resp = ", r.body)
bad = bad + 1
else
good = good + 1
end
end
if good > 0 then
ngx.say("OK")
ngx.exit(ngx.HTTP_OK)
else
ngx.say("All upstreams failed")
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment