Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fe045d314 | ||
|
|
1181093739 | ||
|
|
2b8976551f | ||
|
|
8bb129ac77 | ||
|
|
f19ff03dd6 | ||
|
|
47f77e85de |
No files matched your search
@@ -0,0 +1,29 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Deploy: nunca sobrescrever `.env` de produção (BIT-25005)
|
||||
|
||||
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
|
||||
|
||||
## Proibido em scripts de deploy e agentes
|
||||
|
||||
| Proibido | Alternativa |
|
||||
|----------|------------|
|
||||
| `cp .env.example .env` sobre `.env` **já existente** em produção | `git pull` / rsync **excluindo** `.env` |
|
||||
| Escrever `root`, `changeme`, `password` ou superuser como credencial de BD em produção | Valores da vault; documentar chaves novas em `.env.example` **vazias** |
|
||||
| Alterar `DB_*` / `DATABASE_*` / `MYSQL_*` no host sem issue, rollback e log | Entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo) antes de aplicar |
|
||||
|
||||
## Regras obrigatórias
|
||||
|
||||
1. Scripts de deploy devem **falhar** (`exit 1`) se um passo tentaria sobrescrever um `.env` existente com conteúdo de exemplo.
|
||||
2. Usar **`rsync --exclude='.env'`** (e paths documentados por serviço) ou `git pull` sem toque no `.env`.
|
||||
3. Pós-deploy: validar que variáveis críticas **não** regressaram a placeholders (`changeme`, `root`, `password`, `secret`, etc.).
|
||||
4. Qualquer alteração a `.env` de produção requer: issue explícita, plano de rollback, e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md`.
|
||||
|
||||
## Quando a regra se aplica
|
||||
|
||||
- Todos os scripts de deploy (webhook, CI, manual).
|
||||
- Agentes que editam, geram ou sugerem alterações a ficheiros `.env`, `.env.example`, `docker-compose.yml` com variáveis de ambiente, ou scripts que copiam/escrevem ficheiros de configuração em produção.
|
||||
|
||||
**Referência:** `docs/DEPLOY_STANDARD.md` §3.1 no meta-repo `paperclip` (regra canónica).
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Known-resolved error patterns for the hub resolve-fixed-patterns endpoint (BIT-25072).
|
||||
* Each entry matches against er_incident_occurrences.message (via LIKE or exact).
|
||||
*
|
||||
* Schema: { messagePatterns: string[], note: string }
|
||||
* messagePatterns: SQL LIKE patterns (use % wildcards). All patterns in an entry are AND-ed.
|
||||
* note: human-readable reason / fix reference (written to er_incident_state_history.change_note).
|
||||
*
|
||||
* Transient infrastructure errors: noise from known-bad infra states that self-resolve.
|
||||
* Fixed code errors: added after the fix is deployed to production.
|
||||
*/
|
||||
export interface FixedPattern {
|
||||
/** Each element becomes: o.message LIKE ? (all AND-ed together for this entry). */
|
||||
messagePatterns: string[];
|
||||
note: string;
|
||||
}
|
||||
|
||||
const patterns: FixedPattern[] = [
|
||||
// Galera/WSREP cluster transient — node not ready
|
||||
{
|
||||
messagePatterns: ['%WSREP has not yet prepared node%'],
|
||||
note: 'Transient: Galera cluster node not ready; infrastructure',
|
||||
},
|
||||
// Google API backendError — transient external
|
||||
{
|
||||
messagePatterns: ['%Internal error encountered%', '%backendError%'],
|
||||
note: 'Transient: Google API 500 backendError; external; no code fix',
|
||||
},
|
||||
// Session write fails when DB is unavailable (cascading)
|
||||
{
|
||||
messagePatterns: ['%session_write_close(): Failed to write session data%'],
|
||||
note: 'Transient: cascades from DB unavailability; no code fix',
|
||||
},
|
||||
// Storage / COMMIT transient
|
||||
{
|
||||
messagePatterns: ['%No such device or address%'],
|
||||
note: 'Transient: storage/infrastructure during COMMIT; retry on next request',
|
||||
},
|
||||
];
|
||||
|
||||
export default patterns;
|
||||
@@ -3,11 +3,13 @@
|
||||
* POST /api/error-monitoring/resolve
|
||||
* POST /api/error-monitoring/bulk-resolve
|
||||
* POST /api/error-monitoring/resolve-by-pattern
|
||||
* POST /api/error-monitoring/resolve-fixed-patterns
|
||||
* POST /api/error-monitoring/purge-resolved
|
||||
*/
|
||||
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { ResultSetHeader, RowDataPacket } from 'mysql2';
|
||||
import fixedPatterns from '../../config/resolveFixedPatterns.js';
|
||||
import {
|
||||
authorizeMutation,
|
||||
changedByRef,
|
||||
@@ -611,10 +613,115 @@ async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply)
|
||||
});
|
||||
}
|
||||
|
||||
async function handleResolveFixedPatterns(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
const body = parseJsonBody(request.body);
|
||||
const auth = await authorizeMutation(request, reply, body, 'errors:triage');
|
||||
if (!auth) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dryRun = Boolean(body.dry_run);
|
||||
const { type, ref } = changedByRef(auth);
|
||||
|
||||
const details: Array<{ note: string; resolved?: number; would_resolve?: number }> = [];
|
||||
let total = 0;
|
||||
|
||||
for (const pattern of fixedPatterns) {
|
||||
if (pattern.messagePatterns.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const likeClauses = pattern.messagePatterns.map(() => 'o.message LIKE ?').join(' AND ');
|
||||
const params: string[] = pattern.messagePatterns;
|
||||
|
||||
const [countRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT COUNT(DISTINCT i.id) AS c
|
||||
FROM er_incidents i
|
||||
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
|
||||
WHERE i.current_state IN ('open','investigating')
|
||||
AND (${likeClauses})`,
|
||||
params,
|
||||
);
|
||||
const n = Number((countRows[0] as { c?: number }).c ?? 0);
|
||||
if (n === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
total += n;
|
||||
details.push({ note: pattern.note, would_resolve: n });
|
||||
continue;
|
||||
}
|
||||
|
||||
const [matchRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT DISTINCT CAST(i.id AS CHAR) AS incident_id,
|
||||
CAST(i.project_id AS CHAR) AS project_id,
|
||||
i.current_state AS current_state
|
||||
FROM er_incidents i
|
||||
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
|
||||
WHERE i.current_state IN ('open','investigating')
|
||||
AND (${likeClauses})`,
|
||||
params,
|
||||
);
|
||||
const targets = (matchRows as Record<string, unknown>[]).map((r) => ({
|
||||
incidentId: String(r.incident_id),
|
||||
projectId: String(r.project_id),
|
||||
currentState: String(r.current_state),
|
||||
}));
|
||||
|
||||
let resolved = 0;
|
||||
const conn = await db.getConnection();
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
for (const row of targets) {
|
||||
const [upd] = await conn.execute<ResultSetHeader>(
|
||||
`UPDATE er_incidents
|
||||
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
|
||||
WHERE id = ? AND current_state IN ('open','investigating')`,
|
||||
[row.incidentId],
|
||||
);
|
||||
if (upd.affectedRows === 0) {
|
||||
continue;
|
||||
}
|
||||
await conn.execute(
|
||||
`INSERT INTO er_incident_state_history
|
||||
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
|
||||
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
|
||||
[row.incidentId, row.projectId, row.currentState, type, ref, pattern.note],
|
||||
);
|
||||
resolved += upd.affectedRows;
|
||||
}
|
||||
await conn.commit();
|
||||
} catch (e) {
|
||||
await conn.rollback();
|
||||
throw e;
|
||||
} finally {
|
||||
conn.release();
|
||||
}
|
||||
|
||||
total += resolved;
|
||||
details.push({ note: pattern.note, resolved });
|
||||
}
|
||||
|
||||
if (!dryRun) {
|
||||
await auditMutation(request.server, request, auth, 'error_monitoring.resolve_fixed_patterns', 'batch', {
|
||||
resolved: total,
|
||||
pattern_count: fixedPatterns.length,
|
||||
});
|
||||
}
|
||||
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: dryRun ? `Would resolve ${total} incidents` : `Resolved ${total} incidents`,
|
||||
data: { total, dry_run: dryRun, details },
|
||||
});
|
||||
}
|
||||
|
||||
export default async function errorMonitoringMutationsRoutes(app: FastifyInstance): Promise<void> {
|
||||
const rl = { config: { rateLimit: app.rateLimits.mutation } };
|
||||
app.post('/api/error-monitoring/resolve', rl, handleResolve);
|
||||
app.post('/api/error-monitoring/bulk-resolve', rl, handleBulkResolve);
|
||||
app.post('/api/error-monitoring/resolve-by-pattern', rl, handleResolveByPattern);
|
||||
app.post('/api/error-monitoring/resolve-fixed-patterns', rl, handleResolveFixedPatterns);
|
||||
app.post('/api/error-monitoring/purge-resolved', rl, handlePurgeResolved);
|
||||
}
|
||||
@@ -9,10 +9,20 @@ Stack versionada em [`docker-compose.yml`](../docker-compose.yml) na raiz deste
|
||||
- Docker Engine 24+ e Docker Compose v2 (plugin `docker compose`), ou Podman Compose compatível.
|
||||
- Portas livres no host (por omissão): **3306** → MariaDB, **3041** → ingest API, **3040** → admin UI. Ajustáveis em `.env` (`ER_PUBLISH_*`).
|
||||
|
||||
## Preservação de `.env` em runtime (BIT-25005)
|
||||
|
||||
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
|
||||
|
||||
- **Nunca** executar `cp .env.example .env` sobre um `.env` **já existente** em produção ou staging.
|
||||
- O `cp` abaixo aplica-se **apenas** à configuração inicial num servidor novo onde não existe ainda `.env`.
|
||||
- Em redeploys: `git pull` apenas; o `.env` existente **não é tocado**.
|
||||
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
|
||||
|
||||
## Arranque reproduzível (qualquer ambiente)
|
||||
|
||||
```bash
|
||||
cd /path/to/errors.bitreport.pt # raiz do clone (ver inventário em docs/ENVIRONMENTS.md)
|
||||
# APENAS para configuração inicial — NÃO executar se já existir .env em produção (BIT-25005)
|
||||
cp .env.example .env
|
||||
# Editar .env: definir palavras-passe fortes antes de produção
|
||||
docker compose up --build -d
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
|
||||
Deploy nativo da stack na **raiz do repositório `errors.bitreport.pt`** num contentor **LXC** (Debian 12 ou Ubuntu 24.04 LTS, alinhado com o resto da infra BitReport): **MariaDB 10.11+** (ou MySQL 8+), **Node.js 20+**, **systemd** para **ingest-api**, **admin-ui**, **collector-worker**, env em **`/etc/error-reporting/env`**, proxy TLS opcional com **nginx**.
|
||||
|
||||
## Preservação de `.env` em runtime (BIT-25005)
|
||||
|
||||
> Norma canónica: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
|
||||
|
||||
- **Nunca** sobrescrever `/etc/error-reporting/env` (ou `.env` no clone) com conteúdo de exemplo num servidor de produção já configurado.
|
||||
- Ficheiro de env em `/etc/error-reporting/env` é **fora do Git** — nunca incluir no repositório.
|
||||
- Alterações a `ER_MYSQL_*` requerem issue explícita, plano de rollback e entrada em `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo).
|
||||
- Credenciais de placeholder (`CHANGE_ME_STRONG`, `changeme`) são proibidas em produção.
|
||||
|
||||
Comparação com Compose: variáveis e ordem de migrações espelham [`bitreport-error-reporting-compose-proxmox.md`](./bitreport-error-reporting-compose-proxmox.md) e [`docker-compose.yml`](../docker-compose.yml).
|
||||
|
||||
## Redis
|
||||
|
||||
Reference in new issue
Block a user