homek8s/infrastructure/garage-linode/pitr-restore.md
devops 4c90eba08b docs(pitr): the plugin path is real — transcript, layout, metrics, 1.31 gate closed
Documents what the live migration actually produced (kanban t_5df331de):

- §8.3: restore manifest is externalClusters[].plugin + barmanObjectName/
  serverName, with the 2026-11-19 rehearsal transcript (marker 23:04:53.07,
  target 23:05:00Z, poison 23:05:15.80 -> marker present, poison gone).
- §8.4 (new): how the plugin is wired — vendored manifest, Service-annotation
  registration, cert-manager dependency, ObjectStore/ScheduledBackup shape,
  the injected init-sidecar, and the metrics family change.
- §8.1/§5.1: producer is the plugin; retention moved to the ObjectStore;
  the "1.31 is a hard gate" caveat is replaced by "gate closed".
- §9/§10 + namespace table: cert-manager and barman-cloud are live state now,
  with the verification log rows.
- pitr-restore.md rewritten for the plugin (manifest, sidecar log evidence,
  the two-servers-name trap, retention location).
- CNPG dashboard: the `or` now prefers the plugin's metric — the legacy
  cnpg_collector series still holds the PRE-migration timestamp.
2026-11-19 18:09:23 -05:00

9.9 KiB

Restore notes — point-in-time recovery for sirius-growth/portal

Rehearsed end to end on 2026-11-19 against the live archive, twice: once with the in-tree barman-cloud archiver (kanban t_ce7d6772) and once after the migration to the CNPG-I Barman Cloud plugin (kanban t_5df331de). This file records the commands and the actual output of the plugin rehearsal, so the next person restores from a transcript instead of a hope.

The archive: Garage on the Linode, bucket pg-wal-archive, http://10.10.0.5:3900 over the WireGuard mesh, credentials in Secret sirius-growth/portal-wal-s3. Producer: the Barman Cloud plugin — ObjectStore sirius-growth/portal-wal (store + retentionPolicy: 14d), Cluster portal spec.plugins (isWALArchiver: true, serverName: portal) and ScheduledBackup portal-daily at 03:20 UTC with method: plugin. WAL archiving is continuous; base backups are daily plus on demand.

0. Is the archive actually healthy?

kubectl -n sirius-growth exec portal-1 -c postgres -- \
  psql -U postgres -tAc "select last_archived_wal, last_archived_time, failed_count from pg_stat_archiver"
# 000000010000000000000063|2026-11-19 23:05:16.834323+00|6

last_archived_time must be minutes old and the WAL name must advance when you force a segment (select pg_switch_wal()). A targetTime after the last archived WAL cannot be reached — recovery stops at the last segment it can fetch.

failed_count is cumulative for the life of the instance, not a "current health" gauge: the 6 recorded here are from the pre-migration in-tree archiver and the primary restart during the switch. What matters is that it does not increase while you watch — check it before and after a forced segment.

What actually wrote the last segment is visible in the sidecar log, which names barman's own arguments (server name portal, bucket root s3://pg-wal-archive):

kubectl -n sirius-growth logs portal-1 -c plugin-barman-cloud --tail=20
# {"msg":"Executing barman-cloud-wal-archive", ... "options":["--gzip","--endpoint-url","http://10.10.0.5:3900",
#   "--cloud-provider","aws-s3","s3://pg-wal-archive","portal","/var/lib/postgresql/data/pgdata/pg_wal/<seg>"]}
# {"msg":"Archived WAL file","walName":"...<seg>","elapsedWalTime":0.586...}
kubectl -n sirius-growth get backup -o wide        # newest Backup: METHOD plugin, PHASE completed
kubectl -n sirius-growth get scheduledbackup       # portal-daily, method plugin, LAST BACKUP set

1. Prove the marker, then make the mistake

q() { kubectl -n sirius-growth exec portal-1 -c postgres -- psql -U postgres -d portal -tAc "$1"; }
q "create table if not exists pitr_probe(id bigserial primary key, note text, at timestamptz default now())"
q "insert into pitr_probe(note) values ('MARKER-plugin-before-target') returning id, at"
#  1|2026-11-19 23:04:53.072104+00
q "select pg_switch_wal()" ; sleep 12
q "select last_archived_wal, last_archived_time, failed_count from pg_stat_archiver"
#  000000010000000000000062|2026-11-19 23:04:54.052315+00|6
sleep 10
q "insert into pitr_probe(note) values ('POISON-plugin-after-target') returning id, at"
#  2|2026-11-19 23:05:15.798408+00
q "select pg_switch_wal()" ; sleep 12
q "select last_archived_wal, last_archived_time, failed_count from pg_stat_archiver"
#  000000010000000000000063|2026-11-19 23:05:16.834323+00|6

The target is therefore 2026-11-19T23:05:00Z — 7 s after the marker, 15 s before the row that must be lost. Note that WAL …063 (which contains the poison row) is in the archive: the restore has to choose to stop, it is not starved of data.

2. Restore into a throwaway cluster

Never restore over the live portal cluster while it is serving.

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: portal-pitr-test
  namespace: sirius-growth
  labels: {purpose: pitr-acceptance-test}
spec:
  instances: 1
  imageName: ghcr.io/cloudnative-pg/postgresql:16
  storage: {size: 5Gi, storageClass: local-path}
  affinity: {nodeSelector: {kubernetes.io/hostname: siriussec}}
  resources:
    requests: {cpu: 100m, memory: 256Mi}
    limits: {memory: 1Gi}
  bootstrap:
    recovery:
      source: portal-wal
      recoveryTarget:
        targetTime: "2026-11-19T23:05:00Z"
  externalClusters:
    - name: portal-wal
      plugin:                                   # was barmanObjectStore before the plugin migration
        name: barman-cloud.cloudnative-pg.io
        parameters:
          barmanObjectName: portal-wal          # ObjectStore in THIS namespace
          serverName: portal                    # MUST be the *source* Cluster name

serverName is not optional: it is the barman prefix (portal/base, portal/wals). Omit it and the plugin falls back to the restoring cluster's name (portal-pitr-test) and finds an empty history. targetTime is UTC RFC3339 — a wrong timezone silently restores the wrong hour. The ObjectStore's own spec.configuration.serverName must stay empty (its CRD rejects anything else); the prefix always comes from this plugin parameter.

The operator restores the base backup, replays WAL, stops at the target and promotes:

ready=False phase=Setting up primary
ready=False phase=Waiting for the instances to become active
ready=True phase=Cluster in healthy state
portal-pitr-test   1   1   Cluster in healthy state   portal-pitr-test-1

3. The acceptance evidence

$ kubectl -n sirius-growth exec portal-pitr-test-1 -c postgres -- \
    psql -U postgres -d portal -c "select id, note, at from pitr_probe order by id"
 id |            note             |              at
----+-----------------------------+-------------------------------
  1 | MARKER-plugin-before-target | 2026-11-19 23:04:53.072104+00
(1 row)

$ ... -tAc "select count(*) from pitr_probe where note like 'POISON%'"
0

Marker present, post-target row gone. The rest of the database came back with it (physical restore, all databases, no pg_restore ordering games), e.g. clients 4 = 4, calendar_tokens 3 = 3, applications 1 = 1 against the primary at that moment.

$ ... -tAc "select pg_is_in_recovery()"
f            # replay finished, instance promoted

pg_is_in_recovery() = f is expected here and is not a failure: a CNPG recovery cluster with instances: 1 promotes itself once it hits the target. It is writable from that moment — which is why the test cluster must be deleted, and why nothing may point application traffic at it before you decide to.

kubectl -n sirius-growth delete cluster portal-pitr-test
kubectl -n sirius-growth delete pvc -l cnpg.io/cluster=portal-pitr-test
kubectl -n sirius-growth exec portal-1 -c postgres -- psql -U postgres -d portal -tAc "drop table if exists pitr_probe"

4. Making the restored data the real data

Two shapes, both legitimate:

  1. Cut over (preferred, reversible). Point the app at portal-pitr-test-rw (POSTGRES_HOST in the API/portal Deployments — through git, not kubectl set env), verify, then drop the old cluster only after the app has been confirmed on the restored copy.
  2. In place. Keep portal, stop its instances, and swap the PVC content from the recovered data directory. Slower, destructive, and easy to get wrong — only with the app scaled to zero.

Either way, take a fresh base backup once the decision is made (a Backup CR with method: plugin, or kubectl cnpg backup -n sirius-growth portal --method=plugin --plugin-name=barman-cloud.cloudnative-pg.io) so the archive has a post-recovery base rather than one from before the incident.

Gotchas that cost time

  • Flux owns apps/base/sirius-growth/. A hand kubectl apply of the Cluster, the ObjectStore or the ScheduledBackup is reverted by the apps Kustomization within its 1 min interval. Config changes belong in the branch/PR. (Cluster and Backup objects created by hand for a rehearsal are not in the Kustomization inventory, so they are not pruned — but the objects Flux does own are reverted.)
  • ScheduledBackup.spec.schedule is six-field cron, seconds first. `0 20 3
      • *` = 03:20:00 UTC. Copying a five-field crontab string silently means "every minute" in the first field.
  • Two different serverNames exist and only one may be set. On the ObjectStore it must be absent (CRD CEL rule); on the Cluster's spec.plugins[].parameters / externalClusters[].plugin.parameters it is the prefix. Set the wrong one and archiving writes to portal-<something>/, which silently abandons the existing 14-day window.
  • The bucket prefix is portal/portal/… only if you get destinationPath wrong. Use s3://pg-wal-archive for the bucket root; the server name is appended.
  • Plugin, not in-tree. The operator's in-tree barman-cloud support is deprecated in 1.30 and removed in 1.31; spec.backup.barmanObjectStore on a 1.31 operator would leave the cluster with no archiver at all. Restore config is externalClusters[].plugin + parameters.barmanObjectName, and the store itself is an ObjectStore CR in the cluster's namespace.
  • Retention moved. retentionPolicy lives on the ObjectStore now, enforced by the plugin sidecar every 30 min — not on the Cluster, and not "at backup time".
  • Backup metrics changed family. barman_cloud_cloudnative_pg_io_last_available_backup_timestamp replaces cnpg_collector_last_available_backup_timestamp. The old series for portal still shows the pre-migration timestamp, so alert/dashboard queries must prefer the new one (see monitoring/controllers/home/dashboards/build.py).
  • If archiving has failed (pg_stat_archiver.failed_count increasing), fix it and let a fresh base backup complete before trusting any recent targetTime.
  • Fallback when the archive is unusable: the nightly pg_dump in forgejo/cluster-backup (db/sirius-growth-portal-<stamp>.dump, 14 retained, §8.2 step 2 of docs/cluster-overview.md). 24 h RPO, logical, independent of barman and of the Linode Garage node.