falcon监控redis
admin
2023-02-06 20:00:02
0
falcon 结合脚本redis-monitor.py进行监控redis
* * * * * python  /usr/local/openfalcon-0.2/mymon/redis-monitor.py &> /usr/local/openfalcon-0.2/mymon/redis-monitor.log
cat redis-monitor.py
#注意修改配置项:_redis_cli,def __init__,insts_list,ip
#!/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,请将下面的值替换为你到redis-cli路径
    _redis_cli = '/usr/local/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 -h %s -p %s -a %s info' % (self._redis_cli, host, port, passwd)
    def stats(self):
        ' Return a dict containing redis stats '
        info = commands.getoutput(self._cmd)
        #print info
        return dict(self._stat_regex.findall(info))

def main():
    ip = '192.168.1.1'
    #ip = socket.gethostname()
    timestamp = int(time.time())
    step = 60
    # inst_list中保存了redis配置文件列表,程序将从这些配置中读取port和password,建议使用动态发现的方法获得,如:
    # inst_list = [ i for i in commands.getoutput("find  /etc/ -name 'redis*.conf'" ).split('\n') ]
    insts_list = [ '/etc/redis/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:
            #一些老版本的redis中info输出的信息很少,如果缺少一些我们需要采集的key就跳过
            if key not in stats.keys():
                continue
            #计算命中率
            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:
                #其他的都采集成counter,int
                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:1998/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]))
    sys.stdout.flush()
    if int(proc) < 5:
        main()

redis 进程监控
falcon监控redis

redis状态监控

falcon监控redis

相关内容

热门资讯

工信部部长:搞“脱钩断链”对谁... 7月23日,2026年亚太经合组织(APEC)数字和人工智能部长会议新闻发布会在成都召开。会议主席、...
AMD展示最强AI加速器MI4... IT之家 7 月 24 日消息,今天(7 月 24 日)在美国旧金山召开的年度盛会 Advancin...
河北:知行研学度盛夏 多彩实践... 冀时新闻报道暑假期间,我省各地推出形式多样的青少年研学活动,让孩子们在实践中增长见识、锤炼品格,度过...
世界互联网大会数智健康工作组以... 7月22日,2026年世界互联网大会数字丝路发展论坛在陕西西安开幕。这是世界互联网大会连续第三年举办...
开立医疗获得实用新型专利授权:... 证券之星消息,根据天眼查APP数据显示开立医疗(300633)新获得一项实用新型专利授权,专利名为“...
成都深入实施“人工智能+”行动 成都深入实施“人工智能+”行动 到2027年实现人工智能核心产业规模突破2600亿元 华西都市报讯(...
原创 中... 说真的,看到欧洲科学家一本正经拿粪水浇菜做研究,最后还得出了个“安全无害、肥力充足”的结论,我第一反...
小米智能手环11 Active... IT之家 7 月 23 日消息,科技媒体 WinFuture 昨日(7 月 22 日)发布博文,分享...
胡塞武装袭击红海油轮,特朗普威... 据路透社报道,当地时间7月23日,也门胡塞武装表示已在红海袭击两艘沙特油轮,并称这两艘油轮违反该组织...
刚签就要黄了?特朗普:核能协议... 据彭博社报道,当地时间7月23日,美国总统特朗普表示,美国与沙特阿拉伯的民用核能合作协议能否落地,将...