feat(platform): guard the disk, clock, backups and monitoring after this week's incidents #10

Merged
donghyeon.kang merged 16 commits from claude/w1-infra-hardening into main 2026-11-11 22:43:49 +00:00
Owner

무엇을, 왜

desktop 한 대가 운영 k3s, Gitea Actions runner, 에이전트 세션 게이트를 같이 돌린다. 이번 주 사고 둘과 그 복구에서 빈틈이 드러났다.

  • 11-09 디스크: 빌드 캐시가 상한 없이 쌓여 루트가 90%가 됐다. kubelet이 파드를 내보냈고, imagePullPolicy: Never인 tech-log 운영 이미지를 이미지 GC가 지웠다. 85% 경고는 33시간 울렸지만, 그때는 이미 kubelet이 이미지를 지우기 시작한 뒤였다.
  • 11-11 시계: Windows 이중 부팅 때문에 RTC가 9시간 앞서 읽혔다. k3s가 그 시각으로 인증서를 만든 뒤 NTP가 시계를 되돌려 전부 502가 됐다. Prometheus는 미래 시각 샘플을 저장한 뒤 새 샘플을 전부 버렸고, 이를 알리는 장치가 없었다.
  • 복구 중에 찾은 것: platform-postgres(Gitea·Keycloak·tech-log DB)에 백업이 하나도 없었다. node-exporter는 CFS 주기의 26%에서 쓰로틀링됐다.

소유자 결정(design-docs template-program/README.md 5절 a·f, 2026-11-11 「권장 방식으로 반영」)과 총괄의 추가 범위대로 다음을 넣는다.

브랜치 claude/w1-infra-hardening(main 68a5f7d 위, head 0d703ff). 예전 브랜치 claude/vigorous-booth-e9c7b9는 이것으로 대체한다(force push를 피하려고 새로 만들었다).

커밋 내용
7fe3842 디스크 경보: 경고 80%/10분, 위험 85%/5분, PlatformRootFilesystemFillingFast(6시간 추세로 6시간 안에 여유가 10% 아래로 떨어진다고 예측될 때)
3bca2cf 호스트 Docker 빌드 캐시 상한 infrastructure/host/docker/daemon.json
a5f0bff runner 안쪽 Docker 상한, 주 1회 정리 timer
03ed671 k3s를 시간 동기화 뒤에 시작(drop-in), systemd-time-wait-sync는 최대 10분 대기
fb5535a, 1349ee2, c04d794 소유자 적용 절차 infrastructure/host/README.md, runner README, k3s 재시작 묶음 안내
f19ce54, d7c845c platform-postgres 매일 백업과 WAL 보관(AIStor, HDD sdb3), 30일 보존, 복원 리허설, 백업 경보 둘(백업 폴더의 PrometheusRule)
619b905, 2b13109 Prometheus 자체 감시: PlatformMetricsIngestionStopped, 외부 dead man's switch로 가는 PlatformHeartbeat, 고정 렌더러의 Alertmanager 계약
bed20b4 node-exporter CPU limit 250m → 1
d47d57a (k3s 점검 세션 1c4ef9a cherry-pick) live에 있던 techlog pg_hba 두 줄과 렌더 불변식
4551a2e Postgres priorityClassName: platform-critical, requests=limits(CPU 2·4Gi, Guaranteed). 적용하면 Postgres가 재시작된다 → k3s 재시작 창
d92dc5d node-exporter textfile 수집기(/host/root/var/lib/node_exporter/textfile_collector, k3s 점검 세션 요청)

고른 방법과 버린 대안

  • BuildKit 상한은 defaultMaxUsedSpace로 건다. Docker 29에서 예전 키 defaultKeepStorage는 defaultReservedSpace(최소 보존량)와 같은 뜻이라 상한이 되지 않는다(moby daemon/config/builder.go). 설정 전 기본값은 보존 21.42GiB, 상한 169.5GiB였다. 여유 35GiB(사용 약 85%, kubelet 이미지 GC가 시작되는 지점) 아래면 빌드 캐시를 최소치까지 줄인다.
  • Docker 저장소를 HDD로 옮기는 안: 빌드가 느려져 소유자가 버렸다.
  • 정리 timer는 시스템 timer에 User=donghyeon을 쓴다. 사용자 timer는 linger가 꺼져 있어 로그인이 없으면 멈춘다.
  • systemd-time-wait-sync에 10분 상한을 둔다. 기본값 TimeoutStartSec=infinity 그대로면 NTP가 안 닿을 때 k3s가 영영 안 뜬다.
  • 백업은 내장 barmanObjectStore로 한다. 권장은 Barman Cloud Plugin이지만, plugin에 필요한 cert-manager가 이 클러스터에 없다. 백업이 0개인 지금은 operator 둘을 먼저 세우는 것보다 1.30.0이 바로 지원하는 쪽이 빠르다. operator는 「1.31.0에서 제거」라고 경고하므로, CNPG를 1.31로 올리기 전에 plugin으로 옮긴다(bucket 구조가 같다). 볼륨 스냅숏은 정적 local PV라 쓸 수 없다.
  • 백업은 HDD에만 둔다(소유자 지시). AIStor 데이터 볼륨은 /srv/k3s/aistor = /dev/sdb3(xfs, WD 2TB HDD, ROTA=1)다. NTFS 보관소 /mnt/hdd-archive(sdb2)는 POSIX 권한과 S3 API가 없고, dump로는 시점 복원이 안 돼서 버렸다. 리허설의 임시 Cluster만 SSD local-path 5Gi를 잠깐 쓰고 지운다.
  • 백업 설정은 kubectl patch로만 적용한다. live Cluster의 pg_hba에는 Phase 1 원본에 없는 techlog 줄 둘이 있다. 원본을 통째로 다시 적용하면 tech-log 백엔드가 DB에 못 붙는다.
  • Prometheus 감시는 안팎 둘로 한다. 안: absent(up{job="prometheus-node-exporter"}). 샘플을 버리는 동안에도 규칙은 돌기 때문에 이것은 울린다. 밖: 항상 울리는 PlatformHeartbeat를 5분마다 외부 heartbeat 서비스로 보내고, 끊기면 그 서비스가 알린다. Prometheus·Alertmanager·노드·네트워크가 다 죽어도 알 수 있는 길은 이것뿐이다. 클러스터 안 CronJob이 Prometheus를 묻고 Alertmanager로 보내는 안은 버렸다. 그것도 Alertmanager와 노드에 기대고, 고정된 NetworkPolicy 행렬에 새 workload를 넣어야 한다.
  • 운영 이미지를 GC에서 지키는 pinned 라벨을 kube-system Job으로 붙이는 안: 에이전트 권한 분류기가 막았다. sudo 한 줄로 소유자 단계에 넣었다.

PR #2(outOfOrderTimeWindow: 10h)와의 관계

  • 파일이 겹치지 않는다. PR #2는 kube-prometheus-stack/values/home.yaml과 그 README를, 이 PR은 infrastructure/host를 바꾼다. 어느 쪽을 먼저 병합해도 된다.
  • 하는 일이 다르다. 이 PR은 부팅 때 시계가 틀린 채 k3s가 뜨는 것을 막는다. PR #2는 그래도 시계가 튀었을 때 Prometheus가 스스로 회복하게 한다.
  • 시계를 고친 뒤에도 10h는 남기는 것을 권한다. 근거:
    • drop-in은 부팅 때만 지킨다. NTP가 10분 안에 안 닿으면 k3s는 틀린 시계로 그냥 뜬다.
    • Windows 쪽 RealTimeIsUniversal은 소유자가 아직 설정하지 않았다. Windows 업데이트나 재설치로 풀릴 수도 있다.
    • 비용이 작다. 늦은 샘플이 올 때만 별도 머리를 쓴다. 이번 회복 중 늦은 샘플 1,330만 개를 받았다(prometheus_tsdb_head_out_of_order_samples_appended_total). 시계가 정상일 때의 값은 03:36 KST 이후에 다시 재야 한다.
  • (PR #2는 41b46f6로 병합됐다.) PR #2 본문의 「렌더러를 못 돌렸다」는 사실과 다르다. desktop에 ~/.local/bin/helm v3.19.4와 kubectl 내장 kustomize v5.8.1이 있다. 그 브랜치의 고정 렌더러 결과는 아래 검증에 적는다.

위험과 영향

  • 이 PR은 클러스터와 호스트를 바꾸지 않는다. 적용은 전부 README의 소유자 단계다.
  • 호스트 daemon.json은 Docker를 다시 시작해야 적용된다. 그때 runner·workmachine·cloudflared가 다시 시작되고, 돌던 CI job과 게이트는 실패한다. README에 재시작해도 안전한 때와 lock을 잡고 재시작하는 명령을 적었다.
  • 백업이 막히면 WAL이 SSD 볼륨에 쌓여 PostgreSQL이 멈춘다. PlatformPostgresWALArchiveBacklog가 울린다. README의 순서(Secret → AIStor ingress → patch → ScheduledBackup)를 지켜야 한다.
  • 백업은 같은 desktop의 HDD에 있다. desktop 자체를 잃으면 백업도 같이 잃는다. 다른 기계나 외부로 복사하는 일은 남은 과제다.
  • AlertmanagerConfig가 이제 alertmanager-heartbeat Secret을 가리킨다. Secret보다 먼저 적용하면 operator가 새 설정을 만들지 못한다. 외부 heartbeat 계정은 소유자만 만들 수 있다.
  • PlatformPostgresBackupMissing은 첫 백업 전까지 계속 울린다. 백업이 정말로 없기 때문이다.
  • runner 정리는 이미지를 만든 시각으로 거른다. 그래서 고정 job 이미지도 주 1회 지워지고, 다음 job이 약 543MB를 다시 받는다.

검증

desktop에서 돌렸다. 고정 도구는 ~/.local/bin/helm v3.19.4와 kubectl 내장 kustomize v5.8.1이다.

  • test-platform-disk-alerts.sh(promtool): 두 규칙 파일, 13개 규칙. 디스크·백업·수집 중단·heartbeat 시험이 모두 이전 규칙에서 실패하고(RED), 바꾼 뒤 통과한다(GREEN).
  • test-observability-alerting.sh --server-dry-run: static contract, 전역 Alertmanager 렌더, server dry run 모두 PASS.
  • render-observability-core.sh: OBSERVABILITY CORE STATIC RENDER PASS(--verified-output-dir 모드 포함). test-render-observability-core.sh: PASS.
    • 처음에는 두 군데가 거부했다. 렌더러에 있는 Alertmanager 계약 사본, 그리고 backup 이름 규칙 금지다. 각각 7e8a6aa과 414d62b로 고쳤다.
  • render-phase1.sh: PASS(Phase 1 원본은 바꾸지 않았다).
  • kubectl apply --dry-run=server: core PrometheusRule, 백업 kustomization(ScheduledBackup, AIStor ingress, 백업 PrometheusRule), 리허설 Cluster가 모두 admission을 통과한다.
  • kubectl patch --dry-run=server: patch 뒤에도 techlog pg_hba 두 줄이 남고 spec.backup이 더해진다.
  • 리허설의 행 수 비교 명령을 운영 DB에서 읽기로만 돌렸다(keycloak 100, techlog 44, gitea 116 표).
  • 고정 AIStor client로 quota set, admin policy create, admin user add, admin policy attach 문법을 오프라인으로 확인했다.
  • helm template(prometheus-node-exporter 4.56.1): 렌더 결과가 limits.cpu: "1"이다.
  • dockerd --validate, systemd-analyze verify, docker compose config: 통과.
  • PR #2 브랜치: render-observability-core.sh PASS, test-render-observability-core.sh PASS(단언 216개).
  • 통과하지 못했거나 돌리지 않은 것:
    • scan-platform-sensitive-source.sh는 이 브랜치에서도, origin/main 스냅숏에서도 똑같이 renderer failed: observability-core RC=23으로 멈춘다. 기존 문제이고, 이 변경에 대해서는 아무것도 알려 주지 않는다.
    • shellcheck는 설치돼 있지 않다.
    • sudo 단계, bucket·Secret 생성, 클러스터 적용, 복원 리허설은 하지 않았다.

리뷰어가 볼 곳

  • services/observability/rules/platform/core-rules.yaml: 문턱, 예측식, platform.backup, platform.monitoring.
  • services/platform-postgres-backup/README.md: 적용 순서와 복원 리허설.
  • scripts/bootstrap/create-postgres-backup-credentials.sh: 자격 증명이 화면·로그에 안 남는지.
  • infrastructure/host/README.md: 소유자 명령의 순서와 되돌리기.

관련

  • design-docs template-program/README.md 5절 a·f
  • 공유 노트 desktop-disk-recovery-2026-11-09.md 6절 제안 1~4
  • platform-core PR #2 fix/prometheus-ooo-window
## 무엇을, 왜 desktop 한 대가 운영 k3s, Gitea Actions runner, 에이전트 세션 게이트를 같이 돌린다. 이번 주 사고 둘과 그 복구에서 빈틈이 드러났다. - 11-09 디스크: 빌드 캐시가 상한 없이 쌓여 루트가 90%가 됐다. kubelet이 파드를 내보냈고, `imagePullPolicy: Never`인 tech-log 운영 이미지를 이미지 GC가 지웠다. 85% 경고는 33시간 울렸지만, 그때는 이미 kubelet이 이미지를 지우기 시작한 뒤였다. - 11-11 시계: Windows 이중 부팅 때문에 RTC가 9시간 앞서 읽혔다. k3s가 그 시각으로 인증서를 만든 뒤 NTP가 시계를 되돌려 전부 502가 됐다. Prometheus는 미래 시각 샘플을 저장한 뒤 새 샘플을 전부 버렸고, 이를 알리는 장치가 없었다. - 복구 중에 찾은 것: `platform-postgres`(Gitea·Keycloak·tech-log DB)에 백업이 하나도 없었다. node-exporter는 CFS 주기의 26%에서 쓰로틀링됐다. 소유자 결정(design-docs `template-program/README.md` 5절 a·f, 2026-11-11 「권장 방식으로 반영」)과 총괄의 추가 범위대로 다음을 넣는다. 브랜치 `claude/w1-infra-hardening`(main `68a5f7d` 위, head `0d703ff`). 예전 브랜치 `claude/vigorous-booth-e9c7b9`는 이것으로 대체한다(force push를 피하려고 새로 만들었다). | 커밋 | 내용 | | --- | --- | | `7fe3842` | 디스크 경보: 경고 80%/10분, 위험 85%/5분, `PlatformRootFilesystemFillingFast`(6시간 추세로 6시간 안에 여유가 10% 아래로 떨어진다고 예측될 때) | | `3bca2cf` | 호스트 Docker 빌드 캐시 상한 `infrastructure/host/docker/daemon.json` | | `a5f0bff` | runner 안쪽 Docker 상한, 주 1회 정리 timer | | `03ed671` | k3s를 시간 동기화 뒤에 시작(drop-in), `systemd-time-wait-sync`는 최대 10분 대기 | | `fb5535a`, `1349ee2`, `c04d794` | 소유자 적용 절차 `infrastructure/host/README.md`, runner README, k3s 재시작 묶음 안내 | | `f19ce54`, `d7c845c` | `platform-postgres` 매일 백업과 WAL 보관(AIStor, HDD sdb3), 30일 보존, 복원 리허설, 백업 경보 둘(백업 폴더의 PrometheusRule) | | `619b905`, `2b13109` | Prometheus 자체 감시: `PlatformMetricsIngestionStopped`, 외부 dead man's switch로 가는 `PlatformHeartbeat`, 고정 렌더러의 Alertmanager 계약 | | `bed20b4` | node-exporter CPU limit 250m → 1 | | `d47d57a` | (k3s 점검 세션 `1c4ef9a` cherry-pick) live에 있던 techlog pg_hba 두 줄과 렌더 불변식 | | `4551a2e` | Postgres `priorityClassName: platform-critical`, requests=limits(CPU 2·4Gi, Guaranteed). **적용하면 Postgres가 재시작된다 → k3s 재시작 창** | | `d92dc5d` | node-exporter textfile 수집기(`/host/root/var/lib/node_exporter/textfile_collector`, k3s 점검 세션 요청) | ## 고른 방법과 버린 대안 - **BuildKit 상한은 `defaultMaxUsedSpace`로 건다.** Docker 29에서 예전 키 `defaultKeepStorage`는 `defaultReservedSpace`(최소 보존량)와 같은 뜻이라 상한이 되지 않는다(moby `daemon/config/builder.go`). 설정 전 기본값은 보존 21.42GiB, 상한 169.5GiB였다. 여유 35GiB(사용 약 85%, kubelet 이미지 GC가 시작되는 지점) 아래면 빌드 캐시를 최소치까지 줄인다. - **Docker 저장소를 HDD로 옮기는 안:** 빌드가 느려져 소유자가 버렸다. - **정리 timer는 시스템 timer에 `User=donghyeon`을 쓴다.** 사용자 timer는 linger가 꺼져 있어 로그인이 없으면 멈춘다. - **`systemd-time-wait-sync`에 10분 상한을 둔다.** 기본값 `TimeoutStartSec=infinity` 그대로면 NTP가 안 닿을 때 k3s가 영영 안 뜬다. - **백업은 내장 `barmanObjectStore`로 한다.** 권장은 Barman Cloud Plugin이지만, plugin에 필요한 cert-manager가 이 클러스터에 없다. 백업이 0개인 지금은 operator 둘을 먼저 세우는 것보다 1.30.0이 바로 지원하는 쪽이 빠르다. operator는 「1.31.0에서 제거」라고 경고하므로, **CNPG를 1.31로 올리기 전에 plugin으로 옮긴다**(bucket 구조가 같다). 볼륨 스냅숏은 정적 local PV라 쓸 수 없다. - **백업은 HDD에만 둔다(소유자 지시).** AIStor 데이터 볼륨은 `/srv/k3s/aistor` = `/dev/sdb3`(xfs, WD 2TB HDD, `ROTA=1`)다. NTFS 보관소 `/mnt/hdd-archive`(sdb2)는 POSIX 권한과 S3 API가 없고, dump로는 시점 복원이 안 돼서 버렸다. 리허설의 임시 Cluster만 SSD local-path 5Gi를 잠깐 쓰고 지운다. - **백업 설정은 `kubectl patch`로만 적용한다.** live Cluster의 `pg_hba`에는 Phase 1 원본에 없는 `techlog` 줄 둘이 있다. 원본을 통째로 다시 적용하면 tech-log 백엔드가 DB에 못 붙는다. - **Prometheus 감시는 안팎 둘로 한다.** 안: `absent(up{job="prometheus-node-exporter"})`. 샘플을 버리는 동안에도 규칙은 돌기 때문에 이것은 울린다. 밖: 항상 울리는 `PlatformHeartbeat`를 5분마다 외부 heartbeat 서비스로 보내고, 끊기면 그 서비스가 알린다. Prometheus·Alertmanager·노드·네트워크가 다 죽어도 알 수 있는 길은 이것뿐이다. 클러스터 안 CronJob이 Prometheus를 묻고 Alertmanager로 보내는 안은 버렸다. 그것도 Alertmanager와 노드에 기대고, 고정된 NetworkPolicy 행렬에 새 workload를 넣어야 한다. - **운영 이미지를 GC에서 지키는 pinned 라벨을 kube-system Job으로 붙이는 안:** 에이전트 권한 분류기가 막았다. sudo 한 줄로 소유자 단계에 넣었다. ### PR #2(`outOfOrderTimeWindow: 10h`)와의 관계 - 파일이 겹치지 않는다. PR #2는 `kube-prometheus-stack/values/home.yaml`과 그 README를, 이 PR은 `infrastructure/host`를 바꾼다. 어느 쪽을 먼저 병합해도 된다. - 하는 일이 다르다. 이 PR은 부팅 때 시계가 틀린 채 k3s가 뜨는 것을 막는다. PR #2는 그래도 시계가 튀었을 때 Prometheus가 스스로 회복하게 한다. - **시계를 고친 뒤에도 10h는 남기는 것을 권한다.** 근거: - drop-in은 부팅 때만 지킨다. NTP가 10분 안에 안 닿으면 k3s는 틀린 시계로 그냥 뜬다. - Windows 쪽 `RealTimeIsUniversal`은 소유자가 아직 설정하지 않았다. Windows 업데이트나 재설치로 풀릴 수도 있다. - 비용이 작다. 늦은 샘플이 올 때만 별도 머리를 쓴다. 이번 회복 중 늦은 샘플 1,330만 개를 받았다(`prometheus_tsdb_head_out_of_order_samples_appended_total`). 시계가 정상일 때의 값은 03:36 KST 이후에 다시 재야 한다. - (PR #2는 `41b46f6`로 병합됐다.) PR #2 본문의 「렌더러를 못 돌렸다」는 사실과 다르다. desktop에 `~/.local/bin/helm` v3.19.4와 kubectl 내장 kustomize v5.8.1이 있다. 그 브랜치의 고정 렌더러 결과는 아래 검증에 적는다. ## 위험과 영향 - 이 PR은 클러스터와 호스트를 바꾸지 않는다. 적용은 전부 README의 소유자 단계다. - 호스트 `daemon.json`은 Docker를 다시 시작해야 적용된다. 그때 runner·workmachine·cloudflared가 다시 시작되고, 돌던 CI job과 게이트는 실패한다. README에 재시작해도 안전한 때와 lock을 잡고 재시작하는 명령을 적었다. - 백업이 막히면 WAL이 SSD 볼륨에 쌓여 PostgreSQL이 멈춘다. `PlatformPostgresWALArchiveBacklog`가 울린다. README의 순서(Secret → AIStor ingress → patch → ScheduledBackup)를 지켜야 한다. - 백업은 같은 desktop의 HDD에 있다. desktop 자체를 잃으면 백업도 같이 잃는다. 다른 기계나 외부로 복사하는 일은 남은 과제다. - AlertmanagerConfig가 이제 `alertmanager-heartbeat` Secret을 가리킨다. Secret보다 먼저 적용하면 operator가 새 설정을 만들지 못한다. 외부 heartbeat 계정은 소유자만 만들 수 있다. - `PlatformPostgresBackupMissing`은 첫 백업 전까지 계속 울린다. 백업이 정말로 없기 때문이다. - runner 정리는 이미지를 만든 시각으로 거른다. 그래서 고정 job 이미지도 주 1회 지워지고, 다음 job이 약 543MB를 다시 받는다. ## 검증 desktop에서 돌렸다. 고정 도구는 `~/.local/bin/helm` v3.19.4와 kubectl 내장 kustomize v5.8.1이다. - `test-platform-disk-alerts.sh`(promtool): 두 규칙 파일, 13개 규칙. 디스크·백업·수집 중단·heartbeat 시험이 모두 이전 규칙에서 실패하고(RED), 바꾼 뒤 통과한다(GREEN). - `test-observability-alerting.sh --server-dry-run`: static contract, 전역 Alertmanager 렌더, server dry run 모두 PASS. - `render-observability-core.sh`: `OBSERVABILITY CORE STATIC RENDER PASS`(`--verified-output-dir` 모드 포함). `test-render-observability-core.sh`: PASS. - 처음에는 두 군데가 거부했다. 렌더러에 있는 Alertmanager 계약 사본, 그리고 `backup` 이름 규칙 금지다. 각각 `7e8a6aa`과 `414d62b`로 고쳤다. - `render-phase1.sh`: PASS(Phase 1 원본은 바꾸지 않았다). - `kubectl apply --dry-run=server`: core PrometheusRule, 백업 kustomization(ScheduledBackup, AIStor ingress, 백업 PrometheusRule), 리허설 Cluster가 모두 admission을 통과한다. - `kubectl patch --dry-run=server`: patch 뒤에도 `techlog` pg_hba 두 줄이 남고 `spec.backup`이 더해진다. - 리허설의 행 수 비교 명령을 운영 DB에서 읽기로만 돌렸다(keycloak 100, techlog 44, gitea 116 표). - 고정 AIStor client로 `quota set`, `admin policy create`, `admin user add`, `admin policy attach` 문법을 오프라인으로 확인했다. - `helm template`(prometheus-node-exporter 4.56.1): 렌더 결과가 `limits.cpu: "1"`이다. - `dockerd --validate`, `systemd-analyze verify`, `docker compose config`: 통과. - PR #2 브랜치: `render-observability-core.sh` PASS, `test-render-observability-core.sh` PASS(단언 216개). - **통과하지 못했거나 돌리지 않은 것:** - `scan-platform-sensitive-source.sh`는 이 브랜치에서도, `origin/main` 스냅숏에서도 똑같이 `renderer failed: observability-core RC=23`으로 멈춘다. 기존 문제이고, 이 변경에 대해서는 아무것도 알려 주지 않는다. - shellcheck는 설치돼 있지 않다. - sudo 단계, bucket·Secret 생성, 클러스터 적용, 복원 리허설은 하지 않았다. ## 리뷰어가 볼 곳 - `services/observability/rules/platform/core-rules.yaml`: 문턱, 예측식, `platform.backup`, `platform.monitoring`. - `services/platform-postgres-backup/README.md`: 적용 순서와 복원 리허설. - `scripts/bootstrap/create-postgres-backup-credentials.sh`: 자격 증명이 화면·로그에 안 남는지. - `infrastructure/host/README.md`: 소유자 명령의 순서와 되돌리기. ## 관련 - design-docs `template-program/README.md` 5절 a·f - 공유 노트 `desktop-disk-recovery-2026-11-09.md` 6절 제안 1~4 - platform-core PR #2 `fix/prometheus-ooo-window`
donghyeon.kang added 16 commits 2026-11-11 22:43:33 +00:00
The kubelet starts deleting unused images at 85% root use and evicts
pods at 90%. The root disk warning fired at 85% and the critical at
90%, so both arrived when the kubelet was already acting. On
2026-11-09 the warning fired for 33 hours, then an eviction stopped
the tech-log pods, the image GC deleted their imagePullPolicy: Never
images, and production went down.

Move the warning to 80% for 10m and the critical to 85% for 5m, and
add PlatformRootFilesystemFillingFast (critical, for 15m): the 6h
linear trend of free bytes falls below 10% of the disk, the eviction
point, within 6 hours. On 2026-11-07 the disk lost 17G in 9 hours;
this forecast would have fired hours before the 80% warning. The
info alert at 75% stays.

Add scripts/validate/test-platform-disk-alerts.sh, promtool unit
tests for the usage bands and the forecast with the pinned Prometheus
image. The existing rules test needs live metric inventories, so this
one runs offline.

Risk: the live rules change only when the observability access apply
runs; this commit does not touch the cluster. The forecast can fire
on a large build that the BuildKit GC removes minutes later; the 15m
hold and the 6h window damp that.

Verification: the new test failed against the old rules (no alert at
81%, 86% or for a 1-per-minute fill) and passes after the change;
promtool check rules finds 9 rules. test-observability-alerting.sh
passes its static contract, then stops at the helm render because
helm v3.19.4 is not installed on the desktop.
The host Docker daemon had no daemon.json. The default BuildKit policy
on this 228GiB disk keeps 21.42GiB of build cache untouched and allows
169.5GiB (docker buildx inspect default), so agent gate builds piled
up about 23G in two days before the 2026-11-09 disk incident.

Add infrastructure/host/docker/daemon.json with builder.gc
defaultReservedSpace 5GB, defaultMaxUsedSpace 15GB and
defaultMinFreeSpace 35GB. In Docker 29 the old defaultKeepStorage key
means defaultReservedSpace, a floor and not a cap, so the cap is
defaultMaxUsedSpace. 35GiB free is about 85% use, where the kubelet
starts deleting images; below it the cache shrinks to the floor first.
Moving the Docker data root to the HDD was rejected by the owner
because builds get slower.

Risk: applying needs sudo and a Docker restart, which restarts the
runner, workmachine and cloudflared and fails running CI jobs and
gates. The host apply guide added in this series says when that is
safe. dockerd --validate does not check keys inside builder.gc, so
the guide checks the live policy with docker buildx inspect.

Verification: dockerd --validate passes for the file on Docker
29.6.1; it also passes a typo inside builder.gc and rejects an unknown
top-level key, which is why the live check is in the guide.
The Docker daemon inside the gitea-runner container keeps every job
image and all build cache in the gitea-runner_docker volume on the
root SSD that production k3s also uses. It grew to 16G in the two days
after the runner was installed and held 12.43G of images and 8.44G of
build cache on 2026-11-11. The README only said to look once a week
and prune by hand.

Mount daemon.json into the runner so the inner BuildKit GC keeps 2GB
to 10GB of build cache, and shrinks to 2GB while the disk has less
than 35GB free. Add gitea-runner-prune.service and .timer, a host
systemd timer for Sunday 04:30 KST that removes unused images created
more than 7 days ago and build cache older than 3 days. The service
runs as donghyeon in the docker group, so it needs root only to
install. A user timer was rejected because lingering is off for
donghyeon and user units stop with the last login session.

Risk: image prune filters on image creation time, so the pinned job
image is deleted weekly and the next job pulls about 543MB again.
Recreating the runner to pick up daemon.json cancels a running job,
so it is done only while the runner is idle.

Verification: systemd-analyze verify passes for both units, and the
calendar expression's next run is Sun 2026-11-15 04:30 KST. docker
compose config passes; dockerd --validate inside the runner (Docker
29.9.3) accepts daemon.json.
The desktop dual-boots Windows, which writes local time (KST) to the
RTC, while Ubuntu reads the RTC as UTC. On 2026-11-11 the boot started
9 hours ahead; k3s issued its certificates at that time, timesyncd
then set the clock back, the certificates were not yet valid, and
every Ingress returned 502 until k3s was restarted by hand.

Add a k3s.service drop-in with Wants= and After=time-sync.target, and
a drop-in that caps systemd-time-wait-sync.service at 10 minutes.
Enabling systemd-time-wait-sync makes time-sync.target wait for the
first NTP sync; its packaged TimeoutStartSec=infinity would keep k3s
down forever when NTP is unreachable, so after 10 minutes it fails,
the target is reached anyway and k3s starts as it does today.

Risk: the order only applies at boot, so nothing changes until the
next reboot. If NTP is down at boot, k3s starts 10 minutes later. The
Windows side still writes local time until RealTimeIsUniversal is set
there; the host guide covers that step.

Verification: systemd-analyze verify passes for k3s.service and
systemd-time-wait-sync.service with the drop-ins, and an unknown key
added to each drop-in is reported, so both files are read.
The host files need root, so agent sessions do not install them. The
owner needs one ordered list with checks and rollback for each step,
including when a Docker restart is safe.

Add infrastructure/host/README.md: why the disk and clock settings
exist, the BuildKit key meanings in Docker 29, and four steps. Pin the
tech-log images against kubelet image GC until they move to the Gitea
registry, install the k3s time-sync drop-ins, set the RTC to UTC on
the Windows side, and install the host daemon.json during a window
with no CI job, no agent gate holding the heavy lock, and workmachine
not in use.

Risk: the image pin is a manual label on the current tags; a new
deployment tag needs the label again until the registry move lands.

Verification: the commands were checked on the desktop where they do
not need root (systemctl show, timedatectl, docker buildx inspect,
docker exec gitea-runner docker ps); the sudo steps were not run.
platform-postgres holds the Gitea, Keycloak and tech-log databases and
had no backup: no spec.backup, no ScheduledBackup, and its only copy
is a local PV on the root SSD. A lost SSD or a bad migration had no
way back.

Add services/platform-postgres-backup: a merge patch that gives the
live Cluster barman-cloud WAL archiving and base backups to
s3://platform-postgres-backups on the AIStor ObjectStore (HDD sdb3)
with 30-day retention and gzip, a daily 03:00 KST ScheduledBackup that
also runs once at creation, the object-storage ingress for the
PostgreSQL pods, the bucket policy, and a restore drill Cluster that
only reads the bucket. scripts/bootstrap/create-postgres-backup-
credentials.sh creates the bucket (100GiB quota), policy, user and
the platform-data Secret through a restricted AIStor client Pod,
proves the user can write its bucket and cannot list loki, and prints
no key. Add PlatformPostgresBackupMissing (no base backup in 26h) and
PlatformPostgresWALArchiveBacklog (more than 10 WAL files waiting for
15m; a stuck archive fills the SSD volume).

The native barmanObjectStore is deprecated since CNPG 1.26 and the
operator warns it is removed in 1.31.0. The Barman Cloud Plugin needs
cert-manager, which this cluster does not have; installing two
operators before the first backup is slower and riskier. The bucket
layout is the same, so the plugin can take over before CNPG 1.31.
Volume snapshots do not work on the static local PV.

Risk: the live Cluster has pg_hba lines for techlog that the Phase 1
source lacks, so re-applying services/platform-postgres would cut the
tech-log backend off. The README applies only spec.backup with
kubectl patch. Backups stay on the same desktop; an off-machine copy
is not part of this change. Nothing was applied to the cluster.

Verification: kubectl apply --dry-run=server accepts the
ScheduledBackup, the NetworkPolicy and the drill Cluster; kubectl
patch --dry-run=server keeps both techlog pg_hba lines and adds
spec.backup. The row-count comparison from the drill steps ran
read-only on production (keycloak 100, techlog 44, gitea 116 tables).
mc command syntax was checked with the pinned AIStor client offline.
The two new alert tests failed against the old rules and pass now.
bash -n passes for the script; shellcheck is not installed on the
laptop or the desktop.
Nothing tells the owner when monitoring itself fails. On 2026-11-11
Prometheus stored samples 9 hours ahead, then rejected every new
sample as out of bounds: rules kept running on no data, and the only
sign was a false KubeAPIDown. If Prometheus, Alertmanager or the node
went down, no rule could fire at all.

Add two rules and one route. PlatformMetricsIngestionStopped fires
when no up sample from node-exporter is stored for 5 minutes;
absent() still fires while the TSDB rejects samples. PlatformHeartbeat
always fires, and a new platform-heartbeat route sends it every 5
minutes to an external dead man's switch through a webhook whose URL
comes from the Secret alertmanager-heartbeat. When the pings stop,
that service alerts, which covers Prometheus, Alertmanager, the node
and the network being down. The chart Watchdog stays disabled; the
platform rule keeps the route inside this repository.

Rejected: an in-cluster CronJob that queries Prometheus and posts to
Alertmanager. It still depends on Alertmanager and the node, and
needs a new workload in the exact observability NetworkPolicy matrix.

Risk: the AlertmanagerConfig now references alertmanager-heartbeat;
applying it before that Secret exists keeps the operator from
rendering the new Alertmanager config. The alerting README orders the
steps: create the external check, create the Secret, then apply.
The heartbeat needs an account on an external service, which only
the owner can create.

Verification: promtool tests for both rules failed against the old
rules and pass now. test-observability-alerting.sh pins the new route
and receiver in its exact contract and passes the static contract,
the global Alertmanager render with Helm v3.19.4 and the server
dry run (--server-dry-run). kubectl apply --dry-run=server accepts
the updated PrometheusRule.
node-exporter averages about 2m CPU, but each scrape runs its
collectors in parallel. With a 250m limit (25ms per 100ms CFS period)
26% of its CFS periods were throttled over 30 minutes on 2026-11-11
(container_cpu_cfs_throttled_periods_total / cfs_periods_total), which
delays scrapes and can make them time out.

Raise the CPU limit to one core. The request stays 100m, so
scheduling does not change, and a runaway collector is still capped.
Removing the limit was rejected because every other workload in this
repository sets one.

Risk: none beyond one core of headroom on a 12-core node. The live
DaemonSet changes only when the observability core is applied again.

Verification: the throttling ratio and usage came from live
Prometheus queries. helm template of prometheus-node-exporter 4.56.1
with these values renders limits.cpu "1". The effect after rollout is
not measured yet.
render-observability-core.sh keeps its own exact copy of the
AlertmanagerConfig, and test-render-observability-core.sh feeds it the
same copy as a fixture. 619b905 added the platform-heartbeat route and
receiver to the source and to test-observability-alerting.sh but not
to these two, so the pinned renderer rejected the source with
"platform AlertmanagerConfig is not the exact global Slack contract".

Add the route and receiver to both copies and name the heartbeat in
the reject message.

Verification: render-observability-core.sh (Helm v3.19.4, kustomize
v5.8.1) prints OBSERVABILITY CORE STATIC RENDER PASS, also with
--verified-output-dir; test-render-observability-core.sh passes.

Fixes: 619b90552f ("feat(observability): alert when Prometheus itself stops working")
The observability core renderer rejects any alert or record whose
name contains "backup" (no_unscoped_monitors_rules): backup
monitoring is outside the observability core by design. f19ce54 put
PlatformPostgresBackupMissing and PlatformPostgresWALArchiveBacklog in
core-rules.yaml, so the pinned renderer failed with "out-of-scope
monitor or rule is present".

Move both alerts unchanged into
services/platform-postgres-backup/prometheus-rule.yaml in
platform-data, which Prometheus reads because the namespace has
observability.hyeonworks.com/enabled=true and the rule has
observability.hyeonworks.com/instance=home. They now point their
runbook_url at the backup README and are applied with the
ScheduledBackup. Renaming them to dodge the filter was rejected: it
would keep backup rules inside a scope that excludes them on purpose.

Verification: test-platform-disk-alerts.sh loads both rule files and
passes; promtool checks 13 rules. render-observability-core.sh and
test-render-observability-core.sh pass, and kubectl apply
--dry-run=server accepts the backup kustomization with the rule.
scan-platform-sensitive-source.sh stops at its observability-core
renderer with RC=23 here and on an origin/main snapshot alike, so it
says nothing about this change.

Fixes: f19ce54740 ("feat(postgres): back up platform-postgres to AIStor every day")
The live platform-postgres Cluster has two pg_hba rules for the techlog
role that the repository does not declare. They were added outside the
repository for hyeonworks.com. Applying the current render would remove
them and the production backend could no longer reach its database.

Declare the same two rules, in the same position after the Keycloak
pair, and pin them with render invariants like the Gitea and Keycloak
pairs. The techlog DatabaseRole, Database, Secret and NetworkPolicies
stay outside this build root; where they belong is an owner decision
recorded in the 2026-11-11 maturity review.

Risk: none for the live cluster. The rendered Cluster now matches the
live object. A fresh install without the tech-log tenant gets two
rules for a role that does not exist, which PostgreSQL ignores.

Verification (desktop, Helm 3.19.4, Kustomize 5.8.1):
- render-phase1.sh with the old cluster.yaml and the new invariants
  fails: "the tech-log role must authenticate only to the tech-log
  database"; with the new cluster.yaml it passes.
- kubectl diff of the new render against the live cluster shows no
  Cluster change; only the pre-existing DatabaseRole default fields.
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.
The host timers from the k3s maturity work (last Gitea dump and k3s
datastore backup, live drift count, API server and kubelet certificate
expiry) write their results as *.prom files. node-exporter does not
read any textfile directory, so Prometheus never sees them.

Pass --collector.textfile.directory pointing at
/var/lib/node_exporter/textfile_collector under the read-only host
root mount the chart already has. No volume is added. The host
installer creates the directory; until then the collector only
reports an error metric.

Verification: helm template of prometheus-node-exporter 4.56.1 with
these values renders the argument next to --path.rootfs=/host/root.
scripts/bootstrap/apply-k3s-restart-bundle.sh now installs the two
time-sync drop-ins and enables systemd-time-wait-sync together with the
kubelet drop-ins, so the owner restarts k3s once. Say so in step 2 and
keep the manual commands for installing only these two files.
The owner asked on 2026-11-12 that production database backups stay
off the SSD. State the evidence that the AIStor volume is the HDD
(aistor-data-local-pv -> /srv/k3s/aistor -> /dev/sdb3, WD20EZAZ,
ROTA=1), why the NTFS archive on sdb2 was not used (no POSIX
permissions, no S3 API, a daily dump gives no point-in-time restore),
and that the restore drill uses a short-lived local-path volume on the
SSD because the HDD has no dynamic StorageClass.
donghyeon.kang merged commit 205927f4e7 into main 2026-11-11 22:43:49 +00:00
Sign in to join this conversation.
No Reviewers
No labels
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: donghyeon.kang/platform-core#10