golang自托管脚本化告警管理插件Balerter的使用

Golang自托管脚本化告警管理插件Balerter的使用

Balerter是一个基于脚本的告警系统,它允许您:

  • 从不同数据源(Prometheus、Clickhouse、Postgres、外部HTTP API等)获取所需数据
  • 分析数据并做出关于告警状态的决策
  • 更改告警状态并接收相关通知

Balerter Logo

这是一个正在积极开发的项目。在v1.0.0版本之前,任何功能都可能会有破坏性变更

通知渠道支持

  • Slack
  • Telegram
  • Syslog
  • 桌面通知
  • 电子邮件
  • Discord
  • Webhook
  • Prometheus Alertmanager
  • Prometheus AlertmanagerReceiver
  • Twilio Voice(电话呼叫)

数据源支持

  • Clickhouse
  • Prometheus
  • Postgres
  • MySQL
  • Loki
  • 任何使用Lua http模块的外部API

完整示例

1. 拉取Docker镜像

docker pull balerter/balerter

2. 运行容器

docker run \
    -v /path/to/config.yml:/opt/config.yml \
    -v /path/to/scripts:/opt/scripts \
    -v /path/to/cert.crt:/home/user/db.crt \
    balerter/balerter -config=/opt/config.yml

3. 配置文件示例 (config.yml)

scripts:
  folder:
    - name: debug-folder
      path: /opt/scripts
      mask: '*.lua'

datasources:
  clickhouse:
    - name: ch1
      host: localhost
      port: 6440
      username: default
      password: secret
      database: default
      sslMode: verified_full
      sslCertPath: /home/user/db.crt

channels:
  slack:
    - name: slack1
      url: https://hooks.slack.com/services/hash

4. 脚本示例 (rps.lua)

-- @cron */10 * * * * *  // 每10秒运行一次
-- @name script1

local minRequestsRPS = 100

local log = require("log")
local ch1 = require("datasource.clickhouse.ch1")

-- 查询Clickhouse获取请求RPS
local res, err = ch1.query("SELECT sum(requests) AS rps FROM some_table WHERE date = now()")
if err ~= nil then
    log.error("clickhouse 'ch1' query error: " .. err)
    return
end

local resultRPS = res[1].rps

-- 根据RPS值触发或解除告警
if resultRPS < minRequestsRPS then
    alert.error("rps-min-limit", "Requests RPS are very small: " .. tostring(resultRPS))
else
    alert.success("rps-min-limit", "Requests RPS ok")
end

5. 测试脚本示例

-- @test script1  // 测试script1脚本
-- @name script1-test

test = require('test')

-- 模拟Clickhouse响应
local resp = {
    {
        rps = 10
    }
} 

-- 设置测试数据源响应
test.datasource('clickhouse.ch1').on('query', 'SELECT sum(requests) AS rps FROM some_table WHERE date = now()').response(resp)

-- 验证告警触发情况
test.alert().assertCalled('error', 'rps-min-limit', 'Requests RPS are very small: 10')
test.alert().assertNotCalled('success', 'rps-min-limit', 'Requests RPS ok')

通过这个完整的示例,您可以看到如何使用Balerter创建监控脚本、配置数据源和通知渠道,以及如何为脚本编写测试。Balerter提供了灵活的脚本化方式来管理您的告警系统。


更多关于golang自托管脚本化告警管理插件Balerter的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang自托管脚本化告警管理插件Balerter的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Balerter - 自托管脚本化告警管理工具

Balerter 是一个用 Go 语言编写的自托管脚本化告警管理工具,它允许您使用 Lua 脚本编写自定义告警逻辑,并支持多种通知渠道。

主要特性

  1. 轻量级且易于部署
  2. 使用 Lua 脚本编写告警逻辑
  3. 支持多种数据源和通知渠道
  4. 内置 HTTP API 和 Web 界面
  5. 可扩展的架构

安装与运行

使用 Docker 运行

docker run -d -p 1323:1323 -v /path/to/config:/etc/balerter balerter/balerter

从源码编译

git clone https://github.com/balerter/balerter.git
cd balerter
go build -o balerter main.go
./balerter

基本配置示例

创建 config.yml 配置文件:

storage:
  sqlite:
    path: "./balerter.db"

scripts:
  path: "./scripts"

channels:
  telegram:
    token: "YOUR_TELEGRAM_BOT_TOKEN"
    chat_id: "YOUR_CHAT_ID"

logging:
  level: "info"

编写告警脚本

scripts 目录下创建 Lua 脚本文件(如 cpu_check.lua):

-- 定义一个定时任务,每分钟执行一次
job("cpu_check", function()
    -- 模拟获取 CPU 使用率
    local cpu_usage = math.random(0, 100)
    
    -- 如果 CPU 使用率超过 90%,发送告警
    if cpu_usage > 90 then
        alert({
            title = "High CPU Usage",
            text = "CPU usage is " .. cpu_usage .. "%",
            level = "critical"
        })
    end
end)

完整 Go 集成示例

以下是如何在 Go 应用中集成 Balerter 的示例:

package main

import (
	"log"
	"net/http"

	"github.com/balerter/balerter"
)

func main() {
	// 创建 Balerter 实例
	b, err := balerter.New("./config.yml")
	if err != nil {
		log.Fatal(err)
	}

	// 启动 Balerter
	go func() {
		if err := b.Run(); err != nil {
			log.Fatal(err)
		}
	}()

	// 添加自定义 HTTP 端点用于触发告警
	http.HandleFunc("/trigger", func(w http.ResponseWriter, r *http.Request) {
		// 调用 Balerter 的 API 发送告警
		resp, err := http.Post("http://localhost:1323/api/v1/alert", "application/json", 
			strings.NewReader(`{
				"title": "Manual Alert",
				"text": "This alert was triggered manually",
				"level": "warning"
			}`))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer resp.Body.Close()
		
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Alert triggered"))
	})

	// 启动 HTTP 服务器
	log.Println("Starting server on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

高级功能

数据源集成

Balerter 支持多种数据源,如 Prometheus、MySQL 等。以下是配置 Prometheus 数据源的示例:

datasources:
  prometheus:
    - name: "main"
      url: "http://prometheus:9090"

然后在 Lua 脚本中使用:

job("check_http_errors", function()
    local result, err = prometheus("main", 'sum(rate(http_requests_total{status=~"5.."}[5m])) by (service)')
    
    if err ~= nil then
        error(err)
    end
    
    for _, row in ipairs(result) do
        if row.value > 10 then
            alert({
                title = "High HTTP 5xx Errors - " .. row.metric.service,
                text = "5xx error rate is " .. row.value .. " for service " .. row.metric.service,
                level = "warning"
            })
        end
    end
end)

多通知渠道

Balerter 支持多种通知渠道,如 Slack、Telegram、Email 等:

channels:
  slack:
    - name: "alerts"
      webhook: "https://hooks.slack.com/services/..."
  
  email:
    - name: "admin"
      from: "alerts@example.com"
      to: "admin@example.com"
      smtp_host: "smtp.example.com"
      smtp_port: 587
      smtp_username: "user"
      smtp_password: "pass"

监控与管理

Balerter 提供了内置的监控 API:

// 查询活跃告警
resp, err := http.Get("http://localhost:1323/api/v1/alerts")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

body, _ := io.ReadAll(resp.Body)
fmt.Println("Active alerts:", string(body))

最佳实践

  1. 为不同类型的告警创建单独的脚本文件
  2. 使用适当的告警级别(critical, warning, info)
  3. 实现告警抑制逻辑避免告警风暴
  4. 定期审查和优化告警规则
  5. 为关键告警设置多种通知渠道

Balerter 是一个灵活且强大的工具,特别适合需要自定义告警逻辑的场景。通过 Lua 脚本,您可以实现几乎任何类型的监控和告警需求,而 Go 语言的强大性能保证了系统的高效运行。

回到顶部