prometheus + alertmanager + PrometheusAlert实现告警

news2024/9/30 19:21:55

prometheus 收集监控数据
alertmanager 制定告警路由
PrometheusAlert 连通告警webhook

一、prometheus配置

https://prometheus.io/download/

1.1、prometheus安装

包的下载直接wget就行,放在data目录下,解压后在prometheus目录下创建config和rule目录
配置了热重启,可按需配置数据保存天数

cat >/etc/systemd/system/prometheus.service<<EOF
[Unit]
Description=Prometheus Service
Wants=network-online.target
After=network-online.target

[Service]
User=root
Group=root
Type=simple
ExecStart=/data/prometheus/prometheus --config.file=/data/prometheus/prometheus.yml --web.enable-lifecycle  --storage.tsdb.path=/data/prometheus/data
Restart=on-failure

[Install]
WantedBy=multi-user.target

1.2、prometheus配置文件

相同job使用了锚点省略一些重复配置,blackbox监控业务url

root@prometheus-monitor-c210:/data/prometheus# cat prometheus.yml 
# my global config
global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
           - 10.198.199.210:9093
rule_files:
  - "/data/prometheus/rules/*.yaml"
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:9090"]
  - job_name: 'node-exporter-ops'
    file_sd_configs:
    - files:
      - ./config/node-ops.yml
    relabel_configs: &node_relabel_configs
    - source_labels: [__address__]
      regex: (.*)
      target_label: instance
      replacement: $1
    - source_labels: [__address__]
      regex: (.*)
      target_label: __address__
      replacement: $1:9100
  - job_name: 'node-exporter-rd'
    file_sd_configs:
    - files:
      - ./config/node-rd.yml
    relabel_configs: *node_relabel_configs



  - job_name: 'blackbox'
    metrics_path: /probe
    params:
      module: [http_2xx]  # 使用的探测模块
    static_configs:
      - targets:
        - https://test-1254308391.cos.ap-beijing.myqcloud.com
        - https://www.baidu.com
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: service_url
      - target_label: __address__
        replacement: 10.198.199.28:9115  # Blackbox Exporter 的地址和端口

1.3、主机配置

主机配置文件放在config目录下,上面prometheus文件读取这个目录下的文件,而不是直接将target写在prometheus文件中
这些主机名配置在hosts文件中,aws可以使用route53私有托管

$ cat config/node-ops.yml 
- labels:
    service: node-ops
  targets:
  - sin-ops-logging-monitor-c210 
  - sin-ops-cicd-archery-c10

1.4、role配置

role都配置在统一目录

$ cat blackbox.yaml 
groups:
  - name: blackbox-trace
    rules:
    - alert: web服务超时了
      expr: probe_http_status_code{job="blackbox"} == 0
      for: 2m
      labels:
        severity: critical
        service: probe-service
      annotations:
        title: 'Service timeout ({{ $labels.service_url }}'
        description: "Service timeout ({{ $labels.service_url }})"

node-baseic role

$ cat node-basic-monitor.yaml 
groups:
  - name: node-basic-monitor
    rules:
    - alert: 主机宕机了
      expr: up{job=~"node-exporter.+"} == 0
      for: 0m
      labels:
        severity: critical
        service: node-basic
      annotations:
        title: 'Instance down'
        description: "主机: 【{{ $labels.instance }}】has been down for more than 1 minute"
    - alert: 服务器已重新启动
      expr: (node_time_seconds - node_boot_time_seconds) / 60 <3
      for: 0m
      labels:
        severity: warning
        service: node-basic
      annotations:
        title: '服务器已重新启动'
        description: "主机: 【{{ $labels.instance }}】刚刚启动,请检查服务状态"
    - alert: socket数量超预期
      expr: node_sockstat_TCP_alloc >25000
      for: 2m
      labels:
        severity: critical
        service: node-basic
      annotations:
        title: 'socket数量超预期'
        description: "主机: 【{{ $labels.instance }}】socket(当前值:{{ $value }})"
# ops cpu内存告警
    - alert: CPU使用率到达%90
      expr: (1-((sum(increase(node_cpu_seconds_total{mode="idle"}[5m])) by (instance))/ (sum(increase(node_cpu_seconds_total[5m])) by (instance))))*100 > 90
      for: 5m
      annotations:
        title: "CPU使用率到达%90"
        description: "主机: 【{{ $labels.instance }}】 5分钟内CPU使用率超过90% (当前值: {{ printf \"%.2f\" $value }}%)"
      labels:
        severity: 'critical'
        service: node-basic  
    - alert: 内存使用率到达%90
      expr: (1-((node_memory_Buffers_bytes + node_memory_Cached_bytes + node_memory_MemFree_bytes)/node_memory_MemTotal_bytes))*100 >90
      for: 3m
      annotations:
        title: "主机内存使用率超过90%"
        description: "主机: 【{{ $labels.instance }}】 内存使用率超过90% (当前使用率:{{ humanize $value }}%)"
      labels:
        severity: 'critical'
        service: node-basic

    - alert: 磁盘空间剩余%15
      expr: (1-(node_filesystem_free_bytes{fstype=~"ext4|xfs",mountpoint!~".*tmp|.*boot"}/node_filesystem_size_bytes{fstype=~"ext4|xfs",mountpoint!~".*tmp|.*boot",service!~"benchmark" }))*100 > 90
      for: 1m
      annotations:
        title: "磁盘空间剩余%15"
        description: "主机: 【{{ $labels.instance }}】 {{ $labels.mountpoint }}分区使用率超过85%, 当前值使用率:{{ $value }}%"
      labels:
        severity: 'critical'
        service: node-basic
    - alert: 主机ESTABLISHED连接数
      expr:  sum(node_netstat_Tcp_CurrEstab{instance!~"benchmark.+"}) by (instance) > 1000
      for: 10m
      labels:
        severity: 'warning'
        service: node-basic
      annotations:
        title: "主机ESTABLISHED连接数过高"
        description: "主机: 【{{ $labels.instance }}】 ESTABLISHED连接数超过1000, 当前ESTABLISHED连接数: {{ $value }}"
    - alert: 主机TIME_WAIT数量
      expr:  sum(node_sockstat_TCP_tw{instance!~"benchmark.+"}) by (instance) > 6500
      for: 1h
      labels:
        severity: 'warning'
        service: node-basic
      annotations:
        title: "主机TIME_WAIT连接数过高"
        description: "主机: 【{{ $labels.instance }}】 TIME_WAIT连接数超过6500, 当前TIME_WAIT连接数持续一小时: {{ $value }}"
    - alert: 主机网卡出口流量过高于150MB/s
      expr: sum by (instance, device) (rate(node_network_transmit_bytes_total{device=~"ens.*"}[2m])) / 1024 / 1024 > 150
      for: 20m
      labels:
        severity: 'critical'
        service: node-basic
      annotations:
        title: "主机网卡出口流量高于100MB/s"
        description: "主机: 【{{ $labels.instance }}】, 网卡: {{ $labels.device }} 出口流量超过 (> 100 MB/s), 当前值: {{ $value }}"
    - alert: 主机磁盘写入速率过高
      expr: sum by (instance, device) (rate(node_disk_written_bytes_total{device=~"nvme.+"}[2m])) / 1024 / 1024 > 150
      for: 10m
      labels:
        severity: 'critical'
        service: node-basic
      annotations:
        title: "主机磁盘写入速率过高"
        description: "主机: 【{{ $labels.instance }}】, 磁盘: {{ $labels.device }} 写入速度超过(100 MB/s), 当前值: {{ $value }}"
  
    - alert: 主机分区Inode不足
      expr: node_filesystem_files_free{fstype=~"ext4|xfs",mountpoint!~".*tmp|.*boot" } / node_filesystem_files{fstype=~"ext4|xfs",mountpoint!~".*tmp|.*boot" } * 100 < 10
      for: 2m
      labels:
        severity: 'warning'
        service: node-basic
      annotations:
        title: "主机分区Inode节点不足"
        description: "主机: 【{{ $labels.instance }}】 {{ $labels.mountpoint }}分区inode节点不足 (可用值小于{{ $value }}%)"
    - alert: 主机磁盘Read延迟高
      expr: rate(node_disk_read_time_seconds_total{device=~"nvme.+"}[1m]) / rate(node_disk_reads_completed_total{device=~"nvme.+"}[1m]) > 0.1 and rate(node_disk_reads_completed_total{device=~"nvme.+"}[1m]) > 0
      for: 2m
      labels:
        severity: 'warning'
        service: node-basic
      annotations:
        title: "主机磁盘Read延迟过高"
        description: "主机: 【{{ $labels.instance }}】, 磁盘: {{ $labels.device }} Read延迟过高 (read operations > 100ms), 当前延迟值: {{ $value }}ms"
  
    - alert: 主机磁盘Write延迟过高
      expr: rate(node_disk_write_time_seconds_total{device=~"nvme.+"}[1m]) / rate(node_disk_writes_completed_total{device=~"nvme.+"}[1m]) > 0.1 and rate(node_disk_writes_completed_total{device=~"nvme.+"}[1m]) > 0
      for: 2m
      labels:
        severity: 'warning'
        service: node-basic
      annotations:
        title: "主机磁盘Write延迟过高"
        description: "主机: 【{{ $labels.instance }}】, 磁盘: {{ $labels.device }} Write延迟过高 (write operations > 100ms), 当前延迟值: {{ $value }}ms"
    - alert: 服务器负载高
      expr: (node_load1{instance !~ "sin-cicd-DRONE_.+"} / count without (cpu, mode) (node_cpu_seconds_total{mode="system"})) > 1
      for: 30m
      labels:
        severity: warning
        service: node-basic
      annotations:
        title: 服务器负载高
        description: "{{ $labels.instance }} 每颗cpu的平均负载到达 {{ $value }} "

1.5、热加载

curl -X POST http://localhost:9090/-/reload

二、alertmanager配置

2.1、alertmanager安装

安装到/data下,配置systemd启动

cat >/etc/systemd/system/alertmanager.service<<EOF
[Unit]
Description=Alertmanager Service
Wants=network-online.target
After=network-online.target

[Service]
User=root
Group=root
Type=simple
ExecStart=/data/alertmanager/alertmanager --config.file=/data/alertmanager/alertmanager.yml
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

2.2、alertmanager配置文件

这里的808是PrometheusAlert提供的webhook端口,三种不同级别的告警通知到三个机器人

cat alertmanager.yml 
global:
  resolve_timeout: 1m
route:
  receiver: 'default'
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 30m
  routes:
  - receiver: 'node-critical'
    group_wait: 10s 
    continue: true
    matchers:
      - 'service=~"node-basic|probe-service"'
      - 'severity="critical"'
  - receiver: 'node-warning'
    group_wait: 10s
    continue: true
    matchers:
      - 'service=~"node-basic"'
      - 'severity="warning"'
receivers:
  - name: 'default'
    webhook_configs:
    - url: 'http://127.0.0.1:8080/prometheusalert?type=fs&tpl=prometheus-fs&fsurl=https://open.feishu.cn/open-apis/bot/v2/hook/9264abcdc9c5'
      send_resolved: true
  - name: 'node-critical'
    webhook_configs:
    - url: 'http://127.0.0.1:8080/prometheusalert?type=fs&tpl=prometheus-fs&fsurl=https://open.feishu.cn/open-apis/bot/v2/hook/2fc0f6048e0'
      send_resolved: true
  - name: 'node-warning'
    webhook_configs:
    - url: 'http://127.0.0.1:8080/prometheusalert?type=fs&tpl=prometheus-fs&fsurl=https://open.feishu.cn/open-apis/bot/v2/hook/74dbb053ae33'
      send_resolved: true
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']

三、PrometheusAlert配置

拉包https://github.com/feiyu563/PrometheusAlert
启动后配置模板

3.1、模板配置

我这里是飞书通知,所以修改飞书的模板
在这里插入图片描述

{{ range $k,$v:=.alerts }}{{if eq $v.status "resolved"}}<font color="green">**{{$v.labels.service}}恢复信息**</font>
事件: **{{$v.labels.alertname}}**
告警类型:{{$v.status}}
告警级别: {{$v.labels.severity}}
开始时间: {{GetCSTtime $v.startsAt}}
结束时间: {{GetCSTtime $v.endsAt}}
主机: {{$v.labels.instance}}
服务组: {{$v.labels.service}}
<font color="green">**事件详情: {{$v.annotations.description}}**</font>
{{else}}**{{$v.labels.service}}告警**
事件: **{{$v.labels.alertname}}**
告警类型:{{$v.status}}
告警级别: {{$v.labels.severity}}
开始时间: {{GetCSTtime $v.startsAt}}
主机: {{$v.labels.instance}}
服务组: {{$v.labels.service}}
<font color="red">**事件详情: {{$v.annotations.description}}**</font>
{{end}}
{{ end }}

优化了一下告警内容,我这里使用prometheus-fsv2发送报错,只能用v1发送,暂时没考虑k8s发送告警

3.2、优化告警标题

https://github.com/feiyu563/PrometheusAlert/blob/master/controllers/prometheusalert.go
重新定义告警Title的值,默认是配置文件指定的,但任何告警都是一个标题

        } else {
                json.Unmarshal(c.Ctx.Input.RequestBody, &p_json)
                //针对prometheus的消息特殊处理
                json.Unmarshal(c.Ctx.Input.RequestBody, &p_alertmanager_json)
        }
//大概113行
        title := p_alertmanager_json["alerts"].([]interface{})[0].(map[string]interface{})["labels"].(map[string]interface{})["alertname"].(string)

        // alertgroup
        alertgroup := c.Input().Get("alertgroup")
        openAg := beego.AppConfig.String("open-alertgroup")
        var agMap map[string]string
        if openAg == "1" && len(alertgroup) != 0 {
                agMap = Alertgroup(alertgroup)
        }

更新完之后打个包启动

告警效果如下
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2180491.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

聊一聊 C#中有趣的 SourceGenerator生成器

一&#xff1a;背景 1. 讲故事 前些天在看 AOT的时候关注了下 源生成器&#xff0c;挺有意思的一个东西&#xff0c;今天写一篇文章简单的分享下。 二&#xff1a;源生成器探究之旅 1. 源生成器是什么 简单来说&#xff0c;源生成器是Roslyn编译器给程序员开的一道口子&am…

vxe-grid给单元格加上触发事件

效果&#xff1a;输入框的双击事件(其他事件可以由此替换) 代码 // gridTableOptions是每列的配置项 <vxe-grid v-bind"gridTableOptions" :data"goodsList" ref"xTable">// edit_spbh 是对应的样式名&#xff0c;是写在gridTableOption…

如何通过日志快速定位TTS的缓存放音文件(mod_cti基于FreeSWITCH)

文章目录 前言联系我们分析过程1. 测试话术&#xff0c;记录日志2. 关键词搜索 前言 顶顶通呼叫中心中间件在运行话术时&#xff0c;如果有通过TTS合成的语音&#xff0c;会被freeswitch缓存在目录中&#xff1a;/ddt/fs/storage/http_file_cache。 我们可以分析freeswitch日志…

学习Webpack中图片-JS-Vue-plugin

目录 图片文件资源模块类型 JS文件babel命令行使用babel-loaderbabel-preset Vue文件vue-loadervue/compiler-sfc pluginCleanWebpackPluginHtmlWebpackPluginDefinePlugin 图片文件 需要先在项目中使用图片&#xff0c;比较常见的使用图片的方式是两种&#xff1a; img元素&…

LeetCode 918. 环形子数组的最大和

原题链接&#xff1a;. - 力扣&#xff08;LeetCode&#xff09; 给定一个长度为 n 的环形整数数组 nums &#xff0c;返回 nums 的非空 子数组 的最大可能和 。 环形数组 意味着数组的末端将会与开头相连呈环状。形式上&#xff0c; nums[i] 的下一个元素是 nums[(i 1) % n…

基于STM32的智能室内空气质量监控系统

目录 引言项目背景环境准备 硬件准备软件安装与配置系统设计 系统架构关键技术代码示例 传感器数据采集与处理空气质量分析与报警显示与数据记录功能应用场景结论 1. 引言 智能室内空气质量监控系统用于实时监测环境中的空气质量&#xff0c;通过检测空气中的CO2、PM2.5、温…

软件测试学习笔记丨Pytest 学习指南

本文转自测试人社区&#xff0c;原文链接&#xff1a;https://ceshiren.com/t/topic/32336 基本介绍 pytest框架是一个成熟&#xff0c;全面的测试框架&#xff0c;具有非常丰富的第三方插件&#xff0c;并且可以自定义扩展 比如&#xff1a;pytest-selenium , pytest-html ,…

Git常用方法——详解

一、下载安装git git官网&#xff1a; Git - Downloads (git-scm.com) 下载安装Git&#xff08;超详细超简单&#xff09;_git下载-CSDN博客 二、克隆下载至本地 1、复制HTTPS链接 在gitee或者gitLab或者gitHub上复制HTTPS链接 2、打开Open Git Bash here 在本地想要新建文…

小程序原生-列表渲染

1. 列表渲染的基础用法 <!--渲染数组列表--> <view wx:for"{{numList}}" wx:key"*this" > 序号&#xff1a;{{index}} - 元素&#xff1a;{{item}}</view> <!--渲染对象属性--> <view wx:for"{{userInfo}}" wx:key&q…

怎么给视频加片头片尾和字幕

在这个视觉内容爆炸的时代&#xff0c;一段精心制作的视频不仅能吸引眼球&#xff0c;更能传达深刻的情感与信息。而一个引人入胜的片头、一个温馨感人的片尾&#xff0c;以及恰到好处的字幕&#xff0c;无疑是提升视频质感的关键。那么新人要怎么给视频加片头片尾和字幕效果呢…

2024年9月收评

金1是从2005年12月开始&#xff0c;到现在2024年5月&#xff0c;还差7个月整整20年。一共11轮。 这20年里&#xff0c;真正形成单边趋势&#xff0c;能较好获利或者说至少不亏损的一共有以下几次&#xff0c; 第1轮&#xff0c;第2轮&#xff0c;第7轮&#xff0c;第8轮&…

《程序猿之Redis缓存实战 · 集合类型》

&#x1f4e2; 大家好&#xff0c;我是 【战神刘玉栋】&#xff0c;有10多年的研发经验&#xff0c;致力于前后端技术栈的知识沉淀和传播。 &#x1f497; &#x1f33b; CSDN入驻不久&#xff0c;希望大家多多支持&#xff0c;后续会继续提升文章质量&#xff0c;绝不滥竽充数…

基于微信小程序的商品展示+ssm论文ppt源码调试讲解

2 系统开发环境 2.1微信开发者工具 微信开发者工具现在已经被小程序开发团队开发运行&#xff0c;目前微信开发者工具任然在不断的完善中&#xff0c;在开发小程序时经常要不断的更新。可以使用微信扫码登陆开发者工具&#xff0c;开发者工具将使用这个微信帐号的信息进行小程…

为VRoidStudio制作的vrm格式模型制作blendshape

零、效果展示 bs视频演示 一、准备相关插件 1、VRoidStudio&#xff08;免费&#xff09; 下载网址&#xff1a;https://vroid.com/en/studio 2、UniVRM&#xff08;免费&#xff09; 下载网址&#xff1a;https://github.com/vrm-c/UniVRM/releases 注意&#xff1a;unity…

Qt --- 常用控件的介绍---Widget属性介绍

一、控件概述 编程&#xff0c;讲究的是站在巨人的肩膀上&#xff0c;而不是从头发明轮子。一个图形化界面上的内容&#xff0c;不需要咱们全都从零区实现&#xff0c;Qt中已经提供了很多内置的控件了&#xff08;按钮&#xff0c;文本框&#xff0c;单选按钮&#xff0c;复选…

yolov8实例分割重要图片

训练分割要准备好数据集和分割预训练权重文件 下面这张图是数据集的格式 下面这张图配置数据集&#xff0c;下面names 要和labelme转txt里配置的一样 下面这张图进行训练&#xff0c;配置一些全局参数 &#xff0c;初始的yolov8s-seg.pt文件需要到github上yolov8开源项目里下 l…

linux部署redis,整合ansible和redis

准备服务器192.168.45.133&#xff0c;192.168.45.135 在135上执行命令yum install -y redis安装redis yum install -y redis 源码安装方法 wget http://download.redis.io/releases/redis-2.8.13.tar.gz tar zxf redis-2.8.13.tar.gz cd redis-2.8.13 make PREFIX/usr/loca…

Cannon-es.js之Distance Constrait模拟布料

本文目录 前言1、Particle2、前置代码准备2.1 代码2.2 效果 3、使用距离约束模拟布料3.1 代码3.2 效果 前言 在现代Web开发中&#xff0c;实现逼真的物理效果对于提升用户体验至关重要。Cannon-es.js&#xff0c;作为Cannon.js的ES6模块版本&#xff0c;凭借其轻量级、高性能和…

selenium测试框架快速搭建详解

一、介绍 Selenium目前主流的web自动化测试框架&#xff1b;支持多种编程语言Java、pythan、go、js等&#xff1b;selenium 提供一系列的api 供我们使用&#xff0c;因此在web测试时我们要点页面中的某一个按钮&#xff0c;那么我们只需要获取页面&#xff0c;然后根据id或者n…

拯救华为秘盒M310

这个盒子当年宣传得比较厉害&#xff0c; 当时确实也没有什么可选的&#xff0c;当年是高价入的,这个盒子有二切一的hdmi切换功能&#xff0c; 这点从今天来看&#xff0c; 都是一个亮点 华为秘盒M310是一款小巧但功能强大的网络机顶盒。它搭载了基于安卓系统的操作平台&#x…