#!/bin/env python
#-*-Coding:utf-8-*-
Import JSON
Import time
Import socket
Import OS
Import re
Import Sys
Import commands
Import Urllib2, base64
Class Redisstats:
REDIS_CLI = '/data/redis/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 ', status= ' info '):
Self.cmd = '%s-h%s-p%s%s '% (SELF.REDIS_CLI, host, Port,status)
def stats (self):
info = commands.getoutput (self.cmd)
Return Dict (Self.stat_regex.findall (info))
def main ():
timestamp = Int (time.time ())
Step = 60
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 '),
]
Insts_list = ['/etc/redis/6379.conf ']
With open ('./cfg.json ') as F:
data = F.read (). replace (' \ n ', ')
Jsonhostname = json.loads (data)
Hostpoint = jsonhostname[' hostname ']
For Inst in insts_list:
Port = commands.getoutput ("Sed-n ' S/^port *\ ([0-9]\{4,5\}\)/\\1/p '%s"% inst)
Metric = "Redis"
Endpoint = '%s '% (hostpoint)
tags = ' port=%s '% port
Try
conn = Redisstats ()
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 ()
#!/bin/Env python#-*-coding:utf-8-*-import jsonimport timeimport socketimport osimport reimport sysimport commandsimport urllib2, base64classredisstats:redis_cli='/data/redis/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', status='Info'): Self.cmd='%s-h%s-p%s%s'%(SELF.REDIS_CLI, Host, port,status) def stats (self): info=commands.getoutput (self.cmd)returnDict (Self.stat_regex.findall (info)) def main (): Timestamp=int(Time.time ()) Step= -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'),] insts_list= ['/etc/redis/6379.conf'] with open ('./cfg.json') asF:data= F.read (). Replace ('\ n',"') Jsonhostname=json.loads (data) Hostpoint= jsonhostname['hostname'] forInstinchInsts_list:port= Commands.getoutput ("sed-n ' S/^port *\ ([0-9]\{4,5\}\)/\\1/p '%s"%Inst) Metric="Redis"Endpoint='%s'%(hostpoint) tags='port=%s'%PortTry: Conn=redisstats () stats=conn.stats () except exception,e:Continue forKey,vtypeinchMonit_keys:ifKey = ='Keyspace_hit_ratio': Try: Value=float(stats['keyspace_hits'])/(int(stats['keyspace_hits']) +int(stats['keyspace_misses'])) except Zerodivisionerror:value=0elif Key=='Mem_fragmentation_ratio': Value=float(Stats[key])Else: Try: Value=int(Stats[key]) except:ContinueI= { '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:methodTry: Connection=Opener.open (Request) except URLLIB2. Httperror,e:connection=e # check. Substitute with appropriate HTTP code. ifConnection.code = = $: Print connection.read ()Else: Print'{"Err": 1, "MSG": "%s"}'%Connectionif__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 ()
Monitoring Redis python scripts