PmaControl logo PmaControl
  • 首页
  • PmaControl
    • AI智能代理 13个本地代理
    • 定价方案 Community、Cloud、On-Premise、Premium
    • 文档 指南、API、架构
    • 客户 28+企业
    • 常见问题 25个问题 / 7个类别
    数据库
    • MariaDB 30 篇文章
    • MySQL 10 篇文章
    • Galera Cluster 6 篇文章
    • MaxScale 3 篇文章
    • ProxySQL 2 篇文章
    • Amazon Aurora MySQL 0 篇文章
    • Azure Database 0 篇文章
    • ClickHouse 0 篇文章
    • GCP CloudSQL 0 篇文章
    • Percona Server 0 篇文章
    • SingleStore 0 篇文章
    • TiDB 0 篇文章
    • Vitess 0 篇文章
    解决方案
    • 全天候支持 MariaDB & MySQL紧急支持
    • Observabilité SQL 监控、告警、拓扑
    • Haute disponibilité 复制、故障转移、Galera
    • Disaster Recovery 备份、恢复、RPO/RTO
    • Sécurité & conformité 审计、GDPR、SOC2
    • Migration & upgrade 零停机、pt-osc、gh-ost
  • 定价方案
  • 资源
    • 文档 技术指南与API
    • 常见问题 25个常见问题
    • 客户评价 客户反馈与案例
    • 博客 文章与洞察
    • 路线图 即将推出的功能
    专业领域
    • Observabilité SQL 监控、告警、Dot3拓扑
    • Haute disponibilité 复制、故障转移、Galera
    • Sécurité & conformité 审计、GDPR、SOC2、ISO 27001
    • Disaster Recovery 备份、恢复、RPO/RTO
    • Performance & optimisation Digests、EXPLAIN、调优
    • Migration & upgrade 零停机、pt-osc
    快速链接
    • GitHub Wiki 26页 — 安装、引擎、插件
    • 源代码 GitHub官方仓库
    • 全天候支持 MariaDB & MySQL紧急支持
    • 预约演示 30分钟 — 真实架构
  • 全天候支持
  • 预约演示
预约演示
🇫🇷 FR Français 🇬🇧 EN English 🇵🇱 PL Polski 🇷🇺 RU Русский 🇨🇳 ZH 中文
← 返回博客

将 Telegram 接入 PmaControl:实时告警

发布于 2026年4月13日 作者 Aurélien LEQUOY
pmacontrol telegram alerting notifications automation
分享 X LinkedIn Facebook Email PDF
将 Telegram 接入 PmaControl:实时告警

为什么选择 Telegram 而不是邮件?

邮件告警有一个根本性的问题:没有人会实时阅读它们。凌晨 3 点的告警邮件会被淹没在第二天的邮件洪流中。而一条 Telegram 告警会在值班 DBA 的口袋里振动——从事件发生到响应之间的延迟从数小时缩短到数秒。

PmaControl 使用 Telegram 作为主要告警通道。这不是一个花哨的功能:这是一个技术选择。Telegram 机器人是免费的,API 简单,消息支持 Markdown,群组允许按严重级别路由告警。

创建 Telegram 机器人

第一步:联系 @BotFather

打开 Telegram 并搜索 @BotFather。这是 Telegram 官方用于创建其他机器人的机器人。

你:/newbot
BotFather:Alright, a new bot. How are we going to call it?
你:PmaControl Alerts
BotFather:Good. Now let's choose a username for your bot.
你:pmacontrol_alerts_bot
BotFather:Done! [...] Use this token to access the HTTP API:
            7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

妥善保存此 token ——这是你机器人的 API 密钥。不要将其提交到 Git 仓库,不要以明文方式分享。

第二步:获取 chat_id

机器人需要知道向谁发送消息。对于群组:

  1. 创建一个 Telegram 群组(例如:"PmaControl - 生产告警")
  2. 将你的机器人添加到群组
  3. 在群组中发送一条消息
  4. 调用 getUpdates API:
curl -s "https://api.telegram.org/bot7123456789:AAHxxxx/getUpdates" | python3 -m json.tool

在响应中,找到群组的 chat_id(群组的 chat_id 为负数):

{
    "result": [{
        "message": {
            "chat": {
                "id": -1001234567890,
                "title": "PmaControl - Alertes Production",
                "type": "supergroup"
            }
        }
    }]
}

chat_id 为 -1001234567890。

第三步:测试

curl -s -X POST "https://api.telegram.org/bot7123456789:AAHxxxx/sendMessage" \
  -d chat_id=-1001234567890 \
  -d parse_mode=Markdown \
  -d text="*Test* : PmaControl alert system is working."

如果消息出现在群组中,说明配置已正常工作。

配置 PmaControl

配置文件

PmaControl 的 Telegram 配置位于:

/srv/www/pmacontrol/configuration/telegram.php
<?php
// configuration/telegram.php

define('TELEGRAM_TOKEN', '7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('TELEGRAM_CHAT_ID', '-1001234567890');

// Optional: separate channels by severity
define('TELEGRAM_CHAT_ID_CRITICAL', '-1001234567891');
define('TELEGRAM_CHAT_ID_WARNING', '-1001234567890');
define('TELEGRAM_CHAT_ID_INFO', '-1001234567892');

重要:此文件包含敏感信息(token)。请设置适当的文件权限:

chmod 640 /srv/www/pmacontrol/configuration/telegram.php
chown root:www-data /srv/www/pmacontrol/configuration/telegram.php

告警类型

PmaControl 发送四种类型的告警,每种都有对应的严重级别:

Info(信息)

信息告警通知正常但值得注意的事件:

ℹ️ Info — PmaControl
Server: db-prod-01 (10.0.1.1:3306)
Event: Service restarted
Version: MariaDB 10.11.6
Uptime: 0 days 0 hours 2 minutes
Time: 2026-04-13 14:32:15

Info 事件示例:

  • MariaDB / MySQL 服务重启
  • 检测到版本变更
  • 新服务器加入监控
  • Schema 导出完成

Warning(警告)

警告告警标识需要关注的状况:

⚠️ Warning — PmaControl
Server: db-prod-slave-01 (10.0.1.2:3306)
Event: Replication lag exceeds threshold
Lag: 120 seconds (threshold: 60s)
Status: IO=Yes, SQL=Yes
Duration: 5 minutes
Time: 2026-04-13 14:32:15

Warning 事件示例:

  • 复制延迟超过可配置阈值
  • 磁盘空间 < 20%
  • 连接数 > 最大值的 80%
  • 慢查询数量增加

Improvement(优化建议)

优化建议由 Marina+ 或内部规则生成:

💡 Improvement — PmaControl
Server: db-prod-01 (10.0.1.1:3306)
Suggestion: Missing index detected
Query: SELECT * FROM orders WHERE customer_id = ?
Rows examined/sent ratio: 450:1
Recommended: ALTER TABLE orders ADD INDEX idx_customer_id (customer_id)

Action Required(需要操作)

严重告警需要立即介入处理:

🔴 Action Required — PmaControl
Server: db-prod-slave-01 (10.0.1.2:3306)
Event: Replication stopped
Slave_IO_Running: No
Slave_SQL_Running: No
Last_SQL_Error: Error 'Duplicate entry' on table 'users'
Time: 2026-04-13 14:32:15
Link: https://pmacontrol.example.com/fr/slave/show/42/

Action Required 事件示例:

  • 复制停止(IO 或 SQL 线程)
  • 服务器不可达(SSH 或 MySQL 连接失败)
  • 在日志中检测到 OOM killer
  • 磁盘空间 < 5%(严重)
  • 持续性连接错误(超过 3 次尝试)

RBAC:按严重级别路由

在生产环境中,并非所有告警的受众都相同。PmaControl 支持按严重级别将告警路由到不同的 Telegram 群组。

推荐架构

群组 "PmaControl - Critical"    ← 仅 Action Required
  成员:值班 DBA、技术负责人、SRE

群组 "PmaControl - Operations"  ← Warning + Action Required
  成员:DBA 团队、SRE

群组 "PmaControl - All"         ← Info + Warning + Improvement + Action Required
  成员:扩展团队、核心开发人员

配置

// configuration/telegram.php

// 主群组(所有级别)
define('TELEGRAM_CHAT_ID', '-1001234567890');

// 按严重级别分组
define('TELEGRAM_CHAT_ID_CRITICAL', '-1001234567891');  // Action Required
define('TELEGRAM_CHAT_ID_WARNING',  '-1001234567890');  // Warning
define('TELEGRAM_CHAT_ID_INFO',     '-1001234567892');  // Info + Improvement

// 启用按严重级别路由
define('TELEGRAM_ROUTE_BY_SEVERITY', true);

当 TELEGRAM_ROUTE_BY_SEVERITY 设置为 true 时,每条告警仅发送到对应严重级别的群组。主群组(TELEGRAM_CHAT_ID)接收所有告警的副本。

告警事件

服务重启

PmaControl 通过 Uptime 变量检测重启。如果在两次采集之间 uptime 从 X 小时降到几分钟,说明发生了重启:

if ($current_uptime < $previous_uptime) {
    Telegram::sendInfo(
        "Service restarted",
        $server,
        "Previous uptime: " . formatDuration($previous_uptime) .
        "\nCurrent uptime: " . formatDuration($current_uptime)
    );
}

复制延迟

复制延迟被持续监控。告警在延迟超过阈值且持续一段可配置时间后触发(而非单个峰值):

// Alerte seulement si le lag est > seuil depuis 5 minutes
if ($lag > $threshold && $lag_duration > 300) {
    Telegram::sendWarning(
        "Replication lag exceeds threshold",
        $server,
        "Lag: {$lag}s (threshold: {$threshold}s)\n" .
        "Duration: " . formatDuration($lag_duration)
    );
}

磁盘空间

PmaControl 通过 SSH 收集磁盘使用情况。阈值如下:

  • Warning:可用空间 < 20%
  • Critical:可用空间 < 5%
🔴 Action Required — PmaControl
Server: db-prod-01 (10.0.1.1:3306)
Event: Disk space critical
Partition: /var/lib/mysql
Usage: 96% (used 458GB / 480GB)
Free: 22GB

OOM Killer

PmaControl 分析 syslog 和 dmesg 来检测 OOM 事件:

🔴 Action Required — PmaControl
Server: db-prod-01 (10.0.1.1:3306)
Event: OOM Killer invoked
Process killed: mysqld (PID 1234)
Memory at kill: RSS 14.2GB, limit 16GB
Time: 2026-04-13 03:42:15

连接性

如果 PmaControl 无法连接到服务器(SSH 超时或 MySQL 拒绝连接):

🔴 Action Required — PmaControl
Server: db-prod-03 (10.0.1.3:3306)
Event: Connection failed
Error: SSH timeout after 30s
Attempts: 3/3 failed
Last successful: 2026-04-13 14:25:00 (7 min ago)

告警仅在 3 次连接尝试均失败后才会发送,以避免因网络抖动导致的误报。

发送自定义报告

PmaControl agent 可以发送 Markdown 格式的消息:

// Rapport hebdomadaire
$report = "*Weekly Report — PmaControl*\n\n";
$report .= "📊 *Servers monitored*: 142\n";
$report .= "✅ *Healthy*: 138\n";
$report .= "⚠️ *Warnings*: 3\n";
$report .= "🔴 *Critical*: 1\n\n";
$report .= "*Top issues this week:*\n";
$report .= "1. db-prod-slave-03: lag spike (max 340s) — resolved\n";
$report .= "2. db-staging-01: disk 87% — cleanup scheduled\n";
$report .= "3. db-prod-02: 12 slow queries > 10s — indexes added\n";

Telegram::send($report, TELEGRAM_CHAT_ID, 'Markdown');

Telegram 的 Markdown 格式支持:

  • 粗体:*文本*
  • 斜体:_文本_
  • 行内代码:`文本`
  • 代码块:```文本```
  • 链接:[文本](url)

与 Releem agent 集成

Releem 是一个外部的 MariaDB / MySQL 优化 agent。当它与 PmaControl 集成时,其建议会通过 Telegram 发送:

💡 Improvement — Releem via PmaControl
Server: db-prod-01 (10.0.1.1:3306)
Recommendation: Increase innodb_buffer_pool_size
Current: 4GB
Recommended: 8GB
Reason: Buffer pool hit ratio 91.2% (target: >99%)
Impact: Estimated 15% improvement in read performance

集成在 Listener 层面完成:当 Releem 通过 API 发送建议时,PmaControl 对其进行处理并以标准格式路由到 Telegram。

最佳实践

1. 不要淹没群组

配置合理的阈值。一个每天收到 50 条告警的 Telegram 群组会被忽略。目标是:

  • Critical:每周 0-2 条消息(理想情况下为 0)
  • Warning:每天最多 5-10 条消息
  • Info:放在单独的群组中,按需查看

2. 包含操作链接

每条告警都应包含一个指向对应 PmaControl 页面的直接链接。值班 DBA 点击后即可直接进入问题服务器的仪表板。

3. 添加上下文

"Replication lag: 120s" 不如 "Replication lag: 120s (was 5s an hour ago, threshold: 60s, 3rd alert this week)" 有用。上下文有助于确定优先级。

4. 定期测试机器人

每天发送一条测试消息("PmaControl heartbeat: all systems operational")。如果消息不再到达,你就知道机器人在真正事件发生之前就已经出问题了。

# Cron quotidien de heartbeat
0 8 * * * curl -s -X POST "https://api.telegram.org/bot$TOKEN/sendMessage" \
  -d chat_id=$CHAT_ID \
  -d text="PmaControl heartbeat: $(date) — all systems operational"

5. 保护 token

  • 永远不要将其提交到 Git
  • 将其存储在权限受限的配置文件中
  • 在生产环境中使用密钥管理器
  • 如果 token 泄露,立即撤销并重新生成(在 @BotFather 中使用 /revoke)

6. 配置移动通知

Telegram 允许按群组配置通知:

  • Critical:开启通知,开启声音,始终可见
  • Operations:开启通知,关闭声音
  • All:关闭通知(按需查看)

故障排查

机器人不发送消息

  1. 验证 token:curl "https://api.telegram.org/bot$TOKEN/getMe"
  2. 验证 chat_id:curl "https://api.telegram.org/bot$TOKEN/getUpdates"
  3. 确认机器人已加入群组
  4. 检查 telegram.php 文件的权限
  5. 检查 PHP 日志中的连接错误

消息重复

如果每条告警都收到两次,请检查 TELEGRAM_ROUTE_BY_SEVERITY 的配置是否正确。未启用路由时,告警发送到默认群组。启用路由后,告警发送到指定群组。如果两者是同一个群组,消息就会收到两次。

速率限制

Telegram API 限制每个机器人每秒约 30 条消息。如果 PmaControl 监控着 200 台服务器且所有服务器同时出现问题,消息可能会被限流。解决方案:将告警合并为批次发送:

🔴 Action Required — PmaControl (batch)
Multiple servers affected:
- db-prod-01: Connection failed
- db-prod-02: Connection failed
- db-prod-03: Connection failed
Possible cause: Network outage in DC-1

结论

Telegram 是 PmaControl 理想的告警通道:实时、移动端、Markdown 格式、按严重级别分组。配置简单(10 分钟)且效果立竿见影:MariaDB / MySQL 事件被实时检测和通知,并附带采取行动所需的上下文信息。

经典的陷阱是过度告警。一个被通知淹没的 Telegram 群组比完全没有告警更糟糕——人们会将其设置为静音。校准阈值,分离严重级别,并定期测试机器人是否正常工作。

分享 X LinkedIn Facebook Email PDF
← 返回博客

评论 (0)

暂无评论。

发表评论

PmaControl
+33 6 63 28 27 47 contact@pmacontrol.com
法律声明 GitHub 联系我们
不要等到故障发生才了解您的架构。 © 2014-2026 PmaControl — 68Koncept