Fork me on GitHub

Zabbix監控ActiveMQ

當我們在線上使用了ActiveMQ 后,我們需要對一些參數進行監控,比如 消息是否有阻塞,哪個消息隊列阻塞了,總的消息數是多少等等。下面我們就通過 Zabbix 結合 Python 腳本來實現對 ActiveMQ的監控。

一、創建 Activemq Python 監控腳本

因為 CentOS 系統默認安裝的是 Python2.7,為了避免麻煩,我們這里的腳本也是對應的 Python2

Python2 監控腳本

# -*- coding: utf-8 -*-
# @Time    : 2019/6/25 9:26
# @Author  : djx
# @Email   : [email protected]
# @File    : mointer_mq_python2.py
# @Software: PyCharm
# @Python_version: python2.7

import base64
import urllib2
import json
import logging
import sys


def activemq_mointer(userinfo_encode):
    # 總的消息阻塞數
    pending_queue_sum = 0
    # 阻塞消息的隊列名稱
    pending_queue_lists = ''
    # 總的消息數
    mq_sum = 0
    headers = {
        'Authorization': 'Basic {}'.format(userinfo_encode),
        'ua': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'
    }
    url = 'http://' + ip + ':' + port + \
          '/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost/Queues/'
    request = urllib2.Request(url=url, headers=headers)
    try:
        response = urllib2.urlopen(request)
    except Exception as e:
        logging.error(e)
        return {'pending_queue_sum': 110, 'pending_queue_lists': '110', 'mq_sum': 0}  # 當服務不可用時,返回預警數字,用于預警。
    activemq_info = response.read()
    activemq_info_json = json.loads(activemq_info)
    activemq_queues = activemq_info_json['value']
    for i in activemq_queues:
        queue_url = 'http://' + ip + ':' + port + \
            '/api/jolokia/read/' + i['objectName']
        queue_request = urllib2.Request(url=queue_url, headers=headers)
        try:
            queue_response = urllib2.urlopen(queue_request)
        except Exception as e:
            logging.error(e)
            return {'pending_queue_sum': 110, 'pending_queue_lists': '110', 'mq_sum': 0}
        queue_info = queue_response.read()
        info_dict = json.loads(queue_info)
        mq_sum += info_dict['value']['EnqueueCount']
        if int(info_dict['value']['QueueSize']
               ) > 0:  # 取值 QueueSize ,就是未消費的消息數量
            pending_queue_sum += info_dict['value']['QueueSize']
            pending_queue_lists += info_dict['value']['Name']
            pending_queue_lists += ' and '
            logging.info(
                "消息隊列--{}--有阻塞消息--{} 條".format(
                    info_dict['value']['Name'],
                    info_dict['value']['QueueSize']))
    return {'pending_queue_sum': pending_queue_sum, 'pending_queue_lists': pending_queue_lists, 'mq_sum': mq_sum}


if __name__ == '__main__':
    # ActiveMQ 服務器信息
    username = 'admin'
    password = 'admin'
    ip = '127.0.0.1'
    port = '8161'
    userinfo = username + ':' + password
    userinfo_encode = base64.b64encode(userinfo.encode('utf8'))
    # 日志配置,注意下面日志文件的路徑是采用絕對路徑的。
    logging.basicConfig(
        filename="/var/log/activemq_mointer.log",
        filemode="a",
        format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        level=logging.DEBUG)
    if len(sys.argv) == 2:
        mointer_argv = sys.argv[1]
        if mointer_argv in ('pending', 'pending_lists', 'queue_sum'):
            mq_re = activemq_mointer(userinfo_encode)
            if mointer_argv == 'pending':
                print(mq_re['pending_queue_sum'])
            elif mointer_argv == 'pending_lists':
                print(mq_re['pending_queue_lists'])
            else:
                print(mq_re['mq_sum'])
        else:
            # 錯誤提示
            print("Please enter the correct parameters pending|pending_lists|queue_sum")
    else:
        # 錯誤提示
        print("Please enter the correct parameters pending|pending_lists|queue_sum")

使用該腳本注意事項:

  1. 傳入參數只能一個 ,而且只能是 pending, pending_lists, queue_sum ,分別代表阻塞消息數、阻塞消息隊列名稱、總的消息數。

  2. 腳本有日志記錄和異常記錄,注意設置 日志文件路徑,假設腳本路徑位于 /opt/scripts/,我們在該目錄下進行執行腳本的話,activemq_mointer.log 日志文件也就會產生在當前目錄下。我們可以在路徑中通過絕對路徑來指定文件夾 形如 /var/log/activemq_mointer.log

  3. 該腳本是由 zabbix agent 進行使用 ,所以我們需要設置該 腳本的權限,以及保證該腳本的用戶有創建日志文件的權限(或者我們先前創建好對應權限日志文件)

    sudo chown  zabbix:zabbix  mointer_mq_python2.py
    sudo  chmod 744 mointer_mq_python2.py
    sudo  touch /var/log/activemq_mointer.log
    sudo chown  zabbix:zabbix  /var/log/activemq_mointer.log  # 這個一定得設置,不然會報沒有權限的錯誤,也就收集不到數據了。 如果我們不想設置權限這一步,我們可以設置將日志寫到 `/tmp/activemq_mointer.log`.

二 、設置 zabbix agent

設置 zabbix agent

# 將監控項配置寫入配置文件
sudo echo "UserParameter=activemq.mointer[*],python /opt/scripts/mointer_mq_python2.py \$1 " >> /opt/zabbix-agent/etc/zabbix_agentd.conf
# 重啟zabbix agent
sudo systemctl restart  zabbix-agent 

三、導入監控項:

監控模板 xml 文件。(該監控模板包含三個監控項,一個觸發器)

<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
    <version>4.0</version>
    <date>2019-06-26T03:49:47Z</date>
    <groups>
        <group>
            <name>AWS-1688</name>
        </group>
        <group>
            <name>Fy-hbg</name>
        </group>
    </groups>
    <templates>
        <template>
            <template>Template App ActiveMQ</template>
            <name>Template App ActiveMQ</name>
            <description/>
            <groups>
                <group>
                    <name>AWS-1688</name>
                </group>
                <group>
                    <name>Fy-hbg</name>
                </group>
            </groups>
            <applications>
                <application>
                    <name>ActiveMQ</name>
                </application>
            </applications>
            <items>
                <item>
                    <name>activemq pending amount</name>
                    <type>0</type>
                    <snmp_community/>
                    <snmp_oid/>
                    <key>activemq.mointer[pending]</key>
                    <delay>1m</delay>
                    <history>90d</history>
                    <trends>365d</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units>條</units>
                    <snmpv3_contextname/>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authprotocol>0</snmpv3_authprotocol>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privprotocol>0</snmpv3_privprotocol>
                    <snmpv3_privpassphrase/>
                    <params/>
                    <ipmi_sensor/>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>ActiveMQ</name>
                        </application>
                    </applications>
                    <valuemap/>
                    <logtimefmt/>
                    <preprocessing/>
                    <jmx_endpoint/>
                    <timeout>3s</timeout>
                    <url/>
                    <query_fields/>
                    <posts/>
                    <status_codes>200</status_codes>
                    <follow_redirects>1</follow_redirects>
                    <post_type>0</post_type>
                    <http_proxy/>
                    <headers/>
                    <retrieve_mode>0</retrieve_mode>
                    <request_method>0</request_method>
                    <output_format>0</output_format>
                    <allow_traps>0</allow_traps>
                    <ssl_cert_file/>
                    <ssl_key_file/>
                    <ssl_key_password/>
                    <verify_peer>0</verify_peer>
                    <verify_host>0</verify_host>
                    <master_item/>
                </item>
                <item>
                    <name>activemq pending queue name</name>
                    <type>0</type>
                    <snmp_community/>
                    <snmp_oid/>
                    <key>activemq.mointer[pending_lists]</key>
                    <delay>1m</delay>
                    <history>90d</history>
                    <trends>0</trends>
                    <status>0</status>
                    <value_type>1</value_type>
                    <allowed_hosts/>
                    <units/>
                    <snmpv3_contextname/>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authprotocol>0</snmpv3_authprotocol>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privprotocol>0</snmpv3_privprotocol>
                    <snmpv3_privpassphrase/>
                    <params/>
                    <ipmi_sensor/>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>ActiveMQ</name>
                        </application>
                    </applications>
                    <valuemap/>
                    <logtimefmt/>
                    <preprocessing/>
                    <jmx_endpoint/>
                    <timeout>3s</timeout>
                    <url/>
                    <query_fields/>
                    <posts/>
                    <status_codes>200</status_codes>
                    <follow_redirects>1</follow_redirects>
                    <post_type>0</post_type>
                    <http_proxy/>
                    <headers/>
                    <retrieve_mode>0</retrieve_mode>
                    <request_method>0</request_method>
                    <output_format>0</output_format>
                    <allow_traps>0</allow_traps>
                    <ssl_cert_file/>
                    <ssl_key_file/>
                    <ssl_key_password/>
                    <verify_peer>0</verify_peer>
                    <verify_host>0</verify_host>
                    <master_item/>
                </item>
                <item>
                    <name>Total number of  activemq msg</name>
                    <type>0</type>
                    <snmp_community/>
                    <snmp_oid/>
                    <key>activemq.mointer[queue_sum]</key>
                    <delay>1m</delay>
                    <history>90d</history>
                    <trends>365d</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units>條</units>
                    <snmpv3_contextname/>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authprotocol>0</snmpv3_authprotocol>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privprotocol>0</snmpv3_privprotocol>
                    <snmpv3_privpassphrase/>
                    <params/>
                    <ipmi_sensor/>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>ActiveMQ</name>
                        </application>
                    </applications>
                    <valuemap/>
                    <logtimefmt/>
                    <preprocessing/>
                    <jmx_endpoint/>
                    <timeout>3s</timeout>
                    <url/>
                    <query_fields/>
                    <posts/>
                    <status_codes>200</status_codes>
                    <follow_redirects>1</follow_redirects>
                    <post_type>0</post_type>
                    <http_proxy/>
                    <headers/>
                    <retrieve_mode>0</retrieve_mode>
                    <request_method>0</request_method>
                    <output_format>0</output_format>
                    <allow_traps>0</allow_traps>
                    <ssl_cert_file/>
                    <ssl_key_file/>
                    <ssl_key_password/>
                    <verify_peer>0</verify_peer>
                    <verify_host>0</verify_host>
                    <master_item/>
                </item>
            </items>
            <discovery_rules/>
            <httptests/>
            <macros/>
            <templates/>
            <screens/>
        </template>
    </templates>
    <triggers>
        <trigger>
            <expression>{Template App ActiveMQ:activemq.mointer[pending].avg(10m)}&gt;=5</expression>
            <recovery_mode>1</recovery_mode>
            <recovery_expression>{Template App ActiveMQ:activemq.mointer[pending].avg(5m)}=0</recovery_expression>
            <name>activemq queue  pending on {HOST.NAME}</name>
            <correlation_mode>0</correlation_mode>
            <correlation_tag/>
            <url/>
            <status>0</status>
            <priority>3</priority>
            <description>activemq 消息發生阻塞,10分鐘內平均阻塞消息數超過5條</description>
            <type>0</type>
            <manual_close>0</manual_close>
            <dependencies/>
            <tags/>
        </trigger>
    </triggers>
</zabbix_export>

將該監控模板鏈接到對應的主機。

我們可以看到我們監控的數據了。

至此,ActiveMQ 的監控項都已經配置好了。

posted @ 2019-06-26 13:44 自由早晚亂余生 閱讀(...) 評論(...) 編輯 收藏
内部期期公开一波中特