Files
MikrotikManager/backend/src/services/system-database-backup.ts
T

380 lines
24 KiB
TypeScript

import { randomUUID } from "node:crypto"
import { appendEvent } from "../modules/events/service/events-service.js"
import { AsyncLocalStorage } from "node:async_hooks"
import pg from "pg"
import { readRestoreOwnerConnection, restoreDatabaseToolEnvironment, runPrivateDatabaseDump, validatePrivateRestoreConnection, withPrivateRestoreService } from "./database-dump-connection.js"
import { boundedDatabaseCommand } from "./bounded-database-dump.js"
import { DATABASE_CONTROL_DUMP_EXCLUDE_SCHEMA_ARG } from "./database-control-archive-boundary.js"
import { lstat, open } from "node:fs/promises"
import { databaseSchemaReadiness as schemaReadiness, sharedDatabaseGate } from "./shared-database-gate.js"
import { assertDatabaseRestoreAllowed } from "./config-mutation-policy.js"
import { accessGeneration, invalidateMcpAccess, mcpStateDirectory, privateFingerprinter } from "../modules/mcp/security.js"
import type { RestoreDataJournalRecord } from "./database-maintenance-resolution.js"
import type { RestoreCheckpoint } from "./database-restore-checkpoint.js"
import { executeMcpDatabaseMaintenance } from "../modules/mcp/database-maintenance.js"
import { applySqlMigrations } from "../db/migrate.js"
import { spawn } from "node:child_process"
import { chmod, mkdir, rm, writeFile } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { executeSystemDatabaseRestore, validateSystemDatabaseRestoreArchive, type SystemDatabaseRestoreOutcome } from "./system-database-restore-execution.js"
import { env } from "../config.js"
import { assertRuntimeDatabaseActivationCurrent, pool, readRuntimeDatabaseWriterHead } from "../db/index.js"
import { withSystemDatabaseOperationLock, type DatabaseOperationLockClient } from "../db/operation-lock.js"
import {
assertDatabaseRestoreQuarantineOpen, beginDatabaseRestoreQuarantine,
completeDatabaseRestoreQuarantine, databaseRestoreQuarantineEnabled,
type RestoreJournalHead,
} from "../db/database-restore-quarantine.js"
import { executeDatabaseOperation, type DatabaseOperationWarnings } from "./system-database-operation.js"
import { restartSchedulerAfterDatabaseOperation, stopSchedulerForDatabaseOperation } from "./scheduler.js"
import { pauseRipeBackgroundWork, resumeRipeBackgroundWork } from "./traffic-flow-ripe.js"
import { invalidateSystemDatabaseCaches } from "./system-database-cache.js"
import { restorePartitionedDatabase } from "./system-database-partition-restore.js"
import { databaseRestoreOwnerCheckSql, withDatabaseRestoreTarget } from "./database-restore-target.js"
import {
restartTrafficFlowListenerAfterDatabaseOperation,
stopTrafficFlowListenerForDatabaseOperation,
} from "./traffic-flow-ingest.js"
const backupAdmission = new AsyncLocalStorage<{ active: boolean }>()
const restoreAdmission = new AsyncLocalStorage<{ active: boolean }>()
// The shared readiness latch also refuses new request/worker admission after
// unconfirmed replacement; startup recovery supplies the cross-process guard.
/** Acquire before worker/config locks so admitted requests can drain without a lock inversion. */
export function withSystemDatabaseBackupAdmission<T>(work: () => Promise<T>) {
return sharedDatabaseGate.exclusive(async () => {
const admission = { active: true }
try { return await backupAdmission.run(admission, work) } finally { admission.active = false }
})
}
/** Terminal MCP claim and restore share one exclusive admission from first SQL. */
export function withSystemDatabaseRestoreAdmission<T>(work: () => Promise<T>) {
return sharedDatabaseGate.exclusive(async () => {
const admission = { active: true }
try { return await restoreAdmission.run(admission, work) } finally { admission.active = false }
})
}
function fmtTimestamp(date = new Date()): string {
const pad = (n: number) => String(n).padStart(2, "0")
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}_${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}`
}
function spawnCollected(command: string, args: string[], opts?: { stdin?: Buffer }): Promise<Buffer> {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
env: { ...process.env, DATABASE_URL: env.DATABASE_URL },
stdio: ["pipe", "pipe", "pipe"],
})
const chunks: Buffer[] = []
let err = ""
child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk))
child.stderr.on("data", (chunk: Buffer) => {
err += chunk.toString("utf8")
})
child.on("error", () => reject(new Error(`Утилита ${command} недоступна; проверьте установку PostgreSQL client tools и PATH`)))
child.on("close", (code) => {
if (code !== 0) {
reject(new Error(err.trim().replaceAll(env.DATABASE_URL, "[DATABASE_URL]") || `${command} завершился с кодом ${code}`))
return
}
resolve(Buffer.concat(chunks))
})
if (opts?.stdin) child.stdin.end(opts.stdin)
else child.stdin.end()
})
}
async function runRestoreTool(command: string, args: string[], env: NodeJS.ProcessEnv): Promise<Buffer> {
try {
return await boundedDatabaseCommand(command, args, {
env, timeoutMs: command === "psql" ? 600_000 : 120_000,
})
} catch {
throw new Error(`Команда восстановления PostgreSQL ${command} не выполнена`)
}
}
type PendingRestoreCheckpoint = Extract<RestoreCheckpoint, { status: "pending" }>
async function withDatabaseOperation<T extends object>(fn: (client: DatabaseOperationLockClient, discard: () => void, targetCheckSql?: string, journalHead?: RestoreJournalHead | null, checkpoint?: PendingRestoreCheckpoint) => Promise<T>, admittedKind?: "backup" | "restore"): Promise<T & DatabaseOperationWarnings> {
const execute = () => withSystemDatabaseOperationLock(() => pool.connect(), async (client, discard) => {
const run = (targetCheckSql?: string, journalHead?: RestoreJournalHead | null, checkpoint?: PendingRestoreCheckpoint) => executeDatabaseOperation(() => fn(client, discard, targetCheckSql, journalHead, checkpoint), {
stopListener: stopTrafficFlowListenerForDatabaseOperation,
beforeRestart: schemaReadiness.assertReady,
stopScheduler: async () => {
await stopSchedulerForDatabaseOperation()
await pauseRipeBackgroundWork()
},
startListener: restartTrafficFlowListenerAfterDatabaseOperation,
startScheduler: async () => {
resumeRipeBackgroundWork()
await restartSchedulerAfterDatabaseOperation()
},
})
let journalHead: RestoreJournalHead | null | undefined
let pending: PendingRestoreCheckpoint | undefined
if (databaseRestoreQuarantineEnabled()) {
await assertDatabaseRestoreQuarantineOpen(client)
const { assertDatabaseRestoreJournalCurrent } = await import("./database-maintenance-startup.js")
journalHead = await assertDatabaseRestoreJournalCurrent(client, mcpStateDirectory())
}
if (process.env.DATABASE_RESTORE_CHECKPOINT_FILE !== undefined) {
const { DatabaseRestoreCheckpointRefused, readDatabaseRestoreCheckpoint, restoreJournalHeadsEqual, restoreWriterHeadIsCurrent } = await import("./database-restore-checkpoint.js")
const checkpoint = await readDatabaseRestoreCheckpoint(mcpStateDirectory(), env.DATABASE_URL)
if (!checkpoint || !restoreJournalHeadsEqual(checkpoint.head, journalHead) ||
checkpoint.status !== (admittedKind === "restore" ? "pending" : "sealed") ||
!restoreWriterHeadIsCurrent(checkpoint.writerHead, await readRuntimeDatabaseWriterHead(client))) throw new DatabaseRestoreCheckpointRefused()
if (checkpoint.status === "pending") pending = checkpoint
}
if (process.env.DATABASE_RUNTIME_ACTIVATION_DIRECTORY !== undefined) assertRuntimeDatabaseActivationCurrent()
return admittedKind === "restore" ? withDatabaseRestoreTarget(client, discard, targetCheckSql => run(targetCheckSql, journalHead, pending)) : run()
})
const admission = admittedKind === "backup" ? backupAdmission.getStore() : admittedKind === "restore" ? restoreAdmission.getStore() : undefined
return admission?.active ? sharedDatabaseGate.withinAdmission(execute) : sharedDatabaseGate.exclusive(execute)
}
export async function exportSystemDatabaseBackup(options?: { signal?: AbortSignal; authorize?: () => Promise<void> }): Promise<{ filename: string; buffer: Buffer } & DatabaseOperationWarnings> {
return await withDatabaseOperation(async (client, discard) => {
await options?.authorize?.()
let buffer: Buffer
const archivePasswordFile = process.env.DATABASE_ARCHIVE_PASSWORD_FILE
if (process.env.DATABASE_RUNTIME_REQUEST_FILE !== undefined || archivePasswordFile !== undefined) {
const { exportProtectedDatabaseSnapshot } = await import("./database-protected-archive.js")
buffer = await exportProtectedDatabaseSnapshot(client, discard, archivePasswordFile, options)
} else if (options?.authorize) {
buffer = await runPrivateDatabaseDump(env.DATABASE_URL, options)
} else {
buffer = await spawnCollected("pg_dump", ["-Fc", DATABASE_CONTROL_DUMP_EXCLUDE_SCHEMA_ARG, env.DATABASE_URL])
}
await options?.authorize?.()
return {
filename: `mikrotik-manager_${fmtTimestamp()}.dump`,
buffer,
}
}, "backup")
}
/** REST and MCP share the same export event; event failure never erases a completed dump. */
export async function exportSystemDatabaseBackupWithEvent(options?: Parameters<typeof exportSystemDatabaseBackup>[0], dependencies = { exportBackup: exportSystemDatabaseBackup, event: appendEvent }) {
const result = await dependencies.exportBackup(options)
let eventError: string | undefined
try {
await dependencies.event({ level: "info", eventType: "system.database.backup", sourceModule: "system", title: "Создан бэкап базы приложения", message: result.filename,
entityType: "system_database", entityId: result.filename, payload: { filename: result.filename, sizeBytes: result.buffer.length } })
} catch { eventError = "Не удалось записать событие резервного копирования" }
return { ...result, ...(eventError ? { eventError } : {}) }
}
export async function restoreSystemDatabaseBackup(buffer: Buffer, options?: { beforeRestore?: () => Promise<void> }): Promise<SystemDatabaseRestoreOutcome & DatabaseOperationWarnings> {
validateSystemDatabaseRestoreArchive(buffer)
const quarantine = databaseRestoreQuarantineEnabled()
const dataVerification = process.env.DATABASE_RESTORE_ARCHIVE_SHA256 !== undefined || process.env.DATABASE_RESTORE_DATA_SHA256 !== undefined
? await import("../db/database-restore-data.js") : undefined
const expectedData = dataVerification?.approvedRestoreDataDigest(buffer, quarantine)
if (quarantine && !env.DATABASE_RESTORE_URL_FILE) throw new Error("Для карантина восстановления требуется подключение владельца БД")
if (!env.DATABASE_RESTORE_URL_FILE) validatePrivateRestoreConnection(env.DATABASE_URL)
await assertSystemDatabaseRestoreTools()
return await withDatabaseOperation(async (_client, _discard, targetCheckSql, previousHead, checkpoint) => {
if (!targetCheckSql) throw new Error("Не подтверждено подключение к базе для восстановления")
if ((expectedData && previousHead === undefined) || (!expectedData && previousHead)) {
throw new Error("Для восстановления требуется согласованная настройка защищённого журнала PostgreSQL")
}
if (checkpoint && (expectedData?.archiveSha256 !== checkpoint.archiveSha256 || expectedData?.dataSha256 !== checkpoint.dataSha256)) {
const { DatabaseRestoreCheckpointRefused } = await import("./database-restore-checkpoint.js")
throw new DatabaseRestoreCheckpointRefused()
}
let consumedCheckpoint: Extract<RestoreCheckpoint, { status: "consumed" }> | undefined
const assertCurrentCheckpoint = async () => {
if (!checkpoint) return
const { DatabaseRestoreCheckpointRefused, readDatabaseRestoreCheckpoint } = await import("./database-restore-checkpoint.js")
const current = await readDatabaseRestoreCheckpoint(mcpStateDirectory(), env.DATABASE_URL)
if (JSON.stringify(current) !== JSON.stringify(consumedCheckpoint ?? checkpoint)) throw new DatabaseRestoreCheckpointRefused()
}
await assertDatabaseRestoreAllowed()
const owner = env.DATABASE_RESTORE_URL_FILE ? await readRestoreOwnerConnection(env.DATABASE_RESTORE_URL_FILE) : undefined
const connection = owner?.connection ?? env.DATABASE_URL
const restoreCheckSql = owner ? `${targetCheckSql}\n${databaseRestoreOwnerCheckSql(owner.owner)}` : targetCheckSql
const journalProof = expectedData ? await (async () => {
const { RESTORE_DATA_JOURNAL_DOMAIN, runtimeDatabaseTargetSha256 } = await import("./database-maintenance-resolution.js")
const { databaseRestoreJournalHead, readMaintenanceRecoveryFacts } = await import("./database-maintenance-startup.js")
const { constants } = await import("node:fs")
const activationSha256 = process.env.DATABASE_RUNTIME_ACTIVATION_SHA256 ?? null
if (activationSha256 !== null && !/^[a-f0-9]{64}$/.test(activationSha256)) {
throw new Error("Поколение PostgreSQL для журнала восстановления не подтверждено")
}
return {
format: RESTORE_DATA_JOURNAL_DOMAIN,
openFlags: constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0),
binding: { ...expectedData, runtimeTargetSha256: runtimeDatabaseTargetSha256(env.DATABASE_URL), activationSha256 },
sign: await privateFingerprinter(RESTORE_DATA_JOURNAL_DOMAIN),
readMaintenanceRecoveryFacts,
databaseRestoreJournalHead,
} as const
})() : undefined
await options?.beforeRestore?.()
await assertCurrentCheckpoint()
if (checkpoint) {
const { consumeRestoreCheckpoint } = await import("./database-restore-checkpoint-claim.js")
consumedCheckpoint = await consumeRestoreCheckpoint(checkpoint)
await assertCurrentCheckpoint()
}
await accessGeneration()
const directory = mcpStateDirectory()
const journalPath = path.join(directory, "database-maintenance.jsonl")
const journal = await open(journalPath, journalProof?.openFlags ?? "a", 0o600)
const assertJournalFile = async () => {
const handle = await journal.stat({ bigint: true })
const current = await lstat(journalPath, { bigint: true })
if (!handle.isFile() || !current.isFile() || handle.nlink !== 1n || current.nlink !== 1n ||
handle.dev !== current.dev || handle.ino !== current.ino) {
throw new Error("Файл журнала восстановления PostgreSQL изменился")
}
}
const operationId = checkpoint?.operationId ?? randomUUID()
let verified = false
let intentHead: RestoreJournalHead | undefined
let appliedHead: RestoreJournalHead | undefined
const syncJournalDirectory = async () => {
if (process.platform === "win32") return
const parent = await open(directory, "r")
try { await parent.sync() } finally { await parent.close() }
}
const record = async (state: RestoreDataJournalRecord["state"]) => {
const at = new Date().toISOString()
let signedLine: Buffer | undefined
if (journalProof) {
if (state !== "intent" && !intentHead) throw new Error("Начало восстановления PostgreSQL не подтверждено")
if (state === "applied" && !verified) throw new Error("Проверка данных PostgreSQL не подтверждена")
await assertJournalFile()
const binding = consumedCheckpoint ? { ...journalProof.binding, claimId: consumedCheckpoint.claimId } : journalProof.binding
const record: RestoreDataJournalRecord = { format: journalProof.format, operationId, state, at, binding }
signedLine = Buffer.from(JSON.stringify({ ...record, mac: journalProof.sign(JSON.stringify(record)) }) + "\n")
await journal.writeFile(signedLine)
} else {
await journal.writeFile(JSON.stringify({ operationId, state, at }) + "\n")
}
await journal.sync()
if (journalProof && state === "intent") await syncJournalDirectory()
if (journalProof && signedLine) {
const { journal: persisted } = await journalProof.readMaintenanceRecoveryFacts(directory)
if (!persisted.subarray(-signedLine.length).equals(signedLine)) {
throw new Error("Запись журнала восстановления PostgreSQL не подтверждена")
}
const expectedPrefix = state === "intent" ? previousHead : intentHead
if (expectedPrefix && (persisted.length !== expectedPrefix.bytes + signedLine.length ||
journalProof.databaseRestoreJournalHead(persisted.subarray(0, expectedPrefix.bytes)).sha256 !== expectedPrefix.sha256)) {
throw new Error("История журнала восстановления PostgreSQL изменилась")
}
await assertJournalFile()
if (state === "intent") intentHead = journalProof.databaseRestoreJournalHead(persisted)
if (state === "applied") appliedHead = journalProof.databaseRestoreJournalHead(persisted)
}
}
const claimedRestoreSql = quarantine ? `${restoreCheckSql}
DO $mm_restore_quarantine$
BEGIN
IF NOT EXISTS (SELECT 1 FROM mmapp_control.database_restore_quarantine WHERE id=1 AND operation_id='${operationId}'::pg_catalog.uuid) THEN
RAISE EXCEPTION 'Restore quarantine is unconfirmed' USING ERRCODE='55000';
END IF;
END $mm_restore_quarantine$;` : restoreCheckSql
const updateQuarantine = async (update: typeof beginDatabaseRestoreQuarantine, expected?: RestoreJournalHead | null, next?: RestoreJournalHead) => {
if (journalProof && (expected === undefined || !next)) throw new Error("Не подтверждена запись журнала восстановления")
const client = new pg.Client({ connectionString: connection, connectionTimeoutMillis: 8_000 })
try {
await client.connect()
await client.query("BEGIN")
await client.query("SET LOCAL lock_timeout='5s'; SET LOCAL statement_timeout='10s'; SET LOCAL synchronous_commit=on")
await client.query(restoreCheckSql)
await update(client, operationId, expected !== undefined && next ? { expected, next } : undefined)
await client.query(restoreCheckSql)
if ((await client.query("COMMIT")).command !== "COMMIT") throw new Error("Commit not acknowledged")
} catch {
throw new Error("Не подтверждена запись карантина восстановления")
} finally { await client.end() }
}
const outcome = await executeMcpDatabaseMaintenance(async () => {
let result: SystemDatabaseRestoreOutcome | undefined
try {
await withPrivateRestoreService(connection, async ({ dsn, env: connectionEnvironment }) => {
result = await executeSystemDatabaseRestore(buffer, dsn, {
allocate: async () => {
const tempDir = path.join(os.tmpdir(), "mmapp-db-restore")
await mkdir(tempDir, { recursive: true, mode: 0o700 })
await chmod(tempDir, 0o700)
return path.join(tempDir, `restore-${randomUUID()}.dump`)
},
write: (file, data) => {
if (dataVerification && expectedData) {
const approved = dataVerification.approvedRestoreDataDigest(data, quarantine)
if (approved.archiveSha256 !== expectedData.archiveSha256 || approved.dataSha256 !== expectedData.dataSha256) {
throw new dataVerification.DatabaseRestoreDataRefused()
}
}
return writeFile(file, data, { mode: 0o600 })
},
run: async args => {
await restorePartitionedDatabase(args[args.length - 1], dsn, {
command: (command, commandArgs) => runRestoreTool(command, commandArgs,
command === "psql" ? connectionEnvironment : restoreDatabaseToolEnvironment()),
beforeTargetReplacement: async () => {
await assertCurrentCheckpoint()
schemaReadiness.beginReplacement()
if (quarantine) await updateQuarantine(beginDatabaseRestoreQuarantine, previousHead, intentHead)
},
targetCheckSql: claimedRestoreSql,
exclusivePartitionWriters: quarantine,
writePublicSchemaPreservingList: process.env.DATABASE_RUNTIME_WRITER_APPROVAL_FILE === undefined ? undefined
: (file, list) => writeFile(file, list, { flag: "wx", mode: 0o600 }),
prepareSql: file => writeFile(file, "", { mode: 0o600 }),
})
},
remove: async file => { await Promise.all([rm(file, { force: true }), rm(`${file}.sql`, { force: true }), rm(`${file}.list`, { force: true })]) },
invalidate: invalidateSystemDatabaseCaches,
})
})
} catch (error) {
if (!result) throw error
const warning = "Не удалось удалить временные параметры подключения к базе"
result.cleanupError = result.cleanupError ? `${result.cleanupError}; ${warning}` : warning
}
if (!result) throw new Error("Восстановление PostgreSQL не подтверждено")
const ownerPool = owner ? new pg.Pool({ connectionString: connection, max: 1, connectionTimeoutMillis: 8_000 }) : undefined
const migrationUnconfirmed = "База восстановлена, но миграции приложения не завершены. Требуется проверка схемы; не повторяйте restore."
try {
try { await applySqlMigrations(ownerPool ?? pool, claimedRestoreSql) }
catch { result.migrationError = migrationUnconfirmed }
if (dataVerification && expectedData && !result.migrationError) {
if (!ownerPool) throw new dataVerification.DatabaseRestoreDataRefused()
await dataVerification.assertRuntimeRestoreData(ownerPool, expectedData.dataSha256, claimedRestoreSql)
assertRuntimeDatabaseActivationCurrent()
verified = true
result.dataVerified = true
}
} finally {
if (ownerPool) try { await ownerPool.end() } catch { result.migrationError ??= migrationUnconfirmed }
}
return result
}, { record, invalidateAccess: async () => {
await invalidateMcpAccess()
if (journalProof) await syncJournalDirectory()
}, close: () => journal.close() })
// Neither uncertain replacement nor unconfirmed external completion may
// release request admission or restart consumers. A persisted claim requires operator inspection.
if (!outcome.migrationError && !outcome.maintenanceError) {
if (checkpoint) return { ...outcome, maintenanceError: "Восстановление подтверждено. Карантин сохранён до публикации внешней контрольной записи PostgreSQL." }
if (quarantine) try { await updateQuarantine(completeDatabaseRestoreQuarantine, intentHead, appliedHead) }
catch { return { ...outcome, maintenanceError: "Не подтверждено снятие карантина восстановления. Требуется сверка базы." } }
schemaReadiness.confirmSchema()
}
return outcome
}, "restore")
}
export async function assertSystemDatabaseRestoreTools() {
await runRestoreTool("pg_restore", ["--version"], restoreDatabaseToolEnvironment())
await runRestoreTool("psql", ["--version"], restoreDatabaseToolEnvironment())
}