Skip to content

Instantly share code, notes, and snippets.

@pintsized
Created June 15, 2012 13:49
Show Gist options
  • Save pintsized/2936560 to your computer and use it in GitHub Desktop.
Save pintsized/2936560 to your computer and use it in GitHub Desktop.
Ledge stats
location /stats {
default_type application/json;
content_by_lua '
local redis = require "resty.redis"
local red = redis:new()
local ledge = require "ledge.ledge"
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.exit(500)
return
end
local total_hits_hot = red:get("ledge:counter:HOT")
if total_hits_hot == ngx.null then total_hits_hot = 0 end
local total_hits_warm = red:get("ledge:counter:WARM")
if total_hits_warm == ngx.null then total_hits_warm = 0 end
local total_hits_subzero = red:get("ledge:counter:SUBZERO")
if total_hits_subzero == ngx.null then total_hits_subzero = 0 end
local known_url_count = red:zcount("ledge:uris_by_expiry", "-inf", "+inf")
local fresh_url_count = #red:keys("ledge:cache_obj:*") or 0
local dbsize = red:dbsize()
function total_hits()
return total_hits_hot + total_hits_warm + total_hits_subzero
end
function round(val, decimal)
if (decimal) then
return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
else
return math.floor(val+0.5)
end
end
function parse_info(response)
local info = {}
local current = info
response:gsub("([^\\r\\n]*)\\r\\n", function(kv)
if kv == "" then return end
local section = kv:match("^# (%w+)$")
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(("([^:]*):([^:]*)"):rep(1))
if k:match("db%d+") then
current[k] = {}
v:gsub(",", function(dbkv)
local dbk,dbv = kv:match("([^:]*)=([^:]*)")
current[k][dbk] = dbv
end)
else
if tonumber(v) then
v = tonumber(v)
end
current[k] = v
end
end)
return info
end
local stats = {
ledge_version = ledge._VERSION,
["requests"] = {
counters = {
HOT = tonumber(total_hits_hot),
WARM = tonumber(total_hits_warm),
SUBZERO = tonumber(total_hits_subzero),
},
total = total_hits(),
hit_rate = tostring(round(total_hits_hot / total_hits() * 100)).."%",
},
uris = {
known = known_url_count,
fresh = fresh_url_count
},
health = {
total_items = dbsize,
},
redis = {
dbsize = dbsize,
info = parse_info(red:info()),
}
}
local cjson = require "cjson"
ngx.say(cjson.encode(stats))
red:close()
';
}
-- In main ledge config, to increment the counters..
ledge.bind("response_ready", function(req, res)
local state = res.header["X-Cache-State"]
if state then
ngx.ctx.redis:incr("ledge:counter:"..state)
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment