From f657abeed10434a21336f5d993f215501a691367 Mon Sep 17 00:00:00 2001 From: qiubaishen Date: Thu, 15 Oct 2026 18:35:05 +0800 Subject: [PATCH] Initialize observability stack with local monitoring and server134 deployment --- .gitattributes | 8 + .gitignore | 14 + ...21-搭建三层统一监控告警平台.md | 1641 +++++++++++++++++ AGENTS.md | 381 ++++ README.md | 35 + deploy/monitoring/.env.example | 23 + deploy/monitoring/.gitignore | 3 + deploy/monitoring/README.local.md | 103 ++ deploy/monitoring/README.md | 151 ++ deploy/monitoring/README.mysql.md | 225 +++ deploy/monitoring/README.server134.md | 57 + .../config/alertmanager/alertmanager.yml | 12 + .../dashboards/monitor-host-overview.json | 153 ++ .../provisioning/dashboards/dashboards.yml | 11 + .../provisioning/datasources/datasources.yml | 31 + deploy/monitoring/config/local/blackbox.yml | 11 + .../local/dashboards/new-api-local.json | 239 +++ deploy/monitoring/config/local/prometheus.yml | 40 + .../config/local/rules/application.yml | 19 + deploy/monitoring/config/tempo/tempo.yml | 28 + .../config/vmagent/prometheus.server134.yml | 29 + .../monitoring/config/vmagent/prometheus.yml | 29 + .../monitoring/config/vmalert/host-rules.yml | 39 + deploy/monitoring/docker-compose.local.yml | 77 + deploy/monitoring/docker-compose.yml | 153 ++ deploy/monitoring/scripts/check-ports.sh | 104 ++ .../scripts/install-docker-ubuntu.sh | 34 + deploy/monitoring/scripts/local.py | 191 ++ deploy/monitoring/scripts/prepare.sh | 38 + deploy/monitoring/scripts/smoke-test.sh | 6 + deploy/monitoring/scripts/smoke.py | 134 ++ deploy/monitoring/tests/check-ports-test.sh | 79 + deploy/monitoring/tests/test_local_ports.py | 49 + deploy/monitoring/tests/test_mysql_config.py | 42 + ...Grafana使用手册-本地new-api监控.md | 323 ++++ ...hree-layer-observability-implementation.md | 132 ++ 36 files changed, 4644 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 20260921-搭建三层统一监控告警平台.md create mode 100644 AGENTS.md create mode 100644 README.md create mode 100644 deploy/monitoring/.env.example create mode 100644 deploy/monitoring/.gitignore create mode 100644 deploy/monitoring/README.local.md create mode 100644 deploy/monitoring/README.md create mode 100644 deploy/monitoring/README.mysql.md create mode 100644 deploy/monitoring/README.server134.md create mode 100644 deploy/monitoring/config/alertmanager/alertmanager.yml create mode 100644 deploy/monitoring/config/grafana/dashboards/monitor-host-overview.json create mode 100644 deploy/monitoring/config/grafana/provisioning/dashboards/dashboards.yml create mode 100644 deploy/monitoring/config/grafana/provisioning/datasources/datasources.yml create mode 100644 deploy/monitoring/config/local/blackbox.yml create mode 100644 deploy/monitoring/config/local/dashboards/new-api-local.json create mode 100644 deploy/monitoring/config/local/prometheus.yml create mode 100644 deploy/monitoring/config/local/rules/application.yml create mode 100644 deploy/monitoring/config/tempo/tempo.yml create mode 100644 deploy/monitoring/config/vmagent/prometheus.server134.yml create mode 100644 deploy/monitoring/config/vmagent/prometheus.yml create mode 100644 deploy/monitoring/config/vmalert/host-rules.yml create mode 100644 deploy/monitoring/docker-compose.local.yml create mode 100644 deploy/monitoring/docker-compose.yml create mode 100755 deploy/monitoring/scripts/check-ports.sh create mode 100755 deploy/monitoring/scripts/install-docker-ubuntu.sh create mode 100644 deploy/monitoring/scripts/local.py create mode 100755 deploy/monitoring/scripts/prepare.sh create mode 100755 deploy/monitoring/scripts/smoke-test.sh create mode 100644 deploy/monitoring/scripts/smoke.py create mode 100755 deploy/monitoring/tests/check-ports-test.sh create mode 100644 deploy/monitoring/tests/test_local_ports.py create mode 100644 deploy/monitoring/tests/test_mysql_config.py create mode 100644 docs/Grafana使用手册-本地new-api监控.md create mode 100644 docs/superpowers/plans/2026-09-23-three-layer-observability-implementation.md diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e4b9249 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +* text=auto +*.sh text eol=lf +*.py text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.json text eol=lf +*.md text eol=lf +.env.example text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..34f64bf --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.env +.env.* +!.env.example +**/data/ +**/__pycache__/ +*.py[cod] +*.pem +*.key +*.p12 +*.pfx +mysql-exporter.cnf +grafana-admin-password.txt +.DS_Store +Thumbs.db diff --git a/20260921-搭建三层统一监控告警平台.md b/20260921-搭建三层统一监控告警平台.md new file mode 100644 index 0000000..057a7c6 --- /dev/null +++ b/20260921-搭建三层统一监控告警平台.md @@ -0,0 +1,1641 @@ +# 搭建三层统一监控告警平台 — 系统设计方案(方向 B 全量版) + +> **创建**: 2026-09-21 +> **上游文档**: `docs/需求调研/20260916-搭建三层统一监控告警平台.md` +> **用户决策**: 走**方向 B — 全三层统一平台(Metrics + Logs + Traces 全关联),一步到位** +> **本文覆盖**: 服务器现状实测 → 量级结论 → 技术选型对比与定选 → 架构 → 四级下钻页面 → 可配置告警 → 分批实施 +> **实测范围**: 6 个 SSH 别名(实为 5 台物理机)× 基础/服务/日志/业务四类,共 18 次远程采集,全部为 2026-09-21 12:40–13:10 实时数据 + +--- + +## 〇、先更正一条我之前说错的事实 + +调研报告 §十 写的「**crs3 磁盘 91%、`out.log` 12.1GB 未轮转、2~3 周满盘**」——**这条已经不成立**,我当时引用的是 `.claude/skills/deploy-crs/servers.md` 里的存量记录,没有实测。 + +实测结果(2026-09-21): + +``` +weelink-crs3: /dev/vda2 21G/50G 44% +/var/log/weelinking/: error.log 6.0M | error.log.1 13M | error.log.2.gz…7.gz 各约 3M | out.log 26M +/etc/logrotate.d/weelinking ← 已存在,按天轮转生效中 +``` + +雷已经被人拆了。调研报告 §十「需要你一句话授权」的前置事项**作废**。 + +**但这个问题只是换了台机器,而且更凶。** 见 §二。 + +--- + +## 一、服务器现状(实测) + +### 1.1 拓扑更正:6 个别名 = 5 台物理机 + +`weiyuan-crs01` 与 `weiyuan-cct01` 是**同一台 43.132.182.65**(两者 hostname 均为 `VM-0-17-ubuntu`,内存/磁盘读数完全一致),靠 `weiyuan` / `weiyuanapi` 两个 Linux 用户 + 两套独立 pm2 隔离。 + +``` + ┌──────────────── 国内 VPC 172.16.0.x ────────────────┐ + 客户端 ──HTTPS──▶ web69 (nginx) ──▶ web154 (8×monkey-ai) ──▶ MySQL 172.16.0.10 + 9 品牌 36 域名 :3000/3001/3003-3008 Redis 172.16.0.3 (db0-7) + └──────────────────────┬─────────────────────────────┘ + │ 出境 + ┌──────────────────────────────────────┼──────────────────────┐ + ▼ ▼ ▼ + crs3 43.130.235.3 cct01/crs01 43.132.182.65 crs227 + ├ weelinking(new-api) :3000 ├ [weiyuanapi] wy-cpa-0 :31001 ├ crs :3066 + ├ crs :3066 ← 渠道#17 唯一指向 │ └ wy-crs-0 :31002 ├ tls :9443 + └ tls :9443 │ └ wy-tls-0 :31003 ├ weytoken_sub :18080 + redis 本机 db0 ├ [weiyuan] wy-crs :3066 ├ postgres :5432 + │ └ wy-tls └ redis 本机 + └ redis VPC 172.19.0.10 (db0/db1) +``` + +### 1.2 基础层(5 台全部 4 vCPU / 7745 MB / 50 GB / Ubuntu 22.04) + +| 主机 | hostname | 磁盘 | 内存已用 | 运行天数 | load(1/5/15) | +|---|---|---|---|---|---| +| weelink-crs3 | VM-0-4-ubuntu | 21G/50G **44%** | 2093 MB | 259d | 0.09/0.16/0.22 | +| weelink-crs227 | VM-0-15-ubuntu | 30G/50G **64%** | 2761 MB | 259d | 0.22/0.21/0.19 | +| weiyuan-cct01 / crs01 | VM-0-17-ubuntu | 38G/50G **81%** 🔴 | 1390 MB | 111d | 0.08/0.08/0.03 | +| weiyuan-web154 | weelinking-app | 25G/50G **53%** | 1937 MB | 24d | 0.29/0.45/0.51 | +| weiyuan-web69 | weelinking-nginx | 20G/50G **42%** | 1461 MB | 115d | 0.00/0.01/0.00 | + +**CPU 与内存全线富余**(load 最高 0.51 / 4 核;内存最多用 36%)。**磁盘是唯一紧张的资源,且集中在 cct01。** + +### 1.3 服务层 + +| 主机 | 进程(pm2) | RSS | 重启次数 | 运行时长 | +|---|---|---|---|---| +| crs3 | `crs` | 1.2 GB | **38** | 38h | +| | `weelinking`(new-api) | 209 MB | 33 | 3D | +| | `tls` | 7.8 MB | 0 | 2M | +| crs227 | `crs` | 982 MB | 2 | 38h | +| | `tls` / `weytoken_sub` | 8.7 MB / 66.5 MB | 1 / 3 | 55D / 2M | +| cct01 | `wy-cpa-0` / `wy-crs-0` / `wy-tls-0` | 169 / 299 / 9.8 MB | 1 / 2 / 0 | 25D / 31D / 45D | +| crs01 | `wy-crs` | 222 MB | **40** | 38h | +| | `wy-tls` | 5.6 MB | 0 | 45D | +| web154 | 8 个 monkey-ai(pm2 God daemon 托管,主实例 4 进程) | 49–179 MB | — | 主实例 12h | + +> `crs3.crs`(38↺) 与 `crs01.wy-crs`(40↺) 的 uptime 都是 **38h**——两台机器在同一时间点被重启过,且各自累计重启近 40 次。**这些重启是优雅的还是 OOM 的,现在无从判断**(正是调研痛点 3 的形态)。 + +**中间件** + +| 实例 | 位置 | 键数 | 内存/上限 | 淘汰策略 | +|---|---|---|---|---| +| crs3 本机 Redis | 127.0.0.1:6379 db0 | 239,376 | 138.9M / 2G | **allkeys-lru** 🔴 | +| crs227 本机 Redis | 127.0.0.1:6379 db0 | — | 285.4M / 2G | **allkeys-lru** 🔴 | +| cct 共享 Redis | 172.19.0.10 db0(crs01)/db1(cct01) | 107,960 / 52,440 | 700.9M / 2G | noeviction ✅ | +| 业务 Redis | 172.16.0.3:6379 db0–db7 | — | — | 待测(须从 VPC 内) | +| 业务 MySQL | 172.16.0.10:3306,16 个库 | — | — | — | + +🔴 **crs3 与 crs227 的 Redis 是 `allkeys-lru`**,而 cct 共享 Redis 是正确的 `noeviction`。这两台承载 **25 个 OpenAI 账号 / 43 个 apikey**,一旦触到 2G 上限,粘性会话映射与用量计数会被静默淘汰——**故障形态是"偶发串号 + 计费少算",而且不会有任何报错**。当前 138M/285M 离上限还远,所以没爆,但无人监控。 + +**其他** + +- **web154 没有 nginx**(`ss` 无 80/443,systemd 无 nginx unit)→ 调研报告待核实项 #1 结案:nginx 只在 web69。 +- web154 上 `clamd` 常驻占 **12.4% 内存(约 960 MB)**,比任何一个业务进程都多。 +- pm2-logrotate 的 `module_conf.json` 是空 `{}`,即全部走默认(10M/retain 30/daily)。 + +### 1.4 日志现状 + +| 位置 | 体积 | 轮转 | 备注 | +|---|---|---|---| +| **cct01 `data/wy_cpa/auth/logs`** | **13 GB / 5501 文件** 🔴 | **无** | 见 §二·1 | +| cct01 `logs/wy_crs/out.log` | **2.7 GB** 🔴 | **无**(2026-07-31 起) | 约 52 MB/天 | +| cct01 `logs/wy_crs/billing-headers.log` | 84 MB | 无 | | +| cct01 `releases/` | 7.6 GB | 3 份 | | +| crs01 `/home/weiyuan/logs` | 4.3 GB | 无 | | +| crs01 `weelinking_crs/logs` | 79 MB | 有 | | +| crs3 `weelinking_crs/logs` | 12 MB | 有(按天 + 分片 gz) | 约 17 MB/天 | +| crs227 `logs` | 27 MB | 有 | | +| web69 `/var/log/nginx` | 41 MB | 有 | 见 §二·3 | + +`/etc/logrotate.d/` 在 cct01 上**没有任何一条覆盖 `/opt/wy`**。 + +### 1.5 业务层 + +**newapi:8 实例 / 9 品牌,每个品牌一套独立 MySQL 主库 + 日志库 + Redis db** + +| 品牌 | 端口 | 主库 | 日志库行数 / 体积 | 启用渠道 | +|---|---|---|---|---| +| weelinking(主) | 3000 | weelinking | **1,120,257 / 1036 MB** | 40 / 65 | +| sma | 3001 | weelinking_sma | 222,115 / 204 MB | 8 / 10 | +| ltop | 3003 | weelinking_ltop | 7,428 / 9 MB | 8 / 8 | +| hivetoken | 3004 | weelinking_hivetoken | 18,181 / 23 MB | 7 / 7 | +| aibiyi | 3005 | weelinking_aibiyi | 46 / 0 MB | 8 / 8 | +| paixtoken | 3006 | weelinking_paixtoken | 42 / 0 MB | 5 / 5 | +| tv | 3007 | weelinking_tv | 0 | 7 / 7 | +| youlangg | 3008 | weelinking_youlangg | 0 | 5 / 5 | + +🔴 **`monkey-ai-aibiyi` 与 `monkey-ai-youlangg` 共用 Redis 172.16.0.3 的 db4**(其余品牌 db0/1/2/3/5/7 各一)。两个品牌的缓存/会话/限流键在同一 keyspace 里,**目前 youlangg 零流量所以没撞上**。 + +**近 7 天请求量(type=2 消费日志)** + +``` +日期 weelinking sma +09-14 7,807 2,388 +09-15 16,276 3,327 +09-16 16,895 6,691 +09-17 12,989 3,268 +09-18 15,417 4,304 +09-19 2,554 3 ← 见 §二·2 +09-20 17,703 2,817 +09-21(半天) 5,493 754 +``` + +**全站合计 ≈ 20,000–25,000 请求/天 ≈ 0.25 req/s 均值**,平均 `use_time` 20–26 秒。 + +近 24h 模型 Top:`claude-sonnet-5` 8407(13.4s) / `deepseek-v4.1-flash` 2558(25.9s) / `gpt-5.6-sol` 2086(33.2s) / `gpt-6-astra` 1932(32.6s) / `claude-opus-5` 1519(19.5s)。 + +**CRS 账号池分布(Redis 实扫)** + +| 环境 | claude 账号 | openai 账号 | apikey | 定位 | +|---|---|---|---|---| +| cct01 (db1) | **5** | 0 | 5 | Claude 专用 ✅ | +| crs01 (db0) | 0 | 4 | 12 | GPT | +| crs3 | 0 | **14** | 16 | GPT 主力 | +| crs227 | 0 | **11** | 27 | GPT 主力 | +| **合计** | **5** | **29** | 60 | | + +完全印证你说的分工:**cct 放 Claude,常规 crs 放 GPT**。 + +**渠道 → 自家 CRS 的连接**(主品牌 65 个渠道) + +| 渠道 | 指向 | 状态 | +|---|---|---| +| #17 codex企业专用_weelink企业分组 | `http://43.130.235.3:3066/openai`(crs3) | **启用** | +| #11 / #30 / #52 cc-max-windows 系 | `http://43.132.182.65:3066/api`(crs01) | 禁用 | +| #16 codex企业专用 | `http://43.132.182.65:3066/openai` | 禁用 | +| #62 cc-max-lg第三方-test | `https://cct.weytoken.cn`(cct01) | 禁用 | +| #90 cc-max-星算_微元 | `http://107.149.55.24:8080` | 启用 | + +⚠️ **40 个启用渠道里,只有 1 个走自家 CRS**,其余 39 个全是第三方聚合商(火豹 / 数眼 / 星算 / 顺云 / 小马算力 / 超讯 / 阿姆特斯 / 腾讯云 / 百度 / Azure…)。 + +这直接改写了调研报告的一条判断:**"上游故障"的绝大多数不是我们的 CRS,而是第三方供应商**。监控设计必须把「第三方供应商健康度」当成一等公民,而不只是"下钻到 CRS 账号"。 + +**调用质量看板的真实状态** + +| 表 | 行数 | 结论 | +|---|---|---| +| `weelinking.monitor_outcome_stat` | **13,700**,2026-09-17 00:00 → 今天 13:05,持续写入 | ✅ **已上线且在正常采集** | +| `weelinking.monitor_config` | 1 | ✅ | +| `weelinking.monitor_task_mark` | 755 | ✅ | +| `weelinking.monitor_alert_rule` | **0** 🔴 | **一条告警规则都没配** | +| `weelinking.monitor_alert_event` | **0** 🔴 | 从未触发过任何告警 | +| 7 个马甲库的 `monitor_*` | **不存在** 🔴 | 看板只下发到主品牌 | + +`monitor_outcome_stat` 已聚合的维度(granularity 1=5min / 2=hour / 3=day): + +``` +granularity=1(5min): dim_type 1,2,3,5 +granularity=2(hour): dim_type 1,2,3,4,5,7,8 +granularity=3(day): dim_type 1,2,3,4,5,7,8 +``` + +表结构(42 列)已经是一张设计良好的**预聚合宽表**:`c1..c6`(6 态结局)、`f_upstream/f_platform/f_client/f_quota/f_abort`(5 类责任方)、`x31..x63`(细分原因)、`lat_b0..lat_b7`(延迟直方图桶)、`lat_sum_ms/lat_max_ms/hop_sum/quota/prompt_tokens/completion_tokens`。 + +**这张表可以直接当 Metrics 源,不需要重新设计业务指标模型。** + +### 1.6 链路追踪的现状:三个互不相通的 ID + +| 层 | 现有标识 | 是否向下游传递 | +|---|---|---| +| monkey-ai | `request_id`(前 14 位 = `YYYYMMDDHHMMSS` 到达时刻) | ❌ 不传给 CPA | +| wy_cpa | 自有 `RequestID`(gin ctx → logging ctx → dump 文件名 `*-{requestID}.log`) | ❌ 不传给 CRS | +| weelinking_crs | 自有请求标识 | ❌ 不传给 tls | +| go-tls-proxy | **无任何请求 ID**,只有 `[INFO] … (target=, proxy=, time=)` | — | + +全仓 **零 `go.opentelemetry.io` 依赖、零 `traceparent`**。方向 B 的 Traces 是**从零建**。 + +--- + +## 二、采集新发现的问题(按严重度) + +### 1. 🔴 cct01 的 CPA 请求 dump:13 GB / 5501 文件,单日峰值 6.9 GB + +``` +/opt/wy/stack0/data/wy_cpa/auth/logs/ 13 GB 5501 个文件 + 按天: 09-18 6.9 GB 09-19 0.7 GB 09-20 4.7 GB + 形态: v1-messages-2026-09-*.log × 5491(单文件最大 18.9 MB) + request-log-parts-*/part-*.tmp × 8(2026-08-05 的残留碎片,从未清理) + wp-admin-admin-ajax.php-*.log ← 连扫描器流量也在 dump +``` + +开关全开(`/opt/wy/stack0/config/*.env`): + +``` +ANTHROPIC_DEBUG_REQUEST_DUMP=true +ANTHROPIC_DEBUG_REQUEST_DUMP_CPA=true +CLAUDE_UPSTREAM_REQUEST_DUMP=true +ANTHROPIC_DEBUG_REQUEST_DUMP_CPA_MAX_FILE_BYTES=209715200 # 单文件上限 200MB +DUMP_MAX_FILE_SIZE_BYTES=209715200 +``` + +这正是 memory `wy57-ban-behavior-axis` 里那句「**三层 dump 仍开着(约 1GB)须按 0801 §11.1 关**」——当时 1 GB,现在 **13 GB**。 + +**这台机器磁盘 81%,剩 9.4 GB。09-18 那样的一天就能把它填满。** 而它是 Claude 全部 5 个账号、CPA + CRS + tls 三层、以及 crs01 另一套 CRS 的**唯一宿主**。满盘 = Claude 链路全挂。 + +这是 crs3 那颗雷的同一形态,只是**速度快了 20 倍**(6.9 GB/天 vs 310 MB/天)。 + +### 2. 🔴 smaapi.com 静默断流 27 小时,无人发现 + +``` +sma 按小时请求数 +09-18 12:00 → 21:00 80, 439, 785, 382, 343, 257, 147, 123, 141, 54 +09-18 22:00 → 09-19 08:00 (无数据) +09-19 09:00 3 +09-19 10:00 → 23:00 (无数据) +09-20 00:00 294 ← 恢复 +``` + +**最后一次正常流量 09-18 21:00,恢复在 09-20 00:00,中间约 27 小时只有 3 个请求。** 同期主品牌 weelinking 仍在跑(09-19 全天 2554 条),所以不是全站故障,是 sma 这个马甲单独出事。 + +**没有任何人、任何系统发现过这件事。** 这是本次采集拿到的最硬的一条证据——它比调研报告里所有历史复盘都更有说服力,因为它是**三天前刚发生、到现在都没人知道**的。 + +### 3. 🟠 边缘层(nginx)完全没有可观测数据 + +```nginx +# /etc/nginx/nginx.conf +access_log /var/log/nginx/access.log; # 默认 combined 格式 +# /etc/nginx/conf.d/weelinking.conf 第 460/470/479/725 行 +access_log off; # ← API location 全部关闭 +``` + +后果: + +- `access.log` 今天只有 **1493 行**,抽样全是 `FOFA-Anything` 之类的扫描器打 `GET /` 拿 301。**真实业务请求一条都不记。** +- 即便记了,`combined` 格式里**没有 `$request_time`、没有 `$upstream_response_time`、没有 `$upstream_addr`、没有 `$upstream_status`**。 + +这是整个系统里**最便宜的一块可观测性**:nginx 是唯一一个能同时看到"客户端视角总耗时"和"上游耗时"的位置,改一行 `log_format` 就能得到按域名/路径/上游的完整延迟分布,成本为零。现在它是关着的。 + +余光那 3 天的排查,如果 nginx 记了 `$request_time` 与 `$upstream_response_time`,第一分钟就能看出耗时在客户端到 nginx 还是 nginx 到后端。 + +### 4. 🟠 质量看板建成 4 天,告警规则 0 条 + +`monitor_alert_rule` 和 `monitor_alert_event` 都是空表。数据在正常采集(13,700 行),但**没有任何一条规则在跑**。看板处于"只能人去看"的状态——这正是你说的"现在的设计只有展示"。 + +### 5. 🟠 crs3 / crs227 Redis 淘汰策略错误(`allkeys-lru`) + +见 §1.3。 + +### 6. 🟡 aibiyi 与 youlangg 共用 Redis db4 + +见 §1.5。 + +### 7. 🟡 crs3.crs 与 crs01.wy-crs 各累计约 40 次重启,原因不可考 + +--- + +## 三、量级结论:这个数字决定了全部选型 + +| 指标 | 实测值 | +|---|---| +| 业务请求量 | **20–25K/天,均值 0.25 req/s**,峰值估计 < 10 req/s | +| 单请求耗时 | 平均 20–26 s(LLM 长连接) | +| 全站日志产出 | CRS 约 70 MB/天 + CPA 约 190 MB/累计 + tls 约 55 MB/累计 ≈ **< 300 MB/天**(不含 dump) | +| 主机数 | 5 台 | +| 进程数 | 约 20 个 | +| 业务维度基数 | 9 品牌 × 约 40 模型 × 约 90 渠道 × 约 30 企业 | +| 已有预聚合 | `monitor_outcome_stat` 约 3,400 行/天 / 6 MB | + +**这个量级小得超乎寻常。** 一台 4C8G 对它是数量级的富余。直接后果: + +1. **Traces 可以 100% 全采样**。25K 请求/天 × 5 span = 125K span/天,Tempo 单机压缩后不到 200 MB/天。不需要任何采样策略——这消掉了分布式追踪最难的一块设计。 +2. **日志可以全量入库**,不需要在 agent 侧做抽样,只需要过滤扫描器噪声。 +3. **真正的成本项是 Metrics 的时间序列基数,不是数据量**。9 品牌 × 40 模型 × 90 渠道的笛卡尔积如果直接展开是 32,400 条序列 × 每个指标——这才是要防的。设计上必须**限制标签组合**(见 §六)。 +4. **压测/容量规划不是本项目的重点**,防"零技术含量事故"和"静默失效"才是。 + +--- + +## 四、技术选型对比与最终选择 + +### 4.0 选型原则(来自你的硬约束) + +1. 单台 4C8G 承载全部三栈 + 看板 + 告警 +2. 不影响现有业务(agent 侵入必须可控、可回滚、资源可限) +3. 轻量 +4. 三层数据必须能**互相关联下钻**——这是方向 B 的核心,也是最强的选型约束 + +### 4.1 Metrics 存储 + +| 方案 | 单机内存占用 | 查询语言 | 与 Grafana | 运维复杂度 | 结论 | +|---|---|---|---|---|---| +| **VictoriaMetrics 单机版** | 同等负载下约为 Prometheus 的 **1/3 ~ 1/7** | MetricsQL(PromQL 超集) | 原生数据源 | 单二进制,无依赖 | ✅ **选它** | +| Prometheus + TSDB | 基线约 1.5–2 GB,随序列数线性涨 | PromQL | 原生 | 单二进制,但长期存储要另配 Thanos/Cortex | ❌ 内存是本机最稀缺资源 | +| InfluxDB 3 | 中等 | SQL / InfluxQL | 需插件 | 需额外对象存储 | ❌ 生态与 exporter 不匹配 | +| 云监控(腾讯云) | 0 | 云控制台 | 需桥接 | 零运维 | ❌ 只覆盖基础层,业务层无法自定义;且跨账号/跨地域 | + +**定选:VictoriaMetrics single-node + vmagent(采集)+ vmalert(告警规则)** + +理由: + +- 内存是这台机器的硬约束(8 GB 要放下 Metrics + Logs + Traces + Grafana + 告警)。VM 在这一项上是压倒性的。 +- 完全兼容 PromQL 与 Prometheus exporter 生态(node_exporter / redis_exporter / mysqld_exporter / blackbox_exporter 全部直接可用),**没有生态代价**。 +- vmagent 支持**本地磁盘缓冲 + 失败重试的 remote_write**。这条对我们是刚需:香港 3 台跨境推指标,链路抖动时不能丢数据(memory `web154-to-testcrs-slow-uplink` 实测跨境仅 20–50 KB/s)。 +- 单二进制,无外部依赖,出问题就一个进程。 + +**放弃 Prometheus 的代价**:`prometheus.yml` 的少量配置语法差异、以及部分社区 Dashboard 需微调。可接受。 + +### 4.2 Logs 存储 + +| 方案 | 单机内存 | 索引方式 | 全文检索 | 结论 | +|---|---|---|---|---| +| **VictoriaLogs** | 极低(几百 MB 级) | 全字段自动索引 | ✅ 快 | ✅ **选它** | +| Loki | 中(需 chunk cache) | **只索引标签**,日志体不索引 | ⚠️ 靠暴力扫描,慢 | △ 备选 | +| Elasticsearch | JVM 起步 4 GB+ | 全文倒排 | ✅ 最强 | ❌ 4C8G 直接出局 | +| ClickHouse | 中高 | 列存 | ✅ | ❌ 运维重,且要自己建表建物化视图 | + +**定选:VictoriaLogs** + +理由——**取决于我们实际怎么查日志**: + +我们的日志绝大部分是**半结构化文本**(CRS 的 Winston、CPA 的 logrus、go-tls-proxy 的 `log.Printf`),排查时的真实动作是「拿一个 account 名 / 一个 proxy host:port / 一段错误文本去全库 grep」。举几个真实例子: + +- `grep 'dial failed after 2 retries' wy_tls/err.log`(cct01 两条失败链路) +- `grep 'Non-stream response is not valid JSON'` +- `grep 'incompatible with client (os=mismatch'`(acceptedClientOS 那条,只有 debug 级才打) + +**这恰好是 Loki 最弱的场景**——Loki 只索引标签,日志正文要靠顺序扫描 chunk。而 VictoriaLogs 对所有字段自动建索引,全文检索是它的主场,且内存占用比 Loki 还低。 + +日均 < 300 MB 的量级下,VictoriaLogs 的存储与内存成本几乎可以忽略。 + +**风险与缓解**:VictoriaLogs 比 Loki 年轻,社区资料少。缓解——① 它与 VictoriaMetrics 同一套团队/同一套运维心智,我们本来就要装 VM;② Grafana 有官方 VictoriaLogs 数据源插件,看板联动没问题;③ 数据是 agent 推送的,真要换回 Loki,改 Vector 的 sink 配置即可,**迁移成本被 Vector 隔离了**。 + +### 4.3 Traces 存储 + +| 方案 | 单机资源 | 能否不靠 traceID 搜索 | 与 Grafana | 结论 | +|---|---|---|---|---| +| **Grafana Tempo** | 低(对象存储/本地 FS) | ✅ TraceQL 支持按属性搜索 | **原生,三栈一键跳转** | ✅ **选它** | +| Jaeger v2 | 中(需 ES/Cassandra/Badger) | ✅ 自带 UI 搜索 | 需插件 | △ 备选 | +| SkyWalking | 高(Java + ES/BanyanDB) | ✅ | 自带 UI | ❌ 太重 | + +**定选:Grafana Tempo(local filesystem backend)** + +理由: + +- 方向 B 的**全部价值就在"关联"**。Grafana 里 Metrics → Logs → Traces 的双向跳转(exemplar 跳 trace、trace span 跳该时刻日志、日志行的 traceID 跳 trace)在 Tempo 上是原生一等公民,用 Jaeger 要自己拼。既然关联是唯一目的,就不该在这里省。 +- 25K 请求/天 100% 采样,Tempo 单机本地盘足够,不需要 S3/MinIO。 +- Tempo 不建索引、只靠对象存储,所以内存占用在三个方案里最低。TraceQL 现在已经支持按 span 属性搜索(`{ .brand="sma" && status=error }`),不再是"只能用 traceID 查"的老 Tempo。 + +### 4.4 采集 Agent + +| 用途 | 方案 | 备选 | 理由 | +|---|---|---|---| +| 主机指标 | **node_exporter** | — | 事实标准,约 15 MB RSS | +| 指标推送 | **vmagent** | Prometheus agent mode | 磁盘缓冲 + 跨境重试 | +| 日志采集 | **Vector** | Fluent Bit / Alloy | 见下 | +| Redis | **redis_exporter** | — | | +| MySQL | **mysqld_exporter** | — | | +| 黑盒探活 | **blackbox_exporter** | — | 36 个域名 + 4 个 CRS 端点 | +| 进程 | **process-exporter** + pm2 自采 | — | 补 pm2 重启/RSS/CPU | + +**日志 agent 定选 Vector**,对比: + +| | Vector | Fluent Bit | Grafana Alloy | +|---|---|---|---| +| 内存 | 约 30–80 MB | 约 10–20 MB | 约 100 MB+ | +| 转换能力 | **VRL,强**(正则/结构化/条件/丢弃) | Lua/parser,弱 | River 配置,中 | +| 输出 VictoriaLogs | ✅ | 需 HTTP 通用输出 | ⚠️ | +| 背压/磁盘缓冲 | ✅ | 部分 | ✅ | + +决定因素是**转换能力**。我们的日志必须在 agent 端就地做三件事: + +1. **解析**:把 `[INFO] POST /v1/messages → 200 (target=api.anthropic.com, proxy=socks5://h:p, time=2.3s)` 这类文本抽成 `{status, target, proxy, duration_ms}` 结构化字段——不然到了存储端还是一坨文本,无法按线路聚合(调研痛点 6)。 +2. **降噪**:丢弃 nginx 的扫描器行、丢弃 debug 噪声。 +3. **提取指标**:从日志直接产出 Metrics(例如 `crs_upstream_error_total{proxy=...}`),走 Vector 的 `log_to_metric`,避免为了一个计数器去改业务代码。 + +Fluent Bit 做不到第 1、3 点的程度;Alloy 能做但更重且 Grafana 正在快速迭代。Vector 单二进制、Rust、无 GC、资源可用 systemd 限死。 + +### 4.5 埋点(Traces 的侵入部分) + +| 方案 | 侵入程度 | 结论 | +|---|---|---| +| **OpenTelemetry SDK(手动埋关键 span)** | 中 | ✅ **选它** | +| eBPF 无侵入(Pixie/Beyla) | 零代码 | ❌ 拿不到业务语义(account/model/channel),而这恰恰是我们要的 | +| 只靠日志时间戳拼接 | 零 | ❌ 方向 A 的做法,你已经明确否掉 | + +**定选:OpenTelemetry + W3C `traceparent`**,四层各埋 3–6 个 span。 + +对"不影响现有业务"的四条保证: + +1. **全局开关**:`OTEL_ENABLED=false` 为默认值,灰度打开;关闭时 SDK 走 NoopTracerProvider,零开销。 +2. **异步导出 + 有界队列**:`BatchSpanProcessor`,队列满即丢弃 span,**绝不阻塞业务请求**。 +3. **Collector 下线不影响业务**:OTLP 导出失败只打 warn。 +4. **单机验证 → 单品牌灰度 → 全量**,每一步可独立回滚。 + +### 4.6 告警与通知 + +| 方案 | 结论 | +|---|---| +| **vmalert(规则引擎)+ Alertmanager(路由/抑制/静默)+ 企业微信 webhook** | ✅ 基础/服务层 | +| **monkey-ai 内置 `monitor_alert_rule`(已有表,0 规则)** | ✅ 业务层 | +| Grafana Unified Alerting | △ 补充(看板即规则,适合临时规则) | + +**这里是一个必须说清楚的取舍:告警引擎要不要统一?** + +我的选择是**不统一,分两处,但通知通道统一**: + +- **基础层 + 服务层**走 vmalert → Alertmanager。这些规则是 PromQL 表达式(磁盘增长率、内存水位、进程重启率、探活失败),天然属于指标栈。 +- **业务层**继续走 monkey-ai 已有的 `monitor_alert_rule` 表。因为业务告警需要**企业维度的权限隔离**(企业管理员只能配自己企业的规则),这个能力在 monkey-ai 里已经有(`OrgAdminAuth` + `quality_view` 权限),搬到 Alertmanager 反而要重建一套权限体系。 +- **两边都把最终通知汇聚到同一个 Alertmanager webhook**,从而共享分级、静默、抑制、去重、值班表。 + +放弃"全部统一到 Alertmanager"的代价:业务告警规则的配置界面在 monkey-ai 而非 Grafana,两处入口。**这是有意的**——因为企业客户自助配置告警是业务能力,不该让客户登 Grafana。 + +### 4.7 最终选型总表 + +``` +┌─ 监控机(4C8G,国内 VPC 172.16.0.x)────────────────────────────────┐ +│ VictoriaMetrics (Metrics 存储, ~1.5G) │ +│ VictoriaLogs (Logs 存储, ~0.8G) │ +│ Tempo (Traces 存储, ~0.8G) │ +│ OTel Collector (trace 网关, ~0.3G) │ +│ Grafana (看板+下钻, ~0.5G) │ +│ vmalert (指标规则, ~0.2G) │ +│ Alertmanager (路由/静默, ~0.1G) │ +│ blackbox_exporter(探活, ~0.1G) │ +│ ────────────────────────────────────────── 合计约 4.3G / 8G │ +└──────────────────────────────────────────────────────────────────────┘ + ▲ remote_write / OTLP / VictoriaLogs HTTP(全部 push,含磁盘缓冲) + │ +┌───────┴──── 每台被监控机(agent 合计 < 150 MB RSS,systemd 限死)────┐ +│ node_exporter + vmagent + Vector + (redis/mysqld/process)_exporter │ +└──────────────────────────────────────────────────────────────────────┘ +``` + +**为什么全部用 push 而不是 pull**:香港 3 台跨境 20–50 KB/s,pull 模型下监控机主动抓取会因链路抖动产生大量假性 `up=0`(这本身就会变成误报源)。push + 本地磁盘缓冲能把跨境抖动吸收掉。 + +**监控机放国内 VPC 的理由**: +1. MySQL `172.16.0.10` 与业务 Redis `172.16.0.3` 只能从该 VPC 访问,这两个是最关键的中间件,直连比绕 agent 简单可靠。 +2. Grafana 面向国内运维,不走跨境访问。 +3. cct 的 VPC Redis `172.19.0.10` 只能从 43.132.182.65 访问 → 在该机本地跑 redis_exporter 推出来,这是唯一可行解,与监控机位置无关。 + +--- + +## 五、总体架构与数据流 + +``` +┌── 基础层 ──────────────────────────────────────────────────────────┐ +│ node_exporter × 5 → CPU/内存/磁盘/inode/网络/文件句柄/磁盘增长率 │ +└────────────────────────────────────────────────────────────────────┘ +┌── 服务层 ──────────────────────────────────────────────────────────┐ +│ process-exporter + pm2 采集脚本 → RSS/重启次数/uptime/GC │ +│ redis_exporter × 4 → 键数/内存/maxmemory-policy/命中率/连接数 │ +│ mysqld_exporter → QPS/慢查询/连接数/表体积 │ +│ blackbox_exporter → 36 域名 + 8 newapi 实例 + 4 CRS + 3 tls 探活 │ +│ nginx log(改 log_format) → $request_time/$upstream_response_time │ +└────────────────────────────────────────────────────────────────────┘ +┌── 业务层 ──────────────────────────────────────────────────────────┐ +│ ① monkey-ai: monitor_outcome_stat 直接导出为 Metrics(新增 /metrics)│ +│ ② CRS: Redis 直读账号状态 + reroute JSONL + Winston 日志 → Vector │ +│ ③ CPA: logrus 访问日志 → Vector(解析 status/latency/path) │ +│ ④ go-tls-proxy: [INFO] time= 行 → Vector 解析为按线路的指标 │ +│ ⑤ 第三方供应商健康度: 由 ① 的 dim_type=渠道 派生 │ +└────────────────────────────────────────────────────────────────────┘ +┌── Traces(新建)───────────────────────────────────────────────────┐ +│ nginx(注入 traceparent) → monkey-ai → CPA → CRS → tls → 上游 │ +│ 100% 采样,span 上挂业务属性:brand/model/channel/org/account/proxy │ +└────────────────────────────────────────────────────────────────────┘ +``` + +### 5.1 三层串联的关键:统一标签集 + +所有三种信号(Metric / Log / Trace)都必须携带**同一组标签**,否则关联无从谈起。约定如下: + +| 标签 | 取值示例 | Metrics | Logs | Traces | +|---|---|---|---|---| +| `trace_id` | W3C 32 hex | exemplar | 字段 | 主键 | +| `host` | `cct01` | ✅ | ✅ | resource | +| `service` | `wy-crs` / `monkey-ai` / `wy-tls` | ✅ | ✅ | resource | +| `brand` | `weelinking` / `sma` / `ltop` … | ✅ | ✅ | span attr | +| `model` | `claude-sonnet-5` | ✅ | ✅ | span attr | +| `channel_id` | `17` | ✅ | ✅ | span attr | +| `vendor` | `火豹` / `数眼` / `自建CRS` | ✅ | ✅ | span attr | +| `org_id` | 企业 ID | ⚠️ 仅预聚合 | ✅ | span attr | +| `crs_account` | `Claude_WY_33` | ✅ | ✅ | span attr | +| `proxy_line` | `host:port:user` | ✅ | ✅ | span attr | +| `outcome` | 1–6(复用已有枚举) | ✅ | ✅ | span attr | +| `fault_side` | 0–5(复用已有枚举) | ✅ | ✅ | span attr | + +**基数控制硬规则**(避免 Metrics 序列爆炸): + +- `org_id` **不进 Metrics 标签**(企业数会增长),只在预聚合表和 Logs/Traces 里;企业维度的指标从 `monitor_outcome_stat` 的 `dim_type=企业` 读,那是 MySQL 不是 TSDB。 +- `trace_id` / `request_id` **永不作为 Metrics 标签**,只作为 exemplar。 +- `model` × `channel_id` 不做笛卡尔积展开,各自独立成序列。 +- 预估序列总数 < 20,000,VM 单机轻松承载。 + +> ⚠️ **口径纪律**:`outcome`(6 态)与 `fault_side`(5 类)**必须复用 `service/faultclass` 与 `service/monitor` 里已定义的枚举**,不得另起一套成功率定义。否则会出现"Grafana 看到 97%、质量看板看到 98.2%"这种无法解释的差异,整套系统的可信度会在第一周就破产。 + +--- + +## 六、页面设计:四级下钻 + +> 现有质量看板只有"平铺展示"。新设计的核心是**每一个数字都可以点进去,一路点到那一条失败请求的原始报文**,并且每一层都能横向跳到相关的其他业务。 + +## 6.0 层级定义与页面清单 + +``` +L0 全局总览 「现在有没有事」 —— 一屏,红绿灯 + 未恢复告警 + ↓ 点任意卡片 +L1 域视图 「事出在哪个面」 —— 主机矩阵 / 进程依赖 / 品牌模型矩阵 + ↓ 点任意行 +L2 实体详情 「这个实体怎么了」 —— 单主机/单进程/单渠道/单账号的时序+构成 + ↓ 点任意异常分类 +L3 事件/请求级 「到底哪一条、为什么」 —— 目录文件/重启事件/失败请求 → Trace → 原始日志 +``` + +**全部页面(21 个 + 1 个变体)** + +| 页 | 层级 | 所在节 | 页面 | 回答的问题 | +|---|---|---|---|---| +| P0 | L0 | 6.2 | 全局总览 | 现在有没有事 | +| **基础层** | | | | | +| P1.1 | L1 | 6.3 | 主机矩阵 + 磁盘增长率排行 | 哪台机器有风险 | +| P1.2 | L2 | 6.3 | 单主机详情 | 这台机器怎么了 | +| P1.3 | L3 | 6.3 | 磁盘目录/文件下钻 | 空间被什么吃了、怎么止住 | +| P1.4 | L3 | 6.3 | 网络与连接下钻 | 和谁在连、连得好不好 | +| **服务层** | | | | | +| P2.1 | L1 | 6.4 | 进程 / 中间件 / 探活总览 | 哪个进程或依赖有风险 | +| P2.2 | L2 | 6.4 | 单进程详情 | 这个进程的内存与重启形态 | +| P2.3 | L3 | 6.4 | 重启事件详情 | 这次为什么挂、丢了哪些请求 | +| P2.4 | L2 | 6.4 | Redis 实例详情 | 内存涨在哪、策略对不对 | +| P2.5 | L2 | 6.4 | MySQL 详情 | 慢查询、表膨胀、连接 | +| P2.6 | L2 | 6.4 | nginx 边缘层 | 耗时到底在客户端还是后端 | +| P2.7 | L3 | 6.4 | 慢请求 / 错误请求明细 | 具体哪些请求慢 | +| **业务层** | | | | | +| P3.1 | L1 | 6.5 | 品牌×模型矩阵 + 供应商健康度 | 哪个品牌/模型/供应商有问题 | +| P3.2 | L1 | 6.5 | CRS 域(账号 × 线路 × 内部机制) | 自建链路哪里不对 | +| P3.3 | L2 | 6.5 | 单品牌详情 | 这个品牌怎么了(含断流) | +| P3.4 | L2 | 6.5 | 单渠道 / 供应商详情 | 这个上游怎么了 | +| P3.5 | L2 | 6.5 | 单 CRS 账号详情 | 这个账号是否亚健康 | +| P3.6 | L2 | 6.5 | 单出口线路详情 | 这条代理线路是否抖动 | +| P3.7 | L3 | 6.5 | 失败请求列表 → Trace → 原始报文 | 到底哪一条、卡在哪一跳 | +| P3.7′ | L3 | 6.5 | 走自建 CRS 时的完整瀑布(变体) | 自建链路内部卡在哪一跳 | +| **告警** | | | | | +| P4.1 | — | 6.6 | 告警中心 | 现在有哪些告警、处理到哪了 | +| P4.2 | — | 6.6 | 规则配置 | 怎么让它下次自己叫我 | + +## 6.1 六条贯穿所有页面的设计约定 + +这六条是"直观"的实现方式,不是装饰: + +1. **时间窗跟随下钻。** 从 L0 点到 L3,时间窗一路带下去,绝不重置。排查时最烦的就是钻到第三层发现时间跳回"近1小时"。 +2. **每一页都有「关联区」。** 固定在页面底部,列出保持当前时间窗的横向跳转入口。这是"业务之间要能串联起来分析"的落地形式——不是做一个大而全的页面,而是让每个页面都知道自己旁边还有谁。 +3. **"无数据"必须是独立状态,不能显示为绿。** 用 `░` 表示。这是 sma 断流 27 小时无人发现的直接对策。 +4. **配置偏离与已知陷阱写进 UI,不写进 wiki。** 例如 Redis 的 `allkeys-lru`、pm2 的 `node_args` 不生效、账号的 `acceptedClientOS`——这些坑踩过一次就该固化在页面上,而不是指望下一个人记得。 +5. **每一个异常读数旁边都给"下一步动作"。** 看到 13G 之后运维的下一个问题一定是"怎么关",把答案放在同一屏。 +6. **看板不做写操作,只生成命令。** 生产机的删除/重启必须人工执行,页面负责把命令拼对并解释副作用。 + +## 6.2 总览层页面组 + +### P0 · 全局总览(L0) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ 微元统一监控 [近1h ▾] [全部品牌 ▾] [全部环境 ▾] 🔔 5 ⚙ 规则 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ⚠ 未恢复告警 [全部静默 ▾] │ +│ P1 🔴 cct01 磁盘 81%,dump 目录 13G,按 09-18 速率 1.4 天满盘 2h [下钻▸] │ +│ P1 🔴 sma 品牌请求量 0/5min(基线 180/5min),已持续 27h 27h [下钻▸] │ +│ P2 🟠 渠道#3 cc-max-星算 上游故障率 8.4%(样本 143) 18m [下钻▸] │ +│ P2 🟠 线路 ipdeep:7085(user_b2) 502 率 4.2%(成簇 09:12-09:14) 12m [下钻▸] │ +│ P3 🟡 crs3/crs227 Redis maxmemory-policy=allkeys-lru(应 noev) 稳态 [下钻▸] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ┌─ 基础层 ───────────┐┌─ 服务层 ───────────┐┌─ 业务层 ──────────────────────┐│ +│ │ 主机 5 ● 4 ▲ 1 ││ 进程 20 ● 19 ▲ 1 ││ 成功率 97.8% ↓0.4 P95 24.1s ││ +│ │ CPU max 13% ││ 探活 48/48 ✅ ││ 请求 17.7K/d 兜底挽救 1.2% ││ +│ │ 内存 max 36% ││ Redis 4 ● 2 ▲ 2 ││ 上游故障 1.6% 客户端中断 0.9%││ +│ │ 磁盘 max 81% ▲ ││ MySQL ● 14ms ││ 品牌 9 ● 8 🔴 1(sma) ││ +│ │ [进入基础层 ▸] ││ [进入服务层 ▸] ││ [进入业务层 ▸] ││ +│ └────────────────────┘└────────────────────┘└───────────────────────────────┘│ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 端到端链路健康(点任一段进入该段的 L1) │ +│ │ +│ 客户端 nginx newapi CPA CRS tls 出口代理 上游 │ +│ │ 2ms │ 0.3s │ 0.1s │ 0.04s │ 0.09s │ 0.01s │ 1.2s │ 22.4s │ +│ ●───────●───────●─────────●────────●────────●────────●─────────● │ +│ ✅ ⚠无日志 ✅ ✅ ✅ ✅ 🟠4.2% ✅ │ +│ └─ 内部合计 0.23s (1%) ─┘ └── 外部 23.6s (99%) ──┘ │ +│ │ +│ 今日 Top 故障归因 上游 64% │ 平台 11% │ 调用方 18% │ 额度 5% │ 中断 2% │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 品牌健康矩阵(行=品牌 列=近 12 小时,点格子 → L2) │ +│ 00 01 02 03 04 05 06 07 08 09 10 11 │ +│ weelinking ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ 98.4% │ +│ sma ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ 无流量 🔴 │ +│ ltop ▓▓ ▓▓ ▓▓ ▒▒ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ 96.1% │ +│ hivetoken ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ██ ██ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ 89.2% 🟠 │ +│ aibiyi … ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ ░░ 无流量 │ +│ ▓=正常 ▒=降级 █=故障 ░=无流量 │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **"无流量"必须是一种独立状态(░),不能算作绿。** 这是 sma 断流 27 小时无人发现的直接原因——任何以"失败率"为核心的看板,在分母为 0 时都是满绿。必须有**流量基线对比告警**。 +- 端到端链路条是把余光案例的"减法"做成常驻视图。`⚠无日志` 明确标出 nginx 段当前没数据,不假装健康。 +- 任何一个数字都是链接。 +- 三张卡片(基础/服务/业务)各自是一个入口,对应下面三个独立的 L1→L2→L3 链路。它们在 L0 并列,但在 L2 层互相打通。 + +--- + +## 6.3 基础层页面组 + +### P1.1 · 主机矩阵(L1) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 总览 / 基础层 [近6h ▾] [全部机房 ▾] 自动刷新 30s ● │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 5 台主机 · 容量水位一屏(排序:风险 ▾) │ +│ 主机 角色 CPU 内存 磁盘 网络出/入 │ +│ cct01/crs01 Claude全链路+CRS ▁▁▂ 3% 1.4/7.6G 18% ███ 81%🔴 2/1 Mbps │ +│ └ ⚠ 同机双 pm2(weiyuanapi/weiyuan) /opt/wy 23G 24h +4.7G [目录下钻▸] │ +│ crs227 CRS · GPT 11账号 ▁▂▁ 6% 2.7/7.6G 36% ██ 64% 3/1 Mbps │ +│ web154 8×monkey-ai ▂▃▂ 12% 1.9/7.6G 25% ██ 53% 22/9 Mbps │ +│ crs3 newapi+CRS · 14账号▁▁▂ 4% 2.0/7.6G 27% █ 44% 3/1 Mbps │ +│ web69 nginx 9品牌36域名 ▁▁▁ 0% 1.4/7.6G 19% █ 42% 18/7 Mbps │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 磁盘增长率排行(满盘预测的数据源,本页最重要的一块) │ +│ 主机/挂载点 当前 24h增量 7d增量 预测满盘 近7日趋势 │ +│ cct01 / 81% +4.7 G 🔴 +12.3 G 1.4 天 🔴 ▂▅█▂▅█▂ [下钻▸] │ +│ crs227 / 64% +0.3 G +2.1 G 57 天 ▁▂▁▂▁▂▁ │ +│ web154 / 53% +0.2 G +1.4 G 118 天 ▁▁▂▁▁▁▁ │ +│ crs3 / 44% +0.05G +0.3 G >365 天 ▁▁▁▁▁▁▁ │ +│ web69 / 42% +0.02G +0.1 G >365 天 ▁▁▁▁▁▁▁ │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 资源水位横向对比(找异常机) 系统层异常事件(近 24h) │ +│ CPU ▏▏▏▏▎ max 12% (web154) OOM Killer 0 │ +│ 内存 ▎▎▍▎▎ max 36% (crs227) 磁盘 >85% 1 (cct01) │ +│ 磁盘 █▆▅▄▄ max 81% (cct01)🔴 inode >80% 0 │ +│ 负载 ▏▏▎▏▏ max 0.51 (web154) 网卡丢包 0 │ +│ NTP 偏移 >1s 0 ⓘ 偏移会毁掉链路对齐 │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **磁盘放主位、CPU/内存降为次要**。通用监控模板都把 CPU 放最大,但实测这套系统 CPU max 12%、内存 max 36%,磁盘 max 81%——看板应该反映系统**真实的风险分布**,而不是照搬模板。 +- **「磁盘增长率排行」而不是「使用率排行」是这一页的核心。** 81% 本身不吓人,`24h +4.7G / 预测 1.4 天` 才吓人。crs3 那颗雷能潜伏两个月,正是因为没人看斜率。使用率是状态,增长率才是预警。 +- `cct01/crs01` **合并成一行并显式标注同机双 pm2**。不这样写,两套 pm2 会被当成两台机器,得出"另一台还有空间"的致命误判。 +- 主机名旁写「角色」,运维不必记 IP 与端口。 +- NTP 偏移放进异常事件——它不影响业务,但**时钟偏移会让 Trace 的跨机 span 对不齐**,是链路分析的隐性前提。 + +### P1.2 · 单主机详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 基础层 / cct01 (43.132.182.65 · VM-0-17-ubuntu) [近6h ▾] [+加告警] [静默] │ +│ ⓘ 本机两套 pm2:weiyuanapi(wy-cpa-0/wy-crs-0/wy-tls-0) 与 weiyuan(wy-crs) │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ CPU 4核 内存 7745MB 磁盘 50GB 运行 111 天 │ +│ 用户2.1% 系统0.8% 已用1.4G 缓存3.2G 已用38G 剩9.4G🔴 负载 .08/.08/.03│ +│ iowait 0.1% │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 四联时序(共享时间轴,框选任一图同步放大全部) │ +│ CPU ┤▁▁▂▁▁▁▂▁▁▁▂▁▁▁▂▁▁▁▂▁▁▁▂▁▁▁ 3% │ +│ 内存 ┤▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ 18%(平直 ⇒ 无泄漏迹象) │ +│ 磁盘 ┤▁▁▂▃▄▅▆▇███████████████████ 81% ← 09-18 陡增段 │ +│ 网络 ┤▁▂▁▁▂▁▁▂▁▁▂▁▁▂▁▁▂▁▁▂▁▁▂▁▁▂ 出2/入1 Mbps │ +│ └───┬─────┬─────┬─────┬─────┬─── │ +│ 09-18 09-19 09-20 09-21 │ +│ ▼09-18 06:00 磁盘斜率突变 +6.9G/天 ▼09-19 回落 ▼09-20 再次 +4.7G/天 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 磁盘 TOP 目录(点进 L3) 网络连接 文件句柄 / inode │ +│ /opt/wy 23.0 G ▸ ESTABLISHED 42 句柄 1216/65535 │ +│ └data/wy_cpa/auth 13.0 G🔴▸ TIME_WAIT 118 inode 已用 8% │ +│ └releases 7.6 G ▸ LISTEN 11 │ +│ └logs 3.0 G ▸ 出境 socks5 5 条 │ +│ /var/lib/docker 4.2 G ▸ └ proxy.ipdeep.com:7085 ×5 [连接下钻▸] │ +│ /usr 3.1 G ▸ │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 关联区(保持当前时间窗) │ +│ [本机进程 ▸] [本机 Redis 172.19.0.10 db0/db1 ▸] [本机承载的 CRS 账号 ▸] │ +│ [同时段业务成功率 ▸] [同时段出口线路 ▸] [本机全部日志 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **四联时序共享时间轴 + 框选联动。** 单图放大在排查中几乎无用,因为要回答的是"磁盘涨的时候 CPU 在干什么"。 +- 时间轴上打**变更标记(▼)**,把"斜率突变"这种人眼容易滑过的特征显式标出来。 +- **磁盘 TOP 目录直接嵌在主机页,不藏进二级菜单。** cct01 的教训是:知道"81%"没用,知道"13G 在 `wy_cpa/auth`"才有用。少一次点击,排查就少一次断点。 +- **出境 socks5 连接单列。** 这是基础层唯一能直接看到"代理线路"的地方,与业务层 P3.6 的线路视图形成两个方向的相互印证——一个从 OS 看,一个从业务看,对不上就说明有连接泄漏或配置漂移。 +- 顶部那行 ⓘ 是刚性的:两套 pm2 混在一台机器上,不写清楚必然误操作。 + +### P1.3 · 磁盘目录/文件下钻(L3) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← cct01 / 磁盘 / /opt/wy/stack0/data/wy_cpa/auth/logs 13.0 G · 5501 文件 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 体积按天分布(点柱子 → 该天文件列表) │ +│ 09-15 ▏0.1G 09-16 ▏0.1G 09-17 ▎0.3G │ +│ 09-18 ███████████████ 6.9G🔴 09-19 █ 0.7G 09-20 ██████████ 4.7G │ +│ │ +│ ★ 文件名模式聚类(判断"该不该留"的关键) │ +│ 模式 文件数 总体积 最早 最新 │ +│ v1-messages-2026-09-*.log 5491 12.4 G 09-15 09-21 [样本▸] │ +│ request-log-parts-*/part-*.tmp 8 0.4 G 08-05 08-05 ⚠残留碎片 │ +│ wp-admin-admin-ajax.php-*.log 2 <1 M 09-19 09-20 ⚠扫描器污染 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 产生来源(自动关联到配置开关) │ +│ ANTHROPIC_DEBUG_REQUEST_DUMP = true 🔴 /opt/wy/stack0/config/*.env │ +│ ANTHROPIC_DEBUG_REQUEST_DUMP_CPA = true 🔴 │ +│ CLAUDE_UPSTREAM_REQUEST_DUMP = true 🔴 │ +│ DUMP_MAX_FILE_SIZE_BYTES = 209715200 (200MB/文件) │ +│ ⓘ 关闭以上开关可阻断约 99% 的增量。清理需人工确认(部分报文有调试价值) │ +│ ⚠ 改 .secrets/env 后 pm2 restart wy-cpa-0 不生效,须 restart ecosystem │ +│ --only wy-cpa-0 --update-env │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 最大文件 TOP10 [导出清理命令] [为该目录加告警规则] │ +│ 18.9M v1-messages-2026-09-18T14-22-09-a3f9…21c.log 09-18 14:22 [查看▸] │ +│ ⓘ 文件名尾部即 requestID → [跳到该请求的 Trace ▸] │ +│ 17.2M v1-messages-2026-09-18T14-31-55-b721…8ef.log 09-18 14:31 [查看▸] │ +│ … │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **按"文件名模式"聚类,而不是按目录树。** 5501 个文件用目录树看是灾难;聚成 3 类就一目了然:哪类是正常业务 dump、哪类是 8 月的残留垃圾、哪类是扫描器污染。这个聚类是通用监控工具不会做的,因为它依赖我们自己的命名约定。 +- **把日志体积直接关联到产生它的配置开关**——这是本页最有价值的设计。运维看到 13G 的下一个问题一定是"怎么关",把答案放在同一屏,而不是让他去翻文档。连"改了 env 要怎么重启才生效"这种坑都写上。 +- `requestID` 就在文件名尾部 ⇒ 可以从"这个巨大的文件"**直接跳到这条请求的 Trace**。这是一条罕见的**基础层 → 业务层反向串联通道**。 +- 提供 `[导出清理命令]` 而不是"一键清理"按钮。生产机删除必须人工执行(约定 6)。 + +### P1.4 · 网络与连接下钻(L3) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← cct01 / 网络 [近6h ▾] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 网卡吞吐 / 丢包 / 重传 连接状态分布 │ +│ 出 ▁▂▁▁▂▁▁▂ 2 Mbps ESTABLISHED 42 TIME_WAIT 118 CLOSE_WAIT 0 │ +│ 入 ▁▁▂▁▁▂▁▁ 1 Mbps SYN_SENT 0 FIN_WAIT 2 │ +│ 丢包 0 重传率 0.02% ⓘ CLOSE_WAIT 持续 >0 ⇒ 应用未关连接 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 按对端聚合(区分"内部调用"与"出境") │ +│ 对端 方向 连接数 进程 吞吐 RTT 状态 │ +│ proxy.ipdeep.com:7085 出境 5 wy-tls-0 1.2Mbps 186ms ✅ │ +│ └ user_a1 ×3 user_b2 ×2 ⓘ 同 host 不同 user 是不同出口 [线路视图▸] │ +│ 172.19.0.10:6379 内部 8 wy-crs-0 0.1Mbps 0.3ms ✅ │ +│ 127.0.0.1:31002 本机 12 wy-cpa-0 — — ✅ │ +│ 入站 6 wy-cpa-0 0.8Mbps 38ms ✅ │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 跨境链路质量(这几条是首字节慢的常见嫌疑) │ +│ 路径 RTT p50/p95 丢包 上行实测带宽 │ +│ web154(国内) → cct01(港) 38/52 ms 0% ⚠ 20–50 KB/s │ +│ cct01(港) → 上游(美) 182/240 ms 0.1% — │ +│ ⓘ 上行带宽低会让"上传时间"伪装成服务端处理时间,排查慢请求时先排除这一段 │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- 按**对端**聚合而不是按端口列表,并明确区分「出境 / 内部 / 本机 / 入站」四个方向——这决定了一条连接异常该找谁。 +- 跨境链路质量单独成块,并直接写出"上行带宽低会让上传时间伪装成服务端耗时"这条结论。这是排查慢请求时最容易掉的坑,做成常驻提示比写在复盘文档里有用。 +- `CLOSE_WAIT` 给了判据注解——这个指标只有配上"持续 >0 意味着什么"才有价值。 + +--- + +## 6.4 服务层页面组 + +### P2.1 · 进程 / 中间件 / 探活总览(L1) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 总览 / 服务层 [近6h ▾] [全部主机 ▾] 视角: (进程)(中间件)(接口) │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 进程(20 个,按风险排序) │ +│ 进程 主机 RSS/阈值 CPU 重启 24h/累计 uptime 健康 │ +│ crs crs3 1.20G/2.0G⚠ 3% 0 / 38 🔴 38h 200 31ms │ +│ wy-crs crs01 223M /2.0G 1% 0 / 40 🔴 38h 200 12ms │ +│ wy-crs-0 cct01 299M /2.0G 1% 0 / 2 31D 200 14ms │ +│ weelinking crs3 209M /— 2% 0 / 33 3D 200 8ms │ +│ monkey-ai web154 179M /— 12% 0 / 1 12h 200 9ms │ +│ └ 主品牌为 4 进程(ppid 1356) ⚠ 多实例还是子进程待确认 │ +│ monkey-ai-sma web154 96M /— 28%⚠ 0 / 1 12h 200 11ms │ +│ wy-cpa-0 cct01 169M /1.0G 1% 0 / 1 25D 200 4ms │ +│ wy-tls-0 cct01 9.8M/— 0% 0 / 0 45D — │ +│ clamd web154 960M /— 2% — / — 24D ⓘ非业务进程 │ +│ └ 占 web154 内存 12.4%,比任何业务进程都多 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 中间件(点行进 L2) │ +│ 实例 内存/上限 键数 淘汰策略 连接 延迟 │ +│ Redis crs3 本机 139M/2.0G 239,376 allkeys-lru🔴 12 0.2ms │ +│ Redis crs227 本机 285M/2.0G — allkeys-lru🔴 8 0.2ms │ +│ Redis 172.19.0.10 cct 701M/2.0G 160,400 noeviction ✅ 21 0.3ms │ +│ Redis 172.16.0.3 业务 待接入 db0–db7 待接入 — — │ +│ └ ⚠ aibiyi 与 youlangg 共用 db4 │ +│ MySQL 172.16.0.10 16 库 — — 34 14ms │ +│ └ weelinking_log.logs 112 万行 / 1036 MB 慢查询 0/h │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 接口探活(48 目标) nginx 边缘(web69) │ +│ 域名 36/36 ✅ newapi 8/8 ✅ QPS 0.3 4xx 2.1% 5xx 0.0% │ +│ CRS 4/4 ✅ tls 3/3 ✅ P95 24.3s 上游耗时占比 99.1% │ +│ ★ 探活绿 ≠ 质量绿 [对比业务成功率 ▸] [按域名下钻 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- 进程行同时给 **24h 重启 / 累计重启** 两个数字。只看 24h 会漏掉"累计 38 次但今天 0 次"的慢性病;只看累计会天天报警。 +- **RSS 旁必须写阈值**,没配 `max_memory_restart` 的写 `—` 而不是留白。crs3 的 11 次 OOM 正是因为没人知道 RSS 离阈值还剩多少。 +- **`clamd` 这类非业务进程也要列出来。** 它在 web154 吃掉 12.4% 内存,比任何业务进程都多;不列出来,将来做容量分析时会被误归因成"业务涨了"。 +- 中间件行直接暴露 **`淘汰策略` 列**。这不是常规监控项,是这套系统特有的:`allkeys-lru` 会静默淘汰粘性会话,故障形态是"偶发串号 + 计费少算"且零报错。把隐性约束做成可见状态(约定 4)。 +- 右下角 **「探活绿 ≠ 质量绿」配一个直达业务成功率的按钮**——把设计原则做成交互,而不是写成注释。 + +### P2.2 · 单进程详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 服务层 / crs @ crs3 pm2 id=0 · fork 模式 [近24h ▾] [+加告警] [静默] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ RSS 1.20G / 阈值 2.00G (60%) CPU 3% uptime 38h 累计重启 38 │ +│ ⚠ NODE_OPTIONS 未设 --max-old-space-size → 堆上限取默认,RSS 可达堆上限 2 倍 │ +│ ⓘ pm2 的 node_args 不会传给 node(jlist 会骗人);只有 NODE_OPTIONS + │ +│ delete&start 才生效。故 pm2 的 max_memory_restart 才是真正的杀手阈值 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ RSS / 堆 / CPU 时序(阈值虚线 + 重启竖线) │ +│ 2.0G ┤─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ 阈值 │ +│ 1.5G ┤ ╱▔▔▔╲ ╱▔▔▔▔▔▔▔ │ +│ 1.0G ┤ ╱▔▔▔▔▔▔▔╲____╱ ╲________╱ │ +│ 0.5G ┤______╱ │ +│ └───┬─────┬─────┬─────┬─────┬─────┬─────┬─── │ +│ 24h前 12h前 6h前 now │ +│ ┊重启 ┊重启 │ +│ ── RSS ┄┄ 堆已用 ▁▁ CPU │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 重启事件流(点行 → L3) │ +│ 时间 原因判定 退出码 重启前RSS 在途请求估计 [详情] │ +│ 09-20 23:11 疑似 OOM 🔴 — 1.94G ~3 [▸] │ +│ 09-20 17:02 人工 restart 0 1.21G ~2 [▸] │ +│ 09-19 08:40 疑似 OOM 🔴 — 1.97G ~4 [▸] │ +│ ⓘ 判定规则:退出码非 0 且重启前 RSS > 阈值 85% ⇒ 疑似 OOM(规则可调) │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 端口与依赖 该进程承载的业务 │ +│ 监听 :3066 (0.0.0.0) OpenAI 账号 14 apikey 16 │ +│ 依赖 Redis 127.0.0.1:6379 db0 被渠道 #17 调用(唯一指向自建CRS的启用渠道) │ +│ 依赖 tls 127.0.0.1:9443 近6h 请求 1,142 成功率 99.4% │ +│ [进程日志 ▸] [承载的账号 ▸] [调用它的渠道 ▸] [本机基础指标 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- 顶部把 `--max-old-space-size 未设置` 和「pm2 的 node_args 不生效」这条坑写在最显眼处。**这是把踩过的坑固化进 UI**(约定 4),而不是指望下一个人再踩一次——实测 crs3 的 4096 参数空设了一个月。 +- **RSS 曲线必须叠加阈值虚线与重启竖线。** "每次重启前 RSS 都在逼近阈值"这个模式,有参照线时人眼一秒看出,没有参照线时永远看不出。 +- **重启事件流带「原因判定」列**,不是只列时间戳。判定规则写在脚注里,保证可争议、可修正——这比给一个不透明的结论更可信。 +- **「在途请求估计」把运维语言翻译成业务影响。** "38 次重启"听起来还好,"每次丢 3 个在途请求"才有说服力,也才推得动排期。 + +### P2.3 · 重启事件详情(L3) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← crs @ crs3 / 重启事件 09-20 23:11:42 疑似 OOM · 退出码 — │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 事件前后 5 分钟全信号对齐(判断因果的唯一方式) │ +│ 23:07 23:08 23:09 23:10 23:11▼ 23:12 23:13 │ +│ RSS 1.62G 1.71G 1.83G 1.91G 1.94G 0.21G 0.38G │ +│ 堆已用 1.48G 1.55G 1.66G 1.74G 1.77G 0.09G 0.22G │ +│ CPU 18% 31% 54% 78% 96%🔴 4% 9% │ +│ GC 占比 12% 24% 41% 67% 89%🔴 — — │ +│ 请求并发 6 8 11 14 17 0 3 │ +│ 本机内存 28% 30% 32% 33% 34% 18% 19% │ +│ ⓘ GC 占比在 23:09 已达 41% ⇒ 进程实际上比重启时刻早 2 分钟就不工作了 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 崩溃前最后 20 行日志 [在 VictoriaLogs 中打开 ▸] │ +│ 23:11:38 [WARN] account Claude_WY_38 429 Queue timeout │ +│ 23:11:40 [INFO] selected OpenAI account OpenAI_07 sticky=miss │ +│ 23:11:41 [ERROR] FATAL ERROR: Reached heap limit Allocation failed │ +│ 23:11:42 <--- Last few GCs ---> │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 受影响的在途请求(按 trace_id 关联,3 条) │ +│ trace_id 品牌/企业 模型 开始 结局 │ +│ d41f…9a2 weelinking/A sonnet-5 23:10:58 连接中断→客户端重试 [Trace▸] │ +│ e07b…113 ltop/— gpt-6-astra 23:11:22 连接中断→未重试 [Trace▸] │ +│ f9c1…04d weelinking/B sonnet-5 23:11:05 连接中断→客户端重试 [Trace▸] │ +│ ⚠ 这 3 条在业务层被计入「客户端中断」,真实责任方是平台 —— 归因偏差在此可见 │ +│ [把这 3 条重新归因为平台侧 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- 这一页只做一件事:**把重启前后所有信号按同一时间轴对齐**。复盘方法论第 ③ 条是"某段是瓶颈必须由两端时间戳相减";同理,"进程为什么挂"必须由多信号同刻对齐得出,而不是靠猜。 +- **GC 占比这一行是关键。** RSS 涨到阈值只是结果,`GC 占比 89%` 才是"这个进程在 23:09 就已经不工作了"的证据——比重启时刻早 2 分钟。这 2 分钟就是告警能提前介入的窗口。 +- 底部「受影响的在途请求」把服务层事件**直接接到业务层的 trace 上**,并且**主动指出归因偏差**:这 3 条在业务看板里是"客户端中断",真实责任方是平台。这种偏差不显式标注,会长期污染成功率口径,最终让整块看板失去可信度。 + +### P2.4 · Redis 实例详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 服务层 / Redis @ crs3 (127.0.0.1:6379) [近24h ▾] [+加告警] [静默] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 🔴 maxmemory-policy = allkeys-lru(期望 noeviction) │ +│ 影响 :内存触顶时静默淘汰粘性会话映射与用量计数 │ +│ 形态 :偶发串号 + 计费少算,且不产生任何错误日志 │ +│ 当前 :139M / 2048M (6.8%) evicted_keys 累计 0 │ +│ ⚠ 副作用:改为 noeviction 后撑满会开始拒写,须先评估 TTL 覆盖率 │ +│ [查看修改建议与命令 ▸] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 内存 / 键数 / 命中率 / 淘汰数 时序 │ +│ 内存 ┤▁▂▂▃▃▃▄▄▄▄▅▅▅▅▅▅ 139M ↑ 30 天 +42M │ +│ 键数 ┤▁▂▂▃▃▃▄▄▄▄▅▅▅▅▅▅ 239,376 │ +│ 命中率 ┤▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ 99.2% │ +│ evicted_keys┤________________ 0 ★ 一旦离开 0 即为红线 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 键空间构成(按前缀聚合,回答"为什么在涨""改之前要先干什么") │ +│ 前缀 键数 占比 有 TTL 最大空闲 │ +│ session:* 98,412 41.1% ✅ 24h — │ +│ usage:* 76,203 31.8% ❌ 无 30 天 🔴 │ +│ sticky:* 52,108 21.8% ✅ 1h — │ +│ account:* 30 0.0% ❌ 无 —(应常驻,正常) │ +│ 其他 12,623 5.3% │ +│ ⓘ usage:* 无 TTL 且最大空闲 30 天 ⇒ 内存持续增长的主因,也是改 noeviction │ +│ 之前必须先处理的对象 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ [该实例承载的 CRS 账号 ▸] [本机进程 ▸] [本机基础指标 ▸] [对比其余 3 实例 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- 把「配置偏离」做成整页最顶部的红框,并且**同时写清影响、故障形态、当前距离、以及修改的副作用**。只说"策略错了"运维不敢动;把"改了会拒写"也写出来,他才能做决定。 +- `evicted_keys` 单独成一条时序、基线为 0——这是**唯一能证明"静默淘汰是否已经发生"的指标**,必须常驻而不是藏在 INFO 输出里。 +- **键空间按前缀聚合 + TTL 覆盖情况**,直接回答"为什么内存在涨"和"改策略之前要先做什么"。这比通用 Redis 看板的 hits/misses 有用得多,因为它是可行动的。 + +### P2.5 · MySQL 详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 服务层 / MySQL 172.16.0.10:3306 16 库 [近24h ▾] [+加告警] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ QPS 42 连接 34/151 慢查询 0/h 复制延迟 — 缓冲池命中 99.8% │ +│ QPS ┤▁▂▃▂▁▂▃▄▃▂▁▂▃▄▃▂▁▂ 连接 ┤▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 表体积与增长(日志库是唯一会失控的部分) │ +│ 库.表 行数 体积 30日增量 保留策略 │ +│ weelinking_log.logs 1,120,257 1036 MB +310 MB ⚠ 无 │ +│ weelinking_sma_log.logs 222,115 204 MB +48 MB ⚠ 无 │ +│ weelinking.monitor_outcome_stat 13,700 6 MB +6 MB ⚠ 无 │ +│ weelinking_hivetoken_log.logs 18,181 23 MB +5 MB ⚠ 无 │ +│ ⓘ 自有方案已标注 logs 表"分页查询和聚合统计逐渐成为瓶颈"。当前尚可, │ +│ 但无任何归档/分区策略 ⇒ 属于可预测的中期风险,建议纳入 P3 级告警 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 慢查询 TOP(>1s) 锁等待 / 死锁 │ +│ 当前无慢查询 锁等待 0 死锁 0 │ +│ ⓘ 一旦出现,按 摘要/次数/平均耗时/扫描行数 排序并给出涉及的库表 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 按库连接分布(定位"是哪个品牌在压库") │ +│ weelinking 18 weelinking_sma 6 weelinking_ltop 3 其余 7 │ +│ [各品牌业务视图 ▸] [宿主机指标(云数据库,仅暴露部分)▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- MySQL 目前完全健康(慢查询 0、连接 34/151),所以这一页**把重心放在"表体积增长"而不是"当前性能"**——同 P1.1 的逻辑:监控要盯着会变坏的东西,而不是已经好的东西。 +- 「30 日增量 + 保留策略」两列并排,把"日志表无限增长且没有归档策略"这个中期风险变成可见项。 +- 按库连接分布是为了回答"是哪个品牌在压库"——8 个实例共用一个 MySQL,出问题时必须能快速定位来源。 + +### P2.6 · nginx 边缘层(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 服务层 / nginx @ web69 9 品牌 · 36 域名 · 11 upstream [近6h ▾] │ +│ ⚠ 当前 4 处 API location 为 access_log off 且格式为默认 combined, │ +│ 本页数据不完整 → [查看改造方案 ▸] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 按域名(点行 → P2.7 请求明细) │ +│ 域名 QPS 2xx 4xx 5xx P50 P95 上游耗时占比 │ +│ api.weytoken.com 0.21 97.9% 2.1% 0.0% 18.2s 24.3s 99.1% │ +│ smaapi.com 0.00 ░ ░ ░ ░ ░ ░ 🔴 无流量 │ +│ ltopapi.com 0.03 96.1% 3.5% 0.4% 21.7s 31.2s 98.8% │ +│ hivetoken.cn 0.02 89.2% 7.1% 3.7%🔴 19.4s 28.8s 97.2% │ +│ …(其余 32 个域名) │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 耗时构成拆解($request_time − $upstream_response_time) │ +│ ┌──────────────┬────────────┬─────────────────────────────────────────────┐ │ +│ │ 客户端→nginx │ nginx 自身 │ nginx→后端(上游) │ │ +│ │ 0.02s │ 0.01s │ 24.27s │ │ +│ │ 0.1% │ 0.0% │ 99.1% │ │ +│ └──────────────┴────────────┴─────────────────────────────────────────────┘ │ +│ ⓘ 这一行就是余光案例花 3 天做的那个减法。改一行 log_format 即可变成常驻读数 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ upstream 健康 异常流量 │ +│ api_backend 8 节点 ✅ P95 24.3s 扫描器请求 1,432/日(已自动分类剔除) │ +│ sma_backend 1 节点 ⚠ 无流量 未备案域名拦截 0 │ +│ hivetoken_backend 1 节点 🔴 5xx 3.7% [扫描器 UA TOP ▸] [按状态码下钻 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **顶部那行警告是诚实性设计**:当前这一页有一半数据是缺的(`access_log off`),必须明说,不能让人以为"QPS 0.21"就是全部真相。看板宁可承认自己瞎,也不能假装健康。 +- **「耗时构成拆解」是整个平台最便宜也最值钱的一块。** 只需改一行 `log_format`,就把余光案例的 3 天排查变成常驻读数。它也是 L0 链路条 nginx 段的数据源。 +- 「无流量」在域名表里用 `░` 表示,是独立于 2xx/4xx/5xx 的状态并标红(约定 3)——sma 断流那 27 小时,这一行会是红的。 +- **扫描器流量单独分类计数,不混进 4xx。** 实测 access.log 今天 1493 行全是扫描器,不分类会把 4xx 率算爆,进而让所有基于 4xx 的告警失效。 + +### P2.7 · 慢请求 / 错误请求明细(L3) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← nginx / hivetoken.cn / 5xx 23 条 [07:00–13:00] [导出] [加规则] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 时间 trace_id 路径 上游 状态 总耗时 上游耗时 │ +│ 12:58:40 b721…8ef /v1/messages api_backend#3 502 3.12s 3.10s │ +│ 12:44:03 c0d2…447 /v1/messages api_backend#3 502 3.08s 3.06s │ +│ 11:12:19 a3f9…21c /v1/chat/compl… api_backend#1 504 60.02s 60.00s │ +│ … │ +│ ⓘ 全部集中在 api_backend#3 ⇒ 单节点问题,非全局 [只看 #3 ▸] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 分布分析(帮助判断是偶发还是成簇) │ +│ 按时间 ▁▁▁▃█▇▃▁▁▁▂▁ 集中在 11:10–11:20 与 12:44–12:58 │ +│ 按上游 #3 ████████ 19 #1 ██ 3 #2 ▏1 │ +│ 按路径 /v1/messages ██████ 18 /v1/chat/completions ██ 5 │ +│ 按状态 502 ████████ 20 504 ██ 3 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ [任选一条 → Trace 瀑布 ▸] [同时段业务层错误 ▸] [同时段后端进程指标 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- 列表页必须配**四维分布分析**(时间/上游/路径/状态),否则 23 条记录看完也得不出结论。"全部集中在 #3"这个判断应该由页面给出,而不是靠人一条条扫。 +- 「按时间」分布用于区分**偶发 vs 成簇**——这是代理线路抖动那类问题的核心判据,人工连点测试极易撞进簇内得出错误结论。 + +--- + +## 6.5 业务层页面组 + +### P3.1 · 品牌×模型矩阵 + 供应商健康度(L1) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 总览 / 业务层 [近6h ▾] [全部品牌 ▾] 视角: (品牌)(模型)(渠道)(企业)│ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 品牌 × 模型 成功率矩阵(点格子 → L2;右键 → 加告警规则) │ +│ sonnet-5 opus-5 gpt-6-astra ds-v4.1 gpt-image-2 合计 │ +│ weelinking 99.1% 98.2% 96.4% 99.5% 91.2% 🟠 98.4% │ +│ sma ░░ ░░ ░░ ░░ ░░ 无流量🔴 │ +│ ltop 97.8% — 94.1% 🟠 — — 96.1% │ +│ hivetoken 88.9%🔴 — — 99.0% — 89.2%🔴 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 供应商健康度(40 个启用渠道按 vendor 归并,实测 39/40 是第三方) │ +│ 供应商 渠道数 请求占比 成功率 P95 上游故障 近1h趋势 │ +│ 火豹 8 22.1% 98.9% 19.2s 0.8% ▁▂▁▁▂▁ │ +│ 数眼 6 18.4% 97.2% 26.8s 2.1% ▁▃▂▁▁▂ │ +│ 星算 3 14.7% 91.6%🔴 31.4s 8.4%🔴 ▂▅▇█▆▅ [下钻▸] │ +│ 顺云 6 12.2% 99.1% 17.7s 0.5% ▁▁▁▂▁▁ │ +│ 小马算力 2 9.8% 98.4% 22.1s 1.2% ▁▂▁▁▁▁ │ +│ ▸ 自建CRS 1 6.3% 99.4% 14.2s 0.3% ▁▁▁▁▁▁ [进CRS域▸] │ +│ 超讯/百度/Azure/腾讯云/阿姆特斯 … │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 6 态结局分布(近 6h) 责任方归因 │ +│ 直通成功 ████████████████ 94.1% 上游 ██████████ 64% │ +│ 兜底成功 █ 1.2% 调用方 ███ 18% │ +│ 兜底失败 ▏0.3% 平台 ██ 11% │ +│ 未兜底失败 █ 1.6% 额度 ▏5% │ +│ 客户端中断 █ 0.9% 内容拦截 ▏1.9% 中断 ▏2% │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**串联点**:`自建CRS` 那一行的 `[进CRS域▸]` 是 Newapi 侧 → CRS 侧的跳转,带上时间窗与筛选条件。反过来 CRS 域里每个账号也能跳回"哪些品牌/企业在用这个账号"。 + +### P3.2 · CRS 域(账号 × 线路 × 内部机制)(L1) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 业务层 / CRS 域 [全部环境 ▾] [近6h ▾] 环境: cct01(Claude·5) crs3(GPT·14)│ +│ crs227(GPT·11) crs01(GPT·4) │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 账号健康(34 个,按风险排序) │ +│ 账号 环境 状态 成功率 空回复 429 reroute 最近错误 │ +│ Claude_WY_95 cct01 ⚠亚健康 11.4%🔴 88.6%🔴 0 0 output=0 ×31 │ +│ └ 判据: cache_read 恒为 0 ⇒ 会话跨账号搬迁;CRS 只认 401,已滞后 95 分钟 │ +│ Claude_WY_38 cct01 ●可调度 97.8% 0% 7🟠 7 429 Queue t/o │ +│ OpenAI_03 crs3 ●可调度 99.2% 0% 0 1 — │ +│ … │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 出口线路(按 host:port:user 全量,禁止按 host:port 去重) │ +│ 线路 绑定账号 请求 失败率 p50上行 最近错误 │ +│ ipdeep:7085 (user_a1) Claude_WY_33 412 0.2% 1020KB/s — │ +│ ipdeep:7085 (user_b2) Claude_WY_95 388 4.2%🔴 980KB/s auth failed×9│ +│ └ 成簇爆发 09:12–09:14 集中 7 次(人工连点测试极易撞上,勿判为模型问题) │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ CRS 内部机制健康(这些开关的实际生效状态,不是配置值) │ +│ dynamicDelay 实际生效 ✅ 平均延迟 0.31s 峰值 8.1s(perKCacheRead 放大) │ +│ 并发闸门 limit=10 排队超时 429 ×7 ⚠ 上游慢时会放大为拒绝 │ +│ reroute 配额 2/h 已用 2/2 🟠 所有 trigger 共用此配额 │ +│ go-tls-proxy 已开 ⚠ PROXY_KEEP_ALIVE 配置无效(被 tls 接管) │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点**:最后一块「内部机制健康」是把 CRS 那几条反直觉事实**做成常驻视图**——展示的是**实际生效状态**而非配置值,因为那些坑的本质就是"配置看起来是这样、实际不是"(`maxConcurrency` 是布尔不是并发数、真开关是 `dynamicDelayEnabled`、`PROXY_KEEP_ALIVE` 在 go-tls-proxy 开启时无效)。 + +### P3.3 · 单品牌详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 业务层 / 品牌 sma (smaapi.com) 实例 :3001@web154 库 weelinking_sma │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 🔴 流量基线偏离:近 27 小时请求 3 条,基线 2817–6691/天(偏离 99.9%) │ +│ 首次偏离 09-18 21:00 · 至今未恢复 · 从未触发告警(规则缺失) │ +│ [查看同期主品牌 ▸] → 主品牌正常 ⇒ 非全站故障,范围锁定在本品牌 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 请求量(实线)vs 基线带(阴影 = 近 14 天同时段 P10–P90) │ +│ 800 ┤░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │ +│ 600 ┤░░▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │ +│ 400 ┤▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓░ │ +│ 200 ┤▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓░ │ +│ 0 ┤▔▔▔▔▔▔╲______________________________________________╱▔▔▔▔ │ +│ └──┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬── │ +│ 09-18 18:00 09-19 全天 09-20 00:00 │ +│ └─────────── 27 小时空窗 ───────────┘ │ +│ ⚠ 该期间失败率 = 0%(分母为 0)⇒ 任何以失败率为核心的看板都显示全绿 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 配置快照(排查断流时第一个要看的东西,按请求路径从后往前排) │ +│ MySQL weelinking_sma ✅ Redis 172.16.0.3 db1 ✅ │ +│ 进程 monkey-ai-sma ● 12h RSS 96M CPU 28%⚠ │ +│ 渠道 8 启用 / 10 总 ✅ 令牌/用户 — 待接入 │ +│ 上游 nginx sma_backend ⚠ 无流量 │ +│ 接入 smaapi.com → web69 ✅ DNS 正常 │ +│ ⓘ 进程活着、探活绿、DNS 通、渠道在,但没有流量 ⇒ 断点在更上游(客户端/接入) │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ [模型分布 ▸] [渠道分布 ▸] [企业分布 ▸] [错误分布 ▸] [同时段其他品牌 ▸] │ +│ [该品牌进程指标 ▸] [该品牌 nginx 域名 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **「请求量 vs 基线带」是这一页存在的全部理由。** 绝对值曲线看不出异常("晚上本来就少"),只有叠加同时段历史分位带,空窗才会刺眼。这是对 sma 事故的直接对策。 +- 页面上**显式写出"该期间失败率 = 0%"并标注为陷阱**。不写这一句,下一个人还是会相信那个绿色的成功率。 +- **配置快照按请求路径从后往前排**(DB → Redis → 进程 → 渠道 → nginx → DNS),排查断流时顺着往上看,第一个红的就是断点。这个排序不是随意的,它编码了排查顺序。 +- 结论行("断点在更上游")由页面给出,而不是让人自己推。 + +### P3.4 · 单渠道 / 供应商详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← CRS域 / 渠道#3 cc-max-星算 [近6h ▾] [+ 为该渠道加告警规则] [静默 ▾] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ vendor=星算 base_url=api.xingsuancode.ai 分组=兜底分组 type=14 状态=启用 │ +│ 服务对象: weelinking(82%) ltop(18%) │ 企业: A公司 41% B公司 22% 其他 37% │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 成功率 / 请求量 / P95 时序(三轴叠加,可框选放大 → 自动带入 L3 筛选) │ +│ 100%┤▔▔▔▔▔▔╲ ┌ 2000 │ +│ 95%┤ ╲▁▁▁▁ │ │ +│ 90%┤ ╲▁▁▁▁▁▁▁▁▁▁▁▁ │ 1000 │ +│ 85%┤ ╲▁▁▁▁▁▁▁▁▁▁ │ │ +│ └──┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬──┘ 0 │ +│ 07 08 09 10 11 12 13(now) │ +│ ░░░░ 请求量 ━━ 成功率 ┄┄ P95 │ +│ ▼ 09:14 变更: 无 ▼ 10:02 告警触发 ▼ 11:30 上游 5xx 突增 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 错误分布(点任一行 → L3 该类错误的请求列表) │ +│ 错误类型 次数 占比 首现 末现 趋势 → │ +│ upstream 5xx (502/503) 87 52.1% 10:02 13:04 ▂▅▇█ [列表▸] │ +│ upstream timeout (>60s) 41 24.6% 09:47 12:58 ▂▃▄▅ [列表▸] │ +│ invalid_response (non-JSON) 23 13.8% 11:12 12:44 ▁▂▅▃ [列表▸] │ +│ quota exceeded 15 9.0% 08:30 13:01 ▁▁▁▁ [列表▸] │ +│ 其他 1 0.6% │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 关联视图(横向串联,都带同一时间窗) │ +│ [同 vendor 其他渠道 #34 #90 ▸] [受影响企业清单 ▸] [该渠道兜底去向 ▸] │ +│ [同时段主机指标 ▸] [同时段 CRS 账号 ▸] [同时段出口线路 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **三轴叠加(成功率/请求量/P95)而不是三张图。** 单看成功率下跌无法判断严重性——如果请求量同时也跌了,可能是客户端自己在退避;三轴同框才能识别"量没变、成功率跌"这种真正的故障形态。 +- 时间轴上标注**变更事件**(配置变更、告警触发、上游突变)。"是不是我们自己改出来的"是排查第一问,答案应该在图上而不是在群聊记录里。 +- **框选放大自动带入 L3 筛选条件**——从"这段时间不对"到"看这段时间的请求"之间不应该有第二次操作。 +- 顶部写清「服务对象」(哪些品牌、哪些企业、占比多少)。这决定了故障影响面与通知对象,也是告警分级的依据。 +- 错误分布表带「首现/末现/趋势」三列:**同样是 87 次错误,"持续 3 小时且在上升"和"半小时前已停止"是完全不同的两件事。** + +### P3.5 · 单 CRS 账号详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← CRS域 / 账号 Claude_WY_95 @cct01(db1) [近6h ▾] [+加告警] [强制下线] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ⚠ 亚健康:成功率 11.4%,空回复率 88.6%(31/35),★ HTTP 状态码全部 200 │ +│ 判据:cache_read 恒为 0 ⇒ 会话跨账号搬迁致 thinking 签名失效 + cache 全冷 │ +│ 现状:CRS 只认 401 下线 ⇒ 预计还需 95 分钟才会自动摘除 │ +│ [立即下线] [查看判据明细 ▸] [该账号全部空回复请求 ▸] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 空回复率 / cache_read / 请求量 三联(cache_read 是先行指标) │ +│ 空回复 ┤_______▁▂▅███████████ 88.6% │ +│ cache ┤▔▔▔▔▔▔╲______________ 0 ← 18:08 归零,比空回复爆发早 4 分钟 │ +│ 请求量 ┤▁▂▁▂▁▂▃▅▇███████████ 35(含客户端重试 ×4) │ +│ └───┬──────┬──────┬──────┬─── │ +│ 18:00 18:30 19:00 19:30 │ +│ ⓘ cache_read 归零可用作告警先行信号,比"空回复率>30%"更早 4 分钟 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 账号画像 计费影响(报给老板的数字) │ +│ 平台 Claude 分组 微元分发分组 失败请求 31 条 │ +│ acceptedClientOS ["linux","mac"] ⚠ 客户端重试 4 次/条 │ +│ └ Windows/未知 OS 客户端被静默拒 每轮约 5×96K token │ +│ └ 该过滤是 debug 级,不打日志 ⇒ 估算照常计费 ≈ 59.5M token │ +│ 绑定线路 ipdeep:7085(user_b2) 🔴 4.2% │ +│ sticky 会话 12 个 reroute 0/2h 限流状态 正常 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ [该账号服务的品牌/企业 ▸] [该账号的出口线路 ▸] [宿主机指标 ▸] [原始日志 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **顶部必须写出「HTTP 状态码全部 200」。** 这类故障的形态就是 HTTP 200 + output=0;不点破的话,任何按状态码统计的成功率都显示 100%。这是"成功率必须按业务语义定义而非按 HTTP 码"的活例子。 +- **`cache_read` 作为先行指标单独成行。** 它比空回复率早 4 分钟归零,是唯一能把 95 分钟的下线滞后压进 5 分钟的信号。先行指标与结果指标画在同一张图上,因果关系不言自明。 +- **`acceptedClientOS` 在账号画像里常驻显示。** 实测 cct01 全部 5 个账号都是 `["linux","mac"]`,会把 Windows 客户端静默拒掉,而该过滤是 debug 级不打日志——不在 UI 明示,就只能靠有人恰好记得。 +- **计费影响换算成 token 数**,把技术故障翻译成商务语言。这一栏的存在是为了让这一页能被直接截图发给老板。 + +### P3.6 · 单出口线路详情(L2) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← CRS域 / 线路 proxy.ipdeep.com:7085 (user_b2) [近24h ▾] [+加告警] │ +│ ⚠ 线路身份 = host:port:user 三元组。同 host:port 不同 user 是不同出口,禁止合并│ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 失败率时序(注意成簇特征,不要只看平均值) │ +│ 8% ┤ ██ │ +│ 4% ┤ ███ ██ │ +│ 0% ┤▁▁▁▁▁▁▁▁▁▁▁▁▁▁███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███▁▁▁▁▁▁▁▁▁▁▁▁ │ +│ └───┬──────┬──────┬──────┬──────┬──────┬──────┬─── │ +│ 06:00 09:12-09:14 12:00 15:40-15:42 18:00 │ +│ 日均 4.2%,但 92% 的失败集中在 2 个各 2 分钟的窗口内 │ +│ ⚠ 人工连点测试极易整段撞进簇内 ⇒ 会得出"这个模型不行"的错误结论 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 错误构成 性能 │ +│ socks auth failed 9 (69%) 连接建立 p50 180ms │ +│ dial timeout 3 (23%) 上行 p50 980 KB/s ⚠ 跨境段仅 20–50KB/s │ +│ EOF 1 ( 8%) 下行 p50 2.1 MB/s │ +│ ⓘ go-tls-proxy 对 auth failed 回 502 + text/plain,CRS JSON.parse 失败后 │ +│ 在面板显示为「Upstream returned a non-JSON response」——别去查模型 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 绑定账号 Claude_WY_95 │ 同 host:port 其他 user:user_a1 (0.2%) [对比 ▸] │ +│ [该线路全部失败请求 ▸] [宿主机出境连接 ▸] [原始 tls 日志 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- 顶栏那句**「线路身份是三元组」是硬性纪律**。按 `host:port` 去重会把一条坏出口和一条好出口平均成"还行",直接导致误判。把纪律写在页面上,比写在复盘文档里有效。 +- **失败率时序必须能看出"成簇"**,所以用细粒度时间桶而不是小时均值。"日均 4.2%"和"92% 集中在两个 2 分钟窗口"是两个完全不同的故事,后者才解释了为什么人工测试总能撞上。 +- 错误构成里直接写明"这个错误在面板上会显示成什么"——把**一条排查路径的两个端点接起来**:运维在渠道页看到 `non-JSON response`,在这里才知道真正来源是 socks 认证抖动。 + +### P3.7 · 失败请求列表 → Trace → 原始报文(L3) + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ ← 渠道#3 / upstream 5xx 87 条 [10:02–13:04] [导出 CSV] [全选静默] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 时间 trace_id 品牌/企业 模型 耗时 状态 责任方 账号 │ +│ 13:04:12 a3f9…21c weelinking/A sonnet-5 61.2s 502 上游 — [展开▾] │ +│ 12:58:40 b721…8ef ltop/— gpt-6-astra 60.0s 超时 上游 — [展开▾] │ +│ 12:44:03 c0d2…447 weelinking/B sonnet-5 3.1s 502 上游 — [展开▾] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ▾ 展开 a3f9…21c —— Trace 瀑布图(100% 采样,无需碰运气) │ +│ │ +│ nginx.request ├─┤ 2ms ✅ 200 │ +│ monkey-ai.relay ├──────────────────────────────┤ 61.2s ❌ 502 │ +│ ├ channel.select ├┤ 8ms → channel_id=3 vendor=星算 ✅ │ +│ ├ upstream.call ├─────────────────────────┤ 61.0s ❌ 502 │ +│ │ └ dns 3ms / tcp 21ms / tls 48ms / ttfb 60.8s ← 首字节就卡住 │ +│ └ fallback.eval ├┤ 12ms → 未触发(兜底分组自身即兜底)🟠 │ +│ │ +│ ⓘ 本请求未经过 CPA/CRS/tls(渠道 #3 是第三方直连) │ +│ │ +│ ┌ 该 span 时刻的原始日志(自动按 trace_id + 时间窗关联)──────────────────┐ │ +│ │ 13:03:11 monkey-ai [INFO] relay start ch=3 model=sonnet-5 org=A │ │ +│ │ 13:04:12 monkey-ai [ERROR] do request failed: 502 Bad Gateway │ │ +│ │ 13:04:12 monkey-ai [WARN] channel 3 status_reason=upstream_5xx │ │ +│ │ [在 VictoriaLogs 中打开 ▸] │ │ +│ └────────────────────────────────────────────────────────────────────────┘ │ +│ ┌ 原始报文(仅 error dump 开启时可用,脱敏后)───────────────────────────┐ │ +│ │ 请求头/体摘要 · 响应头/体(32KB 截断) [申请查看完整报文 ▸] │ │ +│ └────────────────────────────────────────────────────────────────────────┘ │ +│ │ +│ [同企业相似失败 ▸] [同模型相似失败 ▸] [复现命令(curl) ▸] [标记为已知问题 ▸] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- Trace 瀑布图里 `dns/tcp/tls/ttfb` 的四段拆分是解决余光那类问题的关键——它把"慢在哪"从推测变成读数。 +- `ⓘ 本请求未经过 CPA/CRS/tls` 这类说明必须有,否则运维会以为是链路数据丢了。 +- **原始报文默认不展示、需申请**——因为 dump 就是 cct01 那 13 GB 的来源。看板提供按需拉取,而不是常开全量落盘。 + +### P3.7' · 走自建 CRS 时的完整瀑布(L3 变体) + +``` + nginx.request ├┤ 2ms ✅ + monkey-ai.relay ├────────────────────────────────┤ 24.1s ✅ + ├ channel.select ├┤ 6ms channel_id=17 vendor=自建CRS + └ cpa.handle ├───────────────────────────────┤ 24.0s + ├ cpa.disguise ├┤ 38ms profile=v220 cch=5位✅ suffix=computed✅ + └ crs.relay ├──────────────────────────────┤ 23.9s + ├ crs.account.select ├┤ 11ms account=Claude_WY_33 sticky=hit + ├ crs.dynamicDelay ├─┤ 310ms ⚠ 被 perKCacheRead 放大 + ├ crs.queue ├┤ 4ms concurrency 3/10 + └ tls.forward ├────────────────────────┤ 23.5s + ├ socks.connect ├─┤ 180ms proxy=ipdeep:7085(user_a1) + └ upstream.anthropic ├──────────────────────┤ 23.3s + └ ttfb 1.9s / stream 21.4s + ───────────────────────────────────────────────────────────────── + 内部合计 0.55s (2.3%) 外部合计 23.5s (97.7%) +``` + +这张图一旦存在,「是不是你们系统慢」这个问题的回答时间从 **3 天** 变成 **一次点击**。 + +--- + +## 6.6 告警页面组 + +### P4.1 · 告警中心 + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ 告警中心 [未恢复 ▾] [全部级别 ▾] [全部层 ▾] [全部负责人 ▾] ⚙ 规则管理│ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 未恢复 5 今日新增 12 今日恢复 7 平均恢复时长 34min 误报标记 2 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 级 状态 标题 层 持续 负责人 操作 │ +│ P1 🔴触发 cct01 磁盘预测 1.4 天满盘 基础 2h — [认领][下钻▸] │ +│ └ 规则 #2 磁盘预测满盘 <7天 │ 当前 81% │ 24h +4.7G │ [静默▾][标记误报] │ +│ P1 🔴触发 sma 请求量偏离基线 99.9% 业务 27h — [认领][下钻▸] │ +│ └ 规则 #4 品牌流量基线偏离 │ 3 条 vs 基线 2817+ │ 影响 1 品牌全部客户 │ +│ P2 🟠触发 渠道#3 星算 上游故障率 8.4% 业务 18m 张三 [下钻▸] │ +│ P2 🟠触发 线路 ipdeep:7085(user_b2) 4.2% 业务 12m 张三 [下钻▸] │ +│ P3 🟡稳态 crs3/crs227 Redis 策略偏离 服务 稳态 — [下钻▸] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ 已恢复(近 24h) │ +│ P2 ✅恢复 hivetoken 5xx 3.7% → 0.2% 业务 持续 42min 09-21 08:14 │ +│ P3 ✅恢复 web154 monkey-ai-sma CPU 28% 服务 持续 11min 09-21 06:02 │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ★ 告警健康度(防止告警系统自己变成噪音源) │ +│ 近 7 日触发 TOP 误报率 平均恢复 是否建议调整 │ +│ 规则#9 渠道成功率 18 次 0% 34min ✅ 合理 │ +│ 规则#13 线路失败率 31 次 19% ⚠ 8min ⚠ 建议提高最小样本量至 50 │ +│ 规则#15 探活失败 7 次 71% 🔴 2min 🔴 建议改为连续 5 次 │ +│ ⓘ 误报率 >30% 的规则会被自动标记;连续两周无人处理的规则建议下线 │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **告警行必须自带"判据摘要"折叠行**(规则名 + 当前值 + 阈值 + 影响面)。只给一句"磁盘告警",收到的人第一反应是去查这是什么规则;把判据写在告警里,认领的人直接就能判断要不要动。 +- **「认领」是一等操作。** 未认领的 P1 会持续升级(企微 → @所有人 → 电话);认领后进入静默期并记录责任人。没有认领机制的告警系统,最终会变成"所有人都以为别人在处理"。 +- **右下角的「告警健康度」是这一页最反常规也最重要的模块。** 它监控的是告警系统自己:误报率 71% 的探活规则如果不被发现并调整,两周内所有人都会把通知静音,整套系统随之报废。这是对"最小样本量和静默期不是可选项"那条教训的制度化延伸——**光有静默期不够,还要有机制发现哪条规则在制造噪音。** +- 「稳态」是独立于「触发/恢复」的第三种状态,用于 Redis 策略偏离这类**长期存在但不会自动恢复**的配置问题。否则它们要么天天重复告警,要么被一次静默永久埋掉。 + +### P4.2 · 规则配置 + +``` +┌──────────────────────────────────────────────────────────────────────────────┐ +│ 规则管理 18 条启用 / 3 条停用 [+ 新建规则] [从模板导入] [导出] │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ # 级别 名称 作用域 条件 状态 近7日 │ +│ 1 P2 磁盘使用率 全部主机 >85% ● 0 │ +│ 2 P1 磁盘预测满盘 全部主机 外推 <7 天 ● 1 │ +│ 4 P1 品牌流量基线偏离 全部品牌 <基线20% 持续30m ● 1 │ +│ 9 P2 渠道成功率 全部渠道 <90% 样本≥50 ● 18 │ +│ 12 P1 CRS账号空回复率 全部账号 >30% 样本≥10 ● 0 │ +│ 16 P1 探活绿但质量红 全部品牌 探活ok且成功率<90 ● 0 │ +│ … │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ ▾ 编辑规则 #9「渠道成功率」 │ +│ │ +│ 作用域 ○全局 ●按维度 维度[渠道 ▾] 范围 ○全部 ●指定 [#3,#34,#90 ▾] │ +│ └ 可选维度:主机/进程/品牌/模型/渠道/供应商/企业/CRS账号/出口线路 │ +│ 指标 [成功率 ▾] 条件 [< ▾] [90] % │ +│ ★最小样本量 [50] 条 ⓘ 低于此值直接不评估(必填,默认 30) │ +│ ★持续时长 [10] 分钟 ⓘ 连续满足才触发,防抖 │ +│ ★静默期 [30] 分钟 ⓘ 同规则同作用域窗口内只发一次(必填) │ +│ 分级 ○P1 ●P2 ○P3 恢复通知 ☑ │ +│ 通知 ☑企微群[运维群 ▾] ☐邮件 ☐短信 ☐自定义webhook │ +│ 生效时段 ●全天 ○仅工作时间 ○自定义 [__:__ – __:__] │ +│ 负责人 [张三 ▾] 升级策略 [15分钟未认领 → @所有人 ▾] │ +│ │ +│ ┌ 回溯校验(保存前必做)───────────────────────────────────────────────┐ │ +│ │ 用近 30 天数据重放本规则: │ │ +│ │ 将触发 23 次 · 其中与已知故障重合 19 次 · 疑似误报 4 次 │ │ +│ │ 最长持续 42min · 最短 3min │ │ +│ │ ▁▁█▁▁▁██▁▁▁▁█▁▁▁▁▁██▁▁▁█▁▁▁▁ │ │ +│ │ ⓘ 若疑似误报 >30%,建议提高最小样本量或持续时长 [重新校验] │ │ +│ └──────────────────────────────────────────────────────────────────────┘ │ +│ [取消] [保存并启用] [仅保存草稿] │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +**设计要点** + +- **「最小样本量 / 持续时长 / 静默期」三个字段带 ★ 且不可留空。** 这是把一条教训做成表单约束——没有它们,凌晨低峰期"1 次失败 = 100% 故障率"会让告警在第一周被全员静音。UI 层面禁止用户跳过,比写在文档里管用。 +- **「回溯校验」是这一页的核心创新。** 保存前用近 30 天真实数据重放这条规则,直接告诉用户"它会触发多少次、多少次踩中了真实故障、多少次是噪音"。**没有回溯校验,配阈值就是纯猜**,而猜错的代价是整套告警系统的可信度。 +- **作用域是"维度 + 范围"两段式**,而不是一个自由输入框。维度列表直接对应 §5.1 定义的统一标签集,保证规则能落到真实存在的标签上,避免配出永远不会触发的规则。 +- 「生效时段」和「升级策略」是给 P1 用的:磁盘告警可以等上班看,生产双挂必须半夜叫醒,这个差异必须可配置而不是硬编码。 + +--- + +## 6.7 跨层串联总线(这是"业务之间能串联分析"的完整答案) + +三层不是三个独立的看板,而是通过**统一标签集**(§5.1)织成的一张网。下面是全部可用的跳转路径: + +``` + ┌─────────────── P0 全局总览 ───────────────┐ + │ 基础卡片 服务卡片 业务卡片 │ + └────┬──────────────┬──────────────┬────────┘ + ▼ ▼ ▼ + ┌───────────────────────────┐ ┌──────────────┐ ┌──────────────────────┐ + │ P1.1 主机矩阵 │ │P2.1 进程中间件│ │P3.1 品牌×模型+供应商 │ + │ ▼ │ │ ▼ │ │P3.2 CRS 域 │ + │ P1.2 单主机 ──host──────────▶P2.2 单进程 │ │ ▼ │ + │ ▼ │ │ ▼ │ │P3.3 品牌 P3.4 渠道 │ + │ P1.3 目录 P1.4 网络 │ │P2.3 重启事件 │ │P3.5 账号 P3.6 线路 │ + └────┬───────────┬──────────┘ └──────┬───────┘ └──────────┬───────────┘ + │ │ │ │ + │requestID │proxy_line │trace_id │ + │ │ │ │ + └───────────┴───────────────────┴────────────────────┘ + ▼ + ┌──────────────────────────────────┐ + │ P3.7 单请求 Trace 瀑布 + 原始日志│ ← 所有路径的汇聚点 + └──────────────────────────────────┘ +``` + +**七条已明确定义的串联路径** + +| # | 从 | 到 | 串联键 | 解决的问题 | +|---|---|---|---|---| +| 1 | P1.3 dump 文件 | P3.7 Trace | `requestID`(在文件名尾部) | 这个 18MB 的文件是哪条请求产生的 | +| 2 | P1.4 出境连接 | P3.6 线路详情 | `proxy_line`(host:port:user) | OS 看到的连接 vs 业务看到的线路是否一致 | +| 3 | P2.3 重启事件 | P3.7 在途请求 | `trace_id` + 时间窗 | 这次重启丢了哪些请求、被错误归因成什么 | +| 4 | P2.4 Redis | P3.5 账号 | `crs_account` | 淘汰策略影响了哪些账号的粘性会话 | +| 5 | P2.6 nginx 域名 | P3.3 品牌 | `brand` | 边缘层看到的流量 vs 业务层记录的请求是否对得上 | +| 6 | P3.4 渠道 | P3.2 CRS 域 | `vendor=自建CRS` → `channel_id` | 上游故障率高,到底是哪个账号/哪条线路 | +| 7 | P3.5 账号 | P1.2 宿主机 | `host` | 账号异常是不是宿主机资源问题引起的 | + +**路径 3 和路径 5 是最有价值的两条**,因为它们能发现**归因偏差**: + +- 路径 3:进程重启导致的中断,在业务层被记成"客户端中断",真实责任方是平台。不打通这条路径,平台侧的锅会长期挂在客户头上,成功率指标会系统性偏高。 +- 路径 5:nginx 记录的请求数与 newapi 记录的请求数如果对不上,说明有请求在边缘层就被丢了(限流/拦截/超时),而业务层完全看不见这部分。sma 断流那 27 小时,就需要这条路径来确定断点在 nginx 之前还是之后。 + +**为什么不做成"一个大而全的页面"**:因为排查时的心智是"顺着一条线索走",不是"同时看 20 个指标"。每个页面只回答一个问题,但都知道自己旁边还有谁——这比把所有东西堆在一屏更直观,也更容易在告警里直接给出落点链接。 + +--- + +## 七、告警设计(可配置) + +### 7.1 规则模型 + +``` +规则 = 作用域 + 指标 + 条件 + 最小样本量 + 持续时长 + 静默期 + 分级 + 通知渠道 +``` + +| 字段 | 说明 | +|---|---| +| 作用域 | 全局 / 主机 / 进程 / 品牌 / 模型 / 渠道 / vendor / 企业 / CRS账号 / 出口线路 | +| 指标 | 成功率、上游故障率、P95、请求量、兜底失败率、空回复率、429率、磁盘%、磁盘增长率、内存水位、重启率、探活、Redis策略、键数… | +| 条件 | `<` `>` `偏离基线 N%` `连续 N 个周期` `同比/环比` | +| **最小样本量** | **必填**,默认 30。样本不足直接不评估 | +| **静默期** | **必填**,默认 30 分钟。同一规则同一作用域在窗口内只发一次 | +| 分级 | P1 电话+企微@所有人 / P2 企微群 / P3 日报汇总 | +| 通知渠道 | 企微 webhook / 邮件 / 短信 / 自定义 webhook | +| 恢复通知 | 默认开 | + +> **最小样本量与静默期不是可选项**——这是质量看板设计方案 §10 的原话,也是它唯一被实践反复验证的结论。没有它们,凌晨低峰期「1 次失败 = 100% 故障率」会让告警在第一周被所有人静音。 + +### 7.2 分级标准 + +| 级别 | 定义 | 通知 | 本次实测中的例子 | +|---|---|---|---| +| **P1** | 正在造成或 24h 内必然造成生产不可用 | 立即电话 + 企微 @所有人 | cct01 磁盘按 09-18 速率 1.4 天满盘;sma 断流 | +| **P2** | 已影响部分用户,但系统仍在服务 | 企微群,5 分钟聚合 | 渠道故障率 8.4%;线路 502 率 4.2% | +| **P3** | 隐患/配置偏离,可等上班处理 | 每日 09:30 汇总日报 | Redis 策略 allkeys-lru;aibiyi/youlangg 共用 db4 | + +### 7.3 必须首批配置的规则(覆盖已发生过的每一类事故) + +| # | 规则 | 条件 | 级别 | 对应历史事故 | +|---|---|---|---|---| +| 1 | 磁盘使用率 | > 85% | P2 | crs3 12GB | +| 2 | **磁盘预测满盘** | 按近 24h 增长率外推 < 7 天 | **P1** | **cct01 dump 13GB(当前触发)** | +| 3 | 单目录日增 | 任一日志/数据目录 24h 增长 > 2 GB | P2 | cct01 dump | +| 4 | **品牌流量基线偏离** | 请求量 < 基线 20% 且持续 > 30min | **P1** | **sma 断流 27h** | +| 5 | 进程 RSS 水位 | > `max_memory_restart` 的 85% | P2 | crs3 11 次 OOM | +| 6 | 进程重启率 | 1h 内 ≥ 3 次 | P1 | crs3 11 次/日 | +| 7 | Redis maxmemory-policy | ≠ `noeviction` | P3 | crs3/crs227 当前触发 | +| 8 | Redis 内存水位 | > 80% maxmemory | P2 | — | +| 9 | 渠道成功率 | < 90%,样本 ≥ 50,持续 10min | P2 | 渠道 62 的 44% 500 率 | +| 10 | 上游故障率 | > 5%,样本 ≥ 50 | P2 | 星算 8.4% | +| 11 | **跨组降级** | `use_channel` 链出现跨分组,任意 1 次 | **P1** | **官key 分组静默降级 10 天** | +| 12 | **CRS 账号空回复率** | > 30%,样本 ≥ 10,持续 5min | **P1** | **WY_95 滞后 95 分钟** | +| 13 | 出口线路失败率 | > 2%,样本 ≥ 30 | P2 | ipdeep 502 成簇 | +| 14 | reroute 配额耗尽 | 2/2 用满 | P3 | — | +| 15 | 探活失败 | 连续 3 次 | P2 | — | +| 16 | **探活绿但质量红** | 探活 ok 且成功率 < 90% | **P1** | 设计方案附录 A 原话 | +| 17 | P95 劣化 | 环比 +100% 且绝对值 > 60s | P2 | 余光 | +| 18 | 兜底失败率 | > 5%,样本 ≥ 20 | P2 | — | + +规则 4 与规则 16 是本方案相对现有质量看板的**根本性增量**:一个解决"分母为 0 时全绿",一个解决"探活绿但真实流量红"。 + +--- + +## 八、分批实施 + +> 质量看板 §14 的教训:两轮静态评审后缺陷严重度没有递减,结论是「本文档是目标形态 + 避雷清单,不是一次性实施蓝图」。方向 B 跨 4 个仓库,这条教训更适用。**一步到位是目标,不是交付节奏。** + +### 第 0 批 · 止血(不依赖监控平台,今天就能做) + +| 动作 | 目标 | 风险 | +|---|---|---| +| cct01 关闭三个 dump 开关,清理 13 GB `auth/logs` 与 8 个 2026-08-05 残留 `.tmp` | 磁盘 81% → 约 55% | 低,dump 是调试用 | +| cct01 补 `/etc/logrotate.d/wy-stack0`,覆盖 `wy_crs/out.log`(2.7G) 等 | 阻断复发 | 低 | +| cct01 清理旧 release(保留 2 份) | 回收约 2.5 GB | 低 | +| crs01 清理 `/home/weiyuan/logs` 4.3 GB | | 低 | +| crs3 / crs227 Redis 改 `noeviction` | 消除静默淘汰 | **中——须先确认 2G 上限下不会 OOM 拒写** | +| 排查 sma 断流 27h 的根因 | | — | + +> 这一批涉及生产机写操作,**我不会擅自执行,需要你逐项授权**。其中 Redis 策略变更风险最高(`noeviction` 下撑满 2G 会开始拒写),建议先扩 maxmemory 或确认键 TTL 覆盖率后再改。 + +### 第 1 批 · 基础层 + 服务层(约 1 周,零业务代码改动) + +监控机部署 VM/VictoriaLogs/Tempo/Grafana/vmalert/Alertmanager → 5 台装 node_exporter + vmagent + Vector → redis/mysqld/blackbox exporter → L0/L1 基础与服务层页面 → 规则 1–8、15 上线。 + +**这一批结束时,cct01 那类事故就再也不会在无人知晓的情况下发生。** + +### 第 2 批 · nginx 边缘层 + 日志结构化(约 3 天,只改配置) + +改 `log_format` 加 `$request_time $upstream_response_time $upstream_addr $upstream_status $host`,API location 的 `access_log off` 改为写入独立文件 → Vector 解析入库 → L0 链路条的 nginx 段点亮。 + +**性价比最高的一批:只改 nginx 配置,就拿到全站按域名/上游的延迟分布。** + +### 第 3 批 · 业务层指标化(约 1 周,monkey-ai 单仓) + +`monitor_outcome_stat` 导出为 Prometheus 指标 → vendor 归并表(渠道 → 供应商)→ 品牌流量基线 → L1/L2 业务页面 → 规则 4、9–11、16–18 上线 → **把 `monitor_alert_rule` 从 0 条填起来** → 看板下发到 7 个马甲库。 + +### 第 4 批 · CRS 侧业务层(约 1 周,零侵入) + +Redis 直读账号状态 + reroute JSONL + Vector 解析 tls 日志 → L1' CRS 域页面 → 规则 12–14 上线。 + +### 第 5 批 · Traces(约 2–3 周,跨 4 仓,灰度) + +`traceparent` 贯通 nginx → monkey-ai → CPA → CRS → tls → OTel Collector → Tempo → L3 瀑布图 → 三栈联动跳转。 + +**灰度路径**:单机验证 → ltop(小流量马甲)→ sma → weelinking。每步可独立回滚,`OTEL_ENABLED` 默认关。 + +--- + +## 九、风险与待确认 + +| # | 风险/待确认 | 影响 | 建议 | +|---|---|---|---| +| 1 | **监控机放国内还是香港** | 决定 MySQL/Redis 能否直连 | 建议国内与 web154 同 VPC(172.16.0.x);cct VPC Redis 必须本地 exporter 推出 | +| 2 | **APISIX 万级并发方案还做不做** | 若做,选型须对齐 | 需你确认。本方案选 VM 而非 Prometheus,若 APISIX 方案坚持 Prometheus,两者 remote_write 兼容,可共存 | +| 3 | Redis 改 `noeviction` 可能触发拒写 | 生产影响 | 先测键 TTL 覆盖率与增长曲线,或先扩 maxmemory | +| 4 | Traces 侵入 4 个仓库 | 最大技术风险 | 全局开关 + 异步导出 + 有界队列 + 灰度;且排在最后一批 | +| 5 | 质量看板"实库冒烟未执行" | 第 3 批依赖它 | 实测表在持续写入(13,700 行至今天 13:05),事实上已在跑;但正式验收结论仍需确认 | +| 6 | 9 品牌 × 40 模型 × 90 渠道基数 | Metrics 序列爆炸 | 已在 §5.1 定死基数控制规则,`org_id` 不入 TSDB | +| 7 | 口径分裂 | 整套系统可信度 | `outcome`/`fault_side` 强制复用现有枚举,不得另定义 | +| 8 | web154 主实例为何是 4 个进程 | 影响进程监控建模 | 需现场确认是 pm2 多实例还是子进程 | +| 9 | 业务 Redis 172.16.0.3 的策略与水位未测 | 未知隐患 | 第 1 批部署 redis_exporter 后即得 | + +--- + +## 十、一句话总结 + +实测下来,这套系统的**监控难度远低于预期**——25K 请求/天、5 台机器、CPU 内存全线富余,一台 4C8G 是数量级的富余,甚至可以 100% 全采样 Traces。 + +**真正的问题不是"数据难采",而是"根本没人在采"**:nginx 把业务日志关了,质量看板建好了但告警规则是 0 条,cct01 的 dump 悄悄长到 13 GB,sma 断流 27 小时至今无人知晓。 + +所以这个平台最大的价值不在技术含量,而在**把已经存在却没人看的信号,变成会主动叫醒你的告警**。 + +--- + +## 附:本次采集的原始事实清单(可复核) + +| 编号 | 事实 | 采集方式 | +|---|---|---| +| F1 | crs3 磁盘 44%,logrotate 已配 | `df -h` / `ls /etc/logrotate.d/` | +| F2 | crs01 与 cct01 同机(VM-0-17-ubuntu) | `hostname` × 2 | +| F3 | cct01 `data/wy_cpa/auth/logs` 13 GB / 5501 文件,09-18 单日 6.9 GB | `du` / `find -printf` 聚合 | +| F4 | 三个 dump 开关全为 true | `grep` config/*.env | +| F5 | cct01 `wy_crs/out.log` 2.7 GB 自 2026-07-31 未轮转 | `ls -la` / `head` 首行时间戳 | +| F6 | crs3/crs227 Redis `allkeys-lru`;cct 共享 Redis `noeviction` | `INFO memory` × 3 | +| F7 | 账号池 claude 5 / openai 29 / apikey 60 | Redis `SCAN` × 4 环境 | +| F8 | 8 个 newapi 实例、9 品牌、各自独立主库+日志库+Redis db | `.env` 枚举 + `information_schema` | +| F9 | aibiyi 与 youlangg 共用 Redis db4 | `.env` 对比 | +| F10 | 近 7 天请求量 2.5K–17.7K/天 | `weelinking_log.logs` 聚合 | +| F11 | sma 09-18 21:00 → 09-20 00:00 断流 | `weelinking_sma_log.logs` 按小时聚合 | +| F12 | `monitor_outcome_stat` 13,700 行,2026-09-17 起持续写入 | `information_schema` + 维度聚合 | +| F13 | `monitor_alert_rule` / `monitor_alert_event` 均 0 行 | 同上 | +| F14 | 马甲库无 `monitor_*` 表 | 同上 | +| F15 | 40 启用渠道中仅 1 个指向自建 CRS | `channels` 表全量 | +| F16 | web154 无 nginx | `ss -lntp` + `systemctl` | +| F17 | nginx API location `access_log off`,格式为默认 combined | `grep` conf.d/weelinking.conf | +| F18 | nginx access.log 今日 1493 行且全为扫描器 | `wc -l` + `tail` 抽样 | +| F19 | 全仓零 OTel 依赖,四层三套互不传递的 ID | 跨 4 仓 `grep` | +| F20 | crs3.crs 38↺ / crs01.wy-crs 40↺,uptime 均 38h | `pm2 list` × 4 | + +> 说明:本文档不含任何账号口令。采集过程中读到的 DSN / Redis 密码等凭据一律未写入本文档或任何仓库文件;需要时从各机 `.env` / `config/.secrets` 现场读取。 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0d87b13 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,381 @@ +# Codex Handoff: Weiyuan Observability + +## Purpose + +This workspace is for implementing a three-layer observability and alerting platform for the `monkey-ai` system and its white-label branches. The intended end state correlates Metrics, Logs, and Traces across hosts, services, brands, upstream vendors, and individual requests. + +The user wants the work performed incrementally. On 2026-10-15 the user changed the immediate task to starting Docker Desktop locally, running smoke tests, and monitoring the already-running local new-api application first. Test-server deployment follows local validation; production and application repository changes remain separately scoped. + +## Production Deployment Request (2026-10-15) + +- User explicitly authorized deploying the current monitoring project to SSH alias `server134-rot`, directory `/opt/observability/`, and committing/pushing this workspace to `https://git.weytoken.com/qiubs/observability.git`. +- This authorization supersedes the historical test-server-only scope for this target. It does not authorize unrelated application/DB/firewall/nginx changes or public exposure. +- Remote Git had no refs when checked. Initialized local main using the existing identity from the adjacent monkey-ai checkout; initial import/push is in progress. +- User corrected SSH configuration: `root@134.175.227.134:22`. Connection and read-only checks succeeded: Ubuntu 22.04.5, x86_64, 2 CPUs, 7.6 GiB RAM (5.7 GiB available), 49 GiB disk available, Docker 29.1.3, Compose 2.40.3, synchronized time. +- `/opt/observability/` contains older project files, but no running monitoring containers or monitoring data/. Preserve these with a backup before upload. Existing application listeners use 3000 and 3001; do not restart them. +- Keep all monitoring ports on loopback. Set GRAFANA_PORT=3002; suggested workstation tunnel ports: 13000 -> remote 3002, 19093 -> remote 9093. +- Server-specific config: VMAGENT_CONFIG=./config/vmagent/prometheus.server134.yml, VM_RETENTION=30d, VL_RETENTION=7d. Tempo remains 30d; no real trace ingestion is configured. Expand disk capacity before broad log/trace ingestion. +- Server `prepare.sh` now restricts `.env` to mode 0600 and does not print the generated Grafana password. +- Production app/MySQL targets have not been supplied; do not upload local credentials or use the Windows host.docker.internal target on Linux. +- The user subsequently supplied a screenshot showing local mysql_up=1. This updates the older credentials-absent snapshot below, but is not a new independently executed full MySQL smoke check. + +## Local Validation History (2026-10-15) + +This section supersedes the older test-server-first workspace snapshot below. + +- User confirmed that "newpai" means new-api / monkey-ai application layer and supplied `http://127.0.0.1:3000`, already running. +- The process on port 3000 is `D:\project\safe_change\tmp\new-api-toolargs-full.exe`; do not assume it is the old `monkey-ai-weiyuan-inspection` checkout. Its `/api/status` returned HTTP 200 and `success: true`. No application source or process was changed. +- Docker Desktop Linux engine was started. Docker Engine is 29.5.2, Compose is v5.1.4; the Docker VM reports 16 CPUs and about 8 GB RAM. +- Local instructions: `deploy/monitoring/README.local.md`. Run `py -3 deploy/monitoring/scripts/local.py {check,up,smoke,ps,logs,down}` from the workspace root. +- Local Compose merges `docker-compose.yml` and `docker-compose.local.yml`; project/network are `observability-local`. Named volumes persist storage. `node-exporter` is excluded because it would observe the Docker VM, not Windows. +- Grafana uses `http://127.0.0.1:3001/d/new-api-local`; the application keeps port 3000. Alertmanager is `http://127.0.0.1:9093`. Every monitoring published port binds loopback. +- Local password is outside the workspace at `%LOCALAPPDATA%\weiyuan-observability\grafana-admin-password.txt` (admin user), with a user-only Windows ACL and Compose secret mount. Never copy its contents into this workspace or chat. Local deployment does not create `.env`. +- The launcher reads effective Compose JSON for port preflight rather than duplicating a list. It checks Docker mappings and actual TCP binds, permits the corresponding project's existing service, and fails before pull/up on conflicts. Six Python port tests plus four existing Bash port tests passed. +- Blackbox exporter v0.27.0 probes `http://host.docker.internal:3000/api/status` every 15 seconds, requiring HTTP 200 and `success: true`. Local rules alert on probe failure or scrape failure after two minutes. Alertmanager still has no external notification destination. +- Current application monitoring is ONLY status endpoint availability, HTTP status and probe duration. Business success rate, application logs, business traces, traffic baselines and cross-navigation are not implemented by this probe. Preserve `service/monitor` semantics when adding them later. +- Runtime testing exposed invalid Tempo 2.x configuration for the pinned Tempo 3.0.3 image. The shared config now uses `overrides.defaults.compaction.block_retention: 720h`; old `ingester` and `compactor` fields were removed. Tempo config verification and exact trace readback passed. +- `scripts/smoke.py` writes fresh unique synthetic metrics/logs/traces and polls exact readback. It avoids the previous seconds-as-milliseconds metric timestamp and stale-data false passes. `smoke-test.sh` delegates to it; telemetrygen is no longer required by the smoke test. +- Grafana now synchronously installs the pinned VictoriaLogs plugin and disables preinstall auto-updates. First startup downloads about 78 MB; local smoke waits up to 10 minutes for Grafana, then authenticates and verifies all three datasources and the application dashboard. +- Copying this workspace to another computer does NOT transfer local Docker named-volume data or the external password. New local startup creates fresh storage and credentials. + +Final local validation on 2026-10-15: + +- Eight local monitoring containers running, all published ports loopback. Nine configured scrape targets healthy (eight components plus the application probe). +- `py -3 deploy/monitoring/scripts/local.py smoke` exited 0 and printed `Local stack, application probe and Grafana checks all passed.` +- Successful synthetic run: `8b7f2181b7f5a99f`; trace: `9a2b6e754911e70dfd4163e4cf108475`. These are synthetic identifiers, not business request data. +- Metrics, Logs, exact OTLP HTTP trace readback, application HTTP 200/probe_success=1, all scrapes, all three authenticated Grafana datasource health checks and the new-api dashboard passed. +- Direct blackbox positive and negative checks passed: real application => success=1; isolated unreachable test address => success=0. The user's application was never stopped. +- Six Python port checks, four Bash port checks, each shell file's syntax, Python compilation, base/merged Compose parsing and YAML/JSON formatting passed. +- Initial failures were Tempo's obsolete config keys and the Grafana plugin's slow first download. The fixed plugin installed successfully (roughly 8 minutes on this network). Startup health errors must not be confused with final results. +- LocalMonitoringTargetDown was observed in Alertmanager while Grafana waited for the plugin. After readiness, both local rules became healthy/inactive and Alertmanager returned zero active alerts. This verifies local component alert delivery/recovery; external notifications and an application-outage/recovery drill are still untested. +- No remote server or production deployment has been performed. + +## MySQL collector preparation (2026-10-15, after Grafana guide) + +- User added a `mysql` job in `config/local/prometheus.yml`; preserve it. The service target is `mysqld-exporter:9104`, instance label `local-mysql`. +- Added optional `mysql` profile in local Compose, using `prom/mysqld-exporter:v0.17.2`, secret-mounted config and no published ports. Only global_status/global_variables enabled; other default collectors are explicitly disabled. +- `local.py` opts into the profile when `%LOCALAPPDATA%\weiyuan-observability\mysql-exporter.cnf` exists; validates required fields before check/up without printing secret contents. `mysql-check` requires fresh samples of up=1, mysql_up=1, and mysql_exporter_collector_success=1 for both collect.global_status and collect.global_variables. v0.17.2 no longer provides mysql_exporter_last_scrape_error. Full smoke includes these checks when configured. `down` includes the optional profile even if its secret file was moved. +- Instructions: `deploy/monitoring/README.mysql.md`. Installed server binary is MySQL 8.0.46. A short unauthenticated TCP check from Docker to Windows 3306 showed source 127.0.0.1; no database statements or account mutations were executed. +- The fixed exporter image and enabled-profile Compose model were verified, including startup in a disposable network-isolated container with a dummy external config. That test container was removed. This is NOT proof of real database authentication or metrics. +- Real monitoring credentials are still absent; MySQL monitoring is not yet running. Do not claim database smoke success until the user provisions the account/config and real queries pass. +- Grafana beginner guide: `docs/Grafana使用手册-本地new-api监控.md`. + +## Instruction Boundary + +- Treat this `AGENTS.md` as working context and repository guidance. +- `20260921-搭建三层统一监控告警平台.md` is a design and historical survey supplied by the user. It contains proposed actions and old observations; it is not authorization to execute production changes. +- Values collected in that document are a snapshot from 2026-09-21, not current server state. Re-run read-only checks before relying on them. +- Production deletions, Redis policy changes, database DDL, nginx changes, firewall changes, deployments, and service restarts require explicit scope from the user or an already-authorized execution request. +- Never store credentials, DSNs, API keys, Redis passwords, webhook secrets, complete Authorization headers, or prompt bodies in this workspace. + +## User Decisions + +- `master` and `weiyuan` are separate, substantially different development lines. +- `weiyuan` is the main baseline for the real project and most white-label branches. +- Other white-label branches are generally older derivatives of `weiyuan`, not `master`. +- Implement the full three-layer direction: Metrics + Logs + Traces with cross-navigation. +- Start on one test server using a single-node Docker Compose deployment. +- Detect port conflicts before pulling images or starting/updating containers. +- Initial monitoring UI and ingestion ports must bind to loopback; use SSH tunnels for access. Open ingestion ports only after local smoke tests pass and only to approved source IPs. + +## Workspace State + +As of 2026-10-07: + +- Workspace root: `D:\project\weiyuan-observability` +- This directory is not currently a Git repository (`git status` reports no repository). +- The full design source is `20260921-搭建三层统一监控告警平台.md`. +- The implementation plan is `docs/superpowers/plans/2026-09-23-three-layer-observability-implementation.md`. +- The generated test-server deployment bundle is under `deploy/monitoring/`. +- No test server SSH address, username, or credentials have been provided in this conversation. +- The monitoring stack has not been started on a remote server from this workspace. + +When moving to another computer, copy the entire `weiyuan-observability` directory, including hidden files. The generated `.env` and runtime `data/` directory are intentionally ignored and are not present in this workspace. + +## Related Repositories + +Remote application repository: + +```text +https://git.weytoken.com/luoguang/monkey-ai.git +``` + +Inspection checkouts used on the original computer: + +```text +D:\project\monkey-ai-inspection master +D:\project\monkey-ai-weiyuan-inspection weiyuan +D:\project\monkey-ai developer working checkout +``` + +The developer working checkout had unrelated user changes when inspected on 2026-09-23 (`web/bun.lock` modified and two DOCX files untracked). Do not discard or overwrite unrelated changes. + +Remote heads last verified on 2026-09-23: + +```text +weiyuan 1eeb66a72e7ada77c9692643f847134163982cac +master d149c427d9fa76396200c447f5201fed9c1b53e1 +sma fb39862511da8900def58847b5a796ad2582bd1f +ltop e90b4f7558cb0464b378694a79b750d3f4778008 +hivetoken 01265293216c0df74d23204a7fffc9d4b81db1ee +aibiyi 7c784a7bcd78f7e99fbe316e94339135206975e0 +paixtoken 2264d8d9ab4eef7d8bcf95a7435c920e9ccb8e68 +tv 5b6052c45167c1765363406d541c8fb8f4c12679 +youlangg a3976e457f513bdc3577df82bd6ffcd50f672d88 +``` + +These SHA values are historical reference points. Run `git ls-remote --heads` or `git fetch` before new branch work. + +Branch history findings: + +- `master` and `weiyuan` diverged after common commit `73ed70f2` from 2026-06-14. At the time of inspection they had 21 and 581 unique commits respectively. +- `sma` was an old `weiyuan` snapshot from 2026-09-14. +- `hivetoken`, `aibiyi`, `paixtoken`, `tv`, `youlangg`, and `vest-baseline` shared a 2026-08-25 `weiyuan` base. +- `ltop` diverged earlier around 2026-07-23. +- The quality monitoring feature entered `weiyuan` in commit `24710573` on 2026-09-16. None of the listed white-label heads contained its core files when inspected. +- `马甲包分支指南.md` inside the application repository says all white-label branches use `master` and references an old remote. That guide is stale for this project and must not override the user's branch decision above. + +## Existing `weiyuan` Monitoring Capability + +`weiyuan` already contains an application-level call-quality subsystem. Do not redesign its outcome model. + +Relevant files: + +```text +model/monitor_quality.go +service/monitor/ +middleware/monitor_outcome.go +controller/monitor_quality_record.go +controller/analytics_quality.go +web/src/components/quality/ +web/src/pages/Analytics/index.jsx +web/src/pages/Organization/OrgQuality.jsx +main.go +``` + +Implemented behavior: + +- Six outcomes: direct success, fallback success, fallback exhausted, failure without fallback, client abort, content block. +- Five fault sides and model/channel/group/organization/error/path dimensions. +- In-memory collection with a 15-second database flush. +- Async task terminal-state scanning. +- Platform and organization quality dashboards and detail queries. +- Alert rules with minimum samples, silence periods, and duplicate-event protection. +- Five-minute, hourly, and daily retention of 7 days, 400 days, and 5 years. +- Graceful shutdown flush. + +Current application alert limitations: + +- Metrics: success rate, fallback failure count, upstream fault percentage, P95 only. +- Scopes: global, model, channel, organization only. +- Alerts notify the root user through existing email/webhook/Bark/Gotify settings. +- No P1/P2/P3 workflow, acknowledgement, escalation, recovery state, or Alertmanager integration. + +Confirmed gaps: + +- Host, PM2/process, Redis, MySQL, nginx, and network observability. +- VictoriaMetrics/VictoriaLogs/Tempo/Grafana deployment. +- W3C `traceparent` across nginx -> monkey-ai -> CPA -> CRS -> tls. +- Brand traffic-baseline/no-traffic alerting and most of the 18 planned rules. +- Automatic `logs` retention. The code still only has an administrator-triggered `DeleteOldLog`; do not enable expanded error logging globally until automatic retention is implemented and tested. +- MySQL and PostgreSQL real-database smoke tests for the quality subsystem remain outstanding. + +The following test command passed in the clean `weiyuan` inspection checkout on 2026-09-23: + +```bash +go test ./service/monitor ./controller ./router ./model +``` + +Re-run it against the current remote state before making new claims. + +## Generated Test-Server Deployment + +Entry point: + +```text +deploy/monitoring/README.md +``` + +The Compose deployment includes: + +- VictoriaMetrics `v1.152.0` +- VictoriaLogs `v1.52.0` +- Grafana `13.2.2` +- Tempo `3.0.3` +- Alertmanager `v0.34.1` +- node_exporter `v1.12.1` +- vmagent and vmalert matching VictoriaMetrics `v1.152.0` +- telemetrygen `v0.161.0` for trace smoke testing +- VictoriaLogs Grafana datasource plugin `0.32.0` + +Default bind policy in `.env.example`: + +```text +UI_BIND_IP=127.0.0.1 +INGEST_BIND_IP=127.0.0.1 +DEBUG_BIND_IP=127.0.0.1 +``` + +Published ports: + +```text +3000 Grafana +9093 Alertmanager +8428 VictoriaMetrics +9428 VictoriaLogs +4317 OTLP gRPC +4318 OTLP HTTP +3200 Tempo debug/query +8880 vmalert +9100 node_exporter +8429 vmagent +``` + +`scripts/prepare.sh` performs these operations in order: + +1. Creates `.env` from `.env.example` if absent. +2. Generates a random Grafana password if the placeholder is still present. +3. Creates persistent data directories and sets container ownership. +4. Validates Compose configuration. +5. Runs `scripts/check-ports.sh`. +6. Pulls images only after port preflight succeeds. +7. Starts containers and prints status. + +Port-preflight behavior: + +- Uses a real TCP bind attempt on the configured IP and port. +- Checks Docker published ports as well as ordinary listeners. +- Rejects ports used by unrelated processes or containers. +- Allows a port already owned by the matching service in this Compose project, so upgrades remain idempotent. +- Prints `ss` and `docker ps` diagnostics and exits before changing containers on conflict. + +Do not change only `docker-compose.yml` when changing a host port. Update all three together: + +```text +deploy/monitoring/docker-compose.yml +deploy/monitoring/scripts/check-ports.sh +deploy/monitoring/scripts/smoke-test.sh +``` + +## Validation Already Performed + +The following checks passed locally after the port-preflight change: + +```text +Port tests: + unused port accepted + externally occupied port rejected + current Compose service port accepted + port published by another Docker container rejected + +Bash syntax: + install-docker-ubuntu.sh + prepare.sh + check-ports.sh + smoke-test.sh + check-ports-test.sh + +Docker Compose: + docker compose ... config --quiet passed + +Configuration formatting: + all YAML/JSON files passed Prettier check +``` + +During the historical September verification the local Docker daemon was unavailable, so those checks did not start containers. See the October local-work section above for current runtime results. Remote runtime validation is still required. + +Useful verification commands from the workspace root: + +```powershell +& 'C:\Program Files\Git\bin\bash.exe' deploy/monitoring/tests/check-ports-test.sh +Get-ChildItem deploy/monitoring/scripts/*.sh,deploy/monitoring/tests/*.sh | ForEach-Object { & 'C:\Program Files\Git\bin\bash.exe' -n $_.FullName; if ($LASTEXITCODE -ne 0) { throw "Bash syntax check failed: $($_.Name)" } } +docker compose --env-file deploy/monitoring/.env.example -f deploy/monitoring/docker-compose.yml config --quiet +npx --yes prettier@3.6.2 --check "deploy/monitoring/**/*.{yml,yaml,json}" +``` + +## Next Actions on the Other Computer + +1. Read this file, `deploy/monitoring/README.md`, and the implementation plan. +2. Confirm the test server OS, CPU/RAM/disk, architecture, SSH address, username, sudo access, Docker registry access, time synchronization, and intended data-disk mount. +3. Run read-only server checks before upload: + + ```bash + cat /etc/os-release + uname -m + nproc + free -h + df -h + timedatectl status + sudo ss -lntp + docker version || true + docker compose version || true + ``` + +4. Upload `deploy/monitoring/` and follow its README. +5. Run `sudo bash scripts/check-ports.sh` before deployment and resolve conflicts without terminating unknown services. +6. Run `sudo bash scripts/prepare.sh` and save the generated Grafana password outside the repository. +7. Run `sudo bash scripts/smoke-test.sh`. Do not state that deployment succeeded unless Metrics, Logs, and Traces smoke checks all pass. +8. Use an SSH tunnel for Grafana and Alertmanager. Keep UI/debug ports on loopback. +9. After local validation, set `INGEST_BIND_IP` to the test server's private IP and restrict 8428/9428/4317/4318 with cloud security groups or the Docker `DOCKER-USER` chain. Docker-published ports may bypass ordinary UFW INPUT rules. +10. Configure real notification receivers only after the user supplies the approved destination. Never commit webhook secrets. + +## Deployment Commands + +From a Windows workstation, replacing the SSH target: + +```powershell +scp -r D:\project\weiyuan-observability\deploy\monitoring ops@MONITOR_SERVER:/tmp/ +ssh ops@MONITOR_SERVER +``` + +On the Ubuntu test server: + +```bash +sudo mkdir -p /opt/observability +sudo cp -a /tmp/monitoring/. /opt/observability/ +cd /opt/observability +sudo bash scripts/install-docker-ubuntu.sh +sudo bash scripts/check-ports.sh +sudo bash scripts/prepare.sh +sudo bash scripts/smoke-test.sh +``` + +SSH tunnel from Windows: + +```powershell +ssh -N -L 3000:127.0.0.1:3000 -L 9093:127.0.0.1:9093 ops@MONITOR_SERVER +``` + +Rollback stops only the monitoring stack and preserves data: + +```bash +cd /opt/observability +sudo docker compose down +``` + +Never run `docker compose down -v` and never delete `/opt/observability/data` unless the user explicitly requests data destruction and a backup has been verified. + +## Broader Implementation Order + +After the central test stack is proven: + +1. Re-collect the five-host baseline read-only. +2. Address urgent disk/dump/log-rotation risks under explicit production scope. +3. Add node_exporter/vmagent/Vector and Redis/MySQL/blackbox exporters. +4. Enable structured nginx access logs and ingest them into VictoriaLogs. +5. Export/reconcile `weiyuan` business quality metrics without changing outcome semantics. +6. Complete the 18 alert rules and notification lifecycle. +7. Add CRS/vendor/egress monitoring. +8. Add Traces last, gated by `OTEL_ENABLED=false`, with canary order ltop -> sma -> small brands -> weelinking. +9. Merge current `weiyuan` into each white-label branch separately, preserving brand assets, domains, ports, and deployment templates. + +## Safety and Quality Rules + +- Read the current files before editing; this workspace may be copied with additional user changes. +- Prefer reversible actions and explicit rollback steps. +- Never use `latest` image tags. +- Never expose Grafana, Alertmanager, component debug ports, or unauthenticated ingestion endpoints to the public internet. +- Keep `org_id`, token IDs, user IDs, request bodies, and similarly high-cardinality or sensitive values out of Metrics labels. +- Reuse `service/faultclass` and `service/monitor` outcome/fault enums; do not create a second success-rate definition. +- Keep `MONITOR_QUALITY_ENABLED=false` and `OTEL_ENABLED=false` as independent rollback switches. +- Before claiming completion, run the relevant tests and runtime smoke checks and report exact failures if any. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5be18eb --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ +# Weiyuan Observability + +为 monkey-ai / new-api 及马甲包提供统一监控基础设施。当前包含 VictoriaMetrics、VictoriaLogs、Tempo、Grafana、vmagent、vmalert、Alertmanager 和 Linux node_exporter。 + +## 使用入口 + +- [Linux 服务器部署](deploy/monitoring/README.md) +- [Windows 本地 Docker 冒烟与 new-api 探测](deploy/monitoring/README.local.md) +- [本地 MySQL 采集器](deploy/monitoring/README.mysql.md) +- [Grafana 中文使用手册](docs/Grafana使用手册-本地new-api监控.md) +- [交接记录及工作约束](AGENTS.md) +- [完整实施计划](docs/superpowers/plans/2026-09-23-three-layer-observability-implementation.md) + +## 生产部署目标 + +用户指定 SSH 别名 `server134-rot`(134.175.227.134),目录 `/opt/observability/`。部署目录对应本仓库 `deploy/monitoring/` 的内容。2026-10-15 已确认 Ubuntu 22.04、2 核、7.6 GiB 内存、磁盘剩余约 49 GiB。服务器已有应用占用 3000/3001,Grafana 使用回环 3002;具体部署参数见 [server134 运维说明](deploy/monitoring/README.server134.md)。 + +先通过 SSH 进行只读检查,确认系统、Docker、磁盘空间和端口;已有部署应先备份配置并保留 `.env` 与 `data/`。检查通过后按服务器部署文档执行,必须通过 Metrics、Logs、Traces 冒烟才能确认部署成功。 + +服务部署成功后,可从工作机建立隧道,使用避开本地应用及本地监控端口的地址: + +```powershell +ssh -N -o ExitOnForwardFailure=yes -L 13000:127.0.0.1:3002 -L 19093:127.0.0.1:9093 server134-rot +``` + +- Grafana: +- Alertmanager: + +这些地址仅在远程部署及 SSH 隧道成功后可用。端口冲突时停止并调整配置,不终止未知业务进程。所有端口默认绑定回环地址。 + +## 当前范围 + +本地已验证三类数据的合成读写,以及 new-api 状态接口探测。Linux 基础部署采集服务器和监控组件自身指标;生产应用、MySQL、业务日志、业务 Trace 和企业微信通知需要分别接入。Windows 的 `host.docker.internal` 目标及本地密码不会自动迁移到生产。 + +`.env`、运行数据、密码和采集器凭据不纳入 Git。原始方案是历史调查资料,不代表当前生产状态或额外变更授权。 diff --git a/deploy/monitoring/.env.example b/deploy/monitoring/.env.example new file mode 100644 index 0000000..3cc011a --- /dev/null +++ b/deploy/monitoring/.env.example @@ -0,0 +1,23 @@ +COMPOSE_PROJECT_NAME=observability + +# Keep every port on loopback for the first deployment. +UI_BIND_IP=127.0.0.1 +INGEST_BIND_IP=127.0.0.1 +DEBUG_BIND_IP=127.0.0.1 +GRAFANA_PORT=3000 + +# Initial server134 deployment uses 30d/7d to fit its shared system disk. +VM_RETENTION=400d +VL_RETENTION=30d +VMAGENT_CONFIG=./config/vmagent/prometheus.yml + +GRAFANA_ADMIN_USER=admin +GRAFANA_ADMIN_PASSWORD=replace-with-a-long-random-password + +VM_VERSION=v1.152.0 +VL_VERSION=v1.52.0 +GRAFANA_VERSION=13.2.2 +TEMPO_VERSION=3.0.3 +ALERTMANAGER_VERSION=v0.34.1 +NODE_EXPORTER_VERSION=v1.12.1 +TELEMETRYGEN_VERSION=v0.161.0 diff --git a/deploy/monitoring/.gitignore b/deploy/monitoring/.gitignore new file mode 100644 index 0000000..9a7bfa1 --- /dev/null +++ b/deploy/monitoring/.gitignore @@ -0,0 +1,3 @@ +.env +data/ +__pycache__/ diff --git a/deploy/monitoring/README.local.md b/deploy/monitoring/README.local.md new file mode 100644 index 0000000..bb75d19 --- /dev/null +++ b/deploy/monitoring/README.local.md @@ -0,0 +1,103 @@ +# Windows 本地冒烟与 new-api 状态监控 + +第一次使用 Grafana,请阅读 [Grafana 中文使用手册](../../docs/Grafana使用手册-本地new-api监控.md),包含登录、切换中文、看板解读、指标/日志/链路查询和告警查看。 + +接入本机 MySQL 请阅读 [MySQL 采集器配置步骤](README.mysql.md)。该服务为可选项;创建工作区外的 `mysql-exporter.cnf` 后,启动脚本会启用它,并将 MySQL 检查加入完整冒烟。 + +适用于本工作机的 Docker Desktop(Linux containers)和已启动的 `http://127.0.0.1:3000` 应用。 +入口使用独立 Compose 项目 `observability-local`,全部发布端口绑定 `127.0.0.1`。 +Grafana 使用 **3001**,避免与应用的 3000 冲突;此入口不运行 Linux node_exporter。 + +## 启动、复测、停止 + +在项目根目录执行(需要 Python 3、Docker Desktop、Compose 2.24.4 或更新版本): + +```powershell +cd D:\project\weiyuan-observability +docker desktop start +py -3 deploy/monitoring/scripts/local.py check +py -3 deploy/monitoring/scripts/local.py up +py -3 deploy/monitoring/scripts/local.py smoke +``` + +`up` 会读取合并后的 Compose 配置,检查全部发布端口的实际 TCP bind 及 Docker 映射归属。 +冲突会在拉取镜像或修改容器前报错退出,允许本项目对应服务原有的相同端口。 +端口检查与启动之间仍存在竞争窗口,Docker 启动失败时应按错误排查,不要终止未知进程。 +首次启动 Grafana 需下载约 78 MB 的日志数据源插件;镜像拉取完成不等于界面就绪。`smoke` 最长等待 Grafana 10 分钟,超时后查看 `logs` 中的下载错误。 + +```powershell +py -3 deploy/monitoring/scripts/local.py ps +py -3 deploy/monitoring/scripts/local.py logs +py -3 deploy/monitoring/scripts/local.py down +``` + +`down` 停止本地监控项目并保留命名卷。下次执行 `up` 恢复;不要加 `-v`。 +Docker Desktop 关闭时监控也会暂停。 + +## 打开看板 + +- Grafana: +- Alertmanager: +- vmagent 采集状态: + +Grafana 用户名:`admin`。随机密码保存在工作区外: + +```powershell +Get-Content "$env:LOCALAPPDATA\weiyuan-observability\grafana-admin-password.txt" +``` + +不要把输出复制进聊天、源码或交接文件。密码由 Compose secret 挂载,不写入本工作区的 `.env`。 +如果之后在 Grafana 中更改了密码,需要同步更新外部文件,才能继续运行登录与数据源检查;不要删除数据卷来重置密码。 + +## 本阶段监控范围 + +每 15 秒从容器内访问 `http://host.docker.internal:3000/api/status`,要求 HTTP 200 且返回体包含 `"success": true`。 +看板显示状态接口可用性、HTTP 状态码和请求耗时。连续失败 2 分钟触发 `NewApiUnavailable`;采集失败 2 分钟触发 `LocalMonitoringTargetDown`。 +默认 Alertmanager 只在本地显示告警,没有对外通知。 + +这些指标**不能代表模型调用成功率、推理延迟、计费或真实用户流量**。 +应用业务 Metrics、应用日志及业务 Traces 尚未接入;Logs/Traces 当前只有冒烟脚本写入的合成数据。 +下一步应基于实际运行分支导出既有 `service/monitor` 数据,复用其结果分类,不能把 `master` 与 `weiyuan` 混为一谈。 + +修改目标地址:编辑 `config/local/prometheus.yml` 中的 `targets`,再执行: + +```powershell +# 只重启监控采集器,使修改后的配置生效。 +docker restart observability-local-vmagent-1 +py -3 deploy/monitoring/scripts/local.py smoke +``` + +`host.docker.internal` 指向 Windows 宿主机。容器中的 `127.0.0.1` 指向容器自身。 +只有应用允许 Docker Desktop 访问时探测才会成功;不要为解决连通性随意关闭防火墙。 + +## 验证内容 + +`smoke` 先等待组件就绪,再完成以下实际读写: + +1. 写入带本轮标识的 Prometheus 样本,轮询查询值为 1。 +2. 写入合成日志,根据唯一 trace_id 查回本轮消息。 +3. 经 OTLP HTTP 写入合成 span,再用精确 trace ID 查回本轮 span。 +4. 检查应用探测成功、HTTP 200、全部配置的采集目标正常。 +5. 使用外部密码验证 Grafana 三个数据源与预置应用看板。 + +最后应输出 `Local stack, application probe and Grafana checks all passed.`。 +这不等于业务链路接入、外部通知或跨组件跳转已经验收。当前未主动停止用户应用测试告警恢复。 + +2026-10-15 本机已完整通过以上检查:8 个监控容器运行,9 个采集目标正常,应用探测为 1、HTTP 状态为 200,3 个 Grafana 数据源正常。首次日志插件下载约耗时 8 分钟;之后插件保存在 Grafana 数据卷中。 +下载期间的 Grafana 采集失败告警已进入 Alertmanager,并在服务就绪后自动恢复;最终没有活动告警。 + +端口预检回归测试: + +```powershell +py -3 deploy/monitoring/tests/test_local_ports.py +``` + +## 与 Ubuntu 部署的区别 + +本地入口合并 `docker-compose.yml` 与 `docker-compose.local.yml`,使用 Docker 命名卷和独立网络。 +Ubuntu 仍按 `README.md` 部署,使用原来的绑定目录与主机监控配置。 +共同修复:Tempo 3.0.3 使用 `overrides.defaults.compaction.block_retention` 设置保留期,已移除 2.x 的 `ingester/compactor` 字段;Grafana 在启动前同步安装固定版本日志插件。 +Ubuntu 冒烟入口也调用 `scripts/smoke.py`,不再依赖 telemetrygen 镜像。 + +迁移到另一台电脑时复制工作区,重新运行 `up` 会生成新的本机密码和空数据卷。 +工作区副本不包含 Docker 卷数据或外部密码;如需保留历史,需另行备份迁移。 diff --git a/deploy/monitoring/README.md b/deploy/monitoring/README.md new file mode 100644 index 0000000..5d551a0 --- /dev/null +++ b/deploy/monitoring/README.md @@ -0,0 +1,151 @@ +# 测试监控服务器部署 + +Windows 本地 Docker Desktop 冒烟、新 API 应用 `127.0.0.1:3000` 接入,请先阅读 [README.local.md](README.local.md)。本地 Grafana 使用 3001,下面章节仍用于 Ubuntu 测试服务器。 + +生产目标 `server134-rot` 使用 [README.server134.md](README.server134.md) 中的参数,Grafana 端口为 3002。 + +本目录部署第一阶段的单机监控栈:VictoriaMetrics、VictoriaLogs、Tempo、Grafana、vmagent、vmalert、Alertmanager 和本机 node_exporter。默认所有端口只绑定 `127.0.0.1`,不会直接暴露到公网。 + +## 1. 前提 + +- Ubuntu 22.04/24.04,建议至少 4 vCPU、8 GB 内存、100 GB 数据盘。 +- 服务器能访问 Docker Hub、GitHub Container Registry 和 Grafana 插件源。 +- 时间同步正常:`timedatectl status` 中 `System clock synchronized: yes`。 + +## 2. 上传部署目录 + +在 Windows 工作机执行,替换 SSH 用户和地址: + +```powershell +scp -r D:\project\weiyuan-observability\deploy\monitoring ops@MONITOR_SERVER:/tmp/ +ssh ops@MONITOR_SERVER +``` + +在测试服务器执行: + +```bash +sudo mkdir -p /opt/observability +sudo cp -a /tmp/monitoring/. /opt/observability/ +cd /opt/observability +sudo bash scripts/install-docker-ubuntu.sh +sudo bash scripts/prepare.sh +``` + +`prepare.sh` 首次运行会生成 Grafana admin 随机密码,保存在权限为 `0600` 的 `/opt/observability/.env`,不会输出到部署日志。请在服务器上私下读取并存入密码管理器,不要提交 `.env`。拉取镜像前,脚本会检查 Compose 所需的 10 个 TCP 监听地址;其他进程或容器占用端口时会停止部署并打印排查命令。重复执行升级时,已经属于本 Compose 项目的端口会自动放行。 + +也可以单独执行端口预检: + +```bash +cd /opt/observability +sudo bash scripts/check-ports.sh +``` + +发生冲突后,按脚本输出检查占用方,例如: + +```bash +sudo ss -ltnp 'sport = :3000' +sudo docker ps --filter publish=3000 --format 'table {{.ID}}\t{{.Names}}\t{{.Ports}}' +``` + +Grafana 端口冲突时,在 `.env` 设置 `GRAFANA_PORT=3002` 等空闲端口;Compose、预检和冒烟会使用同一设置。其他端口如需修改,必须同时更新 Compose、预检和冒烟脚本。不要直接终止未知生产进程。 + +## 3. 验证容器和三类数据 + +```bash +cd /opt/observability +sudo docker compose ps +sudo docker compose logs --tail=100 +sudo bash scripts/smoke-test.sh +``` + +预期最后输出: + +```text +PASS: Metrics fresh write/query +PASS: Logs fresh write/query +PASS: Traces fresh OTLP write/exact trace query +All smoke tests passed. Synthetic run=... trace=... +``` + +如果失败,先查看对应组件: + +```bash +sudo docker compose logs --tail=200 victoriametrics +sudo docker compose logs --tail=200 victorialogs +sudo docker compose logs --tail=200 tempo +sudo docker compose logs --tail=200 grafana +sudo docker compose logs --tail=200 vmagent vmalert alertmanager +``` + +## 4. 打开 Grafana + +在 Windows 工作机建立 SSH 隧道,窗口保持运行: + +```powershell +ssh -N -L 3000:127.0.0.1:3000 -L 9093:127.0.0.1:9093 ops@MONITOR_SERVER +``` + +浏览器访问: + +- Grafana:`http://127.0.0.1:3000` +- Alertmanager:`http://127.0.0.1:9093` + +Grafana 登录用户为 `.env` 中的 `GRAFANA_ADMIN_USER`,密码为 `GRAFANA_ADMIN_PASSWORD`。进入 `Dashboards -> Observability -> Monitor Host Overview`,应看到测试机 CPU、内存、磁盘和采集状态。 + +## 5. 常用运维命令 + +```bash +cd /opt/observability +sudo docker compose ps +sudo docker compose logs -f --tail=100 +sudo docker compose restart grafana +sudo docker compose pull +sudo docker compose up -d +sudo docker compose down +du -sh data/* +df -h /opt/observability +``` + +`docker compose down` 不会删除 `data/`。不要执行 `down -v`,也不要直接删除 `/opt/observability/data`。 + +## 6. 接收业务服务器数据 + +第一阶段自检通过后,将监控服务器的**内网地址**写入 `.env`: + +```bash +cd /opt/observability +sudo sed -i 's/^INGEST_BIND_IP=.*/INGEST_BIND_IP=10.0.0.10/' .env +sudo docker compose up -d +sudo ss -lntp | grep -E ':(8428|9428|4317|4318)\b' +``` + +将示例 `10.0.0.10` 替换成测试服务器真实内网 IP。安全组/防火墙只允许业务服务器源 IP 访问: + +- `8428/tcp`:vmagent remote_write; +- `9428/tcp`:Vector 写 VictoriaLogs; +- `4317/tcp`、`4318/tcp`:OTLP gRPC/HTTP; +- `3000`、`9093`、`3200`、`8429`、`8880`、`9100` 继续保持回环监听。 + +开放前先确认云安全组规则。Docker published port 可能绕过 UFW 的普通 INPUT 规则,不能只依赖 `ufw allow/deny`;优先通过云安全组或 `DOCKER-USER` 链限制源 IP。 + +## 7. 配置真实通知 + +初始 Alertmanager 使用 `local-web` 接收器,只在 Web UI 保存告警,不向外发送。确认收件人和 webhook 后,修改 `config/alertmanager/alertmanager.yml`,再执行: + +```bash +cd /opt/observability +sudo docker compose exec alertmanager amtool check-config /etc/alertmanager/alertmanager.yml +sudo docker compose restart alertmanager +``` + +不要把 webhook 密钥提交到 Git;生产密钥放在服务器权限为 `0600` 的独立配置文件或密钥管理系统中。 + +## 8. 回滚 + +```bash +cd /opt/observability +sudo docker compose down +sudo ss -lntp | grep -E ':(3000|3200|4317|4318|8428|8429|8880|9093|9100|9428)\b' || true +``` + +这只停止监控栈,不删除数据,也不影响 monkey-ai、nginx、Redis、MySQL 或 PM2 业务进程。 diff --git a/deploy/monitoring/README.mysql.md b/deploy/monitoring/README.mysql.md new file mode 100644 index 0000000..7fa041a --- /dev/null +++ b/deploy/monitoring/README.mysql.md @@ -0,0 +1,225 @@ +# 本机 MySQL 采集器配置 + +适用:当前 Windows Docker Desktop 部署、本机 MySQL 8.0。2026-10-15 检测到本机安装 MySQL 8.0.46,监听 3306;Docker 容器到该端口的 TCP 连接在 Windows 上显示来源为 127.0.0.1。 + +已准备好 `mysqld-exporter` Compose 服务和启动脚本。你已经加入的 vmagent `mysql` 采集任务保持不变。**数据库账号尚未创建,真实 MySQL 指标尚未验证。** + +## 1. 创建专用监控账号 + +使用你现有的数据库管理工具,以有创建用户权限的账号连接本机 MySQL。也可以在 PowerShell 中运行客户端,交互输入管理员密码: + +```powershell +& 'C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe' -h 127.0.0.1 -P 3306 -u root -p +``` + +执行下面的 SQL,先把密码占位符替换成你在密码管理器中生成的长随机密码。建议使用至少 32 位的随机字母、数字组合,避免配置文件中引号、注释字符的转义问题。 + +```sql +CREATE USER 'mysqld_exporter'@'127.0.0.1' + IDENTIFIED BY '替换为你的随机监控密码' + WITH MAX_USER_CONNECTIONS 3; + +SHOW GRANTS FOR 'mysqld_exporter'@'127.0.0.1'; +``` + +本配置仅启用 `SHOW GLOBAL STATUS`、`SHOW GLOBAL VARIABLES` 两类采集。MySQL 8.0 的这些语句不要求全库 SELECT 权限,创建可登录的账号即可;`SHOW GRANTS` 显示 USAGE 是预期结果。 + +采集器已关闭默认的复制、InnoDB 压缩表和查询响应时间扩展采集项。先不授予 `SELECT ON *.*`、PROCESS 或 REPLICATION CLIENT。如果以后启用更多采集项,再按需授权。 + +如果提示账号已存在,先检查原账号用途,不要直接覆盖密码。若报来源不匹配,按第 6 节检查 MySQL 实际识别的来源。 + +## 2. 创建工作区外的连接文件 + +PowerShell 执行: + +```powershell +$mysqlConfigDir = Join-Path $env:LOCALAPPDATA 'weiyuan-observability' +New-Item -ItemType Directory -Force -Path $mysqlConfigDir | Out-Null +notepad (Join-Path $mysqlConfigDir 'mysql-exporter.cnf') +``` + +在记事本中填写以下内容,替换密码为第 1 步创建账号时设置的值。保存为 UTF-8,文件名是 `mysql-exporter.cnf`,不要额外加 `.txt`: + +```ini +[client] +host=host.docker.internal +port=3306 +user=mysqld_exporter +password=REPLACE_WITH_MYSQL_MONITOR_PASSWORD +``` + +说明: + +- `host.docker.internal` 是容器访问本机 Windows 的地址。这里不要填写 `127.0.0.1`,否则采集器会连接自己。 +- `127.0.0.1` 在第 1 步的 MySQL 用户定义中表示允许的客户端来源,和这里的连接目标不是同一个概念。 +- 文件在 `%LOCALAPPDATA%\weiyuan-observability\mysql-exporter.cnf`,不要复制进项目或发送到聊天。 +- 若目标不是本机数据库,需要重新确认地址、来源授权和 TLS 配置,不要直接套用本机账号授权。 + +限制文件权限: + +```powershell +$mysqlConfigFile = Join-Path $env:LOCALAPPDATA 'weiyuan-observability\mysql-exporter.cnf' +$mysqlConfigOwner = whoami +icacls $mysqlConfigFile /inheritance:r /grant:r "${mysqlConfigOwner}:(F)" +``` + +启动脚本只读取文件路径和必要字段,不输出密码。文件存在即表示选择启用 MySQL profile;密码仍为占位符时,`check` 和 `up` 会在拉取或修改容器前拒绝启动。 + +## 3. 校验并启动采集器 + +```powershell +cd D:\project\weiyuan-observability + +py -3 deploy/monitoring/scripts/local.py check +py -3 deploy/monitoring/scripts/local.py up + +# 使你新增的 mysql 抓取任务立即生效。 +docker restart observability-local-vmagent-1 + +py -3 deploy/monitoring/scripts/local.py ps +``` + +列表中应该新增: + +```text +observability-local-mysqld-exporter-1 +``` + +采集器固定使用 `prom/mysqld-exporter:v0.17.2`。配置通过 Docker secret 挂载到 `/run/secrets/mysql_exporter_config`。容器内部监听 9104,**没有向 Windows 发布端口**。 + +正常采集链路: + +```text +本机 MySQL:3306 + → mysqld-exporter:9104/metrics + → vmagent + → VictoriaMetrics + → Grafana +``` + +你已经加入的采集配置如下,无需重复添加: + +```yaml + - job_name: mysql + static_configs: + - targets: [mysqld-exporter:9104] + labels: + service: mysql + instance: local-mysql +``` + +这里 `instance: local-mysql` 用于标识这台数据库,不是马甲包品牌。一台数据库服务多个品牌时,也不要把同一组全局指标重复标记成不同品牌。 + +## 4. 验证连接和采集 + +```powershell +py -3 deploy/monitoring/scripts/local.py mysql-check +``` + +脚本会等待本次检查启动后的新采集样本,并检查四个结果: + +```text +PASS: MySQL exporter scrape +PASS: MySQL database connection +PASS: MySQL global_status collector +PASS: MySQL global_variables collector +``` + +对应指标必须分别为: + +```promql +up{job="mysql"} +mysql_up{job="mysql"} +mysql_exporter_collector_success{job="mysql",collector="collect.global_status"} +mysql_exporter_collector_success{job="mysql",collector="collect.global_variables"} +``` + +以上四项均应为 1,分别表示抓取成功、数据库连接成功、全局状态采集成功、全局变量采集成功。`up=1` 单独不能证明数据库连接正常。此版本使用 `mysql_exporter_collector_success`,不要照旧教程查询已不提供的 `mysql_exporter_last_scrape_error`。 + +再运行完整冒烟测试: + +```powershell +py -3 deploy/monitoring/scripts/local.py smoke +``` + +保存了 MySQL 凭据文件后,完整冒烟也会自动包含这些 MySQL 检查。如果先重新加载 vmagent、但还没有启用采集器,MySQL 目标会显示不可用;应完成第 2~3 步。 + +## 5. 在 Grafana 查看 + +打开 ,选择 **VictoriaMetrics** 数据源,输入: + +连接数: + +```promql +mysql_global_status_threads_connected{job="mysql"} +``` + +正在运行的线程数: + +```promql +mysql_global_status_threads_running{job="mysql"} +``` + +每秒收到的查询数(需先积累一些样本): + +```promql +rate(mysql_global_status_questions{job="mysql"}[5m]) +``` + +最大连接数: + +```promql +mysql_global_variables_max_connections{job="mysql"} +``` + +确认有数据后,进入 **仪表板 → 新建 → 导入**,可以尝试社区 MySQL Overview 看板 `7362`,数据源选择 **VictoriaMetrics**,实例选择 `local-mysql`。 + +当前只启用了基础采集。社区看板里的复制延迟、表级统计、SQL 分析等图表可能没有数据,不能仅为填满看板而直接授予全库权限。 + +本次没有新增 MySQL 数据库不可用告警。现有 `LocalMonitoringTargetDown` 只检查 `up`,后续需要另外配置 `mysql_up == 0` 等规则;仅导入图表不会自动增加告警。 + +## 6. 常见问题 + +查看日志和采集状态: + +```powershell +docker logs --tail 50 observability-local-mysqld-exporter-1 +``` + +打开 ,找到 `mysql` 任务。 + +| 现象 | 排查方法 | +| --- | --- | +| 提示先创建 mysql-exporter.cnf | 检查文件路径和扩展名,尚未启用采集器 | +| 提示 Set a real password | 文件里仍是占位符或空密码,请填写真实监控密码 | +| Access denied | 核对用户名、密码,以及错误中 MySQL 识别的客户端来源;在数据库工具中检查同名账号的 Host 匹配情况,不要直接扩大到 `%` | +| Host is not allowed to connect | 当前允许的客户端来源不匹配,应针对实际来源创建专用账号 | +| connection refused / timeout | 检查 MySQL 是否运行,以及 Docker 到宿主机 3306 的连通性 | +| mysqld-exporter 无法解析 | 检查采集器是否启用并在运行,是否属于 `observability-local` 网络 | +| `up=1`、`mysql_up=0` | 采集器自身正常,数据库连接或认证失败 | +| `mysql_up=1`、collector_success 为 0 | 查看对应采集项的错误;若手动启用了扩展采集器,检查其兼容性和额外权限 | +| 只有部分图表无数据 | 查看图表依赖的指标是否属于尚未启用的扩展采集 | + +更改外部连接文件后,重新执行校验,再重启采集器: + +```powershell +py -3 deploy/monitoring/scripts/local.py check +docker restart observability-local-mysqld-exporter-1 +py -3 deploy/monitoring/scripts/local.py mysql-check +``` + +## 7. 停止和验证范围 + +`local.py down` 会停止本地监控项目,包括 MySQL 采集器,保留已有数据卷,不停止 Windows 上的 MySQL 服务。 + +如果只想暂时停采集器: + +```powershell +docker stop observability-local-mysqld-exporter-1 +``` + +vmagent 仍然采集该任务,因此会显示目标失败。若要长期移除,应同时去掉 `mysql` 抓取任务并重新加载 vmagent,将外部凭据文件移到其他安全位置以取消自动启用,然后停止该采集器。不要删除数据库或监控数据卷。 + +本次已验证:固定镜像可拉取、可选 Compose 配置有效、采集器能在隔离网络中启动、没有发布宿主机端口、凭据缺失/占位符/格式错误会被阻止。**本机数据库账号创建、真实认证及指标采集,需要完成前述步骤后才能验收。** + +参考:[mysqld_exporter v0.17.2 官方说明](https://github.com/prometheus/mysqld_exporter/tree/v0.17.2)。官方默认采集项的授权范围比本配置广,勿直接混用授权示例。 diff --git a/deploy/monitoring/README.server134.md b/deploy/monitoring/README.server134.md new file mode 100644 index 0000000..56e5b26 --- /dev/null +++ b/deploy/monitoring/README.server134.md @@ -0,0 +1,57 @@ +# server134 监控运维 + +SSH:`ssh server134-rot`,目标 `134.175.227.134`,部署目录 `/opt/observability/`。 + +## 服务器与部署参数 + +2026-10-15 只读检查:Ubuntu 22.04.5、2 vCPU、7.6 GiB 内存、79 GiB 系统盘(剩余约 49 GiB),已有 Docker 和 Compose。此机同时运行业务服务;3000/3001 均被 monkey-ai 使用,不可抢占。 + +服务器 `.env` 相对 `.env.example` 使用以下参数,密码由 `prepare.sh` 在服务器生成: + +```dotenv +GRAFANA_PORT=3002 +VM_RETENTION=30d +VL_RETENTION=7d +VMAGENT_CONFIG=./config/vmagent/prometheus.server134.yml +``` + +所有 BIND_IP 保持 `127.0.0.1`。Tempo 保留期为 30 天。保留期不是磁盘容量上限,接入真实日志/链路前需根据日增量重新规划容量。 + +## 启动与验证 + +将已提交版本的 `deploy/monitoring/` 内容部署到目标目录;已有配置先备份,保留 `.env` 和 `data/`,不要覆盖真实凭据。 + +```bash +cd /opt/observability +bash scripts/check-ports.sh +bash scripts/prepare.sh +bash scripts/smoke-test.sh +docker compose ps +docker stats --no-stream +df -h /opt +``` + +冒烟检查三类合成数据的写入/查询、采集目标、Grafana 三个数据源与主机仪表盘。运行期间应关注 CPU、内存和磁盘,当前配置不是高可用方案。 + +## 访问 + +在工作机运行并保持终端打开: + +```powershell +ssh -N -o ExitOnForwardFailure=yes -L 13000:127.0.0.1:3002 -L 19093:127.0.0.1:9093 server134-rot +``` + +访问 ,默认用户名 `admin`。密码位于服务器 `/opt/observability/.env`,仅在自己的 SSH 终端私下查看并保存,不要粘贴到聊天或提交 Git。仪表盘为 `Observability / Monitor Host Overview`。 + +## 范围与回滚 + +当前采集 server134 主机和监控组件自身指标。生产 new-api/MySQL、真实业务日志、业务链路和企业微信通知尚未接入;不会复制 Windows 本地数据库凭据。 + +停止此次监控部署并保留数据: + +```bash +cd /opt/observability +docker compose down +``` + +不要执行 `down -v` 或删除 `data/`。首次部署前的旧文件备份保存在 `/opt/observability-backups/`。`DEPLOYED_COMMIT` 记录上传的 Git 版本。 diff --git a/deploy/monitoring/config/alertmanager/alertmanager.yml b/deploy/monitoring/config/alertmanager/alertmanager.yml new file mode 100644 index 0000000..88eb21f --- /dev/null +++ b/deploy/monitoring/config/alertmanager/alertmanager.yml @@ -0,0 +1,12 @@ +global: + resolve_timeout: 5m + +route: + receiver: local-web + group_by: [alertname, instance] + group_wait: 30s + group_interval: 5m + repeat_interval: 4h + +receivers: + - name: local-web diff --git a/deploy/monitoring/config/grafana/dashboards/monitor-host-overview.json b/deploy/monitoring/config/grafana/dashboards/monitor-host-overview.json new file mode 100644 index 0000000..c849638 --- /dev/null +++ b/deploy/monitoring/config/grafana/dashboards/monitor-host-overview.json @@ -0,0 +1,153 @@ +{ + "annotations": { "list": [] }, + "editable": false, + "fiscalYearStartMonth": 0, + "graphTooltip": 1, + "id": null, + "links": [], + "panels": [ + { + "datasource": { "type": "prometheus", "uid": "victoriametrics" }, + "fieldConfig": { + "defaults": { + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "red", "value": 0 }, + { "color": "green", "value": 1 } + ] + } + }, + "overrides": [] + }, + "gridPos": { "h": 5, "w": 6, "x": 0, "y": 0 }, + "id": 1, + "options": { + "colorMode": "background", + "graphMode": "none", + "justifyMode": "center", + "orientation": "auto", + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + }, + "textMode": "auto" + }, + "targets": [{ "expr": "sum(up)", "refId": "A" }], + "title": "Targets Up", + "type": "stat" + }, + { + "datasource": { "type": "prometheus", "uid": "victoriametrics" }, + "fieldConfig": { + "defaults": { "unit": "percentunit", "min": 0, "max": 1 }, + "overrides": [] + }, + "gridPos": { "h": 8, "w": 9, "x": 6, "y": 0 }, + "id": 2, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { "mode": "multi", "sort": "desc" } + }, + "targets": [ + { + "expr": "1 - avg by (instance) (rate(node_cpu_seconds_total{mode=\"idle\"}[5m]))", + "legendFormat": "{{instance}}", + "refId": "A" + } + ], + "title": "CPU Usage", + "type": "timeseries" + }, + { + "datasource": { "type": "prometheus", "uid": "victoriametrics" }, + "fieldConfig": { + "defaults": { "unit": "percentunit", "min": 0, "max": 1 }, + "overrides": [] + }, + "gridPos": { "h": 8, "w": 9, "x": 15, "y": 0 }, + "id": 3, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { "mode": "multi", "sort": "desc" } + }, + "targets": [ + { + "expr": "1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes", + "legendFormat": "{{instance}}", + "refId": "A" + } + ], + "title": "Memory Usage", + "type": "timeseries" + }, + { + "datasource": { "type": "prometheus", "uid": "victoriametrics" }, + "fieldConfig": { + "defaults": { "unit": "percentunit", "min": 0, "max": 1 }, + "overrides": [] + }, + "gridPos": { "h": 8, "w": 12, "x": 0, "y": 8 }, + "id": 4, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { "mode": "multi", "sort": "desc" } + }, + "targets": [ + { + "expr": "1 - node_filesystem_avail_bytes{fstype!~\"tmpfs|devtmpfs|overlay|squashfs\"} / node_filesystem_size_bytes{fstype!~\"tmpfs|devtmpfs|overlay|squashfs\"}", + "legendFormat": "{{instance}} {{mountpoint}}", + "refId": "A" + } + ], + "title": "Filesystem Usage", + "type": "timeseries" + }, + { + "datasource": { "type": "prometheus", "uid": "victoriametrics" }, + "fieldConfig": { "defaults": {}, "overrides": [] }, + "gridPos": { "h": 8, "w": 12, "x": 12, "y": 8 }, + "id": 5, + "options": { + "legend": { + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { "mode": "multi", "sort": "desc" } + }, + "targets": [ + { + "expr": "ALERTS{alertstate=\"firing\"}", + "legendFormat": "{{severity}} {{alertname}} {{instance}}", + "refId": "A" + } + ], + "title": "Firing Alerts", + "type": "timeseries" + } + ], + "refresh": "15s", + "schemaVersion": 39, + "tags": ["observability", "host"], + "templating": { "list": [] }, + "time": { "from": "now-6h", "to": "now" }, + "timezone": "browser", + "title": "Monitor Host Overview", + "uid": "monitor-host-overview", + "version": 1 +} diff --git a/deploy/monitoring/config/grafana/provisioning/dashboards/dashboards.yml b/deploy/monitoring/config/grafana/provisioning/dashboards/dashboards.yml new file mode 100644 index 0000000..4613f74 --- /dev/null +++ b/deploy/monitoring/config/grafana/provisioning/dashboards/dashboards.yml @@ -0,0 +1,11 @@ +apiVersion: 1 + +providers: + - name: Observability + orgId: 1 + folder: Observability + type: file + disableDeletion: true + updateIntervalSeconds: 30 + options: + path: /var/lib/grafana/dashboards diff --git a/deploy/monitoring/config/grafana/provisioning/datasources/datasources.yml b/deploy/monitoring/config/grafana/provisioning/datasources/datasources.yml new file mode 100644 index 0000000..292d3e1 --- /dev/null +++ b/deploy/monitoring/config/grafana/provisioning/datasources/datasources.yml @@ -0,0 +1,31 @@ +apiVersion: 1 + +datasources: + - name: VictoriaMetrics + type: prometheus + uid: victoriametrics + access: proxy + url: http://victoriametrics:8428 + isDefault: true + editable: false + + - name: VictoriaLogs + type: victoriametrics-logs-datasource + uid: victorialogs + access: proxy + url: http://victorialogs:9428 + editable: false + + - name: Tempo + type: tempo + uid: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: victorialogs + spanStartTimeShift: -5m + spanEndTimeShift: 5m + filterByTraceID: true + filterBySpanID: false diff --git a/deploy/monitoring/config/local/blackbox.yml b/deploy/monitoring/config/local/blackbox.yml new file mode 100644 index 0000000..6580e8a --- /dev/null +++ b/deploy/monitoring/config/local/blackbox.yml @@ -0,0 +1,11 @@ +modules: + new_api_status: + prober: http + timeout: 5s + http: + method: GET + valid_status_codes: [200] + follow_redirects: false + preferred_ip_protocol: ip4 + fail_if_body_not_matches_regexp: + - '"success"\s*:\s*true' diff --git a/deploy/monitoring/config/local/dashboards/new-api-local.json b/deploy/monitoring/config/local/dashboards/new-api-local.json new file mode 100644 index 0000000..8ff1b15 --- /dev/null +++ b/deploy/monitoring/config/local/dashboards/new-api-local.json @@ -0,0 +1,239 @@ +{ + "uid": "new-api-local", + "title": "New API - Local Health", + "schemaVersion": 39, + "version": 1, + "refresh": "15s", + "tags": ["new-api", "local"], + "time": { + "from": "now-30m", + "to": "now" + }, + "panels": [ + { + "id": 1, + "title": "Scope", + "type": "text", + "gridPos": { + "x": 0, + "y": 0, + "w": 24, + "h": 3 + }, + "options": { + "mode": "markdown", + "content": "Target: `http://host.docker.internal:3000/api/status` (Windows app at `127.0.0.1:3000`). Checks HTTP 200 and `success: true` every 15 seconds. **Status endpoint availability and latency only.** Model-call success rate, billing, application logs and business traces are not connected yet. No-traffic periods cannot be inferred from this probe." + } + }, + { + "id": 2, + "title": "Status probe (1 = OK, 0 = failed)", + "type": "stat", + "datasource": { + "type": "prometheus", + "uid": "victoriametrics" + }, + "gridPos": { + "x": 0, + "y": 3, + "w": 8, + "h": 7 + }, + "targets": [ + { + "refId": "A", + "expr": "probe_success{job=\"new-api-health\"}", + "legendFormat": "{{service}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + } + } + }, + { + "id": 3, + "title": "HTTP status", + "type": "stat", + "datasource": { + "type": "prometheus", + "uid": "victoriametrics" + }, + "gridPos": { + "x": 8, + "y": 3, + "w": 8, + "h": 7 + }, + "targets": [ + { + "refId": "A", + "expr": "probe_http_status_code{job=\"new-api-health\"}", + "legendFormat": "{{service}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + } + } + }, + { + "id": 4, + "title": "Status endpoint duration", + "type": "stat", + "datasource": { + "type": "prometheus", + "uid": "victoriametrics" + }, + "gridPos": { + "x": 16, + "y": 3, + "w": 8, + "h": 7 + }, + "targets": [ + { + "refId": "A", + "expr": "probe_duration_seconds{job=\"new-api-health\"}", + "legendFormat": "{{service}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + } + } + }, + { + "id": 5, + "title": "Status endpoint availability", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "victoriametrics" + }, + "gridPos": { + "x": 0, + "y": 10, + "w": 12, + "h": 7 + }, + "targets": [ + { + "refId": "A", + "expr": "probe_success{job=\"new-api-health\"}", + "legendFormat": "{{service}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + } + } + }, + { + "id": 6, + "title": "Status endpoint duration (not inference latency)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "victoriametrics" + }, + "gridPos": { + "x": 12, + "y": 10, + "w": 12, + "h": 7 + }, + "targets": [ + { + "refId": "A", + "expr": "probe_duration_seconds{job=\"new-api-health\"}", + "legendFormat": "{{service}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + } + } + }, + { + "id": 7, + "title": "Monitoring scrapes", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "victoriametrics" + }, + "gridPos": { + "x": 0, + "y": 17, + "w": 24, + "h": 7 + }, + "targets": [ + { + "refId": "A", + "expr": "up", + "legendFormat": "{{job}} {{instance}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + } + } + } + ] +} diff --git a/deploy/monitoring/config/local/prometheus.yml b/deploy/monitoring/config/local/prometheus.yml new file mode 100644 index 0000000..9693e41 --- /dev/null +++ b/deploy/monitoring/config/local/prometheus.yml @@ -0,0 +1,40 @@ +global: + scrape_interval: 15s + scrape_timeout: 10s + external_labels: + env: local + cluster: observability-local +scrape_configs: + - job_name: new-api-health + metrics_path: /probe + params: + module: [new_api_status] + static_configs: + - targets: [http://host.docker.internal:3000/api/status] + labels: + service: new-api + brand: local + relabel_configs: + - source_labels: [__address__] + target_label: __param_target + - source_labels: [__param_target] + target_label: instance + - target_label: __address__ + replacement: blackbox:9115 + - job_name: observability-components + static_configs: + - targets: + - victoriametrics:8428 + - victorialogs:9428 + - tempo:3200 + - alertmanager:9093 + - vmalert:8880 + - vmagent:8429 + - grafana:3000 + - blackbox:9115 + - job_name: mysql + static_configs: + - targets: [mysqld-exporter:9104] + labels: + service: mysql + instance: local-mysql diff --git a/deploy/monitoring/config/local/rules/application.yml b/deploy/monitoring/config/local/rules/application.yml new file mode 100644 index 0000000..a45bda6 --- /dev/null +++ b/deploy/monitoring/config/local/rules/application.yml @@ -0,0 +1,19 @@ +groups: + - name: local-application + interval: 15s + rules: + - alert: NewApiUnavailable + expr: probe_success{job="new-api-health"} == 0 + for: 2m + labels: + severity: P1 + annotations: + summary: "Local new-api status check failed for two minutes" + description: "This checks /api/status only; it does not measure model-call success." + - alert: LocalMonitoringTargetDown + expr: up == 0 + for: 2m + labels: + severity: P2 + annotations: + summary: "Monitoring scrape failed: {{ $labels.instance }}" diff --git a/deploy/monitoring/config/tempo/tempo.yml b/deploy/monitoring/config/tempo/tempo.yml new file mode 100644 index 0000000..8206e83 --- /dev/null +++ b/deploy/monitoring/config/tempo/tempo.yml @@ -0,0 +1,28 @@ +server: + http_listen_port: 3200 + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +# Tempo 3 single-binary mode replaces the 2.x ingester/compactor configuration. +overrides: + defaults: + compaction: + block_retention: 720h + +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks + +usage_report: + reporting_enabled: false diff --git a/deploy/monitoring/config/vmagent/prometheus.server134.yml b/deploy/monitoring/config/vmagent/prometheus.server134.yml new file mode 100644 index 0000000..e2de827 --- /dev/null +++ b/deploy/monitoring/config/vmagent/prometheus.server134.yml @@ -0,0 +1,29 @@ +global: + scrape_interval: 15s + scrape_timeout: 10s + external_labels: + env: production + cluster: observability-server134 + +scrape_configs: + - job_name: node-exporter + static_configs: + - targets: [node-exporter:9100] + labels: + host: server134 + service: node-exporter + + - job_name: observability-components + static_configs: + - targets: + - victoriametrics:8428 + - victorialogs:9428 + - tempo:3200 + - alertmanager:9093 + - vmalert:8880 + - vmagent:8429 + + - job_name: grafana + metrics_path: /metrics + static_configs: + - targets: [grafana:3000] diff --git a/deploy/monitoring/config/vmagent/prometheus.yml b/deploy/monitoring/config/vmagent/prometheus.yml new file mode 100644 index 0000000..f91459c --- /dev/null +++ b/deploy/monitoring/config/vmagent/prometheus.yml @@ -0,0 +1,29 @@ +global: + scrape_interval: 15s + scrape_timeout: 10s + external_labels: + env: test + cluster: monitor-test + +scrape_configs: + - job_name: node-exporter + static_configs: + - targets: [node-exporter:9100] + labels: + host: monitor-test + service: node-exporter + + - job_name: observability-components + static_configs: + - targets: + - victoriametrics:8428 + - victorialogs:9428 + - tempo:3200 + - alertmanager:9093 + - vmalert:8880 + - vmagent:8429 + + - job_name: grafana + metrics_path: /metrics + static_configs: + - targets: [grafana:3000] diff --git a/deploy/monitoring/config/vmalert/host-rules.yml b/deploy/monitoring/config/vmalert/host-rules.yml new file mode 100644 index 0000000..f9eb432 --- /dev/null +++ b/deploy/monitoring/config/vmalert/host-rules.yml @@ -0,0 +1,39 @@ +groups: + - name: host-health + interval: 30s + rules: + - alert: ExporterDown + expr: up == 0 + for: 2m + labels: + severity: P1 + annotations: + summary: "Target {{ $labels.instance }} is unavailable" + description: "vmagent has failed to scrape {{ $labels.job }}/{{ $labels.instance }} for two minutes." + + - alert: HostDiskUsageHigh + expr: 100 * (1 - node_filesystem_avail_bytes{fstype!~"tmpfs|devtmpfs|overlay|squashfs",mountpoint!~"/run($|/.*)"} / node_filesystem_size_bytes{fstype!~"tmpfs|devtmpfs|overlay|squashfs",mountpoint!~"/run($|/.*)"}) > 85 + for: 10m + labels: + severity: P2 + annotations: + summary: "Disk usage exceeds 85% on {{ $labels.instance }}" + description: "Mount {{ $labels.mountpoint }} has remained above 85% for ten minutes." + + - alert: HostDiskPredictedFull + expr: predict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs|devtmpfs|overlay|squashfs",mountpoint!~"/run($|/.*)"}[24h], 7 * 24 * 3600) < 0 and node_filesystem_avail_bytes > 0 + for: 30m + labels: + severity: P1 + annotations: + summary: "Disk may fill within seven days on {{ $labels.instance }}" + description: "The last 24 hours of free-space trend predicts that {{ $labels.mountpoint }} will fill within seven days." + + - alert: HostMemoryUsageHigh + expr: 100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) > 85 + for: 10m + labels: + severity: P2 + annotations: + summary: "Memory usage exceeds 85% on {{ $labels.instance }}" + description: "Available memory has remained below 15% for ten minutes." diff --git a/deploy/monitoring/docker-compose.local.yml b/deploy/monitoring/docker-compose.local.yml new file mode 100644 index 0000000..cbdb050 --- /dev/null +++ b/deploy/monitoring/docker-compose.local.yml @@ -0,0 +1,77 @@ +# Docker Desktop only. Merge with docker-compose.yml; use scripts/local.py. +name: observability-local +services: + victoriametrics: + volumes: + - local-metrics:/storage + victorialogs: + volumes: + - local-logs:/storage + tempo: + volumes: + - local-traces:/var/tempo + alertmanager: + volumes: + - local-alerts:/alertmanager + grafana: + ports: !override + - "127.0.0.1:3001:3000" + environment: + GF_SECURITY_ADMIN_PASSWORD: !reset null + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + secrets: [grafana_admin_password] + volumes: + - local-grafana:/var/lib/grafana + - ./config/local/dashboards:/var/lib/grafana/dashboards:ro + node-exporter: + profiles: [linux-host-only] + vmagent: + depends_on: !override [victoriametrics, blackbox] + volumes: + - ./config/local/prometheus.yml:/etc/vmagent/prometheus.yml:ro + - local-agent:/buffer + vmalert: + volumes: + - ./config/local/rules:/etc/vmalert:ro + blackbox: + image: prom/blackbox-exporter:v0.27.0 + restart: unless-stopped + command: [--config.file=/etc/blackbox/config.yml] + volumes: + - ./config/local/blackbox.yml:/etc/blackbox/config.yml:ro + networks: [observability] + mem_limit: 128m + cpus: 0.20 + security_opt: [no-new-privileges:true] + mysqld-exporter: + profiles: [mysql] + image: prom/mysqld-exporter:v0.17.2 + restart: unless-stopped + command: + - --config.my-cnf=/run/secrets/mysql_exporter_config + - --collect.global_status + - --collect.global_variables + - --no-collect.slave_status + - --no-collect.info_schema.innodb_cmp + - --no-collect.info_schema.innodb_cmpmem + - --no-collect.info_schema.query_response_time + secrets: [mysql_exporter_config] + networks: [observability] + mem_limit: 128m + cpus: 0.20 + security_opt: [no-new-privileges:true] +networks: + observability: + name: observability-local +volumes: + local-metrics: + local-logs: + local-traces: + local-alerts: + local-grafana: + local-agent: +secrets: + grafana_admin_password: + file: ${LOCAL_GRAFANA_SECRET_FILE:?Use scripts/local.py} + mysql_exporter_config: + file: ${LOCAL_MYSQL_SECRET_FILE:?Use scripts/local.py} diff --git a/deploy/monitoring/docker-compose.yml b/deploy/monitoring/docker-compose.yml new file mode 100644 index 0000000..376611d --- /dev/null +++ b/deploy/monitoring/docker-compose.yml @@ -0,0 +1,153 @@ +name: observability + +services: + victoriametrics: + image: victoriametrics/victoria-metrics:${VM_VERSION} + restart: unless-stopped + command: + - -storageDataPath=/storage + - -retentionPeriod=${VM_RETENTION:-400d} + - -httpListenAddr=:8428 + ports: + - "${INGEST_BIND_IP}:8428:8428" + volumes: + - ./data/victoriametrics:/storage + networks: [observability] + mem_limit: 1536m + cpus: 1.0 + security_opt: [no-new-privileges:true] + + victorialogs: + image: victoriametrics/victoria-logs:${VL_VERSION} + restart: unless-stopped + command: + - -storageDataPath=/storage + - -retentionPeriod=${VL_RETENTION:-30d} + - -httpListenAddr=:9428 + ports: + - "${INGEST_BIND_IP}:9428:9428" + volumes: + - ./data/victorialogs:/storage + networks: [observability] + mem_limit: 1024m + cpus: 0.75 + security_opt: [no-new-privileges:true] + + tempo: + image: grafana/tempo:${TEMPO_VERSION} + restart: unless-stopped + command: [-config.file=/etc/tempo/tempo.yml] + ports: + - "${DEBUG_BIND_IP}:3200:3200" + - "${INGEST_BIND_IP}:4317:4317" + - "${INGEST_BIND_IP}:4318:4318" + volumes: + - ./config/tempo/tempo.yml:/etc/tempo/tempo.yml:ro + - ./data/tempo:/var/tempo + networks: [observability] + mem_limit: 1024m + cpus: 0.75 + security_opt: [no-new-privileges:true] + + alertmanager: + image: prom/alertmanager:${ALERTMANAGER_VERSION} + restart: unless-stopped + command: + - --config.file=/etc/alertmanager/alertmanager.yml + - --storage.path=/alertmanager + - --web.listen-address=:9093 + ports: + - "${UI_BIND_IP}:9093:9093" + volumes: + - ./config/alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro + - ./data/alertmanager:/alertmanager + networks: [observability] + mem_limit: 256m + cpus: 0.25 + security_opt: [no-new-privileges:true] + + vmalert: + image: victoriametrics/vmalert:${VM_VERSION} + restart: unless-stopped + command: + - -datasource.url=http://victoriametrics:8428 + - -remoteRead.url=http://victoriametrics:8428 + - -remoteWrite.url=http://victoriametrics:8428 + - -notifier.url=http://alertmanager:9093 + - -rule=/etc/vmalert/*.yml + - -httpListenAddr=:8880 + ports: + - "${DEBUG_BIND_IP}:8880:8880" + volumes: + - ./config/vmalert:/etc/vmalert:ro + depends_on: [victoriametrics, alertmanager] + networks: [observability] + mem_limit: 256m + cpus: 0.25 + security_opt: [no-new-privileges:true] + + node-exporter: + image: prom/node-exporter:${NODE_EXPORTER_VERSION} + restart: unless-stopped + command: + - --path.procfs=/host/proc + - --path.sysfs=/host/sys + - --path.rootfs=/rootfs + - --collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/) + pid: host + ports: + - "${DEBUG_BIND_IP}:9100:9100" + volumes: + - /proc:/host/proc:ro + - /sys:/host/sys:ro + - /:/rootfs:ro,rslave + networks: [observability] + mem_limit: 128m + cpus: 0.20 + security_opt: [no-new-privileges:true] + + vmagent: + image: victoriametrics/vmagent:${VM_VERSION} + restart: unless-stopped + command: + - -promscrape.config=/etc/vmagent/prometheus.yml + - -remoteWrite.url=http://victoriametrics:8428/api/v1/write + - -remoteWrite.tmpDataPath=/buffer + - -httpListenAddr=:8429 + ports: + - "${DEBUG_BIND_IP}:8429:8429" + volumes: + - ${VMAGENT_CONFIG:-./config/vmagent/prometheus.yml}:/etc/vmagent/prometheus.yml:ro + - ./data/vmagent:/buffer + depends_on: [victoriametrics, node-exporter] + networks: [observability] + mem_limit: 384m + cpus: 0.35 + security_opt: [no-new-privileges:true] + + grafana: + image: grafana/grafana:${GRAFANA_VERSION} + restart: unless-stopped + environment: + GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER} + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD} + GF_USERS_ALLOW_SIGN_UP: "false" + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_PLUGINS_PREINSTALL_SYNC: victoriametrics-logs-datasource@0.32.0 + GF_PLUGINS_PREINSTALL_AUTO_UPDATE: "false" + GF_METRICS_ENABLED: "true" + ports: + - "${UI_BIND_IP}:${GRAFANA_PORT:-3000}:3000" + volumes: + - ./config/grafana/provisioning:/etc/grafana/provisioning:ro + - ./config/grafana/dashboards:/var/lib/grafana/dashboards:ro + - ./data/grafana:/var/lib/grafana + depends_on: [victoriametrics, victorialogs, tempo] + networks: [observability] + mem_limit: 768m + cpus: 0.50 + security_opt: [no-new-privileges:true] + +networks: + observability: + name: observability diff --git a/deploy/monitoring/scripts/check-ports.sh b/deploy/monitoring/scripts/check-ports.sh new file mode 100755 index 0000000..bfce382 --- /dev/null +++ b/deploy/monitoring/scripts/check-ports.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +env_value() { + local key="$1" + local fallback="$2" + local value="" + if [[ -f .env ]]; then + value="$(sed -n "s/^${key}=//p" .env | tail -n 1)" + value="${value#\"}" + value="${value%\"}" + fi + printf '%s' "${value:-${fallback}}" +} + +if [[ -z "${PORT_CHECK_SPEC:-}" ]]; then + ui_bind_ip="$(env_value UI_BIND_IP 127.0.0.1)" + ingest_bind_ip="$(env_value INGEST_BIND_IP 127.0.0.1)" + debug_bind_ip="$(env_value DEBUG_BIND_IP 127.0.0.1)" + grafana_port="$(env_value GRAFANA_PORT 3000)" + PORT_CHECK_SPEC="$(cat </dev/null || true)" + grep -Fqx -- "${expected}" <<<"${mappings}" +} + +docker_publishers() { + local host_port="$1" + docker ps \ + --filter "publish=${host_port}" \ + --format '{{.ID}} {{.Names}} {{.Ports}}' 2>/dev/null || true +} + +probe_port() { + local bind_ip="$1" + local host_port="$2" + python3 - "${bind_ip}" "${host_port}" <<'PY' +import socket +import sys + +bind_ip = sys.argv[1] +port = int(sys.argv[2]) +family = socket.AF_INET6 if ":" in bind_ip else socket.AF_INET +address = (bind_ip, port, 0, 0) if family == socket.AF_INET6 else (bind_ip, port) +sock = socket.socket(family, socket.SOCK_STREAM) +try: + sock.bind(address) +finally: + sock.close() +PY +} + +conflicts=0 +while read -r service container_port bind_ip host_port; do + [[ -z "${service:-}" ]] && continue + expected="${bind_ip}:${host_port}" + if compose_owns_port "${service}" "${container_port}" "${expected}"; then + printf 'Port %-21s is already owned by Compose service %s; allowing update.\n' "${expected}" "${service}" + continue + fi + publishers="$(docker_publishers "${host_port}")" + if [[ -n "${publishers}" ]]; then + conflicts=$((conflicts + 1)) + printf 'PORT CONFLICT: %s needs %s, already published by another Docker container:\n' "${service}" "${expected}" >&2 + printf ' %s\n' "${publishers}" >&2 + continue + fi + if probe_error="$(probe_port "${bind_ip}" "${host_port}" 2>&1)"; then + printf 'Port %-21s is available for %s.\n' "${expected}" "${service}" + continue + fi + conflicts=$((conflicts + 1)) + printf 'PORT CONFLICT: %s needs %s, but it cannot be bound.\n' "${service}" "${expected}" >&2 + printf ' Probe error: %s\n' "${probe_error}" >&2 + printf ' Inspect: sudo ss -ltnp "sport = :%s"\n' "${host_port}" >&2 + printf ' Docker: docker ps --filter publish=%s --format "table {{.ID}}\\t{{.Names}}\\t{{.Ports}}"\n' "${host_port}" >&2 +done <<<"${PORT_CHECK_SPEC}" + +if ((conflicts > 0)); then + printf 'Port preflight failed with %d conflict(s). No containers were changed.\n' "${conflicts}" >&2 + exit 1 +fi + +echo "Port preflight passed." diff --git a/deploy/monitoring/scripts/install-docker-ubuntu.sh b/deploy/monitoring/scripts/install-docker-ubuntu.sh new file mode 100755 index 0000000..c63c2c2 --- /dev/null +++ b/deploy/monitoring/scripts/install-docker-ubuntu.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "${EUID}" -ne 0 ]]; then + echo "Run with sudo: sudo bash scripts/install-docker-ubuntu.sh" >&2 + exit 1 +fi + +. /etc/os-release +if [[ "${ID}" != "ubuntu" ]]; then + echo "This installer supports Ubuntu only; detected ${ID}." >&2 + exit 1 +fi + +apt-get update +apt-get install -y ca-certificates curl openssl python3 +install -m 0755 -d /etc/apt/keyrings +curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc +chmod a+r /etc/apt/keyrings/docker.asc + +cat >/etc/apt/sources.list.d/docker.sources <= {started})" + data = json.loads(request(base + "/api/v1/query?" + urlencode({"query": fresh, "nocache": "1"}))) + rows = data["data"]["result"] + return bool(rows) and all(float(row["value"][1]) == expected for row in rows) + + poll("MySQL exporter scrape", lambda: has_value('up{job="mysql"}', 1)) + poll("MySQL database connection", lambda: has_value('mysql_up{job="mysql"}', 1)) + for collector in ("global_status", "global_variables"): + expression = f'mysql_exporter_collector_success{{job="mysql",collector="collect.{collector}"}}' + poll(f"MySQL {collector} collector", lambda expression=expression: has_value(expression, 1)) + + +def check_port(service, ip, port, target, containers): + owned = False + for container in containers: + labels = container.get("Config", {}).get("Labels") or {} + for container_port, bindings in (container.get("NetworkSettings", {}).get("Ports") or {}).items(): + for binding in bindings or []: + address = binding["HostIp"] + overlaps = address == ip or address in ("", "0.0.0.0", "::") + if int(binding["HostPort"]) != port or not overlaps: + continue + if (labels.get("com.docker.compose.project") == PROJECT + and labels.get("com.docker.compose.service") == service + and container_port == f"{target}/tcp" and address == ip): + owned = True + else: + raise RuntimeError(f"PORT CONFLICT: {service} {ip}:{port}, Docker owner {container['Name']}") + if owned: + return + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + if hasattr(socket, "SO_EXCLUSIVEADDRUSE"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + try: + sock.bind((ip, port)) + except OSError as exc: + raise RuntimeError(f"PORT CONFLICT: {service} {ip}:{port}: {exc}") from exc + + +def run(args, capture=False, timeout=900): + result = subprocess.run(args, cwd=ROOT, check=True, text=True, encoding="utf-8", + capture_output=capture, timeout=timeout) + return result.stdout if capture else None + + +def compose(*args, capture=False): + os.environ["LOCAL_GRAFANA_SECRET_FILE"] = SECRET.as_posix() + os.environ["LOCAL_MYSQL_SECRET_FILE"] = MYSQL_SECRET.as_posix() + # Credentials opt in to MySQL; include it on down even if the file was removed. + profiles = ["--profile", "mysql"] if MYSQL_SECRET.is_file() or "down" in args else [] + return run(["docker", "compose", "--project-name", PROJECT, + "--env-file", str(ROOT / ".env.example"), + "-f", str(ROOT / "docker-compose.yml"), + "-f", str(ROOT / "docker-compose.local.yml"), *profiles, *args], capture) + + +def model(): + return json.loads(compose("config", "--format", "json", capture=True)) + + +def preflight(config): + run(["docker", "info", "--format", "{{.ServerVersion}}"], capture=True, timeout=30) + ids = run(["docker", "ps", "-q"], capture=True, timeout=30).split() + containers = json.loads(run(["docker", "inspect", *ids], capture=True, timeout=30)) if ids else [] + seen = set() + for service, definition in config["services"].items(): + if definition.get("profiles"): + continue + for binding in definition.get("ports", []): + ip = binding.get("host_ip", "0.0.0.0") + port, target = int(binding["published"]), int(binding["target"]) + if ip != "127.0.0.1": + raise RuntimeError(f"Local stack requires loopback: {service} {ip}:{port}") + if (ip, port) in seen: + raise RuntimeError(f"Duplicate Compose binding: {ip}:{port}") + seen.add((ip, port)) + check_port(service, ip, port, target, containers) + print(f"Port OK: {service} {ip}:{port}", flush=True) + print("Port preflight passed; no containers changed.", flush=True) + + +def ensure_secret(): + STATE.mkdir(parents=True, exist_ok=True) + if not SECRET.exists(): + fd = os.open(SECRET, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + stream.write(secrets.token_urlsafe(32)) + if os.name == "nt": + identity = run(["whoami"], capture=True, timeout=10).strip() + run(["icacls", str(SECRET), "/inheritance:r", "/grant:r", f"{identity}:(F)"], capture=True, timeout=10) + print(f"Grafana user: admin; password file (outside workspace): {SECRET}", flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["check", "up", "smoke", "mysql-check", "ps", "down", "logs"]) + args = parser.parse_args() + if args.action in ("check", "up"): + if MYSQL_SECRET.is_file(): + validate_mysql_config(MYSQL_SECRET) + preflight(model()) + if args.action == "up": + ensure_secret() + compose("pull") + compose("up", "-d") + compose("ps") + elif args.action == "smoke": + from smoke import smoke, grafana_smoke + config = model() + endpoints = {} + for service, definition in config["services"].items(): + if definition.get("profiles"): + continue + for binding in definition.get("ports", []): + endpoints[(service, int(binding["target"]))] = f"http://127.0.0.1:{binding['published']}" + smoke(endpoints, application=True) + grafana_smoke(endpoints[("grafana", 3000)], SECRET.read_text(encoding="utf-8")) + if MYSQL_SECRET.is_file(): + mysql_smoke() + print("Local stack, application probe and Grafana checks all passed.", flush=True) + elif args.action == "mysql-check": + mysql_smoke() + elif args.action == "down": + compose("down") # Deliberately preserves named volumes. + elif args.action == "logs": + compose("logs", "--tail", "60") + else: + compose("ps") + + +if __name__ == "__main__": + try: + main() + except (RuntimeError, subprocess.SubprocessError) as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) diff --git a/deploy/monitoring/scripts/prepare.sh b/deploy/monitoring/scripts/prepare.sh new file mode 100755 index 0000000..78213e6 --- /dev/null +++ b/deploy/monitoring/scripts/prepare.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +# Credentials must not be readable by other host users or printed into logs. +umask 077 +if [[ ! -f .env ]]; then + cp .env.example .env +fi +chmod 600 .env + +if grep -q '^GRAFANA_ADMIN_PASSWORD=replace-with-a-long-random-password$' .env; then + password="$(openssl rand -base64 32 | tr -d '\n')" + sed -i "s|^GRAFANA_ADMIN_PASSWORD=.*|GRAFANA_ADMIN_PASSWORD=${password}|" .env + unset password + echo "Generated Grafana admin password in .env (mode 0600). Read it privately on the server." +fi + +install -d -m 0750 \ + data/victoriametrics \ + data/victorialogs \ + data/tempo \ + data/alertmanager \ + data/vmagent \ + data/grafana + +# Official images use these numeric users. Storage engines that run as root +# retain root ownership; Grafana, Tempo and Alertmanager need explicit owners. +chown -R 472:0 data/grafana +chown -R 10001:10001 data/tempo +chown -R 65534:65534 data/alertmanager + +docker compose config --quiet +bash scripts/check-ports.sh +docker compose pull +docker compose up -d +docker compose ps diff --git a/deploy/monitoring/scripts/smoke-test.sh b/deploy/monitoring/scripts/smoke-test.sh new file mode 100755 index 0000000..4511996 --- /dev/null +++ b/deploy/monitoring/scripts/smoke-test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +# The same fresh-data checks are used by the Windows Docker Desktop launcher. +# Server settings (including GRAFANA_PORT) are read from .env by smoke.py. +exec python3 scripts/smoke.py diff --git a/deploy/monitoring/scripts/smoke.py b/deploy/monitoring/scripts/smoke.py new file mode 100644 index 0000000..d61cca0 --- /dev/null +++ b/deploy/monitoring/scripts/smoke.py @@ -0,0 +1,134 @@ +"""Write fresh synthetic Metrics, Logs and Traces, then query this run's data.""" +from datetime import datetime, timezone +import base64 +import json +import secrets +from pathlib import Path +import time +from urllib.error import URLError +from urllib.parse import urlencode +from urllib.request import Request, build_opener, ProxyHandler + +# Local validation must not go through a workstation HTTP proxy. +HTTP = build_opener(ProxyHandler({})) + + +def request(url, data=None, content_type="application/json"): + headers = {"Accept": "application/json"} + if data is not None: + headers["Content-Type"] = content_type + with HTTP.open(Request(url, data=data, headers=headers), timeout=10) as response: + return response.read().decode("utf-8") + + +def poll(name, check, seconds=120): + deadline = time.monotonic() + seconds + detail = "condition not met" + while time.monotonic() < deadline: + try: + if check(): + print(f"PASS: {name}", flush=True) + return + except (URLError, TimeoutError, OSError, ValueError) as exc: + detail = str(exc) + time.sleep(2) + raise RuntimeError(f"FAIL: {name}: {detail}") + + +def grafana_smoke(url, password, username="admin", dashboard_uid="new-api-local"): + # Read a local secret into memory; never print credentials or Authorization headers. + auth = base64.b64encode((username + ":" + password.strip()).encode()).decode() + + def api(path): + with HTTP.open(Request(url + path, headers={"Authorization": "Basic " + auth}), timeout=15) as response: + return json.load(response) + + for uid in ("victoriametrics", "victorialogs", "tempo"): + poll(f"Grafana {uid} datasource", lambda uid=uid: api(f"/api/datasources/uid/{uid}/health").get("status") == "OK") + poll(f"Grafana {dashboard_uid} dashboard", lambda: api(f"/api/dashboards/uid/{dashboard_uid}")["dashboard"]["uid"] == dashboard_uid) + + +def smoke(endpoints, application=False): + checks = [("victoriametrics", 8428, "/health"), ("victorialogs", 9428, "/health"), + ("tempo", 3200, "/ready"), ("alertmanager", 9093, "/-/ready"), + ("vmalert", 8880, "/health"), ("vmagent", 8429, "/health"), + ("grafana", 3000, "/api/health")] + if ("node-exporter", 9100) in endpoints: + checks.append(("node-exporter", 9100, "/metrics")) + for service, port, path in checks: + def ready(url=endpoints[(service, port)] + path): + request(url) + return True + # First Grafana startup downloads the pinned datasource plugin (~78 MB). + poll(f"{service} ready", ready, seconds=600 if service == "grafana" else 120) + + vm = endpoints[("victoriametrics", 8428)] + vl = endpoints[("victorialogs", 9428)] + tempo = endpoints[("tempo", 3200)] + run_id = secrets.token_hex(8) + trace_id, span_id = secrets.token_hex(16), secrets.token_hex(8) + + # Omit the optional text timestamp so VM uses receipt time (not seconds as milliseconds). + request(vm + "/api/v1/import/prometheus", + f'observability_smoke{{source="smoke-test",run_id="{run_id}"}} 1\n'.encode(), "text/plain") + + def query(expression): + payload = json.loads(request(vm + "/api/v1/query?" + urlencode({"query": expression, "nocache": "1"}))) + if payload.get("status") != "success": + raise ValueError("Metrics query failed") + return payload["data"]["result"] + + poll("Metrics fresh write/query", lambda: any(float(row["value"][1]) == 1 + for row in query(f'observability_smoke{{run_id="{run_id}"}}'))) + + entry = {"_time": datetime.now(timezone.utc).isoformat(), "service": "observability-smoke", + "host": "local-smoke", "message": "synthetic smoke " + run_id, "trace_id": trace_id} + request(vl + "/insert/jsonline?_stream_fields=service,host&_msg_field=message&_time_field=_time", + (json.dumps(entry) + "\n").encode(), "application/stream+json") + log_query = urlencode({"query": f'service:="observability-smoke" AND trace_id:="{trace_id}"', "limit": "10"}) + poll("Logs fresh write/query", lambda: run_id in request(vl + "/select/logsql/query?" + log_query)) + + now = time.time_ns() + payload = {"resourceSpans": [{"resource": {"attributes": [ + {"key": "service.name", "value": {"stringValue": "observability-smoke"}}]}, + "scopeSpans": [{"scope": {"name": "local-smoke"}, "spans": [{ + "traceId": trace_id, "spanId": span_id, "name": "smoke-" + run_id, "kind": 2, + "startTimeUnixNano": str(now - 1000000), "endTimeUnixNano": str(now), + "status": {"code": 1}}]}]}]} + response = json.loads(request(endpoints[("tempo", 4318)] + "/v1/traces", json.dumps(payload).encode()) or "{}") + if int(response.get("partialSuccess", {}).get("rejectedSpans", 0)): + raise RuntimeError("Tempo rejected smoke span") + poll("Traces fresh OTLP write/exact trace query", + lambda: "smoke-" + run_id in request(tempo + "/api/traces/" + trace_id)) + + if application: + poll("new-api /api/status probe success", lambda: any(float(row["value"][1]) == 1 + for row in query('probe_success{job="new-api-health"}'))) + poll("new-api HTTP 200 recorded", lambda: any(float(row["value"][1]) == 200 + for row in query('probe_http_status_code{job="new-api-health"}'))) + poll("all configured scrapes healthy", lambda: bool(query("up")) + and all(float(row["value"][1]) == 1 for row in query("up"))) + print(f"All smoke tests passed. Synthetic run={run_id}, trace={trace_id}", flush=True) + + +if __name__ == "__main__": + ports = {"victoriametrics": [8428], "victorialogs": [9428], "tempo": [3200, 4318], + "alertmanager": [9093], "vmalert": [8880], "vmagent": [8429], + "node-exporter": [9100], "grafana": [3000]} + # Parse generated KEY=value settings as data; never execute .env as shell code. + settings = {} + env_file = Path(__file__).resolve().parents[1] / ".env" + if env_file.exists(): + for line in env_file.read_text().splitlines(): + if line.strip() and not line.lstrip().startswith("#") and "=" in line: + key, value = line.split("=", 1) + settings[key.strip()] = value.strip().strip("\"'") + grafana_port = int(settings.get("GRAFANA_PORT", "3000")) + if not 1 <= grafana_port <= 65535: + raise ValueError("GRAFANA_PORT must be between 1 and 65535") + endpoints = {(name, port): f"http://127.0.0.1:{port}" for name, numbers in ports.items() for port in numbers} + endpoints[("grafana", 3000)] = f"http://127.0.0.1:{grafana_port}" + smoke(endpoints) + if settings.get("GRAFANA_ADMIN_PASSWORD"): + grafana_smoke(endpoints[("grafana", 3000)], settings["GRAFANA_ADMIN_PASSWORD"], + settings.get("GRAFANA_ADMIN_USER", "admin"), "monitor-host-overview") diff --git a/deploy/monitoring/tests/check-ports-test.sh b/deploy/monitoring/tests/check-ports-test.sh new file mode 100755 index 0000000..85859f7 --- /dev/null +++ b/deploy/monitoring/tests/check-ports-test.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +set -euo pipefail + +root_dir="$(cd "$(dirname "$0")/.." && pwd)" +check_script="${root_dir}/scripts/check-ports.sh" +temp_dir="$(mktemp -d)" +listener_pid="" + +cleanup() { + if [[ -n "${listener_pid}" ]]; then + kill "${listener_pid}" >/dev/null 2>&1 || true + wait "${listener_pid}" 2>/dev/null || true + fi + rm -f "${temp_dir}/docker" "${temp_dir}/python3" "${temp_dir}/listener.log" + rmdir "${temp_dir}" +} +trap cleanup EXIT + +cat >"${temp_dir}/python3" <<'EOF' +#!/usr/bin/env bash +exec py "$@" +EOF +chmod +x "${temp_dir}/python3" + +cat >"${temp_dir}/docker" <<'EOF' +#!/usr/bin/env bash +if [[ "${DOCKER_COMPOSE_OWNS_PORT:-false}" == "true" && "$*" == "compose port test-service 9999" ]]; then + printf '127.0.0.1:%s\n' "${TEST_HOST_PORT}" + exit 0 +fi +if [[ "${DOCKER_EXTERNAL_OWNS_PORT:-false}" == "true" && "${1:-}" == "ps" ]]; then + echo "deadbeef external-monitor 127.0.0.1:${TEST_HOST_PORT}->9999/tcp" + exit 0 +fi +exit 1 +EOF +chmod +x "${temp_dir}/docker" + +free_port="$(py -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()')" +spec="test-service 9999 127.0.0.1 ${free_port}" + +PATH="${temp_dir}:${PATH}" PORT_CHECK_SPEC="${spec}" "${check_script}" >/dev/null +echo "PASS: an unused port is accepted" + +py -c 'import socket,sys,time; s=socket.socket(); s.bind(("127.0.0.1", int(sys.argv[1]))); s.listen(); print("ready", flush=True); time.sleep(30)' "${free_port}" >"${temp_dir}/listener.log" & +listener_pid=$! +for _ in $(seq 1 50); do + [[ -s "${temp_dir}/listener.log" ]] && break + sleep 0.1 +done + +set +e +conflict_output="$(PATH="${temp_dir}:${PATH}" PORT_CHECK_SPEC="${spec}" "${check_script}" 2>&1)" +conflict_code=$? +set -e +if [[ ${conflict_code} -eq 0 || "${conflict_output}" != *"${free_port}"* ]]; then + echo "FAIL: an externally occupied port was not rejected with a useful message" >&2 + exit 1 +fi +echo "PASS: an externally occupied port is rejected" + +PATH="${temp_dir}:${PATH}" \ + PORT_CHECK_SPEC="${spec}" \ + DOCKER_COMPOSE_OWNS_PORT=true \ + TEST_HOST_PORT="${free_port}" \ + "${check_script}" >/dev/null +echo "PASS: a port owned by the existing Compose service is accepted" + +docker_port="$(py -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()')" +docker_spec="test-service 9999 127.0.0.1 ${docker_port}" +set +e +docker_conflict_output="$(PATH="${temp_dir}:${PATH}" PORT_CHECK_SPEC="${docker_spec}" DOCKER_EXTERNAL_OWNS_PORT=true TEST_HOST_PORT="${docker_port}" "${check_script}" 2>&1)" +docker_conflict_code=$? +set -e +if [[ ${docker_conflict_code} -eq 0 || "${docker_conflict_output}" != *"external-monitor"* ]]; then + echo "FAIL: a port published by another Docker container was not rejected" >&2 + exit 1 +fi +echo "PASS: a port published by another Docker container is rejected" diff --git a/deploy/monitoring/tests/test_local_ports.py b/deploy/monitoring/tests/test_local_ports.py new file mode 100644 index 0000000..ac033bf --- /dev/null +++ b/deploy/monitoring/tests/test_local_ports.py @@ -0,0 +1,49 @@ +"""Reject real listener conflicts and unrelated Docker mappings before startup.""" +import importlib.util +from pathlib import Path +import socket +import unittest + +spec = importlib.util.spec_from_file_location("local", Path(__file__).parents[1] / "scripts/local.py") +local = importlib.util.module_from_spec(spec) +spec.loader.exec_module(local) + + +class PortChecks(unittest.TestCase): + def test_free_loopback_port(self): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + local.check_port("grafana", "127.0.0.1", port, 3000, []) + + def test_real_listener_rejected(self): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + sock.listen() + with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"): + local.check_port("grafana", "127.0.0.1", sock.getsockname()[1], 3000, []) + + def container(self, project="observability-local", service="grafana", ip="127.0.0.1"): + return {"Name": "/test", "Config": {"Labels": { + "com.docker.compose.project": project, + "com.docker.compose.service": service}}, + "NetworkSettings": {"Ports": {"3000/tcp": [{"HostIp": ip, "HostPort": "3001"}]}}} + + def test_own_mapping_allows_update(self): + local.check_port("grafana", "127.0.0.1", 3001, 3000, [self.container()]) + + def test_other_project_rejected(self): + with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"): + local.check_port("grafana", "127.0.0.1", 3001, 3000, [self.container(project="other")]) + + def test_wildcard_mapping_rejected(self): + with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"): + local.check_port("grafana", "127.0.0.1", 3001, 3000, [self.container(project="other", ip="0.0.0.0")]) + + def test_wrong_service_rejected(self): + with self.assertRaisesRegex(RuntimeError, "PORT CONFLICT"): + local.check_port("tempo", "127.0.0.1", 3001, 3000, [self.container()]) + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/monitoring/tests/test_mysql_config.py b/deploy/monitoring/tests/test_mysql_config.py new file mode 100644 index 0000000..e8139d8 --- /dev/null +++ b/deploy/monitoring/tests/test_mysql_config.py @@ -0,0 +1,42 @@ +"""Credential validation must fail before deployment and must not echo secrets.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location("local", Path(__file__).parents[1] / "scripts/local.py") +local = importlib.util.module_from_spec(spec) +spec.loader.exec_module(local) + + +class MySQLConfigChecks(unittest.TestCase): + def validate(self, content): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "my.cnf" + path.write_text(content, encoding="utf-8") + local.validate_mysql_config(path) + + def test_missing_file_has_actionable_error(self): + with tempfile.TemporaryDirectory() as directory: + with self.assertRaisesRegex(RuntimeError, "mysql-exporter.cnf"): + local.validate_mysql_config(Path(directory) / "mysql-exporter.cnf") + + def test_placeholder_is_rejected(self): + with self.assertRaisesRegex(RuntimeError, "password"): + self.validate("[client]\nhost=host.docker.internal\nport=3306\nuser=mysqld_exporter\npassword=REPLACE_WITH_MYSQL_MONITOR_PASSWORD\n") + + def test_valid_config_accepts_percent_without_interpolation(self): + self.validate("[client]\nhost=host.docker.internal\nport=3306\nuser=mysqld_exporter\npassword=test-only-50%\n") + + def test_invalid_file_does_not_echo_its_contents(self): + with self.assertRaises(RuntimeError) as caught: + self.validate("sensitive-canary-invalid-config") + self.assertNotIn("sensitive-canary", str(caught.exception)) + + def test_invalid_port_is_rejected(self): + with self.assertRaisesRegex(RuntimeError, "port"): + self.validate("[client]\nhost=host.docker.internal\nport=70000\nuser=mysqld_exporter\npassword=test-only\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/Grafana使用手册-本地new-api监控.md b/docs/Grafana使用手册-本地new-api监控.md new file mode 100644 index 0000000..38dcb87 --- /dev/null +++ b/docs/Grafana使用手册-本地new-api监控.md @@ -0,0 +1,323 @@ +# Grafana 使用手册:本地 new-api 监控 + +适用环境:本项目的本地 Docker Desktop 部署,Grafana 13.2.2。文档核对日期:2026-10-15。 + +**第一次使用,先完成第 1~4 节即可:登录、切换中文、打开看板、看懂数据。** 查询日志、链路和告警时,再看后面的章节。 + +## 1. 先认识几个入口 + +| 入口 | 地址 | 用途 | +| --- | --- | --- | +| 业务应用 | | 你已经启动的 new-api / monkey-ai | +| Grafana | | 登录、看图表、查询数据 | +| 应用看板 | | 直接查看应用状态 | +| 探索查询 | | 临时查询指标、日志、链路 | +| Alertmanager | | 查看当前告警、临时静默 | +| 采集目标状态 | | 排查数据为什么没有采集到 | + +这些地址只能在部署监控的这台电脑上使用。转发给同事后,对方电脑的 `127.0.0.1` 指向对方自己,不能打开你的监控。 + +你可以把 Grafana 理解为数据查看窗口:VictoriaMetrics 保存指标,VictoriaLogs 保存日志,Tempo 保存链路;Grafana 把它们查询出来并显示。 + +### 目前能看到什么 + +| 数据 | 当前接入情况 | +| --- | --- | +| new-api 状态接口是否可用 | 已接入,每 15 秒检查一次 | +| 状态接口 HTTP 状态码、耗时 | 已接入 | +| 监控组件能否正常采集 | 已接入 | +| 用于验证存储的测试日志、测试链路 | 已写入,可在对应时间范围查询 | +| 模型调用成功率、推理耗时、Token 用量、费用 | 尚未接入 | +| new-api 的真实业务日志、真实请求链路 | 尚未接入 | +| 企业微信群推送 | 尚未接入,前面对话中的步骤属于待实施方案 | + +**页面显示应用探测正常,不代表所有模型调用都正常。** 当前检查的是 `/api/status`,不是发起一次真实模型调用。 + +## 2. 登录 Grafana + +1. 浏览器打开 。 +2. 用户名填写 `admin`。 +3. 在 Windows PowerShell 中执行以下命令,读取本机密码: + + ```powershell + Get-Content "$env:LOCALAPPDATA\weiyuan-observability\grafana-admin-password.txt" + ``` + +4. 将命令显示的密码填到登录框,点击 **Log in / 登录**。 + +密码保存在工作区之外。不要把密码粘贴到群聊、使用文档或项目文件中。 + +如果你已经在 Grafana 里改过密码,请使用修改后的密码。还需要把外部 `grafana-admin-password.txt` 文件更新为同一个密码,供本地冒烟脚本验证登录;更新这个文件本身不会修改 Grafana 账号的密码。 + +## 3. 设置中文与时区 + +1. 登录后打开 。 +2. 找到 **Preferences / 偏好设置**。也可以通过头像菜单进入 **Profile / 个人资料**。 +3. 在 **Language / 语言** 中选择简体中文,名称可能显示为 **Chinese (Simplified)** 或 **中文(简体)**。 +4. 在 **Timezone / 时区** 中选择 **Browser time / 浏览器时间**;也可以选择 `Asia/Shanghai`。 +5. 点击 **Save / 保存**,刷新页面。 + +语言设置主要改变 Grafana 的菜单和按钮。当前预置看板的名称、图表标题仍然是英文,下一节有逐项解释。 + +如果菜单折叠,先点击左上角的菜单按钮展开导航。不同语言和窗口宽度下,按钮位置、译名可能略有差异;本手册提供的直接链接可用于跳过菜单查找。 + +## 4. 打开并看懂应用看板 + +直接打开 。 + +也可以从 **Dashboards / 仪表板** 进入 **Observability** 文件夹,打开 **New API - Local Health**。如果界面提供星标,可以收藏这个看板。 + +### 4.1 先设置时间范围 + +在页面右上角: + +1. 点击时间范围,选择 **Last 30 minutes / 最近 30 分钟**。 +2. 设置自动刷新为 **15s / 15 秒**,或点击刷新按钮手动更新。 +3. 查看过去的问题时,改成最近 6 小时、24 小时,或指定发生问题的起止时间。 + +图表中的时间范围决定“看哪一段历史”。改变时间范围不会修改业务,也不会删除数据。 + +查看实时状态时,要让时间范围的结束时间保持为“现在”。选择一个过去的固定区间后,即使持续刷新,也只会看到那段历史。 + +### 4.2 每个图表是什么意思 + +| 看板上的英文标题 | 中文含义 | 怎么看 | +| --- | --- | --- | +| Scope | 监控范围说明 | 说明当前目标和未接入的业务数据 | +| Status probe (1 = OK, 0 = failed) | 状态接口探测结果 | `1` 表示本次探测成功;`0` 表示失败 | +| HTTP status | 状态接口 HTTP 响应码 | 正常预期为 `200`;`0` 通常表示未收到有效 HTTP 响应 | +| Status endpoint duration | 状态接口探测耗时 | 例如 `200 ms` 表示约 0.2 秒;不是模型推理时间 | +| Status endpoint availability | 状态接口可用性历史 | 看曲线是否从 `1` 掉到 `0`,以及持续多久 | +| Status endpoint duration (not inference latency) | 状态接口耗时历史 | 看是否突然升高或持续波动 | +| Monitoring scrapes | 各监控目标的采集状态 | 每条曲线对应一个目标;`1` 为采集成功,`0` 为失败 | + +探测成功需要同时满足 **HTTP 200** 和响应体包含 `"success": true`。因此 HTTP 200 与探测成功并不完全等价。 + +**以数值和时间为准,不要只根据图表颜色判断健康。** 当前看板没有针对每个指标配置完整的红绿阈值规则。 + +### 4.3 鼠标怎么操作 + +- 把鼠标放在曲线上,可以查看对应时间的数值。 +- 拖选图表中的一段时间,可以放大那段时间;完成后从右上角恢复“最近 30 分钟”。 +- 点击图例中的目标名称,可以突出显示或筛选曲线,具体行为以当前图表为准。 +- 图表右上角的菜单通常有 **Inspect / 检查**,可以查看查询或数据;日常查看不需要进入编辑模式。 + +### 4.4 容易误解的三种情况 + +| 现象 | 含义 | +| --- | --- | +| 数值为 `0` | 有采集结果,但结果表示失败 | +| 显示 No data / 无数据 | 当前查询和时间范围内没有可显示的数据,不等同于数值为 0 | +| 上面的数字还是 `1`,曲线末尾却断了 | 数字卡片取所选时间范围内最后一个有效值,可能显示的是旧值;应检查最后一个数据点的时间和采集目标 | + +采集器关闭或 Docker Desktop 停止时,数据可能变成断线或无数据,而不是持续显示 0。 + +## 5. 在“探索”中自己查指标 + +看板适合日常看固定图表;**Explore / 探索** 适合临时查一个问题。 + +1. 打开 。 +2. 在数据源下拉框中选择 **VictoriaMetrics**。 +3. 如果查询编辑器提供 **Builder / 构建器** 与 **Code / 代码**,选择 **Code**。 +4. 粘贴下面任意一条查询。 +5. 时间选择最近 30 分钟,点击 **Run query / 运行查询**。 + +查询应用探测结果: + +```promql +probe_success{job="new-api-health"} +``` + +查询 HTTP 状态码: + +```promql +probe_http_status_code{job="new-api-health"} +``` + +查询探测耗时,转换为毫秒: + +```promql +1000 * probe_duration_seconds{job="new-api-health"} +``` + +查询所有监控目标的采集状态: + +```promql +up +``` + +只看正在报告采集失败的目标: + +```promql +up == 0 +``` + +最后一条查询如果没有结果,可能表示当前已有采集目标都正常。它不能证明目标数量完整,也不能检测已从采集配置中删除的目标;需要结合 `up` 和采集目标页面判断。 + +如果编辑器提供查询类型:**Range / 范围** 用于看一段时间的曲线,**Instant / 即时** 用于看所选结束时间的单个查询结果。 + +注意:`up{job="new-api-health"}=1` 只表示采集器成功拿到了探针指标;应用是否可用要看 `probe_success`。 + +## 6. 查询日志 + +1. 打开 **Explore / 探索**。 +2. 数据源切换为 **VictoriaLogs**。 +3. 时间选择 **最近 24 小时**。如果测试数据产生得更早,需要继续扩大时间范围。 +4. 在查询框输入下面的 LogsQL;若出现构建器,切换到代码或文本输入模式。 +5. 点击 **Run query / 运行查询**。 + +```text +service:="observability-smoke" +``` + +这会查询冒烟测试日志。展开一行,可以看到时间、消息和 `trace_id` 等字段。 + +筛选包含指定文字的测试日志: + +```text +service:="observability-smoke" AND "synthetic smoke" +``` + +已经知道某个 trace ID 时,替换下面的占位文字: + +```text +trace_id:="粘贴实际的trace_id" +``` + +目前没有采集 new-api 的真实业务日志,所以这里查不到真实用户请求、模型错误或账单记录。现有测试日志只证明日志写入、存储和查询可用。 + +如果选错成 VictoriaMetrics 数据源,上述日志查询不会按预期执行。指标、日志、链路使用不同的数据源和查询语言。 + +## 7. 查询链路,并从测试日志找到对应链路 + +### 7.1 按服务查找 + +1. 打开 **Explore / 探索**。 +2. 数据源选择 **Tempo**。 +3. 时间先选择 **最近 24 小时**。 +4. 选择 **TraceQL** 查询模式;如果界面显示代码编辑器,就在代码框中输入: + + ```traceql + { resource.service.name = "observability-smoke" } + ``` + +5. 点击 **Run query / 运行查询**。 +6. 在结果中打开一条 trace,查看耗时和 span 明细。 + +`trace` 是一次请求的完整链路;`span` 是链路中的一个操作。当前合成测试通常只有一个 span,不会出现 nginx → new-api → 上游服务的真实调用树。 + +### 7.2 从日志手动定位同一条链路 + +1. 按第 6 节查出一条测试日志。 +2. 展开日志,复制 `trace_id` 的值,不要复制字段名或引号。 +3. 切换到 **Tempo** 数据源。 +4. 选择 **Trace ID** 查询模式。 +5. 粘贴刚才的值,运行查询。 + +如果界面没有明显的 Trace ID 输入框,可以在 TraceQL 模式查询: + +```traceql +{ trace:id = "粘贴实际的trace_id" } +``` + +使用 TraceQL 搜索时,时间范围必须包含该条链路的发生时间。自动跨数据源跳转尚未作为完整功能验收,先使用这个手动方法。 + +## 8. 查看告警:当前主要到 Alertmanager + +**这套项目的规则由 vmalert 执行,通知由 Alertmanager 处理。** Grafana 自带的 Alerting 页面并未接入这些外部规则,因此在那里看不到规则,不代表项目没有告警。 + +1. 打开 。 +2. 查看告警分组及告警详情。 +3. 重点看 `alertname`、`instance`、`severity` 和说明文字。 + +当前有两条规则: + +| 告警名称 | 触发条件 | 等级 | +| --- | --- | --- | +| NewApiUnavailable | 应用探测连续失败 2 分钟 | P1 | +| LocalMonitoringTargetDown | 某个目标连续采集失败 2 分钟 | P2 | + +从第一次失败到告警可见,需要经过采集、规则评估和持续时间判断。通知还受分组等待影响,不是停止服务后立即就有通知。 + +没有活动告警时,Alertmanager 页面可以是空的。它不是保存全部历史告警的工单系统,恢复的告警不保证一直留在列表里。 + +### 临时静默是什么意思 + +维护期间,如果要暂时停止某个告警的通知,可以使用 Alertmanager 的 **Silence / 静默**:选择精确的告警名称和实例,填写结束时间、操作者和原因。 + +静默只抑制通知,不会修复故障、停止采集或让指标恢复正常。当前没有配置企业微信等外部接收器,所以尚不会向群里发送消息。 + +## 9. 无数据、打不开或登录失败时怎么查 + +按表格从上到下处理对应问题即可。 + +| 问题 | 先做什么 | 再检查什么 | +| --- | --- | --- | +| Grafana 页面打不开 | 确认地址是 3001,Docker Desktop 已启动 | 用下方 `ps` 命令查看容器 | +| 登录提示密码错误 | 确认用户名为 admin,读取外部密码文件 | 如果手动改过密码,使用新密码 | +| 图表显示 No data | 把时间改为最近 30 分钟或 24 小时,点击刷新 | 打开采集目标页面,检查目标状态与错误 | +| 应用探测为 0 | 在本机打开 | 再检查容器到宿主机的连通性和探针结果 | +| 某条 `up` 曲线为 0 | 打开 | 根据对应目标的 Last error / 最近错误排查 | +| 新部署后 Grafana 很久未就绪 | 查看 Grafana 日志 | 首次需要下载约 78 MB 的日志插件,本机首次约耗时 8 分钟 | +| 日志或链路没有结果 | 选择正确数据源,扩大到最近 24 小时 | 确认这段时间确实执行过冒烟测试 | +| 找不到 CPU、磁盘、内存看板 | 当前本地部署只展示应用状态 | 未启用 Windows 主机采集,不应把 Docker 虚拟机当作 Windows 本机 | +| 企业微信群没有消息 | 当前企业微信接入尚未实施 | 需要先完成适配服务、接收器配置和推送测试 | + +在 PowerShell 中查看监控状态: + +```powershell +cd D:\project\weiyuan-observability +py -3 deploy/monitoring/scripts/local.py ps +``` + +查看监控日志: + +```powershell +py -3 deploy/monitoring/scripts/local.py logs +``` + +重新运行冒烟测试: + +```powershell +py -3 deploy/monitoring/scripts/local.py smoke +``` + +冒烟测试会写入少量新的合成指标、日志和链路,读取它们,再验证应用探测和 Grafana 数据源。它不会发起收费模型请求,也不会主动关闭你的应用。 + +成功时最后输出: + +```text +Local stack, application probe and Grafana checks all passed. +``` + +测试完成后,选择最近 30 分钟,就可以在日志和链路查询中找到这次新生成的数据。 + +## 10. 想修改图表或自己做一个看板 + +当前 **New API - Local Health** 是由文件自动创建的预置看板。它受项目配置管理,界面可能不允许保存修改;正式修改应更新源 JSON,避免修改被后续配置刷新覆盖。 + +源文件:`deploy/monitoring/config/local/dashboards/new-api-local.json`。 + +初学时可以新建一个独立练习看板: + +1. 进入 **Dashboards / 仪表板**。 +2. 选择 **New / 新建 → New dashboard / 新建仪表板**。 +3. 添加一个 **Visualization / 可视化**。 +4. 数据源选择 **VictoriaMetrics**。 +5. 查询填入 `probe_success{job="new-api-health"}`。 +6. 可视化类型选择 **Time series / 时间序列**,标题填写“应用状态练习”。 +7. 返回看板并保存,名称填写“我的应用监控练习”。 + +这个练习看板保存在 Grafana 数据卷里,不会自动变成工作区中的 JSON 文件。若要跟随项目迁移,需要另行导出并纳入配置。 + +预置数据源同样由文件管理,编辑按钮不可用是正常现象。当前三个数据源已经配置好,日常查询直接选择即可。 + +## 11. 每天使用的最短流程 + +1. 打开 [应用看板](http://127.0.0.1:3001/d/new-api-local)。 +2. 时间选择最近 30 分钟,自动刷新 15 秒。 +3. 查看探测是否为 1、HTTP 是否为 200、曲线末尾是否持续更新。 +4. 有异常时,先查看 [采集目标](http://127.0.0.1:8429/targets) 和 [告警](http://127.0.0.1:9093)。 +5. 要进一步分析时,进入 [探索](http://127.0.0.1:3001/explore),选择对应数据源。 + +部署、停止及数据保留说明见 [本地部署使用说明](../deploy/monitoring/README.local.md)。 diff --git a/docs/superpowers/plans/2026-09-23-three-layer-observability-implementation.md b/docs/superpowers/plans/2026-09-23-three-layer-observability-implementation.md new file mode 100644 index 0000000..538db1a --- /dev/null +++ b/docs/superpowers/plans/2026-09-23-three-layer-observability-implementation.md @@ -0,0 +1,132 @@ +# Three-Layer Observability Platform Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 在 `weiyuan` 代码基线和现有五台物理机上,分批落地基础层、服务层、业务质量层和跨层关联的 Metrics + Logs + Traces 监控告警平台。 + +**Architecture:** 国内 VPC 内新增一台监控节点,运行 VictoriaMetrics、VictoriaLogs、Tempo、Grafana、vmalert 和 Alertmanager。五台业务主机安装 node_exporter、vmagent、Vector、Redis/MySQL/blackbox exporter;`monkey-ai` 的业务质量聚合复用 `monitor_outcome_stat`,通过独立指标导出或采集适配接入 Metrics。业务层完成后,再以 `traceparent` 灰度贯通 nginx → monkey-ai → CPA → CRS → tls。 + +**Tech Stack:** Go 1.25、React/Vite、MySQL 8、Redis、PM2、nginx、VictoriaMetrics、VictoriaLogs、Tempo、Grafana、vmalert、Alertmanager、Vector、OpenTelemetry。 + +**Spec:** `20260921-搭建三层统一监控告警平台.md`;业务质量实现参考 `D:\project\monkey-ai-weiyuan-inspection\docs\系统设计\20260916-调用质量监控看板设计方案.md`。 + +## Global Constraints + +- `weiyuan` 是业务代码主基线;`master` 作为独立代码线单独评估,不把监控改动从 `master` 直接移植到马甲包。 +- 业务质量枚举必须复用 `service/faultclass` 与 `service/monitor` 的 `outcome`、`fault_side`,不另定义成功率口径。 +- 任何生产写操作先做只读检查、备份和回滚演练;dump 清理、Redis 策略变更、日志 DDL 必须单独审批。 +- `MONITOR_QUALITY_ENABLED=false`、`OTEL_ENABLED=false` 必须可独立关闭,关闭监控不能影响请求、计费、兜底和路由。 +- 日志和链路数据禁止写入 API 密钥、Redis 密码、用户提示词原文或完整 Authorization;敏感字段只保留脱敏值或哈希。 +- 所有发布先在 ltop,再到 sma,最后到 weelinking 主品牌;每一批都必须有可执行的验收和回滚记录。 + +--- + +### Task 1: 建立基线与变更台账 + +**Files:** +- Create: `docs/ops/observability-inventory.md` +- Create: `docs/ops/observability-change-log.md` +- Inspect: `D:\project\monkey-ai-weiyuan-inspection\马甲包分支指南.md` + +- [ ] 记录远端提交号:`weiyuan=1eeb66a7`、`master=d149c427`,以及 `sma/ltop/hivetoken/aibiyi/paixtoken/tv/youlangg` 当前提交。 +- [ ] 为五台主机登记 hostname、SSH 别名、内网/公网地址、角色、PM2 应用、Redis/MySQL 连接位置和维护窗口;监控节点放在能访问 `172.16.0.x` 的国内 VPC。 +- [ ] 建立每个监控组件的 owner、数据保留期、告警接收人、回滚命令和最近一次验证时间。 +- [ ] 将附件中的生产操作标成“待授权”,不要在台账中记录密码或 DSN。 +- [ ] 验收:任何工程师可仅凭台账判断数据从哪台主机采集、发往哪里、失败时如何停采集。 + +### Task 2: 先做只读基线采集 + +- [ ] 在五台主机采集 `df -h`、`free -m`、`uptime`、`ss -lntp`、`pm2 jlist`、`pm2 report`、Redis `INFO memory`/`CONFIG GET maxmemory-policy`、MySQL 版本和磁盘剩余空间。 +- [ ] 统计 cct01 dump、`wy_crs/out.log`、release 目录和各日志目录按日增长量;保留采集时间和命令输出摘要。 +- [ ] 核对 nginx 每个 API location 的 `access_log`、当前 `log_format`、上游地址和 TLS 配置。 +- [ ] 核对每个马甲的 `.env` 中 `ERROR_LOG_ENABLED`、`MONITOR_QUALITY_ENABLED`、`LOG_SQL_DSN`、Redis db、PM2 端口;只记录变量是否存在和非敏感值。 +- [ ] 验收:基线结果与附件 2026-09-21 快照对比,差异超过阈值的项目先单独调查,不直接套用旧结论。 + +### Task 3: 生产止血与日志保留门禁 + +- [ ] 先在 cct01 复制并校验 `config/*.env`、PM2 ecosystem、nginx 和 logrotate 配置;记录恢复命令。 +- [ ] 获得授权后关闭三个 CPA request dump 开关,确认新请求不再产生 dump,再按日期删除 dump;删除前用 `du` 和 `find` 生成清单。 +- [ ] 为 cct01 的 `wy_crs/out.log`、billing 日志、CPA 日志和 release 目录补 logrotate/保留策略,执行 `logrotate -d` 后再启用。 +- [ ] 在确认键 TTL、maxmemory 和增长曲线后,再决定 crs3/crs227 Redis 是扩容还是改为 `noeviction`;先做低流量窗口演练,禁止直接切换。 +- [ ] 在 `weiyuan` 增加日志自动保留 worker:按 `LOG_RETENTION_DAYS=30` 分批删除 `LOG_DB.logs`,不复用 HTTP request context;增加 dry-run、删除量、耗时和失败告警。 +- [ ] 验收:磁盘使用率下降、dump 日增长为零、logrotate dry-run 无错误、日志清理可暂停/恢复;失败时只恢复配置,不回滚监控代码。 + +### Task 4: 部署监控节点和三栈存储 + +- [ ] 为监控节点准备 systemd 服务用户、专用数据盘、NTP、备份目录和防火墙白名单;只允许管理网访问 Grafana,采集端只允许向监控节点推送。 +- [ ] 以固定版本部署 VictoriaMetrics single-node、VictoriaLogs、Tempo、Grafana、vmalert 和 Alertmanager;全部使用本地磁盘、systemd 或受控 compose,不暴露未鉴权端口。 +- [ ] 配置保留:Metrics 400 天,业务聚合按应用已有 7 天/400 天/5 年,Logs 30 天,Traces 30 天起步;磁盘达到 70/80/85% 分别触发 P3/P2/P1。 +- [ ] 配置 Grafana 数据源和统一标签:`env`、`host`、`service`、`brand`、`instance`、`channel`、`vendor`;禁止把 `org_id`、token、用户 ID 放入高基数 Metrics 标签。 +- [ ] 验收:写入一条测试 metric、log、trace,Grafana 能查询,重启后数据仍在,磁盘和备份策略有效。 + +### Task 5: 接入基础层与服务层 + +- [ ] 五台主机安装 node_exporter、vmagent、Vector;cct01/crs01 同机但按两个逻辑服务标签区分。 +- [ ] 接入 Redis exporter、mysqld exporter 和 blackbox exporter;对 Redis maxmemory-policy、内存水位、键数、连接数,MySQL 可用性/连接池/慢查询,HTTP/HTTPS 探活分别建指标。 +- [ ] 通过 PM2/systemd 采集进程 RSS、CPU、重启次数、启动时间、退出码;保留 PM2 应用名、品牌、宿主机标签。 +- [ ] 建 Grafana 主机矩阵、主机详情、进程/中间件总览和重启事件面板。 +- [ ] 上线规则 1–8、15:磁盘、预测满盘、目录增长、RSS、重启率、Redis 策略/水位、探活;每条规则先用历史窗口试算,确认样本量和静默期。 +- [ ] 验收:用测试进程、临时 blackbox endpoint 和告警静默窗口验证告警触发、恢复、去重和通知。 + +### Task 6: 补齐 nginx 边缘日志 + +- [ ] 在 web69 备份 nginx 配置并先执行 `nginx -t`;新增 JSON/结构化 `log_format`,至少包含 `$time_iso8601`、`$host`、`$request`、`$status`、`$request_time`、`$upstream_response_time`、`$upstream_addr`、`$upstream_status`、请求 ID。 +- [ ] 将真实 API location 的 `access_log off` 改为独立文件;扫描器/静态资源日志单独存放,避免和业务请求混合。 +- [ ] 通过 Vector 解析 nginx 日志写入 VictoriaLogs,字段映射为 `brand`、`host`、`route`、`status`、`upstream`、`request_time_ms`、`upstream_time_ms`。 +- [ ] 逐域名验证 2xx/4xx/5xx、上游超时、客户端中断和静态资源不会丢字段;确认日志轮转后 Vector 不重复/不漏读。 +- [ ] 验收:Grafana 能从一个域名下钻到上游耗时和原始日志,nginx 请求量与 monkey-ai 入口量可比较。 + +### Task 7: 接入 `weiyuan` 业务质量指标 + +**Files:** +- Modify: `D:\project\monkey-ai-weiyuan-inspection\service\monitor\collector.go` +- Modify: `D:\project\monkey-ai-weiyuan-inspection\model\monitor_quality.go` +- Modify: `D:\project\monkey-ai-weiyuan-inspection\main.go` +- Test: `D:\project\monkey-ai-weiyuan-inspection\service\monitor\monitor_test.go` + +- [ ] 先补 MySQL/PostgreSQL 实库冒烟:验证质量表建表、`utf8mb4_bin`、聚合 upsert、日志列和复合索引;SQLite 通过不能代替这一步。 +- [ ] 增加只读指标导出适配:从 `monitor_outcome_stat` 聚合出请求量、六态结局、责任方、延迟桶、token/quota;默认只导出总量、品牌、模型、渠道和 vendor 低基数维度。 +- [ ] 建立渠道到 vendor 的归并配置,避免 90 个渠道直接形成高基数序列;把 vendor 映射版本写入配置和变更台账。 +- [ ] 增加品牌流量基线计算,处理“无流量”与“低样本”状态;不把零请求误报成 100% 成功。 +- [ ] 将告警范围扩展到 vendor,增加跨组降级、兜底失败率和探活绿但质量红所需的数据字段;保留现有平台/企业看板口径。 +- [ ] 验收:造直通成功、兜底成功、兜底失败、客户端中断、内容拦截各一条,15 秒内聚合可见;PromQL/MetricsQL 与业务看板的总量一致。 + +### Task 8: 完成业务告警和通知闭环 + +- [ ] 为 18 条规则建立配置清单:指标、作用域、最小样本量、持续时间、静默期、P1/P2/P3、通知渠道、恢复条件和对应历史事故。 +- [ ] 业务侧保留企业自助规则;基础设施侧统一由 vmalert/Alertmanager 管理,避免同一规则在两个入口重复告警。 +- [ ] 为事件模型补充严重级别、状态、认领人、恢复时间、升级策略和通知投递结果;通知失败必须可重试并写审计日志。 +- [ ] 配置 P1 电话/企微 @所有人、P2 群通知、P3 日报;先发测试接收人,验证恢复通知和静默期。 +- [ ] 验收:每类事故至少有一条可触发规则;同一窗口只通知一次,恢复后有恢复事件,未达到最小样本量不告警。 + +### Task 9: CRS、第三方供应商和线路观测 + +- [ ] 在不改业务协议的前提下采集 CRS Redis 账号状态、reroute JSONL、tls 代理日志和出口线路;账号、线路和 vendor 使用受控标签。 +- [ ] 将第三方渠道按供应商归并,统计供应商成功率、502/429/超时、P95 和线路失败率;自建 CRS 单独标记。 +- [ ] 建 CRS 域、账号、出口线路和供应商健康度页面;从质量告警跳转到具体渠道/账号/线路。 +- [ ] 配置规则 9–14、17–18,包含最小样本量和跨组降级检测;对敏感账号信息只展示脱敏标识。 +- [ ] 验收:人为制造一条测试供应商错误和出口失败,能够从告警落到原始日志和对应请求。 + +### Task 10: 跨仓库 Traces 灰度 + +- [ ] 先在 `ltop` 建立单请求 trace 骨架和 `OTEL_ENABLED=false` 默认关闭;确认 trace exporter 异步、有界队列、超时和丢弃计数。 +- [ ] 依次贯通 nginx → monkey-ai → CPA → CRS → tls,统一 W3C `traceparent`、`trace_id`、`span_id` 和服务名;不得把 request body 或密钥写入 span。 +- [ ] 每层增加 span 属性:`brand`、`route`、`channel`、`vendor`、`status`、`outcome`、`fault_side`、`host`;高基数用户/组织仅放日志字段或哈希。 +- [ ] 配置 Grafana Metrics → Logs → Traces 跳转;从 trace 可按时间窗查 VictoriaLogs,从日志可打开 Tempo。 +- [ ] 灰度顺序:单机 → ltop → sma → weelinking;每级观察 CPU、内存、请求延迟、队列丢弃和磁盘,异常立即关闭 `OTEL_ENABLED`。 +- [ ] 验收:同一请求在四层出现同一 trace ID,成功、重试、兜底、超时和进程重启场景均能形成可读瀑布。 + +### Task 11: 同步到马甲包并逐包验收 + +- [ ] 从最新 `origin/weiyuan` 建监控功能分支;禁止从 `master` 取监控代码。 +- [ ] 对 `sma/ltop/hivetoken/aibiyi/paixtoken/tv/youlangg` 逐个建立 worktree,先合并/变基到明确的 `weiyuan` 提交,再解决品牌配置、部署模板和端口冲突。 +- [ ] 每个马甲包确认 `monitor_*` 表迁移、`MONITOR_QUALITY_ENABLED`、日志库配置、Grafana `brand` 标签、PM2 实例名和 nginx 域名映射。 +- [ ] 每包执行后端监控测试、前端构建、迁移 dry-run、健康检查和一条真实低流量请求;记录提交号和回滚提交号。 +- [ ] 发布顺序固定为 ltop → sma → 小流量马甲 → weelinking;每次间隔至少一个完整业务高峰观察窗口。 + +### Task 12: 运营化和最终验收 + +- [ ] 建立每日检查:监控节点磁盘、采集延迟、Vector 错误、vmagent remote_write、Tempo/Logs 写入、告警投递和备份。 +- [ ] 建立每周检查:规则噪声、误报/漏报、vendor 映射、Redis 策略、PM2 重启、日志保留和 trace 采样量。 +- [ ] 执行故障演练:磁盘增长、进程重启、Redis 接近上限、单品牌断流、第三方 5xx、nginx 5xx、跨层 trace 丢失;每项验证发现、通知、定位、止损、恢复和复盘。 +- [ ] 最终验收标准:基础层、服务层、业务层三类页面均有数据;18 条规则有责任人和测试结果;任一采集器关闭不影响业务;所有生产变更有回滚记录。