88 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# threshold-event-detector
主机监控系统HMS指标阈值事件检测模块。
## 功能
1. **规则加载与热更新**:从 MySQL `metric_rule` / `rule_scope` 读取规则,写入 Redis
缓存(`hms:rule:cache:{rule_id}``hms:rule:version`),后台线程按版本号轮询热加载。
2. **检测引擎**:消费 `metrics.samples`,按 `(host_id, rule_id)` 维护滑动窗口与状态机
`OK → FIRING → PENDING → OK`),阈值比对触发 `firing` / `resolved` 事件。
3. **事件写入与告警收敛**:事件写入 `event` 表;告警按 `(host, rule)` 去重、
`scope/rule/severity + 时间桶` 聚合,输出 `alert` 并发布到 `alerts.converged`
4. **通知渠道封装**email / webhook / dingtalk / wechat 统一封装。
5. **REST API**:阈值规则管理、事件告警查询与确认/关闭、样本接入。
## 技术栈
- Python 3.10+(标准库实现核心逻辑与 HTTP API零强制第三方依赖
- 可选依赖:`pymysql`MySQL`redis`Redis`kafka-python`Kafka
未安装时自动回退到进程内内存实现,便于本地运行与单元测试。
## 目录结构
```
threshold-event-detector/
├── detector/
│ ├── __init__.py # 包说明
│ ├── __main__.py # 入口python -m detector
│ ├── models.py # 领域模型
│ ├── config.py # 配置
│ ├── storage.py # 存储/缓存/总线抽象 + 内存/MySQL/Redis/Kafka 适配器
│ ├── rule_loader.py # 规则加载与热更新
│ ├── engine.py # 检测引擎(滑动窗口 + 状态机)
│ ├── converger.py # 告警收敛(去重 + 聚合)
│ ├── notifier.py # 通知渠道封装
│ ├── api.py # REST API
│ └── app.py # 应用装配
└── tests/ # 单元测试
```
## 运行
```bash
# 零依赖本地运行(进程内存储 + 示例规则)
python3 -m detector --addr 0.0.0.0:8080
# 健康检查
curl http://127.0.0.1:8080/healthz
# 查看规则
curl http://127.0.0.1:8080/api/v1/rules
# 样本接入(端到端联调)
curl -X POST http://127.0.0.1:8080/api/v1/ingest \
-H 'Content-Type: application/json' \
-d '{"host_id":"h-001","host_group":"web","samples":[
{"name":"cpu_usage","value":95,"timestamp":1700000000,"labels":{"service":"web"}}]}'
```
## 测试
```bash
python3 -m unittest discover -s tests -v
```
## 配置(环境变量)
| 变量 | 默认 | 说明 |
|---|---|---|
| `HMS_HTTP_ADDR` | `0.0.0.0:8080` | HTTP 监听地址 |
| `HMS_EVALUATION_INTERVAL` | `15s` | 评估/恢复观察周期 |
| `HMS_DEDUP_WINDOW` | `5m` | 告警去重窗口 |
| `HMS_AGGREGATE_WINDOW` | `1m` | 告警聚合窗口 |
| `HMS_RULE_STORE_DRIVER` | `memory` | 规则仓库驱动 `memory`/`mysql` |
| `HMS_EVENT_STORE_DRIVER` | `memory` | 事件仓库驱动 |
| `HMS_ALERT_STORE_DRIVER` | `memory` | 告警仓库驱动 |
| `HMS_CACHE_DRIVER` | `memory` | 缓存驱动 `memory`/`redis` |
| `HMS_BUS_DRIVER` | `memory` | 总线驱动 `memory`/`kafka` |
| `HMS_MYSQL_DSN` | 空 | MySQL DSN`mysql://user:pass@host:port/hms` |
| `HMS_REDIS_URL` | `redis://127.0.0.1:6379/0` | Redis URL |
| `HMS_KAFKA_BOOTSTRAP` | `127.0.0.1:9092` | Kafka bootstrap |
## 设计文档
- `docs/01-design/architecture.md`5.2 threshold-event-detector
- `docs/01-design/database-design.md`
- `docs/01-design/api-design.md`