设为首页 收藏本站
查看: 558|回复: 0

[经验分享] centos7上使用Zabbix3.2监控RabbitMQ3-CanonInD

[复制链接]

尚未签到

发表于 2019-1-21 11:59:49 | 显示全部楼层 |阅读模式
#!/usr/bin/env /usr/bin/python  
'''Python module to query the RabbitMQ Management Plugin REST API and get
  
results that can then be used by Zabbix.
  
https://github.com/jasonmcintosh/rabbitmq-zabbix
  
'''
  
'''
  
    This script is tested on RabbitMQ 3.5.3
  
'''
  
import json
  
import optparse
  
import socket
  
import urllib2
  
import subprocess
  
import tempfile
  
import os
  
import logging
  

  
logging.basicConfig(filename='/opt/logs/zabbix/rabbitmq_zabbix.log', level=logging.WARNING, format='%(asctime)s %(levelname)s: %(message)s')
  

  
class RabbitMQAPI(object):
  
    '''Class for RabbitMQ Management API'''
  

  
    def __init__(self, user_name='guest', password='guest', host_name='',
  
                 protocol='http', port=15672, conf='/opt/app/zabbix/conf/zabbix_agentd.conf', senderhostname=None):
  
        self.user_name = user_name
  
        self.password = password
  
        self.host_name = host_name or socket.gethostname()
  
        self.protocol = protocol
  
        self.port = port
  
        self.conf = conf or '/opt/app/zabbix/conf/zabbix_agentd.conf'
  
        self.senderhostname = senderhostname if senderhostname else host_name
  

  
    def call_api(self, path):
  
        '''
  
           All URIs will server only resource of type application/json,and will require HTTP basic authentication. The default username and password is guest/guest.  /%sf is encoded for the default virtual host '/'
  
        '''
  
        url = '{0}://{1}:{2}/api/{3}'.format(self.protocol, self.host_name, self.port, path)
  
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
  
        password_mgr.add_password(None, url, self.user_name, self.password)
  
        handler = urllib2.HTTPBasicAuthHandler(password_mgr)
  
        logging.debug('Issue a rabbit API call to get data on ' + path)
  
######## json.loads()  transfer json data to python data
  
######## json.dump()   transfer python data to json data
  
        return json.loads(urllib2.build_opener(handler).open(url).read())
  

  
    def list_queues(self):
  
        ''' curl -i -u guest:guest http://localhost:15672/api/queues
  
        return a list
  
        '''
  
        queues = []
  
        for queue in self.call_api('queues'):
  
            logging.debug("Discovered queue " + queue['name'])
  
            element = {'{#VHOSTNAME}': queue['vhost'],
  
                       '{#QUEUENAME}': queue['name']
  
                      }
  
            queues.append(element)
  
            logging.debug('Discovered queue '+queue['vhost']+'/'+queue['name'])
  
        return queues
  

  
    def list_nodes(self):
  
        '''Lists all rabbitMQ nodes in the cluster'''
  
        nodes = []
  
        for node in self.call_api('nodes'):
  
            # We need to return the node name, because Zabbix
  
            # does not support @ as an item parameter
  
            name = node['name'].split('@')[1]
  
            element = {'{#NODENAME}': name,
  
                       '{#NODETYPE}': node['type']}
  
            nodes.append(element)
  
            logging.debug('Discovered nodes '+name+'/'+node['type'])
  
        return nodes
  

  
    def check_queue(self):
  
        '''Return the value for a specific item in a queue's details.'''
  
        return_code = 0
  
        #### use tempfile module to create a file on memory, will not be deleted when it is closed , because 'delete' argument is set to False
  
        rdatafile = tempfile.NamedTemporaryFile(delete=False)
  
        for queue in self.call_api('queues'):
  
            self._get_queue_data(queue, rdatafile)
  
        rdatafile.close()
  
        return_code = self._send_queue_data(rdatafile)
  
        #### os.unlink is used to remove a file
  
        os.unlink(rdatafile.name)
  
        return return_code
  

  
    def _get_queue_data(self, queue, tmpfile):
  
        '''Prepare the queue data for sending'''
  
        '''
  
          ### one single  queue's information like this #####
  
          ### curl -i -u guest:guest http://localhost:15672/api/queues   dumps a list   ###
  
{"memory":32064,"message_stats":{"ack":3870,"ack_details":{"rate":0.0},"deliver":3871,"deliver_details":{"rate":0.0},"deliver_get":3871,"deliver_get_details":{"rate":0.0},"disk_writes":3870,"disk_writes_details":{"rate":0.0},"publish":3870,"publish_details":{"rate":0.0},"redeliver":1,"redeliver_details":{"rate":0.0}},"messages":0,"messages_details":{"rate":0.0},"messages_ready":0,"messages_ready_details":{"rate":0.0},"messages_unacknowledged":0,"messages_unacknowledged_details":{"rate":0.0},"idle_since":"2016-03-01 22:04:22","consumer_utilisation":"","policy":"","exclusive_consumer_tag":"","consumers":4,"recoverable_slaves":"","state":"running","messages_ram":0,"messages_ready_ram":0,"messages_unacknowledged_ram":0,"messages_persistent":0,"message_bytes":0,"message_bytes_ready":0,"message_bytes_unacknowledged":0,"message_bytes_ram":0,"message_bytes_persistent":0,"disk_reads":0,"disk_writes":3870,"backing_queue_status":{"q1":0,"q2":0,"delta":["delta",0,0,0],"q3":0,"q4":0,"len":0,"target_ram_count":"infinity","next_seq_id":3870,"avg_ingress_rate":0.060962064328682466,"avg_egress_rate":0.060962064328682466,"avg_ack_ingress_rate":0.060962064328682466,"avg_ack_egress_rate":0.060962064328682466},"name":"app000","vhost":"/","durable":true,"auto_delete":false,"arguments":{},"node":"rabbit@test2"}
  
        '''
  
        for item in [ 'memory','messages','messages_ready','messages_unacknowledged','consumers' ]:
  
            #key = rabbitmq.queues[/,queue_memory,queue.helloWorld]
  
            key = '"rabbitmq.queues[{0},queue_{1},{2}]"'.format(queue['vhost'], item, queue['name'])
  
            ### if item is in queue,value=queue[item],else value=0
  
            value = queue.get(item, 0)
  
            logging.debug("SENDER_DATA: - %s %s" % (key,value))
  
            tmpfile.write("- %s %s\n" % (key, value))
  
        ##  This is a non standard bit of information added after the standard items
  
        for item in ['deliver_get', 'publish']:
  
            key = '"rabbitmq.queues[{0},queue_message_stats_{1},{2}]"'.format(queue['vhost'], item, queue['name'])
  
            value = queue.get('message_stats', {}).get(item, 0)
  
            logging.debug("SENDER_DATA: - %s %s" % (key,value))
  
            tmpfile.write("- %s %s\n" % (key, value))
  

  
    def _send_queue_data(self, tmpfile):
  
        '''Send the queue data to Zabbix.'''
  
        '''Get key value from temp file. '''
  
        args = '/opt/app/zabbix/sbin/zabbix_sender -c {0} -i {1}'
  
        if self.senderhostname:
  
            args = args + " -s " + self.senderhostname
  
        return_code = 0
  
        process = subprocess.Popen(args.format(self.conf, tmpfile.name),
  
                                           shell=True, stdout=subprocess.PIPE,
  
                                           stderr=subprocess.PIPE)
  
        out, err = process.communicate()
  
        logging.debug("Finished sending data")
  
        return_code = process.wait()
  
        logging.info("Found return code of " + str(return_code))
  
        if return_code != 0:
  
            logging.warning(out)
  
            logging.warning(err)
  
        else:
  
            logging.debug(err)
  
            logging.debug(out)
  
        return return_code
  

  
    def check_aliveness(self):
  
        '''Check the aliveness status of a given vhost. '''
  
        '''virtual host '/' should be encoded as '/%2f' '''
  
        return self.call_api('aliveness-test/%2f')['status']
  

  
    def check_overview(self, item):
  
        '''First, check the overview specific items'''
  
        ''' curl -i -u guest:guest http://localhost:15672/api/overview   '''
  
        ## rabbitmq[overview,connections]
  
        if   item in [ 'channels','connections','consumers','exchanges','queues' ]:
  
          return self.call_api('overview').get('object_totals').get(item,0)
  
        ## rabbitmq[overview,messages]
  
        elif item in [ 'messages','messages_ready','messages_unacknowledged' ]:
  
          return self.call_api('overview').get('queue_totals').get(item,0)
  
        elif item == 'message_stats_deliver_get':
  
          return self.call_api('overview').get('message_stats', {}).get('deliver_get',0)
  
        elif item == 'message_stats_publish':
  
          return self.call_api('overview').get('message_stats', {}).get('publish',0)
  
        elif item == 'message_stats_ack':
  
          return self.call_api('overview').get('message_stats', {}).get('ack',0)
  
        elif item == 'message_stats_redeliver':
  
          return self.call_api('overview').get('message_stats', {}).get('redeliver',0)
  
        elif item == 'rabbitmq_version':
  
          return self.call_api('overview').get('rabbitmq_version', 'None')
  

  
    def check_server(self,item,node_name):
  
        '''Return the value for a specific item in a node's details. '''
  
        '''curl -i -u guest:guest http://localhost:15672/api/nodes'''
  
        '''return a list'''
  
        # hostname     hk-prod-mq1.example.com
  
        # self.call_api('nodes')[0]['name']   rabbit@hk-prod-mq1
  
        node_name = node_name.split('.')[0]
  
        for nodeData in self.call_api('nodes'):
  
            if node_name in nodeData['name']:
  
                return nodeData.get(item,0)
  
        return 'Not Found'
  

  

  
def main():
  
    '''Command-line parameters and decoding for Zabbix use/consumption.'''
  
    choices = ['list_queues', 'list_nodes', 'queues', 'check_aliveness',
  
               'overview','server']
  
    parser = optparse.OptionParser()
  
    parser.add_option('--username', help='RabbitMQ API username',
  
                      default='guest')
  
    parser.add_option('--password', help='RabbitMQ API password',
  
                      default='guest')
  
    parser.add_option('--hostname', help='RabbitMQ API host',
  
                      default=socket.gethostname())
  
    parser.add_option('--protocol', help='RabbitMQ API protocol (http or https)',
  
                      default='http')
  
    parser.add_option('--port', help='RabbitMQ API port', type='int',
  
                      default=15672)
  
    parser.add_option('--check', type='choice', choices=choices,
  
                      help='Type of check')
  
    parser.add_option('--metric', help='Which metric to evaluate', default='')
  
    parser.add_option('--node', help='Which node to check (valid for --check=server)')
  
    parser.add_option('--conf', default='/opt/app/zabbix/conf/zabbix_agentd.conf')
  
    parser.add_option('--senderhostname', default='', help='Allows including a sender parameter on calls to zabbix_sender')
  
    (options, args) = parser.parse_args()
  
    if not options.check:
  
        parser.error('At least one check should be specified')
  
    logging.debug("Started trying to process data")
  
    api = RabbitMQAPI(user_name=options.username, password=options.password,
  
                      host_name=options.hostname, protocol=options.protocol, port=options.port,
  
                      conf=options.conf, senderhostname=options.senderhostname)
  

  
    if options.check == 'list_queues':
  
        print json.dumps({'data': api.list_queues()},indent=4,separators=(',',':'))
  
    elif options.check == 'list_nodes':
  
        print json.dumps({'data': api.list_nodes()},indent=4,separators=(',',':'))
  
    elif options.check == 'queues':
  
        print api.check_queue()
  
    elif options.check == 'check_aliveness':
  
        print api.check_aliveness()
  
    elif options.check == 'overview':
  
    #rabbitmq[overview,connections]
  
    #--check=overview   --metric=connections
  
        if not options.metric:
  
            parser.error('Missing required parameter: "metric"')
  
        else:
  
            if options.node:
  
                print api.check_overview(options.metric)
  
            else:
  
                print api.check_overview(options.metric)
  
    elif options.check == 'server':
  
    #rabbitmq[server,sockets_used]
  
    #--check=server   --metric=sockets_used
  
         if not options.metric:
  
            parser.error('Missing required parameter: "metric"')
  
         else:
  
            if options.node:
  
                print api.check_server(options.metric,options.node)
  
            else:
  
                print api.check_server(options.metric,api.host_name)
  

  

  
if __name__ == '__main__':
  
    main()



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-665990-1-1.html 上篇帖子: 实战Zabbix 下篇帖子: zabbix企业应用之从数据库提取centos 6.2系统在线天数
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表