编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Django自研告警平台-让告警排好队

wxchong 2024-07-23 21:38:19 开源技术 53 ℃ 0 评论

Django简介

Django是一个开放源代码的Web应用框架,由Python写成。采用了MTV的框架模式,即模型M,视图V和模版T。它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内容为主的网站的,即是CMS(内容管理系统)软件。

Django环境安装

操作系统要求

Centos7.5以上

1、安装python3和pip3

版本信息:Python-3.8.0a1和pip-20.0.2

2、安装Django

版本信息:Django-3.0.3(注:离线环境可能需要sqlparse 0.3.0、pytz 2019.3、asgiref 3.2.3等安装包,下载地址:https://pypi.org/search)

3、Sqlite3升级

版本信息:sqlite-autoconf-3280000

4、安装psycopg2

版本信息:psycopg2-2.8.4(注:确认centos已安装postgresql-devel)

5、安装uwsgi

版本信息:uwsgi-2.0.18

对接alertmanager

alertmanager配置:
alertmanager.yml

global:
  resolve_timeout: 5m
route:
  group_by: ['alertname','severity','hosttype']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 1h
  receiver: 'webhook'
receivers:
- name: 'webhook'
  webhook_configs:
  - url: 'http://localhost:9999/receivefromprometheus/'

Django接收告警信息功能模块:

receivefromprometheus.py

# -*- coding: utf-8 -*-
from PgModel.models import Warn_Info,Warn_List #引用定义好的表对象
from django.http import HttpResponse
from django.shortcuts import render
import datetime
import pytz
import logging
import json
from . import selectpg
from django.core import serializers
from . import modelcontrol
models = [Warn_Info,Warn_List]
def receivefromprometheus(request):
    postBody=request.body #接收alertmanager消息体,一般为json格式
    data= json.loads(postBody) #将json格式消息体转换为字典
    f = open('/opt/test.txt', 'a+') #记录消息体,方便问题跟踪,及确认解析方法
    current_time=datetime.datetime.now()
    f.write(datetime.datetime.strftime(current_time,'%Y-%m-%d %H:%M:%S')+'\n')
    for var in data.get("alerts"): #结构化alertmanager消息体
        warn_status=var['status']
        warn_id=var['annotations']['warnid']
        warn_id_foreign=Warn_Info.objects.get(id=warn_id)
        current_value=var['annotations']['value']
        f.write(warn_status+'\n')           
        warnlist=Warn_List.objects.filter(warn_id=warn_id,warn_status='firing')
        if warn_status=='firing' and len(warnlist)==0:  #如果消息体为预警状态,判断之前未存在未恢复同类告警,则插入告警信息
            warnlistadd=Warn_List(current_value=current_value,warn_id=warn_id_foreign,warn_status=warn_status)
            warnlistadd.save()
        elif warn_status=='resolved' and len(warnlist)>0: #如果消息体为恢复状态,判断之前存在未恢复同类告警,则更新告警状态
            warnlist.update(warn_status='resolved',end_time=current_time)
        elif warn_status=='firing' and len(warnlist)>0: #如果消息体为恢复状态,判断之前存在未恢复同类告警,则更新告警当前值
            warnlist.update(current_value=current_value,end_time=current_time)
    f.close()
    return HttpResponse('success')

效果展示

左侧目录树包含四类告警类型,子菜单为监控主机IP,主机下挂对应的告警指标,如CPU、内存等。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表