zabbix monitor docker

# Upcoming 

There are two unresolved problems,

A zabbix template automatically discovers complex filtering rules, the graphical display of the automatic discovery cannot be seen, and the automatically discovered item cannot be seen  in the host in the  application cluster.

Second, grafana is similar to the automatic network discovery graphic display, Variables:

$ net *.Network interfaces.*

  I have not fully grasped the way of writing.

 

------------------------------------- Start the topic zabbix monitoring docker:

Monitoring script description: The
first solution is to use docker's python version of the api, and then encapsulate a custom script by yourself, which is a bit more troublesome, but can achieve personal customization effects.
The second is to use the packaged template to do it, which is simple and saves things, but the functions are limited, and more functions still need to be developed by writing scripts.
Start to configure
Install the module docker-py
pip install docker-py for
specific usage see: https://docker-py.readthedocs.io/en/stable/
The following starts to write a script for automatically discovering docker containers, the following operations are performed on the zabbix_agent side . There are also two types, one is shell script and the other is python script. The
script is generally placed here /etc/zabbix/script (a new script directory is created)
# cat /etc/zabbix/script/docker_discovery.sh
#!/bin /bash
docker() {             port=($(sudo docker ps -a|grep -v "CONTAINER ID"|awk'{print $NF}'))             printf'{\n'             printf'\t"data":[ \n'                for key in ${!port[@]}                    do





                       if [[ "${#port[@]}" -gt 1 && "${key}" -ne "$((${#port[@]}-1))" ]];then
                          printf '\t {\n'
                          printf "\t\t\t\"{#CONTAINERNAME}\":\"${port[${key}]}\"},\n"
 
                     else [[ "${key}" -eq "((${#port[@]}-1))" ]]
                          printf '\t {\n'
                          printf "\t\t\t\"{#CONTAINERNAME}\":\"${port[${key}]}\"}\n"
 
                       fi
               done
 
                          printf '\t ]\n'
                          printf '}\n'
}
case $1 in
docker)
docker
;;
*)
echo "Usage:`basename $0` {docker}"
;;
esac
The second script I use:
#cat /etc/zabbix/script/docker_discovery.py

#!/usr/bin/env python
import os
import simplejson as json
t=os.popen("""sudo docker ps |grep -v 'CONTAINER ID'|awk {'print $NF'} """)
container_name = []
for container in  t.readlines():
         r = os.path.basename(container.strip())
         container_name += [{'{#CONTAINERNAME}':r}]
print json.dumps({'data':container_name},sort_keys=True,indent=4,separators=(',',':'))


It is recommended to use the second type of script to execute the above script. You need to install the module first and give the execution permission
pip install simplejson
chmod 757 docker_discovery.py
chown zabbix :zabbix /etx/zabbix/script -R
Give zabbix permission, edit /etc/sudoers, add The following content
zabbix ALL=(root) NOPASSWD: ALL #May have more permissions
or
zabbix ALL=(root) NOPASSWD:/usr/bin/docker,/usr/bin/python,/etc/zabbix/script/docker_discovery.py, /etc/zabbix/script/docker_minion.py #This way of writing is more specific.
Add a configuration file, which is placed in /etc/zabbix/zabbix_agentd.d/, as follows
#cat
docker_discovery.conf UserParameter=docker_discovery,python /etc/zabbix /script/docker_discovery.py
UserParameter=docker_discovery[*],python /etc/zabbix/script/docker_discovery.sh $1
test:
[root@localhost zabbix_agentd.d]# zabbix_get -s 127.0.0.1 -k docker_discovery
{     "data":[         {             "{#CONTAINERNAME}":"slave2"         },         {             "{#CONTAINERNAME}":"slave1"         },         {             "{#CONTAINERNAME}":"master"         }     ] } That’s it . Another script monitors the various states in the container. As follows: #cat /etc/zabbix/script/docker_minion.py














#!/usr/bin/env python
import docker
import sys
import subprocess
import os
def check_container_stats(container_name,collect_item):
    #docker_client = docker_client.containers.get(container_name)
    container_collect=docker_client.containers.get(container_name).stats(stream=True)
    old_result=eval(container_collect.next())
    new_result=eval(container_collect.next())
    container_collect.close()
    if collect_item == 'cpu_total_usage':
        result=new_result['cpu_stats']['cpu_usage']['total_usage'] - old_result['cpu_stats']['cpu_usage']['total_usage']
    elif collect_item == 'cpu_system_usage':
         result=new_result['cpu_stats']['system_cpu_usage'] - old_result['cpu_stats']['system_cpu_usage']
    elif collect_item == 'cpu_percent':
        cpu_total_usage=new_result['cpu_stats']['cpu_usage']['total_usage'] - old_result['cpu_stats']['cpu_usage']['total_usage']
        cpu_system_uasge=new_result['cpu_stats']['system_cpu_usage'] - old_result['cpu_stats']['system_cpu_usage']
        cpu_num=len(old_result['cpu_stats']['cpu_usage']['percpu_usage'])
        result=round((float(cpu_total_usage)/float(cpu_system_uasge))*cpu_num*100.0,2)
    elif collect_item == 'mem_usage':
        result=new_result['memory_stats']['usage']
    elif collect_item == 'mem_limit':
        result=new_result['memory_stats']['limit']
    elif collect_item == 'network_rx_bytes':
        result=new_result['networks']['eth0']['rx_bytes']
    elif collect_item == 'network_tx_bytes':
        result=new_result['networks']['eth0']['tx_bytes']
    elif collect_item == 'mem_percent':
        mem_usage=new_result['memory_stats']['usage']
        mem_limit=new_result['memory_stats']['limit']
        result=round(float(mem_usage)/float(mem_limit)*100.0,2)
    return result
if __name__ == "__main__":
    docker_client = docker.DockerClient(base_url='unix://var/run/docker.sock', version='1.27')
    container_name=sys.argv[1]
    collect_item=sys.argv[2]
    print check_container_stats(container_name,collect_item)



Grant script permissions: chmod 757 docker_discovery.py
chmod 757 docker_minion.py
Add a configuration file, which is placed in /etc/zabbix/zabbix_agentd.d/, as follows
cat docker_status.conf
UserParameter=docker_status[*],sudo /usr/bin /python /etc/zabbix/script/docker_monitor.py $1 $2
First test:
[root@localhost zabbix_agentd.d]# zabbix_get -s 127.0.0.1 -k docker_status[master,cpu_percent]
1.4
This means success.

Make a template:

Final Results

The template I made: https://github.com/fungitive/zabbix_template/blob/master/Template_Discovery_Docker.xml

Refer to the article: https://blog.csdn.net/yang00322/article/details/77895301

Guess you like

Origin blog.csdn.net/yuezhilangniao/article/details/112799013