~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Backups: a snapshot of the data directory, held to what was answered

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:durability/snapshots
harness/checks/backup.mjsnew+116−0
@@ -0,0 +1,116 @@
// Backups (spec/DURABILITY.md, "Backups"): a copy of the data directory
// taken at one instant while the server writes, which a filesystem or
// volume snapshot takes. SIGSTOP freezes the server between two of its
// system calls, as a snapshot freezes its files; the copy is made then, and
// a second server started on it must hold every write answered before, and
// of the rest a prefix, each whole.
import { spawn } from 'node:child_process'
import { cpSync, mkdtempSync, openSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { command } from '../lib/args.mjs'
import { COLLECTIONS, below, goodRecord, pick } from '../lib/random.mjs'
import { cand, dataDir, freePort, ref, server, wait } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf, nextBatch, noteCommit, noteWrite, tokenOf } from '../lib/state.mjs'
import { xrpc, xrpcHttp } from '../lib/xrpc.mjs'
/// The puts in a run, one after another.
const PUTS = 8
/// The variables the copy's server is started without: it exports
/// nothing, serves no metrics, writes no mail, and its guard keeps it from
/// the harness's services (spec/PROXY.md); with no crawlers too, nothing it
/// does reaches what the run checks.
const APART = ['PDS_METRICS_PORT', 'OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_HEADERS', 'PDS_DEV_MAIL_DIR', 'PDS_DISABLE_SSRF_PROTECTION']
const broke = (what, request, want, got) => differ(`a server started on a snapshot: ${what}`, request, want, got, 'spec/DURABILITY.md, "Backups"')
/// A second server on `dir`, on a port of its own; answers it once it
/// answers, with its `url` and `stop()`.
async function startOn(dir, errPath) {
const port = await freePort()
const env = { ...process.env, ...server.env, PDS_PORT: String(port), PDS_DATA_DIR: dir, PDS_CRAWLERS: '' }
for (const k of APART) delete env[k]
const proc = spawn(command[0], command.slice(1), { env, stdio: ['ignore', 'ignore', openSync(errPath, 'w')] })
let exited = null
proc.on('exit', (code, signal) => (exited = { code, signal }))
const stop = () => new Promise((ok) => (exited ? ok() : (proc.once('exit', ok), proc.kill('SIGKILL'))))
const url = `http://127.0.0.1:${port}`
for (let i = 0; i < 300 && !exited; i++) {
if (await fetch(`${url}/xrpc/com.atproto.server.describeServer`).then((r) => r.ok, () => false)) return { url, stop }
await wait(100)
}
await stop()
return broke('start', { data: 'a copy taken while it was stopped' }, 'it serves', { exited, stderr: readFileSync(errPath, 'utf8').slice(-400) })
}
/// A run of puts to one account; the server stopped once some are
/// answered, its data directory copied, and let go on; then the copy held
/// to what was answered before the stop, and the puts made on the
/// reference too, so that the repositories still agree.
export async function snapshot() {
const acct = pick(accounts)
const did = didOf(cand, acct)
const collection = pick(COLLECTIONS)
const batch = nextBatch()
const puts = Array.from({ length: PUTS }, (_, i) => ({ rkey: `snap${batch}-${i}`, record: { ...goodRecord(collection), batch } }))
const head = (await xrpcHttp(cand, 'com.atproto.sync.getLatestCommit', { params: { did } })).body?.cid
const dir = mkdtempSync(join(tmpdir(), 'pds-snapshot-'))
const copy = join(dir, 'data')
let answered = 0
let before = null
const stop = () => {
process.kill(server.proc.pid, 'SIGSTOP')
before = answered
cpSync(dataDir, copy, { recursive: true })
process.kill(server.proc.pid, 'SIGCONT')
}
// Stopped once `stopAfter` are answered, with the next on its way.
const stopAfter = 1 + below(PUTS - 2)
let stopped = null
for (const p of puts) {
const res = xrpcHttp(cand, 'com.atproto.repo.putRecord', { body: { repo: did, collection, rkey: p.rkey, record: p.record }, token: tokenOf(cand, acct) })
if (answered === stopAfter) stopped = new Promise((ok) => setImmediate(ok)).then(stop)
p.res = await res
if (p.res.status !== 200) await differ('putRecord, in a run a snapshot is taken during', { rkey: p.rkey }, 'the record put', p.res.body)
answered += 1
}
await stopped
const request = { account: `<did:${acct.n}>`, puts: PUTS, answeredBeforeTheCopy: before }
const other = await startOn(copy, join(dir, 'server.err'))
const fail = async (...args) => {
await other.stop()
await broke(...args)
}
// Each put in the copy whole, as answered; those in it a prefix of the
// run; every one answered before the copy among them.
let held = 0
for (const [i, p] of puts.entries()) {
const got = await xrpcHttp({ url: other.url }, 'com.atproto.repo.getRecord', { params: { repo: did, collection, rkey: p.rkey } })
const there = got.status === 200
if (there && got.body.cid !== p.res.body.cid) await fail('getRecord', { ...request, rkey: p.rkey }, { cid: p.res.body.cid }, got.body)
if (there && held !== i) await fail('getRecord', { ...request, rkey: p.rkey }, `not there: put ${held} is not`, got.body)
if (!there && i < before) await fail('getRecord', { ...request, rkey: p.rkey }, 'the put answered before the copy', got.body)
if (there) held += 1
}
const latest = await xrpcHttp({ url: other.url }, 'com.atproto.sync.getLatestCommit', { params: { did } })
const want = held ? puts[held - 1].res.body.commit.cid : head
if (latest.body?.cid !== want) await fail('getLatestCommit', request, { cid: want, after: `${held} puts` }, latest.body)
const session = await xrpcHttp({ url: other.url }, 'com.atproto.server.getSession', { token: tokenOf(cand, acct) })
if (session.status !== 200) await fail('getSession with a token given before', request, 'the session', session.body)
await other.stop()
rmSync(dir, { recursive: true, force: true })
count('snapshot taken while writing', true)
// The run on the reference too, and noted, as every put is.
for (const p of puts) {
const a = await xrpc(ref, 'com.atproto.repo.putRecord', { body: { repo: acct.handle, collection, rkey: p.rkey, record: p.record }, token: acct })
if (a.status !== 200 || a.body.cid !== p.res.body.cid) await differ('putRecord, in a run a snapshot is taken during', { rkey: p.rkey }, { cid: a.body?.cid }, { cid: p.res.body.cid })
noteWrite(acct, collection, p.rkey, a)
noteCommit(ref, acct, a)
noteCommit(cand, acct, p.res)
}
}
harness/compare.mjs+7−2
@@ -80,6 +80,7 @@ import { checkCommands } from './checks/commands.mjs'
import { blobRecord, getBlob, listBlobs, uploadBlob } from './checks/blobs.mjs'
import { appPasswordEmail, confirmEmail, emailFactor, passwordReset, requestEmailConfirmation, requestEmailUpdate, updateEmail } from './checks/email.mjs'
import { crash, crashes } from './checks/crashes.mjs'
import { snapshot } from './checks/backup.mjs'
import { checkCrawls, getBlocks, getGoneBlocks, getRepoStatus, listRepos, noCrawlsYet, syncGetRecord } from './checks/federation.mjs'
import { startFirehose } from './checks/firehose.mjs'
import { handleRace, recommendedCredentials, resolveHandle, updateHandle, updateHandleNoToken, updateHandleRefused, wellKnownHandle } from './checks/identity.mjs'
@@ -194,8 +195,12 @@ for (run.step = 1; run.step <= STEPS; run.step++) {
break
}
}
if (CRASH_EVERY && run.step % CRASH_EVERY === 0) await crash()
else if (run.step % CHECK_EVERY === 0) await checkRepos()
if (CRASH_EVERY && run.step % CRASH_EVERY === 0) {
// Every second crash, a snapshot of the data directory taken first,
// while it writes (spec/DURABILITY.md, "Backups").
if (run.step % (2 * CRASH_EVERY) === 0) await snapshot()
await crash()
} else if (run.step % CHECK_EVERY === 0) await checkRepos()
await outage(run.step)
if (run.step % 100 === 0) console.error(`${run.step} steps agree`)
}
spec/DURABILITY.md+42−0
@@ -87,3 +87,45 @@ held only for `PDS_BLOB_TTL_SECS` (`LIMITS.md`), and a client that lost one
uploads it again. The server's own tests model a power cut as the loss of
every file not synced, and check that a referenced blob survives wherever
its commit does.
## Backups
A copy of `PDS_DATA_DIR` taken at one instant while the server runs, as a
filesystem or volume snapshot takes it, is a data directory the server
starts on. A snapshot that holds what the process had handed to the
operating system is as the disk after a kill; one of the disk alone, as a
block device's, is as the disk after a power cut. Started on the copy, the
server holds what this page says survives the one or the other at that
instant: every write answered before it, and every account `createAccount`
answered; of a write under way, all or nothing; and of each account's
writes after the last answered, those in the copy are the first of them in
order. The sessions it gave out before still work on it. The copy holds the
secrets the server signs and seals its tokens with, which it keeps in the
directory, and none of what is in its environment: the PLC rotation key
(`ACCOUNTS.md`) and the admin's password are kept apart from it.
A copy made file by file over a span of time, as `cp` or `rsync` of a
running server's directory makes it, is not such a copy, and nothing is
said of it. A server stopped first, with SIGTERM or SIGKILL, may be copied
any way.
A server started on a copy is a rollback, and does nothing of its own
about it, as the reference does nothing for a database brought back.
What was written after the copy is lost. The firehose numbers its next
events from the copy's last `seq`, so `seq`s it sent before are sent again
for other events, and those who read it, relays and AppViews, hold commits
and a cursor the server no longer has. Handle changes after the copy stay
at the PLC directory.
With `--crash-every N`, before every second kill, the harness puts a run of
eight records to one account, one after another. Once some are answered it
stops the server with SIGSTOP, which freezes it between two of its system
calls as a snapshot freezes its files, with the next put on its way; it
copies the data directory and lets the server go on with SIGCONT. A second
server, started on the copy on a port of its own, with no crawlers, no
metrics or traces, and SSRF protection on (`PROXY.md`), must answer every
put answered before the stop; of the rest, a prefix of the run, each record
as the put answered it; the latest commit, the last put's in it; and
`getSession` with the account's token. What a block device's snapshot
holds is what a power cut leaves, which the server's own tests check
(above).
README.md+12−0
@@ -262,6 +262,15 @@ says the rest):
`PDS_DISABLE_SSRF_PROTECTION` are for development, never for a server on
the network.
Back the server up by snapshots of its volume or filesystem, taken while
it runs: a snapshot is a data directory the server starts on, holding
every write answered before it (`spec/DURABILITY.md`, "Backups"). A `cp` or
`rsync` of a running server's directory is not a backup; stop the server
first, or snapshot. Keep the environment apart, and safe: the data
directory holds no PLC rotation key. Starting on a backup rolls the server
back: what was written after is lost, and relays and AppViews hold commits
and firehose `seq`s it no longer has.
## Checks
Besides the harness and the tests, the source itself is held to these, the
@@ -298,6 +307,9 @@ cd harness && node compare.mjs --upgrade-write -- ../../pds-release/target/relea
## Known gaps
- A server started on a backup does nothing about the rollback: it numbers
its firehose events again from the backup's last, and tells no relay or
AppView to sync its accounts again.
- Accounts are made with `createAccount`, with handles under the server's
own domains.
- Of OAuth, no account pages (`/account`), or sign-up from the