dickens7 commented on a change in pull request #4559:
URL: https://github.com/apache/apisix/pull/4559#discussion_r668898785
##########
File path: apisix/plugins/request-id.lua
##########
@@ -41,9 +72,134 @@ function _M.check_schema(conf)
end
+-- Generates the current process worker number
+local function gen_worker_number(max_number)
+ if worker_number == nil then
+ local etcd_cli, prefix = core.etcd.new()
+ local prefix = prefix .. "/plugins/request-id/snowflake/"
+ local uuid = uuid.generate_v4()
+ local id = 1
+ while (id <= max_number) do
+ ::continue::
+ local res, _ = etcd_cli:grant(attr.snowflake.worker_number_ttl)
+ local _, err1 = etcd_cli:setnx(prefix .. tostring(id), uuid)
+ local res2, err2 = etcd_cli:get(prefix .. tostring(id))
+
+ if err1 or err2 or res2.body.kvs[1].value ~= uuid then
+ core.log.notice("worker_number " .. id .. " is not available")
+ id = id + 1
+ else
+ worker_number = id
+
+ local _, err3 =
+ etcd_cli:set(
+ prefix .. tostring(id),
+ uuid,
+ {
+ prev_kv = true,
+ lease = res.body.ID
+ }
+ )
+
+ if err3 then
+ id = id + 1
+ etcd_cli:delete(prefix .. tostring(id))
+ core.log.error("set worker_number " .. id .. " lease
error: " .. err3)
+ goto continue
+ end
+
+ local lease_id = res.body.ID
+ local start_at = ngx.time()
+ local handler = function()
+ local now = ngx.time()
+ if now - start_at < attr.snowflake.worker_number_interval
then
+ return
+ end
+
+ local _, err4 = etcd_cli:keepalive(lease_id)
+ if err4 then
+ snowflake_inited = nil
+ worker_number = nil
+ core.log.error("snowflake worker_number: " .. id .."
lease faild.")
+ end
+ start_at = now
+ core.log.info("snowflake worker_number: " .. id .." lease
success.")
+ end
+
+ timers.register_timer("plugin#request-id", handler)
+ core.log.info(
+ "timer created to lease snowflake algorithm worker number,
interval: ",
+ attr.snowflake.worker_number_interval)
+ core.log.notice("lease snowflake worker_number: " .. id)
+ break
+ end
+ end
+
+ if worker_number == nil then
+ core.log.error("No worker_number is not available")
+ return nil
+ end
+ end
+ return worker_number
+end
+
+
+-- Split 'Worker Number' into 'Worker ID' and 'datacenter ID'
+local function split_worker_number(worker_number, node_id_bits,
datacenter_id_bits)
+ local num = bit.tobit(worker_number)
+ local worker_id = bit.band(num, math_pow(2, node_id_bits) - 1) + 1
+ num = bit.rshift(num, node_id_bits)
+ local datacenter_id = bit.band(num, math_pow(2, datacenter_id_bits) - 1) +
1
+ return worker_id, datacenter_id
Review comment:
It's going to be a bug to start at 1 here, let me fix that
--
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]