feat(observability): 接通预发布告警收件箱
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-30 10:29:40 +08:00
parent 11ed667c85
commit ee9aa707a7
7 changed files with 266 additions and 7 deletions

View File

@ -4,7 +4,7 @@
| --- | --- | | --- | --- |
| `local/` | 本地联调和演示所需的 Compose 配置、样例环境变量 | | `local/` | 本地联调和演示所需的 Compose 配置、样例环境变量 |
| `helm/item-atlas/` | Kubernetes Helm Chart,部署网关、物品与录入服务 | | `helm/item-atlas/` | Kubernetes Helm Chart,部署网关、物品与录入服务 |
| `observability/` | 预发布 Prometheus、Grafana、Alloy、Loki 和 Tempo 的 Helm 配置与安装脚本 | | `observability/` | 预发布指标、日志、链路和告警收件箱的配置与安装脚本 |
| [`public/`](public/README.md) | iOS 公网预览的 PostgreSQL、Keycloak、FRP、Nginx 和验收步骤 | | [`public/`](public/README.md) | iOS 公网预览的 PostgreSQL、Keycloak、FRP、Nginx 和验收步骤 |
| [`admin-preview/`](admin-preview/README.md) | 管理后台专用的 kind 本机预览与账号权限验收 | | [`admin-preview/`](admin-preview/README.md) | 管理后台专用的 kind 本机预览与账号权限验收 |

View File

@ -0,0 +1,67 @@
apiVersion: v1
kind: Service
metadata:
name: atlas-alert-inbox
spec:
selector: {app.kubernetes.io/name: atlas-alert-inbox}
ports:
- {name: http, port: 8080}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: atlas-alert-inbox
spec:
serviceName: atlas-alert-inbox
replicas: 1
selector:
matchLabels: {app.kubernetes.io/name: atlas-alert-inbox}
template:
metadata:
labels: {app.kubernetes.io/name: atlas-alert-inbox}
spec:
automountServiceAccountToken: false
securityContext:
fsGroup: 10001
fsGroupChangePolicy: OnRootMismatch
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
seccompProfile: {type: RuntimeDefault}
containers:
- name: ntfy
image: binwiederhier/ntfy:v2.38.3@sha256:874299b207a9815e7a0cf551b3a094241db7604fa2d274bbd86f569154b6ea51
args: [serve]
env:
- {name: NTFY_LISTEN_HTTP, value: ':8080'}
- {name: NTFY_BASE_URL, value: 'http://127.0.0.1:18485'}
- {name: NTFY_AUTH_FILE, value: /data/users.db}
- {name: NTFY_AUTH_DEFAULT_ACCESS, value: deny-all}
- {name: NTFY_AUTH_ACCESS, value: 'atlas-alert-publisher:atlas-staging-alerts:wo,atlas-alert-viewer:atlas-staging-alerts:ro'}
- {name: NTFY_ENABLE_LOGIN, value: 'true'}
- {name: NTFY_CACHE_FILE, value: /data/messages.db}
- {name: NTFY_CACHE_DURATION, value: 48h}
envFrom:
- secretRef: {name: atlas-alert-inbox-auth}
ports:
- {name: http, containerPort: 8080}
readinessProbe:
httpGet: {path: /v1/health, port: http}
timeoutSeconds: 3
livenessProbe:
httpGet: {path: /v1/health, port: http}
timeoutSeconds: 3
resources:
requests: {cpu: 15m, memory: 32Mi}
limits: {memory: 128Mi}
securityContext:
allowPrivilegeEscalation: false
capabilities: {drop: [ALL]}
volumeMounts:
- {name: data, mountPath: /data}
volumeClaimTemplates:
- metadata: {name: data}
spec:
accessModes: [ReadWriteOnce]
resources:
requests: {storage: 256Mi}

View File

@ -7,8 +7,14 @@ config_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
kubectl --context "$context" get namespace item-atlas-staging >/dev/null kubectl --context "$context" get namespace item-atlas-staging >/dev/null
kubectl --context "$context" -n "$observability" get secret atlas-grafana-admin -o name >/dev/null kubectl --context "$context" -n "$observability" get secret atlas-grafana-admin -o name >/dev/null
for secret in atlas-alert-inbox-auth atlas-alert-inbox-publisher; do
kubectl --context "$context" -n "$observability" get secret "$secret" -o name >/dev/null
done
kubectl --context "$context" apply --dry-run=server -f "$config_dir/serviceaccount.yaml" -f "$config_dir/rbac.yaml" >/dev/null kubectl --context "$context" apply --dry-run=server -f "$config_dir/serviceaccount.yaml" -f "$config_dir/rbac.yaml" >/dev/null
kubectl --context "$context" apply -f "$config_dir/serviceaccount.yaml" -f "$config_dir/rbac.yaml" kubectl --context "$context" apply -f "$config_dir/serviceaccount.yaml" -f "$config_dir/rbac.yaml"
kubectl --context "$context" -n "$observability" apply --dry-run=server -f "$config_dir/alert-inbox.yaml" >/dev/null
kubectl --context "$context" -n "$observability" apply -f "$config_dir/alert-inbox.yaml"
kubectl --context "$context" -n "$observability" rollout status statefulset/atlas-alert-inbox --timeout=4m
if [ -z "${ATLAS_CHART_DIR:-}" ]; then if [ -z "${ATLAS_CHART_DIR:-}" ]; then
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts helm repo add prometheus-community https://prometheus-community.github.io/helm-charts

View File

@ -0,0 +1,52 @@
"""Prepare credentials for the internal alert inbox in a private directory."""
import argparse
import json
import os
import secrets
import string
import subprocess
from pathlib import Path
def password_hash(username, password):
result = subprocess.run(
['htpasswd', '-niBC', '10', username],
input=password + '\n', text=True, capture_output=True, check=True,
)
return result.stdout.strip().split(':', 1)[1]
def prepare(directory):
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
if directory.stat().st_mode & 0o077:
raise SystemExit('Use a private directory (chmod 700) outside the Git worktree.')
vault = directory / 'credentials.json'
if not vault.exists():
alphabet = string.ascii_lowercase + string.digits
values = {
'viewer_password': secrets.token_urlsafe(24),
'publisher_password': secrets.token_urlsafe(24),
'publisher_token': 'tk_' + ''.join(secrets.choice(alphabet) for _ in range(29)),
}
with vault.open('x') as stream:
json.dump(values, stream, indent=2)
values = json.loads(vault.read_text())
viewer = 'atlas-alert-viewer'
publisher = 'atlas-alert-publisher'
users = ','.join(
f'{name}:{password_hash(name, values[field])}:user'
for name, field in ((viewer, 'viewer_password'), (publisher, 'publisher_password'))
)
token = values['publisher_token']
(directory / 'inbox.env').write_text(
f'NTFY_AUTH_USERS={users}\nNTFY_AUTH_TOKENS={publisher}:{token}:Alertmanager\n',
)
(directory / 'publisher-token').write_text(token)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('directory', type=Path, help='Private directory outside the Git worktree')
os.umask(0o077)
prepare(parser.parse_args().directory)

View File

@ -11,6 +11,9 @@ server:
scrape_interval: 30s scrape_interval: 30s
scrape_timeout: 5s scrape_timeout: 5s
evaluation_interval: 30s evaluation_interval: 30s
alertmanagers:
- static_configs:
- targets: [atlas-alertmanager:9093]
persistentVolume: persistentVolume:
size: 2Gi size: 2Gi
resources: resources:
@ -22,7 +25,40 @@ configmapReload:
requests: {cpu: 10m, memory: 24Mi} requests: {cpu: 10m, memory: 24Mi}
limits: {memory: 64Mi} limits: {memory: 64Mi}
alertmanager: alertmanager:
enabled: false enabled: true
fullnameOverride: atlas-alertmanager
automountServiceAccountToken: false
persistence:
enabled: true
size: 256Mi
resources:
requests: {cpu: 15m, memory: 32Mi}
limits: {memory: 128Mi}
configmapReload:
resources:
requests: {cpu: 10m, memory: 16Mi}
limits: {memory: 48Mi}
extraSecretMounts:
- name: alert-inbox-token
mountPath: /etc/alertmanager/secrets/inbox
secretName: atlas-alert-inbox-publisher
readOnly: true
config:
route:
receiver: atlas-alert-inbox
group_by: [alertname, namespace, workload]
group_wait: 10s
group_interval: 30s
repeat_interval: 2h
receivers:
- name: atlas-alert-inbox
webhook_configs:
- url: 'http://atlas-alert-inbox:8080/atlas-staging-alerts?template=alertmanager'
send_resolved: true
http_config:
follow_redirects: false
authorization:
credentials_file: /etc/alertmanager/secrets/inbox/token
kube-state-metrics: kube-state-metrics:
enabled: false enabled: false
prometheus-node-exporter: prometheus-node-exporter:
@ -62,17 +98,28 @@ scrapeConfigs:
- source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name] - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name]
target_label: workload target_label: workload
serverFiles: serverFiles:
alerts: alerting_rules.yml:
groups: groups:
- name: item-atlas - name: item-atlas
rules: rules:
- alert: AtlasBackendScrapeDown - alert: AtlasBackendScrapeDown
expr: up{job="item-atlas"} == 0 expr: >-
(max by (job, namespace, workload) (up{job="item-atlas",namespace="item-atlas-staging",
workload=~"item-atlas-(gateway|inventory-service|intake-service)"}) == 0)
or absent(up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-gateway"})
or absent(up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-inventory-service"})
or absent(up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-intake-service"})
for: 2m for: 2m
labels:
severity: critical
annotations: annotations:
summary: "无法采集 {{ $labels.workload }} 的应用指标" summary: "无法采集 {{ $labels.workload }} 的应用指标"
- alert: AtlasOutboxNeedsReview - alert: AtlasOutboxNeedsReview
expr: max(atlas_outbox_operations{job="item-atlas",state="needs_review"}) > 0 expr: max(atlas_outbox_operations{job="item-atlas",state="needs_review"}) > 0
for: 2m for: 2m
labels:
severity: warning
namespace: item-atlas-staging
workload: item-atlas-intake-service
annotations: annotations:
summary: "批量录入有待核查操作" summary: "批量录入有待核查操作"

View File

@ -0,0 +1,51 @@
rule_files: [alerting_rules.yml]
evaluation_interval: 30s
tests:
- interval: 30s
input_series:
- series: 'up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-gateway",pod="gateway-old"}'
values: '0 0 stale _ _ _ _'
- series: 'up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-gateway",pod="gateway-new"}'
values: '_ _ _ _ _ 1 1'
- series: 'up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-inventory-service",pod="inventory-old"}'
values: '0+0x6'
- series: 'up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-inventory-service",pod="inventory-new"}'
values: '1+0x6'
- series: 'up{job="item-atlas",namespace="item-atlas-staging",workload="item-atlas-intake-service"}'
values: '1+0x6'
alert_rule_test:
- eval_time: 1m30s
alertname: AtlasBackendScrapeDown
exp_alerts: []
- eval_time: 2m
alertname: AtlasBackendScrapeDown
exp_alerts:
- exp_labels:
job: item-atlas
namespace: item-atlas-staging
workload: item-atlas-gateway
severity: critical
exp_annotations:
summary: 无法采集 item-atlas-gateway 的应用指标
- eval_time: 2m30s
alertname: AtlasBackendScrapeDown
exp_alerts: []
- interval: 30s
input_series:
- series: 'atlas_outbox_operations{job="item-atlas",state="needs_review",pod="intake-one"}'
values: '0 2 2 2 2 2 0'
- series: 'atlas_outbox_operations{job="item-atlas",state="needs_review",pod="intake-two"}'
values: '0 2 2 2 2 2 0'
alert_rule_test:
- eval_time: 2m30s
alertname: AtlasOutboxNeedsReview
exp_alerts:
- exp_labels:
severity: warning
namespace: item-atlas-staging
workload: item-atlas-intake-service
exp_annotations:
summary: 批量录入有待核查操作
- eval_time: 3m
alertname: AtlasOutboxNeedsReview
exp_alerts: []

View File

@ -1,10 +1,12 @@
# 预发布监控部署 # 预发布监控部署
应用、采集器和查询端都使用 Kubernetes 内部服务。预发布由五个独立的上游 Helm release 组成。Prometheus 拉指标,Alloy 从 Kubernetes API 读应用日志并接收 OTLP 链路,Grafana 统一查询。告警规则由 Prometheus 计算,当前在 Prometheus 页面查看。 预发布的遥测使用 Kubernetes 内部服务。Prometheus 拉指标,Alloy 从 Kubernetes API 读应用日志并接收 OTLP 链路,Grafana 统一查询。Prometheus 判定告警,Alertmanager 分组并将触发和恢复消息投递到 ntfy 收件箱。
| 组件 | Chart 版本 | 内网入口 | 存储 | | 组件 | Chart 版本 | 内网入口 | 存储 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Prometheus | `prometheus-community/prometheus@30.0.0` | `atlas-prometheus-server:80` | 2 GiB,保留 3 天,容量目标 1200 MB | | Prometheus | `prometheus-community/prometheus@30.0.0` | `atlas-prometheus-server:80` | 2 GiB,保留 3 天,容量目标 1200 MB |
| Alertmanager | Prometheus Chart 内置的 `alertmanager@2.5.1` | `atlas-alertmanager:9093` | 256 MiB,保存静默和通知状态 |
| ntfy | `binwiederhier/ntfy:v2.38.3`,由 StatefulSet 部署 | `atlas-alert-inbox:8080` | 256 MiB,保存访问控制库和最近 48 小时通知 |
| Loki | `grafana-community/loki@21.6.0` | `atlas-loki:3100` | 2 GiB,单进程 TSDB 文件存储,保留 72 小时 | | Loki | `grafana-community/loki@21.6.0` | `atlas-loki:3100` | 2 GiB,单进程 TSDB 文件存储,保留 72 小时 |
| Tempo | `grafana-community/tempo@2.4.0` | 查询 `atlas-tempo:3200`,OTLP HTTP `atlas-tempo:4318` | 2 GiB,单进程本地块存储,保留 72 小时 | | Tempo | `grafana-community/tempo@2.4.0` | 查询 `atlas-tempo:3200`,OTLP HTTP `atlas-tempo:4318` | 2 GiB,单进程本地块存储,保留 72 小时 |
| Alloy | `grafana/alloy@1.16.0` | OTLP HTTP `atlas-alloy:4318` | 收发缓冲 | | Alloy | `grafana/alloy@1.16.0` | OTLP HTTP `atlas-alloy:4318` | 收发缓冲 |
@ -16,17 +18,51 @@ Tempo 的容器内存上限为 512 MiB,Go 内存软上限为 320 MiB,留出
## 安装和更新 ## 安装和更新
先核对工作集群、`item-atlas-staging` 命名空间、默认 StorageClass 和 SSD 余量。由集群维护账号创建监控命名空间,并在其下创建 `atlas-grafana-admin` Secret。将管理员密码以受控文件输入,执行后安全移除临时文件。 先核对工作集群、`item-atlas-staging` 命名空间、默认 StorageClass 和 SSD 余量。首次部署时,由集群维护账号创建监控命名空间和凭据。Grafana 管理员密码从受控文件读取。收件箱用 Python 3 和支持 bcrypt 的 `htpasswd` 生成凭据,将下列示例路径替换为 SSD 上仓库外的目录。目录权限为 700,生成的文件权限为 600。
```sh ```sh
kubectl --context kind-atlas-dev create namespace item-atlas-observability kubectl --context kind-atlas-dev create namespace item-atlas-observability
kubectl --context kind-atlas-dev -n item-atlas-observability create secret generic atlas-grafana-admin \ kubectl --context kind-atlas-dev -n item-atlas-observability create secret generic atlas-grafana-admin \
--from-literal=admin-user=admin --from-file=admin-password=/path/to/managed-password-file --from-literal=admin-user=admin --from-file=admin-password=/path/to/managed-password-file
alert_secrets=/path/on/ssd/atlas-alert-secrets
python3 deploy/observability/prepare-alert-secrets.py "$alert_secrets"
kubectl --context kind-atlas-dev -n item-atlas-observability create secret generic atlas-alert-inbox-auth \
--from-env-file="$alert_secrets/inbox.env"
kubectl --context kind-atlas-dev -n item-atlas-observability create secret generic atlas-alert-inbox-publisher \
--from-file="token=$alert_secrets/publisher-token"
sh deploy/observability/install.sh kind-atlas-dev sh deploy/observability/install.sh kind-atlas-dev
kubectl --context kind-atlas-dev -n item-atlas-observability get deployment,statefulset,pvc,service kubectl --context kind-atlas-dev -n item-atlas-observability get deployment,statefulset,pvc,service
``` ```
安装脚本核对现有环境,用服务端 dry run 校验 Role、RoleBinding 和 ServiceAccount,再执行 Helm `--atomic --wait`。若环境只能从内网下载,先按脚本的版本将官方 Chart 下载为 `组件-版本.tgz`,通过 `ATLAS_CHART_DIR` 指定其目录。Prometheus 只需在预发布读 Pod,Alloy 另需读同一命名空间的 `pods/log`。应用遥测端点、数据查询端和 Collector 均使用 ClusterIP。上线环境应当在入口只转业务路径,并为采集和查询配置对应的网络权限。 [Kubernetes RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) 更新时保留既有 Secret,直接重跑安装脚本。脚本用服务端 dry run 校验 RBAC 和收件箱,等收件箱就绪后执行 Helm `--atomic --wait`。若环境只能从内网下载,先按脚本版本将官方 Chart 下载为 `组件-版本.tgz`,通过 `ATLAS_CHART_DIR` 指定目录。Prometheus 只需在预发布读 Pod,Alloy 另需读同一命名空间的 `pods/log`。应用遥测端点、数据查询端和 Collector 均使用 ClusterIP。上线环境应当在入口只转业务路径,并为采集和查询配置对应的网络权限。 [Kubernetes RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)
## 告警规则和收件箱
- `AtlasBackendScrapeDown` 按工作负载检查网关、物品服务和录入服务。连续两分钟没有一个副本采集成功时触发,服务从发现列表彻底消失也算不可用。
- `AtlasOutboxNeedsReview` 在录入待核查数量连续两分钟大于零时触发。多个副本读取同一数据库,取最大值以避免重复计数。
- Alertmanager 按告警名、命名空间和工作负载分组。首次等待 10 秒,组变化间隔 30 秒,持续触发时每两小时重复通知。恢复后发同组的恢复消息。发布账号只能写入该主题,登录账号 `atlas-alert-viewer` 只能读取,密码取生成的 `credentials.json`。 [Prometheus 告警规则](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) · [Alertmanager 路由](https://prometheus.io/docs/alerting/latest/configuration/) · [ntfy 访问控制](https://docs.ntfy.sh/config/#access-control)
从维护终端打开回环转发,再访问本机 `http://127.0.0.1:18485/atlas-staging-alerts`。通知保存在本机收件箱里。
```sh
kubectl --context kind-atlas-dev -n item-atlas-observability \
port-forward --address 127.0.0.1 svc/atlas-alert-inbox 18485:8080
```
排错时先用 Prometheus 的 Rules 页面看规则有没有进入 `firing`,再用 Alertmanagers 状态页检查目标是否可用。Alertmanager 已收到但是收件箱无消息时,检查 Alertmanager 容器日志中的 webhook 响应、ntfy 健康检查和两个 Secret 是否使用同一发布 token。验收时用带唯一标识的合成规则触发,再让条件到期,核对收到触发和恢复两条消息后移除测试规则。
规则变更可以导出 Chart 生成的规则文件,在同目录运行入库用例。需要 Helm、kubectl 和与部署相同版本的 `promtool`。
```sh
qa_dir=$(mktemp -d)
helm template atlas-prometheus ./prometheus-30.0.0.tgz \
-n item-atlas-observability -f deploy/observability/prometheus.yaml \
--show-only templates/cm.yaml > "$qa_dir/prometheus-cm.yaml"
kubectl create --dry-run=client -f "$qa_dir/prometheus-cm.yaml" \
-o 'jsonpath={.data.alerting_rules\.yml}' > "$qa_dir/alerting_rules.yml"
cp deploy/observability/tests/alerts.yaml "$qa_dir/"
(cd "$qa_dir" && promtool test rules alerts.yaml)
```
## Java 接入的位置 ## Java 接入的位置