Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb78ccdb0b | ||
|
|
9e9ea94461 | ||
|
|
ba3dddc139 | ||
|
|
012452cf78 | ||
|
|
77daa39a41 | ||
|
|
b484110b6b | ||
|
|
3eafb7e1d8 | ||
|
|
ebdf33f072 | ||
|
|
c0749ec8a4 | ||
|
|
c2a3f75bc3 | ||
|
|
7580eb7f75 | ||
|
|
4fa02fb43d | ||
|
|
388eb74d4c | ||
|
|
18638f3782 | ||
|
|
497c37b44b | ||
|
|
1c4ef9affd | ||
|
|
41b46f64ea | ||
|
|
af5a90bef8 |
@@ -0,0 +1,21 @@
|
||||
# platform-core 문서 지도
|
||||
|
||||
이 폴더는 이 저장소 안에 두는 기록 문서만 담는다. 아키텍처·운영 절차·결정 기록의
|
||||
정본은 루트 [README](../README.md)가 가리키는 중앙 Platform 문서다. 구성요소의 사용법과
|
||||
적용 절차는 각 디렉터리의 `README.md`와 [`bootstrap/manual/`](../bootstrap/manual/)에 있다.
|
||||
|
||||
| 폴더 | 담는 것 | 수명 |
|
||||
|---|---|---|
|
||||
| [`reviews/`](reviews/) | 점검·리뷰 결과 | 기록(쓴 날의 상태) |
|
||||
| [`platform/plans/`](platform/plans/) | 설계 메모 | 기록 |
|
||||
| [`superpowers/plans/`](superpowers/plans/) | 실행 계획 | 기록 |
|
||||
|
||||
폴더 이름과 수명 구분은 design-docs `conventions/docs-system.md` 2절을 따른다.
|
||||
새 폴더를 만들면 같은 변경에서 이 표에 더한다.
|
||||
|
||||
## 기록 문서의 머리 블록
|
||||
|
||||
`reviews/`에 새로 쓰는 기록은 맨 위에 머리 블록(상태·작성일·요약·현재 정본)을 단다.
|
||||
형식과 상태 어휘는 design-docs `conventions/docs-system.md` 4절이 정본이다. 리뷰의
|
||||
상태는 「진행 중」·「닫힘」 둘이다. 이 절을 만들기 전에 쓴 `platform/plans/`·
|
||||
`superpowers/plans/` 문서에는 머리 블록이 없다.
|
||||
@@ -0,0 +1,496 @@
|
||||
<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->
|
||||
> **기록 · 리뷰** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다.
|
||||
|
||||
- 상태: 진행 중
|
||||
- 작성일: 2026-11-11
|
||||
- 요약: desktop 단일 노드 운영 k3s의 구성 성숙도를 16개 축으로 매기고, 위험 순서의 문제 목록과 drift 표, 점검 도구 결과, 소유자 결정 항목을 정리했다.
|
||||
- 현재 정본: 없음 — 점검 기록이다. 구성의 정본은 루트 `README.md`와 각 디렉터리 `README.md`다.
|
||||
<!-- 머리 블록 끝 -->
|
||||
|
||||
# desktop 운영 k3s 성숙도 점검 (2026-11-11)
|
||||
|
||||
점검 대상은 desktop 한 대(`donghyeon-system-product-name`, k3s `v1.36.2+k3s1`)에서 도는 운영 k3s다. Gitea(소스·CI·패키지), platform-postgres(CNPG), Keycloak, AIStor, 관측 스택, tech-log 운영(hyeonworks.com)이 여기에 있다. 클러스터는 읽기만 했다. 바꾼 것은 이 문서와 같은 PR의 매니페스트 두 가지뿐이고, 적용은 PR 병합 뒤 총괄과 소유자가 정한다.
|
||||
|
||||
이번 주 사고 셋(11-09 디스크 90% 축출, 11-11 RTC +9시간, 그 여파의 Prometheus 정지)과 운영 DB 백업 없음은 W1 세션이 고치는 중이다. 이 문서는 그 항목을 「w1 진행 중」으로만 적고 같은 일을 하지 않는다.
|
||||
|
||||
## 0. 한눈에
|
||||
|
||||
### 0.1 성숙도 단계
|
||||
|
||||
| 단계 | 뜻 |
|
||||
|---|---|
|
||||
| 0 | 장치가 없다 |
|
||||
| 1 | 한 번 손으로 했다. 문서·자동화가 없거나 기억에 기댄다 |
|
||||
| 2 | 선언·문서가 있다. 자동 검사나 리허설은 없다 |
|
||||
| 3 | 선언과 자동 검사(렌더 불변식, 경보)가 있고 대부분에 적용됐다 |
|
||||
| 4 | 정기 리허설·drift 자동 검출이 있어 깨지면 바로 드러난다 |
|
||||
| 5 | 측정으로 개선하고, 흔한 실패는 사람 없이 회복한다 |
|
||||
|
||||
### 0.2 축별 성숙도
|
||||
|
||||
| # | 축 | 단계 | 한 줄 근거 |
|
||||
|---|---|---|---|
|
||||
| A1 | 백업·복구 | **1** | CNPG 백업 0개(w1 진행 중). Gitea 저장소 PV·k3s datastore·AIStor는 백업 자체가 없다. k3s는 2026-08-09 수동 번들 한 번, 복원 리허설 없음 |
|
||||
| A2 | 업그레이드 경로 | **1** | 설치(2026-07-18) 뒤 한 번도 올리지 않았다. v1.36 최신은 v1.36.6(4개 뒤). 절차·사전 백업·되돌리기 문서 없음 |
|
||||
| A3 | 리소스·QoS·축출 | **2** | 대부분 requests·limits 있음. 하지만 kubelet 메모리 축출 문턱·예약(kube/systemReserved)·PriorityClass가 없다. limits 합이 메모리의 95% |
|
||||
| A4 | probe·시작 순서 | **3** | 주요 파드에 probe 있음. 재시작 때 의존 순서(DB → Keycloak → 앱)로 재시작이 몇 번 나지만 1분 안에 스스로 회복 |
|
||||
| A5 | 이미지 출처·pull·서명 | **2** | 관측 스택은 digest 고정. 나머지는 태그만. 운영 이미지 `Never`(w1 진행 중). Keycloak은 가변 태그 + `Always`. 서명 검증 없음 |
|
||||
| A6 | 비밀 값 관리 | **3** | k3s Secret 암호화(aescbc) 켜짐, repo에 Secret 없음, 생성 스크립트가 계약 검사. 키 회전·외부 비밀 저장소 없음. tech-log 비밀은 계약 문서 밖 |
|
||||
| A7 | RBAC·ServiceAccount | **3** | cluster-admin은 k3s 기본 묶음뿐, 장기 SA 토큰 0. 다만 매일 쓰는 kubeconfig가 `system:masters` 인증서(회수 불가) |
|
||||
| A8 | NetworkPolicy | **3** | 플랫폼 namespace 대부분 기본 차단 + 허용 목록. `keycloak`은 ingress 정책 하나뿐, egress 제한 없음 |
|
||||
| A9 | Pod Security | **3** | namespace마다 PSA 라벨(baseline·restricted). 클러스터 기본값 없음. 운영 `hyeonworks-prod`는 라벨이 없어 제한 없음 |
|
||||
| A10 | 컨트롤 플레인·노드 설정 | **2** | anonymous-auth 끔, profiling 끔, API는 127.0.0.1. 감사 로그 없음, `protect-kernel-defaults` 없음, graceful shutdown 꺼짐. kube-bench 결과는 5절 |
|
||||
| A11 | 인증서·시계 | **3** | 인증서 만료 2027-07-18, 클라이언트 인증서 7일 전 경보. kubelet 인증서 경보 둘은 k3s에 지표가 없어 울릴 수 없다. 시계는 w1 진행 중 |
|
||||
| A12 | 저장소 | **2** | 정적 Local PV + Retain. 그런데 DB·Gitea·Prometheus PV가 OS·이미지·빌드 캐시와 같은 SSD 한 장(파티션 하나)에 있다. 용량 격리 없음 |
|
||||
| A13 | 관측·경보 | **3** | 기본 규칙 + 플랫폼 규칙 다수, Slack 전송. Watchdog 꺼짐(w1 진행 중). 백업·인증서 갱신 실패 같은 경보는 대상이 없어서 없다 |
|
||||
| A14 | GitOps 일치(drift) | **1** | GitOps 컨트롤러 없음(`clusters/home` 비어 있음). 손으로 적용. repo 밖에서 `kubectl apply`로 들어간 객체 27개(4절) |
|
||||
| A15 | runbook·복구 문서 | **2** | 구축·전환 runbook은 많다. 그런데 중앙 문서 폴더가 git이 아니고 desktop에만 있다. 호스트 전체를 잃었을 때의 재구축 절차가 없다 |
|
||||
| A16 | 단일 노드 구조·자원 공유 | **1** | 노드 1대, 디스크 1장. 같은 호스트가 CI runner·Gradle·Playwright·데스크톱 앱을 같이 돌린다. 점검 중 노드 CPU 89% |
|
||||
|
||||
### 0.3 위험 상위 10개
|
||||
|
||||
위험 = 일어날 가능성 × 일어났을 때 피해. 크기: 작음(파일 몇 개·되돌리기 쉬움) · 중간(경계 하나 안, 재시작 동반) · 큼(구조·데이터·소유자 결정).
|
||||
|
||||
| 순위 | 문제 | 왜 위험한가 | 고치는 법 | 크기 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | **백업이 하나도 없다** (CNPG는 w1 진행 중. Gitea 저장소 PV 50Gi, k3s datastore, AIStor는 w1 범위 밖) | SSD 한 장이 죽거나 사람이 실수하면 소스·CI·패키지·인증·운영 데이터가 전부 사라진다. timer·cron·CronJob·ScheduledBackup이 0개다 | Gitea: `gitea dump` 또는 PV 스냅숏을 HDD(sdb)와 off-host로. k3s: `state.db`·token 정기 복사. 모두 복원 리허설까지(7.1절) | 큼 |
|
||||
| 2 | **상태 데이터가 OS·빌드와 같은 SSD 파티션에 있다** | `/srv/k3s/ssd/*`(Postgres·Gitea·Prometheus·Loki 등 PV 8개)가 `/dev/sdc1` 루트와 같은 파일시스템이다. 11-09처럼 빌드 캐시가 디스크를 채우면 DB가 WAL을 못 써 멈추고, PV `capacity`는 아무것도 막지 않는다 | 단기: w1의 디스크 상한·경보. 중기: 상태 PV를 별도 파티션이나 디스크로 옮긴다(데이터 이전이라 소유자 결정) | 큼 |
|
||||
| 3 | **메모리가 모자랄 때 보호 장치가 없다** | kubelet `evictionHard`가 디스크 두 항목뿐이라 메모리 축출이 없다. 예약도 없다. 그러면 커널 OOM killer가 고르는데 Postgres `oom_score_adj` 985, Traefik 1000이라 DB와 입구가 먼저 죽는다. 호스트는 CI·Gradle도 같이 돌린다 | kubelet `system-reserved`·`kube-reserved`·`eviction-hard memory.available`·`eviction-soft`(k3s 설정 drop-in, 재시작). Postgres는 requests=limits(Guaranteed)로 | 중간 |
|
||||
| 4 | **repo를 다시 적용하면 운영이 깨지는 drift** | 공용 DB `pg_hba`의 techlog 두 줄이 repo에 없었다. 렌더를 그대로 적용하면 hyeonworks.com backend가 DB에 못 붙는다. tech-log 운영 객체 17개와 플랫폼 쪽 허용 객체 10개도 repo 밖이다 | pg_hba는 고칠 변경을 만들어 **w1에 넘김**(같은 파일을 CNPG 백업이 고친다, 6.1절). 나머지는 둘 곳을 정한다(8절 결정 2) | 작음 + 결정 |
|
||||
| 5 | **감사 로그가 없고, 일상 kubeconfig가 회수 불가 인증서** | 누가 무엇을 바꿨는지 남지 않는다. `~/.kube/config`는 `system:masters` 클라이언트 인증서(2027-07-18까지)라 유출돼도 끌 방법이 CA 교체뿐이다 | k3s `audit-log-path`·audit policy(hardening 가이드), 일상용은 RBAC 바인딩한 별도 사용자, `system:masters`는 비상용 | 중간 |
|
||||
| 6 | **업그레이드 경로가 없다** | v1.36.2에서 멈춰 있다(v1.36.6까지 패치 4개). 올릴 때 쓸 절차·사전 datastore 백업·되돌리기가 없고, CNPG PDB(`disruptionsAllowed: 0`)가 `kubectl drain`을 막는다. Traefik chart도 k3s 버전에 묶여 있다 | runbook: datastore 백업 → 같은 minor 최신 패치 → 검증 목록(Traefik chart·이미지 검사 스크립트 포함). drain 대신 정지·재시작 절차 | 중간 |
|
||||
| 7 | **PriorityClass가 없다** | 플랫폼 파드는 전부 우선순위 0이다. 11-09 디스크 축출 때 tech-log 운영 파드가 grafana·kube-state-metrics와 같은 순위로 내보내졌다 | `platform-critical`(DB·Gitea·Keycloak·운영)과 `platform-low`(관측·관리 도구) 두 개를 만들고 붙인다. 붙이면 파드가 재시작된다 | 중간 |
|
||||
| 8 | **운영 namespace와 Keycloak의 파드 보안이 비어 있다** | `hyeonworks-prod`에 PSA 라벨이 없고 컨테이너 3개 모두 securityContext가 없다(frontend는 root 실행). Keycloak도 securityContext 없음 | `hyeonworks-prod`에 `enforce=baseline`·`warn=restricted`, 컨테이너에 restricted 수준 설정. Keycloak은 CR의 podTemplate로 | 중간 |
|
||||
| 9 | **이미지·원격 매니페스트가 고정돼 있지 않다** | Keycloak Operator 원격 리소스 `?ref=26.7.0`의 내용이 실제로 바뀌었다(라이브 build-timestamp 07-09, 지금 렌더 07-23). Keycloak 두 이미지는 가변 태그 + `Always`라 재시작마다 quay.io에 기대고, 그 사이에 이미지가 바뀔 수 있다 | 원격 ref를 커밋 SHA(`38fd7a0c…`)로, 이미지를 digest로, pull은 `IfNotPresent`로. 렌더·apply 스크립트의 검사 문자열도 같이 | 작음 |
|
||||
| 10 | **복구 문서가 버전 관리 밖, 같은 디스크에 있다** | 중앙 문서(`/home/donghyeon/workspace/docs/platform`, runbook 20개)가 git이 아니고 desktop에만 있다. 디스크를 잃으면 복구 절차도 같이 잃는다. 호스트 전체 재구축 절차가 없다 | 중앙 문서를 Gitea repo로(그 Gitea도 같은 호스트라 off-host 사본도). 재구축 runbook 작성 | 중간 |
|
||||
|
||||
그다음 순위: graceful node shutdown 꺼짐(재부팅 때 DB 정상 종료 보장 없음), `keycloak` namespace egress 무제한, 기본 StorageClass `local-path`(Delete, 루트 디스크)가 살아 있음, Traefik BestEffort(**이 PR에서 고침**), 시작 의존 순서로 인한 재시작.
|
||||
|
||||
## 1. 기준과 점검 방법
|
||||
|
||||
### 1.1 기준
|
||||
|
||||
축은 다음 출처에서 골랐다. 각 축의 조항 번호는 9절 출처 표에 있다.
|
||||
|
||||
- Kubernetes 공식: 보안 체크리스트, 운영 환경 고려 사항, 노드 압박 축출, 노드 종료, RBAC 좋은 관행, 이미지, local 볼륨
|
||||
- NSA/CISA Kubernetes Hardening Guide v1.2(2022-08)
|
||||
- k3s 공식: Hardening Guide, CIS 자기 평가, 백업·복원, 업그레이드, 인증서 회전
|
||||
- CIS Kubernetes Benchmark(k3s 판) — kube-bench로 기계 점검
|
||||
- OpenGitOps 원칙(선언·버전 관리·자동 pull·지속 조정)
|
||||
|
||||
### 1.2 수집한 것 (모두 읽기)
|
||||
|
||||
| 무엇 | 어떻게 |
|
||||
|---|---|
|
||||
| 클러스터 객체 127종 | `kubectl get <종류> -A -o json`. Secret은 이름·타입·키 이름만 |
|
||||
| kubelet 설정 | `kubectl get --raw /api/v1/nodes/<노드>/proxy/configz` |
|
||||
| API 서버 인자 | k3s journal의 `Running kube-apiserver` 줄(비밀 경로·값 제외) |
|
||||
| k3s 설정 | `/etc/rancher/k3s/config.yaml.d/*`(읽기 가능한 두 파일), `systemctl cat k3s` |
|
||||
| 인증서 | `openssl s_client`로 6443·10250, kubeconfig 클라이언트 인증서의 기간 |
|
||||
| repo 렌더 | platform-core `main`(`89e8130`)을 desktop 임시 폴더에 풀고 `scripts/validate/render-{phase1,phase2,admin-services,observability-core}.sh` + Traefik overlay 세 개 |
|
||||
| 값 차이 | 렌더 결과(Secret 제외)로 `kubectl diff`(서버 dry-run, 저장 안 함) |
|
||||
| 점검 도구 | 5절 |
|
||||
|
||||
## 2. 축별 상세
|
||||
|
||||
각 축은 「본 것 → 판단 → 다음 단계로 가려면」 순서다.
|
||||
|
||||
### A1 백업·복구 — 1
|
||||
|
||||
- 본 것:
|
||||
- CNPG `Backup`·`ScheduledBackup` 0개, `Cluster.spec.backup` 없음(w1 진행 중).
|
||||
- Gitea PV `gitea-local-pv` 50Gi(저장소, 패키지, Actions 산출물)를 복사하는 장치가 없다. CNPG 백업은 Gitea DB만 덮고 git 저장소 파일은 덮지 않는다.
|
||||
- k3s datastore는 sqlite(kine, `--etcd-servers=unix://kine.sock`)다. 2026-08-09에 암호화 recovery 번들을 손으로 한 번 만들었다(`bootstrap/manual/k3s-secret-encryption-restore-drill.md`). 격리 환경 복원 리허설·주기 실행·off-host 사본은 그 문서도 「미완료」로 적고 있다.
|
||||
- AIStor(HDD `sdb3`, 19G 사용)는 Loki·Tempo 데이터만 있고 백업이 없다. 잃어도 되는 데이터인지는 정해지지 않았다.
|
||||
- 호스트의 systemd timer·cron·k8s CronJob에 백업 작업이 하나도 없다.
|
||||
- 판단: 복구할 수 있는 것은 노트북 clone에 남은 소스뿐이다. Gitea 패키지(라이브러리 1.0.0 둘), Keycloak realm, 운영 DB는 복구 수단이 없다.
|
||||
- 다음 단계(2): 데이터마다 「무엇을·어디로·얼마나 자주·얼마나 보관」을 표로 정한다. (3): 주기 실행 + 실패 경보. (4): 분기마다 복원 리허설.
|
||||
|
||||
### A2 업그레이드 경로 — 1
|
||||
|
||||
- 본 것: `/usr/local/bin/k3s` 2026-07-18 설치 그대로. 채널 정보(`update.k3s.io`)로 v1.36 최신 v1.36.6, stable v1.37.2. system-upgrade-controller 없음. 업그레이드 runbook 없음. 렌더 도구 버전(Helm 3.19.4, Kustomize 5.8.1)은 스크립트가 정확히 맞는지 검사한다(좋음).
|
||||
- 판단: 패치를 못 따라가고 있고, 올릴 때 무엇을 확인할지 정해 둔 것이 없다. k3s가 Traefik chart(`40.1.3+up40.1.0`)와 coredns·metrics-server·local-path를 같이 바꾸므로, Traefik 검사 스크립트(`common.sh`의 chart·이미지 고정값)가 업그레이드 직후 실패하게 돼 있다. 이건 의도된 멈춤이지만 절차가 없다.
|
||||
- 다음 단계(2): 같은 minor 안 패치 업그레이드 runbook(사전 백업, 검사 목록, 되돌리기 = 이전 바이너리 + datastore 복원). (3): 새 패치가 나오면 알림.
|
||||
|
||||
### A3 리소스·QoS·축출 — 2
|
||||
|
||||
- 본 것:
|
||||
- 컨테이너 40개 중 Traefik·local-path-provisioner 둘만 BestEffort. 나머지는 Burstable(requests·limits 있음). Guaranteed는 없다.
|
||||
- 노드 할당: requests CPU 42%·메모리 34%, limits CPU 176%·메모리 95%.
|
||||
- kubelet: `evictionHard`가 `imagefs.available 5%`·`nodefs.available 5%`뿐이고 `mergeDefaultEvictionSettings: false`라 메모리 축출 문턱이 없다. `systemReserved`·`kubeReserved` 없음(Allocatable = Capacity). `evictionSoft` 없음.
|
||||
- 프로세스 `oom_score_adj`: Traefik 1000, Postgres 985.
|
||||
- PriorityClass: 시스템 기본 둘뿐, 플랫폼 파드는 모두 0. PDB는 CNPG가 만든 `platform-postgres-primary` 하나(`disruptionsAllowed: 0`).
|
||||
- LimitRange·ResourceQuota 없음.
|
||||
- 판단: 디스크 압박은 kubelet이 처리하지만 메모리 압박은 커널이 처리한다. 커널은 requests 비율로 고르므로 메모리 요청이 작은 DB가 거의 첫 대상이다. 같은 호스트의 Gradle·Playwright·runner가 메모리를 잡으면 파드 밖 프로세스 때문에 파드가 죽는다.
|
||||
- 다음 단계(3): 예약·메모리 축출 문턱·PriorityClass·DB Guaranteed. PDB는 노드가 한 대라 가용성을 올리지 못하고 drain만 막으므로 더 만들지 않는다.
|
||||
|
||||
### A4 probe·시작 순서 — 3
|
||||
|
||||
- 본 것: 앱·DB·관측 주요 컨테이너는 liveness·readiness가 있고, 느리게 뜨는 것(Gitea, Keycloak, Prometheus, CNPG, pgAdmin, tech-log backend)은 startup probe도 있다. probe가 없는 것: AIStor operator 둘·MinIO 본 컨테이너(operator가 만듦), alloy liveness, sidecar류.
|
||||
- 11-11 k3s 재시작 때의 재시작: tech-log backend 3(Keycloak 준비 전 OIDC discovery 503), Keycloak 1(Postgres 연결 실패), Tempo 2(MinIO 실패), Gitea init 4(DB·Keycloak 전). 모두 1분 안에 회복(`desktop-pod-recovery-2026-11-11` 공유 노트).
|
||||
- 판단: 의존 순서를 재시작으로 푸는 구조다. 지금은 회복되지만, 재시작 backoff가 길어지면 회복 시간이 늘어난다.
|
||||
- 다음 단계(4): 재부팅 리허설에서 「모든 파드 Ready까지 걸린 시간」을 잰다. tech-log backend는 issuer discovery 대신 endpoint를 직접 주는 안(공유 노트 후보 4).
|
||||
|
||||
### A5 이미지 출처·pull·서명 — 2
|
||||
|
||||
- 본 것: digest 고정은 관측 스택 전부와 pgAdmin, runner. 태그만: CNPG, Postgres, Gitea, Keycloak 둘, AIStor 셋, k3s 구성요소, tech-log 셋(`redis:7-alpine`은 움직이는 태그). `Always`: Keycloak 둘. `Never`: tech-log 둘(w1 진행 중).
|
||||
- Keycloak Operator 원격 kustomize 리소스가 태그 ref다. 지금 렌더한 내용의 `app.quarkus.io/build-timestamp`는 `2026-07-23 07:31:25`, 라이브는 `2026-07-09 07:13:57`이다. 같은 태그가 다른 내용을 준 적이 있다는 뜻이다. 태그 `26.7.0`은 지금 커밋 `38fd7a0c84e15d4b66b37d1c2ea728ca2f5416a4`를 가리킨다.
|
||||
- 서명 검증(admission 정책) 없음.
|
||||
- 다음 단계(3): Keycloak 원격 ref·이미지 digest 고정, `redis` 태그 고정. (4): 서명 검증은 노드 한 대 규모에선 비용 대비 효과가 낮아 마지막.
|
||||
|
||||
### A6 비밀 값 관리 — 3
|
||||
|
||||
- 본 것: `secrets-encryption: true`, provider `aescbc`(drop-in `40-secrets-encryption.yaml`). Kubernetes 문서는 `aescbc`를 「약함」(CBC padding oracle)으로, `secretbox`를 「강함」으로 분류한다. k3s는 `secretbox`를 지원한다. repo에 `kind: Secret` 없음(렌더 스크립트가 검사). 생성 스크립트가 계약(존재·타입·키·교차 namespace 동일성)을 검사한다. Slack webhook은 KeePass 복구 경로가 있다.
|
||||
- 계약 문서 밖 Secret: `platform-data/techlog-db-credentials`, `hyeonworks-prod/hyeonworks-secrets`. 누가 언제 만들었는지 repo에 기록이 없다.
|
||||
- Keycloak `keycloak-initial-admin`이 남아 있다. Operator가 만든 임시 관리자다. 영구 관리자로 바꾸고 지웠는지는 이번에 확인하지 않았다(로그인 필요).
|
||||
- 다음 단계(4): provider를 `secretbox`로 바꾸고 키 회전(`k3s secrets-encrypt rotate-keys`)을 한 번 돌려 본다. 순서를 틀리면 datastore가 복구 불가가 될 수 있다고 문서가 경고하므로 datastore 백업(A1) 뒤에 한다. tech-log 비밀을 계약 문서에 올린다.
|
||||
|
||||
### A7 RBAC·ServiceAccount — 3
|
||||
|
||||
- 본 것: `cluster-admin` 바인딩은 `system:masters`와 k3s helm-controller 작업 SA 둘(k3s 설계). 비밀을 쓰는 권한은 operator들(CNPG, AIStor, prometheus-operator)과 Traefik(읽기)뿐. `kubernetes.io/service-account-token` Secret 0개.
|
||||
- 사람이 쓰는 kubeconfig(`~/.kube/config`)는 `CN=system:admin, O=system:masters` 인증서, 2027-07-18 만료. Kubernetes RBAC 좋은 관행은 `system:masters`를 비상용으로만 쓰라고 한다. 이 그룹은 RBAC·webhook을 모두 건너뛰고 인증서는 개별 회수가 안 된다.
|
||||
- API 토큰이 필요 없는데 마운트된 파드: Gitea(default SA, 토큰 자동 마운트). Gitea egress 허용 목록(DNS, Postgres, `192.168.0.107:443`, 사설 대역을 뺀 `:443`)에 API 서버(`:6443`)가 없어 실제 위험은 작다.
|
||||
- 다음 단계(4): 일상용 사용자(인증서나 OIDC) + `cluster-admin`이 아닌 바인딩, `system:masters` 인증서는 오프라인 보관.
|
||||
|
||||
### A8 NetworkPolicy — 3
|
||||
|
||||
- 본 것: `aistor`·`gitea`·`hyeonworks-prod`·`object-storage`·`observability`·`observability-agent`·`platform-admin`은 기본 차단 + 허용 목록이다. `platform-data`는 ingress 허용 목록(기본 차단 정책 이름은 없지만 Postgres 파드를 고르는 ingress 정책이 있어 그 밖은 막힌다). `keycloak`은 Operator가 만든 ingress 정책 하나뿐이라 egress가 열려 있고 Operator 파드는 정책이 없다. `kube-system`은 Traefik ingress 하나.
|
||||
- 다음 단계(4): `keycloak`에 기본 차단과 egress 허용 목록(DNS, Postgres, API 서버). 정책을 실제로 통과·차단하는지 보는 시험(지금은 렌더 불변식만).
|
||||
|
||||
### A9 Pod Security — 3
|
||||
|
||||
- 본 것: PSA 라벨 — restricted 강제: `observability`·`platform-admin`. baseline 강제(+restricted 경고): `aistor`·`cnpg-system`·`gitea`·`keycloak`·`object-storage`·`platform-data`. privileged: `observability-agent`(node-exporter·alloy가 hostPath 필요). 라벨 없음: `hyeonworks-prod`·`default`·`kube-system`.
|
||||
- API 서버에 PodSecurity admission 설정 파일이 없어 라벨 없는 namespace는 privileged와 같다. k3s hardening 가이드는 클러스터 기본값을 restricted로 두고 예외를 적는 방식을 권한다.
|
||||
- 다음 단계(4): `hyeonworks-prod` 라벨, 클러스터 기본 `baseline` 강제 + `kube-system` 예외.
|
||||
|
||||
### A10 컨트롤 플레인·노드 설정 — 2
|
||||
|
||||
- 본 것(API 서버 인자): `--anonymous-auth=false`, `--profiling=false`, `--bind-address=127.0.0.1`, `--authorization-mode=Node,RBAC`, `--encryption-provider-config` 있음, `--enable-admission-plugins=NodeRestriction`. `--audit-log-*` 없음, admission 설정 파일 없음.
|
||||
- kubelet: anonymous 끔, webhook 인증·인가, `protectKernelDefaults` 없음, `seccompDefault: false`, `shutdownGracePeriod: 0s`(graceful node shutdown 꺼짐), `streamingConnectionIdleTimeout: 4h`.
|
||||
- k3s 설정 파일: `config.yaml`은 없고 drop-in 둘(`30-nodeport-loopback.yaml`, `40-secrets-encryption.yaml`)만 있다. unit의 인자는 `--disable=servicelb` 하나.
|
||||
- 다음 단계(3): k3s hardening 가이드의 `audit-log-*`·`protect-kernel-defaults`(sysctl 먼저)·`kubelet-arg` 묶음을 drop-in 하나로. graceful shutdown(`shutdownGracePeriod` 60s, critical 20s 정도).
|
||||
|
||||
### A11 인증서·시계 — 3
|
||||
|
||||
- 본 것:
|
||||
- API 서버 serving(6443)·관리자 클라이언트 인증서 notAfter 2027-07-18. kubelet serving(10250) 2027-11-11(11-11 재시작 때 새로 발급).
|
||||
- k3s는 만료가 가까운 인증서를 **재시작할 때만** 갱신한다(기간은 9절 출처).
|
||||
- 경보: `KubeClientCertificateExpiration`(API 서버에 들어온 클라이언트 인증서, 7일·1일 전), `PlatformCertificateExpiry`(Host Nginx 공개·사설 엣지, 14일 전).
|
||||
- `KubeletClientCertificateExpiration`·`KubeletServerCertificateExpiration`은 규칙은 있지만 **울릴 수 없다.** k3s kubelet은 `kubelet_certificate_manager_*` 지표를 내지 않는다(`/api/v1/nodes/<노드>/proxy/metrics`에서 0줄). API 서버 serving 인증서를 보는 경보도 없다.
|
||||
- 시계는 w1 진행 중.
|
||||
- 판단: 만료 7일 전 경보 하나에 기대고 있다. 경보를 받고 7일 안에 k3s를 재시작하면 되지만, 재시작 자체가 운영 중단(1~2분)이라 계획할 여유가 짧다.
|
||||
- 다음 단계(4): 6443 serving 인증서를 blackbox로 보고 만료 90일 전에 경고, 계획된 재시작을 runbook에 둔다. 울릴 수 없는 kubelet 인증서 규칙 둘은 끈다.
|
||||
|
||||
### A12 저장소 — 2
|
||||
|
||||
- 본 것:
|
||||
- 디스크: `sdc`(SSD 250GB, 파티션 하나 `/`)에 OS·containerd·Docker·빌드 캐시·`/srv/k3s/ssd`(PV 8개). `sdb3`(HDD xfs 932G)에 AIStor. `sda`(SSD 1TB)는 Windows NTFS. RAID 없음.
|
||||
- StorageClass: 정적 `no-provisioner` + `Retain` + `WaitForFirstConsumer` 10개(좋음). 기본 StorageClass는 k3s `local-path`(Delete, `/var/lib/rancher/k3s/storage`, 루트 디스크)인데 쓰는 PVC가 없다.
|
||||
- 파드 안에서 본 `/var/lib/postgresql/data`는 루트 파일시스템 전체(228G, 67%)다. PV `capacity: 20Gi`는 쓰기를 막지 않는다.
|
||||
- 판단: 정적 PV 구성은 잘 돼 있다. 문제는 물리 배치다. 상태 데이터와 「아무 때나 커지는 것」(이미지, 빌드 캐시)이 한 파일시스템을 나눠 쓴다.
|
||||
- 다음 단계(3): 상태 PV를 별도 파티션(또는 sda 일부)으로. 기본 StorageClass 표시를 없앤다(k3s `--disable=local-storage` 또는 annotation).
|
||||
|
||||
### A13 관측·경보 — 3
|
||||
|
||||
- 본 것: kube-prometheus-stack 기본 규칙 + 플랫폼 규칙(루트 디스크, PVC, 재시작 폭주, OOM, 인증서·엣지 probe, CNPG collector, Loki·Alloy, tech-log). Alertmanager → Slack. `defaultRules.disabled.Watchdog: true`(w1 진행 중).
|
||||
- 빈틈(w1 범위 밖): 백업 성공·실패, k3s datastore 크기, 호스트 Docker·runner 상태, 메모리 압박 중 OOM kill 수(노드 수준 `node_vmstat_oom_kill`)에 대한 경보가 없다. 백업이 생기면 같이 넣어야 한다.
|
||||
- 다음 단계(4): 경보 하나마다 「울렸을 때 할 일」 runbook 링크.
|
||||
|
||||
### A14 GitOps 일치 — 1
|
||||
|
||||
- 본 것: `clusters/home/{applications,projects}`는 `.gitkeep`뿐. Argo CD·Flux 없음. 적용은 `scripts/bootstrap/*.sh`를 사람이 실행. 렌더 스크립트의 불변식은 촘촘하다. 하지만 라이브와 비교하는 자동 검사가 없어 이번 점검 전까지 pg_hba drift를 아무도 몰랐다.
|
||||
- project-gitops·project-infra는 다른 클러스터(dev-k3s, lab)를 겨냥한다. 둘의 선언(Argo CD, Vault, auth-system, forward-auth 등)은 desktop에 하나도 없다.
|
||||
- 다음 단계(2→3): 렌더 → `kubectl diff`를 주기적으로 돌려 차이가 있으면 경보(이번에 쓴 방법을 스크립트로). GitOps 컨트롤러는 그다음.
|
||||
|
||||
### A15 runbook·복구 문서 — 2
|
||||
|
||||
- 본 것: platform-core `bootstrap/manual/` 6개, 중앙 문서 `docs/platform/runbooks` 20개(구축·전환·사고 기록). 중앙 문서 폴더는 git 저장소가 아니고 desktop에만 있다(`README.md.orig`, `platform-overview.md.orig` 같은 편집 잔재도 있다). 이 repo의 README가 그 경로를 정본으로 가리킨다.
|
||||
- 없는 것: 호스트 전체 재구축, k3s datastore 복원, Gitea 복원, 업그레이드, 재부팅 후 확인 순서.
|
||||
- 다음 단계(3): 중앙 문서를 버전 관리 + off-host 사본. 빠진 runbook을 쓰고 새 세션 cold-read로 시험.
|
||||
|
||||
### A16 단일 노드 구조·자원 공유 — 1
|
||||
|
||||
- 본 것: 노드 1대(12 CPU, 32GiB, swap 8GiB). 같은 호스트에서 Gitea Actions runner(privileged dind, job 컨테이너는 비특권), 에이전트 세션의 Gradle·Playwright 게이트, 데스크톱 앱이 돈다. 점검 중 노드 CPU 사용 89%, load average 11~20.
|
||||
- 판단: 이번 주 사고 셋 모두 「같은 호스트의 다른 일」(빌드 캐시, Windows 이중 부팅)이 운영을 넘어뜨린 경우다. 노드를 더하지 않는 한 남는 위험이다.
|
||||
- 다음 단계: 구조를 바꾸는 일이라 8절 결정 4.
|
||||
|
||||
## 3. w1·PR #2와 겹치는 항목
|
||||
|
||||
| 항목 | 지금 상태 | 담당 |
|
||||
|---|---|---|
|
||||
| 디스크 경보 80/85%·6시간 예측, 빌드 캐시 상한, runner 정리 | 브랜치 `claude/vigorous-booth-e9c7b9`, PR 전 | w1 진행 중 |
|
||||
| k3s를 시간 동기화 뒤에 시작, RTC UTC | 같은 브랜치 + 소유자 sudo 단계 | w1 진행 중 |
|
||||
| CNPG `platform-postgres` 백업·WAL을 HDD로, 복원 리허설 | 소유자 결정 i(2026-11-11) | w1 진행 중 |
|
||||
| Prometheus 자기 감시(Watchdog이 `values/home.yaml`에서 꺼져 있음) | — | w1 진행 중 |
|
||||
| node-exporter CPU limit 쓰로틀링 | — | w1 진행 중 |
|
||||
| Prometheus `outOfOrderTimeWindow` 10h | 라이브 적용됨, PR #2가 점검 중 main에 병합됨(`41b46f6`, 2026-11-11 23:18 KST) | 끝남 |
|
||||
| 운영 이미지 `imagePullPolicy: Never` → 레지스트리 | 소유자 단계 C·D | w1 진행 중 |
|
||||
| platform-postgres `pg_hba` techlog 두 줄(이 점검에서 찾은 drift) | 변경 `1c4ef9a` 준비됨. CNPG 백업과 같은 파일이라 이 PR에서는 되돌림(`388eb74`) | w1에 넘김(6.1절) |
|
||||
|
||||
점검 중 본 사실 하나를 w1에 넘긴다: `journalctl --list-boots`를 보면 시작 시각이 끝 시각보다 늦은 부팅이 11-11 말고도 07-18, 10-29에 있다. 시계 +9시간이 처음이 아니다.
|
||||
|
||||
## 4. drift 표
|
||||
|
||||
비교 기준: platform-core `main` `89e8130`(점검 시작 때)의 렌더 결과(objects 312개)와 2026-11-11 23:10 KST 클러스터의 최상위 객체(ownerReference 없는 것, Event·Pod 같은 자동 생성 종류 제외). 값 비교는 Secret을 뺀 렌더 결과로 `kubectl diff`(서버 dry-run)를 돌렸다.
|
||||
|
||||
### 4.1 요약
|
||||
|
||||
| 구분 | 개수 | 뜻 |
|
||||
|---|---|---|
|
||||
| repo에 있고 클러스터에도 있음 | 312 | platform-core 선언은 하나도 빠지지 않고 적용돼 있다 |
|
||||
| 그중 값이 다른 것 | 9 | 4.2(객체 기준. Traefik 행은 drift가 아니라 세지 않음) |
|
||||
| repo에 없는데 클러스터에 있음 — `kubectl apply`로 직접 넣은 것 | 27 (+ Secret 2) | 4.3. 전부 tech-log 운영과 그 허용 객체 |
|
||||
| repo에 없는데 클러스터에 있음 — 정상 | 135 (+ CRD 37) | k3s 내장 구성요소, 기본 RBAC·컨트롤러 SA, operator·StatefulSet이 만든 객체, 계약 Secret(4.4) |
|
||||
| repo에 있는데 클러스터에 없음 | platform-core 0 · project-gitops·project-infra 전부 | 4.5 |
|
||||
|
||||
### 4.2 값이 다른 것
|
||||
|
||||
| 객체 | 라이브 | repo 렌더 | 다시 적용하면 | 처리 |
|
||||
|---|---|---|---|---|
|
||||
| `platform-data` Cluster `platform-postgres` `pg_hba` | techlog 두 줄 있음 | 없음 | **운영 backend가 DB에 못 붙음** | **repo를 라이브에 맞추는 변경을 w1에 넘김(6.1절)** |
|
||||
| `observability` Prometheus `tsdb.outOfOrderTimeWindow` | `10h` | `0s` | 시계가 다시 튀면 수집이 멈춤 | PR #2가 병합돼(`41b46f6`) 지금 main은 라이브와 같다 |
|
||||
| `kube-system` HelmChartConfig `traefik` | trust overlay와 같음 | 루트 `kustomization.yaml`은 observe overlay | 루트로 적용하면 trusted IP가 빠짐 | 의도된 구조(Traefik README). drift 아님 |
|
||||
| `keycloak` Operator Deployment·SA·Service | build-timestamp `2026-07-09` | `2026-07-23` | 라벨만 바뀌고 Operator 재시작 | 원격 ref를 커밋 SHA로(7.4) |
|
||||
| `observability` prometheus-operator·kube-state-metrics 이미지 문자열 | `repo:tag@sha256:…` | `repo@sha256:…`(같은 digest) | 같은 이미지로 재시작 | 낮음. 렌더 경로 확인만 |
|
||||
| `platform-data` DatabaseRole `gitea`·`keycloak` | 기본값 필드 생략 | `bypassrls`·`createdb` 등 `false` 명시 | 값은 같음 | 없음 |
|
||||
|
||||
### 4.3 repo 밖에서 들어간 것 (tech-log 운영)
|
||||
|
||||
모두 `kubectl.kubernetes.io/last-applied-configuration`이 있어 `kubectl apply`로 들어왔다. 어느 repo(platform-core, project-gitops, project-infra, tech-log 두 repo)에도 정본 파일이 없다. w1도 Deployment 쪽을 같은 결론으로 적었다.
|
||||
|
||||
| namespace | 객체 | 개수 |
|
||||
|---|---|---|
|
||||
| (클러스터) | Namespace `hyeonworks-prod` | 1 |
|
||||
| `hyeonworks-prod` | Deployment `techlog-backend`·`techlog-frontend`·`redis`, Service 4(`techlog-backend`·`techlog-frontend`·`techlog-management`·`redis`), Ingress `hyeonworks-core`, ConfigMap `techlog-logging`, ServiceMonitor `techlog-backend`, NetworkPolicy 6 | 16 |
|
||||
| `platform-data` | Database·DatabaseRole `platform-postgres-techlog`, NetworkPolicy `allow-techlog-backend` | 3 |
|
||||
| `object-storage` | NetworkPolicy `allow-techlog-backend` | 1 |
|
||||
| `observability` | Probe `techlog-edge`·`techlog-readiness`, PrometheusRule `techlog`, ConfigMap `grafana-dashboard-techlog`, NetworkPolicy `blackbox-allow-techlog-health`·`observability-allow-techlog-scrape` | 6 |
|
||||
| Secret(계약 문서 밖) | `hyeonworks-prod/hyeonworks-secrets`, `platform-data/techlog-db-credentials` | 2 |
|
||||
|
||||
위험: 이 객체들은 지워져도 다시 만들 원본이 없다. 그리고 플랫폼 쪽 객체(Cluster 등)를 repo대로 다시 적용하면 tech-log 쪽 허용이 사라질 수 있다. pg_hba가 그 예였다.
|
||||
|
||||
### 4.4 repo 밖이지만 정상인 것
|
||||
|
||||
| 무엇 | 예 |
|
||||
|---|---|
|
||||
| k3s 내장(addon, `objectset.rio.cattle.io/hash`) | coredns, metrics-server, local-path-provisioner·StorageClass `local-path`, HelmChart `traefik`·`traefik-crd`, RuntimeClass 10개 |
|
||||
| k3s Traefik chart가 만든 것(Helm) | Deployment·Service·IngressClass·ServiceMonitor `traefik` |
|
||||
| 쿠버네티스 기본 | `cluster-admin`·`admin`·`edit`·`view`, 컨트롤러 SA 약 40개, PriorityClass 둘 |
|
||||
| operator·StatefulSet이 만든 것 | PVC 5(StatefulSet volumeClaimTemplates), `cnpg-default-monitoring`, `minio-aistor-sa`·RoleBinding·PolicyBinding, Service `observability-core-kube-pr-kubelet` |
|
||||
| 계약 Secret(repo에 두지 않는 것이 규칙) | Phase 1·2 계약 8개, 관측·관리 도구 Secret(생성 스크립트가 만듦) |
|
||||
|
||||
### 4.5 repo에 있는데 클러스터에 없는 것
|
||||
|
||||
- platform-core: 없음. `services/gitea`(baseline 프로필)는 신규 설치용이고 라이브는 OIDC 프로필이다(README의 설계).
|
||||
- project-gitops(`e4a7f2a`): Argo CD 부트스트랩·AppProject·ApplicationSet, `auth-system`(Keycloak·Postgres), Vault, `auth-server`·`api-server` 워크로드. 대상 클러스터가 `dev-k3s`이고 desktop에는 하나도 없다.
|
||||
- project-infra(`80f58cd`): Vault, `identity-postgres`, `forward-auth`, Keycloak Operator, `mnt` tenant. 대상이 `lab`이고 desktop에는 하나도 없다(Keycloak Operator는 platform-core 것이 돌고 있다).
|
||||
- 판단: 두 repo는 desktop 운영의 drift 대상이 아니다. 다만 둘 다 「Kubernetes desired state의 정본」을 자처하므로(`project-infra/AGENTS.md`), desktop 운영의 정본이 platform-core라는 것을 어딘가에 한 번 적어야 혼동이 없다(8절 결정 2).
|
||||
|
||||
## 5. 점검 도구 결과
|
||||
|
||||
desktop 호스트 Docker에서 버전을 고정해 돌렸다. 모두 읽기만 했고(kube-bench는 `/etc`·`/var`를 읽기 전용 mount, 나머지는 kubeconfig로 list·get), 끝난 뒤 이미지를 지웠다(`docker image ls`에 남은 것 없음). heavy.lock 앞에 다른 세션 작업이 4개 줄 서 있었고 네 도구 모두 빌드급 부하가 아니어서, lock 대신 `nice -n 10`으로 돌렸다(2026-11-11 14:29~14:33Z).
|
||||
|
||||
| 도구 | 이미지(digest) | 대상 |
|
||||
|---|---|---|
|
||||
| kube-bench | `aquasec/kube-bench:v0.16.0` (`sha256:75506f22…`) | 노드·컨트롤 플레인, 프로필 `k3s-cis-1.9` |
|
||||
| kube-linter | `stackrox/kube-linter:v0.8.3` (`sha256:f2bfce78…`) | repo 렌더 결과(Secret 제외) + 라이브 `hyeonworks-prod` |
|
||||
| Polaris | `quay.io/fairwinds/polaris:10.1.8` (`sha256:7af68852…`) | 라이브 클러스터 |
|
||||
| kubescape | `quay.io/kubescape/kubescape-cli:v4.0.16` (`sha256:d575d4f2…`) | 라이브 클러스터, 프레임워크 NSA·CIS v1.10.0. 결과는 로컬 파일만 |
|
||||
|
||||
버전은 릴리스된 지 2주 넘은 것으로 골랐다(kubescape는 v4.0.20이 최신이지만 5일 전 릴리스라 v4.0.16).
|
||||
|
||||
### 5.1 kube-bench (`k3s-cis-1.9`)
|
||||
|
||||
- 합계: PASS 34 · FAIL 25 · WARN 57 · INFO 14.
|
||||
- **FAIL 25개 중 21개는 도구 쪽 문제다.** 이 이미지에 `journalctl`이 없어서, journal에서 인자를 읽는 항목이 「출력 없음」으로 FAIL이 됐다(1.2.1·1.2.4~1.2.8·1.2.10·1.2.14·1.2.15·1.2.22·1.2.24~1.2.26·1.2.29·1.3.2~1.3.5·1.4.1·1.4.2·4.2.4). 호스트 journal에서 직접 읽은 인자로 판정하면 1.2.26(etcd CA)은 sqlite라 해당 없음이고 나머지 20개는 모두 기준을 만족한다. 4.2.4(read-only port)는 kubelet configz로 0을 확인했다.
|
||||
- **진짜 FAIL 4개:**
|
||||
- 1.1.20 PKI 인증서 파일 권한 644(기준 600). 인증서는 공개 정보라 위험은 낮다. k3s 기본값이다.
|
||||
- 5.1.3 Role·ClusterRole의 wildcard. k3s 내장과 operator 것이다.
|
||||
- 5.1.5 namespace `default` SA의 토큰 자동 마운트를 끄지 않았다. k3s hardening 가이드의 수동 조치 항목이다.
|
||||
- 5.1.6 SA 토큰이 필요 없는 파드에도 마운트된다.
|
||||
- 주목할 WARN(수동 항목): 1.2.16~1.2.19 감사 로그 없음, 1.2.9 EventRateLimit 없음, 1.2.11 AlwaysPullImages 없음(k3s 가이드는 오프라인 운영에 안 맞을 수 있다고 본다), 4.2.13 파드 PID 제한 없음, 5.2.1 클러스터 기본 정책 없음, 5.7.2 seccomp 기본값 없음.
|
||||
- 한계: k3s 공식 CIS 자기 평가는 k3s v1.34~v1.37에 「CIS v2.0」 판을 쓴다. kube-bench v0.16.0의 k3s 프로필은 1.9가 가장 새 것이라 판 차이가 있다. 처음 실행에서 이름 정렬로 옛 프로필 `k3s-cis-1.24`가 골라져 1.9로 다시 돌렸다.
|
||||
|
||||
### 5.2 kube-linter (기본 검사)
|
||||
|
||||
| 대상 | 건수 | 내용 |
|
||||
|---|---|---|
|
||||
| repo 렌더 | 17 | 읽기 전용 루트 FS 아님 9(AIStor operator 셋, Gitea 넷 등), 짝 파드 없는 Service 4(렌더에 파드가 없는 kube-system 대상 등 — 정적 검사 한계), 민감한 hostPath 3(node-exporter `/proc`·`/sys`·`/` — 설계상 필요), `runAsNonRoot` 없음 1(Keycloak Operator) |
|
||||
| 라이브 `hyeonworks-prod` | 6 | 세 Deployment 모두 `runAsNonRoot` 없음, 읽기 전용 루트 FS 아님 |
|
||||
|
||||
### 5.3 Polaris
|
||||
|
||||
- 점수 88(Polaris 산식), 검사 1,134개 중 913개 통과.
|
||||
- 「위험」 등급 23건:
|
||||
- root 실행 허용 6·권한 상승 허용 5: tech-log 셋, Keycloak Operator, coredns·local-path(k3s 내장). 8번 위험과 같은 대상이다.
|
||||
- RBAC 10건: k3s helm 작업 SA의 cluster-admin, CNPG operator의 `pods/exec`, AIStor 바인딩. 모두 upstream 설계다. `loki-clusterrole`은 규칙이 비어 있는데 잡혔다(오탐).
|
||||
- `sensitiveContainerEnvVar` 2건(AIStor `TOKEN_VALIDATION`, Gitea `GITEA_ADMIN_PASSWORD_MODE`): 이름만 걸린 설정값이다(오탐).
|
||||
- 「경고」에서 의미 있는 것: PriorityClass 없음 18, Ingress TLS 없음 6(TLS는 Host Nginx가 끝내는 설계라 해당 없음), Traefik·local-path·metrics-server의 requests·limits 없음.
|
||||
|
||||
### 5.4 kubescape
|
||||
|
||||
- 점수: NSA 71, CIS v1.10.0 48.
|
||||
- 「높음」 실패 중 진짜인 것: 5.7.3 securityContext 없음 28(tech-log·Keycloak·k3s 내장·sidecar), 5.2.2·5.2.11 등 「namespace에 정책 강제 없음」 6(`hyeonworks-prod`, `default`, `kube-system`, `kube-public`, `kube-node-lease`, `observability-agent`), CPU limit 없음 7·메모리 limit 없음 3(tech-log와 k3s 내장).
|
||||
- 오탐: C-0012 「설정 안의 자격 증명」 8건. 값을 보지 않고 형태만 확인했다. env는 이름에 AUTH·KEY가 들어간 모드·ID·URI이고, Loki ConfigMap의 키 둘은 `${…}` env 참조다. 평문 자격 증명은 없다.
|
||||
- 중간 등급 다수(SA 토큰 마운트 18, secret 접근 22 등)는 operator 권한이 대부분이다.
|
||||
|
||||
### 5.5 도구 결과가 판단을 바꾼 곳
|
||||
|
||||
- 도구 넷이 공통으로 가리킨 곳은 `hyeonworks-prod`와 Keycloak의 securityContext, PriorityClass 없음, k3s 내장의 requests·limits 없음이다. 0.3절 7·8번 순위의 근거가 됐다.
|
||||
- kube-bench FAIL 25를 그대로 믿었다면 A10을 1로 매겼을 것이다. journal 인자를 직접 대조하니 컨트롤 플레인 인자는 기준을 만족했고, 빈 곳은 감사 로그·PSA 기본값·kubelet 하드닝뿐이라 2로 두었다.
|
||||
|
||||
## 6. 이 PR에서 고친 것과 넘긴 것
|
||||
|
||||
위험이 낮고 되돌릴 수 있는 매니페스트·문서만 고쳤다. 클러스터에는 아무것도 적용하지 않았다.
|
||||
|
||||
| 변경 | 파일 | 라이브에 적용하면 | 되돌리기 |
|
||||
|---|---|---|---|
|
||||
| Traefik requests `cpu: 50m`·`memory: 64Mi`, limit `memory: 256Mi` | `infrastructure/networking/traefik/base/helm-chart-config.yaml`, overlay patch 둘, `infrastructure/networking/traefik/README.md` | k3s helm-controller가 Traefik을 다시 배포한다(RollingUpdate, 몇 초). 적용은 기존 `apply-trust.sh` | 이전 HelmChartConfig 다시 적용 |
|
||||
| 이 보고서와 `docs/README.md` 지도 | `docs/` | 없음 | — |
|
||||
|
||||
### 6.1 w1에 넘긴 것: platform-postgres `pg_hba`
|
||||
|
||||
CNPG 백업(w1 범위)이 같은 파일 `services/platform-postgres/base/cluster.yaml`을 고친다. 프로그램 규칙상 w1 범위의 파일은 다른 세션이 고치지 않으므로, 이 PR에서 한 번 넣었던 변경(`1c4ef9a`)을 되돌리고(`388eb74`) w1에 넘겼다. w1은 `1c4ef9a`를 그대로 cherry-pick하면 된다.
|
||||
|
||||
- 넣을 것: `pg_hba`의 keycloak 두 줄 다음에 `- host techlog techlog all scram-sha-256`, `- host all techlog all reject`(라이브와 같은 순서). `scripts/validate/render-phase1.sh`에 Gitea·Keycloak 쌍과 같은 형식의 불변식 둘. `services/platform-postgres/README.md`의 `pg_hba` 문단에 techlog 쌍과 그 출처.
|
||||
- 이 변경으로 확인한 것(desktop, 2026-11-11):
|
||||
|
||||
```text
|
||||
$ bash scripts/validate/render-phase1.sh # 수정 전 cluster.yaml + 새 불변식
|
||||
ERROR: the tech-log role must authenticate only to the tech-log database (exit 1)
|
||||
$ bash scripts/validate/render-phase1.sh # 수정 후
|
||||
Phase 1 baseline and Gitea OIDC desired rendering invariants passed. (exit 0)
|
||||
|
||||
$ kubectl diff -f platform-postgres.yaml # 수정 후 렌더 vs 라이브
|
||||
(Cluster 차이 없음. DatabaseRole gitea의 기본값 필드 5줄만 +)
|
||||
```
|
||||
|
||||
- 넣기 전까지는 platform-postgres 렌더를 그대로 적용하지 않는다. 적용하면 hyeonworks.com backend가 DB에 못 붙는다.
|
||||
|
||||
### 6.2 Traefik 렌더 결과
|
||||
|
||||
```text
|
||||
$ kubectl kustomize infrastructure/networking/traefik/overlays/trust | kubectl diff -f -
|
||||
+ resources:
|
||||
+ requests:
|
||||
+ cpu: 50m
|
||||
+ memory: 64Mi
|
||||
+ limits:
|
||||
+ memory: 256Mi
|
||||
|
||||
$ bash infrastructure/networking/traefik/scripts/validate.sh
|
||||
Traefik observation and trust overlays rendered successfully. (exit 0)
|
||||
```
|
||||
|
||||
일부러 넣지 않은 것과 이유:
|
||||
|
||||
- PriorityClass: 붙이는 순간 Postgres·Gitea·Keycloak이 재시작된다. 재시작 시간을 소유자가 정해야 한다(7.2).
|
||||
- PDB 추가: 노드가 한 대라 가용성을 올리지 못하고 drain만 막는다. Kubernetes 문서도 단일 인스턴스는 PDB를 두지 않거나 운영자와 따로 합의하라고 한다.
|
||||
- Keycloak 원격 ref·이미지 고정: `render-phase2.sh`와 운영 적용 스크립트 `apply-keycloak.sh`가 `?ref=26.7.0` 문자열을 검사한다. 적용 스크립트의 방어 조건을 바꾸는 일이라 따로 낸다(7.4).
|
||||
- tech-log 객체 27개를 repo로 옮기기: 둘 곳이 소유자 결정이다(8절 결정 2).
|
||||
|
||||
## 7. 권하는 안과 순서 (바꾸지 않은 것)
|
||||
|
||||
위에서부터 한다. 앞 단계가 뒤 단계의 안전망이다.
|
||||
|
||||
### 7.1 백업을 먼저 (위험 1)
|
||||
|
||||
1. w1의 CNPG 백업이 들어오는 것을 기다린다(같은 HDD 경로를 쓰면 관리가 쉽다).
|
||||
2. Gitea: 주 1회 `gitea dump`(저장소·DB·설정·패키지)를 HDD로. DB는 CNPG가 따로 받으므로 `--skip-db`도 된다. 복원 리허설은 일회용 namespace에서.
|
||||
3. k3s datastore: k3s 문서대로 `/var/lib/rancher/k3s/server/db/`와 `server/token`을 같이 복사한다. token 없이는 백업을 못 쓴다. sqlite라 복사 중 쓰기를 피하려면 `sqlite3 .backup`이 안전하다(문서는 멈춤 여부를 말하지 않는다).
|
||||
4. off-host: HDD는 같은 컴퓨터 안이다. 화재·도난·전원 사고에는 소용없다. 최소 한 사본은 다른 곳으로(암호화).
|
||||
5. 경보: 「마지막 성공 백업이 N시간보다 오래됨」. Google SRE 책의 권고대로 성공 신호가 끊기면 울리게 한다.
|
||||
|
||||
### 7.2 메모리 보호와 우선순위 (위험 3, 7)
|
||||
|
||||
1. k3s drop-in 하나(`/etc/rancher/k3s/config.yaml.d/50-kubelet-reserve.yaml`)로:
|
||||
- `kubelet-arg: system-reserved=cpu=1,memory=2Gi`, `kube-reserved=cpu=500m,memory=1Gi`
|
||||
- `eviction-hard=memory.available<500Mi,nodefs.available<5%,imagefs.available<5%`(디스크 두 항목을 같이 써야 기본값이 0이 되지 않는다)
|
||||
- `eviction-soft=memory.available<1Gi`, `eviction-soft-grace-period=memory.available=1m`
|
||||
- k3s 재시작이 필요하다(운영 1~2분 중단). w1의 time-sync drop-in과 같은 창에 하면 재시작이 한 번이다.
|
||||
2. PriorityClass 둘: `platform-critical`(Postgres·Gitea·Keycloak·tech-log), `platform-low`(Grafana·pgAdmin·Loki·Tempo). 붙이는 변경은 재시작을 부르므로 1과 같은 창에.
|
||||
3. Postgres를 Guaranteed로(requests = limits, 예: CPU 2·메모리 4Gi). `oom_score_adj`가 985에서 -997로 내려간다. 노드 requests가 그만큼 늘어나니 위 예약과 같이 계산한다.
|
||||
|
||||
### 7.3 감사 로그와 관리자 자격 (위험 5)
|
||||
|
||||
1. k3s hardening 가이드의 audit policy(Metadata 수준)와 `audit-log-path`·`maxage=30`·`maxbackup=10`·`maxsize=100`. 로그는 Alloy가 Loki로 보내게 한다(호스트 밖으로는 아직 못 보낸다).
|
||||
2. 일상용 kubeconfig: 사람용 인증서(또는 Keycloak OIDC)를 새로 만들고 `cluster-admin`이 아닌 바인딩. 지금 `system:admin` 인증서는 비상용으로 오프라인 보관.
|
||||
3. 같은 drop-in 창에 `protect-kernel-defaults`(sysctl 먼저 설정), graceful node shutdown(`shutdown-grace-period=60s`, `shutdown-grace-period-critical-pods=20s`).
|
||||
|
||||
### 7.4 업그레이드·공급망 (위험 6, 9)
|
||||
|
||||
1. 업그레이드 runbook: 백업(7.1) → 같은 minor의 최신 패치(v1.36.6) → Traefik chart·이미지 고정값 갱신 → 렌더·`kubectl diff`·스모크 → 실패 시 이전 바이너리 + datastore 복원. minor는 건너뛰지 않는다(쿠버네티스 버전 차이 정책).
|
||||
2. Keycloak Operator `?ref=` 를 커밋 SHA로, Keycloak 두 이미지를 digest로, pull policy `IfNotPresent`. `render-phase2.sh`·`apply-keycloak.sh`의 검사 문자열을 같은 PR에서.
|
||||
3. `redis:7-alpine` → 고정 태그 + digest(tech-log 쪽).
|
||||
|
||||
### 7.5 파드 보안 (위험 8)
|
||||
|
||||
1. `hyeonworks-prod`에 PSA `enforce=baseline`, `warn=restricted`, `audit=restricted`. 먼저 `warn`만 붙여 경고가 없는지 본 뒤 `enforce`.
|
||||
2. tech-log 세 컨테이너에 `runAsNonRoot`, `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]`, `seccompProfile: RuntimeDefault`. frontend 이미지는 root 사용자라 이미지부터 고친다(tech-log-frontend repo).
|
||||
3. 클러스터 PSA 기본값(`admission-control-config-file`): 기본 `baseline` 강제, `kube-system`·`observability-agent` 예외. 7.3의 drop-in 창에.
|
||||
4. `keycloak` namespace 기본 차단 + egress 허용 목록.
|
||||
|
||||
### 7.6 저장소 (위험 2)
|
||||
|
||||
1. 단기(w1): 디스크 상한·경보.
|
||||
2. 중기: 상태 PV(`/srv/k3s/ssd`)를 별도 파일시스템으로. 후보는 sda(1TB SSD, 지금 Windows) 일부를 줄여 만든 파티션이나 새 SSD. 데이터 이전·Windows 디스크 변경이 걸려 소유자 결정(8절 결정 3).
|
||||
3. 기본 StorageClass `local-path`의 기본 표시를 없앤다(k3s `--disable=local-storage`나 annotation). 실수로 만든 PVC가 루트 디스크에 Delete 정책으로 생기는 것을 막는다.
|
||||
|
||||
### 7.7 drift 검출과 문서 (위험 4, 10)
|
||||
|
||||
1. 이번에 손으로 한 「렌더 → `kubectl diff`」를 스크립트로 만들어 하루 한 번 돌리고, 차이가 있으면 경보. GitOps 컨트롤러는 그다음 단계.
|
||||
2. 중앙 문서(`/home/donghyeon/workspace/docs/platform`)를 Gitea repo로 옮기고, off-host 사본을 둔다.
|
||||
3. 새 runbook: 호스트 재구축, datastore 복원, Gitea 복원, 업그레이드, 재부팅 후 확인 순서. 각각 새 세션 cold-read로 시험.
|
||||
4. kubelet 인증서 경보 둘(울릴 수 없음)을 끄고, 6443 serving 인증서 blackbox probe를 넣는다.
|
||||
|
||||
## 8. 소유자 결정이 필요한 것
|
||||
|
||||
| # | 결정 | 권하는 안 | 왜 소유자인가 |
|
||||
|---|---|---|---|
|
||||
| 1 | 백업 범위와 off-host 위치 | Gitea·k3s datastore도 w1 백업과 같은 HDD 경로에 + 암호화 off-host 사본 하나 | 비용·외부 저장소 선택·보관 기간 |
|
||||
| 2 | tech-log 운영 매니페스트의 정본 위치 | 앱 쪽(Deployment·Service·Ingress·ServiceMonitor·앱 NetworkPolicy)은 tech-log repo `deploy/`, 플랫폼 쪽 허용(DB Role·Database·pg_hba·플랫폼 namespace NetworkPolicy·Probe·PrometheusRule·대시보드)은 platform-core에 tenant 단위로. desktop 운영의 정본이 platform-core라는 것을 project-infra·project-gitops README에 한 줄 | 저장소 경계 결정. w1의 이미지 레지스트리 전환(단계 D)과 같은 결정이다 |
|
||||
| 3 | 상태 데이터 디스크 분리 | sda 일부나 새 SSD로 `/srv/k3s/ssd` 이전 | Windows 디스크 변경·데이터 이전·중단 시간 |
|
||||
| 4 | 단일 노드 구조 | 당장은 유지. CI runner와 에이전트 게이트를 다른 기계로 옮기는 것이 노드 추가보다 싸고 효과가 크다 | 하드웨어·비용 |
|
||||
| 5 | k3s 재시작 창 | 7.2·7.3·7.5의 drop-in과 w1의 time-sync drop-in을 한 번의 재시작에 | 운영 중단 시간 |
|
||||
| 6 | AIStor(Loki·Tempo) 데이터 | 잃어도 되는 데이터로 정하고 백업하지 않음 | 보관 정책 |
|
||||
|
||||
## 9. 출처
|
||||
|
||||
| 축 | 출처 | 조항·절 |
|
||||
|---|---|---|
|
||||
| A1 | <https://docs.k3s.io/datastore/backup-restore> | Backup and Restore with SQLite — `db/`와 `token`을 함께 |
|
||||
| A1·A15 | <https://sre.google/sre-book/data-integrity/> | 26장 — 복원이 되는지 정기적으로 증명, 성공 신호가 끊기면 경보 |
|
||||
| A2 | <https://docs.k3s.io/upgrades/manual>, <https://kubernetes.io/releases/version-skew-policy/> | stable 채널 권장, minor 건너뛰기 금지 |
|
||||
| A3 | <https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/> | 기본 문턱, 하나를 바꾸면 나머지가 0이 됨(`MergeDefaultEvictionSettings`), 축출 순위 |
|
||||
| A3 | <https://kubernetes.io/docs/tasks/administer-cluster/reserve-compute-resources/> | kubeReserved·systemReserved |
|
||||
| A3 | <https://kubernetes.io/docs/tasks/run-application/configure-pdb/> | 단일 인스턴스 stateful 앱의 PDB |
|
||||
| A3 | <https://kubernetes.io/docs/concepts/scheduling-eviction/pod-priority-preemption/> | PriorityClass |
|
||||
| A4 | <https://kubernetes.io/docs/concepts/configuration/liveness-readiness-startup-probes/> | probe 종류별 쓰임 |
|
||||
| A5 | <https://kubernetes.io/docs/concepts/containers/images/> | 태그는 움직이고 digest는 고정 |
|
||||
| A5·A7·A8 | <https://kubernetes.io/docs/concepts/security/security-checklist/> | Images, Authentication & Authorization, Network security |
|
||||
| A6 | <https://docs.k3s.io/security/secrets-encryption>, <https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/> | provider 선택, aescbc 「약함」·secretbox 「강함」 |
|
||||
| A7 | <https://kubernetes.io/docs/concepts/security/rbac-good-practices/> | `system:masters`를 쓰지 말 것, 토큰 자동 마운트 끄기 |
|
||||
| A9 | <https://docs.k3s.io/security/hardening-guide> | Pod Security(`psa.yaml`), API Server audit configuration, `protect-kernel-defaults`, NetworkPolicies |
|
||||
| A9·A10 | <https://docs.k3s.io/security/self-assessment-2.0> | k3s v1.34~v1.37용 CIS v2.0 자기 평가(1.2.16~1.2.19 감사, 5.1.5·5.1.6·5.2.1·5.3.2) |
|
||||
| A10 | <https://kubernetes.io/docs/concepts/cluster-administration/node-shutdown/> | `shutdownGracePeriod` 둘 다 0이면 꺼짐 |
|
||||
| A11 | <https://docs.k3s.io/cli/certificate> | 유효 365일, 만료 120일 안이면 시작할 때 갱신(2025-05 릴리스 전에는 90일), `k3s certificate rotate` |
|
||||
| A12 | <https://kubernetes.io/docs/concepts/storage/volumes/#local>, <https://github.com/rancher/local-path-provisioner> | local PV 제약, local-path 용량 제한 없음 |
|
||||
| A13 | <https://runbooks.prometheus-operator.dev/runbooks/general/watchdog/> | Watchdog과 외부 dead man's switch |
|
||||
| A14 | <https://opengitops.dev/> | 원칙 1~4(선언, 버전 관리, 자동 pull, 지속 조정) |
|
||||
| 전체 | <https://kubernetes.io/docs/setup/production-environment/> | 단일 기계는 단일 장애점 |
|
||||
| 전체 | NSA/CISA Kubernetes Hardening Guide v1.2(2022-08), <https://media.defense.gov/2022/Aug/29/2003066362/-1/-1/0/CTR_KUBERNETES_HARDENING_GUIDANCE_1.2_20220829.PDF> | Pod security, Network separation, Authentication and authorization, Audit logging. PDF가 열리지 않아(403) 절 이름은 2차 자료로만 확인했다 |
|
||||
|
||||
CIS 4.2.6(`protect-kernel-defaults`)은 CIS v1.7부터 빠진 번호라 이 문서에서는 번호 없이 k3s hardening 가이드만 근거로 쓴다.
|
||||
|
||||
## 사고 순서 흔적 (크기: 큼)
|
||||
|
||||
1. 목적: 운영과 프로그램 전체 CI가 걸린 단일 노드 k3s의 남은 약점을 사고 전에 찾는다. 성공 기준은 축별 단계와 근거, 위험 순서 목록, drift 표, 도구 결과, 낮은 위험 수정 PR.
|
||||
2. 선행 사례: 이번 주 공유 노트 셋(디스크 복구 11-09, 파드 복구 11-11, w1 재발 방지), 이 repo의 k3s Secret 암호화·recovery drill 문서, k3s hardening 가이드·CIS 자기 평가, NSA/CISA 가이드, Kubernetes 보안 체크리스트·운영 환경 문서, OpenGitOps, Google SRE 26장. 출처는 9절.
|
||||
3. 방법: 체크리스트를 그대로 채우지 않고, 출처의 항목을 「이 노드에서 실제로 일어날 실패」로 묶어 16축으로 만들었다. 도구 점수는 그대로 쓰지 않고 FAIL마다 원인을 대조했다(kube-bench 21개, kubescape C-0012, Polaris RBAC가 오탐이었다). GitOps 컨트롤러 도입 같은 큰 처방은 버리고, 지금 손으로 한 「렌더 → `kubectl diff`」를 자동화하는 것을 먼저 권했다.
|
||||
4. 필요한 정보: 클러스터 객체 127종, kubelet configz, API 서버·컨트롤러 인자(journal), 인증서 기간, 디스크 배치(`lsblk`·`findmnt`), 렌더 결과 312개와 `kubectl diff`, 도구 넷의 결과. 모두 읽기만.
|
||||
5. 격차: 백업 0개, 상태 PV와 빌드가 같은 파일시스템, 메모리 축출 문턱 0, 우선순위 0, repo 밖 객체 27개와 그로 인한 pg_hba drift, 감사 로그 없음, 업그레이드 116일 없음(패치 4개 뒤).
|
||||
6. 만들고 시험:
|
||||
- pg_hba(w1에 넘김): 새 불변식이 수정 전 파일에서 실패(RED)하고 수정 후 통과(GREEN). 수정 후 렌더로 `kubectl diff`하면 Cluster 차이가 없다.
|
||||
- Traefik: `validate.sh` 통과, `kubectl diff`에 resources만 더해진다.
|
||||
- 이 보고서: 반증할 수 있는 가정 — 「repo를 다시 적용해도 운영이 깨지지 않는다」는 w1이 6.1절의 두 줄을 넣은 뒤에는 pg_hba에 대해 참이어야 한다. 남은 반례는 4.3의 객체들이 지워지는 경우다.
|
||||
- 큰 일의 소유자 승인: 소유자 지시 「k3s 구성의 성숙도를 보고 문제 지점을 확인하라」(template-program README 4절 W6, 2026-11-11)를 이 점검의 승인으로 보았다. 구조를 바꾸는 항목은 만들지 않고 8절에 결정으로 올렸다.
|
||||
@@ -76,67 +76,44 @@ Gradle·Docker 게이트는 `flock /tmp/claude-gates/heavy.lock`으로 서로
|
||||
## 디스크와 정리
|
||||
|
||||
안쪽 daemon의 데이터(job 이미지, Testcontainers 이미지, 빌드 cache)는 이름 있는
|
||||
볼륨 `gitea-runner_docker`에 쌓인다. 이 볼륨은 desktop 루트 SSD에 있고, 운영 k3s와
|
||||
같은 디스크다. 설치 이틀 만에 16G가 됐다(2026-11-09: 이미지 12.35G, 빌드 cache 3.4G).
|
||||
2026-11-11에는 이미지 12.43G, 빌드 cache 8.44G였다.
|
||||
볼륨 `gitea-runner_docker`에 쌓인다. desktop root 디스크는 228G 중 182G를 쓰고
|
||||
있다(2026-11-07, 여유 34G). 예상 사용량은 다음과 같다.
|
||||
|
||||
상한은 두 가지로 건다.
|
||||
| 항목 | 크기 |
|
||||
| --- | --- |
|
||||
| runner 이미지(`gitea/runner:5.4.1-dind`) | 약 133MB |
|
||||
| job 이미지(`runner-images:ubuntu-24.04`) | amd64 압축 543MB, 안쪽 daemon에서 2.325GB(2026-11-07 실측) |
|
||||
| Testcontainers 이미지(PostgreSQL, Ryuk 등) | 수백 MB |
|
||||
| actions/cache(`/data/cache`) | 상한 5GB |
|
||||
|
||||
| 무엇 | 방법 | 값 |
|
||||
| --- | --- | --- |
|
||||
| 빌드 cache | `daemon.json`의 BuildKit GC. 안쪽 daemon이 스스로 지운다 | 최소 2GB, 상한 10GB. 디스크 여유가 35GB 아래면 2GB까지 |
|
||||
| job 이미지 | 호스트 systemd timer `gitea-runner-prune.timer`. 주 1회 | 만든 지 7일 지난 안 쓰는 이미지, 3일 지난 빌드 cache |
|
||||
| actions/cache | `config.yaml`의 `cache.size_limit` | 5GB |
|
||||
runner는 job이 끝나면 job 컨테이너와 proxy로 만든 컨테이너·네트워크·볼륨을
|
||||
지우지만(`container.sweep: true`) 이미지는 지우지 않는다. 정리 주기는 다음과 같다.
|
||||
|
||||
- BuildKit 키의 뜻과 값을 고른 이유는 [호스트 설정](../../host/README.md)의
|
||||
「BuildKit 상한 값」에 있다. 호스트와 같은 키에 더 작은 값을 쓴다.
|
||||
- Docker daemon은 이미지를 스스로 지우지 않는다. 그래서 이미지는 timer로 지운다.
|
||||
- `image prune --filter until=168h`는 이미지를 **만든** 시각으로 거른다. 마지막으로 쓴
|
||||
시각이 아니다. 그래서 고정한 job 이미지(`runner-images:ubuntu-24.04`, 2026-11-03 생성)도
|
||||
지워지고, 다음 job이 압축 약 543MB를 다시 받는다. 실행 중인 job 컨테이너가 쓰는
|
||||
이미지는 지워지지 않는다.
|
||||
- timer는 일요일 04:30(KST)에 돈다. 그 시각에 꺼져 있었으면 다음 부팅 때 돈다
|
||||
(`Persistent=true`). service는 `donghyeon` 사용자(docker group)로 돌아 root가 필요 없다.
|
||||
- 매주 한 번 사용량을 본다.
|
||||
|
||||
설치(소유자, sudo 한 번):
|
||||
```bash
|
||||
docker system df -v | grep gitea-runner
|
||||
docker exec gitea-runner docker system df
|
||||
```
|
||||
|
||||
```bash
|
||||
sudo install -m 0644 infrastructure/ci/gitea-runner/gitea-runner-prune.service \
|
||||
infrastructure/ci/gitea-runner/gitea-runner-prune.timer /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now gitea-runner-prune.timer
|
||||
systemctl list-timers gitea-runner-prune.timer
|
||||
```
|
||||
- 안쪽 사용량이 15GB를 넘거나 root 디스크 여유가 20G 아래로 내려가면 job이 없을 때
|
||||
안쪽 이미지를 정리한다. 고정된 job 이미지도 지워지므로 다음 job이 압축 약 543MB를
|
||||
다시 받는다.
|
||||
|
||||
바로 한 번 돌리려면 job이 없을 때 `sudo systemctl start gitea-runner-prune.service`를
|
||||
실행하고 `journalctl -u gitea-runner-prune.service -n 30`으로 결과를 본다.
|
||||
```bash
|
||||
docker exec gitea-runner docker image prune -a -f
|
||||
docker exec gitea-runner docker builder prune -f
|
||||
```
|
||||
|
||||
되돌리기:
|
||||
|
||||
```bash
|
||||
sudo systemctl disable --now gitea-runner-prune.timer
|
||||
sudo rm /etc/systemd/system/gitea-runner-prune.service /etc/systemd/system/gitea-runner-prune.timer
|
||||
sudo systemctl daemon-reload
|
||||
```
|
||||
|
||||
사용량 보기:
|
||||
|
||||
```bash
|
||||
docker system df -v | grep gitea-runner
|
||||
docker exec gitea-runner docker system df
|
||||
docker exec gitea-runner docker buildx inspect default | sed -n '/GC Policy rule#1/,/Min Free/p'
|
||||
```
|
||||
|
||||
볼륨 `gitea-runner_docker` 자체를 지우는 것은 runner를 완전히 지울 때만 한다
|
||||
(「되돌리기」). 등록 파일이 있는 `gitea-runner_data`와 섞지 않는다.
|
||||
- 볼륨 `gitea-runner_docker` 자체를 지우는 것은 runner를 완전히 지울 때만 한다
|
||||
(「되돌리기」). 등록 파일이 있는 `gitea-runner_data`와 섞지 않는다.
|
||||
|
||||
## 파일과 위치
|
||||
|
||||
| 무엇 | 위치 |
|
||||
| --- | --- |
|
||||
| 원본 설정 | 이 디렉터리의 `compose.yaml`, `config.yaml`, `daemon.json` |
|
||||
| 주 1회 정리 | 이 디렉터리의 `gitea-runner-prune.service`·`.timer` → `/etc/systemd/system/` |
|
||||
| desktop 실행 폴더 | `/home/donghyeon/.local/share/gitea-runner/` (`compose.yaml`, `config.yaml`, `daemon.json`, `secrets/`) |
|
||||
| 원본 설정 | 이 디렉터리의 `compose.yaml`, `config.yaml` |
|
||||
| desktop 실행 폴더 | `/home/donghyeon/.local/share/gitea-runner/` (`compose.yaml`, `config.yaml`, `secrets/`) |
|
||||
| 등록 파일 `.runner` | Docker 볼륨 `gitea-runner_data`의 `/data/.runner` (runner 자격 증명, Secret으로 취급) |
|
||||
| job 이미지·안쪽 daemon 데이터 | Docker 볼륨 `gitea-runner_docker` (`/var/lib/docker`) |
|
||||
| actions/cache 저장소 | `gitea-runner_data`의 `/data/cache`, 상한 5GB |
|
||||
@@ -156,10 +133,8 @@ docker exec gitea-runner docker buildx inspect default | sed -n '/GC Policy rule
|
||||
|
||||
```bash
|
||||
install -d -m 0700 ~/.local/share/gitea-runner ~/.local/share/gitea-runner/secrets
|
||||
install -m 0644 infrastructure/ci/gitea-runner/compose.yaml infrastructure/ci/gitea-runner/config.yaml \
|
||||
infrastructure/ci/gitea-runner/daemon.json ~/.local/share/gitea-runner/
|
||||
sha256sum infrastructure/ci/gitea-runner/{compose.yaml,config.yaml,daemon.json} \
|
||||
~/.local/share/gitea-runner/{compose.yaml,config.yaml,daemon.json}
|
||||
install -m 0644 infrastructure/ci/gitea-runner/compose.yaml infrastructure/ci/gitea-runner/config.yaml ~/.local/share/gitea-runner/
|
||||
sha256sum infrastructure/ci/gitea-runner/*.yaml ~/.local/share/gitea-runner/*.yaml
|
||||
```
|
||||
|
||||
2. 등록 token을 편집기로 `~/.local/share/gitea-runner/secrets/registration-token`에
|
||||
@@ -195,7 +170,7 @@ docker exec gitea-runner docker buildx inspect default | sed -n '/GC Policy rule
|
||||
재생성은 실행 중인 job을 취소하므로 job이 없을 때 한다.
|
||||
- 이미지 올리기: `compose.yaml`의 tag와 digest를 함께 바꾼다. 등록 파일은 그대로 유효하다.
|
||||
major가 바뀌면 [Upgrading](https://docs.gitea.com/runner/upgrade/)의 호환 변경을 먼저 읽는다.
|
||||
- 디스크: 「디스크와 정리」의 상한과 timer가 맡는다. 매주 `list-timers`로 마지막 실행을 본다.
|
||||
- 디스크: 「디스크와 정리」의 주기를 따른다.
|
||||
|
||||
## 되돌리기
|
||||
|
||||
|
||||
@@ -22,8 +22,6 @@ services:
|
||||
CONFIG_FILE: /config.yaml
|
||||
volumes:
|
||||
- ./config.yaml:/config.yaml:ro
|
||||
# Caps the build cache of the inner Docker daemon. See README.md.
|
||||
- ./daemon.json:/etc/docker/daemon.json:ro
|
||||
- ./secrets:/run/gitea-runner:ro
|
||||
- data:/data
|
||||
- docker:/var/lib/docker
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"builder": {
|
||||
"gc": {
|
||||
"enabled": true,
|
||||
"defaultReservedSpace": "2GB",
|
||||
"defaultMaxUsedSpace": "10GB",
|
||||
"defaultMinFreeSpace": "35GB"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
# Weekly cleanup of the Docker daemon inside the gitea-runner container.
|
||||
# Installed by infrastructure/ci/gitea-runner/README.md ("디스크와 정리").
|
||||
[Unit]
|
||||
Description=Prune old images and build cache in the Gitea runner Docker
|
||||
Requires=docker.service
|
||||
After=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
# The docker group is enough for docker exec. No root needed at run time.
|
||||
User=donghyeon
|
||||
Group=docker
|
||||
# image prune keeps images used by a running job container; until= filters
|
||||
# on image creation time, so the pinned job image is pulled again after a week.
|
||||
ExecStart=/usr/bin/docker exec gitea-runner docker image prune --all --force --filter until=168h
|
||||
ExecStart=/usr/bin/docker exec gitea-runner docker builder prune --all --force --filter until=72h
|
||||
ExecStartPost=/usr/bin/docker exec gitea-runner docker system df
|
||||
@@ -1,12 +0,0 @@
|
||||
[Unit]
|
||||
Description=Weekly prune of the Gitea runner Docker
|
||||
|
||||
[Timer]
|
||||
# Sunday 04:30 local time (Asia/Seoul), when CI and agent sessions are quiet.
|
||||
OnCalendar=Sun *-*-* 04:30:00
|
||||
RandomizedDelaySec=30min
|
||||
# Run at the next boot if the machine was off at that time.
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -1,184 +0,0 @@
|
||||
# desktop 호스트 설정
|
||||
|
||||
desktop 한 대(k3s 노드 `donghyeon-system-product-name`)는 운영 k3s, Gitea
|
||||
Actions runner, 에이전트 세션의 Docker 게이트를 같이 돌린다. 루트 SSD 하나와
|
||||
시계 하나가 무너지면 운영까지 같이 내려간다. 이 폴더는 그 두 가지를 막는 호스트
|
||||
설정 조각이다. Kubernetes 리소스가 아니므로 `kustomization.yaml`이 없고, root
|
||||
권한으로 아래 경로에 설치한다.
|
||||
|
||||
| 파일 | 설치 경로 | 하는 일 |
|
||||
| --- | --- | --- |
|
||||
| `docker/daemon.json` | `/etc/docker/daemon.json` | 호스트 Docker 빌드 캐시 상한 |
|
||||
| `systemd/k3s.service.d/10-after-time-sync.conf` | `/etc/systemd/system/k3s.service.d/` | k3s를 시간 동기화 뒤에 시작 |
|
||||
| `systemd/systemd-time-wait-sync.service.d/10-timeout.conf` | `/etc/systemd/system/systemd-time-wait-sync.service.d/` | 동기화를 10분까지만 기다림 |
|
||||
|
||||
runner 안쪽 Docker 상한과 주 1회 정리는
|
||||
[`../ci/gitea-runner/README.md`](../ci/gitea-runner/README.md)의 「디스크와 정리」에 있다.
|
||||
|
||||
## 왜 바꾸나
|
||||
|
||||
### 디스크 (2026-11-09 사고)
|
||||
|
||||
- 11-07~08 이틀 동안 에이전트 게이트의 Docker 빌드 캐시가 약 23G 쌓였다. 상한이 없었다.
|
||||
- 루트 사용률 85%에서 kubelet이 안 쓰는 이미지를 지우기 시작했고, 90%(여유 10% 미만)에서
|
||||
파드를 내보냈다. 내보내진 tech-log 파드의 이미지가 「안 쓰는 이미지」가 되어 지워졌고,
|
||||
`imagePullPolicy: Never`라 다시 받지 못했다.
|
||||
- 디스크 경보(85% 경고)는 사고 전 33시간 동안 울렸지만, 이미 kubelet 이미지 GC가 시작되는
|
||||
시점이었다.
|
||||
|
||||
### BuildKit 상한 값
|
||||
|
||||
Docker 29에서 `builder.gc` 키의 뜻은 다음과 같다(moby `daemon/config/builder.go`).
|
||||
|
||||
| 키 | 뜻 | 호스트 값 |
|
||||
| --- | --- | --- |
|
||||
| `defaultReservedSpace` | 이 양 아래로는 지우지 않는다 | 5GB |
|
||||
| `defaultMaxUsedSpace` | 캐시가 이 양을 넘으면 지운다(상한) | 15GB |
|
||||
| `defaultMinFreeSpace` | 디스크 여유가 이 양 아래면 `reservedSpace`까지 지운다 | 35GB |
|
||||
|
||||
- 예전 키 `defaultKeepStorage`는 이제 `defaultReservedSpace`와 같은 뜻이다. 상한이 아니라
|
||||
「최소 보존량」이라 쓰지 않는다.
|
||||
- 설정 전 기본 정책은 `docker buildx inspect default`에서 Reserved 21.42GiB,
|
||||
Max Used 169.5GiB, Min Free 42.84GiB였다(2026-11-11). 캐시가 21GB까지는 전혀 지워지지
|
||||
않았다.
|
||||
- `35GB`는 1024 단위다. 루트 228GiB에서 여유 35GiB는 사용률 약 85%, 즉 kubelet이 이미지를
|
||||
지우기 시작하는 지점이다. 그 전에 빌드 캐시부터 줄인다.
|
||||
- Docker 저장소를 HDD(sdb)로 옮기는 안은 빌드가 느려져 하지 않는다(소유자 결정, 2026-11-11).
|
||||
|
||||
### 시계 (2026-11-11 사고)
|
||||
|
||||
- desktop은 Windows와 이중 부팅한다(`efibootmgr`: Windows Boot Manager, Ubuntu).
|
||||
- Linux는 RTC를 UTC로 읽는다(`timedatectl`: `RTC in local TZ: no`). Windows는 기본값으로
|
||||
RTC에 현지 시각(KST)을 쓴다. 그래서 Windows를 쓴 뒤 Linux로 부팅하면 시계가 9시간 앞선다.
|
||||
- 11-11 부팅이 그 상태로 시작했다(`journalctl --list-boots`의 시작 시각 11-12 04:33 KST).
|
||||
k3s가 그 시각으로 인증서를 만든 뒤 timesyncd가 시계를 되돌렸고, 인증서가 「not yet valid」가
|
||||
되어 전부 502가 됐다. `sudo systemctl restart k3s`로 복구했다.
|
||||
- Prometheus도 그 사이 9시간 앞선 시각의 샘플을 저장했다. 시계가 돌아온 뒤 새 샘플이 전부
|
||||
「out of bounds」로 버려져, 미래 시각을 따라잡을 때까지 지표와 경보가 멈춘다.
|
||||
|
||||
고치는 방법은 둘이다.
|
||||
|
||||
1. **k3s가 시간 동기화 뒤에 시작한다.** `systemd-time-wait-sync.service`는 커널 시계가
|
||||
NTP로 맞춰질 때까지 `time-sync.target`을 막는다. k3s는 `After=time-sync.target`으로 그
|
||||
뒤에 시작한다. 이 서비스는 기본으로 꺼져 있고 끝없이 기다리므로, 켜고 10분 상한을 둔다.
|
||||
10분 안에 NTP에 닿지 못하면 k3s는 지금처럼 그냥 시작한다.
|
||||
2. **Windows도 RTC를 UTC로 쓰게 한다.** 그러면 9시간 차이가 처음부터 생기지 않는다.
|
||||
|
||||
## 소유자가 실행할 명령
|
||||
|
||||
sudo가 필요해 에이전트 세션은 실행하지 않는다. platform-core checkout(이 PR이 병합된
|
||||
main)에서 위에서부터 순서대로 실행한다. 단계마다 확인 명령과 되돌리는 법이 있다.
|
||||
|
||||
### 1. 운영 이미지를 kubelet 이미지 GC에서 지킨다 (재시작 없음, 바로)
|
||||
|
||||
tech-log 이미지를 Gitea 레지스트리로 옮기기 전까지만 쓴다. pinned 라벨이 있는 이미지는
|
||||
kubelet이 지우지 않는다.
|
||||
|
||||
```bash
|
||||
sudo k3s ctr -n k8s.io images label docker.io/library/tech-log-backend:46b1cc7 io.cri-containerd.pinned=pinned
|
||||
sudo k3s ctr -n k8s.io images label docker.io/library/tech-log-frontend:7a4e201 io.cri-containerd.pinned=pinned
|
||||
sudo k3s ctr -n k8s.io images ls | grep -E 'tech-log-(backend|frontend)'
|
||||
```
|
||||
|
||||
마지막 줄의 LABELS 칸에 `io.cri-containerd.pinned=pinned`가 있어야 한다.
|
||||
배포 이미지가 바뀌면 새 tag에 다시 붙인다.
|
||||
|
||||
되돌리기: 라벨 값을 비운다.
|
||||
|
||||
```bash
|
||||
sudo k3s ctr -n k8s.io images label docker.io/library/tech-log-backend:46b1cc7 io.cri-containerd.pinned=
|
||||
sudo k3s ctr -n k8s.io images label docker.io/library/tech-log-frontend:7a4e201 io.cri-containerd.pinned=
|
||||
```
|
||||
|
||||
### 2. k3s를 시간 동기화 뒤에 시작한다 (재시작 없음, 다음 부팅부터)
|
||||
|
||||
```bash
|
||||
sudo install -D -m 0644 infrastructure/host/systemd/k3s.service.d/10-after-time-sync.conf \
|
||||
/etc/systemd/system/k3s.service.d/10-after-time-sync.conf
|
||||
sudo install -D -m 0644 infrastructure/host/systemd/systemd-time-wait-sync.service.d/10-timeout.conf \
|
||||
/etc/systemd/system/systemd-time-wait-sync.service.d/10-timeout.conf
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable systemd-time-wait-sync.service
|
||||
```
|
||||
|
||||
확인:
|
||||
|
||||
```bash
|
||||
systemctl show k3s -p After -p Wants | grep -o time-sync.target
|
||||
systemctl is-enabled systemd-time-wait-sync.service
|
||||
systemctl show systemd-time-wait-sync.service -p TimeoutStartUSec
|
||||
```
|
||||
|
||||
`time-sync.target` 두 줄, `enabled`, `TimeoutStartUSec=10min`이 나와야 한다. 순서는 부팅할
|
||||
때만 쓰이므로 지금 k3s를 다시 시작하지 않는다. 다음 재부팅 뒤
|
||||
`journalctl -b -u systemd-time-wait-sync -u k3s | head`에서 동기화가 k3s 시작보다 앞서는지 본다.
|
||||
|
||||
되돌리기:
|
||||
|
||||
```bash
|
||||
sudo systemctl disable systemd-time-wait-sync.service
|
||||
sudo rm /etc/systemd/system/k3s.service.d/10-after-time-sync.conf \
|
||||
/etc/systemd/system/systemd-time-wait-sync.service.d/10-timeout.conf
|
||||
sudo systemctl daemon-reload
|
||||
```
|
||||
|
||||
### 3. RTC를 UTC로 맞춘다
|
||||
|
||||
Linux 쪽은 이미 UTC다. 확인만 한다.
|
||||
|
||||
```bash
|
||||
timedatectl | grep -e 'RTC in local TZ' -e 'System clock synchronized'
|
||||
```
|
||||
|
||||
`RTC in local TZ: no`가 아니면 `sudo timedatectl set-local-rtc 0`을 실행한다.
|
||||
|
||||
Windows 쪽(다음에 Windows로 부팅했을 때, 관리자 명령 프롬프트):
|
||||
|
||||
```bat
|
||||
reg add "HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" /v RealTimeIsUniversal /t REG_DWORD /d 1 /f
|
||||
```
|
||||
|
||||
그 뒤 Windows 설정 → 시간 및 언어 → 날짜 및 시간 → 「지금 동기화」를 누른다. Windows가
|
||||
RTC를 UTC로 다시 쓴다. Linux로 돌아와 `timedatectl`의 `RTC time`이 `Universal time`과
|
||||
같은지 본다.
|
||||
|
||||
되돌리기(Windows): `reg delete "HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" /v RealTimeIsUniversal /f`
|
||||
|
||||
### 4. 호스트 Docker 빌드 캐시 상한 (Docker 재시작 필요)
|
||||
|
||||
`systemctl restart docker`는 호스트 Docker의 컨테이너를 모두 다시 시작한다. 운영 k3s는
|
||||
자기 containerd를 쓰므로 영향이 없다. 영향을 받는 것:
|
||||
|
||||
| 컨테이너 | 영향 |
|
||||
| --- | --- |
|
||||
| `gitea-runner` | 실행 중인 CI job이 실패한다. `restart: always`로 다시 뜬다 |
|
||||
| `workmachine` | cokacremote 원격 작업이 끊긴다. `unless-stopped`로 다시 뜬다 |
|
||||
| `chatgpt-cloudflared` | 터널이 잠깐 끊긴다. `unless-stopped`로 다시 뜬다 |
|
||||
| 에이전트 세션 게이트 | 돌고 있던 Testcontainers·이미지 빌드가 실패한다 |
|
||||
|
||||
**안전한 때:** 아래 세 가지가 모두 참일 때.
|
||||
|
||||
```bash
|
||||
# 1) CI job이 없다: job 컨테이너가 0개
|
||||
docker exec gitea-runner docker ps --format '{{.Names}}' | wc -l
|
||||
# 2) 에이전트 세션의 무거운 게이트가 없다: lock을 바로 잡을 수 있다
|
||||
flock -n /tmp/claude-gates/heavy.lock true && echo free
|
||||
# 3) workmachine을 지금 쓰고 있지 않다 (소유자 판단)
|
||||
```
|
||||
|
||||
적용은 lock을 잡은 채로 한다. 재시작하는 동안 새 게이트가 시작되지 않는다.
|
||||
|
||||
```bash
|
||||
sudo install -m 0644 infrastructure/host/docker/daemon.json /etc/docker/daemon.json
|
||||
sudo dockerd --validate --config-file /etc/docker/daemon.json
|
||||
flock /tmp/claude-gates/heavy.lock sudo systemctl restart docker
|
||||
docker ps --format '{{.Names}} {{.Status}}'
|
||||
docker buildx inspect default | sed -n '/GC Policy rule#1/,/Min Free/p'
|
||||
```
|
||||
|
||||
`dockerd --validate`는 맨 위 키만 검사하고 `builder.gc` 안쪽 키 오타는 잡지 못한다. 그래서
|
||||
마지막 줄로 실제 정책을 본다. `Reserved Space: 5GiB`, `Max Used Space: 15GiB`,
|
||||
`Min Free Space: 35GiB`가 나와야 한다. 세 컨테이너가 `Up`이어야 한다.
|
||||
|
||||
되돌리기: `sudo rm /etc/docker/daemon.json` 뒤 같은 조건에서 Docker를 다시 시작한다(설치 전에는
|
||||
이 파일이 없었다).
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Back up Gitea (gitea dump --skip-db) to AIStor (platform-host-backups)
|
||||
Documentation=file:///usr/local/lib/platform-backup/README.md
|
||||
After=k3s.service docker.service
|
||||
Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/bin/bash /usr/local/lib/platform-backup/backup/gitea-backup.sh
|
||||
Nice=10
|
||||
IOSchedulingClass=idle
|
||||
TimeoutStartSec=1h
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Weekly Gitea backup
|
||||
|
||||
[Timer]
|
||||
OnCalendar=Sun *-*-* 04:00:00
|
||||
RandomizedDelaySec=10min
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,8 @@
|
||||
[Unit]
|
||||
Description=Record the k3s API server and kubelet serving certificate expiry
|
||||
After=k3s.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=donghyeon
|
||||
ExecStart=/bin/bash /usr/local/lib/platform-backup/validate/k3s-cert-expiry.sh
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Daily k3s certificate expiry check
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 05:00:00
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Back up the k3s datastore and token to AIStor (platform-host-backups)
|
||||
Documentation=file:///usr/local/lib/platform-backup/README.md
|
||||
After=k3s.service docker.service
|
||||
Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/bin/bash /usr/local/lib/platform-backup/backup/k3s-datastore-backup.sh
|
||||
Nice=10
|
||||
IOSchedulingClass=idle
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Daily k3s datastore backup
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 03:30:00
|
||||
RandomizedDelaySec=10min
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,16 @@
|
||||
[Unit]
|
||||
Description=Compare the cluster with platform-core origin/main (kubectl diff, server dry-run)
|
||||
After=k3s.service network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=donghyeon
|
||||
Environment=PLATFORM_HELM_BIN=/home/donghyeon/.local/bin/helm
|
||||
Environment=PLATFORM_CHECKOUT=/home/donghyeon/workspace/platform
|
||||
ExecStart=/bin/bash /usr/local/lib/platform-backup/validate/live-drift-check-main.sh
|
||||
# Exit 1 means "drift found"; the metric and its alert report that. Only 2 (the
|
||||
# check itself failed) marks the unit failed.
|
||||
SuccessExitStatus=1
|
||||
Nice=10
|
||||
TimeoutStartSec=30min
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Daily live drift check
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 05:15:00
|
||||
RandomizedDelaySec=10min
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"builder": {
|
||||
"gc": {
|
||||
"enabled": true,
|
||||
"defaultReservedSpace": "5GB",
|
||||
"defaultMaxUsedSpace": "15GB",
|
||||
"defaultMinFreeSpace": "35GB"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
# Start k3s only after the system clock is synchronized.
|
||||
# k3s writes certificates with the current time at start. If the clock is
|
||||
# wrong at boot (RTC read 9 hours ahead on 2026-11-11) and NTP corrects it
|
||||
# later, those certificates are "not yet valid" and every Ingress returns 502.
|
||||
# time-sync.target is reached only when systemd-time-wait-sync.service is
|
||||
# enabled. See infrastructure/host/README.md.
|
||||
[Unit]
|
||||
Wants=time-sync.target
|
||||
After=time-sync.target
|
||||
@@ -1,5 +0,0 @@
|
||||
# The packaged unit waits forever (TimeoutStartSec=infinity). If NTP is not
|
||||
# reachable at boot, k3s would never start. After 10 minutes this unit fails,
|
||||
# time-sync.target is reached anyway, and k3s starts with the clock it has.
|
||||
[Service]
|
||||
TimeoutStartSec=10min
|
||||
@@ -0,0 +1,38 @@
|
||||
# keycloak namespace NetworkPolicy
|
||||
|
||||
2026-11-11 점검 전 `keycloak` namespace에는 Keycloak Operator가 만든 ingress 정책 하나뿐이었다.
|
||||
Keycloak 파드와 Operator 파드의 egress는 막혀 있지 않았다. 다른 플랫폼 namespace처럼 기본 차단에
|
||||
필요한 것만 연다.
|
||||
|
||||
| 정책 | 대상 | 허용 |
|
||||
| --- | --- | --- |
|
||||
| `keycloak-default-deny` | 모든 파드 | ingress·egress 기본 차단 |
|
||||
| `keycloak-allow-dns` | 모든 파드 | kube-dns 53 |
|
||||
| `keycloak-allow-platform-postgres` | 모든 파드(서버와 realm import Job) | `platform-data` Postgres 5432 |
|
||||
| `keycloak-allow-cluster-peers` | Keycloak 파드 | 같은 Keycloak 파드 JGroups 7800·57800 |
|
||||
| `keycloak-operator-allow-egress` | Operator | API 서버(`10.43.0.1:443`, `192.168.0.107:6443`), Keycloak 8080·9000 |
|
||||
|
||||
- Keycloak 파드의 **ingress**는 계속 Keycloak CR `spec.networkPolicy`로 Operator가 만드는
|
||||
`keycloak-network-policy`가 소유한다(Traefik 8080, 관리 9000, JGroups).
|
||||
- 바깥(인터넷)으로 나가는 길은 없다. 2026-11-12에 repo와 Keycloak CR에 SMTP·외부 IdP 설정이
|
||||
없고, Keycloak 파드의 열린 TCP 연결이 Postgres뿐인 것을 확인했다. SMTP나 외부 IdP를 붙이면
|
||||
여기에 egress를 더해야 한다(안 더하면 메일·외부 로그인만 조용히 실패한다).
|
||||
- kubelet probe는 노드에서 오므로 막히지 않는다.
|
||||
|
||||
## 적용과 확인
|
||||
|
||||
```sh
|
||||
bash scripts/validate/render-tenants-and-policies.sh
|
||||
kubectl kustomize infrastructure/networking/keycloak | kubectl diff -f -
|
||||
kubectl apply -k infrastructure/networking/keycloak
|
||||
```
|
||||
|
||||
적용 뒤 확인(모두 통과해야 한다):
|
||||
|
||||
```sh
|
||||
kubectl -n keycloak get pods
|
||||
curl -fsS -o /dev/null -w '%{http_code}\n' https://id.learn.hyeonworks.com/realms/hyeonworks/.well-known/openid-configuration
|
||||
kubectl -n keycloak logs deploy/keycloak-operator --since=5m | grep -i -E 'error|exception|timeout' || echo no-operator-errors
|
||||
```
|
||||
|
||||
되돌리기: `kubectl delete -k infrastructure/networking/keycloak`(Operator 정책은 남는다).
|
||||
@@ -0,0 +1,12 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
namespace: keycloak
|
||||
|
||||
labels:
|
||||
- pairs:
|
||||
app.kubernetes.io/part-of: platform
|
||||
includeSelectors: false
|
||||
|
||||
resources:
|
||||
- network-policies.yaml
|
||||
@@ -0,0 +1,117 @@
|
||||
# keycloak namespace: 기본 차단 + 필요한 것만 허용.
|
||||
# Keycloak 파드의 ingress는 Keycloak CR(spec.networkPolicy)로 Operator가 만드는
|
||||
# keycloak-network-policy가 계속 소유한다. 여기서는 기본 차단과 egress만 정한다.
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: keycloak-default-deny
|
||||
spec:
|
||||
podSelector: {}
|
||||
policyTypes:
|
||||
- Ingress
|
||||
- Egress
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: keycloak-allow-dns
|
||||
spec:
|
||||
podSelector: {}
|
||||
policyTypes:
|
||||
- Egress
|
||||
egress:
|
||||
- to:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: kube-system
|
||||
podSelector:
|
||||
matchLabels:
|
||||
k8s-app: kube-dns
|
||||
ports:
|
||||
- port: 53
|
||||
protocol: UDP
|
||||
- port: 53
|
||||
protocol: TCP
|
||||
---
|
||||
# Keycloak 서버와 realm import Job이 공용 PostgreSQL에 붙는다.
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: keycloak-allow-platform-postgres
|
||||
spec:
|
||||
podSelector: {}
|
||||
policyTypes:
|
||||
- Egress
|
||||
egress:
|
||||
- to:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: platform-data
|
||||
podSelector:
|
||||
matchLabels:
|
||||
cnpg.io/cluster: platform-postgres
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
---
|
||||
# 같은 Keycloak 인스턴스끼리의 JGroups(7800, 57800). Operator ingress 정책과 짝이다.
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: keycloak-allow-cluster-peers
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app: keycloak
|
||||
app.kubernetes.io/instance: keycloak
|
||||
app.kubernetes.io/managed-by: keycloak-operator
|
||||
policyTypes:
|
||||
- Egress
|
||||
egress:
|
||||
- to:
|
||||
- podSelector:
|
||||
matchLabels:
|
||||
app: keycloak
|
||||
app.kubernetes.io/instance: keycloak
|
||||
app.kubernetes.io/managed-by: keycloak-operator
|
||||
ports:
|
||||
- port: 7800
|
||||
protocol: TCP
|
||||
- port: 57800
|
||||
protocol: TCP
|
||||
---
|
||||
# Operator: Kubernetes API(ClusterIP와 실제 API 서버 주소)와 Keycloak 관리 포트.
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: keycloak-operator-allow-egress
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: keycloak-operator
|
||||
policyTypes:
|
||||
- Egress
|
||||
egress:
|
||||
- to:
|
||||
- ipBlock:
|
||||
cidr: 10.43.0.1/32
|
||||
ports:
|
||||
- port: 443
|
||||
protocol: TCP
|
||||
- to:
|
||||
- ipBlock:
|
||||
cidr: 192.168.0.107/32
|
||||
ports:
|
||||
- port: 6443
|
||||
protocol: TCP
|
||||
- to:
|
||||
- podSelector:
|
||||
matchLabels:
|
||||
app: keycloak
|
||||
app.kubernetes.io/instance: keycloak
|
||||
app.kubernetes.io/managed-by: keycloak-operator
|
||||
ports:
|
||||
- port: 8080
|
||||
protocol: TCP
|
||||
- port: 9000
|
||||
protocol: TCP
|
||||
@@ -101,6 +101,15 @@ infrastructure/networking/traefik/
|
||||
세 overlay는 모두 Service `NodePort`, `externalTrafficPolicy: Cluster`와
|
||||
`30080/30443`을 명시적으로 소유한다.
|
||||
|
||||
세 overlay는 같은 `resources`도 소유한다: requests `cpu: 50m`·`memory: 64Mi`,
|
||||
limit `memory: 256Mi`, CPU limit 없음. k3s 기본 Traefik은 requests·limits가 없는
|
||||
BestEffort다. 이 노드의 kubelet에는 메모리 축출 문턱이 없어(k3s 기본 `evictionHard`는
|
||||
디스크 두 항목뿐) 메모리가 모자라면 커널 OOM killer가 고르는데, BestEffort 컨테이너는
|
||||
`oom_score_adj` 1000이라 가장 먼저 죽는다. 모든 공개 경로가 Traefik 하나를 지나므로
|
||||
Burstable로 올린다. 2026-11-11 실측 사용량은 CPU 약 5m,
|
||||
메모리 약 42Mi다. CPU limit은 throttling을 피하려고 두지 않는다. overlay 둘이
|
||||
`valuesContent`를 통째로 바꾸므로 값을 바꿀 때는 base와 두 patch를 함께 고친다.
|
||||
|
||||
- `baseline`: Service 경계만 남긴다. access log와 forwarded-header trust는 없다.
|
||||
- `observe`: Service 경계와 header를 버리는 JSON access log를 적용한다. trust는 없다.
|
||||
- `trust`: observe 설정에 `web.forwardedHeaders.trustedIPs=10.42.0.1/32`만 추가한다.
|
||||
|
||||
@@ -14,6 +14,12 @@ spec:
|
||||
prometheus.io/path: /metrics
|
||||
prometheus.io/port: "9100"
|
||||
prometheus.io/scrape: "true"
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
memory: 256Mi
|
||||
service:
|
||||
spec:
|
||||
type: NodePort
|
||||
|
||||
@@ -6,6 +6,12 @@
|
||||
prometheus.io/path: /metrics
|
||||
prometheus.io/port: "9100"
|
||||
prometheus.io/scrape: "true"
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
memory: 256Mi
|
||||
service:
|
||||
spec:
|
||||
type: NodePort
|
||||
|
||||
@@ -6,6 +6,12 @@
|
||||
prometheus.io/path: /metrics
|
||||
prometheus.io/port: "9100"
|
||||
prometheus.io/scrape: "true"
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
memory: 256Mi
|
||||
service:
|
||||
spec:
|
||||
type: NodePort
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Back up Gitea (repositories, packages, attachments, Actions data, app.ini) to
|
||||
# AIStor (HDD sdb3). Root only. Run by platform-gitea-backup.timer.
|
||||
#
|
||||
# `gitea dump --skip-db` runs inside the live Gitea container and streams a
|
||||
# tar.gz to stdout (logs go to stderr). The database is backed up separately by
|
||||
# CloudNativePG (services/platform-postgres-backup). The dump contains app.ini,
|
||||
# whose secrets are needed to restore, so the archive is sensitive.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
# shellcheck source=../lib/host-backup.sh
|
||||
source "$(dirname -- "${BASH_SOURCE[0]}")/../lib/host-backup.sh"
|
||||
|
||||
readonly NAME=gitea_backup
|
||||
readonly KCFG=/etc/rancher/k3s/k3s.yaml
|
||||
[[ "$(id -u)" -eq 0 ]] || hb_fail "run as root"
|
||||
hb_load_aistor_env
|
||||
kubectl() { command /usr/local/bin/k3s kubectl --kubeconfig "$KCFG" "$@"; }
|
||||
|
||||
started="$(date +%s)"
|
||||
previous_success="$(awk '/^platform_backup_last_success_timestamp_seconds/ {print $2}' "$TEXTFILE_DIR/$NAME.prom" 2>/dev/null || echo 0)"
|
||||
on_error() {
|
||||
hb_write_metrics "$NAME" <<PROM
|
||||
platform_backup_last_run_success{backup="gitea"} 0
|
||||
platform_backup_last_run_timestamp_seconds{backup="gitea"} $(date +%s)
|
||||
platform_backup_last_success_timestamp_seconds{backup="gitea"} ${previous_success:-0}
|
||||
PROM
|
||||
}
|
||||
trap on_error ERR
|
||||
|
||||
work="$(mktemp -d "$HB_WORK_ROOT/gitea.XXXXXX")"
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
ts="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
archive="gitea-dump-$ts.tar.gz"
|
||||
|
||||
kubectl -n gitea exec deploy/gitea -c gitea -- \
|
||||
gitea dump --skip-db --type tar.gz --file - >"$work/$archive" 2>"$work/dump.log"
|
||||
tar -tzf "$work/$archive" >"$work/list.txt"
|
||||
grep -qx 'app.ini' "$work/list.txt" || hb_fail "the dump has no app.ini"
|
||||
repos="$(grep -c -E '^repos/[^/]+/[^/]+\.git/HEAD$' "$work/list.txt" || true)"
|
||||
(( repos > 0 )) || hb_fail "the dump has no repositories"
|
||||
sha256sum "$work/$archive" | awk '{print $1}' >"$work/$archive.sha256"
|
||||
size="$(stat -c %s "$work/$archive")"
|
||||
# What a restore must match: restore with the same Gitea version (docs/runbooks/gitea-restore.md).
|
||||
{
|
||||
echo "created=$ts"
|
||||
echo "gitea_image=$(kubectl -n gitea get deploy gitea -o jsonpath='{.spec.template.spec.containers[0].image}')"
|
||||
echo "gitea_version=$(kubectl -n gitea exec deploy/gitea -c gitea -- gitea --version 2>/dev/null | awk '{print $3}')"
|
||||
echo "repositories=$repos"
|
||||
} >"$work/$archive.meta"
|
||||
|
||||
hb_mc "$work" cp --quiet "/work/$archive" "/work/$archive.sha256" "/work/$archive.meta" "backup/$AISTOR_BUCKET/gitea/" >/dev/null
|
||||
hb_mc "$work" stat "backup/$AISTOR_BUCKET/gitea/$archive" >/dev/null
|
||||
|
||||
trap - ERR
|
||||
hb_write_metrics "$NAME" <<PROM
|
||||
# HELP platform_backup_last_success_timestamp_seconds Unix time of the last successful backup.
|
||||
# TYPE platform_backup_last_success_timestamp_seconds gauge
|
||||
platform_backup_last_success_timestamp_seconds{backup="gitea"} $(date +%s)
|
||||
platform_backup_last_run_success{backup="gitea"} 1
|
||||
platform_backup_last_run_timestamp_seconds{backup="gitea"} $(date +%s)
|
||||
platform_backup_last_size_bytes{backup="gitea"} $size
|
||||
platform_backup_last_duration_seconds{backup="gitea"} $(( $(date +%s) - started ))
|
||||
# HELP platform_backup_gitea_repositories Repositories in the last successful Gitea dump.
|
||||
# TYPE platform_backup_gitea_repositories gauge
|
||||
platform_backup_gitea_repositories $repos
|
||||
PROM
|
||||
hb_log "gitea backup $archive ($size bytes, $repos repositories) uploaded"
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
# Back up the k3s datastore (sqlite) and the server token to AIStor (HDD sdb3).
|
||||
# Root only. Run by platform-k3s-datastore-backup.timer (infrastructure/host/backup).
|
||||
#
|
||||
# k3s docs (datastore/backup-restore, SQLite): copy server/db and server/token;
|
||||
# the token is required to read the datastore back. `sqlite3 .backup` takes a
|
||||
# consistent copy of the live database.
|
||||
#
|
||||
# Off-host copy (prepared, off by default): set in /etc/platform-backup/aistor.env
|
||||
# OFFHOST_GPG_RECIPIENT_FILE=/etc/platform-backup/offhost-recipient.asc
|
||||
# OFFHOST_RCLONE_TARGET=<rclone remote:path>
|
||||
# The archive is then encrypted to that public key and copied with rclone.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
# shellcheck source=../lib/host-backup.sh
|
||||
source "$(dirname -- "${BASH_SOURCE[0]}")/../lib/host-backup.sh"
|
||||
|
||||
readonly SERVER=/var/lib/rancher/k3s/server
|
||||
readonly NAME=k3s_datastore_backup
|
||||
[[ "$(id -u)" -eq 0 ]] || hb_fail "run as root"
|
||||
command -v sqlite3 >/dev/null || hb_fail "sqlite3 is required"
|
||||
hb_load_aistor_env
|
||||
|
||||
started="$(date +%s)"
|
||||
on_error() {
|
||||
hb_write_metrics "$NAME" <<PROM
|
||||
# HELP platform_backup_last_run_success 1 when the last run of this backup succeeded.
|
||||
# TYPE platform_backup_last_run_success gauge
|
||||
platform_backup_last_run_success{backup="k3s-datastore"} 0
|
||||
platform_backup_last_run_timestamp_seconds{backup="k3s-datastore"} $(date +%s)
|
||||
platform_backup_last_success_timestamp_seconds{backup="k3s-datastore"} ${previous_success:-0}
|
||||
PROM
|
||||
}
|
||||
previous_success="$(awk '/^platform_backup_last_success_timestamp_seconds/ {print $2}' "$TEXTFILE_DIR/$NAME.prom" 2>/dev/null || echo 0)"
|
||||
trap on_error ERR
|
||||
|
||||
work="$(mktemp -d "$HB_WORK_ROOT/k3s.XXXXXX")"
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
ts="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
stage="$work/k3s-datastore-$ts"
|
||||
mkdir -m 0700 "$stage"
|
||||
|
||||
sqlite3 "$SERVER/db/state.db" ".backup '$stage/state.db'"
|
||||
check="$(sqlite3 "$stage/state.db" 'PRAGMA integrity_check;')"
|
||||
[[ "$check" == "ok" ]] || hb_fail "integrity_check on the copy returned: $check"
|
||||
install -m 0600 "$SERVER/token" "$stage/token"
|
||||
{
|
||||
echo "created=$ts"
|
||||
echo "k3s_version=$(/usr/local/bin/k3s --version | head -1)"
|
||||
echo "host=$(hostname)"
|
||||
echo "kine_rows=$(sqlite3 "$stage/state.db" 'SELECT COUNT(*) FROM kine;')"
|
||||
} >"$stage/META"
|
||||
tar -C "$work" -czf "$work/k3s-datastore-$ts.tar.gz" "k3s-datastore-$ts"
|
||||
sha256sum "$work/k3s-datastore-$ts.tar.gz" | awk '{print $1}' >"$work/k3s-datastore-$ts.tar.gz.sha256"
|
||||
size="$(stat -c %s "$work/k3s-datastore-$ts.tar.gz")"
|
||||
|
||||
hb_mc "$work" cp --quiet "/work/k3s-datastore-$ts.tar.gz" "/work/k3s-datastore-$ts.tar.gz.sha256" "backup/$AISTOR_BUCKET/k3s-datastore/" >/dev/null
|
||||
hb_mc "$work" stat "backup/$AISTOR_BUCKET/k3s-datastore/k3s-datastore-$ts.tar.gz" >/dev/null
|
||||
|
||||
# Local copy outside AIStor on the same HDD (sdb3). AIStor runs inside the
|
||||
# cluster this archive restores, so after losing the cluster the AIStor copy
|
||||
# cannot be read until k3s is back; this copy can. The directory sits next to
|
||||
# AIStor's drive directory (data/), so AIStor does not see it as a bucket.
|
||||
readonly LOCAL_DIR=/srv/k3s/aistor/host-backups/k3s-datastore
|
||||
install -d -m 0700 -o root -g root "$(dirname "$LOCAL_DIR")" "$LOCAL_DIR"
|
||||
install -m 0600 "$work/k3s-datastore-$ts.tar.gz" "$work/k3s-datastore-$ts.tar.gz.sha256" "$LOCAL_DIR/"
|
||||
ls -1t "$LOCAL_DIR"/k3s-datastore-*.tar.gz | tail -n +8 | while read -r old; do rm -f -- "$old" "$old.sha256"; done
|
||||
local_copies="$(ls -1 "$LOCAL_DIR"/k3s-datastore-*.tar.gz | wc -l)"
|
||||
|
||||
offhost=0
|
||||
if [[ -n "${OFFHOST_GPG_RECIPIENT_FILE:-}" && -n "${OFFHOST_RCLONE_TARGET:-}" ]]; then
|
||||
command -v rclone >/dev/null || hb_fail "OFFHOST_RCLONE_TARGET is set but rclone is not installed"
|
||||
gpg --batch --yes --trust-model always --recipient-file "$OFFHOST_GPG_RECIPIENT_FILE" \
|
||||
--output "$work/k3s-datastore-$ts.tar.gz.gpg" --encrypt "$work/k3s-datastore-$ts.tar.gz"
|
||||
rclone copyto "$work/k3s-datastore-$ts.tar.gz.gpg" "$OFFHOST_RCLONE_TARGET/k3s-datastore-$ts.tar.gz.gpg"
|
||||
offhost=1
|
||||
fi
|
||||
|
||||
trap - ERR
|
||||
hb_write_metrics "$NAME" <<PROM
|
||||
# HELP platform_backup_last_success_timestamp_seconds Unix time of the last successful backup.
|
||||
# TYPE platform_backup_last_success_timestamp_seconds gauge
|
||||
platform_backup_last_success_timestamp_seconds{backup="k3s-datastore"} $(date +%s)
|
||||
# HELP platform_backup_last_run_success 1 when the last run of this backup succeeded.
|
||||
# TYPE platform_backup_last_run_success gauge
|
||||
platform_backup_last_run_success{backup="k3s-datastore"} 1
|
||||
platform_backup_last_run_timestamp_seconds{backup="k3s-datastore"} $(date +%s)
|
||||
# HELP platform_backup_last_size_bytes Size of the last successful backup archive.
|
||||
# TYPE platform_backup_last_size_bytes gauge
|
||||
platform_backup_last_size_bytes{backup="k3s-datastore"} $size
|
||||
platform_backup_last_duration_seconds{backup="k3s-datastore"} $(( $(date +%s) - started ))
|
||||
# HELP platform_backup_local_copies Archives kept outside AIStor on the HDD.
|
||||
# TYPE platform_backup_local_copies gauge
|
||||
platform_backup_local_copies{backup="k3s-datastore"} $local_copies
|
||||
# HELP platform_backup_offhost_copy 1 when the last run also wrote the encrypted off-host copy.
|
||||
# TYPE platform_backup_offhost_copy gauge
|
||||
platform_backup_offhost_copy{backup="k3s-datastore"} $offhost
|
||||
PROM
|
||||
hb_log "k3s datastore backup k3s-datastore-$ts.tar.gz ($size bytes) uploaded; off-host=$offhost"
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env bash
|
||||
# Create the AIStor bucket, lifecycle rules, policy and user that the host backup
|
||||
# timers use, and the root-only /etc/platform-backup/aistor.env.
|
||||
#
|
||||
# sudo bash scripts/bootstrap/create-host-backup-credentials.sh
|
||||
#
|
||||
# Run once, by the owner, on the desktop. Refuses to run when the env file exists;
|
||||
# never rotates or deletes a bucket, policy, user or object. No key is printed.
|
||||
set -Eeuo pipefail
|
||||
set +x
|
||||
umask 077
|
||||
|
||||
readonly ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
# shellcheck source=../lib/host-backup.sh
|
||||
source "$ROOT/scripts/lib/host-backup.sh"
|
||||
readonly BUCKET=platform-host-backups
|
||||
readonly POLICY=platform-host-backups
|
||||
readonly QUOTA=50GiB
|
||||
readonly POLICY_FILE="$ROOT/services/platform-host-checks/bucket-policy.json"
|
||||
readonly PASS_LINE=PLATFORM_HOST_BACKUP_BOOTSTRAP_PASS
|
||||
kubectl() { command /usr/local/bin/k3s kubectl --kubeconfig /etc/rancher/k3s/k3s.yaml "$@"; }
|
||||
|
||||
[[ "$(id -u)" -eq 0 ]] || hb_fail "run with sudo"
|
||||
for c in docker jq openssl; do command -v "$c" >/dev/null || hb_fail "missing command: $c"; done
|
||||
jq -e . "$POLICY_FILE" >/dev/null || hb_fail "bucket policy is not valid JSON"
|
||||
[[ ! -e "$HOST_BACKUP_ENV" ]] || hb_fail "$HOST_BACKUP_ENV already exists; this script does not rotate it"
|
||||
|
||||
ip="$(kubectl -n object-storage get service minio -o jsonpath='{.spec.clusterIP}')"
|
||||
[[ -n "$ip" ]] || hb_fail "object-storage/minio Service not found"
|
||||
endpoint="http://${ip}:80"
|
||||
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
kubectl -n object-storage get secret aistor-root-configuration -o jsonpath='{.data.config\.env}' | base64 -d >"$work/root.env"
|
||||
grep -q '^export MINIO_ROOT_USER=' "$work/root.env" || hb_fail "aistor-root-configuration has an unexpected format"
|
||||
printf 'pcbackup%s' "$(openssl rand -hex 8)" >"$work/ACCESS_KEY"
|
||||
openssl rand -hex 32 | tr -d '\n' >"$work/SECRET_KEY"
|
||||
cp "$POLICY_FILE" "$work/policy.json"
|
||||
|
||||
printf '%s\n' \
|
||||
"Bucket: $BUCKET (quota $QUOTA; expire gitea/ after 56 days, k3s-datastore/ after 30 days) on $endpoint" \
|
||||
"Policy: $POLICY (${POLICY_FILE#"$ROOT/"})" \
|
||||
"User: a new generated access key attached to $POLICY" \
|
||||
"File: $HOST_BACKUP_ENV (root, 0600)" \
|
||||
'No key value will be printed.'
|
||||
printf 'Type APPLY to create them: '
|
||||
IFS= read -r confirmation
|
||||
[[ "$confirmation" == "APPLY" ]] || hb_fail "confirmation did not match APPLY"
|
||||
|
||||
# Every mc call is silenced so no key reaches the terminal.
|
||||
docker run --rm --network host -v "$work:/run/b:ro" --tmpfs /tmp -e MC_CONFIG_DIR=/tmp/mc \
|
||||
--entrypoint /bin/sh "$MC_IMAGE" -ec '
|
||||
. /run/b/root.env
|
||||
ak="$(cat /run/b/ACCESS_KEY)"; sk="$(cat /run/b/SECRET_KEY)"
|
||||
mc alias set root "'"$endpoint"'" "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" --api S3v4 >/dev/null
|
||||
mc mb --ignore-existing "root/'"$BUCKET"'" >/dev/null
|
||||
mc quota set "root/'"$BUCKET"'" --size "'"$QUOTA"'" >/dev/null
|
||||
mc ilm rule add --prefix gitea/ --expire-days 56 "root/'"$BUCKET"'" >/dev/null
|
||||
mc ilm rule add --prefix k3s-datastore/ --expire-days 30 "root/'"$BUCKET"'" >/dev/null
|
||||
mc admin policy create root "'"$POLICY"'" /run/b/policy.json >/dev/null
|
||||
mc admin user add root "$ak" "$sk" >/dev/null
|
||||
mc admin policy attach root "'"$POLICY"'" --user "$ak" >/dev/null
|
||||
mc alias set backup "'"$endpoint"'" "$ak" "$sk" --api S3v4 >/dev/null
|
||||
probe=".bootstrap-probe-$(date +%s)"
|
||||
printf probe | mc pipe "backup/'"$BUCKET"'/$probe" >/dev/null
|
||||
[ "$(mc cat "backup/'"$BUCKET"'/$probe")" = probe ]
|
||||
mc rm "backup/'"$BUCKET"'/$probe" >/dev/null
|
||||
if mc ls backup/loki >/dev/null 2>&1; then echo "the backup user can list another bucket" >&2; exit 1; fi
|
||||
echo "'"$PASS_LINE"'"' | grep -qx "$PASS_LINE" || hb_fail "bootstrap did not finish; $HOST_BACKUP_ENV was not written"
|
||||
|
||||
install -d -m 0700 -o root -g root "$(dirname "$HOST_BACKUP_ENV")"
|
||||
{
|
||||
echo "AISTOR_BUCKET=$BUCKET"
|
||||
echo "AISTOR_ACCESS_KEY=$(cat "$work/ACCESS_KEY")"
|
||||
echo "AISTOR_SECRET_KEY=$(cat "$work/SECRET_KEY")"
|
||||
echo "# Off-host encrypted copy of the k3s datastore archive (off until both are set):"
|
||||
echo "# OFFHOST_GPG_RECIPIENT_FILE=/etc/platform-backup/offhost-recipient.asc"
|
||||
echo "# OFFHOST_RCLONE_TARGET=remote:path"
|
||||
} >"$HOST_BACKUP_ENV"
|
||||
chmod 0600 "$HOST_BACKUP_ENV"
|
||||
printf '%s\n' "$PASS_LINE" "Created bucket $BUCKET, policy $POLICY, one user and $HOST_BACKUP_ENV."
|
||||
@@ -1,170 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Create the AIStor bucket, policy and user that CloudNativePG uses to back up
|
||||
# platform-postgres, and the platform-data/platform-postgres-backup-s3 Secret.
|
||||
#
|
||||
# Run once, by the owner, from a platform-core checkout on the desktop. The
|
||||
# script refuses to run when the Secret already exists; it never rotates or
|
||||
# deletes a bucket, policy, user or object. No credential value is printed.
|
||||
set -Eeuo pipefail
|
||||
set +x
|
||||
umask 077
|
||||
|
||||
readonly ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
readonly EXPECTED_CONTEXT=default
|
||||
readonly OS_NAMESPACE=object-storage
|
||||
readonly PG_NAMESPACE=platform-data
|
||||
readonly ROOT_SECRET=aistor-root-configuration
|
||||
readonly TARGET_SECRET=platform-postgres-backup-s3
|
||||
readonly BUCKET=platform-postgres-backups
|
||||
readonly POLICY=platform-postgres-backups
|
||||
readonly QUOTA=100GiB
|
||||
readonly S3_ENDPOINT=http://minio.object-storage.svc.cluster.local
|
||||
# Same pinned AIStor client as scripts/validate/aistor-s3-smoke.sh.
|
||||
readonly MC_IMAGE="quay.io/minio/aistor/mc@sha256:c5ec777c080fd6292b7529309a0f311c58c3a92e268c9c57c0901da86881949b"
|
||||
readonly POLICY_FILE="${ROOT}/services/platform-postgres-backup/bucket-policy.json"
|
||||
readonly PASS_LINE=PLATFORM_POSTGRES_BACKUP_BOOTSTRAP_PASS
|
||||
|
||||
fail() {
|
||||
printf 'FAIL: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
for command in kubectl jq openssl; do
|
||||
command -v "$command" >/dev/null || fail "missing command: ${command}"
|
||||
done
|
||||
[[ -f "$POLICY_FILE" ]] || fail "missing ${POLICY_FILE}"
|
||||
jq -e . "$POLICY_FILE" >/dev/null || fail "bucket policy is not valid JSON"
|
||||
|
||||
[[ "$(kubectl config current-context)" == "$EXPECTED_CONTEXT" ]] ||
|
||||
fail "kube context must be ${EXPECTED_CONTEXT}"
|
||||
if kubectl --namespace "$PG_NAMESPACE" get secret "$TARGET_SECRET" >/dev/null 2>&1; then
|
||||
fail "${PG_NAMESPACE}/${TARGET_SECRET} already exists; this script does not rotate it"
|
||||
fi
|
||||
kubectl --namespace "$OS_NAMESPACE" get secret "$ROOT_SECRET" >/dev/null ||
|
||||
fail "${OS_NAMESPACE}/${ROOT_SECRET} is missing"
|
||||
|
||||
work="$(mktemp -d)"
|
||||
pod="pg-backup-bootstrap-$(date +%H%M%S)-$$"
|
||||
handoff_secret="${pod}-keys"
|
||||
policy_map="${pod}-policy"
|
||||
|
||||
cleanup() {
|
||||
kubectl --namespace "$OS_NAMESPACE" delete pod "$pod" \
|
||||
--ignore-not-found --wait=false >/dev/null 2>&1 || true
|
||||
kubectl --namespace "$OS_NAMESPACE" delete secret "$handoff_secret" \
|
||||
--ignore-not-found >/dev/null 2>&1 || true
|
||||
kubectl --namespace "$OS_NAMESPACE" delete configmap "$policy_map" \
|
||||
--ignore-not-found >/dev/null 2>&1 || true
|
||||
rm -rf -- "$work"
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
printf 'pgbackup%s' "$(openssl rand -hex 8)" >"${work}/ACCESS_KEY_ID"
|
||||
openssl rand -hex 32 | tr -d '\n' >"${work}/ACCESS_SECRET_KEY"
|
||||
|
||||
printf '%s\n' \
|
||||
"Bucket: ${BUCKET} (quota ${QUOTA}) on AIStor ${S3_ENDPOINT}" \
|
||||
"Policy: ${POLICY} (${POLICY_FILE#"${ROOT}/"})" \
|
||||
"User: a new generated access key attached to ${POLICY}" \
|
||||
"Secret: ${PG_NAMESPACE}/${TARGET_SECRET} (ACCESS_KEY_ID, ACCESS_SECRET_KEY)" \
|
||||
"Temporary: one restricted client Pod, one Secret and one ConfigMap in ${OS_NAMESPACE}" \
|
||||
'No credential value will be printed.'
|
||||
printf 'Type APPLY to create them: '
|
||||
IFS= read -r confirmation
|
||||
[[ "$confirmation" == "APPLY" ]] || fail "confirmation did not match APPLY"
|
||||
|
||||
kubectl --namespace "$OS_NAMESPACE" create secret generic "$handoff_secret" \
|
||||
--from-file=ACCESS_KEY_ID="${work}/ACCESS_KEY_ID" \
|
||||
--from-file=ACCESS_SECRET_KEY="${work}/ACCESS_SECRET_KEY" >/dev/null
|
||||
kubectl --namespace "$OS_NAMESPACE" create configmap "$policy_map" \
|
||||
--from-file=policy.json="$POLICY_FILE" >/dev/null
|
||||
|
||||
# Every mc call is silenced so neither key reaches the Pod log.
|
||||
bootstrap_command='set -eu
|
||||
. /run/aistor-root/config.env
|
||||
access_key="$(cat /run/backup/ACCESS_KEY_ID)"
|
||||
secret_key="$(cat /run/backup/ACCESS_SECRET_KEY)"
|
||||
mc alias set root "'"$S3_ENDPOINT"'" "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" --api S3v4 >/dev/null
|
||||
mc mb --ignore-existing "root/'"$BUCKET"'" >/dev/null
|
||||
mc quota set "root/'"$BUCKET"'" --size "'"$QUOTA"'" >/dev/null
|
||||
mc admin policy create root "'"$POLICY"'" /run/policy/policy.json >/dev/null
|
||||
mc admin user add root "$access_key" "$secret_key" >/dev/null
|
||||
mc admin policy attach root "'"$POLICY"'" --user "$access_key" >/dev/null
|
||||
mc alias set backup "'"$S3_ENDPOINT"'" "$access_key" "$secret_key" --api S3v4 >/dev/null
|
||||
probe=".bootstrap-probe-$(date +%s)"
|
||||
printf "probe" | mc pipe "backup/'"$BUCKET"'/$probe" >/dev/null
|
||||
[ "$(mc cat "backup/'"$BUCKET"'/$probe")" = "probe" ]
|
||||
mc rm "backup/'"$BUCKET"'/$probe" >/dev/null
|
||||
if mc ls backup/loki >/dev/null 2>&1; then
|
||||
echo "the backup user can list another bucket" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf "%s\n" "'"$PASS_LINE"'"'
|
||||
|
||||
overrides="$(
|
||||
jq -nc --arg command "$bootstrap_command" --arg image "$MC_IMAGE" \
|
||||
--arg root "$ROOT_SECRET" --arg keys "$handoff_secret" --arg policy "$policy_map" '{
|
||||
spec: {
|
||||
automountServiceAccountToken: false,
|
||||
securityContext: {
|
||||
runAsNonRoot: true,
|
||||
runAsUser: 1000,
|
||||
runAsGroup: 1000,
|
||||
fsGroup: 1000,
|
||||
seccompProfile: {type: "RuntimeDefault"}
|
||||
},
|
||||
containers: [{
|
||||
name: "pg-backup-bootstrap",
|
||||
image: $image,
|
||||
imagePullPolicy: "IfNotPresent",
|
||||
command: ["/bin/sh", "-ec"],
|
||||
args: [$command],
|
||||
securityContext: {
|
||||
allowPrivilegeEscalation: false,
|
||||
capabilities: {drop: ["ALL"]},
|
||||
readOnlyRootFilesystem: true
|
||||
},
|
||||
env: [{name: "MC_CONFIG_DIR", value: "/tmp/mc"}],
|
||||
volumeMounts: [
|
||||
{name: "root-config", mountPath: "/run/aistor-root", readOnly: true},
|
||||
{name: "backup-keys", mountPath: "/run/backup", readOnly: true},
|
||||
{name: "policy", mountPath: "/run/policy", readOnly: true},
|
||||
{name: "tmp", mountPath: "/tmp"}
|
||||
]
|
||||
}],
|
||||
volumes: [
|
||||
{name: "root-config", secret: {secretName: $root, defaultMode: 256}},
|
||||
{name: "backup-keys", secret: {secretName: $keys, defaultMode: 256}},
|
||||
{name: "policy", configMap: {name: $policy}},
|
||||
{name: "tmp", emptyDir: {}}
|
||||
]
|
||||
}
|
||||
}'
|
||||
)"
|
||||
|
||||
kubectl --namespace "$OS_NAMESPACE" run "$pod" \
|
||||
--image="$MC_IMAGE" \
|
||||
--restart=Never \
|
||||
--labels='platform.hyeonworks.com/aistor-client=true,app.kubernetes.io/name=pg-backup-bootstrap' \
|
||||
--overrides="$overrides" >/dev/null
|
||||
|
||||
phase=''
|
||||
for _ in $(seq 1 90); do
|
||||
phase="$(kubectl --namespace "$OS_NAMESPACE" get pod "$pod" --output=jsonpath='{.status.phase}')"
|
||||
[[ "$phase" == "Succeeded" || "$phase" == "Failed" ]] && break
|
||||
sleep 2
|
||||
done
|
||||
logs="$(kubectl --namespace "$OS_NAMESPACE" logs "$pod" 2>&1 || true)"
|
||||
if [[ "$phase" != "Succeeded" || "$logs" != *"$PASS_LINE"* ]]; then
|
||||
printf '%s\n' "$logs" | tail -20 >&2
|
||||
fail "bootstrap Pod ended in phase '${phase}'; the platform-data Secret was not created"
|
||||
fi
|
||||
|
||||
kubectl --namespace "$PG_NAMESPACE" create secret generic "$TARGET_SECRET" \
|
||||
--from-file=ACCESS_KEY_ID="${work}/ACCESS_KEY_ID" \
|
||||
--from-file=ACCESS_SECRET_KEY="${work}/ACCESS_SECRET_KEY" >/dev/null
|
||||
kubectl --namespace "$PG_NAMESPACE" label secret "$TARGET_SECRET" \
|
||||
app.kubernetes.io/part-of=platform app.kubernetes.io/component=platform-postgres-backup >/dev/null
|
||||
|
||||
printf '%s\n' "$PASS_LINE" \
|
||||
"Created bucket ${BUCKET}, policy ${POLICY}, one user and ${PG_NAMESPACE}/${TARGET_SECRET}."
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install the host backup and check timers (infrastructure/host/backup).
|
||||
#
|
||||
# bash scripts/bootstrap/install-host-checks.sh --check # no root, changes nothing
|
||||
# sudo bash scripts/bootstrap/install-host-checks.sh --execute # install, enable, first runs
|
||||
#
|
||||
# Scripts are copied to /usr/local/lib/platform-backup (root-owned) so the root
|
||||
# timers never execute files the desktop user can edit.
|
||||
set -Eeuo pipefail
|
||||
umask 022
|
||||
|
||||
readonly ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
readonly LIB=/usr/local/lib/platform-backup
|
||||
readonly UNIT_DIR=/etc/systemd/system
|
||||
readonly TEXTFILE_DIR=/var/lib/node_exporter/textfile_collector
|
||||
readonly WORK_ROOT=/var/lib/platform-backup/work
|
||||
readonly USER_NAME=donghyeon
|
||||
readonly -a SCRIPTS=(
|
||||
scripts/lib/host-backup.sh:lib/host-backup.sh
|
||||
scripts/backup/k3s-datastore-backup.sh:backup/k3s-datastore-backup.sh
|
||||
scripts/backup/gitea-backup.sh:backup/gitea-backup.sh
|
||||
scripts/validate/live-drift-check-main.sh:validate/live-drift-check-main.sh
|
||||
scripts/validate/k3s-cert-expiry.sh:validate/k3s-cert-expiry.sh
|
||||
services/platform-host-checks/README.md:README.md
|
||||
)
|
||||
readonly -a TIMERS=(platform-k3s-datastore-backup platform-gitea-backup platform-live-drift-check platform-k3s-cert-expiry)
|
||||
|
||||
fail() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
|
||||
mode="${1:-}"
|
||||
[[ "$#" -eq 1 && ( "$mode" == "--check" || "$mode" == "--execute" ) ]] || { sed -n '2,8p' "$0" >&2; exit 2; }
|
||||
|
||||
echo "== check"
|
||||
for pair in "${SCRIPTS[@]}"; do
|
||||
src="${pair%%:*}"
|
||||
[[ -f "$ROOT/$src" ]] || fail "missing $src"
|
||||
[[ "$src" != *.sh ]] || bash -n "$ROOT/$src" || fail "syntax error in $src"
|
||||
done
|
||||
for t in "${TIMERS[@]}"; do
|
||||
for u in service timer; do [[ -f "$ROOT/infrastructure/host/backup/$t.$u" ]] || fail "missing $t.$u"; done
|
||||
done
|
||||
if command -v systemd-analyze >/dev/null; then
|
||||
verify_dir="$(mktemp -d)"
|
||||
trap 'rm -rf -- "$verify_dir"' EXIT
|
||||
cp "$ROOT"/infrastructure/host/backup/*.service "$ROOT"/infrastructure/host/backup/*.timer "$verify_dir/"
|
||||
# ExecStart paths do not exist before installation; only syntax and keys are checked.
|
||||
out="$(cd "$verify_dir" && systemd-analyze verify ./*.timer ./*.service 2>&1 | grep -v -E 'is not executable|No such file|Command .* is not executable' || true)"
|
||||
[[ -z "$out" ]] || { printf '%s\n' "$out" >&2; fail "systemd-analyze verify reported problems"; }
|
||||
echo " units: systemd-analyze verify clean"
|
||||
fi
|
||||
echo "== plan"
|
||||
for pair in "${SCRIPTS[@]}"; do echo " install ${pair%%:*} -> $LIB/${pair##*:}"; done
|
||||
for t in "${TIMERS[@]}"; do echo " install $UNIT_DIR/$t.service, $UNIT_DIR/$t.timer; enable --now $t.timer"; done
|
||||
echo " mkdir $TEXTFILE_DIR (root:$USER_NAME 0775), $WORK_ROOT (root 0700)"
|
||||
echo " first runs: k3s-cert-expiry, k3s-datastore-backup, gitea-backup, live-drift-check"
|
||||
[[ "$mode" == "--execute" ]] || { echo "CHECK ONLY: nothing changed"; exit 0; }
|
||||
|
||||
[[ "$(id -u)" -eq 0 ]] || fail "--execute needs root (sudo)"
|
||||
[[ -f /etc/platform-backup/aistor.env ]] || fail "run scripts/bootstrap/create-host-backup-credentials.sh first"
|
||||
echo "== install"
|
||||
for pair in "${SCRIPTS[@]}"; do
|
||||
install -D -o root -g root -m 0755 "$ROOT/${pair%%:*}" "$LIB/${pair##*:}"
|
||||
done
|
||||
install -d -o root -g "$USER_NAME" -m 0775 "$TEXTFILE_DIR"
|
||||
install -d -o root -g root -m 0700 "$WORK_ROOT"
|
||||
for t in "${TIMERS[@]}"; do
|
||||
install -o root -g root -m 0644 "$ROOT/infrastructure/host/backup/$t.service" "$ROOT/infrastructure/host/backup/$t.timer" "$UNIT_DIR/"
|
||||
done
|
||||
systemctl daemon-reload
|
||||
for t in "${TIMERS[@]}"; do systemctl enable --now "$t.timer"; done
|
||||
|
||||
echo "== first runs"
|
||||
for t in platform-k3s-cert-expiry platform-k3s-datastore-backup platform-gitea-backup platform-live-drift-check; do
|
||||
if systemctl start "$t.service"; then echo " $t: ok"; else echo " $t: FAILED (journalctl -u $t)"; fi
|
||||
done
|
||||
echo "== metrics"
|
||||
grep -h -E '^platform_' "$TEXTFILE_DIR"/*.prom || echo " no metrics yet"
|
||||
systemctl list-timers 'platform-*' --no-pager
|
||||
echo "HOST CHECKS INSTALLED"
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shared helpers for the host backup and host check scripts. Source only.
|
||||
# shellcheck shell=bash
|
||||
|
||||
readonly HOST_BACKUP_ENV=/etc/platform-backup/aistor.env
|
||||
readonly TEXTFILE_DIR=/var/lib/node_exporter/textfile_collector
|
||||
# Backup staging (root 0700, same SSD). Not /var/tmp: dockerd must see the path.
|
||||
readonly HB_WORK_ROOT=/var/lib/platform-backup/work
|
||||
# Same pinned AIStor client as scripts/validate/aistor-s3-smoke.sh.
|
||||
readonly MC_IMAGE="quay.io/minio/aistor/mc@sha256:c5ec777c080fd6292b7529309a0f311c58c3a92e268c9c57c0901da86881949b"
|
||||
|
||||
hb_log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*"; }
|
||||
hb_fail() { hb_log "FAIL: $*" >&2; exit 1; }
|
||||
|
||||
# Write Prometheus textfile metrics atomically: hb_write_metrics NAME <<'PROM' ... PROM
|
||||
hb_write_metrics() {
|
||||
local name="$1" tmp
|
||||
[[ -d "$TEXTFILE_DIR" ]] || { hb_log "textfile dir $TEXTFILE_DIR missing; metrics not written"; cat >/dev/null; return 0; }
|
||||
tmp="$(mktemp "$TEXTFILE_DIR/.${name}.XXXXXX")"
|
||||
cat >"$tmp"
|
||||
chmod 0644 "$tmp"
|
||||
mv -f -- "$tmp" "$TEXTFILE_DIR/${name}.prom"
|
||||
}
|
||||
|
||||
# Load the AIStor endpoint and the backup user's keys (root-only file).
|
||||
hb_load_aistor_env() {
|
||||
[[ -f "$HOST_BACKUP_ENV" ]] || hb_fail "$HOST_BACKUP_ENV is missing; run scripts/bootstrap/create-host-backup-credentials.sh"
|
||||
[[ "$(stat -c '%u %a' "$HOST_BACKUP_ENV")" == "0 600" ]] || hb_fail "$HOST_BACKUP_ENV must be owned by root with mode 0600"
|
||||
# shellcheck disable=SC1090
|
||||
. "$HOST_BACKUP_ENV"
|
||||
: "${AISTOR_BUCKET:?}" "${AISTOR_ACCESS_KEY:?}" "${AISTOR_SECRET_KEY:?}"
|
||||
# The host cannot resolve cluster DNS, so use the Service ClusterIP (port 80 -> 9000).
|
||||
if [[ -z "${AISTOR_ENDPOINT:-}" ]]; then
|
||||
local ip
|
||||
ip="$(/usr/local/bin/k3s kubectl --kubeconfig /etc/rancher/k3s/k3s.yaml -n object-storage \
|
||||
get service minio -o jsonpath='{.spec.clusterIP}')"
|
||||
[[ -n "$ip" ]] || hb_fail "cannot find the object-storage/minio Service"
|
||||
AISTOR_ENDPOINT="http://${ip}:80"
|
||||
fi
|
||||
}
|
||||
|
||||
# Run the pinned mc client on the host network with the backup user's keys.
|
||||
# The keys go through a 0600 env file, never the command line (ps would show it).
|
||||
# Usage: hb_mc <dir mounted at /work> <mc args...>
|
||||
hb_mc() {
|
||||
local work="$1"; shift
|
||||
local envfile="$work/.mc.env"
|
||||
if [[ ! -f "$envfile" ]]; then
|
||||
( umask 077; printf 'MC_HOST_backup=%s\nMC_CONFIG_DIR=/tmp/mc\n' \
|
||||
"${AISTOR_ENDPOINT/:\/\//://${AISTOR_ACCESS_KEY}:${AISTOR_SECRET_KEY}@}" >"$envfile" )
|
||||
fi
|
||||
docker run --rm --network host --user "$(id -u):$(id -g)" \
|
||||
--env-file "$envfile" -v "$work:/work" --tmpfs /tmp \
|
||||
"$MC_IMAGE" "$@"
|
||||
}
|
||||
@@ -559,3 +559,50 @@ parser와 세 mode의 fixture 회귀는 live cluster에 연결하지 않고 다
|
||||
```sh
|
||||
bash scripts/validate/test-k3s-secret-encryption-status.sh
|
||||
```
|
||||
|
||||
## 테넌트·우선순위·keycloak 정책 렌더 검사
|
||||
|
||||
`render-tenants-and-policies.sh`는 클러스터에 닿지 않고 세 빌드 루트를 렌더해 불변식을
|
||||
확인한다.
|
||||
|
||||
- `services/tenants/techlog`: tech-log 테넌트의 플랫폼 쪽 객체 11개(목록이 정확히 같아야
|
||||
한다), `hyeonworks-prod` PSA 라벨, techlog DatabaseRole 권한 플래그, 대시보드 이름
|
||||
- `services/priority-classes`: `platform-critical`(0보다 크고 시스템 클래스보다 작다),
|
||||
`platform-low`(0보다 작고 선점하지 않는다), 둘 다 global default가 아니다
|
||||
- `infrastructure/networking/keycloak`: namespace 전체 기본 차단, egress 규칙마다 포트,
|
||||
허용 CIDR은 API 서버 둘뿐
|
||||
|
||||
```sh
|
||||
bash scripts/validate/render-tenants-and-policies.sh
|
||||
```
|
||||
|
||||
## 라이브 drift 검사
|
||||
|
||||
`live-drift-check.sh`는 이 저장소의 라이브 빌드 루트를 모두 렌더하고(Phase 1·2, 관리 도구,
|
||||
관측 core, Traefik trust overlay, 위 세 루트) Secret을 뺀 뒤 `kubectl diff`(서버 dry-run,
|
||||
저장하지 않음)로 클러스터와 비교한다. 렌더에는 위 render 스크립트의 `--verified-output-dir`
|
||||
출력을 읽기만 하는 용도로 쓴다(그 디렉터리는 스크립트가 끝날 때 지운다).
|
||||
|
||||
```sh
|
||||
PLATFORM_HELM_BIN=/home/donghyeon/.local/bin/helm \
|
||||
bash scripts/validate/live-drift-check.sh \
|
||||
--accepted scripts/validate/live-drift-accepted.txt
|
||||
```
|
||||
|
||||
- 종료 코드: 0 차이 없음, 1 차이 있음, 2 검사 자체 실패.
|
||||
- `DRIFT <Kind> <ns>/<name> (+추가 -삭제) [입력 파일]`로 객체마다 한 줄을 쓴다.
|
||||
`generation` 줄만 다른 것은 세지 않는다.
|
||||
- `--accepted`: 알고 있는 차이를 기한과 이유를 달아 적는다. 기한이 지나면 다시 drift로 센다.
|
||||
- `--textfile FILE`: `platform_live_drift_objects`, `platform_live_drift_check_success`,
|
||||
`platform_live_drift_last_run_timestamp_seconds`를 Prometheus textfile 형식으로 쓴다.
|
||||
- Secret 값의 차이는 보지 않는다.
|
||||
|
||||
## 호스트 백업·점검 시험
|
||||
|
||||
- `test-platform-host-checks-alerts.sh`: `services/platform-host-checks/prometheus-rules.yaml`의 promtool
|
||||
단위 시험(백업 신선도, 실패, 지표 없음, drift, k3s 인증서). docker 필요, 클러스터 접근 없음.
|
||||
- `k3s-cert-expiry.sh`: 6443·10250 serving 인증서 만료를 textfile 지표로 쓴다(타이머가 매일 돌림).
|
||||
- `live-drift-check-main.sh`: checkout의 작업 트리가 아니라 `origin/main`으로 `live-drift-check.sh`를 돌린다.
|
||||
- `k3s-datastore-restore-drill.sh`, `gitea-backup-restore-drill.sh`: 복원 리허설. 인자 없이 root로 돌리면 AIStor의
|
||||
최신 백업을 쓰고, `--from-dir`·`--from-file`로 로컬 사본을 줄 수 있다.
|
||||
- `test-k3s-datastore-restore-drill.sh`: 운영 데이터 없이 k3s 복원 리허설 경로를 시험한다(일회용 k3s, 시험 Secret 셋).
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env bash
|
||||
# Restore drill for the Gitea backup (file level).
|
||||
#
|
||||
# sudo bash scripts/validate/gitea-backup-restore-drill.sh # latest dump in AIStor
|
||||
# bash scripts/validate/gitea-backup-restore-drill.sh --from-file DUMP.tar.gz
|
||||
#
|
||||
# Extracts the dump into a throwaway directory and checks what a restore needs:
|
||||
# app.ini is present, every repository passes `git fsck`, and the repository
|
||||
# count matches the live Gitea. The database is restored from the CloudNativePG
|
||||
# backup instead (services/platform-postgres-backup); the full restore order is
|
||||
# in docs/runbooks/gitea-restore.md. Nothing is written to the cluster.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
readonly ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
# shellcheck source=../lib/host-backup.sh
|
||||
source "$ROOT/scripts/lib/host-backup.sh"
|
||||
readonly NAME=gitea_restore_drill
|
||||
|
||||
from_file=""
|
||||
case "${1:-}" in
|
||||
--from-file) from_file="${2:?--from-file needs a path}" ;;
|
||||
"") ;;
|
||||
*) sed -n '2,11p' "$0" >&2; exit 2 ;;
|
||||
esac
|
||||
if [[ "$(id -u)" -eq 0 ]]; then
|
||||
kubectl() { command /usr/local/bin/k3s kubectl --kubeconfig /etc/rancher/k3s/k3s.yaml "$@"; }
|
||||
fi
|
||||
|
||||
base="$HB_WORK_ROOT"; [[ -w "$base" ]] || base="$(mktemp -d)"
|
||||
work="$(mktemp -d "$base/gitea-drill.XXXXXX")"
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
|
||||
if [[ -z "$from_file" ]]; then
|
||||
[[ "$(id -u)" -eq 0 ]] || hb_fail "run as root to read the backup credentials"
|
||||
hb_load_aistor_env
|
||||
latest="$(hb_mc "$work" ls "backup/$AISTOR_BUCKET/gitea/" | awk '{print $NF}' | grep -E '^gitea-dump-.*\.tar\.gz$' | sort | tail -1)"
|
||||
[[ -n "$latest" ]] || hb_fail "no Gitea dump found"
|
||||
hb_mc "$work" cp --quiet "backup/$AISTOR_BUCKET/gitea/$latest" "backup/$AISTOR_BUCKET/gitea/$latest.sha256" /work/ >/dev/null
|
||||
[[ "$(sha256sum "$work/$latest" | awk '{print $1}')" == "$(cat "$work/$latest.sha256")" ]] || hb_fail "checksum mismatch for $latest"
|
||||
from_file="$work/$latest"
|
||||
hb_log "drill on $latest"
|
||||
fi
|
||||
|
||||
mkdir "$work/restore"
|
||||
tar -C "$work/restore" -xzf "$from_file"
|
||||
[[ -s "$work/restore/app.ini" ]] || hb_fail "app.ini is missing from the dump"
|
||||
for key in INTERNAL_TOKEN SECRET_KEY; do
|
||||
grep -q "^${key}[[:space:]]*=" "$work/restore/app.ini" || hb_fail "app.ini has no ${key} (needed to restore)"
|
||||
done
|
||||
|
||||
total=0 broken=0
|
||||
while IFS= read -r -d '' repo; do
|
||||
total=$((total + 1))
|
||||
if ! git -c safe.directory='*' --git-dir="$repo" fsck --no-dangling --no-progress >/dev/null 2>"$work/fsck.err"; then
|
||||
broken=$((broken + 1))
|
||||
hb_log "fsck failed: ${repo#"$work/restore/"}: $(head -1 "$work/fsck.err")"
|
||||
fi
|
||||
done < <(find "$work/restore/repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0)
|
||||
hb_log "repositories in dump: $total, fsck failures: $broken"
|
||||
(( total > 0 )) || hb_fail "the dump has no repositories"
|
||||
(( broken == 0 )) || hb_fail "$broken repositories failed git fsck"
|
||||
|
||||
live="$(kubectl -n gitea exec deploy/gitea -c gitea -- sh -c 'find /data/git/gitea-repositories -mindepth 2 -maxdepth 2 -name "*.git" -type d | wc -l' 2>/dev/null || echo "")"
|
||||
if [[ -n "$live" ]]; then
|
||||
hb_log "live Gitea repositories: $live"
|
||||
(( total >= live - 2 )) || hb_fail "the dump has $total repositories, live Gitea has $live"
|
||||
fi
|
||||
|
||||
hb_write_metrics "$NAME" <<PROM
|
||||
# HELP platform_backup_restore_drill_last_success_timestamp_seconds Unix time of the last successful restore drill.
|
||||
# TYPE platform_backup_restore_drill_last_success_timestamp_seconds gauge
|
||||
platform_backup_restore_drill_last_success_timestamp_seconds{backup="gitea"} $(date +%s)
|
||||
PROM
|
||||
echo "GITEA RESTORE DRILL PASS"
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Write the notAfter time of the k3s API server (6443) and kubelet (10250)
|
||||
# serving certificates as Prometheus textfile metrics. No root needed.
|
||||
# k3s renews these only when it starts and they are within 120 days of expiry
|
||||
# (docs.k3s.io cli/certificate), and the kubelet exposes no certificate metric,
|
||||
# so nothing else in the cluster watches them.
|
||||
set -Eeuo pipefail
|
||||
# shellcheck source=../lib/host-backup.sh
|
||||
source "$(dirname -- "${BASH_SOURCE[0]}")/../lib/host-backup.sh"
|
||||
|
||||
lines=""
|
||||
for target in apiserver:6443 kubelet:10250; do
|
||||
name="${target%%:*}" port="${target##*:}"
|
||||
end="$(echo | timeout 10 openssl s_client -connect "127.0.0.1:$port" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | sed 's/^notAfter=//')" || true
|
||||
[[ -n "$end" ]] || hb_fail "could not read the $name certificate on 127.0.0.1:$port"
|
||||
lines+="platform_k3s_certificate_not_after_seconds{certificate=\"$name\"} $(date -d "$end" +%s)"$'\n'
|
||||
hb_log "$name certificate notAfter $end"
|
||||
done
|
||||
hb_write_metrics platform_k3s_certificates <<PROM
|
||||
# HELP platform_k3s_certificate_not_after_seconds notAfter of a k3s serving certificate (Unix time).
|
||||
# TYPE platform_k3s_certificate_not_after_seconds gauge
|
||||
${lines}# HELP platform_k3s_certificate_check_timestamp_seconds Unix time of the last certificate check.
|
||||
# TYPE platform_k3s_certificate_check_timestamp_seconds gauge
|
||||
platform_k3s_certificate_check_timestamp_seconds $(date +%s)
|
||||
PROM
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
# Restore drill for the k3s datastore backup.
|
||||
#
|
||||
# sudo bash scripts/validate/k3s-datastore-restore-drill.sh # latest backup in AIStor
|
||||
# bash scripts/validate/k3s-datastore-restore-drill.sh --from-dir DIR [--expect-secrets N]
|
||||
# DIR holds state.db and token (an extracted archive, or a test datastore)
|
||||
#
|
||||
# Starts a throwaway k3s server (same version as production, --network none,
|
||||
# no agent) on a copy of the backup, and checks that the API answers, that the
|
||||
# Secret count matches and that every Secret decrypts (the token unlocks the
|
||||
# encryption config stored in the datastore). Prints no Secret value. The
|
||||
# container and the copy are removed at the end.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
readonly ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
# shellcheck source=../lib/host-backup.sh
|
||||
source "$ROOT/scripts/lib/host-backup.sh"
|
||||
# Same version as the desktop server (k3s --version: v1.36.2+k3s1).
|
||||
readonly K3S_IMAGE="docker.io/rancher/k3s:v1.36.2-k3s1@sha256:6a47cea22c4b834d4ba72c89d291696b79ebe406251f90b446e4dff03513dd87"
|
||||
readonly NAME=k3s_datastore_restore_drill
|
||||
|
||||
from_dir="" expect_secrets=""
|
||||
while (( $# > 0 )); do
|
||||
case "$1" in
|
||||
--from-dir) from_dir="${2:?}"; shift 2 ;;
|
||||
--expect-secrets) expect_secrets="${2:?}"; shift 2 ;;
|
||||
*) sed -n '2,13p' "$0" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
base="${HB_WORK_ROOT}"
|
||||
[[ -w "$base" ]] || base="$(mktemp -d)"
|
||||
work="$(mktemp -d "$base/k3s-drill.XXXXXX")"
|
||||
container="k3s-restore-drill-$$"
|
||||
cleanup() {
|
||||
docker rm -f "$container" >/dev/null 2>&1 || true
|
||||
# The drill container writes as root; remove its files with the same image.
|
||||
docker run --rm -v "$work:/w" --entrypoint /bin/sh "$K3S_IMAGE" -c 'rm -rf /w/*' >/dev/null 2>&1 || true
|
||||
rm -rf -- "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
if [[ -z "$from_dir" ]]; then
|
||||
[[ "$(id -u)" -eq 0 ]] || hb_fail "run as root to read the backup credentials"
|
||||
hb_load_aistor_env
|
||||
latest="$(hb_mc "$work" ls "backup/$AISTOR_BUCKET/k3s-datastore/" | awk '{print $NF}' | grep -E '^k3s-datastore-.*\.tar\.gz$' | sort | tail -1)"
|
||||
[[ -n "$latest" ]] || hb_fail "no k3s datastore backup found"
|
||||
hb_mc "$work" cp --quiet "backup/$AISTOR_BUCKET/k3s-datastore/$latest" "backup/$AISTOR_BUCKET/k3s-datastore/$latest.sha256" /work/ >/dev/null
|
||||
[[ "$(sha256sum "$work/$latest" | awk '{print $1}')" == "$(cat "$work/$latest.sha256")" ]] || hb_fail "checksum mismatch for $latest"
|
||||
tar -C "$work" -xzf "$work/$latest"
|
||||
from_dir="$(find "$work" -mindepth 1 -maxdepth 1 -type d -name 'k3s-datastore-*' | head -1)"
|
||||
hb_log "drill on $latest"
|
||||
if [[ -z "$expect_secrets" ]]; then
|
||||
expect_secrets="$(/usr/local/bin/k3s kubectl --kubeconfig /etc/rancher/k3s/k3s.yaml get secrets -A --no-headers | wc -l)"
|
||||
hb_log "live cluster has $expect_secrets Secrets (counts may differ by objects created since the backup)"
|
||||
fi
|
||||
fi
|
||||
[[ -f "$from_dir/state.db" && -f "$from_dir/token" ]] || hb_fail "$from_dir must contain state.db and token"
|
||||
|
||||
install -d -m 0700 "$work/server/db"
|
||||
cp "$from_dir/state.db" "$work/server/db/state.db"
|
||||
cp "$from_dir/token" "$work/server/token"
|
||||
[[ "$(sqlite3 "$work/server/db/state.db" 'PRAGMA integrity_check;')" == "ok" ]] || hb_fail "integrity_check failed"
|
||||
|
||||
started="$(date +%s)"
|
||||
docker run -d --name "$container" --network none --tmpfs /run --tmpfs /var/run \
|
||||
-v "$work/server:/var/lib/rancher/k3s/server" \
|
||||
"$K3S_IMAGE" server --disable-agent --secrets-encryption \
|
||||
--token-file /var/lib/rancher/k3s/server/token \
|
||||
--bind-address 127.0.0.1 --advertise-address 127.0.0.1 --node-ip 127.0.0.1 \
|
||||
--disable traefik,servicelb,metrics-server,local-storage,coredns >/dev/null
|
||||
|
||||
ready=0
|
||||
for _ in $(seq 1 60); do
|
||||
if docker exec "$container" kubectl get --raw /readyz >/dev/null 2>&1; then ready=1; break; fi
|
||||
sleep 5
|
||||
done
|
||||
if (( ready == 0 )); then
|
||||
docker logs --tail 20 "$container" 2>&1 | sed 's/^/ k3s: /' >&2
|
||||
hb_fail "restored k3s did not become ready in 5 minutes"
|
||||
fi
|
||||
namespaces="$(docker exec "$container" kubectl get namespaces --no-headers | wc -l)"
|
||||
secrets="$(docker exec "$container" kubectl get secrets -A --no-headers | wc -l)"
|
||||
# -o json decrypts every Secret on the server side; any failure makes kubectl exit non-zero.
|
||||
decrypted="$(docker exec "$container" kubectl get secrets -A -o json | python3 -I -c 'import json,sys; d=json.load(sys.stdin)["items"]; print(sum(1 for s in d if s.get("data")))')"
|
||||
hb_log "restored: namespaces=$namespaces secrets=$secrets with-data=$decrypted in $(( $(date +%s) - started ))s"
|
||||
if [[ -n "$expect_secrets" ]]; then
|
||||
diff=$(( secrets - expect_secrets ))
|
||||
(( ${diff#-} <= 5 )) || hb_fail "Secret count $secrets is far from the expected $expect_secrets"
|
||||
fi
|
||||
(( decrypted > 0 )) || hb_fail "no Secret carried data after restore"
|
||||
|
||||
hb_write_metrics "$NAME" <<PROM
|
||||
# HELP platform_backup_restore_drill_last_success_timestamp_seconds Unix time of the last successful restore drill.
|
||||
# TYPE platform_backup_restore_drill_last_success_timestamp_seconds gauge
|
||||
platform_backup_restore_drill_last_success_timestamp_seconds{backup="k3s-datastore"} $(date +%s)
|
||||
PROM
|
||||
echo "K3S DATASTORE RESTORE DRILL PASS"
|
||||
@@ -0,0 +1,10 @@
|
||||
# 알고 있는 라이브 drift. 형식: <Kind> <namespace 또는 -> <name> <기한 YYYY-MM-DD> <이유>
|
||||
# 기한이 지나면 live-drift-check.sh가 다시 drift로 센다. 해소하면 줄을 지운다.
|
||||
Cluster platform-data platform-postgres 2026-11-30 pg_hba의 techlog 두 줄이 repo에 없다. w1이 CNPG 백업과 함께 넣는다(1c4ef9a).
|
||||
DatabaseRole platform-data platform-postgres-gitea 2026-11-30 렌더가 false 기본값 필드를 명시할 뿐 값은 같다. 다음 Phase 1 적용 때 사라진다.
|
||||
DatabaseRole platform-data platform-postgres-keycloak 2026-11-30 렌더가 false 기본값 필드를 명시할 뿐 값은 같다. 다음 Phase 2 적용 때 사라진다.
|
||||
Deployment keycloak keycloak-operator 2026-11-30 원격 ref 26.7.0 태그 내용이 바뀌어 build-timestamp 라벨만 다르다. 재시작 창에 커밋 SHA 고정과 함께 적용한다.
|
||||
Service keycloak keycloak-operator 2026-11-30 위와 같은 build-timestamp 라벨.
|
||||
ServiceAccount keycloak keycloak-operator 2026-11-30 위와 같은 build-timestamp 라벨.
|
||||
Deployment observability observability-core-kube-pr-operator 2026-11-30 이미지 문자열이 tag@digest와 digest로 다르고 digest는 같다. 적용하면 재시작되므로 재시작 창에.
|
||||
Deployment observability observability-core-kube-state-metrics 2026-11-30 위와 같은 이미지 문자열 차이.
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Daily drift check against origin/main (not the working tree of the checkout),
|
||||
# so local edits or a stale checkout do not hide or invent drift.
|
||||
# Run by platform-live-drift-check.timer as the desktop user.
|
||||
set -Eeuo pipefail
|
||||
readonly CHECKOUT="${PLATFORM_CHECKOUT:-/home/donghyeon/workspace/platform}"
|
||||
readonly TEXTFILE=/var/lib/node_exporter/textfile_collector/platform_live_drift.prom
|
||||
|
||||
git -C "$CHECKOUT" fetch --quiet origin main
|
||||
work="$(mktemp -d /tmp/platform-drift-main.XXXXXX)"
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
git -C "$CHECKOUT" archive origin/main | tar -x -C "$work"
|
||||
printf 'origin/main %s\n' "$(git -C "$CHECKOUT" rev-parse --short origin/main)"
|
||||
args=(--accepted "$work/scripts/validate/live-drift-accepted.txt")
|
||||
[[ -d "$(dirname "$TEXTFILE")" ]] && args+=(--textfile "$TEXTFILE")
|
||||
bash "$work/scripts/validate/live-drift-check.sh" "${args[@]}"
|
||||
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env bash
|
||||
# Render every live build root of this repository and compare it with the
|
||||
# cluster using `kubectl diff` (server-side dry-run: nothing is persisted).
|
||||
#
|
||||
# Usage:
|
||||
# PLATFORM_HELM_BIN=/abs/helm bash scripts/validate/live-drift-check.sh \
|
||||
# [--accepted FILE] [--textfile FILE]
|
||||
#
|
||||
# --accepted FILE known differences, one per line:
|
||||
# `<Kind> <namespace or -> <name> <until YYYY-MM-DD> <reason...>`
|
||||
# Expired entries count as drift again.
|
||||
# --textfile FILE also write Prometheus textfile metrics (atomic rename).
|
||||
#
|
||||
# Exit status: 0 no drift, 1 drift found, 2 the check itself failed.
|
||||
# Secrets are removed from the renders before diffing; Secret drift is out of scope.
|
||||
set -Eeuo pipefail
|
||||
|
||||
readonly REPOSITORY_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
accepted_file=""
|
||||
textfile=""
|
||||
while (( $# > 0 )); do
|
||||
case "$1" in
|
||||
--accepted) accepted_file="${2:?--accepted needs a file}"; shift 2 ;;
|
||||
--textfile) textfile="${2:?--textfile needs a file}"; shift 2 ;;
|
||||
-h|--help) sed -n '2,16p' "${BASH_SOURCE[0]}"; exit 0 ;;
|
||||
*) printf 'unknown argument: %s\n' "$1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
|
||||
declare -a made_dirs=()
|
||||
cleanup() {
|
||||
local d
|
||||
for d in "${made_dirs[@]}"; do
|
||||
case "$d" in /tmp/platform-*) rm -rf -- "$d" ;; esac
|
||||
done
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
write_textfile() {
|
||||
local drift="$1" ok="$2"
|
||||
[[ -n "$textfile" ]] || return 0
|
||||
local tmp="${textfile}.tmp.$$"
|
||||
{
|
||||
echo '# HELP platform_live_drift_objects Objects whose live state differs from the repository render.'
|
||||
echo '# TYPE platform_live_drift_objects gauge'
|
||||
echo "platform_live_drift_objects ${drift}"
|
||||
echo '# HELP platform_live_drift_check_success 1 when the drift check itself completed.'
|
||||
echo '# TYPE platform_live_drift_check_success gauge'
|
||||
echo "platform_live_drift_check_success ${ok}"
|
||||
echo '# HELP platform_live_drift_last_run_timestamp_seconds Unix time the drift check finished.'
|
||||
echo '# TYPE platform_live_drift_last_run_timestamp_seconds gauge'
|
||||
echo "platform_live_drift_last_run_timestamp_seconds $(date +%s)"
|
||||
} >"$tmp"
|
||||
mv -f -- "$tmp" "$textfile"
|
||||
}
|
||||
|
||||
die() {
|
||||
printf 'DRIFT CHECK ERROR: %s\n' "$*" >&2
|
||||
write_textfile 0 0
|
||||
exit 2
|
||||
}
|
||||
|
||||
work="$(mktemp -d /tmp/platform-drift.XXXXXX)"; made_dirs+=("$work")
|
||||
mkdir -p "$work/in" "$work/out"
|
||||
|
||||
render_root() {
|
||||
local script="$1" prefix="$2" dir
|
||||
dir="$(mktemp -d "/tmp/${prefix}.XXXXXX")"; made_dirs+=("$dir")
|
||||
bash "$REPOSITORY_ROOT/scripts/validate/${script}" --verified-output-dir "$dir" \
|
||||
>"$work/${script}.log" 2>&1 || { tail -5 "$work/${script}.log" >&2; die "${script} failed"; }
|
||||
printf '%s\n' "$dir"
|
||||
}
|
||||
|
||||
phase1="$(render_root render-phase1.sh platform-phase1-apply)"
|
||||
phase2="$(render_root render-phase2.sh platform-phase2-apply)"
|
||||
admin="$(render_root render-admin-services.sh platform-admin-apply)"
|
||||
observability="$(render_root render-observability-core.sh platform-observability-core-apply)"
|
||||
|
||||
# The live Gitea is the OIDC profile; gitea.yaml is the fresh-install baseline only.
|
||||
declare -a inputs=(
|
||||
"$phase1/namespaces.yaml" "$phase1/ssd-local-pv.yaml" "$phase1/cnpg-operator.yaml"
|
||||
"$phase1/platform-postgres.yaml" "$phase1/gitea-oidc.yaml"
|
||||
"$observability/aggregate.yaml"
|
||||
)
|
||||
for f in "$phase2"/*.yaml "$admin"/*.yaml; do inputs+=("$f"); done
|
||||
|
||||
# Live Traefik is the trust overlay (infrastructure/networking/traefik/README.md).
|
||||
kubectl kustomize "$REPOSITORY_ROOT/infrastructure/networking/traefik/overlays/trust" >"$work/traefik-trust.yaml" || die "traefik render failed"
|
||||
kubectl kustomize "$REPOSITORY_ROOT/services/tenants/techlog" >"$work/tenant-techlog.yaml" || die "tenant render failed"
|
||||
kubectl kustomize "$REPOSITORY_ROOT/services/priority-classes" >"$work/priority-classes.yaml" || die "priority class render failed"
|
||||
kubectl kustomize "$REPOSITORY_ROOT/infrastructure/networking/keycloak" >"$work/keycloak-network-policies.yaml" || die "keycloak policy render failed"
|
||||
inputs+=("$work/traefik-trust.yaml" "$work/tenant-techlog.yaml" "$work/priority-classes.yaml" "$work/keycloak-network-policies.yaml")
|
||||
|
||||
n=0
|
||||
for f in "${inputs[@]}"; do
|
||||
n=$((n + 1))
|
||||
python3 -I - "$f" "$work/in/$(printf '%02d' "$n")-$(basename "$f")" <<'PY' || die "could not strip Secrets from $f"
|
||||
import sys, yaml
|
||||
yaml.SafeLoader.add_constructor("tag:yaml.org,2002:value", lambda l, n: l.construct_scalar(n))
|
||||
docs = [d for d in yaml.safe_load_all(open(sys.argv[1])) if isinstance(d, dict) and d.get("kind") not in (None, "Secret")]
|
||||
yaml.safe_dump_all(docs, open(sys.argv[2], "w"), sort_keys=False)
|
||||
PY
|
||||
done
|
||||
|
||||
for f in "$work"/in/*.yaml; do
|
||||
set +e
|
||||
KUBECTL_EXTERNAL_DIFF="diff -u -N" kubectl diff -f "$f" >"$work/out/$(basename "$f").diff" 2>"$work/out/$(basename "$f").err"
|
||||
rc=$?
|
||||
set -e
|
||||
if (( rc > 1 )); then
|
||||
sed -n '1,5p' "$work/out/$(basename "$f").err" >&2
|
||||
die "kubectl diff failed for $(basename "$f")"
|
||||
fi
|
||||
done
|
||||
|
||||
set +e
|
||||
python3 -I - "$work/out" "${accepted_file:-}" "$work/drift-count" <<'PY'
|
||||
import sys, pathlib, re, datetime
|
||||
out, accepted_path, count_path = pathlib.Path(sys.argv[1]), sys.argv[2], pathlib.Path(sys.argv[3])
|
||||
today = datetime.date.today()
|
||||
accepted, expired = {}, set()
|
||||
if accepted_path:
|
||||
for line in pathlib.Path(accepted_path).read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
kind, ns, name, until, *reason = line.split()
|
||||
key = (kind, "" if ns == "-" else ns, name)
|
||||
if datetime.date.fromisoformat(until) < today:
|
||||
expired.add(key)
|
||||
else:
|
||||
accepted[key] = " ".join(reason)
|
||||
version = re.compile(r"^v\d+((alpha|beta)\d+)?$")
|
||||
objects = {}
|
||||
for diff in sorted(out.glob("*.diff")):
|
||||
current = None
|
||||
for line in diff.read_text().splitlines():
|
||||
if line.startswith("diff -u -N "):
|
||||
parts = line.split()[3].rsplit("/", 1)[-1].split(".")
|
||||
i = next(i for i, p in enumerate(parts) if version.match(p))
|
||||
current = (parts[i + 1], parts[i + 2], ".".join(parts[i + 3:]))
|
||||
objects.setdefault(current, [0, 0, diff.name])
|
||||
elif current and line[:1] in "+-" and not line.startswith(("+++", "---")):
|
||||
if re.match(r"^[+-]\s+generation:", line):
|
||||
continue
|
||||
objects[current][0 if line[0] == "+" else 1] += 1
|
||||
drift = accepted_seen = 0
|
||||
for key, (plus, minus, src) in sorted(objects.items()):
|
||||
if plus == 0 and minus == 0:
|
||||
continue
|
||||
kind, ns, name = key
|
||||
label = f"{kind} {ns or '-'}/{name} (+{plus} -{minus}) [{src}]"
|
||||
if key in accepted:
|
||||
accepted_seen += 1
|
||||
print(f"ACCEPTED {label}: {accepted[key]}")
|
||||
continue
|
||||
drift += 1
|
||||
print(f"DRIFT {label}" + (" (accepted entry expired)" if key in expired else ""))
|
||||
print(f"SUMMARY drift={drift} accepted={accepted_seen}")
|
||||
count_path.write_text(str(drift))
|
||||
PY
|
||||
rc=$?
|
||||
set -e
|
||||
(( rc == 0 )) || die "could not summarize the diffs"
|
||||
drift_count="$(cat "$work/drift-count")"
|
||||
write_textfile "$drift_count" 1
|
||||
if (( drift_count == 0 )); then
|
||||
echo "LIVE DRIFT CHECK PASS"
|
||||
exit 0
|
||||
fi
|
||||
echo "LIVE DRIFT CHECK FOUND DRIFT"
|
||||
exit 1
|
||||
@@ -412,9 +412,9 @@ elif mode == "alertmanager_routing":
|
||||
if item.get("kind") == "AlertmanagerConfig"
|
||||
and (item.get("metadata") or {}).get("name") == "platform-alertmanager"
|
||||
]
|
||||
expected_config = json.loads(r'''{"apiVersion":"monitoring.coreos.com/v1alpha1","kind":"AlertmanagerConfig","metadata":{"name":"platform-alertmanager","namespace":"observability","labels":{"observability.hyeonworks.com/instance":"home"}},"spec":{"route":{"receiver":"platform-slack","groupBy":["cluster","namespace","alertname","severity"],"groupWait":"30s","groupInterval":"5m","repeatInterval":"4h","routes":[{"receiver":"platform-null","matchers":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}]},{"receiver":"platform-heartbeat","matchers":[{"name":"alertname","matchType":"=","value":"PlatformHeartbeat"}],"groupWait":"0s","groupInterval":"1m","repeatInterval":"5m"}]},"inhibitRules":[{"sourceMatch":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}],"targetMatch":[{"name":"severity","matchType":"=","value":"info"}],"equal":["namespace"]}],"receivers":[{"name":"platform-null"},{"name":"platform-heartbeat","webhookConfigs":[{"urlSecret":{"name":"alertmanager-heartbeat","key":"url"},"sendResolved":false,"maxAlerts":1}]},{"name":"platform-slack","slackConfigs":[{"apiURL":{"name":"alertmanager-slack-webhook","key":"url"},"sendResolved":true,"linkNames":false,"mrkdwnIn":["text","fields"],"fallback":"{{ if eq .Status \"firing\" }}FIRING{{ else }}RESOLVED{{ end }}: {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","title":"{{ if eq .Status \"firing\" }}[FIRING:{{ .Alerts.Firing | len }}]{{ else }}[RESOLVED]{{ end }} {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","titleLink":"https://grafana.learn.hyeonworks.com/","color":"{{ if eq .Status \"resolved\" }}good{{ else if or (eq .CommonLabels.severity \"emergency\") (eq .CommonLabels.severity \"critical\") }}danger{{ else if eq .CommonLabels.severity \"warning\" }}warning{{ else }}#439FE0{{ end }}","fields":[{"title":"Status","value":"{{ .Status | toUpper }}","short":true},{"title":"Severity","value":"{{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }}","short":true},{"title":"Location","value":"{{ if .CommonLabels.cluster }}{{ .CommonLabels.cluster }}{{ else }}unknown-cluster{{ end }} / {{ if .CommonLabels.namespace }}{{ .CommonLabels.namespace }}{{ else }}cluster-scoped{{ end }}","short":true},{"title":"Alert count","value":"{{ len .Alerts }}","short":true}],"text":"{{ range .Alerts }}\n*Alert status:* {{ .Status | toUpper }}\n*Target:* {{ $target := .Labels.Remove $.GroupLabels.Names }}{{ if $target }}{{ range $target.SortedPairs }}{{ .Name }}={{ .Value }} {{ end }}{{ else }}unknown{{ end }}\n*Summary:* {{ with .Annotations.summary }}{{ . }}{{ else }}No summary provided{{ end }}\n*Details:* {{ with .Annotations.description }}{{ . }}{{ else }}No description provided{{ end }}\n*Started:* {{ .StartsAt.Format \"2006-01-02T15:04:05Z07:00\" }}\n{{ if eq .Status \"resolved\" }}*Ended:* {{ .EndsAt.Format \"2006-01-02T15:04:05Z07:00\" }}{{ end }}\n{{ with .Annotations.runbook_url }}*Runbook:* <{{ . }}|대응 절차 열기>{{ end }}\n\n{{ end }}\n<https://grafana.learn.hyeonworks.com/|Grafana> · <https://grafana.learn.hyeonworks.com/explore|Explore>","footer":"hyeonworks observability · Alertmanager"}]}]}}''')
|
||||
expected_config = json.loads(r'''{"apiVersion":"monitoring.coreos.com/v1alpha1","kind":"AlertmanagerConfig","metadata":{"name":"platform-alertmanager","namespace":"observability","labels":{"observability.hyeonworks.com/instance":"home"}},"spec":{"route":{"receiver":"platform-slack","groupBy":["cluster","namespace","alertname","severity"],"groupWait":"30s","groupInterval":"5m","repeatInterval":"4h","routes":[{"receiver":"platform-null","matchers":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}]}]},"inhibitRules":[{"sourceMatch":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}],"targetMatch":[{"name":"severity","matchType":"=","value":"info"}],"equal":["namespace"]}],"receivers":[{"name":"platform-null"},{"name":"platform-slack","slackConfigs":[{"apiURL":{"name":"alertmanager-slack-webhook","key":"url"},"sendResolved":true,"linkNames":false,"mrkdwnIn":["text","fields"],"fallback":"{{ if eq .Status \"firing\" }}FIRING{{ else }}RESOLVED{{ end }}: {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","title":"{{ if eq .Status \"firing\" }}[FIRING:{{ .Alerts.Firing | len }}]{{ else }}[RESOLVED]{{ end }} {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","titleLink":"https://grafana.learn.hyeonworks.com/","color":"{{ if eq .Status \"resolved\" }}good{{ else if or (eq .CommonLabels.severity \"emergency\") (eq .CommonLabels.severity \"critical\") }}danger{{ else if eq .CommonLabels.severity \"warning\" }}warning{{ else }}#439FE0{{ end }}","fields":[{"title":"Status","value":"{{ .Status | toUpper }}","short":true},{"title":"Severity","value":"{{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }}","short":true},{"title":"Location","value":"{{ if .CommonLabels.cluster }}{{ .CommonLabels.cluster }}{{ else }}unknown-cluster{{ end }} / {{ if .CommonLabels.namespace }}{{ .CommonLabels.namespace }}{{ else }}cluster-scoped{{ end }}","short":true},{"title":"Alert count","value":"{{ len .Alerts }}","short":true}],"text":"{{ range .Alerts }}\n*Alert status:* {{ .Status | toUpper }}\n*Target:* {{ $target := .Labels.Remove $.GroupLabels.Names }}{{ if $target }}{{ range $target.SortedPairs }}{{ .Name }}={{ .Value }} {{ end }}{{ else }}unknown{{ end }}\n*Summary:* {{ with .Annotations.summary }}{{ . }}{{ else }}No summary provided{{ end }}\n*Details:* {{ with .Annotations.description }}{{ . }}{{ else }}No description provided{{ end }}\n*Started:* {{ .StartsAt.Format \"2006-01-02T15:04:05Z07:00\" }}\n{{ if eq .Status \"resolved\" }}*Ended:* {{ .EndsAt.Format \"2006-01-02T15:04:05Z07:00\" }}{{ end }}\n{{ with .Annotations.runbook_url }}*Runbook:* <{{ . }}|대응 절차 열기>{{ end }}\n\n{{ end }}\n<https://grafana.learn.hyeonworks.com/|Grafana> · <https://grafana.learn.hyeonworks.com/explore|Explore>","footer":"hyeonworks observability · Alertmanager"}]}]}}''')
|
||||
if configs != [expected_config]:
|
||||
reject("platform AlertmanagerConfig is not the exact global Slack and heartbeat contract")
|
||||
reject("platform AlertmanagerConfig is not the exact global Slack contract")
|
||||
|
||||
policies = [
|
||||
item
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env bash
|
||||
# Render the tech-log tenant root, the platform PriorityClasses and the keycloak
|
||||
# namespace NetworkPolicies, and check their invariants. Static: no cluster access.
|
||||
set -Eeuo pipefail
|
||||
|
||||
readonly EXPECTED_KUSTOMIZE_VERSION="v5.8.1"
|
||||
readonly REPOSITORY_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
|
||||
fail() {
|
||||
printf 'ERROR: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
kustomize_version="$(kubectl version --client --output=yaml | sed -n 's/^kustomizeVersion: //p')"
|
||||
[[ "$kustomize_version" == "$EXPECTED_KUSTOMIZE_VERSION" ]] || \
|
||||
fail "expected Kustomize ${EXPECTED_KUSTOMIZE_VERSION}, found ${kustomize_version:-unknown}"
|
||||
|
||||
work="$(mktemp -d "${TMPDIR:-/tmp}/platform-tenants-render.XXXXXX")"
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
|
||||
kubectl kustomize "$REPOSITORY_ROOT/services/tenants/techlog" >"$work/techlog.yaml"
|
||||
kubectl kustomize "$REPOSITORY_ROOT/services/priority-classes" >"$work/priority-classes.yaml"
|
||||
kubectl kustomize "$REPOSITORY_ROOT/infrastructure/networking/keycloak" >"$work/keycloak-network-policies.yaml"
|
||||
|
||||
python3 -I - "$work" <<'PY'
|
||||
import sys, pathlib, yaml
|
||||
|
||||
work = pathlib.Path(sys.argv[1])
|
||||
errors = []
|
||||
|
||||
def load(name):
|
||||
return [d for d in yaml.safe_load_all((work / name).read_text()) if d]
|
||||
|
||||
def keyset(docs):
|
||||
return sorted((d["kind"], d["metadata"].get("namespace", ""), d["metadata"]["name"]) for d in docs)
|
||||
|
||||
for name in ("techlog.yaml", "priority-classes.yaml", "keycloak-network-policies.yaml"):
|
||||
for d in load(name):
|
||||
if d["kind"] == "Secret":
|
||||
errors.append(f"{name}: Secret objects must not be rendered")
|
||||
|
||||
techlog = load("techlog.yaml")
|
||||
expected = sorted([
|
||||
("Namespace", "", "hyeonworks-prod"),
|
||||
("Database", "platform-data", "platform-postgres-techlog"),
|
||||
("DatabaseRole", "platform-data", "platform-postgres-techlog"),
|
||||
("NetworkPolicy", "platform-data", "allow-techlog-backend"),
|
||||
("NetworkPolicy", "object-storage", "allow-techlog-backend"),
|
||||
("Probe", "observability", "techlog-edge"),
|
||||
("Probe", "observability", "techlog-readiness"),
|
||||
("PrometheusRule", "observability", "techlog"),
|
||||
("ConfigMap", "observability", "grafana-dashboard-techlog"),
|
||||
("NetworkPolicy", "observability", "blackbox-allow-techlog-health"),
|
||||
("NetworkPolicy", "observability", "observability-allow-techlog-scrape"),
|
||||
])
|
||||
if keyset(techlog) != expected:
|
||||
errors.append(f"tech-log tenant objects differ: {keyset(techlog)}")
|
||||
for d in techlog:
|
||||
kind = d["kind"]
|
||||
if kind == "Namespace":
|
||||
labels = d["metadata"].get("labels", {})
|
||||
want = {
|
||||
"pod-security.kubernetes.io/enforce": "baseline",
|
||||
"pod-security.kubernetes.io/warn": "restricted",
|
||||
"pod-security.kubernetes.io/audit": "restricted",
|
||||
"observability.hyeonworks.com/enabled": "true",
|
||||
}
|
||||
for k, v in want.items():
|
||||
if labels.get(k) != v:
|
||||
errors.append(f"hyeonworks-prod label {k} must be {v}")
|
||||
if kind == "DatabaseRole":
|
||||
spec = d["spec"]
|
||||
if spec.get("passwordSecret", {}).get("name") != "techlog-db-credentials":
|
||||
errors.append("techlog DatabaseRole must reference techlog-db-credentials")
|
||||
for flag in ("superuser", "createdb", "createrole", "replication", "bypassrls"):
|
||||
if spec.get(flag) is not False:
|
||||
errors.append(f"techlog DatabaseRole {flag} must be false")
|
||||
if kind in ("Database", "DatabaseRole"):
|
||||
policy = d["spec"].get("databaseReclaimPolicy") or d["spec"].get("databaseRoleReclaimPolicy")
|
||||
if policy != "retain":
|
||||
errors.append(f"{kind} must keep the retain reclaim policy")
|
||||
if kind == "ConfigMap":
|
||||
labels = d["metadata"].get("labels", {})
|
||||
if labels.get("grafana_dashboard") != "1":
|
||||
errors.append("tech-log dashboard ConfigMap needs grafana_dashboard=1")
|
||||
if d["metadata"]["name"] != "grafana-dashboard-techlog":
|
||||
errors.append("tech-log dashboard ConfigMap must keep its name (no hash suffix)")
|
||||
|
||||
classes = {d["metadata"]["name"]: d for d in load("priority-classes.yaml")}
|
||||
if sorted(classes) != ["platform-critical", "platform-low"]:
|
||||
errors.append(f"PriorityClasses differ: {sorted(classes)}")
|
||||
else:
|
||||
crit, low = classes["platform-critical"], classes["platform-low"]
|
||||
if not (0 < crit["value"] < 1_000_000_000):
|
||||
errors.append("platform-critical must be above 0 and below the system classes")
|
||||
if not low["value"] < 0:
|
||||
errors.append("platform-low must be below the default priority 0")
|
||||
if low.get("preemptionPolicy") != "Never":
|
||||
errors.append("platform-low must never preempt")
|
||||
for d in classes.values():
|
||||
if d.get("globalDefault") is not False:
|
||||
errors.append(f"{d['metadata']['name']} must not be the global default")
|
||||
|
||||
policies = {d["metadata"]["name"]: d for d in load("keycloak-network-policies.yaml")}
|
||||
deny = policies.get("keycloak-default-deny")
|
||||
if not deny or deny["spec"].get("podSelector") != {} or sorted(deny["spec"].get("policyTypes", [])) != ["Egress", "Ingress"]:
|
||||
errors.append("keycloak needs a namespace-wide default deny for ingress and egress")
|
||||
for d in policies.values():
|
||||
if d["metadata"].get("namespace") != "keycloak":
|
||||
errors.append(f"{d['metadata']['name']} must live in the keycloak namespace")
|
||||
for rule in d["spec"].get("egress", []) or []:
|
||||
for peer in rule.get("to", []):
|
||||
cidr = peer.get("ipBlock", {}).get("cidr")
|
||||
if cidr and cidr not in ("10.43.0.1/32", "192.168.0.107/32"):
|
||||
errors.append(f"{d['metadata']['name']}: unexpected egress CIDR {cidr}")
|
||||
if not rule.get("ports"):
|
||||
errors.append(f"{d['metadata']['name']}: every egress rule must name its ports")
|
||||
|
||||
if errors:
|
||||
for e in errors:
|
||||
print(f"ERROR: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(f"tech-log tenant: {len(techlog)} objects; PriorityClasses: {len(classes)}; keycloak NetworkPolicies: {len(policies)}")
|
||||
PY
|
||||
|
||||
echo "TENANTS AND POLICIES STATIC RENDER PASS"
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# Test k3s-datastore-restore-drill.sh without production data: start a fresh,
|
||||
# network-less k3s with secrets encryption, add three test Secrets, stop it,
|
||||
# and run the drill on its state.db and token. Needs docker; no root.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
readonly ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
readonly K3S_IMAGE="$(sed -n 's/^readonly K3S_IMAGE="\(.*\)"$/\1/p' "$ROOT/scripts/validate/k3s-datastore-restore-drill.sh")"
|
||||
[[ -n "$K3S_IMAGE" ]] || { echo "cannot read K3S_IMAGE from the drill script" >&2; exit 1; }
|
||||
work="$(mktemp -d)"
|
||||
seed="w6-k3s-drill-seed-$$"
|
||||
cleanup() {
|
||||
docker rm -f "$seed" >/dev/null 2>&1 || true
|
||||
docker run --rm -v "$work:/w" --entrypoint /bin/sh "$K3S_IMAGE" -c 'rm -rf /w/*' >/dev/null 2>&1 || true
|
||||
rm -rf -- "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
mkdir -p "$work/server" "$work/copy"
|
||||
|
||||
docker run -d --name "$seed" --network none --tmpfs /run --tmpfs /var/run \
|
||||
-v "$work/server:/var/lib/rancher/k3s/server" "$K3S_IMAGE" server --disable-agent --secrets-encryption \
|
||||
--bind-address 127.0.0.1 --advertise-address 127.0.0.1 --node-ip 127.0.0.1 \
|
||||
--disable traefik,servicelb,metrics-server,local-storage,coredns >/dev/null
|
||||
for _ in $(seq 1 60); do docker exec "$seed" kubectl get --raw /readyz >/dev/null 2>&1 && break; sleep 5; done
|
||||
for i in 1 2 3; do docker exec "$seed" kubectl create secret generic "drill-test-$i" --from-literal=value="test-$i" >/dev/null; done
|
||||
expected="$(docker exec "$seed" kubectl get secrets -A --no-headers | wc -l)"
|
||||
docker stop -t 30 "$seed" >/dev/null
|
||||
docker run --rm -v "$work:/w" --entrypoint /bin/sh "$K3S_IMAGE" -c \
|
||||
"cp /w/server/db/state.db* /w/server/token /w/copy/ && chown $(id -u):$(id -g) /w/copy/*"
|
||||
# Fold the WAL into state.db, as `sqlite3 .backup` does in the real backup.
|
||||
sqlite3 "$work/copy/state.db" 'PRAGMA wal_checkpoint(TRUNCATE);' >/dev/null
|
||||
rm -f "$work/copy/state.db-wal" "$work/copy/state.db-shm"
|
||||
# The test Secrets must be stored encrypted (k8s:enc:...), so the drill really
|
||||
# proves that the token unlocks the encryption key.
|
||||
encrypted="$(sqlite3 "$work/copy/state.db" "SELECT COUNT(*) FROM kine WHERE name LIKE '/registry/secrets/default/drill-test-%' AND CAST(value AS TEXT) LIKE 'k8s:enc:%';")"
|
||||
echo "seed: $expected Secrets, encrypted test Secret rows=$encrypted"
|
||||
(( encrypted >= 3 )) || { echo "test Secrets are not encrypted at rest in the seed datastore" >&2; exit 1; }
|
||||
|
||||
bash "$ROOT/scripts/validate/k3s-datastore-restore-drill.sh" --from-dir "$work/copy" --expect-secrets "$expected"
|
||||
echo "K3S DATASTORE RESTORE DRILL TEST PASS"
|
||||
@@ -87,20 +87,7 @@ if alert != {
|
||||
"value": "InfoInhibitor",
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"receiver": "platform-heartbeat",
|
||||
"matchers": [
|
||||
{
|
||||
"name": "alertname",
|
||||
"matchType": "=",
|
||||
"value": "PlatformHeartbeat",
|
||||
}
|
||||
],
|
||||
"groupWait": "0s",
|
||||
"groupInterval": "1m",
|
||||
"repeatInterval": "5m",
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
"inhibitRules": [
|
||||
@@ -124,16 +111,6 @@ if alert != {
|
||||
],
|
||||
"receivers": [
|
||||
{"name": "platform-null"},
|
||||
{
|
||||
"name": "platform-heartbeat",
|
||||
"webhookConfigs": [
|
||||
{
|
||||
"urlSecret": {"name": "alertmanager-heartbeat", "key": "url"},
|
||||
"sendResolved": False,
|
||||
"maxAlerts": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"name": "platform-slack",
|
||||
"slackConfigs": [
|
||||
@@ -179,7 +156,7 @@ if alert != {
|
||||
],
|
||||
},
|
||||
}:
|
||||
fail("platform-alertmanager must match the exact global Slack and heartbeat contract")
|
||||
fail("platform-alertmanager must match the exact global Slack contract")
|
||||
|
||||
if policy != {
|
||||
"apiVersion": "networking.k8s.io/v1",
|
||||
|
||||
@@ -1,263 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Unit tests for the alerts that guard the desktop host: core-rules.yaml and
|
||||
# services/platform-postgres-backup/prometheus-rule.yaml.
|
||||
#
|
||||
# Root disk: the kubelet starts deleting unused images at 85% use and evicts
|
||||
# pods at 90% (nodefs.available < 10%). The alerts sit in front of those two
|
||||
# points: warning at 80%, critical at 85%, and a forecast that fires when the
|
||||
# 6h trend reaches the eviction point within 6 hours.
|
||||
# PostgreSQL backups: no successful base backup for 26 hours, or WAL waiting
|
||||
# to be archived. Monitoring: ingestion stopped, and the always-firing
|
||||
# heartbeat that an external dead man's switch watches.
|
||||
#
|
||||
# Needs docker, jq and kubectl (client only, no cluster access).
|
||||
set -euo pipefail
|
||||
|
||||
readonly ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
readonly RULE_FILE="${ROOT_DIR}/services/observability/rules/platform/core-rules.yaml"
|
||||
readonly BACKUP_RULE_FILE="${ROOT_DIR}/services/platform-postgres-backup/prometheus-rule.yaml"
|
||||
# Same pinned image as test-platform-observability-rules.sh.
|
||||
readonly PROMETHEUS_IMAGE="quay.io/prometheus/prometheus:v3.13.2-distroless@sha256:ce95cfa77eff5aad28bd7a65aff19868cf78d9e17e4c254da7dfe22ade78318b"
|
||||
readonly RUNBOOK_URL="https://git.learn.hyeonworks.com/donghyeon.kang/project-infra/src/branch/main/docs/runbooks/2026-07-31-observability-access-cutover.md"
|
||||
readonly BACKUP_RUNBOOK_URL="https://git.learn.hyeonworks.com/donghyeon.kang/platform-core/src/branch/main/services/platform-postgres-backup/README.md"
|
||||
|
||||
temp_dir=''
|
||||
cleanup() {
|
||||
if [[ -n "$temp_dir" && -d "$temp_dir" ]]; then
|
||||
rm -rf -- "$temp_dir"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
fail() {
|
||||
printf 'FAIL: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
for command in docker jq kubectl; do
|
||||
command -v "$command" >/dev/null || fail "missing command: ${command}"
|
||||
done
|
||||
|
||||
temp_dir="$(mktemp -d)"
|
||||
chmod 0755 "$temp_dir"
|
||||
|
||||
kubectl create --dry-run=client --validate=false -f "$RULE_FILE" -o json |
|
||||
jq '.spec' >"${temp_dir}/core.rules.json"
|
||||
kubectl create --dry-run=client --validate=false -f "$BACKUP_RULE_FILE" -o json |
|
||||
jq '.spec' >"${temp_dir}/backup.rules.json"
|
||||
|
||||
# Every core alert keeps the runbook the other platform rules use.
|
||||
jq -e --arg url "$RUNBOOK_URL" '
|
||||
all(.groups[].rules[] | select(has("alert")); .annotations.runbook_url == $url)
|
||||
' "${temp_dir}/core.rules.json" >/dev/null || fail "core alert without the shared runbook_url"
|
||||
jq -e --arg url "$BACKUP_RUNBOOK_URL" '
|
||||
all(.groups[].rules[] | select(has("alert")); .annotations.runbook_url == $url)
|
||||
' "${temp_dir}/backup.rules.json" >/dev/null || fail "backup alert without the backup README runbook_url"
|
||||
|
||||
# node-exporter labels as scraped by serviceMonitor/observability-agent/node-exporter.
|
||||
readonly SERIES_LABELS='job="prometheus-node-exporter",instance="10.42.0.95:9100",device="/dev/sdc1",fstype="ext4",mountpoint="/"'
|
||||
readonly PG_LABELS='job="platform-postgres",namespace="platform-data",pod="platform-postgres-1",instance="10.42.0.130:9187"'
|
||||
readonly ALERT_LABELS=' job: prometheus-node-exporter
|
||||
instance: 10.42.0.95:9100
|
||||
device: /dev/sdc1
|
||||
fstype: ext4
|
||||
mountpoint: /'
|
||||
|
||||
usage_case() {
|
||||
# name, used percent, eval minute, expected alerts (YAML list body or "[]")
|
||||
local name=$1 used=$2 eval_minute=$3 expected=$4
|
||||
local avail=$((100 - used))
|
||||
cat <<EOF
|
||||
- name: ${name}
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'node_filesystem_avail_bytes{${SERIES_LABELS}}'
|
||||
values: '${avail}+0x40'
|
||||
- series: 'node_filesystem_size_bytes{${SERIES_LABELS}}'
|
||||
values: '100+0x40'
|
||||
alert_rule_test:
|
||||
- eval_time: ${eval_minute}m
|
||||
alertname: PlatformRootFilesystemUsage
|
||||
exp_alerts:${expected}
|
||||
EOF
|
||||
}
|
||||
|
||||
usage_alert() {
|
||||
local severity=$1 threshold=$2 summary=$3 description=$4
|
||||
cat <<EOF
|
||||
|
||||
- exp_labels:
|
||||
${ALERT_LABELS}
|
||||
severity: ${severity}
|
||||
threshold: "${threshold}"
|
||||
exp_annotations:
|
||||
summary: ${summary}
|
||||
description: ${description}
|
||||
runbook_url: ${RUNBOOK_URL}
|
||||
EOF
|
||||
}
|
||||
|
||||
readonly WARNING_ALERT="$(usage_alert warning 80 \
|
||||
'루트 파일시스템 사용률이 80%를 초과함' \
|
||||
'노드 루트 파일시스템 사용률이 80%를 10분간 초과했습니다. 85%에서 kubelet이 이미지를 지우기 시작합니다.')"
|
||||
readonly CRITICAL_ALERT="$(usage_alert critical 85 \
|
||||
'루트 파일시스템 사용률이 85%를 초과함' \
|
||||
'노드 루트 파일시스템 사용률이 85%를 5분간 초과했습니다. kubelet이 안 쓰는 이미지를 지우는 중이고 90%에서 파드를 내보냅니다.')"
|
||||
|
||||
forecast_case() {
|
||||
# name, starting avail, avail change per minute, eval minute, expected alerts
|
||||
local name=$1 start=$2 step=$3 eval_minute=$4 expected=$5
|
||||
cat <<EOF
|
||||
- name: ${name}
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'node_filesystem_avail_bytes{${SERIES_LABELS}}'
|
||||
values: '${start}${step}x60'
|
||||
- series: 'node_filesystem_size_bytes{${SERIES_LABELS}}'
|
||||
values: '1000+0x60'
|
||||
alert_rule_test:
|
||||
- eval_time: ${eval_minute}m
|
||||
alertname: PlatformRootFilesystemFillingFast
|
||||
exp_alerts:${expected}
|
||||
EOF
|
||||
}
|
||||
|
||||
readonly FORECAST_ALERT="
|
||||
- exp_labels:
|
||||
${ALERT_LABELS}
|
||||
severity: critical
|
||||
exp_annotations:
|
||||
summary: 루트 파일시스템이 6시간 안에 축출 문턱에 닿을 것으로 예측됨
|
||||
description: 최근 6시간 추세대로면 루트 파일시스템 여유가 6시간 안에 10% 아래로 내려갑니다. 10% 아래에서 kubelet이 파드를 내보냅니다.
|
||||
runbook_url: ${RUNBOOK_URL}"
|
||||
|
||||
{
|
||||
printf '%s\n' \
|
||||
'rule_files:' \
|
||||
' - /work/core.rules.json' \
|
||||
' - /work/backup.rules.json' \
|
||||
'evaluation_interval: 1m' \
|
||||
'tests:'
|
||||
usage_case 'warning stays quiet at 79 percent' 79 11 ' []'
|
||||
usage_case 'warning fires at 81 percent after 10 minutes' 81 11 "$WARNING_ALERT"
|
||||
usage_case 'warning is still pending at 81 percent after 9 minutes' 81 9 ' []'
|
||||
usage_case 'critical fires at 86 percent after 5 minutes' 86 6 "$CRITICAL_ALERT"
|
||||
usage_case 'warning and critical both fire at 86 percent after 10 minutes' 86 11 "${WARNING_ALERT}${CRITICAL_ALERT}"
|
||||
# 1000 bytes, 400 free, losing 1 per minute: the 6h trend reaches the
|
||||
# 100-byte eviction point in 300 minutes.
|
||||
forecast_case 'forecast fires for a fast fill after 15 minutes' 400 '-1' 16 "$FORECAST_ALERT"
|
||||
forecast_case 'forecast is still pending before 15 minutes' 400 '-1' 14 ' []'
|
||||
# Losing 0.1 per minute takes far longer than 6 hours to reach 100.
|
||||
forecast_case 'forecast stays quiet for a slow fill' 400 '-0.1' 30 ' []'
|
||||
forecast_case 'forecast stays quiet for flat usage' 400 '+0' 30 ' []'
|
||||
|
||||
# PostgreSQL backups. Timestamps are seconds since the test epoch.
|
||||
cat <<EOF
|
||||
# The test clock starts at 0, so "27.8 hours ago" is a negative timestamp.
|
||||
# In production a cluster without any backup reports 0 and fires the same way.
|
||||
- name: backup alert fires when the last backup is older than 26 hours
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'cnpg_collector_last_available_backup_timestamp{${PG_LABELS}}'
|
||||
values: '-100000+0x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 31m
|
||||
alertname: PlatformPostgresBackupMissing
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
job: platform-postgres
|
||||
namespace: platform-data
|
||||
severity: critical
|
||||
exp_annotations:
|
||||
summary: platform-postgres에 26시간 안에 끝난 백업이 없음
|
||||
description: platform-postgres의 마지막 성공한 base backup이 26시간보다 오래됐거나 없습니다. 매일 03:00 KST 백업(ScheduledBackup platform-postgres-daily)을 확인하세요.
|
||||
runbook_url: ${BACKUP_RUNBOOK_URL}
|
||||
- name: backup alert stays quiet after a fresh backup
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'cnpg_collector_last_available_backup_timestamp{${PG_LABELS}}'
|
||||
values: '60+0x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 31m
|
||||
alertname: PlatformPostgresBackupMissing
|
||||
exp_alerts: []
|
||||
- name: WAL backlog fires after 15 minutes
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'cnpg_collector_pg_wal_archive_status{${PG_LABELS},value="ready"}'
|
||||
values: '11+0x30'
|
||||
- series: 'cnpg_collector_pg_wal_archive_status{${PG_LABELS},value="done"}'
|
||||
values: '500+0x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 16m
|
||||
alertname: PlatformPostgresWALArchiveBacklog
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
job: platform-postgres
|
||||
namespace: platform-data
|
||||
severity: critical
|
||||
exp_annotations:
|
||||
summary: platform-postgres의 WAL이 보관소로 올라가지 않음
|
||||
description: 보관을 기다리는 WAL 파일이 10개를 넘은 채 15분이 지났습니다. 보관이 막히면 WAL이 PostgreSQL 볼륨에 쌓여 디스크가 찹니다.
|
||||
runbook_url: ${BACKUP_RUNBOOK_URL}
|
||||
- name: WAL backlog stays quiet at 10 ready files
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'cnpg_collector_pg_wal_archive_status{${PG_LABELS},value="ready"}'
|
||||
values: '10+0x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 20m
|
||||
alertname: PlatformPostgresWALArchiveBacklog
|
||||
exp_alerts: []
|
||||
- name: ingestion alert fires when node-exporter samples stop
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'up{job="prometheus-node-exporter",instance="10.42.0.95:9100"}'
|
||||
values: '1x5 _x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 20m
|
||||
alertname: PlatformMetricsIngestionStopped
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
job: prometheus-node-exporter
|
||||
severity: critical
|
||||
exp_annotations:
|
||||
summary: Prometheus에 새 지표가 저장되지 않음
|
||||
description: 5분 넘게 node-exporter의 up 샘플이 저장되지 않았습니다. Prometheus가 샘플을 버리고 있으면(예 시계가 되돌아감) 다른 지표 경보도 울리지 않습니다.
|
||||
runbook_url: ${RUNBOOK_URL}
|
||||
- name: ingestion alert stays quiet while samples arrive
|
||||
interval: 1m
|
||||
input_series:
|
||||
- series: 'up{job="prometheus-node-exporter",instance="10.42.0.95:9100"}'
|
||||
values: '1x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 20m
|
||||
alertname: PlatformMetricsIngestionStopped
|
||||
exp_alerts: []
|
||||
- name: heartbeat always fires
|
||||
interval: 1m
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: PlatformHeartbeat
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: none
|
||||
exp_annotations:
|
||||
summary: 경보 경로 heartbeat
|
||||
description: 항상 울린다. Alertmanager가 이 경보를 외부 dead man's switch로 5분마다 보내고, 끊기면 외부 서비스가 알린다.
|
||||
runbook_url: ${RUNBOOK_URL}
|
||||
EOF
|
||||
} >"${temp_dir}/disk.test.yaml"
|
||||
|
||||
chmod 0444 "${temp_dir}"/*
|
||||
docker run --rm \
|
||||
--network none \
|
||||
--volume "${temp_dir}:/work:ro" \
|
||||
--entrypoint /bin/promtool \
|
||||
"$PROMETHEUS_IMAGE" check rules /work/core.rules.json /work/backup.rules.json
|
||||
docker run --rm \
|
||||
--network none \
|
||||
--volume "${temp_dir}:/work:ro" \
|
||||
--entrypoint /bin/promtool \
|
||||
"$PROMETHEUS_IMAGE" test rules /work/disk.test.yaml
|
||||
printf 'PASS: root filesystem, PostgreSQL backup, ingestion and heartbeat alerts\n'
|
||||
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env bash
|
||||
# promtool unit tests for services/platform-host-checks/prometheus-rules.yaml.
|
||||
# Needs docker and python3 (PyYAML). No cluster access.
|
||||
set -Eeuo pipefail
|
||||
|
||||
readonly ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
|
||||
# Same pinned image as test-platform-observability-rules.sh.
|
||||
readonly PROMETHEUS_IMAGE="quay.io/prometheus/prometheus:v3.13.2-distroless@sha256:ce95cfa77eff5aad28bd7a65aff19868cf78d9e17e4c254da7dfe22ade78318b"
|
||||
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
python3 -I - "$ROOT/services/platform-host-checks/prometheus-rules.yaml" "$work/rules.yaml" <<'PY'
|
||||
import sys, yaml
|
||||
rule = yaml.safe_load(open(sys.argv[1]))
|
||||
yaml.safe_dump({"groups": rule["spec"]["groups"]}, open(sys.argv[2], "w"), sort_keys=False)
|
||||
PY
|
||||
|
||||
# promtool evaluates from Unix time 0, so "now" in each test is the eval_time.
|
||||
cat >"$work/tests.yaml" <<'EOF'
|
||||
rule_files:
|
||||
- rules.yaml
|
||||
evaluation_interval: 1m
|
||||
tests:
|
||||
# k3s datastore: last success at t=0; stale after 2 days, alert after 1h more.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: 'platform_backup_last_success_timestamp_seconds{backup="k3s-datastore"}'
|
||||
values: '0x5500'
|
||||
- series: 'platform_backup_last_run_timestamp_seconds{backup="k3s-datastore"}'
|
||||
values: '0x5500'
|
||||
- series: 'platform_backup_last_run_timestamp_seconds{backup="gitea"}'
|
||||
values: '0x5500'
|
||||
- series: 'platform_backup_last_success_timestamp_seconds{backup="gitea"}'
|
||||
values: '0x5500'
|
||||
alert_rule_test:
|
||||
- eval_time: 24h
|
||||
alertname: PlatformK3sDatastoreBackupTooOld
|
||||
exp_alerts: []
|
||||
- eval_time: 50h
|
||||
alertname: PlatformK3sDatastoreBackupTooOld
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: k3s datastore has not been backed up for more than 2 days
|
||||
description: Check `journalctl -u platform-k3s-datastore-backup` on desktop. Daily timer, 03:30 KST.
|
||||
- eval_time: 90h
|
||||
alertname: PlatformGiteaBackupTooOld
|
||||
exp_alerts: []
|
||||
- eval_time: 90h
|
||||
alertname: PlatformHostBackupMetricsAbsent
|
||||
exp_alerts: []
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: 'platform_backup_last_success_timestamp_seconds{backup="gitea"}'
|
||||
values: '0x11700'
|
||||
alert_rule_test:
|
||||
- eval_time: 194h
|
||||
alertname: PlatformGiteaBackupTooOld
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: Gitea has not been backed up for more than 8 days
|
||||
description: Check `journalctl -u platform-gitea-backup` on desktop. Weekly timer, Sunday 04:00 KST.
|
||||
# A failed run is reported with its backup label.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: 'platform_backup_last_run_success{backup="gitea",instance="desktop"}'
|
||||
values: '0x30'
|
||||
- series: 'platform_backup_last_run_success{backup="k3s-datastore",instance="desktop"}'
|
||||
values: '1x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 15m
|
||||
alertname: PlatformHostBackupFailed
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, backup: gitea}
|
||||
exp_annotations:
|
||||
summary: "The last gitea backup run failed"
|
||||
description: "Check `journalctl -u platform-gitea-backup` on desktop."
|
||||
# Metrics never written (timers or textfile collector missing).
|
||||
- interval: 1h
|
||||
input_series:
|
||||
- series: 'up{job="prometheus-node-exporter"}'
|
||||
values: '1x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 25h
|
||||
alertname: PlatformHostBackupMetricsAbsent
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, backup: k3s-datastore}
|
||||
exp_annotations:
|
||||
summary: Host backup metrics are missing
|
||||
description: The backup timers or the node-exporter textfile collector (/var/lib/node_exporter/textfile_collector) are not running.
|
||||
- exp_labels: {severity: warning, backup: gitea}
|
||||
exp_annotations:
|
||||
summary: Host backup metrics are missing
|
||||
description: The backup timers or the node-exporter textfile collector (/var/lib/node_exporter/textfile_collector) are not running.
|
||||
# Drift for 7h fires; drift 0 does not.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: 'platform_live_drift_objects'
|
||||
values: '3x500'
|
||||
- series: 'platform_live_drift_last_run_timestamp_seconds'
|
||||
values: '0x500'
|
||||
- series: 'platform_live_drift_check_success'
|
||||
values: '1x500'
|
||||
alert_rule_test:
|
||||
- eval_time: 5h
|
||||
alertname: PlatformLiveDriftDetected
|
||||
exp_alerts: []
|
||||
- eval_time: 7h
|
||||
alertname: PlatformLiveDriftDetected
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: "3 live objects differ from platform-core origin/main"
|
||||
description: Run `scripts/validate/live-drift-check.sh --accepted scripts/validate/live-drift-accepted.txt` on desktop to list them.
|
||||
- eval_time: 7h
|
||||
alertname: PlatformLiveDriftCheckStale
|
||||
exp_alerts: []
|
||||
# Certificates: 50 days left -> warning only; 10 days left -> warning and critical.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: 'platform_k3s_certificate_not_after_seconds{certificate="apiserver"}'
|
||||
values: '4320000x200'
|
||||
- series: 'platform_k3s_certificate_not_after_seconds{certificate="kubelet"}'
|
||||
values: '864000x200'
|
||||
- series: 'platform_k3s_certificate_check_timestamp_seconds'
|
||||
values: '0x200'
|
||||
alert_rule_test:
|
||||
- eval_time: 2h
|
||||
alertname: PlatformK3sServingCertificateExpiry
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, certificate: apiserver}
|
||||
exp_annotations:
|
||||
summary: "k3s apiserver serving certificate expires in less than 100 days"
|
||||
description: k3s renews certificates only when it starts within 120 days of expiry. Plan a k3s restart window (docs/runbooks).
|
||||
- exp_labels: {severity: warning, certificate: kubelet}
|
||||
exp_annotations:
|
||||
summary: "k3s kubelet serving certificate expires in less than 100 days"
|
||||
description: k3s renews certificates only when it starts within 120 days of expiry. Plan a k3s restart window (docs/runbooks).
|
||||
- exp_labels: {severity: critical, certificate: kubelet}
|
||||
exp_annotations:
|
||||
summary: "k3s kubelet serving certificate expires in less than 14 days"
|
||||
description: Restart k3s (it renews certificates within 120 days of expiry) or run `k3s certificate rotate`.
|
||||
- eval_time: 2h
|
||||
alertname: PlatformK3sCertificateCheckStale
|
||||
exp_alerts: []
|
||||
EOF
|
||||
|
||||
docker run --rm --user "$(id -u):$(id -g)" -v "$work:/work:ro" -w /work --entrypoint /bin/promtool "$PROMETHEUS_IMAGE" check rules rules.yaml
|
||||
docker run --rm --user "$(id -u):$(id -g)" -v "$work:/work:ro" -w /work --entrypoint /bin/promtool "$PROMETHEUS_IMAGE" test rules tests.yaml
|
||||
echo "PLATFORM HOST CHECK ALERTS PASS"
|
||||
@@ -197,7 +197,7 @@ write_file "$alertmanager_fixture" \
|
||||
' alertmanagerConfiguration:' \
|
||||
' name: platform-alertmanager'
|
||||
alerting_fixture="$fixture_dir/alerting.yaml"
|
||||
write_file "$alerting_fixture" '{"apiVersion":"monitoring.coreos.com/v1alpha1","kind":"AlertmanagerConfig","metadata":{"name":"platform-alertmanager","namespace":"observability","labels":{"observability.hyeonworks.com/instance":"home"}},"spec":{"route":{"receiver":"platform-slack","groupBy":["cluster","namespace","alertname","severity"],"groupWait":"30s","groupInterval":"5m","repeatInterval":"4h","routes":[{"receiver":"platform-null","matchers":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}]},{"receiver":"platform-heartbeat","matchers":[{"name":"alertname","matchType":"=","value":"PlatformHeartbeat"}],"groupWait":"0s","groupInterval":"1m","repeatInterval":"5m"}]},"inhibitRules":[{"sourceMatch":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}],"targetMatch":[{"name":"severity","matchType":"=","value":"info"}],"equal":["namespace"]}],"receivers":[{"name":"platform-null"},{"name":"platform-heartbeat","webhookConfigs":[{"urlSecret":{"name":"alertmanager-heartbeat","key":"url"},"sendResolved":false,"maxAlerts":1}]},{"name":"platform-slack","slackConfigs":[{"apiURL":{"name":"alertmanager-slack-webhook","key":"url"},"sendResolved":true,"linkNames":false,"mrkdwnIn":["text","fields"],"fallback":"{{ if eq .Status \"firing\" }}FIRING{{ else }}RESOLVED{{ end }}: {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","title":"{{ if eq .Status \"firing\" }}[FIRING:{{ .Alerts.Firing | len }}]{{ else }}[RESOLVED]{{ end }} {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","titleLink":"https://grafana.learn.hyeonworks.com/","color":"{{ if eq .Status \"resolved\" }}good{{ else if or (eq .CommonLabels.severity \"emergency\") (eq .CommonLabels.severity \"critical\") }}danger{{ else if eq .CommonLabels.severity \"warning\" }}warning{{ else }}#439FE0{{ end }}","fields":[{"title":"Status","value":"{{ .Status | toUpper }}","short":true},{"title":"Severity","value":"{{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }}","short":true},{"title":"Location","value":"{{ if .CommonLabels.cluster }}{{ .CommonLabels.cluster }}{{ else }}unknown-cluster{{ end }} / {{ if .CommonLabels.namespace }}{{ .CommonLabels.namespace }}{{ else }}cluster-scoped{{ end }}","short":true},{"title":"Alert count","value":"{{ len .Alerts }}","short":true}],"text":"{{ range .Alerts }}\n*Alert status:* {{ .Status | toUpper }}\n*Target:* {{ $target := .Labels.Remove $.GroupLabels.Names }}{{ if $target }}{{ range $target.SortedPairs }}{{ .Name }}={{ .Value }} {{ end }}{{ else }}unknown{{ end }}\n*Summary:* {{ with .Annotations.summary }}{{ . }}{{ else }}No summary provided{{ end }}\n*Details:* {{ with .Annotations.description }}{{ . }}{{ else }}No description provided{{ end }}\n*Started:* {{ .StartsAt.Format \"2006-01-02T15:04:05Z07:00\" }}\n{{ if eq .Status \"resolved\" }}*Ended:* {{ .EndsAt.Format \"2006-01-02T15:04:05Z07:00\" }}{{ end }}\n{{ with .Annotations.runbook_url }}*Runbook:* <{{ . }}|대응 절차 열기>{{ end }}\n\n{{ end }}\n<https://grafana.learn.hyeonworks.com/|Grafana> · <https://grafana.learn.hyeonworks.com/explore|Explore>","footer":"hyeonworks observability · Alertmanager"}]}]}}' \
|
||||
write_file "$alerting_fixture" '{"apiVersion":"monitoring.coreos.com/v1alpha1","kind":"AlertmanagerConfig","metadata":{"name":"platform-alertmanager","namespace":"observability","labels":{"observability.hyeonworks.com/instance":"home"}},"spec":{"route":{"receiver":"platform-slack","groupBy":["cluster","namespace","alertname","severity"],"groupWait":"30s","groupInterval":"5m","repeatInterval":"4h","routes":[{"receiver":"platform-null","matchers":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}]}]},"inhibitRules":[{"sourceMatch":[{"name":"alertname","matchType":"=","value":"InfoInhibitor"}],"targetMatch":[{"name":"severity","matchType":"=","value":"info"}],"equal":["namespace"]}],"receivers":[{"name":"platform-null"},{"name":"platform-slack","slackConfigs":[{"apiURL":{"name":"alertmanager-slack-webhook","key":"url"},"sendResolved":true,"linkNames":false,"mrkdwnIn":["text","fields"],"fallback":"{{ if eq .Status \"firing\" }}FIRING{{ else }}RESOLVED{{ end }}: {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","title":"{{ if eq .Status \"firing\" }}[FIRING:{{ .Alerts.Firing | len }}]{{ else }}[RESOLVED]{{ end }} {{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }} · {{ .CommonLabels.alertname }}","titleLink":"https://grafana.learn.hyeonworks.com/","color":"{{ if eq .Status \"resolved\" }}good{{ else if or (eq .CommonLabels.severity \"emergency\") (eq .CommonLabels.severity \"critical\") }}danger{{ else if eq .CommonLabels.severity \"warning\" }}warning{{ else }}#439FE0{{ end }}","fields":[{"title":"Status","value":"{{ .Status | toUpper }}","short":true},{"title":"Severity","value":"{{ if .CommonLabels.severity }}{{ .CommonLabels.severity | toUpper }}{{ else }}UNKNOWN{{ end }}","short":true},{"title":"Location","value":"{{ if .CommonLabels.cluster }}{{ .CommonLabels.cluster }}{{ else }}unknown-cluster{{ end }} / {{ if .CommonLabels.namespace }}{{ .CommonLabels.namespace }}{{ else }}cluster-scoped{{ end }}","short":true},{"title":"Alert count","value":"{{ len .Alerts }}","short":true}],"text":"{{ range .Alerts }}\n*Alert status:* {{ .Status | toUpper }}\n*Target:* {{ $target := .Labels.Remove $.GroupLabels.Names }}{{ if $target }}{{ range $target.SortedPairs }}{{ .Name }}={{ .Value }} {{ end }}{{ else }}unknown{{ end }}\n*Summary:* {{ with .Annotations.summary }}{{ . }}{{ else }}No summary provided{{ end }}\n*Details:* {{ with .Annotations.description }}{{ . }}{{ else }}No description provided{{ end }}\n*Started:* {{ .StartsAt.Format \"2006-01-02T15:04:05Z07:00\" }}\n{{ if eq .Status \"resolved\" }}*Ended:* {{ .EndsAt.Format \"2006-01-02T15:04:05Z07:00\" }}{{ end }}\n{{ with .Annotations.runbook_url }}*Runbook:* <{{ . }}|대응 절차 열기>{{ end }}\n\n{{ end }}\n<https://grafana.learn.hyeonworks.com/|Grafana> · <https://grafana.learn.hyeonworks.com/explore|Explore>","footer":"hyeonworks observability · Alertmanager"}]}]}}' \
|
||||
'---' \
|
||||
'apiVersion: networking.k8s.io/v1' \
|
||||
'kind: NetworkPolicy' \
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
# Alertmanager 경로
|
||||
|
||||
`platform-alertmanager.yaml`은 kube-prometheus-stack이 전역
|
||||
`alertmanagerConfiguration`으로 읽는 AlertmanagerConfig 하나다. 경로는 셋이다.
|
||||
|
||||
| 경보 | receiver | 보내는 곳 |
|
||||
| --- | --- | --- |
|
||||
| `InfoInhibitor` | `platform-null` | 버린다 |
|
||||
| `PlatformHeartbeat` | `platform-heartbeat` | 외부 heartbeat 서비스(dead man's switch), 5분마다 |
|
||||
| 나머지 | `platform-slack` | Slack, 4시간마다 다시 |
|
||||
|
||||
## heartbeat (dead man's switch)
|
||||
|
||||
`PlatformHeartbeat`(`rules/platform/core-rules.yaml`)는 항상 울린다. Alertmanager가 이것을
|
||||
5분마다 외부 서비스의 ping URL로 보낸다. ping이 끊기면 그 서비스가 소유자에게 알린다.
|
||||
|
||||
- 막는 것: Prometheus·Alertmanager가 죽었을 때, desktop이나 인터넷 연결이 끊겼을 때.
|
||||
이 경우는 클러스터 안의 어떤 규칙도 알리지 못한다.
|
||||
- 막지 못하는 것: Prometheus가 돌면서 샘플만 버리는 경우(2026-11-11 시계 사고). 규칙은 돌고
|
||||
heartbeat도 계속 나간다. 그 경우는 `PlatformMetricsIngestionStopped`가 Slack으로 알린다.
|
||||
|
||||
### 소유자가 할 일 (적용 전에 한 번)
|
||||
|
||||
1. 외부 heartbeat 서비스에 check를 하나 만든다. 예: healthchecks.io(무료 요금제, 오픈소스라
|
||||
나중에 직접 띄울 수도 있다). 주기 5분, 유예 10분. 알림은 Slack이 아닌 곳(메일·휴대폰)도
|
||||
하나 건다. Slack 경로가 죽었을 때도 알아야 하기 때문이다.
|
||||
2. ping URL을 Secret으로 만든다. URL 자체가 자격 증명이라 화면에 남기지 않는다.
|
||||
|
||||
```bash
|
||||
read -rs HEARTBEAT_URL # ping URL 붙여 넣기, 화면에 안 보임
|
||||
printf '%s' "$HEARTBEAT_URL" | kubectl -n observability create secret generic alertmanager-heartbeat \
|
||||
--from-file=url=/dev/stdin
|
||||
unset HEARTBEAT_URL
|
||||
```
|
||||
|
||||
3. 그 뒤에 rules·alerts를 다시 적용한다(`scripts/bootstrap/apply-observability-access.sh
|
||||
--execute --rules-alerts`). **Secret보다 먼저 적용하지 않는다.** operator가 없는 Secret을
|
||||
가리키는 AlertmanagerConfig로는 설정을 만들지 못한다.
|
||||
4. 확인: 외부 서비스의 check가 5분 안에 「up」이 된다. Alertmanager 지표
|
||||
`alertmanager_notifications_total{integration="webhook"}`가 5분마다 는다.
|
||||
|
||||
Alertmanager egress는 공개 IPv4 TCP/443만 허용한다(`alertmanager-public-https-egress.yaml`).
|
||||
ping URL은 HTTPS여야 한다.
|
||||
@@ -22,16 +22,6 @@ spec:
|
||||
- name: alertname
|
||||
matchType: "="
|
||||
value: InfoInhibitor
|
||||
# PlatformHeartbeat always fires. Sending it every 5 minutes keeps the
|
||||
# external dead man's switch quiet; when it stops, that service alerts.
|
||||
- receiver: platform-heartbeat
|
||||
matchers:
|
||||
- name: alertname
|
||||
matchType: "="
|
||||
value: PlatformHeartbeat
|
||||
groupWait: 0s
|
||||
groupInterval: 1m
|
||||
repeatInterval: 5m
|
||||
inhibitRules:
|
||||
- sourceMatch:
|
||||
- name: alertname
|
||||
@@ -45,15 +35,6 @@ spec:
|
||||
- namespace
|
||||
receivers:
|
||||
- name: platform-null
|
||||
- name: platform-heartbeat
|
||||
webhookConfigs:
|
||||
# Ping URL of the external heartbeat check. Create the Secret before
|
||||
# applying this file; see services/observability/alerting/README.md.
|
||||
- urlSecret:
|
||||
name: alertmanager-heartbeat
|
||||
key: url
|
||||
sendResolved: false
|
||||
maxAlerts: 1
|
||||
- name: platform-slack
|
||||
slackConfigs:
|
||||
- apiURL:
|
||||
|
||||
@@ -13,3 +13,10 @@ Alertmanager source는 selector discovery 대신 global
|
||||
`alertmanagerConfiguration.name=platform-alertmanager`를 참조한다. 참조 대상의
|
||||
Slack Secret이 준비되기 전에는 이 변경을 live에 적용하지 않고 기존 null 구성을
|
||||
유지한다.
|
||||
|
||||
Prometheus TSDB는 `outOfOrderTimeWindow: 10h`로 늦게 도착한 샘플을 받는다. 시계가
|
||||
앞으로 튀었다가 되돌아오면 TSDB 머리에 미래 시각 샘플이 남고, 창이 0이면 그 시각이
|
||||
지날 때까지 모든 수집이 `out of bounds`로 버려진다. 메트릭과 경보가 함께 멈추고,
|
||||
`absent()` 경보(`KubeAPIDown` 등)는 거짓으로 울린다. 10시간은 재부팅 때 RTC의 KST를
|
||||
UTC로 읽는 +9시간 오차를 덮는 값이다(2026-11-11 사고). 늦은 샘플이 없으면 추가 메모리는
|
||||
거의 들지 않는다. 시계 자체를 막는 설정은 `infrastructure/host`가 맡는다.
|
||||
|
||||
@@ -34,6 +34,11 @@ kubeProxy:
|
||||
defaultRules:
|
||||
disabled:
|
||||
Watchdog: true
|
||||
# k3s kubelet exposes no kubelet_certificate_manager_* metrics, so these two
|
||||
# can never fire. Serving certificates are watched by platform-host-checks
|
||||
# (PlatformK3sServingCertificateExpiry) instead. Review 2026-11-11 A11.
|
||||
KubeletClientCertificateExpiration: true
|
||||
KubeletServerCertificateExpiration: true
|
||||
rules:
|
||||
etcd: false
|
||||
kubeControllerManager: false
|
||||
@@ -219,6 +224,8 @@ prometheus:
|
||||
scrapeInterval: 30s
|
||||
evaluationInterval: 30s
|
||||
walCompression: true
|
||||
tsdb:
|
||||
outOfOrderTimeWindow: 10h
|
||||
automountServiceAccountToken: true
|
||||
image:
|
||||
registry: quay.io
|
||||
|
||||
@@ -32,11 +32,7 @@ resources:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
# Average use is about 2m, but each scrape runs the collectors in
|
||||
# parallel. At 250m (25ms per 100ms CFS period) 26% of periods were
|
||||
# throttled on 2026-11-11. One core removes the throttling and still caps
|
||||
# a runaway collector.
|
||||
cpu: "1"
|
||||
cpu: 250m
|
||||
memory: 256Mi
|
||||
|
||||
serviceAccount:
|
||||
|
||||
@@ -41,14 +41,14 @@ spec:
|
||||
node_filesystem_avail_bytes{job="prometheus-node-exporter",mountpoint="/",fstype!~"rootfs|tmpfs|ramfs|squashfs|overlay|nsfs|tracefs|debugfs|securityfs|proc|sysfs|cgroup2?"}
|
||||
/
|
||||
node_filesystem_size_bytes{job="prometheus-node-exporter",mountpoint="/",fstype!~"rootfs|tmpfs|ramfs|squashfs|overlay|nsfs|tracefs|debugfs|securityfs|proc|sysfs|cgroup2?"}
|
||||
) > 80
|
||||
for: 10m
|
||||
) > 85
|
||||
for: 15m
|
||||
labels:
|
||||
severity: warning
|
||||
threshold: "80"
|
||||
threshold: "85"
|
||||
annotations:
|
||||
summary: 루트 파일시스템 사용률이 80%를 초과함
|
||||
description: 노드 루트 파일시스템 사용률이 80%를 10분간 초과했습니다. 85%에서 kubelet이 이미지를 지우기 시작합니다.
|
||||
summary: 루트 파일시스템 사용률이 85%를 초과함
|
||||
description: 노드 루트 파일시스템 사용률이 경고 임계치인 85%를 15분간 초과했습니다.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/project-infra/src/branch/main/docs/runbooks/2026-07-31-observability-access-cutover.md
|
||||
- alert: PlatformRootFilesystemUsage
|
||||
expr: >-
|
||||
@@ -56,32 +56,14 @@ spec:
|
||||
node_filesystem_avail_bytes{job="prometheus-node-exporter",mountpoint="/",fstype!~"rootfs|tmpfs|ramfs|squashfs|overlay|nsfs|tracefs|debugfs|securityfs|proc|sysfs|cgroup2?"}
|
||||
/
|
||||
node_filesystem_size_bytes{job="prometheus-node-exporter",mountpoint="/",fstype!~"rootfs|tmpfs|ramfs|squashfs|overlay|nsfs|tracefs|debugfs|securityfs|proc|sysfs|cgroup2?"}
|
||||
) > 85
|
||||
) > 90
|
||||
for: 5m
|
||||
labels:
|
||||
severity: critical
|
||||
threshold: "85"
|
||||
threshold: "90"
|
||||
annotations:
|
||||
summary: 루트 파일시스템 사용률이 85%를 초과함
|
||||
description: 노드 루트 파일시스템 사용률이 85%를 5분간 초과했습니다. kubelet이 안 쓰는 이미지를 지우는 중이고 90%에서 파드를 내보냅니다.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/project-infra/src/branch/main/docs/runbooks/2026-07-31-observability-access-cutover.md
|
||||
# kubelet evicts pods when nodefs.available drops below 10%. Fire when
|
||||
# the 6h trend says that happens within the next 6 hours, so a fast
|
||||
# fill (17G in 9h on 2026-11-07) is caught before the 80% warning.
|
||||
- alert: PlatformRootFilesystemFillingFast
|
||||
expr: >-
|
||||
predict_linear(
|
||||
node_filesystem_avail_bytes{job="prometheus-node-exporter",mountpoint="/",fstype!~"rootfs|tmpfs|ramfs|squashfs|overlay|nsfs|tracefs|debugfs|securityfs|proc|sysfs|cgroup2?"}[6h],
|
||||
6 * 3600
|
||||
)
|
||||
<
|
||||
0.10 * node_filesystem_size_bytes{job="prometheus-node-exporter",mountpoint="/",fstype!~"rootfs|tmpfs|ramfs|squashfs|overlay|nsfs|tracefs|debugfs|securityfs|proc|sysfs|cgroup2?"}
|
||||
for: 15m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: 루트 파일시스템이 6시간 안에 축출 문턱에 닿을 것으로 예측됨
|
||||
description: 최근 6시간 추세대로면 루트 파일시스템 여유가 6시간 안에 10% 아래로 내려갑니다. 10% 아래에서 kubelet이 파드를 내보냅니다.
|
||||
summary: 루트 파일시스템 사용률이 90%를 초과함
|
||||
description: 노드 루트 파일시스템 사용률이 심각 임계치인 90%를 5분간 초과했습니다.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/project-infra/src/branch/main/docs/runbooks/2026-07-31-observability-access-cutover.md
|
||||
- alert: PlatformRootFilesystemInodes
|
||||
expr: >-
|
||||
@@ -113,32 +95,6 @@ spec:
|
||||
summary: 루트 파일시스템 inode 사용률이 90%를 초과함
|
||||
description: 노드 루트 파일시스템 inode 사용률이 심각 임계치인 90%를 15분간 초과했습니다.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/project-infra/src/branch/main/docs/runbooks/2026-07-31-observability-access-cutover.md
|
||||
- name: platform.monitoring
|
||||
rules:
|
||||
# When the TSDB rejects every sample (2026-11-11: the clock went back
|
||||
# after samples were stored 9 hours ahead) rules still run, but on no
|
||||
# data. absent() is one of the few expressions that still fires then.
|
||||
- alert: PlatformMetricsIngestionStopped
|
||||
expr: absent(up{job="prometheus-node-exporter"})
|
||||
for: 5m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: Prometheus에 새 지표가 저장되지 않음
|
||||
description: 5분 넘게 node-exporter의 up 샘플이 저장되지 않았습니다. Prometheus가 샘플을 버리고 있으면(예 시계가 되돌아감) 다른 지표 경보도 울리지 않습니다.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/project-infra/src/branch/main/docs/runbooks/2026-07-31-observability-access-cutover.md
|
||||
# Dead man's switch. Alertmanager forwards this to an external
|
||||
# heartbeat service; when the heartbeat stops, that service alerts.
|
||||
# It covers what no rule here can: Prometheus, Alertmanager or the
|
||||
# whole node being down.
|
||||
- alert: PlatformHeartbeat
|
||||
expr: vector(1)
|
||||
labels:
|
||||
severity: none
|
||||
annotations:
|
||||
summary: 경보 경로 heartbeat
|
||||
description: 항상 울린다. Alertmanager가 이 경보를 외부 dead man's switch로 5분마다 보내고, 끊기면 외부 서비스가 알린다.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/project-infra/src/branch/main/docs/runbooks/2026-07-31-observability-access-cutover.md
|
||||
- name: platform.workloads
|
||||
rules:
|
||||
- alert: PlatformPodRestartBurst
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# 호스트 백업과 점검
|
||||
|
||||
desktop 호스트에서 systemd 타이머로 도는 백업과 점검이다. 결과는 node-exporter textfile 수집기
|
||||
(`/var/lib/node_exporter/textfile_collector/*.prom`)로 Prometheus에 올라가고, 이 폴더의 PrometheusRule이
|
||||
경보를 낸다. 근거와 결정은 `docs/reviews/2026-11-11-k3s-maturity-review.md` A1·A11·A13·A14, 8절 결정 1·6이다.
|
||||
|
||||
## 무엇을 어디에 얼마나
|
||||
|
||||
| 대상 | 방법 | 주기 | 보관 | 위치 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| k3s datastore + `server/token` | `sqlite3 .backup` → tar.gz + sha256 | 매일 03:30 KST | AIStor 30일 + 로컬 최근 7개 | AIStor `platform-host-backups/k3s-datastore/`와 `/srv/k3s/aistor/host-backups/k3s-datastore/`(root 0700). 둘 다 HDD sdb3 |
|
||||
| Gitea (저장소·패키지·첨부·Actions·`app.ini`) | 라이브 파드에서 `gitea dump --skip-db` | 일요일 04:00 KST | 56일(8주) | AIStor `platform-host-backups/gitea/` |
|
||||
| platform-postgres (Gitea·Keycloak·tech-log DB) | CloudNativePG base backup + WAL | 매일 03:00 KST | 30일 | AIStor `platform-postgres-backups/` (W1, `services/platform-postgres-backup`) |
|
||||
| AIStor 데이터(Loki·Tempo) | **백업하지 않는다** | — | — | 8절 결정 6: 잃어도 되는 관측 데이터. 디스크를 잃으면 로그·추적 기록만 사라진다 |
|
||||
| Prometheus·Grafana·Alertmanager PV | 백업하지 않는다 | — | — | 설정은 이 저장소가 정본이고, 지표는 다시 쌓인다 |
|
||||
|
||||
- Gitea DB는 dump에 없다(`--skip-db`). Gitea를 복원하려면 CNPG 복원이 먼저다(`docs/runbooks/gitea-restore.md`).
|
||||
- k3s 백업에는 `token`이 들어 있다. token과 datastore가 같이 있으면 클러스터의 모든 Secret을 풀 수 있다.
|
||||
Gitea dump의 `app.ini`에도 비밀 값이 있다. 그래서 둘 다 AIStor의 전용 사용자만 읽고 쓴다.
|
||||
- AIStor는 같은 desktop의 HDD다. SSD가 죽으면 남지만 desktop 자체를 잃으면 같이 잃는다.
|
||||
- k3s 백업을 AIStor 밖에도 두는 이유: AIStor는 바로 그 k3s 위에서 돈다. 클러스터를 통째로 잃으면 AIStor를
|
||||
다시 띄우기 전에는 AIStor 안의 사본을 꺼낼 수 없다. 로컬 사본은 sdb3를 mount하기만 하면 읽힌다
|
||||
(`docs/runbooks/k3s-datastore-restore.md`). 폴더는 AIStor 드라이브 폴더(`data/`) 옆이라 bucket으로 보이지 않는다.
|
||||
|
||||
## off-host 사본 (준비만, 기본 꺼짐)
|
||||
|
||||
위치는 소유자가 정한다(8절 결정 1). `/etc/platform-backup/aistor.env`에 두 줄을 넣으면 k3s datastore
|
||||
백업이 그 공개 키로 암호화한 사본을 `rclone`으로 보낸다.
|
||||
|
||||
```bash
|
||||
OFFHOST_GPG_RECIPIENT_FILE=/etc/platform-backup/offhost-recipient.asc # 공개 키. 개인 키는 desktop에 두지 않는다
|
||||
OFFHOST_RCLONE_TARGET=<rclone remote>:<path> # rclone 설치·설정 필요
|
||||
```
|
||||
|
||||
지표 `platform_backup_offhost_copy{backup="k3s-datastore"}`가 1이 된다. Gitea dump의 off-host 사본은 아직 없다.
|
||||
|
||||
## 점검
|
||||
|
||||
| 타이머 | 사용자 | 하는 일 | 지표 |
|
||||
| --- | --- | --- | --- |
|
||||
| `platform-k3s-cert-expiry` | donghyeon | 6443·10250 serving 인증서 notAfter | `platform_k3s_certificate_not_after_seconds` |
|
||||
| `platform-live-drift-check` | donghyeon | origin/main 렌더 → `kubectl diff`(서버 dry-run) | `platform_live_drift_objects` |
|
||||
|
||||
## 경보 (`prometheus-rules.yaml`)
|
||||
|
||||
| 경보 | 조건 |
|
||||
| --- | --- |
|
||||
| `PlatformK3sDatastoreBackupTooOld` | 마지막 성공이 2일보다 오래됨 |
|
||||
| `PlatformGiteaBackupTooOld` | 8일보다 오래됨 |
|
||||
| `PlatformHostBackupFailed` | 마지막 실행 실패 |
|
||||
| `PlatformHostBackupMetricsAbsent` | 지표가 하루 동안 없음(타이머나 textfile 수집기가 안 돎) |
|
||||
| `PlatformLiveDriftDetected` | drift가 6시간 넘게 남음 |
|
||||
| `PlatformLiveDriftCheckStale` | drift 검사가 2일 넘게 완료되지 않음 |
|
||||
| `PlatformK3sServingCertificateExpiry` | 100일 미만 warning, 14일 미만 critical |
|
||||
| `PlatformK3sCertificateCheckStale` | 인증서 점검이 2일 넘게 안 돎 |
|
||||
|
||||
`scripts/validate/test-platform-host-checks-alerts.sh`가 promtool 단위 시험으로 각 경보가 울려야 할 때 울리고
|
||||
아닐 때 안 울리는지 본다. 같은 PR에서 kube-prometheus-stack의 `KubeletClientCertificateExpiration`·
|
||||
`KubeletServerCertificateExpiration`을 껐다. k3s kubelet은 그 지표를 내지 않아 울릴 수 없었다.
|
||||
|
||||
## 적용 (소유자, 순서대로)
|
||||
|
||||
전제: node-exporter textfile 수집기(W1, `services/observability/node-exporter/values/home.yaml`의
|
||||
`--collector.textfile.directory=/host/root/var/lib/node_exporter/textfile_collector`)가 들어간 main checkout.
|
||||
|
||||
```bash
|
||||
cd /home/donghyeon/workspace/platform && git pull --ff-only
|
||||
sudo bash scripts/bootstrap/create-host-backup-credentials.sh # bucket·정책·사용자·/etc/platform-backup/aistor.env (APPLY 입력)
|
||||
bash scripts/bootstrap/install-host-checks.sh --check
|
||||
sudo bash scripts/bootstrap/install-host-checks.sh --execute # 타이머 설치·켜기·첫 실행
|
||||
kubectl apply -k services/platform-host-checks # 경보 규칙
|
||||
sudo bash scripts/validate/k3s-datastore-restore-drill.sh # 첫 백업으로 복원 리허설
|
||||
sudo bash scripts/validate/gitea-backup-restore-drill.sh
|
||||
```
|
||||
|
||||
`install-host-checks.sh --execute` 마지막에 `platform_backup_last_run_success{backup="k3s-datastore"} 1`과
|
||||
`{backup="gitea"} 1`이 보여야 한다. 리허설 둘은 각각 `K3S DATASTORE RESTORE DRILL PASS`, `GITEA RESTORE DRILL PASS`로 끝나야 한다.
|
||||
|
||||
## 복원 리허설
|
||||
|
||||
- k3s: 백업을 내려받아 sha256을 맞춘 뒤, 운영과 같은 버전의 k3s를 **네트워크 없는** 일회용 컨테이너로
|
||||
띄워 API가 뜨는지, Secret 수가 라이브와 비슷한지(±5), 모든 Secret이 복호화되는지 본다.
|
||||
`scripts/validate/test-k3s-datastore-restore-drill.sh`는 운영 데이터 없이 같은 경로를 시험한다(새 k3s에
|
||||
시험 Secret 셋 → 암호화돼 저장된 것을 확인 → 복원).
|
||||
- Gitea: dump를 풀어 `app.ini`(INTERNAL_TOKEN·SECRET_KEY), 모든 저장소의 `git fsck`, 라이브와 저장소 수를 본다.
|
||||
- 분기마다 한 번 돌린다. 성공하면 `platform_backup_restore_drill_last_success_timestamp_seconds`가 갱신된다.
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::platform-host-backups"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::platform-host-backups/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- prometheus-rules.yaml
|
||||
@@ -0,0 +1,88 @@
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: PrometheusRule
|
||||
metadata:
|
||||
name: platform-host-checks
|
||||
namespace: observability
|
||||
labels:
|
||||
observability.hyeonworks.com/instance: home
|
||||
app.kubernetes.io/part-of: platform
|
||||
spec:
|
||||
groups:
|
||||
- name: platform-host-backups
|
||||
rules:
|
||||
- alert: PlatformK3sDatastoreBackupTooOld
|
||||
expr: time() - max(platform_backup_last_success_timestamp_seconds{backup="k3s-datastore"}) > 2 * 86400
|
||||
for: 1h
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: k3s datastore has not been backed up for more than 2 days
|
||||
description: Check `journalctl -u platform-k3s-datastore-backup` on desktop. Daily timer, 03:30 KST.
|
||||
- alert: PlatformGiteaBackupTooOld
|
||||
expr: time() - max(platform_backup_last_success_timestamp_seconds{backup="gitea"}) > 8 * 86400
|
||||
for: 1h
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Gitea has not been backed up for more than 8 days
|
||||
description: Check `journalctl -u platform-gitea-backup` on desktop. Weekly timer, Sunday 04:00 KST.
|
||||
- alert: PlatformHostBackupFailed
|
||||
expr: max by (backup) (platform_backup_last_run_success) == 0
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "The last {{ $labels.backup }} backup run failed"
|
||||
description: "Check `journalctl -u platform-{{ $labels.backup }}-backup` on desktop."
|
||||
- alert: PlatformHostBackupMetricsAbsent
|
||||
expr: absent(platform_backup_last_run_timestamp_seconds{backup="k3s-datastore"}) or absent(platform_backup_last_run_timestamp_seconds{backup="gitea"})
|
||||
for: 1d
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Host backup metrics are missing
|
||||
description: The backup timers or the node-exporter textfile collector (/var/lib/node_exporter/textfile_collector) are not running.
|
||||
- name: platform-host-drift
|
||||
rules:
|
||||
- alert: PlatformLiveDriftDetected
|
||||
expr: max(platform_live_drift_objects) > 0
|
||||
for: 6h
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "{{ $value }} live objects differ from platform-core origin/main"
|
||||
description: Run `scripts/validate/live-drift-check.sh --accepted scripts/validate/live-drift-accepted.txt` on desktop to list them.
|
||||
- alert: PlatformLiveDriftCheckStale
|
||||
expr: time() - max(platform_live_drift_last_run_timestamp_seconds) > 2 * 86400 or max(platform_live_drift_check_success) == 0
|
||||
for: 1h
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: The daily live drift check has not completed
|
||||
description: Check `journalctl -u platform-live-drift-check` on desktop.
|
||||
- name: platform-k3s-certificates
|
||||
rules:
|
||||
- alert: PlatformK3sServingCertificateExpiry
|
||||
expr: (min by (certificate) (platform_k3s_certificate_not_after_seconds) - time()) < 100 * 86400
|
||||
for: 1h
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "k3s {{ $labels.certificate }} serving certificate expires in less than 100 days"
|
||||
description: k3s renews certificates only when it starts within 120 days of expiry. Plan a k3s restart window (docs/runbooks).
|
||||
- alert: PlatformK3sServingCertificateExpiry
|
||||
expr: (min by (certificate) (platform_k3s_certificate_not_after_seconds) - time()) < 14 * 86400
|
||||
for: 10m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "k3s {{ $labels.certificate }} serving certificate expires in less than 14 days"
|
||||
description: Restart k3s (it renews certificates within 120 days of expiry) or run `k3s certificate rotate`.
|
||||
- alert: PlatformK3sCertificateCheckStale
|
||||
expr: time() - max(platform_k3s_certificate_check_timestamp_seconds) > 2 * 86400
|
||||
for: 1h
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: The daily k3s certificate expiry check has not run
|
||||
description: Check `journalctl -u platform-k3s-cert-expiry` on desktop.
|
||||
@@ -1,163 +0,0 @@
|
||||
# 플랫폼 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일 안의
|
||||
아무 시점으로나 되돌릴 수 있게 한다.
|
||||
|
||||
## 무엇이 어디로 가나
|
||||
|
||||
```text
|
||||
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`.
|
||||
|
||||
**주의: `services/platform-postgres`를 통째로 다시 적용하지 않는다.** live Cluster의
|
||||
`pg_hba`에는 Phase 1 원본에 없는 `host techlog techlog all scram-sha-256`과
|
||||
`host all techlog all reject`가 있다. 원본을 다시 적용하면 이 두 줄이 지워져 tech-log 운영
|
||||
백엔드가 DB에 붙지 못한다. 그래서 백업 설정만 `kubectl patch`로 더한다.
|
||||
|
||||
1. bucket, 정책, 사용자, Secret을 만든다. 화면에 자격 증명이 나오지 않는다.
|
||||
|
||||
```bash
|
||||
bash scripts/bootstrap/create-postgres-backup-credentials.sh
|
||||
```
|
||||
|
||||
마지막 줄에 `PLATFORM_POSTGRES_BACKUP_BOOTSTRAP_PASS`가 나와야 한다. 새 사용자가 자기
|
||||
bucket에 쓰고 읽고 지울 수 있고, `loki` bucket은 못 보는 것까지 확인한다.
|
||||
|
||||
2. AIStor 쪽 ingress를 연다. 그 전에는 PostgreSQL이 9000에 닿지 못한다.
|
||||
|
||||
```bash
|
||||
kubectl apply -f services/platform-postgres-backup/object-storage-counterpart.yaml
|
||||
```
|
||||
|
||||
3. live Cluster에 백업 설정을 더한다. PostgreSQL은 재시작하지 않는다.
|
||||
|
||||
```bash
|
||||
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이 올라가는지 본다.
|
||||
|
||||
```bash
|
||||
kubectl -n platform-data get cluster platform-postgres \
|
||||
-o jsonpath='{.status.conditions[?(@.type=="ContinuousArchiving")].status}{" "}{.status.firstRecoverabilityPoint}{"\n"}'
|
||||
```
|
||||
|
||||
4. 매일 백업을 건다. 만들자마자 첫 base backup이 돈다.
|
||||
|
||||
```bash
|
||||
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이 틀리면 이것이 울린다.
|
||||
|
||||
### 되돌리기
|
||||
|
||||
```bash
|
||||
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)를 잠깐 쓴다.
|
||||
|
||||
```bash
|
||||
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` 등)는 조금 다를 수 있다. 표가 없거나 크게 다르면 실패다.
|
||||
|
||||
```bash
|
||||
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. 복원된 시점을 기록한다.
|
||||
|
||||
```bash
|
||||
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도 같이 지워진다.
|
||||
|
||||
```bash
|
||||
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 두 줄이 남는 것을 봤다.
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetBucketLocation",
|
||||
"s3:ListBucket",
|
||||
"s3:ListBucketMultipartUploads"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::platform-postgres-backups"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject",
|
||||
"s3:PutObject",
|
||||
"s3:DeleteObject",
|
||||
"s3:AbortMultipartUpload",
|
||||
"s3:ListMultipartUploadParts"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::platform-postgres-backups/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
# Merge patch for the live Cluster. Apply it with kubectl patch, not by
|
||||
# re-applying services/platform-postgres: the live Cluster carries pg_hba lines
|
||||
# for techlog that the Phase 1 source does not have (README.md, "적용").
|
||||
spec:
|
||||
backup:
|
||||
# Base backups and WAL older than the newest point that still lets a
|
||||
# restore reach 30 days back are deleted by the operator.
|
||||
retentionPolicy: "30d"
|
||||
barmanObjectStore:
|
||||
# AIStor ObjectStore on the HDD (sdb3, aistor-local-xfs-retain), not the
|
||||
# root SSD that holds the database itself.
|
||||
destinationPath: s3://platform-postgres-backups/
|
||||
endpointURL: http://minio.object-storage.svc.cluster.local
|
||||
s3Credentials:
|
||||
accessKeyId:
|
||||
name: platform-postgres-backup-s3
|
||||
key: ACCESS_KEY_ID
|
||||
secretAccessKey:
|
||||
name: platform-postgres-backup-s3
|
||||
key: ACCESS_SECRET_KEY
|
||||
wal:
|
||||
compression: gzip
|
||||
maxParallel: 2
|
||||
data:
|
||||
compression: gzip
|
||||
jobs: 2
|
||||
@@ -1,17 +0,0 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
# Applied after platform-postgres (Phase 1) and AIStor (Phase 2) exist and
|
||||
# after scripts/bootstrap/create-postgres-backup-credentials.sh has created
|
||||
# the bucket and the platform-data/platform-postgres-backup-s3 Secret.
|
||||
# cluster-backup-patch.yaml and restore-drill/ are applied by hand; see README.md.
|
||||
resources:
|
||||
- object-storage-counterpart.yaml
|
||||
- scheduled-backup.yaml
|
||||
- prometheus-rule.yaml
|
||||
|
||||
labels:
|
||||
- pairs:
|
||||
app.kubernetes.io/part-of: platform
|
||||
app.kubernetes.io/managed-by: kustomize
|
||||
includeSelectors: false
|
||||
@@ -1,30 +0,0 @@
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: object-storage-allow-platform-postgres-backup
|
||||
namespace: object-storage
|
||||
labels:
|
||||
app.kubernetes.io/component: platform-postgres-backup
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels:
|
||||
aistor.min.io/objectStore: minio-aistor
|
||||
policyTypes:
|
||||
- Ingress
|
||||
ingress:
|
||||
# barman-cloud in the PostgreSQL pods writes base backups and WAL; the
|
||||
# restore drill cluster reads them.
|
||||
- from:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: platform-data
|
||||
podSelector:
|
||||
matchExpressions:
|
||||
- key: cnpg.io/cluster
|
||||
operator: In
|
||||
values:
|
||||
- platform-postgres
|
||||
- platform-postgres-restore-drill
|
||||
ports:
|
||||
- protocol: TCP
|
||||
port: 9000
|
||||
@@ -1,46 +0,0 @@
|
||||
# Backup alerts for platform-postgres. They live with the backup and not in
|
||||
# the observability core, whose renderer keeps backup rules out of its scope
|
||||
# (scripts/validate/render-observability-core.sh, no_unscoped_monitors_rules).
|
||||
# Prometheus loads PrometheusRules from namespaces labelled
|
||||
# observability.hyeonworks.com/enabled=true, which platform-data is.
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: PrometheusRule
|
||||
metadata:
|
||||
name: platform-postgres-backup
|
||||
namespace: platform-data
|
||||
labels:
|
||||
app.kubernetes.io/name: platform-postgres
|
||||
app.kubernetes.io/component: backup
|
||||
observability.hyeonworks.com/instance: home
|
||||
spec:
|
||||
groups:
|
||||
- name: platform.backup
|
||||
rules:
|
||||
# cnpg_collector_last_available_backup_timestamp is 0 until the first
|
||||
# base backup, so a cluster without backups fires as well.
|
||||
- alert: PlatformPostgresBackupMissing
|
||||
expr: >-
|
||||
time() - max by (job, namespace) (
|
||||
cnpg_collector_last_available_backup_timestamp{job="platform-postgres",namespace="platform-data"}
|
||||
) > 26 * 3600
|
||||
for: 30m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: platform-postgres에 26시간 안에 끝난 백업이 없음
|
||||
description: platform-postgres의 마지막 성공한 base backup이 26시간보다 오래됐거나 없습니다. 매일 03:00 KST 백업(ScheduledBackup platform-postgres-daily)을 확인하세요.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/platform-core/src/branch/main/services/platform-postgres-backup/README.md
|
||||
# A failing archive_command keeps WAL in pg_wal, which then fills the
|
||||
# PostgreSQL volume.
|
||||
- alert: PlatformPostgresWALArchiveBacklog
|
||||
expr: >-
|
||||
max by (job, namespace) (
|
||||
cnpg_collector_pg_wal_archive_status{job="platform-postgres",namespace="platform-data",value="ready"}
|
||||
) > 10
|
||||
for: 15m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: platform-postgres의 WAL이 보관소로 올라가지 않음
|
||||
description: 보관을 기다리는 WAL 파일이 10개를 넘은 채 15분이 지났습니다. 보관이 막히면 WAL이 PostgreSQL 볼륨에 쌓여 디스크가 찹니다.
|
||||
runbook_url: https://git.learn.hyeonworks.com/donghyeon.kang/platform-core/src/branch/main/services/platform-postgres-backup/README.md
|
||||
@@ -1,49 +0,0 @@
|
||||
# Restore drill: a throwaway Cluster bootstrapped from the platform-postgres
|
||||
# backups. It has no backup section, so it never writes to the bucket.
|
||||
# Apply, compare, delete; see ../README.md ("복원 리허설").
|
||||
apiVersion: postgresql.cnpg.io/v1
|
||||
kind: Cluster
|
||||
metadata:
|
||||
name: platform-postgres-restore-drill
|
||||
namespace: platform-data
|
||||
labels:
|
||||
app.kubernetes.io/name: platform-postgres-restore-drill
|
||||
app.kubernetes.io/component: restore-drill
|
||||
spec:
|
||||
instances: 1
|
||||
imageName: ghcr.io/cloudnative-pg/postgresql:17.9-standard-trixie
|
||||
storage:
|
||||
# Dynamic local-path volume on the root SSD, deleted with the Cluster.
|
||||
storageClass: local-path
|
||||
size: 5Gi
|
||||
bootstrap:
|
||||
recovery:
|
||||
source: platform-postgres
|
||||
externalClusters:
|
||||
- name: platform-postgres
|
||||
barmanObjectStore:
|
||||
destinationPath: s3://platform-postgres-backups/
|
||||
endpointURL: http://minio.object-storage.svc.cluster.local
|
||||
serverName: platform-postgres
|
||||
s3Credentials:
|
||||
accessKeyId:
|
||||
name: platform-postgres-backup-s3
|
||||
key: ACCESS_KEY_ID
|
||||
secretAccessKey:
|
||||
name: platform-postgres-backup-s3
|
||||
key: ACCESS_SECRET_KEY
|
||||
wal:
|
||||
maxParallel: 2
|
||||
managed:
|
||||
services:
|
||||
disabledDefaultServices:
|
||||
- ro
|
||||
- r
|
||||
affinity:
|
||||
enablePodAntiAffinity: false
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
memory: 1Gi
|
||||
@@ -1,17 +0,0 @@
|
||||
apiVersion: postgresql.cnpg.io/v1
|
||||
kind: ScheduledBackup
|
||||
metadata:
|
||||
name: platform-postgres-daily
|
||||
namespace: platform-data
|
||||
labels:
|
||||
app.kubernetes.io/name: platform-postgres
|
||||
app.kubernetes.io/component: backup
|
||||
spec:
|
||||
# Seconds field first. The operator runs in UTC: 18:00 UTC is 03:00 KST.
|
||||
schedule: "0 0 18 * * *"
|
||||
# Take the first base backup as soon as this object is created.
|
||||
immediate: true
|
||||
backupOwnerReference: self
|
||||
method: barmanObjectStore
|
||||
cluster:
|
||||
name: platform-postgres
|
||||
@@ -0,0 +1,20 @@
|
||||
# 플랫폼 PriorityClass
|
||||
|
||||
노드가 한 대라 자원이 모자라면 kubelet이 파드를 내보낸다. 내보낼 순서는 requests를 넘었는지,
|
||||
그다음 우선순위로 정한다. 2026-11-09 디스크 축출 때 플랫폼 파드는 모두 우선순위 0이라 tech-log
|
||||
운영 파드가 Grafana·kube-state-metrics와 같은 순위로 나갔다.
|
||||
|
||||
| 이름 | 값 | 선점 | 붙일 곳 |
|
||||
| --- | --- | --- | --- |
|
||||
| `platform-critical` | 1000000 | 낮은 것을 선점 | platform-postgres, Gitea, Keycloak, tech-log |
|
||||
| `platform-low` | -1000 | 선점 안 함 | Grafana, pgAdmin, Loki, Tempo |
|
||||
|
||||
- 아무것도 안 붙인 파드는 기본값 0이다. 시스템 클래스(`system-*`, 20억)는 그대로 가장 높다.
|
||||
- `globalDefault`는 둘 다 끈다. 새 파드가 모르게 우선순위를 얻지 않게 하려는 것이다.
|
||||
- 클래스를 만드는 것은 아무 파드도 바꾸지 않는다. **붙이는 것은 파드 재시작을 부르므로**
|
||||
k3s 재시작 창에 한다(`infrastructure/host/k3s/README.md`).
|
||||
|
||||
```sh
|
||||
kubectl apply -k services/priority-classes
|
||||
kubectl get priorityclass platform-critical platform-low
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- priority-classes.yaml
|
||||
@@ -0,0 +1,25 @@
|
||||
apiVersion: scheduling.k8s.io/v1
|
||||
kind: PriorityClass
|
||||
metadata:
|
||||
name: platform-critical
|
||||
labels:
|
||||
app.kubernetes.io/part-of: platform
|
||||
value: 1000000
|
||||
globalDefault: false
|
||||
preemptionPolicy: PreemptLowerPriority
|
||||
description: >-
|
||||
Stateful platform services and production workloads that other services depend on
|
||||
(platform-postgres, Gitea, Keycloak, tech-log). Evicted after everything else.
|
||||
---
|
||||
apiVersion: scheduling.k8s.io/v1
|
||||
kind: PriorityClass
|
||||
metadata:
|
||||
name: platform-low
|
||||
labels:
|
||||
app.kubernetes.io/part-of: platform
|
||||
value: -1000
|
||||
globalDefault: false
|
||||
preemptionPolicy: Never
|
||||
description: >-
|
||||
Tools whose loss does not stop a user-facing service (Grafana, pgAdmin, Loki, Tempo).
|
||||
Evicted first and never preempts another pod.
|
||||
@@ -0,0 +1,44 @@
|
||||
# tech-log 테넌트 — 플랫폼 쪽 객체
|
||||
|
||||
tech-log(hyeonworks.com 운영)가 플랫폼을 쓰려면 플랫폼 namespace 안에 허용 객체가 있어야 한다.
|
||||
이 빌드 루트가 그 객체를 소유한다. 앱 자체(Deployment·Service·Ingress·ServiceMonitor·앱
|
||||
namespace 안의 NetworkPolicy)는 tech-log 저장소의 `deploy/`가 소유한다.
|
||||
|
||||
2026-11-11 점검(`docs/reviews/2026-11-11-k3s-maturity-review.md` 4.3절) 전까지 이 객체들은
|
||||
`kubectl apply`로만 들어가 있었고 어느 저장소에도 없었다. 처음 내용은 라이브 객체의
|
||||
`last-applied-configuration`을 그대로 옮겼다. 라이브와 다른 것은 `hyeonworks-prod`의 PSA 라벨뿐이다.
|
||||
|
||||
| 파일 | 객체 |
|
||||
| --- | --- |
|
||||
| `namespace.yaml` | Namespace `hyeonworks-prod`: 관측 대상 라벨, PSA `enforce=baseline`·`warn=restricted`·`audit=restricted` |
|
||||
| `platform-data.yaml` | `techlog` Database와 DatabaseRole(로그인만, 연결 30), Postgres로 들어오는 ingress |
|
||||
| `object-storage.yaml` | AIStor 9000으로 들어오는 ingress |
|
||||
| `observability-probes.yaml` | blackbox Probe 둘(공개 HTTPS, 내부 readiness) |
|
||||
| `observability-rules.yaml` | PrometheusRule `techlog` 일곱 개 |
|
||||
| `dashboards/techlog-operations.json` | Grafana 대시보드(`grafana-dashboard-techlog` ConfigMap으로 생성) |
|
||||
| `observability-network-policies.yaml` | blackbox → readiness, Prometheus → management scrape egress |
|
||||
|
||||
## 여기에 없는 것
|
||||
|
||||
- `platform-data/platform-postgres`의 `pg_hba` techlog 두 줄: Cluster 객체는
|
||||
`services/platform-postgres`가 소유한다.
|
||||
- Secret: `platform-data/techlog-db-credentials`(`kubernetes.io/basic-auth`, `username`은 정확히
|
||||
`techlog`)는 DatabaseRole이 참조한다. 앱 쪽 `hyeonworks-prod/hyeonworks-secrets`는 tech-log가
|
||||
소유한다. 둘 다 Git에 두지 않는다.
|
||||
|
||||
## PSA
|
||||
|
||||
`enforce=baseline`은 2026-11-12에 서버 dry-run(`kubectl label --dry-run=server`)으로 위반 0을
|
||||
확인하고 붙였다. `restricted`로 강제하면 지금 파드 셋(redis, backend, frontend)이 모두 걸린다
|
||||
(`allowPrivilegeEscalation`, capabilities, `runAsNonRoot`, seccomp). tech-log 쪽 securityContext가
|
||||
고쳐진 뒤 같은 dry-run이 경고 없이 통과하면 `enforce`를 `restricted`로 올린다.
|
||||
|
||||
## 렌더·적용
|
||||
|
||||
```sh
|
||||
bash scripts/validate/render-tenants-and-policies.sh
|
||||
kubectl kustomize services/tenants/techlog | kubectl diff -f -
|
||||
kubectl apply -k services/tenants/techlog
|
||||
```
|
||||
|
||||
새로 설치할 때는 이 루트를 tech-log `deploy/`보다 먼저 적용한다(namespace를 여기서 만든다).
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,23 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
# tech-log(hyeonworks.com) 테넌트의 플랫폼 쪽 객체. 앱 쪽 매니페스트는 tech-log repo가 소유한다.
|
||||
resources:
|
||||
- namespace.yaml
|
||||
- platform-data.yaml
|
||||
- object-storage.yaml
|
||||
- observability-probes.yaml
|
||||
- observability-rules.yaml
|
||||
- observability-network-policies.yaml
|
||||
|
||||
generatorOptions:
|
||||
disableNameSuffixHash: true
|
||||
labels:
|
||||
app.kubernetes.io/part-of: techlog
|
||||
grafana_dashboard: "1"
|
||||
|
||||
configMapGenerator:
|
||||
- name: grafana-dashboard-techlog
|
||||
namespace: observability
|
||||
files:
|
||||
- dashboards/techlog-operations.json
|
||||
@@ -0,0 +1,12 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: hyeonworks-prod
|
||||
labels:
|
||||
observability.hyeonworks.com/enabled: 'true'
|
||||
pod-security.kubernetes.io/enforce: baseline
|
||||
pod-security.kubernetes.io/enforce-version: latest
|
||||
pod-security.kubernetes.io/warn: restricted
|
||||
pod-security.kubernetes.io/warn-version: latest
|
||||
pod-security.kubernetes.io/audit: restricted
|
||||
pod-security.kubernetes.io/audit-version: latest
|
||||
@@ -0,0 +1,22 @@
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: allow-techlog-backend
|
||||
namespace: object-storage
|
||||
spec:
|
||||
ingress:
|
||||
- from:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: hyeonworks-prod
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app: techlog-backend
|
||||
ports:
|
||||
- port: 9000
|
||||
protocol: TCP
|
||||
podSelector:
|
||||
matchLabels:
|
||||
aistor.min.io/objectStore: minio-aistor
|
||||
policyTypes:
|
||||
- Ingress
|
||||
@@ -0,0 +1,45 @@
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: blackbox-allow-techlog-health
|
||||
namespace: observability
|
||||
spec:
|
||||
egress:
|
||||
- ports:
|
||||
- port: 9001
|
||||
protocol: TCP
|
||||
to:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: hyeonworks-prod
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app: techlog-backend
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: prometheus-blackbox-exporter
|
||||
policyTypes:
|
||||
- Egress
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: observability-allow-techlog-scrape
|
||||
namespace: observability
|
||||
spec:
|
||||
egress:
|
||||
- ports:
|
||||
- port: 9001
|
||||
protocol: TCP
|
||||
to:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: hyeonworks-prod
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app: techlog-backend
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: prometheus
|
||||
policyTypes:
|
||||
- Egress
|
||||
@@ -0,0 +1,46 @@
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: Probe
|
||||
metadata:
|
||||
labels:
|
||||
observability.hyeonworks.com/instance: home
|
||||
name: techlog-edge
|
||||
namespace: observability
|
||||
spec:
|
||||
interval: 30s
|
||||
jobName: techlog-edge
|
||||
module: http_2xx
|
||||
prober:
|
||||
path: /probe
|
||||
scheme: http
|
||||
url: blackbox-exporter.observability.svc.cluster.local:9115
|
||||
scrapeTimeout: 15s
|
||||
targets:
|
||||
staticConfig:
|
||||
labels:
|
||||
application: techlog
|
||||
static:
|
||||
- https://hyeonworks.com/
|
||||
- https://hyeonworks.com/api/healthcheck
|
||||
---
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: Probe
|
||||
metadata:
|
||||
labels:
|
||||
observability.hyeonworks.com/instance: home
|
||||
name: techlog-readiness
|
||||
namespace: observability
|
||||
spec:
|
||||
interval: 30s
|
||||
jobName: techlog-readiness
|
||||
module: http_2xx
|
||||
prober:
|
||||
path: /probe
|
||||
scheme: http
|
||||
url: blackbox-exporter.observability.svc.cluster.local:9115
|
||||
scrapeTimeout: 15s
|
||||
targets:
|
||||
staticConfig:
|
||||
labels:
|
||||
application: techlog
|
||||
static:
|
||||
- http://techlog-management.hyeonworks-prod.svc.cluster.local:9001/actuator/health/readiness
|
||||
@@ -0,0 +1,67 @@
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: PrometheusRule
|
||||
metadata:
|
||||
labels:
|
||||
observability.hyeonworks.com/instance: home
|
||||
name: techlog
|
||||
namespace: observability
|
||||
spec:
|
||||
groups:
|
||||
- name: techlog
|
||||
rules:
|
||||
- alert: TechLogMetricsDown
|
||||
annotations:
|
||||
summary: TechLog metrics target is unreachable
|
||||
expr: up{namespace="hyeonworks-prod",service="techlog-management"} == 0
|
||||
for: 5m
|
||||
labels:
|
||||
application: techlog
|
||||
severity: warning
|
||||
- alert: TechLogReadinessDown
|
||||
annotations:
|
||||
summary: TechLog dependency readiness is DOWN
|
||||
expr: probe_success{job="techlog-readiness"} == 0
|
||||
for: 3m
|
||||
labels:
|
||||
application: techlog
|
||||
severity: critical
|
||||
- alert: TechLogHTTPSDown
|
||||
annotations:
|
||||
summary: TechLog HTTPS or API health is failing
|
||||
expr: probe_success{job="techlog-edge"} == 0
|
||||
for: 3m
|
||||
labels:
|
||||
application: techlog
|
||||
severity: critical
|
||||
- alert: TechLogHTTP5xx
|
||||
annotations:
|
||||
summary: TechLog HTTP 5xx exceeds 5%
|
||||
expr: (sum(rate(http_server_requests_seconds_count{namespace="hyeonworks-prod",status=~"5.."}[5m])) / clamp_min(sum(rate(http_server_requests_seconds_count{namespace="hyeonworks-prod"}[5m])),0.001)) > 0.05 and sum(increase(http_server_requests_seconds_count{namespace="hyeonworks-prod"}[5m])) > 20
|
||||
for: 5m
|
||||
labels:
|
||||
application: techlog
|
||||
severity: warning
|
||||
- alert: TechLogLatencyHigh
|
||||
annotations:
|
||||
summary: TechLog p99 latency exceeds 2 seconds
|
||||
expr: histogram_quantile(0.99,sum by(le)(rate(http_server_requests_seconds_bucket{namespace="hyeonworks-prod",uri!~"/actuator.*"}[5m]))) > 2
|
||||
for: 10m
|
||||
labels:
|
||||
application: techlog
|
||||
severity: warning
|
||||
- alert: TechLogHeapPressure
|
||||
annotations:
|
||||
summary: TechLog heap usage exceeds 85%
|
||||
expr: sum(jvm_memory_used_bytes{namespace="hyeonworks-prod",area="heap"}) / sum(jvm_memory_max_bytes{namespace="hyeonworks-prod",area="heap"}) > 0.85
|
||||
for: 10m
|
||||
labels:
|
||||
application: techlog
|
||||
severity: warning
|
||||
- alert: TechLogDatabasePoolWaiting
|
||||
annotations:
|
||||
summary: TechLog database connections are queued
|
||||
expr: hikaricp_connections_pending{namespace="hyeonworks-prod"} > 0
|
||||
for: 5m
|
||||
labels:
|
||||
application: techlog
|
||||
severity: warning
|
||||
@@ -0,0 +1,55 @@
|
||||
apiVersion: postgresql.cnpg.io/v1
|
||||
kind: Database
|
||||
metadata:
|
||||
name: platform-postgres-techlog
|
||||
namespace: platform-data
|
||||
spec:
|
||||
cluster:
|
||||
name: platform-postgres
|
||||
databaseReclaimPolicy: retain
|
||||
ensure: present
|
||||
name: techlog
|
||||
owner: techlog
|
||||
---
|
||||
apiVersion: postgresql.cnpg.io/v1
|
||||
kind: DatabaseRole
|
||||
metadata:
|
||||
name: platform-postgres-techlog
|
||||
namespace: platform-data
|
||||
spec:
|
||||
bypassrls: false
|
||||
cluster:
|
||||
name: platform-postgres
|
||||
connectionLimit: 30
|
||||
createdb: false
|
||||
createrole: false
|
||||
databaseRoleReclaimPolicy: retain
|
||||
login: true
|
||||
name: techlog
|
||||
passwordSecret:
|
||||
name: techlog-db-credentials
|
||||
replication: false
|
||||
superuser: false
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: allow-techlog-backend
|
||||
namespace: platform-data
|
||||
spec:
|
||||
ingress:
|
||||
- from:
|
||||
- namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: hyeonworks-prod
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app: techlog-backend
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
podSelector:
|
||||
matchLabels:
|
||||
cnpg.io/cluster: platform-postgres
|
||||
policyTypes:
|
||||
- Ingress
|
||||
Reference in New Issue
Block a user