Initialize observability stack with local monitoring and server134 deployment
This commit is contained in:
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
.env
|
||||
data/
|
||||
__pycache__/
|
||||
@@ -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 卷数据或外部密码;如需保留历史,需另行备份迁移。
|
||||
@@ -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 业务进程。
|
||||
@@ -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)。官方默认采集项的授权范围比本配置广,勿直接混用授权示例。
|
||||
@@ -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 }}"
|
||||
@@ -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}
|
||||
@@ -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
|
||||
Executable
+104
@@ -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
@@ -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
|
||||
@@ -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)
|
||||
Executable
+38
@@ -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
|
||||
Executable
+6
@@ -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
|
||||
@@ -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")
|
||||
Executable
+79
@@ -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()
|
||||
Reference in New Issue
Block a user