Files
platform-core/services/platform-postgres-backup/README.md
T
DongHyeonka 4551a2ece6 feat(platform-postgres): run the shared database as Guaranteed QoS
The one PostgreSQL instance holds the Gitea, Keycloak and tech-log
databases. It is Burstable at priority 0 with oom_score_adj 985, so
under memory pressure the kernel kills it before almost anything else,
and an eviction treats it like Grafana (k3s maturity review
2026-11-11, 7.2 items 2 and 3).

Set priorityClassName platform-critical (services/priority-classes)
and raise the requests to the existing limits, CPU 2 and memory 4Gi,
so the pod is Guaranteed and its oom_score_adj becomes -997. The
backup README now gives the restart, not pg_hba, as the reason to add
spec.backup with kubectl patch.

Risk: applying this changes the pod spec, so CloudNativePG restarts
the single instance and the three databases are down for that time.
It belongs in the k3s restart window. Node requests grow by 1.75 CPU
and 3.5Gi; peak use over the last 6 hours was 0.025 CPU and 195MB.

Verification: kubectl diff of the rendered build root against the live
cluster shows only priorityClassName, the two requests and the
DatabaseRole defaults that were already there; no pg_hba line differs.
render-phase1.sh passes.
2026-11-12 07:29:48 +09:00

8.3 KiB

플랫폼 PostgreSQL 백업

platform-data/platform-postgres 하나에 Gitea, Keycloak, tech-log의 DB가 같이 있다 (2026-11-11: gitea 608MB, keycloak 14MB, techlog 14MB). 2026-11-11까지 백업 설정도, ScheduledBackup도 없었다. 그 PV는 루트 SSD 하나에만 있었다.

이 폴더는 매일 base backup과 WAL 연속 보관을 AIStor(HDD sdb3)에 두고, 30일 안의 아무 시점으로나 되돌릴 수 있게 한다.

무엇이 어디로 가나

platform-postgres-1 (SSD)
  ├─ WAL 파일이 찰 때마다, 그리고 5분마다 ─▶ s3://platform-postgres-backups/platform-postgres/wals/
  └─ 매일 03:00 KST base backup ─────────▶ s3://platform-postgres-backups/platform-postgres/base/
AIStor ObjectStore minio-aistor (HDD sdb3, aistor-local-xfs-retain)
파일 하는 일
cluster-backup-patch.yaml live Cluster에 spec.backup(보관소, 30일 보존, gzip)을 더한다
scheduled-backup.yaml 매일 18:00 UTC(03:00 KST) base backup. 만들자마자 한 번
object-storage-counterpart.yaml object-storage 쪽 ingress: platform-data의 PostgreSQL 파드 → AIStor 9000
bucket-policy.json 백업 사용자가 자기 bucket만 읽고 쓰는 정책
prometheus-rule.yaml 백업 경보 둘(아래). 관측 core 렌더러가 백업 규칙을 core 범위 밖으로 두므로 여기 둔다
restore-drill/cluster.yaml 복원 리허설용 임시 Cluster
../../scripts/bootstrap/create-postgres-backup-credentials.sh bucket·정책·사용자·Secret 생성

고른 방법

  • 내장 barmanObjectStore. CloudNativePG 1.26부터 deprecated이고 Barman Cloud Plugin이 권장이다. 하지만 plugin은 cert-manager가 필요한데 이 클러스터에는 없다(2026-11-11 CRD 없음). 백업이 하나도 없는 지금은 새 operator 두 개(cert-manager, plugin)를 먼저 세우는 것보다 지금 operator(1.30.0)가 바로 지원하는 쪽이 빠르고 위험이 작다. bucket 구조가 같아 plugin으로 옮겨도 백업을 그대로 쓴다.
    • 기한: operator 경고는 「1.31.0에서 완전히 제거」라고 한다(문서는 1.32.0). 그래서 CNPG를 1.31로 올리기 전에 Barman Cloud Plugin으로 옮긴다.
  • 보관소는 AIStor. 같은 desktop이지만 SSD가 아닌 HDD(sdb3, 900Gi)다. SSD가 죽어도 남는다. desktop 자체가 죽으면 같이 잃는다. 다른 기계·외부로 복사하는 일은 남은 과제다.
  • 보존 30일, quota 100GiB. 압축한 base backup이 하루 수백 MB, WAL은 5분마다 한 파일 (archive_timeout 기본값)이라 30일에 수십 GB 안쪽이다.
  • 볼륨 스냅숏은 쓰지 않는다. ssd-local-postgres-retain은 정적 local PV라 CSI 스냅숏이 없다.

적용 (소유자, 순서대로)

전제: 이 PR이 병합된 platform-core checkout, desktop의 kube context default.

백업 설정은 kubectl patch로만 더한다. services/platform-postgres 렌더를 다시 적용하면 priorityClassName과 Guaranteed resources도 같이 들어가 PostgreSQL이 재시작된다. 그것은 k3s 재시작 창(scripts/bootstrap/apply-k3s-restart-bundle.sh)에서 한다. 2026-11-11까지는 live pg_hba의 techlog 두 줄이 원본에 없어서 다시 적용하면 tech-log 백엔드가 끊겼다. 이 브랜치에서 원본에 넣었으므로(fix(platform-postgres): keep the tech-log pg_hba rules) 지금 렌더의 kubectl diff에는 pg_hba 차이가 없다.

  1. bucket, 정책, 사용자, Secret을 만든다. 화면에 자격 증명이 나오지 않는다.

    bash scripts/bootstrap/create-postgres-backup-credentials.sh
    

    마지막 줄에 PLATFORM_POSTGRES_BACKUP_BOOTSTRAP_PASS가 나와야 한다. 새 사용자가 자기 bucket에 쓰고 읽고 지울 수 있고, loki bucket은 못 보는 것까지 확인한다.

  2. AIStor 쪽 ingress를 연다. 그 전에는 PostgreSQL이 9000에 닿지 못한다.

    kubectl apply -f services/platform-postgres-backup/object-storage-counterpart.yaml
    
  3. live Cluster에 백업 설정을 더한다. PostgreSQL은 재시작하지 않는다.

    kubectl -n platform-data patch cluster platform-postgres --type merge \
      --patch-file services/platform-postgres-backup/cluster-backup-patch.yaml --dry-run=server -o name
    kubectl -n platform-data patch cluster platform-postgres --type merge \
      --patch-file services/platform-postgres-backup/cluster-backup-patch.yaml
    kubectl -n platform-data get cluster platform-postgres -o jsonpath='{.spec.postgresql.pg_hba}{"\n"}'
    

    마지막 줄에 techlog 두 줄이 있어야 한다. 몇 분 뒤 WAL이 올라가는지 본다.

    kubectl -n platform-data get cluster platform-postgres \
      -o jsonpath='{.status.conditions[?(@.type=="ContinuousArchiving")].status}{" "}{.status.firstRecoverabilityPoint}{"\n"}'
    
  4. 매일 백업을 건다. 만들자마자 첫 base backup이 돈다.

    kubectl apply -k services/platform-postgres-backup   # ScheduledBackup, AIStor ingress, 경보
    kubectl -n platform-data get backup -w
    

    PHASE가 completed가 되면 된다. failed면 kubectl -n platform-data describe backup <이름>의 마지막 줄을 본다.

  5. 아래 「복원 리허설」을 한 번 한다.

경보(prometheus-rule.yaml, 4단계에서 같이 들어간다. platform-data는 Prometheus가 규칙을 읽는 namespace다):

  • PlatformPostgresBackupMissing: 26시간 안에 끝난 base backup이 없다. 위 4단계 전까지는 계속 울린다(백업이 정말 없으니까).
  • PlatformPostgresWALArchiveBacklog: 보관을 기다리는 WAL이 10개를 넘은 채 15분. 보관이 막히면 WAL이 SSD 볼륨에 쌓여 PostgreSQL이 멈춘다. 2·3단계의 순서가 바뀌었거나 Secret이 틀리면 이것이 울린다.

되돌리기

kubectl delete -k services/platform-postgres-backup        # ScheduledBackup, ingress, 경보
kubectl -n platform-data patch cluster platform-postgres --type json -p '[{"op":"remove","path":"/spec/backup"}]'

bucket, 사용자, Secret, 이미 올린 백업은 지우지 않는다. 지울 때는 소유자가 mc로 직접 한다.

복원 리허설

백업이 실제로 복원되는지는 복원해 봐야 안다. 첫 base backup이 끝난 뒤 한 번, 그 뒤로는 CNPG나 PostgreSQL을 올릴 때마다 한다. 운영 Cluster는 건드리지 않는다. 임시 Cluster는 bucket을 읽기만 한다 (backup 칸이 없다).

  1. 임시 Cluster를 만든다. local-path 5Gi(루트 SSD)를 잠깐 쓴다.

    kubectl apply -f services/platform-postgres-backup/restore-drill/cluster.yaml
    kubectl -n platform-data wait cluster/platform-postgres-restore-drill \
      --for=condition=Ready --timeout=20m
    
  2. 두 쪽의 표마다 행 수를 비교한다. 운영은 그 사이에도 쓰이므로 활동이 많은 표(Gitea의 action, notice 등)는 조금 다를 수 있다. 표가 없거나 크게 다르면 실패다.

    count_rows() {  # $1 = cluster, $2 = database
      kubectl -n platform-data exec "$1-1" -c postgres -- psql -At -d "$2" -c \
        "select string_agg(format('select %L, count(*) from %I.%I', schemaname||'.'||relname, schemaname, relname), ' union all ')
         from pg_stat_user_tables" |
      kubectl -n platform-data exec -i "$1-1" -c postgres -- psql -At -d "$2" | sort
    }
    for db in gitea keycloak techlog; do
      diff <(count_rows platform-postgres "$db") <(count_rows platform-postgres-restore-drill "$db") \
        && echo "$db: same" || echo "$db: differs (see above)"
    done
    
  3. 복원된 시점을 기록한다.

    kubectl -n platform-data exec platform-postgres-restore-drill-1 -c postgres -- \
      psql -At -c "select now(), pg_last_xact_replay_timestamp()"
    
  4. 임시 Cluster를 지운다. PVC도 같이 지워진다.

    kubectl -n platform-data delete cluster platform-postgres-restore-drill
    

결과(날짜, 복원된 시점, 표 비교, 걸린 시간)는 아래 「기록」에 남긴다.

기록

  • 2026-11-11: 설계와 원본만. bucket·Secret·적용·리허설은 하지 않았다(소유자 단계). kubectl apply --dry-run=server로 ScheduledBackup, ingress, 리허설 Cluster가 admission을 통과했고, kubectl patch --dry-run=server로 patch 뒤에도 techlog pg_hba 두 줄이 남는 것을 봤다.