-
Notifications
You must be signed in to change notification settings - Fork 40
/
redis-monitor.py
114 lines (98 loc) · 3.44 KB
/
redis-monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'iambocai'
import json
import time
import socket
import os
import re
import sys
import commands
import urllib2, base64
class RedisStats:
_redis_cli = '/usr/bin/redis-cli'
_stat_regex = re.compile(ur'(\w+):([0-9]+\.?[0-9]*)\r')
def __init__(self, port='6379', passwd=None, host='127.0.0.1'):
self._cmd = '%s -h %s -p %s info' % (self._redis_cli, host, port)
if passwd not in ['', None]:
self._cmd = "%s -a %s" % (self._cmd, passwd )
def stats(self):
' Return a dict containing redis stats '
info = commands.getoutput(self._cmd)
return dict(self._stat_regex.findall(info))
def main():
ip = socket.gethostname()
timestamp = int(time.time())
step = 60
# inst_list = [ i for i in commands.getoutput("find /etc/ -name 'redis*.conf'" ).split('\n') ]
insts_list = [ '/etc/redis.conf' ]
p = []
monit_keys = [
('connected_clients','GAUGE'),
('blocked_clients','GAUGE'),
('used_memory','GAUGE'),
('used_memory_rss','GAUGE'),
('mem_fragmentation_ratio','GAUGE'),
('total_commands_processed','COUNTER'),
('rejected_connections','COUNTER'),
('expired_keys','COUNTER'),
('evicted_keys','COUNTER'),
('keyspace_hits','COUNTER'),
('keyspace_misses','COUNTER'),
('keyspace_hit_ratio','GAUGE'),
]
for inst in insts_list:
port = commands.getoutput("sed -n 's/^port *\([0-9]\{4,5\}\)/\\1/p' %s" % inst)
passwd = commands.getoutput("sed -n 's/^requirepass *\([^ ]*\)/\\1/p' %s" % inst)
metric = "redis"
endpoint = ip
tags = 'port=%s' % port
try:
conn = RedisStats(port, passwd)
stats = conn.stats()
except Exception,e:
continue
for key,vtype in monit_keys:
if key == 'keyspace_hit_ratio':
try:
value = float(stats['keyspace_hits'])/(int(stats['keyspace_hits']) + int(stats['keyspace_misses']))
except ZeroDivisionError:
value = 0
elif key == 'mem_fragmentation_ratio':
value = float(stats[key])
else:
try:
value = int(stats[key])
except:
continue
i = {
'Metric': '%s.%s' % (metric, key),
'Endpoint': endpoint,
'Timestamp': timestamp,
'Step': step,
'Value': value,
'CounterType': vtype,
'TAGS': tags
}
p.append(i)
print json.dumps(p, sort_keys=True,indent=4)
method = "POST"
handler = urllib2.HTTPHandler()
opener = urllib2.build_opener(handler)
url = 'http://127.0.0.1:1988/v1/push'
request = urllib2.Request(url, data=json.dumps(p) )
request.add_header("Content-Type",'application/json')
request.get_method = lambda: method
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e
# check. Substitute with appropriate HTTP code.
if connection.code == 200:
print connection.read()
else:
print '{"err":1,"msg":"%s"}' % connection
if __name__ == '__main__':
proc = commands.getoutput(' ps -ef|grep %s|grep -v grep|wc -l ' % os.path.basename(sys.argv[0]))
if int(proc) < 5:
main()