Skip to content

Commit 0a1cdc7

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 b8521e6 commit 0a1cdc7

24 files changed

Lines changed: 2378 additions & 14 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: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
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"
1114
"github.com/cobaltcore-dev/lightstack/internal/middleware"
15+
"github.com/cobaltcore-dev/lightstack/pkg/paths"
1216
)
1317

1418
func main() {
@@ -45,6 +49,17 @@ func main() {
4549
// Initialize logging
4650
middleware.InitLogger(&cfg.Logging)
4751

52+
// backup and check work on the database file alone and read no migrations, so they run
53+
// wherever the binary does — a node debug pod included (SPEC-030).
54+
switch command {
55+
case "backup":
56+
handleBackup(cfg.Database.URL, cfg.StatePath)
57+
return
58+
case "check":
59+
handleCheck(cfg.Database.URL)
60+
return
61+
}
62+
4863
// Validate migrations directory
4964
if err := database.ValidateMigrations(*migrationsPath); err != nil {
5065
fmt.Fprintf(os.Stderr, "Migration validation failed: %v\n", err)
@@ -201,6 +216,54 @@ func handleForce(dbURL, migrationsPath string) {
201216
fmt.Printf("✅ Version forced to %d\n", version)
202217
}
203218

219+
// handleBackup takes a consistent copy of the SQLite database while Lightstack keeps serving
220+
// it: to the named file, or by default to <state_path>/backups/lightstack-<UTC time>.db.
221+
func handleBackup(dbURL, statePath string) {
222+
dest, err := resolveBackupDest(flag.Args(), statePath)
223+
if err != nil {
224+
fmt.Fprintf(os.Stderr, "%v\n", err)
225+
os.Exit(1)
226+
}
227+
if err := database.Backup(context.Background(), dbURL, dest); err != nil {
228+
fmt.Fprintf(os.Stderr, "Backup failed: %v\n", err)
229+
os.Exit(1)
230+
}
231+
fmt.Printf("✅ Backup written to %s\n", dest)
232+
}
233+
234+
// resolveBackupDest picks the backup target as an absolute path: the named file, or — when no
235+
// file is given — the default <state_path>/backups/lightstack-<UTC time>.db. More than one
236+
// positional argument is a usage error.
237+
func resolveBackupDest(args []string, statePath string) (string, error) {
238+
if len(args) > 1 {
239+
return "", fmt.Errorf("usage: lightstack-migrate backup [options] [<file>]")
240+
}
241+
dest := ""
242+
if len(args) == 1 {
243+
dest = args[0]
244+
}
245+
if dest == "" {
246+
paths.SetBase(statePath)
247+
dest = paths.BackupPath(time.Now())
248+
}
249+
if abs, err := filepath.Abs(dest); err == nil {
250+
dest = abs
251+
}
252+
return dest, nil
253+
}
254+
255+
// handleCheck runs SQLite's integrity check; it exits non-zero, listing the problems, on a
256+
// damaged database, and on one holding no Lightstack schema. It only reads, so it runs against
257+
// a serving Lightstack too.
258+
func handleCheck(dbURL string) {
259+
version, err := database.IntegrityCheck(context.Background(), dbURL)
260+
if err != nil {
261+
fmt.Fprintf(os.Stderr, "Check failed: %v\n", err)
262+
os.Exit(1)
263+
}
264+
fmt.Printf("✅ Integrity check passed (schema version %d)\n", version)
265+
}
266+
204267
func printUsage() {
205268
fmt.Println("Lightstack Database Migration Tool")
206269
fmt.Println("===========================")
@@ -214,6 +277,13 @@ func printUsage() {
214277
fmt.Println(" goto <version> Migrate to specific version")
215278
fmt.Println(" reset Drop all tables and re-run migrations (DANGEROUS)")
216279
fmt.Println(" force <version> Force migration version (for fixing dirty state)")
280+
fmt.Println(" backup [<file>] Copy the SQLite database while Lightstack runs; never overwrites.")
281+
fmt.Println(" Default file: <state_path>/backups/lightstack-<UTC time>.db")
282+
fmt.Println(" check Check the SQLite database's integrity and schema version;")
283+
fmt.Println(" non-zero if damaged, empty or not a Lightstack database")
284+
fmt.Println()
285+
fmt.Println("backup and check are for SQLite only; for PostgreSQL use pg_dump. Options go before")
286+
fmt.Println("the file: lightstack-migrate backup -config <path> <file>.")
217287
fmt.Println()
218288
fmt.Println("The database is database.url in the configuration file, or LIGHTSTACK_DB_URL when set:")
219289
fmt.Println("postgres://… for PostgreSQL, sqlite:///absolute/path/lightstack.db for SQLite. Both read")
@@ -229,5 +299,7 @@ func printUsage() {
229299
fmt.Println(" lightstack-migrate down")
230300
fmt.Println(" lightstack-migrate goto 5")
231301
fmt.Println(" lightstack-migrate force 7")
302+
fmt.Println(" lightstack-migrate backup")
303+
fmt.Println(" lightstack-migrate check")
232304
fmt.Println()
233305
}
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
@@ -441,21 +441,88 @@ volumes:
441441

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

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

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

461528
```bash

0 commit comments

Comments
 (0)