Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whatvn/7f3fdaf91889f85fcd7fbd0ba484d3c0 to your computer and use it in GitHub Desktop.
Save whatvn/7f3fdaf91889f85fcd7fbd0ba484d3c0 to your computer and use it in GitHub Desktop.
nginxStatusCacti.py
#!/usr/bin/env python
try:
import simplejson as json
except:
import json
import urllib2
class ServerStatistics(object):
def __init__(self):
self.serverName = None
self.responseTime = 0
self.requestCounter = 0
self.request1xx = 0
self.request2xx = 0
self.request4xx = 0
self.request5xx = 0
@property
def toString(self):
return 'responseTime:{0} requestCounter:{1} request1xx:{2} request2xx:{3} request4xx:{4} request5xx:{5}'.format(self.responseTime,
self.requestCounter,
self.request1xx,
self.request2xx,
self.request4xx,
self.request5xx)
def writeToFile(self):
with open('/tmp/{0}'.format(self.serverName), 'w') as f:
f.write(self.toString)
def getData(url):
res = None
try:
response = urllib2.urlopen(url)
statsJson = json.load(response)
res = getServerZones(statsJson)
except Exception:
pass
return res
def getServerZones(data):
return data.get('serverZones')
def getBackendStats(serverZoneData, backendName):
return serverZoneData.get(backendName)
def set(oldValue, newValue):
return newValue if oldValue is None else newValue - int(oldValue)
def buildResponse(stats, name):
# type: (object, object) -> object
oldResult , oldResponseData = {}, {}
lastResultFile = '/tmp/{0}'.format(name)
backendStats = getBackendStats(stats, name)
if backendStats is None: return backendStats
try:
with open(lastResultFile, 'r') as f:
oldResult = json.load(f)
except:
pass
serverStatistics = ServerStatistics()
serverStatistics.serverName = name
serverStatistics.responseTime = backendStats.get('requestMsec')
responsesData = backendStats.get('responses')
oldResponseData = oldResult.get('responses') if oldResult else {}
serverStatistics.request1xx = set(oldResponseData.get('1xx'), responsesData.get('1xx'))
serverStatistics.request2xx = set(oldResponseData.get('2xx'), responsesData.get('2xx'))
serverStatistics.request4xx = set(oldResponseData.get('4xx'), responsesData.get('4xx'))
serverStatistics.request5xx = set(oldResponseData.get('5xx'), responsesData.get('5xx'))
serverStatistics.requestCounter = set(oldResult.get('requestCounter'), backendStats.get('requestCounter'))
with open(lastResultFile, 'w') as f:
json.dump(backendStats, f)
return serverStatistics
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print 'Usage: {0} nginx_ip server_name'
sys.exit(1)
statusUrl = "http://{0}/status/format/json".format(sys.argv[1])
cactiStatistics = buildResponse(getData(statusUrl), sys.argv[2])
if cactiStatistics:
print cactiStatistics.toString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment