PageRenderTime 24ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/python/nginxstats.py

http://timoseven.googlecode.com/
Python | 89 lines | 68 code | 20 blank | 1 comment | 14 complexity | 3d67df91b545e58c8877e70de08d90c2 MD5 | raw file
Possible License(s): MIT, LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-3.0, AGPL-1.0
  1. #!/usr/bin/env python
  2. import re
  3. import sys
  4. import time
  5. import urllib
  6. TIME_SLEEP = 30
  7. def get_data(url):
  8. data = urllib.urlopen(url)
  9. data = data.read()
  10. result = {}
  11. match1 = re.search(r'Active connections:\s+(\d+)', data)
  12. match2 = re.search(r'\s*(\d+)\s+(\d+)\s+(\d+)', data)
  13. match3 = re.search(r'Reading:\s*(\d+)\s*Writing:\s*(\d+)\s*'
  14. 'Waiting:\s*(\d+)', data)
  15. if not match1 or not match2 or not match3:
  16. raise Exception('Unable to parse %s' % url)
  17. result['connections'] = int(match1.group(1))
  18. result['accepted'] = int(match2.group(1))
  19. result['handled'] = int(match2.group(2))
  20. result['requests'] = int(match2.group(3))
  21. result['reading'] = int(match3.group(1))
  22. result['writing'] = int(match3.group(2))
  23. result['waiting'] = int(match3.group(3))
  24. return result
  25. def main():
  26. url = sys.argv[1]
  27. prev = None
  28. next = time.time() + TIME_SLEEP
  29. total = None
  30. count = 0
  31. try:
  32. while True:
  33. data = get_data(url)
  34. if prev:
  35. result = print_stat(prev, data)
  36. if total is None:
  37. total = list(result)
  38. else:
  39. for i, v in enumerate(result):
  40. total[i] += v
  41. count += 1
  42. else:
  43. print_head()
  44. prev = data
  45. time.sleep(next - time.time())
  46. next += TIME_SLEEP
  47. except KeyboardInterrupt:
  48. if total:
  49. print_foot(total, count)
  50. def print_foot(total, count):
  51. total = [v / count for v in total]
  52. print '-------- ---------- ---------- ----- ----- -----'
  53. print '%8d %10.2f %10.2f %5d %5d %5d' % tuple(total)
  54. def print_head():
  55. print '%-8s %-10s %-10s %-5s %-5s %-5s' % (
  56. 'Conn', 'Conn/s', 'Request/s', 'Read', 'Write', 'Wait')
  57. print '-------- ---------- ---------- ----- ----- -----'
  58. def print_stat(prev, data):
  59. result = (
  60. data['connections'],
  61. float(data['accepted'] - prev['accepted']) / TIME_SLEEP,
  62. float(data['requests'] - prev['requests']) / TIME_SLEEP,
  63. data['reading'],
  64. data['writing'],
  65. data['waiting'])
  66. print '%8d %10.2f %10.2f %5d %5d %5d' % result
  67. return result
  68. if __name__ == '__main__':
  69. main()