Skip to content

Commit cc122c2

Browse files
author
杨红飞
committed
[Add]新增ZABBIX管理及钩子故障自愈等
1 parent 718db4e commit cc122c2

File tree

17 files changed

+1195
-6
lines changed

17 files changed

+1195
-6
lines changed

biz/application.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
# from biz.tail_data import tail_data
1818
from biz.handlers.password_handler import password_urls
1919
from biz.handlers.mycrypt_handler import mycrypt_urls
20-
20+
from biz.handlers.zabbix_mg_handler import zabbix_urls
2121

2222
class Application(myApplication):
2323
def __init__(self, **settings):
@@ -29,7 +29,7 @@ def __init__(self, **settings):
2929
urls.extend(paid_urls)
3030
urls.extend(password_urls)
3131
urls.extend(mycrypt_urls)
32-
32+
urls.extend(zabbix_urls)
3333
# Application 放一些定时任务 ,可能会导致阻塞, 放到了crontab_app里面,单独起
3434
# tailed_callback = tornado.ioloop.PeriodicCallback(tail_data, 3600000) # 一小时执行一次
3535
# tailed_callback.start()

biz/handlers/fault_mg_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def get(self, *args, **kwargs):
207207
if cache_config_info:
208208
config_info = convert(cache_config_info)
209209

210-
if not config_info['STORAGE_REGION'] and not config_info['STORAGE_REGION']:
210+
if not config_info.get('STORAGE_REGION') and not config_info.get('STORAGE_REGION'):
211211
return self.write(dict(code=-1, msg='没有发现OSS配置信息'))
212212

213213
oss_info = {

biz/handlers/zabbix_mg_handler.py

Lines changed: 541 additions & 0 deletions
Large diffs are not rendered by default.

db_sync.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from models.project_mg import Base as project_base
1313
from models.event_record import Base as event_record_base
1414
from models.paid_mg import Base as paid_base
15+
from models.zabbix_mg import Base as zabbix_base
1516
from websdk.consts import const
1617
from settings import settings as app_settings
1718
# ORM创建表结构
@@ -33,6 +34,7 @@ def create():
3334
project_base.metadata.create_all(engine)
3435
event_record_base.metadata.create_all(engine)
3536
paid_base.metadata.create_all(engine)
37+
zabbix_base.metadata.create_all(engine)
3638
print('[Success] 表结构创建成功!')
3739

3840

@@ -42,6 +44,7 @@ def drop():
4244
project_base.metadata.drop_all(engine)
4345
event_record_base.metadata.drop_all(engine)
4446
paid_base.metadata.drop_all(engine)
47+
zabbix_base.metadata.drop_all(engine)
4548

4649

4750
if __name__ == '__main__':

libs/db_context.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env python
2+
# -*-coding:utf-8-*-
3+
'''
4+
Author : SS
5+
date : 2017年10月17日17:23:19
6+
role : 数据库连接
7+
'''
8+
import sys
9+
import pymysql
10+
from urllib.parse import quote_plus
11+
from sqlalchemy import create_engine
12+
from sqlalchemy.pool import NullPool
13+
from sqlalchemy.orm import sessionmaker
14+
from websdk.consts import const
15+
16+
sys.path.append("..")
17+
from settings import settings
18+
19+
20+
def get_db_engine(db_key):
21+
databases = settings.get('databases', 0)
22+
db_conf = databases[db_key]
23+
dbuser = db_conf['user']
24+
dbpwd = db_conf['pwd']
25+
dbhost = db_conf['host']
26+
dbport = db_conf.get('port', 0)
27+
dbname = db_conf['name']
28+
return create_engine('mysql+pymysql://{user}:{pwd}@{host}:{port}/{dbname}?charset=utf8'
29+
.format(user=dbuser, pwd=quote_plus(dbpwd), host=dbhost, port=dbport, dbname=dbname),
30+
logging_name=db_key, pool_pre_ping=True) #pool_size=10 poolclass=NullPool, pool_recycle=60
31+
32+
class DBContext(object):
33+
def __init__(self, rw='r', db_key=None):
34+
self.__db_key = db_key
35+
if not self.__db_key:
36+
if rw == 'w':
37+
self.__db_key = const.DEFAULT_DB_KEY
38+
elif rw == 'r':
39+
self.__db_key = const.READONLY_DB_KEY
40+
engine = get_db_engine(self.__db_key)
41+
self.__engine = engine
42+
43+
def __enter__(self):
44+
self.__session = sessionmaker(bind=self.__engine)()
45+
return self.__session
46+
47+
def __exit__(self, exc_type, exc_val, exc_tb):
48+
self.__session.close()
49+
50+
def get_session(self):
51+
return self.__session

libs/public.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# @Time : 2019/7/4 15:44
4+
# @Author : Fred Yangxiaofei
5+
# @File : public.py
6+
# @Role : 公用的方法
7+
8+
9+
import time
10+
11+
def timestamp_to_datatime(timestamp):
12+
"""
13+
将时间戳转换成时间
14+
:param timestamp: 时间戳 int类型
15+
:return:
16+
"""
17+
if not isinstance(timestamp, int):
18+
return 'Incorrect format'
19+
# 转换成localtime
20+
time_local = time.localtime(timestamp)
21+
# 转换成新的时间格式(2016-05-05 20:28:54)
22+
data_time = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
23+
return data_time

libs/zabbix/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# @Time : 2019/7/2 13:39
4+
# @Author : Fred Yangxiaofei
5+
# @File : __init__.py.py
6+
# @Role : 说明脚本功能

libs/zabbix/get_hosts.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# @Time : 2019/7/15 9:48
4+
# @Author : Fred Yangxiaofei
5+
# @File : get_hosts.py
6+
# @Role : 获取ZABBIX监控的主机组/主机/ID等信息
7+
8+
from libs.zabbix.zabbix_api import ZabbixAPI
9+
from libs.db_context import DBContext
10+
from models.zabbix_mg import ZabbixConfig, model_to_dict
11+
import fire
12+
13+
14+
class GetZabbixHosts():
15+
def __init__(self, zabbix_url, zabbix_user, zabbix_password):
16+
self.zabbix_url = zabbix_url
17+
self.zabbix_user = zabbix_user
18+
self.zabbix_password = zabbix_password
19+
self.zapi = self.login()
20+
21+
def login(self):
22+
zapi = ZabbixAPI(self.zabbix_url)
23+
zapi.login(self.zabbix_user, self.zabbix_password)
24+
return zapi
25+
26+
def get_all_hostgroups(self):
27+
"""
28+
获取所有主机组
29+
:return:
30+
"""
31+
zabbix_all_hostgroups = self.zapi.hostgroup.get(output='extend')
32+
return zabbix_all_hostgroups
33+
34+
def get_hostgroup_hostinfo(self, all_host_group_info):
35+
"""
36+
获取单个组下所有的主机信息
37+
:param all_host_group_info: 所有主机组信息
38+
:return:
39+
"""
40+
41+
for g in all_host_group_info:
42+
if g:
43+
group_name = g['name']
44+
group_id = g['groupid']
45+
hostid_in_group_list = self.zapi.host.get(output=['hostid', 'name'], groupids=group_id)
46+
if hostid_in_group_list:
47+
for h in hostid_in_group_list:
48+
zabbix_group_data = {
49+
"zabbix_url": self.zabbix_url,
50+
"group_id": group_id,
51+
"group_name": group_name,
52+
"host_id": h['hostid'],
53+
"host_name": h['name']
54+
}
55+
yield zabbix_group_data
56+
# print(group_name, g['groupid'],h['hostid'], h['name'])
57+
58+
59+
def get_zabbix_configs():
60+
"""
61+
从数据库里面看下用户有几个监控
62+
:return:
63+
"""
64+
zabbix_configs_list = []
65+
66+
with DBContext('w') as session:
67+
zabbix_config_info = session.query(ZabbixConfig).all()
68+
for data in zabbix_config_info:
69+
data_dict = model_to_dict(data)
70+
zabbix_configs_list.append(data_dict)
71+
return zabbix_configs_list
72+
73+
74+
def main():
75+
zabbix_generator_list = [] # 每一组ZABBIX的信息都返回出来一个generator
76+
zabbix_configs_list = get_zabbix_configs()
77+
for zabbix_data in zabbix_configs_list:
78+
zabbix_url = zabbix_data.get('zabbix_url')
79+
zabbix_username = zabbix_data.get('zabbix_username')
80+
zabbix_password = zabbix_data.get('zabbix_password')
81+
obj = GetZabbixHosts(zabbix_url, zabbix_username, zabbix_password)
82+
all_hostgroups_list = obj.get_all_hostgroups()
83+
zabbix_group_data = obj.get_hostgroup_hostinfo(all_hostgroups_list)
84+
zabbix_generator_list.append(zabbix_group_data)
85+
86+
return zabbix_generator_list
87+
88+
89+
if __name__ == '__main__':
90+
fire.Fire(main)

libs/zabbix/get_issues.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# @Time : 2019/7/2 13:53
4+
# @Author : Fred Yangxiaofei
5+
# @File : get_issues.py
6+
# @Role : 获取Zabbix报警信息
7+
8+
9+
from libs.zabbix.login import zabbix_login
10+
from libs.public import timestamp_to_datatime
11+
from libs.db_context import DBContext
12+
from models.zabbix_mg import ZabbixConfig, model_to_dict
13+
import fire
14+
15+
16+
def get_last_issues(zabbix_url, zabbix_user, zabbix_password):
17+
"""
18+
获取最近的ISSUES 没有确认的报警
19+
:return:
20+
"""
21+
try:
22+
zapi = zabbix_login(zabbix_url, zabbix_user, zabbix_password)
23+
unack_triggers = zapi.trigger.get(
24+
only_true=1,
25+
skipDependent=1,
26+
monitored=1,
27+
active=1,
28+
output='extend',
29+
expandDescription=1,
30+
selectHosts=['host'],
31+
withLastEventUnacknowledged=1, )
32+
# print(unack_triggers)
33+
last_issues_list = []
34+
for t in unack_triggers:
35+
issues_data = dict()
36+
issues_data['host'] = t['hosts'][0].get('host')
37+
issues_data['issue'] = t.get('description')
38+
issues_data['last_change'] = timestamp_to_datatime(int(t.get('lastchange')))
39+
issues_data['level'] = t.get('priority')
40+
last_issues_list.append(issues_data)
41+
42+
return last_issues_list
43+
44+
except Exception as e:
45+
print(e)
46+
# 错误,拿不到数据,返回一个空列表出去
47+
return []
48+
49+
50+
def get_zabbix_configs():
51+
"""
52+
从数据库里面看下用户有几个监控
53+
:return:
54+
"""
55+
zabbix_configs_list = []
56+
57+
with DBContext('w') as session:
58+
zabbix_config_info = session.query(ZabbixConfig).all()
59+
for data in zabbix_config_info:
60+
data_dict = model_to_dict(data)
61+
zabbix_configs_list.append(data_dict)
62+
return zabbix_configs_list
63+
64+
65+
def main():
66+
zabbix_last_issues = []
67+
zabbix_configs_list = get_zabbix_configs()
68+
69+
for zabbix_data in zabbix_configs_list:
70+
zabbix_url = zabbix_data.get('zabbix_url')
71+
zabbix_username = zabbix_data.get('zabbix_username')
72+
zabbix_password = zabbix_data.get('zabbix_password')
73+
zdata = get_last_issues(zabbix_url, zabbix_username, zabbix_password)
74+
# 2个列表合成一个list
75+
zabbix_last_issues += zdata
76+
return zabbix_last_issues
77+
78+
79+
if __name__ == '__main__':
80+
fire.Fire(main)

libs/zabbix/login.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# @Time : 2019/7/8 10:24
4+
# @Author : Fred Yangxiaofei
5+
# @File : login.py
6+
# @Role : 测试登陆
7+
8+
9+
from libs.zabbix.zabbix_api import ZabbixAPI
10+
11+
12+
def zabbix_login(zabbix_url, zabbix_user, zabbix_password):
13+
zapi = ZabbixAPI(zabbix_url)
14+
zapi.login(zabbix_user, zabbix_password)
15+
return zapi
16+
17+
18+
if __name__ == '__main__':
19+
pass

0 commit comments

Comments
 (0)