diff --git a/infrastructure/host/k3s/README.md b/infrastructure/host/k3s/README.md new file mode 100644 index 0000000..66bda42 --- /dev/null +++ b/infrastructure/host/k3s/README.md @@ -0,0 +1,92 @@ +# k3s 재시작 묶음 + +k3s를 **한 번만** 재시작해서 다음을 같이 넣는다. 근거는 `docs/reviews/2026-11-11-k3s-maturity-review.md` +A3·A9·A10·7.2·7.3·7.5절, 결정은 같은 문서 8절 결정 5(2026-11-12 총괄 확정)다. + +| 파일 | 설치 위치 | 하는 일 | +| --- | --- | --- | +| `kubelet.conf.d/50-platform-resources.conf` | `/var/lib/rancher/k3s/agent/etc/kubelet.conf.d/` | 예약(system 1 CPU·2Gi, kube 0.5 CPU·1Gi), 메모리 축출(hard 500Mi, soft 1Gi/1분), graceful node shutdown(60초, critical 20초) | +| `config.yaml.d/60-platform-apiserver.yaml` | `/etc/rancher/k3s/config.yaml.d/` | API 서버 감사 로그와 PodSecurity admission 설정 파일 지정 | +| `server/audit.yaml` | `/var/lib/rancher/k3s/server/audit.yaml` | 감사 정책: Metadata 수준(본문을 남기지 않아 Secret 값이 로그에 없다), 잦고 값 없는 요청은 뺌 | +| `server/psa.yaml` | `/var/lib/rancher/k3s/server/psa.yaml` | 라벨 없는 namespace의 기본값: enforce `baseline`, warn·audit `restricted`, `kube-system` 예외 | +| (W1) `../systemd/k3s.service.d/10-after-time-sync.conf` | `/etc/systemd/system/k3s.service.d/` | k3s를 시간 동기화 뒤에 시작 | +| (W1) `../systemd/systemd-time-wait-sync.service.d/10-timeout.conf` | `/etc/systemd/system/systemd-time-wait-sync.service.d/` | 동기화를 10분까지만 기다림 | + +그리고 `/var/lib/rancher/k3s/server/manifests/local-storage.yaml.skip`을 만들어 k3s가 local-path +addon을 다시 덮어쓰지 않게 한 뒤, `local-path` StorageClass의 기본 표시를 끈다. 쓰는 PVC가 없고 +(2026-11-11), 기본으로 남아 있으면 `storageClassName`을 빠뜨린 PVC가 루트 SSD에 Delete 정책으로 생긴다. +k3s 문서의 `.skip` 방식이다(packaged components). 그 뒤 local-path-provisioner는 k3s 업그레이드로 +갱신되지 않는다. + +## 값을 이렇게 정한 이유 + +- 예약: 노드 32GiB, 12 CPU. 파드 requests 합이 메모리 11Gi(34%)라 예약 3Gi를 빼도 여유가 크다. + 예약이 없으면 Allocatable = Capacity라 파드가 노드 전부를 잡을 수 있고, 같은 호스트의 Docker + 빌드·CI·데스크톱 앱과 겹치면 커널 OOM killer가 고른다. +- `evictionHard`: 메모리·디스크 셋을 모두 적는다. 이 맵을 정하면 정하지 않은 항목의 기본값이 0이 된다 + (`mergeDefaultEvictionSettings: false`). 디스크 5%는 k3s 기본값 그대로다. +- graceful shutdown: 두 값이 0이면 기능이 꺼진다. 재부팅 때 Postgres 같은 파드가 정상 종료할 시간을 + 준다. 호스트 종료가 최대 60초 늦어진다. kubelet이 logind `InhibitDelayMaxSec`(지금 30초)가 모자라면 + 스스로 늘린다. 적용 뒤 `systemd-analyze cat-config systemd/logind.conf`로 확인한다. +- PSA 기본값은 `restricted`가 아니라 `baseline`이다. 라벨 없는 namespace는 `default`·`kube-public`· + `kube-node-lease`뿐이고 파드가 없다. 플랫폼 namespace는 모두 자기 라벨이 있어 영향이 없다. + +## 넣지 않은 것: `protect-kernel-defaults` + +7.3절에서 권했지만 이 묶음에서 뺐다. + +- CIS Kubernetes Benchmark는 v1.7부터 이 항목(옛 4.2.6)을 뺐다. +- 켜려면 kubelet이 기대하는 sysctl을 먼저 맞춰야 한다(k3s hardening 가이드: `vm.overcommit_memory=1`, + `kernel.panic=10`, `kernel.panic_on_oops=1`, `vm.panic_on_oom=0`). `kernel.panic_on_oops=1`은 커널 + oops가 한 번만 나도 10초 뒤 호스트를 재부팅한다. 이 기계는 GPU 드라이버가 있는 데스크톱이고 + 이중 부팅이며, 재부팅 자체가 11-11 시계 사고의 출발점이었다. `vm.overcommit_memory=1`은 호스트 전체의 + 메모리 할당 방식을 바꾼다. +- 얻는 것(kubelet이 커널 값을 못 바꾸게 함)보다 잃는 것이 커서 뺀다. 다시 넣으려면 sysctl 변경을 따로 + 소유자가 정한다. + +## 적용 (소유자, 한 번) + +전제: + +- desktop, 이 디렉터리와 W1의 `infrastructure/host/systemd/*`가 **둘 다** 있는 platform-core `main` checkout + (W1 PR 병합 뒤). 없으면 스크립트가 `MISSING …(W1)`을 찍고 멈춘다. +- CI job과 에이전트 게이트가 없는 때. k3s 재시작 중 1~2분 API가 멈춘다. k3s는 `KillMode=process`라 + 컨테이너는 계속 돈다(파드가 재시작되지는 않는다). + +```bash +cd /home/donghyeon/workspace/platform && git pull --ff-only +bash scripts/bootstrap/apply-k3s-restart-bundle.sh --check +sudo bash scripts/bootstrap/apply-k3s-restart-bundle.sh --execute +``` + +`--execute`가 하는 일: + +1. 클러스터 Ready와 health 셋(Keycloak OIDC discovery, tech-log health, Gitea healthz)을 본다. +2. 바꿀 파일을 `/var/backups/platform-k3s-restart-bundle/<시각>/`에 복사하고, datastore를 + `sqlite3 .backup`으로 복사한다(`token`도 같이, 모드 0600, `PRAGMA integrity_check` 출력). +3. 파일을 설치하고 `systemd-time-wait-sync`를 켠 뒤 k3s를 한 번 재시작한다. +4. 확인: kubelet configz(예약·eviction·shutdown 값), 감사 로그가 쓰이는지, `default` namespace에서 + privileged 파드가 서버 dry-run으로 거절되는지, health 셋이 200인지, time-wait-sync가 enabled인지. +5. 3·4 중 하나라도 실패하면 백업한 파일을 되돌리고 새 파일을 지운 뒤 k3s를 다시 재시작한다. +6. 다 통과하면 `local-path`의 기본 표시를 끈다. + +마지막 줄이 `K3S RESTART BUNDLE APPLIED`여야 한다. + +## 같은 재시작 창에 이어서 할 것 + +PriorityClass를 파드에 붙이는 변경과 Keycloak 이미지 고정은 파드 재시작을 부르므로 이 묶음 바로 뒤에 +한다(`docs/runbooks/` 재시작 창 절차). Postgres의 `priorityClassName`·Guaranteed는 W1 범위다. + +## 되돌리기 (수동) + +```bash +B=/var/backups/platform-k3s-restart-bundle/<시각> +sudo rm -f /var/lib/rancher/k3s/agent/etc/kubelet.conf.d/50-platform-resources.conf \ + /etc/rancher/k3s/config.yaml.d/60-platform-apiserver.yaml \ + /var/lib/rancher/k3s/server/manifests/local-storage.yaml.skip +sudo systemctl daemon-reload && sudo systemctl restart k3s +kubectl annotate storageclass local-path storageclass.kubernetes.io/is-default-class=true --overwrite +``` + +`audit.yaml`·`psa.yaml`는 참조가 없어지면 쓰이지 않으므로 남겨도 된다. W1 시간 동기화 되돌리기는 +`infrastructure/host/README.md` 2단계를 따른다. diff --git a/infrastructure/host/k3s/config.yaml.d/60-platform-apiserver.yaml b/infrastructure/host/k3s/config.yaml.d/60-platform-apiserver.yaml new file mode 100644 index 0000000..8a2a678 --- /dev/null +++ b/infrastructure/host/k3s/config.yaml.d/60-platform-apiserver.yaml @@ -0,0 +1,12 @@ +# Installed as /etc/rancher/k3s/config.yaml.d/60-platform-apiserver.yaml. +# "+" appends to kube-apiserver-arg instead of replacing it (docs.k3s.io, +# installation/configuration, multiple config files). +# Audit log: k3s hardening guide "API Server audit configuration". +# PodSecurity default: k3s hardening guide "Pod Security" (baseline here, see README). +kube-apiserver-arg+: + - "audit-log-path=/var/lib/rancher/k3s/server/logs/audit.log" + - "audit-policy-file=/var/lib/rancher/k3s/server/audit.yaml" + - "audit-log-maxage=30" + - "audit-log-maxbackup=10" + - "audit-log-maxsize=100" + - "admission-control-config-file=/var/lib/rancher/k3s/server/psa.yaml" diff --git a/infrastructure/host/k3s/kubelet.conf.d/50-platform-resources.conf b/infrastructure/host/k3s/kubelet.conf.d/50-platform-resources.conf new file mode 100644 index 0000000..86ef9ac --- /dev/null +++ b/infrastructure/host/k3s/kubelet.conf.d/50-platform-resources.conf @@ -0,0 +1,29 @@ +# Installed as /var/lib/rancher/k3s/agent/etc/kubelet.conf.d/50-platform-resources.conf. +# k3s starts the kubelet with --config-dir on that directory and keeps its own +# defaults in 00-k3s-defaults.conf; this file is merged after it. +# Why: docs/reviews/2026-11-11-k3s-maturity-review.md A3 and 7.2. +apiVersion: kubelet.config.k8s.io/v1beta1 +kind: KubeletConfiguration +# Keep memory and CPU for the host (desktop, Docker builds, CI runner) and for +# k3s itself, so pods cannot take the whole node. +systemReserved: + cpu: "1" + memory: 2Gi +kubeReserved: + cpu: 500m + memory: 1Gi +# All three keys are listed on purpose: setting evictionHard replaces the +# defaults, and k3s's own default only had the two disk keys. +evictionHard: + memory.available: 500Mi + nodefs.available: "5%" + imagefs.available: "5%" +evictionSoft: + memory.available: 1Gi +evictionSoftGracePeriod: + memory.available: 1m +evictionMaxPodGracePeriod: 60 +# Graceful node shutdown: on reboot or power-off the kubelet stops normal pods +# first (40s), then critical pods (20s), instead of leaving it to systemd. +shutdownGracePeriod: 60s +shutdownGracePeriodCriticalPods: 20s diff --git a/infrastructure/host/k3s/server/audit.yaml b/infrastructure/host/k3s/server/audit.yaml new file mode 100644 index 0000000..f132d91 --- /dev/null +++ b/infrastructure/host/k3s/server/audit.yaml @@ -0,0 +1,28 @@ +# Installed as /var/lib/rancher/k3s/server/audit.yaml (mode 0600). +# Metadata level only: who did what to which object, never request or +# response bodies, so Secret values are not written to the log. +apiVersion: audit.k8s.io/v1 +kind: Policy +omitStages: + - RequestReceived +rules: + # High-volume, low-value traffic. + - level: None + resources: + - group: coordination.k8s.io + resources: ["leases"] + - level: None + resources: + - group: "" + resources: ["events"] + - level: None + nonResourceURLs: + - /healthz* + - /livez* + - /readyz* + - /version + - /metrics + - level: None + users: ["system:kube-proxy"] + verbs: ["watch"] + - level: Metadata diff --git a/infrastructure/host/k3s/server/psa.yaml b/infrastructure/host/k3s/server/psa.yaml new file mode 100644 index 0000000..66df334 --- /dev/null +++ b/infrastructure/host/k3s/server/psa.yaml @@ -0,0 +1,22 @@ +# Installed as /var/lib/rancher/k3s/server/psa.yaml (mode 0600). +# Cluster-wide Pod Security default for namespaces without their own labels. +# Namespace labels still win: every platform namespace already sets its level. +apiVersion: apiserver.config.k8s.io/v1 +kind: AdmissionConfiguration +plugins: + - name: PodSecurity + configuration: + apiVersion: pod-security.admission.config.k8s.io/v1 + kind: PodSecurityConfiguration + defaults: + enforce: "baseline" + enforce-version: "latest" + audit: "restricted" + audit-version: "latest" + warn: "restricted" + warn-version: "latest" + exemptions: + usernames: [] + runtimeClasses: [] + # k3s helm-install jobs and local-path helper pods run here. + namespaces: [kube-system]