PageRenderTime 20ms CodeModel.GetById 13ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/python/nginxstats.py

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