Skip to content

Commit

Permalink
added more error info and keep test cases.
Browse files Browse the repository at this point in the history
  • Loading branch information
moonming committed Jan 21, 2019
1 parent c782f22 commit 8ea7501
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 19 deletions.
47 changes: 30 additions & 17 deletions rootfs/etc/nginx/lua/lua_ingress.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,50 @@ local original_randomseed = math.randomseed

local function get_seed_from_urandom()
local seed
local frandom = io.open("/dev/urandom", "rb")
if frandom then
local str = frandom:read(4)
frandom:close()
seed = 0
for i = 1, 4 do
seed = 256 * seed + str:byte(i)
end
local frandom, err = io.open("/dev/urandom", "rb")
if not frandom then
ngx.log(ngx.WARN, 'failed to open /dev/urandom: ', err)
return nil
end

local str = frandom:read(4)
frandom:close()
if not str then
ngx.log(ngx.WARN, 'failed to read data from /dev/urandom')
return nil
end

seed = 0
for i = 1, 4 do
seed = 256 * seed + str:byte(i)
end

return seed
end

math.randomseed = function()
math.randomseed = function(seed)
local pid = ngx.worker.pid()
local seed = seeds[pid]
if seed then
if seeds[pid] then
ngx.log(ngx.WARN,
string.format("ignoring math.randomseed() since PRNG is already seeded for worker %d", pid))
string.format("ignoring math.randomseed(%d) since PRNG is already seeded for worker %d", seed, pid))
return
end

seed = get_seed_from_urandom()
if not seed then
seed = ngx.now() * 1000 + pid
end
original_randomseed(seed)
seeds[pid] = seed
end

local function randomseed()
local seed = get_seed_from_urandom()
if not seed then
ngx.log(ngx.WARN, 'failed to get seed from urandom')
seed = ngx.now() * 1000 + ngx.worker.pid()
end
math.randomseed(seed)
end

function _M.init_worker()
math.randomseed()
randomseed()
end

return _M
4 changes: 2 additions & 2 deletions rootfs/etc/nginx/lua/test/lua_ingress_test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ describe("lua_ingress", function()
it("patches math.randomseed to not be called more than once per worker", function()
local s = spy.on(ngx, "log")

math.randomseed()
math.randomseed(100)
assert.spy(s).was_called_with(ngx.WARN,
string.format("ignoring math.randomseed() since PRNG is already seeded for worker %d", ngx.worker.pid()))
string.format("ignoring math.randomseed(%d) since PRNG is already seeded for worker %d", 100, ngx.worker.pid()))
end)
end)

0 comments on commit 8ea7501

Please sign in to comment.