Skip to content

Instantly share code, notes, and snippets.

@frah
Created Oct 9, 2012
Embed
What would you like to do?
Lua script of server status monitoring for nginx
string.split_it = function(str, sep)
if str == nil then return nil end
assert(type(str) == "string", "str must be a string")
assert(type(sep) == "string", "sep must be a string")
return string.gmatch(str, "[^\\" .. sep .. "\n]+")
end
string.split = function(str, sep)
local ret = {}
for seg in string.split_it(str, sep) do
ret[#ret+1] = seg
end
return ret
end
string.encode = function(str)
str = string.gsub(str, '\\', '\\\\')
str = string.gsub(str, '"', '\\"')
str = string.gsub(str, "'", "\\'")
str = string.gsub(str, '\n', '\\n')
str = string.gsub(str, '\t', '\\t')
return str
end
function jsonEncode(v)
if v == nil then return 'null' end
local t = type(v)
if t == 'string' then
return '"' .. v:encode() .. '"'
end
if t == 'number' then
return tostring(v)
end
if t == 'boolean' then
return tostring(v)
end
if t == 'table' then
local ret = {}
for key,val in pairs(v) do
table.insert(ret, '"' .. key:encode() .. '": ' .. jsonEncode(val))
end
return '{' .. table.concat(ret, ',') .. '}'
end
return 'null'
end
ret = {}
daemons = {'sshd', 'cron', 'ntpd', 'named', 'snmpd', 'mpd5', 'httpd', 'nginx', 'java', 'squid', 'mysqld', 'postfix', 'dovecot', 'fetchmail', 'sendmail', 'smbd', 'transmission'}
----------------
-- get uptime --
----------------
o = assert(io.popen('/usr/bin/uptime', 'r'))
u = o:read('*a')
o:close()
local _, _, up, user, l1, l2, l3 = u:find("up (.+), (%d+) users?, load averages: ([0-9%.]+),%s([0-9%.]+),%s([0-9%.]*)")
local t = {}
local uptime = 0
_, _, t[1] = up:find("(%d+) days?")
_, _, t[2] = up:find("(%d+) hrs?")
_, _, t[3], t[4] = up:find("(%d+):(%d+)")
_, _, t[5] = up:find("(%d+) mins?")
for k,v in pairs({1440, 60, 60, 1, 1}) do
uptime = uptime + tonumber((t[k] ~= nil) and t[k] or 0) * v
end
ret['uptime'] = uptime
ret['user'] = tonumber(user)
ret['1min'] = l1
ret['5min'] = l2
ret['10min'] = l3
-----------------------
-- get daemon status --
-----------------------
ds = {}
o = assert(io.popen('/bin/ps auxww'))
p = o:read('*a')
o:close()
for k,v in pairs(daemons) do
ds[v] = p:find(v)~=nil
end
ret['dstats'] = ds
ngx.print(jsonEncode(ret))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment