leslie-tsang commented on a change in pull request #5682:
URL: https://github.com/apache/apisix/pull/5682#discussion_r763666306
##########
File path: apisix/patch.lua
##########
@@ -86,6 +93,44 @@ do
end
+do -- `math.randomseed` patch
+ -- `math.random` generates PRND(pseudo-random numbers) from the seed set
by `math.randomseed`
+ -- Many module libraries use `ngx.time` and `ngx.worker.pid` to generate
seeds which may
+ -- loss randomness in container env (where pids are identical, e.g. root
pid is 1)
+ -- Kubernetes may launch multi instance with deployment RS, so `ngx.time`
may get same return in pods.
+ -- Therefore, this global patch enforce entire framework to use the
best-practice PRND generates.
+
+ local resty_random = require("resty.random")
+ local math_randomseed = math.randomseed
+ local seeded
+
+ -- make linter happy
+ -- luacheck: ignore
+ math.randomseed = function()
+ -- check seed mark
+ if seeded or false then
+ log(ngx.DEBUG, debug.traceback("Random seed has been inited", 2))
+ return
+ end
+
+ -- generate randomseed
+ -- chose 6 from APISIX's SIX, 256 ^ 6 should do the trick
+ -- it shouldn't be large than 16 to prevent overflow.
+ local random_bytes = resty_random.bytes(6)
+ local t = {}
+
+ for i = 1, #random_bytes do
+ t[i] = string.byte(random_bytes, i)
+ end
+
+ local s = table.concat(t)
+
+ seeded = true
+ math_randomseed(tonumber(s))
Review comment:
Make sense. thanks for suggestion. 🥳
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]