Skip to content

Commit

Permalink
Merge pull request #3671 from moonming/randomseed-bugfix
Browse files Browse the repository at this point in the history
bugfix: fixed duplicated seeds.
  • Loading branch information
k8s-ci-robot authored Feb 10, 2019
2 parents 566444d + 8ea7501 commit d9845c7
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions rootfs/etc/nginx/lua/lua_ingress.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,32 @@ local _M = {}

local seeds = {}
local original_randomseed = math.randomseed

local function get_seed_from_urandom()
local seed
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(seed)
local pid = ngx.worker.pid()

if seeds[pid] then
ngx.log(ngx.WARN,
string.format("ignoring math.randomseed(%d) since PRNG is already seeded for worker %d", seed, pid))
Expand All @@ -16,7 +39,12 @@ math.randomseed = function(seed)
end

local function randomseed()
math.randomseed(ngx.time() + ngx.worker.pid())
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()
Expand Down

0 comments on commit d9845c7

Please sign in to comment.