Skip to content

Instantly share code, notes, and snippets.

@davidbirdsong
Created October 17, 2017 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbirdsong/8efec8efa44b7a86dac8fcaa48263ca9 to your computer and use it in GitHub Desktop.
Save davidbirdsong/8efec8efa44b7a86dac8fcaa48263ca9 to your computer and use it in GitHub Desktop.
replicate endpoint
local http = require('ext.resty.http')
local c = require('imgix.hwy.common')
local cjson = require('cjson')
local _ngx = ngx
if _ngx.req.get_method() ~= 'REPLICATE' then
_ngx.status = _ngx.HTTP_NOT_ALLOWED
local e = string.format('unsupported method: %s', _ngx.req.get_method())
_ngx.say(e)
_ngx.log(_ngx.ERR, e)
_ngx.exit(_ngx.HTTP_OK)
end
local args = ngx.req.get_uri_args()
local must_args = {
'fidid', 'sdev', 'ddev', 'dhostip', 'dport', 'clen'
}
for _, x in ipairs(must_args) do
if not args[x] or args[x] == "" then
_ngx.status = _ngx.HTTP_BAD_REQUEST
local e = string.format('missing required query paramater: %s, all params: [%s]', x, cjson.encode(must_args))
_ngx.say(e)
_ngx.log(_ngx.ERR, e)
_ngx.exit(_ngx.HTTP_OK)
end
end
local fid, sdev, ddev = tonumber(args.fidid), tonumber(args.sdev), tonumber(args.ddev)
local filepath = get_fid_url(sdev, fid)
local httpc = http.new()
local req_headers = _ngx.req.get_headers()
local uri = string.format('http://%s:%s%s', args.dhostip, args.dport,
c.get_fid_url(ddev, fid))
local httpfilec = http.new()
local ok, err = httpfilec:connect('127.0.0.1', 8091)
if not ok then
_ngx.log(_ngx.ERR, err)
_ngx.status = _ngx.HTTP_BAD_GATEWAY
_ngx.exit(_ngx.HTTP_BAD_GATEWAY)
end
local res, err = httpfilec:request(
{
method = 'GET',
version = 1.0,
path = filepath,
}
)
if err then
_ngx.log(_ngx.ERR, err)
_ngx.status = _ngx.HTTP_INTERNAL_SERVER_ERROR
_ngx.exit(_ngx.HTTP_INTERNAL_SERVER_ERROR)
end
if res.status ~= _ngx.HTTP_OK then
_ngx.log(_ngx.ERR, err)
_ngx.status = res.status
_ngx.exit(res.status)
end
local body = res.body_reader
res, err = httpc:request_uri(uri, {
method = "PUT",
body = body,
headers = {
['Content-MD5'] = req_headers['Content-MD5'],
['Content-Length'] = args.clen,
}
})
if not res then
_ngx.status = _ngx.HTTP_BAD_GATEWAY
_ngx.log(_ngx.ERR, 'FAILED REPLICATE ', err)
_ngx.say(err)
_ngx.exit(_ngx.HTTP_OK)
return
end
local b, err = res:read_body()
_ngx.status = res.status
for k,v in pairs(res.headers) do _ngx.header[k] = v end
_ngx.say(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment