Point the Flexit runbook bullet in RUNBOOK_TRIAGE to BIT-903 and ERRCLUSTER:e83a5ee5e95d (§5.2 of RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) so triage agents land on the documented er-cli and host playbook. Paperclip-Task: 7bb8299c-f6e2-41a3-9ae8-b6966ee9713f Made-with: Cursor
262 lines
11 KiB
Markdown
262 lines
11 KiB
Markdown
# 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](HTTP_CONTRACTS.md) (contratos + curl), [RUNBOOK_OPERATIONS.md](RUNBOOK_OPERATIONS.md) (5 cenários CLI), [RUNBOOK_INGEST_DEBUG.md](RUNBOOK_INGEST_DEBUG.md) (ingest 401/429/fingerprint), [RUNBOOK_REPORTER_GOOGLE_TLS.md](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-909](/BIT/issues/BIT-909) / [BIT-938](/BIT/issues/BIT-938) (503), [BIT-912](/BIT/issues/BIT-912) / [BIT-916](/BIT/issues/BIT-916) (500); DNS `oauth2` + `import_margin` em `wdmi-store` — §5.11 / [BIT-921](/BIT/issues/BIT-921); CRM `import_margin` cURL 35 em `sheets.googleapis.com` — §5.12 / [BIT-947](/BIT/issues/BIT-947)), [RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md](RUNBOOK_REPORTER_WDMI_FLEXIT_XML.md) (`simplexml_load_file` / Flexit Importer no **reporter** PHP; p.ex. [BIT-903](/BIT/issues/BIT-903) — `ERRCLUSTER:e83a5ee5e95d` / §5.2), [RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md](RUNBOOK_REPORTER_WDMI_SIMPLEXLS_AUFERMA.md) (`SimpleXLS` / `_auferma.php` / `Uninitialized string offset` no **reporter** `wdmi-store`), [RUNBOOK_REPORTER_WDMI_FEED_UPLOAD.md](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](RUNBOOK_REPORTER_WDMI_CACHE_MKDIR.md) (Importer `CacheFilesystem` / `mkdir(): File exists` no **reporter** `wdmi-store`), [RUNBOOK_REPORTER_WDMI_VISIOTECH_STRLEN.md](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](RUNBOOK_REPORTER_CRM_ERRORMONITORING_VIEW.md) (CRM `View.php` / `@errormonitoring/dashboard` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_PROCESSMANAGER_VIEW.md](RUNBOOK_REPORTER_CRM_PROCESSMANAGER_VIEW.md) (CRM `View.php` / `@processmanager/dashboard` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md](RUNBOOK_REPORTER_CRM_LOGGER_MKDIR.md) (CRM `Logger.php` / `mkdir(): Permission denied` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_AUTH_PASS_RESET_BASIC.md](RUNBOOK_REPORTER_CRM_AUTH_PASS_RESET_BASIC.md) (CRM `layouts/auth.php` / password reset basic / `Closure` com layout aninhado no **reporter** PHP; [BIT-935](/BIT/issues/BIT-935)), [RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md](RUNBOOK_REPORTER_CRM_VALIDATE_EMAIL_NULL.md) (CRM `Validate::email` / argumento `string` vs `null` no POST de login — `AuthController::handleLogin`; [BIT-941](/BIT/issues/BIT-941)), [RUNBOOK_REPORTER_CRM_VENDOR_CLASSLIST.md](RUNBOOK_REPORTER_CRM_VENDOR_CLASSLIST.md) (CRM `vendor.*.js` / `classList` em nó nulo no **reporter** front-end; [BIT-936](/BIT/issues/BIT-936)), [RUNBOOK_REPORTER_CRM_TASKS_DUE_TIME.md](RUNBOOK_REPORTER_CRM_TASKS_DUE_TIME.md) (CRM `crm_tasks.due_time` / string vazia vs `NULL` no **reporter** PHP), [RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md](RUNBOOK_REPORTER_CRM_SQL_LIMIT_QUOTED_NUMERIC.md) (CRM SQL 1064 próximo a `'10'` / `LIMIT`–`OFFSET` quotados ou binds incorrectos no **reporter** PHP; [BIT-937](/BIT/issues/BIT-937) / [BIT-952](/BIT/issues/BIT-952)), [RUNBOOK_REPORTER_CRM_DATABASE_MEMORY.md](RUNBOOK_REPORTER_CRM_DATABASE_MEMORY.md) (CRM `DatabaseManager.php` / esgotamento de `memory_limit` no **reporter** PHP), [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md).
|
||
|
||
---
|
||
|
||
## Variáveis de ambiente necessárias
|
||
|
||
```bash
|
||
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
|
||
|
||
```bash
|
||
./scripts/er-cli.sh list-open
|
||
```
|
||
|
||
Filtros opcionais:
|
||
|
||
```bash
|
||
./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
|
||
|
||
```bash
|
||
# 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
|
||
|
||
```bash
|
||
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
|
||
|
||
```bash
|
||
./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:
|
||
|
||
```json
|
||
{
|
||
"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:**
|
||
|
||
```bash
|
||
# 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)
|
||
|
||
```bash
|
||
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:**
|
||
|
||
```bash
|
||
# 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):
|
||
|
||
```json
|
||
{ "success": true, "message": "Dry run", "data": { "dry_run": true, "would_delete": 42 } }
|
||
```
|
||
|
||
Saída esperada (execução real):
|
||
|
||
```json
|
||
{ "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:
|
||
|
||
```bash
|
||
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)
|
||
|
||
```bash
|
||
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)
|
||
|
||
```bash
|
||
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
|
||
|
||
```bash
|
||
# 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`.
|