feat(obs): add Loki/Promtail LXC config for central production stack (BIT-21663)

- deploy/loki/promtail-lxc.yaml: journald-based Promtail config for native
  LXC/systemd deployment; unit filter on bitreport-error-reporting-*.service;
  LOKI_PUSH_URL via env var expansion (-config.expand-env=true)
- deploy/loki/systemd/promtail.service: systemd unit; loopback-only binding;
  EnvironmentFile=/etc/promtail/env for secrets
- docs/deployment/loki-lxc-runbook.md: full operational runbook — Loki on
  central obs CT, Promtail on app LXC, firewall, smoke LogQL queries
- docs/OBSERVABILITY_LOKI.md: document production topology divergence vs
  lab compose; update configuration files table

Paperclip-Task: BIT-21663
Paperclip-Agent: tiago-neves
This commit is contained in:
David Santos committed 2026-05-11 22:18:58 +00:00
1 parent b4356e747d
commit c74e05b844
4 files changed
+435 -2

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
# Promtail configuration for errors.bitreport.pt — native LXC/systemd deployment.
# Reads logs from the systemd journal (no Docker socket needed).
# Ships to a central Loki instance; set LOKI_PUSH_URL in the systemd unit environment.
# Start promtail with: promtail -config.file=... -config.expand-env=true
# Docs: docs/deployment/loki-lxc-runbook.md, docs/OBSERVABILITY_LOKI.md
server:
# Bind only to loopback — no external exposure from the app LXC.
http_listen_address: 127.0.0.1
http_listen_port: 9080
grpc_listen_port: 0
log_level: warn
positions:
filename: /var/lib/promtail/positions.yaml
clients:
- url: ${LOKI_PUSH_URL}
backoff_config:
min_period: 500ms
max_period: 5m
max_retries: 10
scrape_configs:
# ── errors-hub services (systemd journal) ──────────────────────────────────
- job_name: errors-hub-journal
journal:
json: false
max_age: 12h
# Path to journal; /var/log/journal if persistent logging is enabled,
# otherwise /run/log/journal (volatile, cleared on reboot).
path: /var/log/journal
labels:
app: errors-hub
env: production
relabel_configs:
# Only keep journal entries from the four bitreport-error-reporting units.
- source_labels: [__journal__systemd_unit]
regex: "bitreport-error-reporting-(.+)\\.service"
action: keep
# Extract service name: "bitreport-error-reporting-ingest-api.service" → "ingest-api"
- source_labels: [__journal__systemd_unit]
regex: "bitreport-error-reporting-(.+)\\.service"
replacement: "$1"
target_label: service
pipeline_stages:
# ── Attempt JSON parse (Pino / structured logs) ───────────────────────
- json:
expressions:
pino_level: level
log_msg: msg
log_err: err
# ── Normalize Pino numeric levels to human-readable strings ───────────
# Pino: 10=trace 20=debug 30=info 40=warn 50=error 60=fatal
- template:
source: pino_level
template: |
{{ if eq .Value "10" }}trace
{{- else if eq .Value "20" }}debug
{{- else if eq .Value "30" }}info
{{- else if eq .Value "40" }}warn
{{- else if eq .Value "50" }}error
{{- else if eq .Value "60" }}fatal
{{- else }}{{ .Value }}
{{- end }}
# Promote the normalised level to a Loki label (low-cardinality).
- labels:
level: pino_level
# ── Drop trace/debug in production ────────────────────────────────────
- match:
selector: '{level=~"trace|debug"}'
action: drop
drop_counter_reason: below_min_level
+48
View File
@@ -0,0 +1,48 @@
# systemd unit for Promtail on the errors.bitreport.pt app LXC.
# Ships journald logs from the four bitreport-error-reporting-*.service units
# to the central Loki instance.
#
# Installation (run as root on the app LXC):
# cp this file /etc/systemd/system/bitreport-promtail.service
# systemctl daemon-reload
# systemctl enable --now bitreport-promtail.service
#
# Required before enabling:
# 1. Binary installed: /usr/local/bin/promtail (see runbook)
# 2. Config deployed: /etc/promtail/promtail-lxc.yaml
# 3. Data directory: install -d -m 0750 -o promtail -g promtail /var/lib/promtail
# 4. User created: useradd --system --no-create-home --shell /usr/sbin/nologin promtail
# usermod -aG systemd-journal promtail
# 5. Set LOKI_PUSH_URL in /etc/promtail/env (no quotes, no export):
# LOKI_PUSH_URL=http://<central-loki-ip>:3100/loki/api/v1/push
#
# Full runbook: docs/deployment/loki-lxc-runbook.md
[Unit]
Description=Promtail — errors-hub log shipper to central Loki
Documentation=https://grafana.com/docs/loki/latest/send-data/promtail/
After=network.target
# Start after the app services so journal entries are already flowing.
After=bitreport-error-reporting-ingest-api.service
After=bitreport-error-reporting-api.service
After=bitreport-error-reporting-collector-worker.service
After=bitreport-error-reporting-admin-ui.service
[Service]
Type=simple
User=promtail
Group=promtail
# Read LOKI_PUSH_URL from a separate secrets file (not in git).
EnvironmentFile=/etc/promtail/env
ExecStart=/usr/local/bin/promtail \
-config.file=/etc/promtail/promtail-lxc.yaml \
-config.expand-env=true
Restart=on-failure
RestartSec=10s
# Cap memory; Promtail is lightweight — adjust if ingestion volume grows.
MemoryMax=128M
# Journal read requires supplementary group membership (usermod -aG systemd-journal promtail).
# No extra SupplementaryGroups= directive needed when usermod is used.
[Install]
WantedBy=multi-user.target
+39 -2
View File
@@ -4,6 +4,8 @@ Centralised log aggregation for all errors.bitreport.pt services using Grafana L
## Architecture
### Development / lab (Docker Compose)
```
ingest-api ──┐
collector-worker ─┤ stdout/stderr ┌──────────────┐ HTTP push ┌──────┐
@@ -16,6 +18,38 @@ mariadb ──┘ └───────────
Promtail discovers containers via the Docker socket by matching the `errors-bitreport-pt` compose project label. All services emit structured JSON logs (Pino format); Promtail parses them and normalises Pino numeric levels to human-readable strings before shipping.
### Production (LXC/systemd — stack central)
In production the services run as **native systemd units on an LXC container** (no Docker). Promtail runs on the same app LXC and reads logs from the **systemd journal** instead of the Docker socket. Loki runs on a **separate central observability LXC** shared across company services.
```
┌─────────────────────────────────────┐
│ LXC: errors-hub (app) │
│ ingest-api / api / collector-worker│
│ admin-ui (systemd units) │
│ │
│ Promtail 127.0.0.1:9080 │──── journald (/var/log/journal)
└──────────────┬──────────────────────┘
│ HTTP push :3100 (LAN)
▼
┌──────────────────────────────────────┐
│ LXC: observability (central CT) │
│ Loki :3100 (LAN only) │──▶ Grafana (LogQL)
└──────────────────────────────────────┘
```
**Key differences from the lab setup:**
| Aspect | Lab (Compose) | Production (LXC) |
|--------|--------------|-----------------|
| Log source | Docker socket (container SD) | systemd journal |
| Promtail config | `deploy/loki/promtail.yaml` | `deploy/loki/promtail-lxc.yaml` |
| Loki location | Same host as app | Central observability LXC |
| Service filter | `com.docker.compose.project=errors-bitreport-pt` | `bitreport-error-reporting-*.service` units |
| Promtail binding | Docker network | 127.0.0.1 (loopback only) |
Full operational runbook: **[`docs/deployment/loki-lxc-runbook.md`](deployment/loki-lxc-runbook.md)**
## Starting the observability stack
```bash
@@ -171,6 +205,9 @@ docker compose --profile observability up -d
| File | Purpose |
|---|---|
| `deploy/loki/loki.yaml` | Loki server — storage, schema, retention |
| `deploy/loki/promtail.yaml` | Promtail — Docker SD, JSON parsing, label extraction |
| `deploy/loki/loki.yaml` | Loki server — storage, schema, retention (lab and production) |
| `deploy/loki/promtail.yaml` | Promtail — Docker socket SD (lab/compose only) |
| `deploy/loki/promtail-lxc.yaml` | Promtail — journald SD (production LXC) |
| `deploy/loki/systemd/promtail.service` | systemd unit for Promtail on the app LXC |
| `deploy/grafana/loki-logs-dashboard.json` | Grafana log visualisation dashboard |
| `docs/deployment/loki-lxc-runbook.md` | Operational runbook — LXC/central stack setup |
+269
View File
@@ -0,0 +1,269 @@
# Loki/Promtail — produção LXC (stack central)
Runbook operacional para a stack de logs da plataforma **errors.bitreport.pt** em produção (LXC/systemd, fora do compose de laboratório). Complementa `docs/OBSERVABILITY_LOKI.md` — a diferença chave é o método de descoberta de logs: **journald** em vez de Docker socket.
---
## 1. Arquitectura de produção
```
┌─────────────────────────────────────┐ rede interna (LAN/VLAN)
│ LXC: errors-hub (app) │
│ │
│ ingest-api.service (3041) │──┐
│ api.service (3200) │ │ journald
│ collector-worker.service │ │
│ admin-ui.service (3040) │ │
│ │ │
│ promtail.service (127.0.0.1:9080)│─┘ → lê /var/log/journal
└────────────────────┬────────────────┘
│ HTTP push → :3100
▼
┌──────────────────────────────────────┐
│ LXC: observability (CT obs) │
│ Loki :3100 (LAN only) │
│ Grafana :3000 (LAN/VPN) │
└──────────────────────────────────────┘
```
### Decisões de design
| Decisão | Escolha | Razão |
|---------|---------|-------|
| Onde corre Loki | CT dedicado (observability) | Isolamento; partilhado por outros serviços da empresa |
| Onde corre Promtail | Mesmo LXC que a app (errors-hub) | Acesso directo ao journal; sem socket Docker |
| Método de descoberta | `journal` (systemd) | LXC sem Docker; unidades `bitreport-error-reporting-*.service` |
| Porto Loki externo | 3100 (LAN only — não exposto à internet) | Sem colisão; app LXC usa 3040/3041/3200 |
| Porto Promtail | 127.0.0.1:9080 (loopback only) | Sem exposição externa; só métricas locais |
| Retenção | 30 dias | Alinhado com config de laboratório |
| TLS Promtail→Loki | Não (LAN interna) | Se Loki migrar para fora da LAN, adicionar mTLS |
---
## 2. CT observability — instalar Loki
### 2.1 Criar o LXC (Proxmox)
- Template Debian 12 ou Ubuntu 24.04 (alinhado com restante infra)
- 1 GB RAM, 1 vCPU, ≥ 20 GB disco SSD (dados Loki crescem ~1-2 GB/dia com tráfego típico a 30 dias)
- Sem nesting (não é necessário Docker se usar binário nativo)
- IP LAN fixo (ex.: anotar na vault e em `docs/ENVIRONMENTS.md`)
### 2.2 Instalar Loki (binário nativo)
```bash
# Descarregar binário (substituir VERSION pela última estável)
LOKI_VERSION=3.4.3
curl -LO "https://github.com/grafana/loki/releases/download/v${LOKI_VERSION}/loki-linux-amd64.zip"
unzip loki-linux-amd64.zip
install -m 0755 loki-linux-amd64 /usr/local/bin/loki
# Utilizador de serviço
useradd --system --no-create-home --shell /usr/sbin/nologin loki
# Direcórias de dados e config
install -d -m 0750 -o loki -g loki /etc/loki /var/lib/loki /var/lib/loki/chunks /var/lib/loki/rules /var/lib/loki/compactor
```
### 2.3 Deploy da config
```bash
# O loki.yaml de produção é o mesmo que deploy/loki/loki.yaml (filesystem storage).
# Ajuste os caminhos para /var/lib/loki em vez de /loki:
cp /opt/errors.bitreport.pt/deploy/loki/loki.yaml /etc/loki/loki.yaml
```
Editar `/etc/loki/loki.yaml` — alterar `path_prefix` e `chunks_directory` para `/var/lib/loki`:
```yaml
common:
instance_addr: 127.0.0.1
path_prefix: /var/lib/loki
storage:
filesystem:
chunks_directory: /var/lib/loki/chunks
rules_directory: /var/lib/loki/rules
```
### 2.4 Systemd unit para Loki
```ini
# /etc/systemd/system/loki.service
[Unit]
Description=Loki — log aggregation (BitReport observability)
After=network.target
[Service]
Type=simple
User=loki
Group=loki
ExecStart=/usr/local/bin/loki -config.file=/etc/loki/loki.yaml
Restart=on-failure
RestartSec=10s
MemoryMax=512M
[Install]
WantedBy=multi-user.target
```
```bash
systemctl daemon-reload
systemctl enable --now loki.service
# Verificar
curl http://localhost:3100/ready # → "ready"
```
### 2.5 Firewall — expor porto apenas na LAN
```bash
# Exemplo UFW: permitir apenas a sub-rede interna (ajustar ao VLAN real)
ufw allow from 192.168.1.0/24 to any port 3100 proto tcp
ufw deny 3100
```
---
## 3. LXC errors-hub — instalar Promtail
### 3.1 Instalar binário
```bash
PROMTAIL_VERSION=3.4.3
curl -LO "https://github.com/grafana/loki/releases/download/v${PROMTAIL_VERSION}/promtail-linux-amd64.zip"
unzip promtail-linux-amd64.zip
install -m 0755 promtail-linux-amd64 /usr/local/bin/promtail
# Utilizador de serviço com acesso ao journal
useradd --system --no-create-home --shell /usr/sbin/nologin promtail
usermod -aG systemd-journal promtail
# Direcórias
install -d -m 0750 -o promtail -g promtail /etc/promtail /var/lib/promtail
```
### 3.2 Deploy da config
```bash
cp /opt/errors.bitreport.pt/deploy/loki/promtail-lxc.yaml /etc/promtail/promtail-lxc.yaml
chmod 644 /etc/promtail/promtail-lxc.yaml
```
### 3.3 Ficheiro de ambiente (segredos fora do git)
```bash
# /etc/promtail/env (mode 640, root:promtail)
install -m 0640 /dev/null /etc/promtail/env
chown root:promtail /etc/promtail/env
```
Conteúdo de `/etc/promtail/env` (sem `export`, sem aspas):
```
LOKI_PUSH_URL=http://<IP-LAN-DO-CT-OBS>:3100/loki/api/v1/push
```
### 3.4 Instalar e activar systemd unit
```bash
cp /opt/errors.bitreport.pt/deploy/loki/systemd/promtail.service \
/etc/systemd/system/bitreport-promtail.service
systemctl daemon-reload
systemctl enable --now bitreport-promtail.service
```
### 3.5 Verificar que o Promtail está a recolher
```bash
# Estado do serviço
systemctl status bitreport-promtail.service
# Readiness
curl http://127.0.0.1:9080/ready
# Targets activos (deve mostrar as 4 unidades bitreport-error-reporting-*)
curl -s http://127.0.0.1:9080/targets | python3 -m json.tool | grep -E "job|labels|health"
# Logs do próprio Promtail
journalctl -u bitreport-promtail.service -f --no-pager
```
---
## 4. Grafana — ligar ao Loki central
Na instância Grafana da empresa (CT obs ou Grafana Cloud):
1. **Connections → Data sources → Add → Loki**
2. URL: `http://<IP-LAN-DO-CT-OBS>:3100` (ou `http://localhost:3100` se Grafana estiver no mesmo CT)
3. Nome da datasource: **`Loki`** (para compatibilidade com o dashboard existente)
4. Guardar e testar.
Importar o dashboard: **Dashboards → Import → Upload JSON** → `deploy/grafana/loki-logs-dashboard.json`.
---
## 5. Smoke — validação em staging
Após arranque dos serviços, executar as seguintes queries no **Grafana Explore** com datasource `Loki`:
### 5.1 Confirmar que há dados das 4 unidades
```logql
{app="errors-hub"} | limit 20
```
Esperado: linhas com `service` ∈ `{ingest-api, api, collector-worker, admin-ui}`.
### 5.2 Logs de erro recentes
```logql
{app="errors-hub", level="error"} | json
```
### 5.3 Logs da ingest-api (última hora)
```logql
{app="errors-hub", service="ingest-api"} | json
```
### 5.4 Verificação via API Loki (sem Grafana)
```bash
# Labels presentes (confirmar `app=errors-hub`)
curl 'http://<IP-LOKI>:3100/loki/api/v1/labels'
# 5 linhas recentes de qualquer serviço errors-hub
curl -G 'http://<IP-LOKI>:3100/loki/api/v1/query_range' \
--data-urlencode 'query={app="errors-hub"}' \
--data-urlencode 'limit=5' \
--data-urlencode "start=$(date -d '1 hour ago' +%s)000000000" \
--data-urlencode "end=$(date +%s)000000000"
```
Critério de aceitação: resposta com `status: "success"` e `data.result` não vazio.
---
## 6. Troubleshooting rápido
| Sintoma | Verificação |
|---------|-------------|
| Promtail não arranca | `journalctl -u bitreport-promtail -n 50`; verificar `LOKI_PUSH_URL` em `/etc/promtail/env` |
| Sem targets no `/targets` | Confirmar que as unidades `bitreport-error-reporting-*.service` estão a correr; verificar permissão journal (`id promtail`) |
| Loki recusa amostras antigas | `curl -s http://<LOKI>:3100/metrics | grep loki_discarded`; ajustar `reject_old_samples_max_age` em `loki.yaml` |
| Journal não persistente | `ls /var/log/journal` vazio → activar: `mkdir -p /var/log/journal && systemctl restart systemd-journald` |
| Logs sem label `level` | Serviço não emite JSON (ex.: MariaDB) — normal; `level` fica ausente para linhas plain-text |
---
## 7. Referência de artefactos
| Artefacto | Caminho |
|-----------|---------|
| Config Promtail (LXC/journald) | `deploy/loki/promtail-lxc.yaml` |
| Config Promtail (lab/Docker) | `deploy/loki/promtail.yaml` |
| Config Loki | `deploy/loki/loki.yaml` |
| Systemd unit Promtail | `deploy/loki/systemd/promtail.service` |
| Dashboard Grafana | `deploy/grafana/loki-logs-dashboard.json` |
| Doc principal Loki | `docs/OBSERVABILITY_LOKI.md` |