diff --git a/PostgreSQL/MIGRATION_RUNBOOK.md b/PostgreSQL/MIGRATION_RUNBOOK.md new file mode 100644 index 0000000..7efefce --- /dev/null +++ b/PostgreSQL/MIGRATION_RUNBOOK.md @@ -0,0 +1,240 @@ +# PostgreSQL Migration Runbook + +Migrate the `postgres` database from the old StatefulSet (local-storage, image `pgvector/pgvector:pg18-trixie`) to a new Deployment `postgres-hetzner` on `hcloud-volumes` (Hetzner CSI), using the public image `pgvector/pgvector:pg18-trixie` (Postgres 18 + pgvector 0.8.2). + +**Strategy:** logical dump/restore via `pg_dumpall`, Option A service repoint (external IP `10.2.0.122` and internal DNS `postgres.database.svc.cluster.local` both unchanged → outside dependency and in-cluster consumers need no reconfiguration). + +**Downtime:** required (writers stopped during dump/restore). Estimated window: ~20–40 min depending on 18 GB transfer speed. + +--- + +## Current state (verified in cluster) + +### Old DB +- **StatefulSet** `postgres` in namespace `database` (120 days old). +- **Pod** `postgres-0` on node `woker-1-8gb-hel1-1`, IP `10.0.2.116`. +- **Image:** `pgvector/pgvector:pg18-trixie` (Postgres 18 + pgvector). +- **Credentials:** hardcoded `POSTGRES_USER=admin`, `POSTGRES_PASSWORD=jd@wXseh9z7vM@9`. Also stored in Secret `postgres-secret` (namespace `database`) with the same values. +- **PVC** `postgres-data-postgres-0` (from STS `volumeClaimTemplates`): `local-storage`, 30Gi requested, bound to PV `example-pv` (50Gi). + +### Services (two) +1. **`postgres`** — ClusterIP `10.107.200.144`, selector `app: postgres`. **Internal DNS** `postgres.database.svc.cluster.local` used by in-cluster consumers. +2. **`postgres-service`** — LoadBalancer, **external IP `10.2.0.122`** (annotation `lbipam.cilium.io/ips: 10.2.0.122`, pool `postgres-pool` CIDR `10.2.0.0/24`), selector `app: postgres`. **Used by the outside dependency.** + +### Cilium LB IP pools +- `lan-pool` → `10.1.0.101–10.1.0.199` (94 free) — used by Cilium ingresses. +- `postgres-pool` → `10.2.0.0/24` (255 free, 1 used = `10.2.0.122`) — dedicated postgres pool. + +### Databases to migrate (~18.4 GB total) +| Database | Size | Owner | Used by | +|---|---|---|---| +| homeassistant | 18 GB | homeassistant | outside dependency (via LB `10.2.0.122`) | +| immich | 445 MB | admin | immich-server, immich-machine-learning | +| gitea | 15 MB | gitea | gitea | +| grafana | 14 MB | grafana | grafana | +| backup | 8.5 MB | data_mover | (legacy) | +| admin | 7.7 MB | admin | — | + +### `immich` DB extensions (must be present in new image) +`cube`, `earthdistance`, `pg_trgm`, `unaccent`, `uuid-ossp`, `vector (0.8.2)`, `plpgsql`. +All present in the custom image (`postgres:18.4` + `pgvector v0.8.2`) and in `pgvector/pgvector:pg18-trixie`. + +### Consumers of `postgres.database.svc.cluster.local` (all unchanged with Option A) +| Consumer | Namespace | Deployment | +|---|---|---| +| immich-server | immich | immich-server | +| immich-machine-learning | immich | immich-machine-learning | +| gitea | gitea | gitea | +| grafana | monitoring | grafana | + +### External consumer +- **The outside dependency connects via the old pod IP `10.0.2.116` (NOT the LB `10.2.0.122`).** This was incorrect — pod IPs are ephemeral and disappear when the pod is deleted. +- After migration, the old pod IP `10.0.2.116` is gone. The outside dependency **must be reconfigured to use `10.2.0.122:5432`** (the stable LB IP, which routes to the new `postgres-hetzner` pod). +- The LB `postgres-service` keeps IP `10.2.0.122` via the Cilium annotation `lbipam.cilium.io/ips: 10.2.0.122` (pool `postgres-pool`) — this IP is stable across pod restarts/replacements. +- **Action required:** update the outside dependency's DB host from `10.0.2.116` → `10.2.0.122` before/after cutover. + +--- + +## Repo manifest changes (already applied) + +- `PostgreSQL/postgress_deplay.yaml` — synced to live STS (rollback reference). +- `PostgreSQL/postgres_service.yaml` — ClusterIP `postgres`, selector `app: postgres-hetzner`. +- `PostgreSQL/postgres_lb_service.yaml` (new) — LB `postgres-service`, static IP `10.2.0.122`, selector `app: postgres-hetzner`. +- `PostgreSQL/hetzner/postgres_hetzner_deployment.yaml` — uses `postgres-secret` (secretKeyRef), public image `pgvector/pgvector:pg18-trixie` (custom image `10.0.2.119:5000/custom-postgres:latest` not reachable — old node IP gone; nodes now on 10.1.0.x and cluster DNS not resolvable from node containerd), `strategy: Recreate`. +- Removed stale `postgres_pvc.yaml` and `postgres_static_endpoint.yaml`. + +--- + +## Execution + +### Phase 0 — Pre-flight (re-run on migration day to confirm no drift) +```bash +kubectl get pvc -n database +kubectl get sts,deploy,svc,pod,endpointslice -n database +kubectl exec -n database postgres-0 -- psql -U admin -d postgres -c '\l+' +kubectl get svc postgres-service -n database -o jsonpath='{.status.loadBalancer.ingress[0].ip}' # expect 10.2.0.122 +# Confirm new objects don't exist yet +kubectl get deploy postgres-hetzner -n database # expect NotFound +kubectl get pvc postgres-hetzner-pvc -n database # expect NotFound +``` + +### Phase 1 — Stand up new empty DB (no downtime yet) +```bash +kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_pvc.yaml +kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_secret.yml +kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_deployment.yaml +kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_service.yaml # temp internal svc for restore +kubectl rollout status deploy/postgres-hetzner -n database +kubectl get pod -n database -l app=postgres-hetzner -w # wait Running +``` + +### Phase 2 — Downtime begins, stop ALL writers +```bash +kubectl scale deploy/immich-server -n immich --replicas=0 +kubectl scale deploy/immich-machine-learning -n immich --replicas=0 +kubectl scale deploy/gitea -n gitea --replicas=0 +kubectl scale deploy/grafana -n monitoring --replicas=0 +# >>> STOP the outside dependency writing to homeassistant DB now <<< + +# confirm all stopped +kubectl get pod -n immich -l app=immich-server +kubectl get pod -n immich -l app=immich-machine-learning +kubectl get pod -n gitea -l app=gitea +kubectl get pod -n monitoring -l app=grafana +``` + +### Phase 3 — Dump + restore (writers down = consistent ~18.4 GB) + +> **IMPORTANT:** Do NOT use `pg_dumpall | psql` over a `kubectl exec` pipe. The kubectl websocket times out on large transfers (~18 GB) and the text format corrupts `vector` data (long embedding strings get truncated, breaking `smart_search` and other pgvector tables). Use binary `pg_dump -Fc` with `pg_restore`, running `pg_dump` from inside the new pod pointing at the old DB via the `postgres` Service. + +```bash +OLD=$(kubectl get pod -n database -l app=postgres -o jsonpath='{.items[0].metadata.name}') +NEW=$(kubectl get pod -n database -l app=postgres-hetzner -o jsonpath='{.items[0].metadata.name}') +echo "OLD=$OLD NEW=$NEW" + +# Step 1: pg_dumpall for roles + small DBs (admin, backup, postgres, gitea, grafana) via text pipe +# — these have no vector data and are small (<15 MB each), safe over kubectl pipe. +kubectl exec -n database $OLD -- pg_dumpall -c -U admin --roles-only \ + | kubectl exec -i -n database $NEW -- psql -U admin -d postgres +# Create the small databases (gitea, grafana, backup, homeassistant) — schema only first if needed, +# or rely on pg_dumpall to recreate them. For non-immich DBs, text pipe is fine (no vector columns): +kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d gitea -f /tmp/gitea.dump +kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d grafana -f /tmp/grafana.dump +kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d backup -f /tmp/backup.dump +kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d homeassistant -f /tmp/homeassistant.dump +# Transfer each dump from old pod to new pod using pg_dump from the new pod (binary-safe, avoids kubectl pipe): +for db in gitea grafana backup homeassistant immich; do + kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \ + pg_dump -h postgres.database.svc.cluster.local -U admin -d $db -Fc -f /tmp/$db.dump +done + +# Step 2: restore each DB on the new pod (drop existing first if re-running) +for db in gitea grafana backup homeassistant immich; do + kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \ + psql -h localhost -U admin -d postgres -c "DROP DATABASE IF EXISTS $db;" + kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \ + psql -h localhost -U admin -d postgres -c "CREATE DATABASE $db OWNER admin;" + kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \ + pg_restore -h localhost -U admin -d $db --no-owner --no-privileges /tmp/$db.dump +done + +# Step 3: verify DBs + sizes +kubectl exec -n database $NEW -- psql -U admin -d postgres -c '\l+' +# verify immich extensions +kubectl exec -n database $NEW -- psql -U admin -d immich -c "\dx" +# spot-check row counts +kubectl exec -n database $NEW -- psql -U admin -d immich -c "SELECT count(*) FROM asset;" +kubectl exec -n database $NEW -- psql -U admin -d immich -c "SELECT count(*) FROM smart_search;" +kubectl exec -n database $NEW -- psql -U admin -d homeassistant -c "SELECT count(*) FROM events;" +kubectl exec -n database $NEW -- psql -U admin -d gitea -c "SELECT count(*) FROM repository;" +kubectl exec -n database $NEW -- psql -U admin -d grafana -c "SELECT count(*) FROM dashboard;" + +# Step 4: cleanup dump files +for db in gitea grafana backup homeassistant immich; do + kubectl exec -n database $NEW -- rm -f /tmp/$db.dump + kubectl exec -n database $OLD -- rm -f /tmp/$db.dump 2>/dev/null +done +``` + +**Why dump from the new pod:** the new pod can reach the old DB via `postgres.database.svc.cluster.local` (still pointing at old pods until cutover), and writes the binary dump file directly to its own PVC — no kubectl pipe, no truncation, no websocket timeout. + +### Phase 4 — Cutover (repoint both Services to new pods) +```bash +kubectl apply -f PostgreSQL/postgres_service.yaml # ClusterIP postgres → app: postgres-hetzner +kubectl apply -f PostgreSQL/postgres_lb_service.yaml # LB postgres-service → app: postgres-hetzner, IP 10.2.0.122 kept + +kubectl get svc postgres postgres-service -n database +# verify external IP still 10.2.0.122 +kubectl get svc postgres-service -n database -o jsonpath='{.status.loadBalancer.ingress[0].ip}' + +# verify in-cluster connectivity via the unchanged DNS name +kubectl run pg-test --rm -it --image=postgres:18 --restart=Never -- \ + psql -h postgres.database.svc.cluster.local -U admin -d postgres -c '\l+' +``` + +### Phase 5 — Restart consumers (immich's initContainer pg_isready validates) +```bash +kubectl scale deploy/immich-server -n immich --replicas=1 +kubectl scale deploy/immich-machine-learning -n immich --replicas=1 +kubectl scale deploy/gitea -n gitea --replicas=1 +kubectl scale deploy/grafana -n monitoring --replicas=1 + +kubectl rollout status deploy/immich-server -n immich +kubectl rollout status deploy/gitea -n gitea +kubectl rollout status deploy/grafana -n monitoring + +kubectl logs deploy/immich-server -n immich --tail=50 # no DB errors +kubectl logs deploy/gitea -n gitea --tail=50 +# >>> restart the outside dependency (now pointed at 10.2.0.122) <<< +``` + +### Phase 6 — Cleanup (after a few days green; KEEP old PVC as rollback first) +```bash +kubectl delete sts postgres -n database --cascade=orphan # orphan keeps pods/PVC for rollback +kubectl delete svc postgres-hetzner -n database # temp restore svc + +# DO NOT delete PVC postgres-data-postgres-0 yet — rollback safety net (~1 week) + +# After confidence period: +kubectl delete pod -n database -l app=postgres # leftover orphan pod +kubectl delete pvc postgres-data-postgres-0 -n database +``` + +--- + +## Rollback (if Phase 4/5 fails — recovers OLD DB) + +> **Caveat:** rollback loses any writes made to the new DB after cutover (old PVC was not updated by dump/restore). This is inherent to logical dump/restore migration. If you need zero-data-loss rollback, the migration must use logical replication instead — request that redesign separately. + +```bash +# Repoint both Services back to old pods +kubectl patch svc postgres -n database --type=json \ + -p='[{"op":"replace","path":"/spec/selector","value":{"app":"postgres"}}]' +kubectl patch svc postgres-service -n database --type=json \ + -p='[{"op":"replace","path":"/spec/selector","value":{"app":"postgres"}}]' + +# Scale consumers back up — they hit old DB again +kubectl scale deploy/immich-server -n immich --replicas=1 +kubectl scale deploy/immich-machine-learning -n immich --replicas=1 +kubectl scale deploy/gitea -n gitea --replicas=1 +kubectl scale deploy/grafana -n monitoring --replicas=1 +# >>> restart the outside dependency (pointed at 10.2.0.122) <<< +``` + +If rollback happens **before** Phase 6 cleanup, the old STS + PVC `postgres-data-postgres-0` are intact and the old DB serves immediately. If rollback happens **after** `kubectl delete sts postgres --cascade=orphan`, recreate the STS from `PostgreSQL/postgress_deplay.yaml` (the orphan pod + PVC are reused because the STS name + selector match). + +--- + +## Pre-migration checklist (outside dependency) + +Before starting Phase 1, ensure: +- [ ] **Outside dependency DB host updated from `10.0.2.116` → `10.2.0.122`** (the old pod IP is gone; the LB IP `10.2.0.122` is stable and routes to the new DB). +- [ ] Outside dependency that writes to `homeassistant` DB via `10.2.0.122` can be stopped for the maintenance window. +- [ ] Backup of any critical external state taken. +- [ ] Maintenance window scheduled. + +## Pre-migration checklist (cluster) +- [ ] `kubectl get pvc -n database` shows `postgres-data-postgres-0` Bound on `local-storage`. +- [ ] `postgres-service` LB external IP is `10.2.0.122`. +- [ ] All consumer Deployments exist and are Ready (immich-server, immich-machine-learning, gitea, grafana). +- [ ] No `postgres-hetzner` Deployment/PVC exist yet. \ No newline at end of file diff --git a/PostgreSQL/hetzner/postgres_hetzner_deployment.yaml b/PostgreSQL/hetzner/postgres_hetzner_deployment.yaml index 196c2f6..5e9f920 100644 --- a/PostgreSQL/hetzner/postgres_hetzner_deployment.yaml +++ b/PostgreSQL/hetzner/postgres_hetzner_deployment.yaml @@ -5,6 +5,8 @@ metadata: namespace: database spec: replicas: 1 + strategy: + type: Recreate selector: matchLabels: app: postgres-hetzner @@ -15,15 +17,22 @@ spec: spec: containers: - name: postgres - image: 10.0.2.119:5000/custom-postgres:latest + image: pgvector/pgvector:pg18-trixie + imagePullPolicy: IfNotPresent volumeMounts: - name: postgres-data mountPath: /var/lib/postgresql env: - name: POSTGRES_PASSWORD - value: "jd@wXseh9z7vM@9" + valueFrom: + secretKeyRef: + name: postgres-secret + key: POSTGRES_PASSWORD - name: POSTGRES_USER - value: admin + valueFrom: + secretKeyRef: + name: postgres-secret + key: POSTGRES_USER volumes: - name: postgres-data persistentVolumeClaim: diff --git a/PostgreSQL/postgres_lb_service.yaml b/PostgreSQL/postgres_lb_service.yaml new file mode 100644 index 0000000..9ae136c --- /dev/null +++ b/PostgreSQL/postgres_lb_service.yaml @@ -0,0 +1,17 @@ +apiVersion: v1 +kind: Service +metadata: + name: postgres-service + namespace: database + labels: + io.cilium/static-ip: "true" + annotations: + lbipam.cilium.io/ips: "10.2.0.122" +spec: + type: LoadBalancer + selector: + app: postgres-hetzner + ports: + - protocol: TCP + port: 5432 + targetPort: 5432 \ No newline at end of file diff --git a/PostgreSQL/postgres_pvc.yaml b/PostgreSQL/postgres_pvc.yaml deleted file mode 100644 index 1ae54e1..0000000 --- a/PostgreSQL/postgres_pvc.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: postgres-pvc - namespace: database -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 39Gi - storageClassName: local-storage \ No newline at end of file diff --git a/PostgreSQL/postgres_service.yaml b/PostgreSQL/postgres_service.yaml index 04f1586..f550305 100644 --- a/PostgreSQL/postgres_service.yaml +++ b/PostgreSQL/postgres_service.yaml @@ -1,12 +1,12 @@ -apiVersion: v1 -kind: Service -metadata: - name: postgres - namespace: database -spec: - selector: - app: postgres - ports: - - protocol: TCP - port: 5432 - targetPort: 5432 +apiVersion: v1 +kind: Service +metadata: + name: postgres + namespace: database +spec: + selector: + app: postgres-hetzner + ports: + - protocol: TCP + port: 5432 + targetPort: 5432 \ No newline at end of file diff --git a/PostgreSQL/postgres_static_endpoint.yaml b/PostgreSQL/postgres_static_endpoint.yaml deleted file mode 100644 index b2ac5b4..0000000 --- a/PostgreSQL/postgres_static_endpoint.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: discovery.k8s.io/v1 -kind: EndpointSlice -metadata: - name: postgres-static-service - namespace: database - labels: - kubernetes.io/service-name: postgres # Links to the Service -addressType: IPv4 -ports: - - port: 5432 -endpoints: - - addresses: - - "10.0.2.122" \ No newline at end of file diff --git a/PostgreSQL/postgress_deplay.yaml b/PostgreSQL/postgress_deplay.yaml index 2c81981..567300f 100644 --- a/PostgreSQL/postgress_deplay.yaml +++ b/PostgreSQL/postgress_deplay.yaml @@ -1,36 +1,38 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: postgres - namespace: database -spec: - replicas: 1 - selector: - matchLabels: - app: postgres - template: - metadata: - labels: - app: postgres - spec: - containers: - - name: postgres - image: 10.0.2.119:5000/custom-postgres:latest - volumeMounts: - - name: postgres-data - mountPath: /var/lib/postgresql - env: - - name: POSTGRES_PASSWORD - valueFrom: - secretKeyRef: - name: postgres-secret - key: POSTGRES_PASSWORD - - name: POSTGRES_USER - valueFrom: - secretKeyRef: - name: postgres-secret - key: POSTGRES_USER - volumes: - - name: postgres-data - persistentVolumeClaim: - claimName: postgres-data \ No newline at end of file +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: postgres + namespace: database +spec: + replicas: 1 + serviceName: postgres + selector: + matchLabels: + app: postgres + template: + metadata: + labels: + app: postgres + spec: + containers: + - name: postgres + image: pgvector/pgvector:pg18-trixie + imagePullPolicy: IfNotPresent + volumeMounts: + - name: postgres-data + mountPath: /var/lib/postgresql + env: + - name: POSTGRES_PASSWORD + value: "jd@wXseh9z7vM@9" + - name: POSTGRES_USER + value: admin + volumeClaimTemplates: + - metadata: + name: postgres-data + spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 30Gi + storageClassName: local-storage \ No newline at end of file