Skip to content

Instantly share code, notes, and snippets.

@thom-vend
Last active March 28, 2021 21:10
Show Gist options
  • Save thom-vend/7b3ae9c4404a59311f459c0c382d78aa to your computer and use it in GitHub Desktop.
Save thom-vend/7b3ae9c4404a59311f459c0c382d78aa to your computer and use it in GitHub Desktop.
-- Quick and Dirty script to get Redis'keys TTL distribution per hours
-- How to run it?
-- With a redis-cli:
-- `redis-cli -h my.redis.host.local --eval distribution.lua`
--
local logtable = {} -- Array to store our logs, returned by the script, printed to the screen
-- A small log function
local function logit(msg)
logtable[#logtable+1] = msg
end
logit("Hello from my script") -- Example to log a message
-- Parameters to get distribution per hours
local max = 24 * 7 -- max 7d
local increment = 4 -- increment by 4h
--
local results = {} -- declare an array to store all measures
for j = 0, max, increment
do
results[j] = 0
end
local abovemax = 0 -- count nb of key above our max
local nottl = 0
--
local cursor = "0" -- The scan function need a cursor
repeat -- start a loop until the cursor is back to the original value.
-- Using the scan function is much safer and consume less resource than the `key *`
-- SCAN is not deterministic, inside the loop we can't have atomic writes.
local t = redis.call("SCAN", cursor, "COUNT", 10000); -- return an array {cursor,results}
local list = t[2]; -- our result are in the 2nd position, t[1] is the cursor ; IDK what's inside t[0]
for i = 1, #list do -- iterate on our results
local vttl = redis.call("TTL", list[i]) -- call another redis function to get the TTL on each key
-- logic to have the distribution
if vttl < 1 then
nottl = nottl + 1
elseif vttl > (max * 3600) then
abovemax = abovemax + 1
else
for j = 0, max, increment
do
if vttl > (j * 3600) and vttl < ((j + increment) * 3600) then
results[j] = results[j] + 1
break
end
end
end
-- end logic
end
cursor = t[1]; -- Update the cursor to be able to do the next SCAN, if we don't update this scan will.
until cursor == "0"; -- Cusor back to the original position, scan is completed
-- Construct human readable output
logit("END")
logit("No TTL: " .. nottl .. " keys")
for j = 0, max, increment
do
logit("Up to " .. ( j + increment ) .. " hours: " .. results[j] .. " keys")
end
logit("More than" .. max .. " hours:" .. abovemax .. " keys")
-- return output filled by `logit` function
return logtable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment