Created
October 9, 2012 01:28
-
-
Save frah/3856030 to your computer and use it in GitHub Desktop.
Lua script of server status monitoring for nginx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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