Skip to content

Commit 39d4baa

Browse files
Uwe Schwaekeclaude
andcommitted
feat(database): back up, integrity-check and restore SQLite (SPEC-030)
SPEC-030 (cloud-storage#600), part 3 of 3 of SQLite support — the backend is #598, the chart #599. Lightstack now ships for SQLite what an operator gets from pg_dump on PostgreSQL: a consistent online backup, an integrity check, and a documented restore and recovery procedure. CLI (lightstack-migrate), SQLite only — both refuse a PostgreSQL URL and name pg_dump: - backup [<file>] runs VACUUM INTO for a consistent, standalone copy (no -wal/-shm) taken while Lightstack keeps serving. The target is created 0600 before the copy and never overwrites an existing file; the default is <state_path>/backups/lightstack-<UTC timestamp>.db. - check runs PRAGMA integrity_check and exits non-zero listing the problems on a damaged database. It also refuses a file that records no migration version — an empty file passes SQLite's own check, and restoring one would start Lightstack as a fresh install (FR-005a). Restore and retention: - MigrateUp refuses a database written by a newer Lightstack, naming both versions, instead of golang-migrate's opaque "no migration found" (FR-008). An older backup is migrated forward on start. - BackupsDir sits beside db/, not inside it, and is absent from the uninstall purge list, so dataRetentionPolicy: delete keeps backups — they are the operator's (FR-004). Tests and docs: - backup/check are covered on real files (concurrent writer, existing- target refusal, 0600/0750 modes, the wrong-order vs documented restore, the non-Lightstack refusals); the CLI target resolution and the integrity gate over a real golang-migrate schema are unit-tested. - KUBERNETES_DEPLOYMENT.md and DOCKER_DEPLOYMENT.md document backup, restore (delete -wal/-shm first) and recovery for a node debug pod and for Compose; CONFIGURATION.md points at them. A host-testing runbook and contracts live under docs/specs/030-sqlite-backup-restore/. No new modules, no schema change, no migration. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Uwe Schwaeke <uwe.schwaeke@sap.com>
1 parent 4aca4ed commit 39d4baa

24 files changed

Lines changed: 2374 additions & 13 deletions

‎CLAUDE.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,8 @@ if requestedVersion == "" {
486486
- PostgreSQL (unchanged) **or** one SQLite file chosen by the `database.url` scheme (`sqlite:///abs/path`, WAL, `synchronous=FULL`, 0600). One `migrations/` folder read through a per-backend view; SQLite starts at a generated `073_baseline.sqlite`; migration `074_reservation_node` (`volumes`/`snapshots.reserved_by`) on both (028-sqlite-database-layer)
487487
- Helm 3.12+ chart (Go `text/template` + Sprig); JSON Schema **draft-07** (`values.schema.json`); Go 1.27.3 for the one `internal/teardown` change; Markdown docs. (029-sqlite-chart-compose)
488488
- node-local hostPath SQLite directory at `<realMode.hostStoragePath>/db` (`lightstack.db` + `-wal` + `-shm`), **no PVC**. External PostgreSQL unchanged. **No schema change, no migration, no persisted data owned by the chart.** (029-sqlite-chart-compose)
489+
- Go 1.27.3 (module pins `go 1.26`; Constitution requires 1.26+). Markdown docs. (030-sqlite-backup-restore)
490+
- the operator's SQLite database file and a sibling `backups/` directory under the node storage root (`state_path` / `realMode.hostStoragePath`, default `/var/lib/lightstack`). **No schema change, no migration, no persisted data owned by the chart.** PostgreSQL is untouched except the backend-neutral ceiling check. (030-sqlite-backup-restore)
489491

490492
## Recent Changes
491493
- 028-sqlite-database-layer: plan — SQLite as a second backend behind a backend-neutral `internal/database` contract whose method sets mirror pgx's, so the 736 call sites change types only. PostgreSQL passes SQL through untouched; SQLite translates casts, `= ANY($n)`, `FOR UPDATE` and the console expiry, registers `now()`/`gen_random_uuid()`/no-op advisory locks, and converts times, JSON, lists and `[]byte` (a STRICT TEXT column refuses BLOBs). Ten rewrite sites, the same for both backends; `name ~` stays a database match (`REGEXP` on SQLite), as upstream's. Cinder creates reserve a `creating` row and build the backing outside any transaction (+ a per-node startup sweep); Nova gains a binding quota recheck under an advisory lock and answers **403** instead of 413 (with FR-036a's 400s, the two API changes). Probe-verified: deferred read-then-write hits `SQLITE_BUSY_SNAPSHOT` (517) → immediate transactions expected (SPEC-028 plan)

‎cmd/lightstack-migrate/main.go‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package main
22

33
import (
4+
"context"
45
"flag"
56
"fmt"
67
"os"
8+
"path/filepath"
79
"strconv"
10+
"time"
811

912
"github.com/cobaltcore-dev/lightstack/internal/common"
1013
"github.com/cobaltcore-dev/lightstack/internal/database"
@@ -53,6 +56,17 @@ func main() {
5356
// Initialize logging
5457
middleware.InitLogger(&cfg.Logging)
5558

59+
// backup and check work on the database file alone and read no migrations, so they run
60+
// wherever the binary does — a node debug pod included (SPEC-030).
61+
switch command {
62+
case "backup":
63+
handleBackup(cfg.Database.URL, cfg.StatePath)
64+
return
65+
case "check":
66+
handleCheck(cfg.Database.URL)
67+
return
68+
}
69+
5670
// Validate migrations directory
5771
if err := database.ValidateMigrations(*migrationsPath); err != nil {
5872
fmt.Fprintf(os.Stderr, "Migration validation failed: %v\n", err)
@@ -209,6 +223,54 @@ func handleForce(dbURL, migrationsPath string) {
209223
fmt.Printf("✅ Version forced to %d\n", version)
210224
}
211225

226+
// handleBackup takes a consistent copy of the SQLite database while Lightstack keeps serving
227+
// it: to the named file, or by default to <state_path>/backups/lightstack-<UTC time>.db.
228+
func handleBackup(dbURL, statePath string) {
229+
dest, err := resolveBackupDest(flag.Args(), statePath)
230+
if err != nil {
231+
fmt.Fprintf(os.Stderr, "%v\n", err)
232+
os.Exit(1)
233+
}
234+
if err := database.Backup(context.Background(), dbURL, dest); err != nil {
235+
fmt.Fprintf(os.Stderr, "Backup failed: %v\n", err)
236+
os.Exit(1)
237+
}
238+
fmt.Printf("✅ Backup written to %s\n", dest)
239+
}
240+
241+
// resolveBackupDest picks the backup target as an absolute path: the named file, or — when no
242+
// file is given — the default <state_path>/backups/lightstack-<UTC time>.db. More than one
243+
// positional argument is a usage error.
244+
func resolveBackupDest(args []string, statePath string) (string, error) {
245+
if len(args) > 1 {
246+
return "", fmt.Errorf("usage: lightstack-migrate backup [options] [<file>]")
247+
}
248+
dest := ""
249+
if len(args) == 1 {
250+
dest = args[0]
251+
}
252+
if dest == "" {
253+
paths.SetBase(statePath)
254+
dest = paths.BackupPath(time.Now())
255+
}
256+
if abs, err := filepath.Abs(dest); err == nil {
257+
dest = abs
258+
}
259+
return dest, nil
260+
}
261+
262+
// handleCheck runs SQLite's integrity check; it exits non-zero, listing the problems, on a
263+
// damaged database, and on one holding no Lightstack schema. It only reads, so it runs against
264+
// a serving Lightstack too.
265+
func handleCheck(dbURL string) {
266+
version, err := database.IntegrityCheck(context.Background(), dbURL)
267+
if err != nil {
268+
fmt.Fprintf(os.Stderr, "Check failed: %v\n", err)
269+
os.Exit(1)
270+
}
271+
fmt.Printf("✅ Integrity check passed (schema version %d)\n", version)
272+
}
273+
212274
func printUsage() {
213275
fmt.Println("Lightstack Database Migration Tool")
214276
fmt.Println("===========================")
@@ -222,6 +284,13 @@ func printUsage() {
222284
fmt.Println(" goto <version> Migrate to specific version")
223285
fmt.Println(" reset Drop all tables and re-run migrations (DANGEROUS)")
224286
fmt.Println(" force <version> Force migration version (for fixing dirty state)")
287+
fmt.Println(" backup [<file>] Copy the SQLite database while Lightstack runs; never overwrites.")
288+
fmt.Println(" Default file: <state_path>/backups/lightstack-<UTC time>.db")
289+
fmt.Println(" check Check the SQLite database's integrity and schema version;")
290+
fmt.Println(" non-zero if damaged, empty or not a Lightstack database")
291+
fmt.Println()
292+
fmt.Println("backup and check are for SQLite only; for PostgreSQL use pg_dump. Options go before")
293+
fmt.Println("the file: lightstack-migrate backup -config <path> <file>.")
225294
fmt.Println()
226295
fmt.Println("The database is database.url in the configuration file, or LIGHTSTACK_DB_URL when set:")
227296
fmt.Println("postgres://… for PostgreSQL, sqlite:///absolute/path/lightstack.db for SQLite. Both read")
@@ -237,5 +306,7 @@ func printUsage() {
237306
fmt.Println(" lightstack-migrate down")
238307
fmt.Println(" lightstack-migrate goto 5")
239308
fmt.Println(" lightstack-migrate force 7")
309+
fmt.Println(" lightstack-migrate backup")
310+
fmt.Println(" lightstack-migrate check")
240311
fmt.Println()
241312
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package main
2+
3+
import (
4+
"path/filepath"
5+
"strings"
6+
"testing"
7+
8+
"github.com/cobaltcore-dev/lightstack/pkg/paths"
9+
)
10+
11+
// TestResolveBackupDest covers the three branches of the backup target resolution: too many
12+
// arguments is refused, a named file is made absolute, and no file falls back to the default
13+
// under <state_path>/backups with a timestamped name.
14+
func TestResolveBackupDest(t *testing.T) {
15+
// resolveBackupDest mutates the package-global base via paths.SetBase; restore it.
16+
t.Cleanup(func() { paths.SetBase(paths.DefaultBase) })
17+
18+
t.Run("too many arguments", func(t *testing.T) {
19+
if _, err := resolveBackupDest([]string{"a.db", "b.db"}, "/var/lib/lightstack"); err == nil ||
20+
!strings.Contains(err.Error(), "usage") {
21+
t.Fatalf("resolveBackupDest(two files) = %v; want a usage error", err)
22+
}
23+
})
24+
25+
t.Run("named relative file is made absolute", func(t *testing.T) {
26+
got, err := resolveBackupDest([]string{"my.db"}, "/var/lib/lightstack")
27+
if err != nil {
28+
t.Fatalf("resolveBackupDest: %v", err)
29+
}
30+
if !filepath.IsAbs(got) || filepath.Base(got) != "my.db" {
31+
t.Errorf("resolveBackupDest(my.db) = %q; want an absolute path ending in my.db", got)
32+
}
33+
})
34+
35+
t.Run("named absolute file is kept", func(t *testing.T) {
36+
got, err := resolveBackupDest([]string{"/tmp/backup.db"}, "/var/lib/lightstack")
37+
if err != nil {
38+
t.Fatalf("resolveBackupDest: %v", err)
39+
}
40+
if got != "/tmp/backup.db" {
41+
t.Errorf("resolveBackupDest(/tmp/backup.db) = %q; want it unchanged", got)
42+
}
43+
})
44+
45+
t.Run("no file defaults under state_path", func(t *testing.T) {
46+
const statePath = "/srv/lightstack"
47+
got, err := resolveBackupDest(nil, statePath)
48+
if err != nil {
49+
t.Fatalf("resolveBackupDest: %v", err)
50+
}
51+
if dir := filepath.Dir(got); dir != filepath.Join(statePath, "backups") {
52+
t.Errorf("default backup directory = %q; want %q", dir, filepath.Join(statePath, "backups"))
53+
}
54+
if base := filepath.Base(got); !strings.HasPrefix(base, "lightstack-") || !strings.HasSuffix(base, ".db") {
55+
t.Errorf("default backup name = %q; want lightstack-<time>.db", base)
56+
}
57+
})
58+
}

‎docs/CONFIGURATION.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -338,8 +338,11 @@ database:
338338
For a missing file, `console-tokens` exits 1 naming the path; `cleanup` warns naming it and does
339339
its host-only cleanup, as for an unreachable PostgreSQL.
340340
- **Files**: `lightstack.db`, and beside it `lightstack.db-wal`, `lightstack.db-shm` and
341-
`lightstack.db.migrate-lock`. Committed data can sit in the `-wal` file until a checkpoint: copy
342-
the files together, with Lightstack stopped, or use `sqlite3 lightstack.db ".backup <file>"`.
341+
`lightstack.db.migrate-lock`. Committed data can sit in the `-wal` file until a checkpoint, so
342+
never copy `lightstack.db` alone. Back up with `lightstack-migrate backup` (a consistent copy while
343+
Lightstack runs, to `<state_path>/backups`) and verify with `lightstack-migrate check`; restoring
344+
means deleting `-wal` and `-shm` first ([KUBERNETES_DEPLOYMENT.md](KUBERNETES_DEPLOYMENT.md#backup-integrity-check-and-restore),
345+
[DOCKER_DEPLOYMENT.md](DOCKER_DEPLOYMENT.md#backup-and-restore-on-sqlite)).
343346

344347
The startup log line names the backend, where the database is (never with credentials), the schema
345348
version and the node name:

‎docs/DOCKER_DEPLOYMENT.md‎

Lines changed: 75 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -442,21 +442,88 @@ volumes:
442442

443443
Drop the `postgres` service and the `depends_on` entry that waits for it. `lightstack-migrate`
444444
creates and migrates the file on the first start; the `database ready` log line names it.
445-
`neutron.vxlan_enabled` must stay off. To back the file up, stop the container and copy the volume —
446-
the `-wal` file beside the database holds committed data until a checkpoint. The Lightstack image
447-
ships no `sqlite3`, so for a live backup run one from another image against the volume:
448-
449-
```bash
450-
docker run --rm -v lightstack-db:/db alpine sh -c \
451-
'apk add --no-cache sqlite >/dev/null && sqlite3 /db/lightstack.db ".backup /db/backup.db"'
452-
```
445+
`neutron.vxlan_enabled` must stay off. Back the database up with `lightstack-migrate backup`, never
446+
by copying the files while Lightstack runs ([Backup and restore on SQLite](#backup-and-restore-on-sqlite)).
453447

454448
The KVM stack (`deployments/docker-compose-kvm.yml`) needs no edit: it mounts the whole state root
455449
at the same path, so `LIGHTSTACK_DB_URL=sqlite:///var/lib/lightstack/db/lightstack.db` in the
456450
environment of `docker compose` — or that URL as `database.url` in its config — selects SQLite.
457451
With host networking the container carries the host's name, which keeps the node name stable without
458452
`LIGHTSTACK_NODE_NAME` ([README-KVM.md](../deployments/README-KVM.md)).
459453

454+
### Backup and restore on SQLite
455+
456+
These procedures are for the **real-mode** stack, `deployments/docker-compose-kvm.yml`, which mounts the
457+
whole state root (`/var/lib/lightstack` by default) from the host at the same path. Backups go to
458+
`<state_path>/backups`, so they land on the host. Stub-mode SQLite stacks such as
459+
`docker-compose-sqlite.yml` keep only `db/` on a volume and are not backed up. On PostgreSQL use
460+
`pg_dump` ([Database Management](#database-management)); `backup` and `check` refuse a PostgreSQL URL
461+
and say so.
462+
463+
```bash
464+
KVM="docker compose -f deployments/docker-compose-kvm.yml"
465+
CFG=/opt/lightstack/config/lightstack.yaml # the stack's config path; flags go before a file name
466+
```
467+
468+
**Take a backup** while Lightstack runs. `lightstack-migrate backup` copies the database consistently
469+
from inside it:
470+
471+
```bash
472+
$KVM exec lightstack /app/lightstack-migrate backup -config $CFG
473+
# ✅ Backup written to /var/lib/lightstack/backups/lightstack-20261028T143000Z.db
474+
```
475+
476+
The backup is one file (no `-wal`/`-shm`), `0600` in a `0750` directory, named after its UTC time, and
477+
an existing file is never overwritten — pass a name to choose one. It is on the host's disk: copy it
478+
off the host. Nothing prunes old backups.
479+
480+
**Check integrity**, also while running; it exits non-zero and lists the problems on a damaged
481+
database, and refuses one that holds no Lightstack schema (an empty file passes SQLite's own check):
482+
483+
```bash
484+
$KVM exec lightstack /app/lightstack-migrate check -config $CFG
485+
```
486+
487+
**Restore.** Delete `lightstack.db-wal` and `lightstack.db-shm` before putting the backup in place:
488+
left there, SQLite replays the old write-ahead log onto the restored file and brings back the data
489+
written after the backup.
490+
491+
```bash
492+
$KVM stop lightstack
493+
$KVM run --rm --entrypoint sh lightstack
494+
```
495+
496+
In that container (same mounts and environment as the service):
497+
498+
```sh
499+
S=/var/lib/lightstack # state_path
500+
rm -f $S/db/lightstack.db-wal $S/db/lightstack.db-shm
501+
cp $S/backups/lightstack-20261028T143000Z.db $S/db/lightstack.db
502+
chmod 600 $S/db/lightstack.db
503+
/app/lightstack-migrate check -config /opt/lightstack/config/lightstack.yaml
504+
exit
505+
```
506+
507+
```bash
508+
$KVM start lightstack
509+
```
510+
511+
A backup from an older Lightstack is migrated forward on start; one from a **newer** Lightstack is
512+
refused (`the database is at migration version N, but this Lightstack knows versions up to M`).
513+
514+
**Recovery.** Restore the latest backup that passes `check`; what was written after it is lost.
515+
Without a usable backup, salvage with the `sqlite3` shell's `.recover`. The image ships no `sqlite3`,
516+
and Debian's and Ubuntu's builds cannot run `.recover` (`no such table: sqlite_dbpage`), so stop
517+
Lightstack, copy `lightstack.db` with its `-wal` and `-shm` (one database, three files) into one
518+
directory, and use Alpine's:
519+
520+
```bash
521+
docker run --rm -v "$PWD":/w docker.io/library/alpine:3.24 sh -c 'apk add -q sqlite && sqlite3 /w/lightstack.db ".recover" | sqlite3 /w/recovered.db'
522+
```
523+
524+
The result is best effort: restore `recovered.db` with the steps above, whose `check` refuses a file
525+
that holds no Lightstack schema.
526+
460527
### Update Lightstack
461528

462529
```bash

0 commit comments

Comments
 (0)