Files
errors.bitreport.pt/docs/RUNBOOK_TRIAGE.md
T
Peter Spark 7f9cb51391 docs(runbook): document BIT-921 wdmi-store OAuth2 DNS (import_margin)
- Add ERRSIG:c41bcf736d8b to Google TLS runbook (§5.3 cluster, §5.11, er-cli).
- Cross-link from RUNBOOK_TRIAGE related-docs line.

Paperclip-Agent: 0b1fcf92-5fe3-4ac0-9f29-df4ab72f5376
Paperclip-Issue: BIT-921
Paperclip-Run: ded9f3f2-7f5c-4843-b5b5-f2b9caede9e3
Made-with: Cursor
2026-04-05 04:07:14 +00:00

9.6 KiB

Runbook — errors.bitreport.pt: Triagem, Correção, Deploy e Fecho

Audiência: Operação, agentes Paperclip, on-call. Última revisão: 2026-04-05 Requisitos: curl, jq, acesso à variável ERROR_RESOLVE_API_KEY, acesso SSH ao LXC host (se deploy necessário).

Documentação relacionada: HTTP_CONTRACTS.md (contratos + curl), RUNBOOK_OPERATIONS.md (5 cenários CLI), RUNBOOK_INGEST_DEBUG.md (ingest 401/429/fingerprint), RUNBOOK_REPORTER_GOOGLE_TLS.md (cURL 35 / 6 — TLS e DNS / Google OAuth no reporter PHP; HTTP 503/500 Sheets backendError — §5.7–§5.9, p.ex. BIT-912 / BIT-916; DNS oauth2 + import_margin em wdmi-store — §5.11 / BIT-921), RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md (simplexml_load_file / Flexit Importer no reporter PHP), RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md (SimpleXLS / _auferma.php / Uninitialized string offset no reporter wdmi-store), RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md (upload de feed / upload_feed_tier / clients.wdmi.pt no reporter PHP; confusão host ingestão vs URL de upload — ver §1.1 desse runbook), RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md (Importer CacheFilesystem / mkdir(): File exists no reporter wdmi-store), RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md (Importer _visiotech.php / strlen(null) deprecation PHP 8.1+ no reporter wdmi-store), RUNBOOK_REPORTER_CRM_ERRORMONITORING_VIEW.md (CRM View.php / @errormonitoring/dashboard no reporter PHP), RUNBOOK_REPORTER_CRM_PROCESSMANAGER_VIEW.md (CRM View.php / @processmanager/dashboard no reporter PHP), RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md (CRM Logger.php / mkdir(): Permission denied no reporter PHP), RUNBOOK_REPORTER_CRM_TASKS_DUE_TIME.md (CRM crm_tasks.due_time / string vazia vs NULL no reporter PHP), RUNBOOK_REPORTER_CRM_DATABASE_MEMORY.md (CRM DatabaseManager.php / esgotamento de memory_limit no reporter PHP), OBSERVABILITY_PROMETHEUS.md.


Variáveis de ambiente necessárias

export ERROR_RESOLVE_API_KEY="<chave de operações>"
export ER_API_BASE="https://errors.bitreport.pt"   # default; omitir se correcto

1. Triagem — Verificar estado actual

1.1 Listar incidentes abertos

./scripts/er-cli.sh list-open

Filtros opcionais:

./scripts/er-cli.sh list-open --project crm --severity critical
./scripts/er-cli.sh list-open --project wdmi --limit 50
./scripts/er-cli.sh list-open --q "Connection refused"

Saída: [<id>] <projecto> | <severidade> | <título> — um por linha.

1.2 Exportar para CSV ou JSON

# Todos os abertos → CSV
./scripts/er-cli.sh export --state open --format csv > /tmp/open-$(date +%Y%m%d).csv

# Todos os estados → JSON
./scripts/er-cli.sh export --state all > /tmp/snapshot-$(date +%Y%m%d).json

1.3 Verificar saúde dos serviços

curl -sf "${ER_API_BASE}/health" | jq '.'
# Espera-se: {"status":"ok"} ou equivalente

curl -sf "${ER_API_BASE}/api/error-monitoring/recent-errors?api_key=${ERROR_RESOLVE_API_KEY}&limit=1" | jq '.success'
# Espera-se: true

1.4 Checklist de triagem

  • Serviço ingest a responder em /health
  • API de leitura a devolver success: true
  • Volume de incidentes critical aceitável (ver thresholds no permission-matrix.md)
  • Sem pico anómalo de occurrences nas últimas 24h

2. Resolução — Fechar incidentes

2.1 Resolver incidente individual

./scripts/er-cli.sh resolve 12345
./scripts/er-cli.sh resolve 12345 --note "Fixed in deploy v2.3.1" --assigned-to "devops"

Resposta de sucesso:

{
  "success": true,
  "message": "Erro marcado como resolvido",
  "data": { "unique_id": "12345", "resolution_notes": "Fixed in deploy v2.3.1" }
}

2.2 Resolver por padrão de mensagem (bulk)

Sempre fazer dry-run primeiro:

# Pré-visualizar o que seria resolvido
./scripts/er-cli.sh resolve-by-pattern "Connection refused to redis" --dry-run

# Confirmar e executar
./scripts/er-cli.sh resolve-by-pattern "Connection refused to redis" \
  --note "Redis restarted, connections recovered" \
  --assigned-to "infra"

Nota: O padrão usa LIKE %pattern%. Usar padrões específicos para evitar resoluções em excesso.

2.3 Resolver vários IDs de uma vez (via curl directo)

curl -sf -X POST "${ER_API_BASE}/api/error-monitoring/bulk-resolve" \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "'"${ERROR_RESOLVE_API_KEY}"'",
    "unique_ids": ["123", "456", "789"],
    "resolution_notes": "Closed after investigation"
  }' | jq '.'

3. Purge — Limpar incidentes resolvidos

Sempre dry-run antes do purge real:

# Ver quantos seriam apagados
./scripts/er-cli.sh purge --dry-run

# Apagar (irreversível — ver secção 5 se precisar de backup)
./scripts/er-cli.sh purge

Saída esperada (dry-run):

{ "success": true, "message": "Dry run", "data": { "dry_run": true, "would_delete": 42 } }

Saída esperada (execução real):

{ "success": true, "message": "Apagados 42 incidentes resolvidos", "data": { "deleted": 42 } }

Atenção: O purge remove incidentes e todas as occurrences associadas (CASCADE). Não é reversível sem restauro de base de dados.


4. Deploy — Atualizar o hub

4.1 Deploy via webhook (CI)

O repositório tem webhook Gitea configurado. Push para master dispara deploy automático no LXC.

Para forçar manualmente via SSH:

ssh <lxc-host>
cd <ER_REPO_ROOT>   # definido em /etc/error-reporting/env
bash deploy/lxc/webhook-deploy.sh

4.2 Deploy manual (passo-a-passo)

ssh <lxc-host>
set -a && source /etc/error-reporting/env && set +a

cd "${ER_REPO_ROOT}"
git fetch origin master
git merge --ff-only origin/master

# Build
(cd ingest-api && npm ci && npm run build)
(cd admin-ui && npm ci && npm run build)
(cd collector-worker && npm ci && npm run build)
(cd api && npm ci && npm run build)

# Migrações
bash scripts/run-mysql-migrations.sh

# Reiniciar serviços
systemctl restart er-ingest er-api er-collector er-admin-ui 2>/dev/null || \
  systemctl restart error-reporting 2>/dev/null

# Smoke check
bash deploy/lxc/verify.sh

4.3 Checklist pós-deploy

  • deploy/lxc/verify.sh — todos os checks a passar
  • curl -sf "${ER_API_BASE}/health" → {"status":"ok"}
  • Ingest /health responde
  • er-cli.sh list-open devolve resultados sem erro
  • Admin UI acessível em https://errors.bitreport.pt (sem 502/504)
  • Volume de novas occurrences estável (sem flood pós-deploy)

5. Backup pré-purge (opcional)

export BACKUP_FILE="/tmp/er-backup-$(date +%Y%m%d%H%M%S).json"
./scripts/er-cli.sh export --state all > "${BACKUP_FILE}"
echo "Backup: ${BACKUP_FILE} ($(wc -l < "${BACKUP_FILE}") linhas)"

6. Fecho — Critérios de conclusão

Uma sessão de triagem está concluída quando:

  • Zero incidentes critical abertos (ou todos justificados/em investigação)
  • Todos os incidentes resolvidos estão com resolution_notes preenchidas
  • Purge executado (ou agendado) para manter base de dados limpa
  • Snippet de evidência HTTP/JSON registado no ticket Paperclip associado

7. Referências rápidas

Operação Comando
Listar abertos er-cli.sh list-open
Listar críticos er-cli.sh list-open --severity critical
Exportar snapshot er-cli.sh export --state all --format json
Resolver ID er-cli.sh resolve <id> --note "..."
Bulk resolve por padrão er-cli.sh resolve-by-pattern "<texto>" --dry-run depois sem --dry-run
Purge (seguro) er-cli.sh purge --dry-run → er-cli.sh purge
Health check curl -sf "${ER_API_BASE}/health"
Stats curl -sf "${ER_API_BASE}/v1/stats/summary?..." (requer sessão admin)

8. Escalada

Situação Acção
Ingest /health a falhar Verificar processo er-ingest no LXC; reiniciar; verificar logs systemd
DB inacessível Verificar MariaDB no LXC; verificar DATABASE_URL em /etc/error-reporting/env
ERROR_RESOLVE_API_KEY inválida (401) Rever /etc/error-reporting/env; regenerar chave se necessário
Flood de novos erros (>500/min) Verificar noise rules no collector worker; activar filtro rate-limit
Deploy falhou Ver verify.sh output; rollback com git checkout <prev-commit> + rebuild

9. Comandos de diagnóstico complementares

# Occurrences nas últimas 24h (raw, via admin session — apenas acesso directo)
curl -sf "${ER_API_BASE}/v1/stats/summary" \
  -H "Cookie: __Host-access=<jwt>" | jq '.resolvedLast24h, .totalLast24h'

# Tendência por severidade (7 dias)
curl -sf "${ER_API_BASE}/v1/stats/trend?granularity=day&days=7" \
  -H "Cookie: __Host-access=<jwt>" | jq '.'

# Top incidentes recorrentes (48h)
curl -sf "${ER_API_BASE}/v1/stats/recurrence?hours=48" \
  -H "Cookie: __Host-access=<jwt>" | jq '.'

Nota: Os endpoints /v1/stats/* e /v1/incidents/* requerem sessão de admin (cookie JWT). Para automação sem UI, usar /api/error-monitoring/recent-errors com api_key.