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
+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")