Initialize observability stack with local monitoring and server134 deployment

This commit is contained in:
qiubaishen
2026-10-15 18:35:05 +08:00
commit f657abeed1
36 changed files with 4644 additions and 0 deletions
+8
View File
@@ -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
+14
View File
@@ -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
File diff suppressed because it is too large Load Diff
+381
View File
@@ -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.
+35
View File
@@ -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:<http://127.0.0.1:13000>
- Alertmanager:<http://127.0.0.1:19093>
这些地址仅在远程部署及 SSH 隧道成功后可用。端口冲突时停止并调整配置,不终止未知业务进程。所有端口默认绑定回环地址。
## 当前范围
本地已验证三类数据的合成读写,以及 new-api 状态接口探测。Linux 基础部署采集服务器和监控组件自身指标;生产应用、MySQL、业务日志、业务 Trace 和企业微信通知需要分别接入。Windows 的 `host.docker.internal` 目标及本地密码不会自动迁移到生产。
`.env`、运行数据、密码和采集器凭据不纳入 Git。原始方案是历史调查资料,不代表当前生产状态或额外变更授权。
+23
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
.env
data/
__pycache__/
+103
View File
@@ -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:<http://127.0.0.1:3001/d/new-api-local>
- Alertmanager:<http://127.0.0.1:9093>
- vmagent 采集状态:<http://127.0.0.1:8429/targets>
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 卷数据或外部密码;如需保留历史,需另行备份迁移。
+151
View File
@@ -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 业务进程。
+225
View File
@@ -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 查看
打开 <http://127.0.0.1:3001/explore>,选择 **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
```
打开 <http://127.0.0.1:8429/targets>,找到 `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)。官方默认采集项的授权范围比本配置广,勿直接混用授权示例。
+57
View File
@@ -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
```
访问 <http://127.0.0.1:13000>,默认用户名 `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 版本。
@@ -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
@@ -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
}
@@ -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
@@ -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
@@ -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'
@@ -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
}
}
}
]
}
@@ -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
@@ -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 }}"
+28
View File
@@ -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
@@ -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]
@@ -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]
@@ -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."
@@ -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}
+153
View File
@@ -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
+104
View File
@@ -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 <<EOF
grafana 3000 ${ui_bind_ip} ${grafana_port}
alertmanager 9093 ${ui_bind_ip} 9093
victoriametrics 8428 ${ingest_bind_ip} 8428
victorialogs 9428 ${ingest_bind_ip} 9428
tempo 4317 ${ingest_bind_ip} 4317
tempo 4318 ${ingest_bind_ip} 4318
tempo 3200 ${debug_bind_ip} 3200
vmalert 8880 ${debug_bind_ip} 8880
node-exporter 9100 ${debug_bind_ip} 9100
vmagent 8429 ${debug_bind_ip} 8429
EOF
)"
fi
compose_owns_port() {
local service="$1"
local container_port="$2"
local expected="$3"
local mappings
mappings="$(docker compose port "${service}" "${container_port}" 2>/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."
+34
View File
@@ -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 <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: ${VERSION_CODENAME}
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker
docker version
docker compose version
+191
View File
@@ -0,0 +1,191 @@
"""Local Docker Desktop monitoring; no credentials are written into the workspace."""
import argparse
import configparser
import json
import os
from pathlib import Path
import secrets
import socket
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
STATE = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / ".local/share"))) / "weiyuan-observability"
SECRET = STATE / "grafana-admin-password.txt"
MYSQL_SECRET = STATE / "mysql-exporter.cnf"
PROJECT = "observability-local"
def validate_mysql_config(path):
if not path.is_file():
raise RuntimeError(f"Create the external mysql-exporter.cnf first: {path}")
config = configparser.ConfigParser(interpolation=None)
try:
config.read_string(path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, configparser.Error):
# Parser exceptions can contain entire lines, including credentials.
raise RuntimeError("Invalid MySQL config; expected UTF-8 INI with a [client] section. Contents hidden.") from None
if not config.has_section("client"):
raise RuntimeError("MySQL config needs a [client] section.")
for key in ("host", "user", "password"):
value = config.get("client", key, fallback="").strip().strip('\"\'')
if not value or value == "REPLACE_WITH_MYSQL_MONITOR_PASSWORD":
raise RuntimeError(f"Set a real {key} in the external MySQL config; value hidden.")
if config.get("client", "user").strip().strip('\"\'').lower() == "root":
raise RuntimeError("Use a dedicated monitoring account instead of root.")
try:
port = config.getint("client", "port")
if not 1 <= port <= 65535:
raise ValueError()
except (ValueError, TypeError, configparser.Error):
raise RuntimeError("MySQL port must be an integer between 1 and 65535.") from None
def mysql_smoke():
from urllib.parse import urlencode
from smoke import request, poll
validate_mysql_config(MYSQL_SECRET)
config = model()
binding = config["services"]["victoriametrics"]["ports"][0]
base = f"http://127.0.0.1:{binding['published']}"
started = time.time()
def has_value(expression, expected):
# Wait for a scrape after this check started, not a cached pre-restart value.
fresh = f"({expression}) and (timestamp({expression}) >= {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)
+38
View File
@@ -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
+6
View File
@@ -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
+134
View File
@@ -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")
+79
View File
@@ -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"
@@ -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()
@@ -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()
@@ -0,0 +1,323 @@
# Grafana 使用手册:本地 new-api 监控
适用环境:本项目的本地 Docker Desktop 部署,Grafana 13.2.2。文档核对日期:2026-10-15。
**第一次使用,先完成第 1~4 节即可:登录、切换中文、打开看板、看懂数据。** 查询日志、链路和告警时,再看后面的章节。
## 1. 先认识几个入口
| 入口 | 地址 | 用途 |
| --- | --- | --- |
| 业务应用 | <http://127.0.0.1:3000> | 你已经启动的 new-api / monkey-ai |
| Grafana | <http://127.0.0.1:3001> | 登录、看图表、查询数据 |
| 应用看板 | <http://127.0.0.1:3001/d/new-api-local> | 直接查看应用状态 |
| 探索查询 | <http://127.0.0.1:3001/explore> | 临时查询指标、日志、链路 |
| Alertmanager | <http://127.0.0.1:9093> | 查看当前告警、临时静默 |
| 采集目标状态 | <http://127.0.0.1:8429/targets> | 排查数据为什么没有采集到 |
这些地址只能在部署监控的这台电脑上使用。转发给同事后,对方电脑的 `127.0.0.1` 指向对方自己,不能打开你的监控。
你可以把 Grafana 理解为数据查看窗口:VictoriaMetrics 保存指标,VictoriaLogs 保存日志,Tempo 保存链路;Grafana 把它们查询出来并显示。
### 目前能看到什么
| 数据 | 当前接入情况 |
| --- | --- |
| new-api 状态接口是否可用 | 已接入,每 15 秒检查一次 |
| 状态接口 HTTP 状态码、耗时 | 已接入 |
| 监控组件能否正常采集 | 已接入 |
| 用于验证存储的测试日志、测试链路 | 已写入,可在对应时间范围查询 |
| 模型调用成功率、推理耗时、Token 用量、费用 | 尚未接入 |
| new-api 的真实业务日志、真实请求链路 | 尚未接入 |
| 企业微信群推送 | 尚未接入,前面对话中的步骤属于待实施方案 |
**页面显示应用探测正常,不代表所有模型调用都正常。** 当前检查的是 `/api/status`,不是发起一次真实模型调用。
## 2. 登录 Grafana
1. 浏览器打开 <http://127.0.0.1:3001>。
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. 登录后打开 <http://127.0.0.1:3001/profile>。
2. 找到 **Preferences / 偏好设置**。也可以通过头像菜单进入 **Profile / 个人资料**。
3. 在 **Language / 语言** 中选择简体中文,名称可能显示为 **Chinese (Simplified)** 或 **中文(简体)**。
4. 在 **Timezone / 时区** 中选择 **Browser time / 浏览器时间**;也可以选择 `Asia/Shanghai`。
5. 点击 **Save / 保存**,刷新页面。
语言设置主要改变 Grafana 的菜单和按钮。当前预置看板的名称、图表标题仍然是英文,下一节有逐项解释。
如果菜单折叠,先点击左上角的菜单按钮展开导航。不同语言和窗口宽度下,按钮位置、译名可能略有差异;本手册提供的直接链接可用于跳过菜单查找。
## 4. 打开并看懂应用看板
直接打开 <http://127.0.0.1:3001/d/new-api-local>。
也可以从 **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. 打开 <http://127.0.0.1:3001/explore>。
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. 打开 <http://127.0.0.1:9093>。
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 | 在本机打开 <http://127.0.0.1:3000/api/status> | 再检查容器到宿主机的连通性和探针结果 |
| 某条 `up` 曲线为 0 | 打开 <http://127.0.0.1:8429/targets> | 根据对应目标的 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)。
@@ -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 条规则有责任人和测试结果;任一采集器关闭不影响业务;所有生产变更有回滚记录。