# 終端機擴充模組:k8s(kubectl / helm 叢集模擬)

給課程作者看的文件。模組檔:`resources/js/terminal-k8s.js`;測試:`node tools/test-terminal-k8s.mjs`。

在 terminal 單元的 config 加上 `'modules' => ['k8s']` 即可啟用;初始世界用 `'world' => ['k8s' => [...]]` 提供(全部可省略)。
模組只在記憶體內模擬一個小叢集,**不會**連網、也不會執行任何真實指令。每次重設(reset)都會從 world 重新建立,沒有跨次的狀態。

啟用後多出三個指令:`kubectl`、`helm`、`base64`(`kubectl get secret ... -o jsonpath=... | base64 -d` 會用到;`base64` 只支援 `-d`/`--decode`、`-w0` 與檔案/管線輸入)。

## 虛擬時間(重要)
- 每執行一次 `kubectl` 或 `helm` 指令,叢集時間前進 **1 個 tick(= 10 秒)**。Pod 的狀態是 tick 的決定性函數,沒有任何隨機。
- 典型節奏:`kubectl apply` 之後立刻 `kubectl get pods` → `ContainerCreating`(`0/1`);再執行一次 → `Running`(`1/1`)。
- `kubectl rollout status`、`kubectl wait`、`kubectl get -w` 會自動連續推進時間直到完成或逾時(`get -w` 只模擬約 12 個 tick 後結束)。
- 其他非 kubectl 指令(ls、cat…)不推進時間。
- **任務檢查不推進時間**,檢查的是「當下」的狀態。所以 `ready`、`podstatus` 這類檢查要等學員再執行一次 `kubectl get pods` / `rollout status` 之後才會成立。**`solution` 的最後請放一兩個 `kubectl get pods`(或 `rollout status`)**,不然驗證時最後一步的 Pod 還在 ContainerCreating。
- 任務一旦完成不會取消;任務在一開始不能已經成立。

## 預設世界
- 節點:`control-plane`(有 `node-role.kubernetes.io/control-plane:NoSchedule` taint)、`worker-1`、`worker-2`,各 2 CPU / 4Gi。
- 命名空間:`default`、`kube-system`、`kube-public`、`kube-node-lease`(每個都有 `default` ServiceAccount 與 `kube-root-ca.crt` ConfigMap)。`default`、`kube-system`、`kube-public` 不可刪除。
- kube-system:`coredns`(Deployment ×2)、`kube-proxy`(DaemonSet)、`etcd-control-plane` 等 4 個靜態 Pod、`kube-dns` Service。`default` 有 `kubernetes` Service。
- StorageClass `standard`(預設,動態配置);ClusterRole `cluster-admin` / `admin` / `edit` / `view`。
- 目前的 context 是 `kubernetes-admin@kubernetes`(叢集版本 v1.29.4)。

## world.k8s 設定格式
```php
'world' => ['k8s' => [
    'nodes' => [                                 // 省略則用預設的 1 control-plane + 2 worker
        ['name' => 'control-plane', 'role' => 'control-plane', 'cpu' => 2, 'memory' => '4Gi'],
        ['name' => 'worker-1', 'cpu' => 4, 'memory' => '8Gi', 'labels' => ['disk' => 'ssd'], 'taints' => [['key' => 'dedicated', 'value' => 'gpu', 'effect' => 'NoSchedule']]],
    ],
    'images' => [                                // 映像目錄(與內建目錄合併;內建有 nginx、httpd、redis、busybox、alpine、ubuntu、mysql、postgres、node、python…)
        'myapp' => [
            'tags' => ['1', '2'],                //   列出的 tag 才存在;其他 tag → ErrImagePull → ImagePullBackOff(省略 tags = 任何 tag 都存在)
            'ports' => [8080],                   //   容器實際監聽的埠(probe / Service targetPort 打錯會連線被拒;省略 = 不檢查)
            'paths' => ['/', '/healthz'],        //   HTTP 有回應的路徑(其他路徑回 404;省略 = 不檢查)
            'crash' => true,                     //   啟動就失敗 → CrashLoopBackOff(restarts 遞增)
            'logs' => ['panic: DATABASE_URL is not set'],   // kubectl logs 的內容(crash 時也是 --previous 的內容)
            'response' => 'hello from {{hostname}}\n',      // curl / wget 的回應本文,{{hostname}} 會換成 Pod 名稱
            'healthy' => false,                  //   HTTP probe 一律回 500
            'exits' => true,                     //   沒指定 command 就立刻結束(busybox/alpine 預設如此)
            'requireEnvAny' => ['DB_PASSWORD'],  //   沒設其中任何一個環境變數就 crash(mysql、postgres 內建此行為)
        ],
    ],
    'strictImages' => false,                     // true:不在目錄(內建+images)的映像一律拉不到;預設 false(只有名稱含 nonexistent 或 tag 不存在才失敗)
    'storageClasses' => [['name' => 'standard', 'provisioner' => 'k8s.io/minikube-hostpath', 'default' => true, 'volumeBindingMode' => 'Immediate']],   // 省略 = 只有預設的 standard
    'persistentVolumes' => [['name' => 'pv-manual', 'capacity' => '5Gi', 'storageClass' => 'manual', 'accessModes' => ['ReadWriteOnce'], 'reclaimPolicy' => 'Retain']],
    'objects' => ['<YAML 字串>', '...'],          // 一開始就存在的資源(視為 1 小時前建立且早已穩定:Pod 都是 Running)
    'metricsServer' => true,                     // false:kubectl top 回 "Metrics API not available"
    'loadBalancerIPs' => ['192.168.49.200'],     // 省略 = LoadBalancer Service 的 EXTERNAL-IP 為 <pending>
    'contexts' => ['kubernetes-admin@kubernetes'], // 可多個,use-context 切換(只切名稱與預設 namespace,叢集內容共用)
    'version' => 'v1.29.4',
    'repos' => ['bitnami' => 'https://charts.bitnami.com/bitnami'],   // helm 一開始就已加入的 repo
    'charts' => [                                // helm chart(key = repo/名稱)
        'bitnami/nginx' => [
            'version' => '15.1.0', 'appVersion' => '1.25.3', 'description' => 'NGINX Open Source',
            'values' => ['replicaCount' => 1, 'image' => 'nginx:1.25'],
            'templates' => ['deployment.yaml' => "apiVersion: apps/v1\nkind: Deployment\n...{{ .Release.Name }}...{{ .Values.replicaCount }}"],
        ],
    ],
]],
```
YAML 檔請放在 `config.fs`(`kubectl apply -f 檔名` 讀虛擬檔案系統)。核心不支援 heredoc,所以課程要不是預先放好 YAML,就是讓學員用 `kubectl create ... --dry-run=client -o yaml > file.yaml` 產生再 `apply -f`。

## 支援的 kubectl 指令
資源簡稱:`po deploy svc cm ns pv pvc no rs ds sts ing ep sa cj sc`(也接受複數、`deployment.apps`、`kind/name`、`pods,svc` 逗號清單、`all`)。
全域選項:`-n/--namespace`(也可放在子指令前)、`-A`、`--context`。

| 指令 | 支援內容 |
|---|---|
| `version` / `cluster-info` | `version --client` |
| `config` | `view`、`current-context`、`get-contexts`、`use-context`、`set-context --current --namespace=` |
| `get` | `-o wide/yaml/json/name/jsonpath=…/custom-columns=…`、`-l`、`--field-selector`(status.phase、metadata.name、spec.nodeName)、`--show-labels`、`--no-headers`、`--sort-by`、`-A`、`-w`(簡化)、`get all`、`get events` |
| `describe` | Pod / Deployment / Service / Node / ConfigMap / Secret / PVC 有專屬格式(含 Events);其他種類為簡化版。名稱可用前綴 |
| `apply -f` | 檔案、目錄(`-R`)、`-`(stdin)、多文件 `---`、`kind: List`;`created`/`configured`/`unchanged` 判斷、`--dry-run=client|server`、`--validate=false`。不支援 `--server-side`、`--prune`、`-k` |
| `create` | `-f`;`deployment`(--image --replicas --port)、`namespace`、`configmap`(--from-literal/--from-file/--from-env-file)、`secret generic`、`service clusterip|nodeport|loadbalancer|externalname`(--tcp)、`job`(--image、--from=cronjob/x)、`cronjob`、`serviceaccount`、`role`、`clusterrole`、`rolebinding`、`clusterrolebinding`;全部支援 `--dry-run=client -o yaml`(可重導向存檔) |
| `delete` | `-f`、資源名稱(可多個)、`--all`、`-l`、`all`、`--cascade=orphan`;`--force --grace-period=0 --now --wait` 會被接受 |
| `run` | `--image --port --restart=Never|OnFailure --labels --env --command -- 指令`、`--dry-run=client -o yaml`;`--rm -it --image=… -- 指令` 以一次性 Pod 執行(例如 `-- curl -s web`、`-- wget -qO- http://web`) |
| `expose` | deployment / pod / service / rs / sts / ds;`--port --target-port --type --name --protocol`、`--dry-run` |
| `scale` | deployment / replicaset / statefulset,`--replicas`、`--current-replicas` |
| `set image` | `容器名=映像`、`*=映像`;deployment / sts / ds / rs / pod / cronjob |
| `rollout` | `status`(`--timeout`)、`history`(`--revision`)、`undo`(`--to-revision`)、`restart`(deployment)。`pause`/`resume` 未支援 |
| `label` / `annotate` | `k=v`、`k-`、`--overwrite`、`--all`、`-l`;改 Pod 標籤會讓它脫離/重新被 ReplicaSet 認領、Service endpoints 即時更新 |
| `logs` | `-c`、`--previous`/`-p`、`--tail`、`-f`(視為一次輸出)、`-l`、`deploy/x`、`job/x`、`sts/x`;對 ContainerCreating / ImagePullBackOff 等狀態回真實的 BadRequest 錯誤 |
| `exec` | 在 `--` 後帶指令:`ls`、`cat`、`env`/`printenv`、`hostname`、`pwd`、`whoami`、`id`、`date`、`echo`、`curl`、`wget`、`nslookup`、`sh -c "…"`(以 `;`、`&&` 串接)。可讀到 ConfigMap/Secret 掛載的檔案、`/etc/resolv.conf`、nginx 的 index.html。不支援互動式 shell(`-it sh`) |
| `port-forward` | 只顯示 `Forwarding from 127.0.0.1:L -> R`,不會真的轉送 |
| `top` | `nodes`、`pods`(數值為決定性的假資料) |
| `cordon` / `uncordon` / `drain` / `taint` | drain 支援 `--ignore-daemonsets --delete-emptydir-data --force`,真實的錯誤訊息;taint 支援 `k=v:Effect`、`k:Effect-`、`--overwrite` |
| `auth can-i` | `VERB RESOURCE [-n ns] [--as USER|system:serviceaccount:ns:name]`(依 Role/RoleBinding/ClusterRole/ClusterRoleBinding 判斷);不加 `--as` 是 cluster-admin(一律 yes) |
| `explain` | pod / deployment / service / configmap / namespace 與其 spec、containers、replicas、selector、strategy、template、ports、type |
| `api-resources` / `events` / `wait` | `events --for pod/x --types=Warning`;`wait --for=condition=Ready|Available|Complete / delete / jsonpath=…`、`--timeout` |

**刻意不支援**(會回覆「練習環境尚未支援」或說明):`edit`(需要編輯器)、`patch`、`replace`、`cp`、`attach`、`debug`、`proxy`、`diff`、`autoscale`、`kustomize`、`rollout pause/resume`、`set env/resources`、`create secret docker-registry/tls`、`auth can-i --list`、`apply --server-side`、互動式 shell、go-template 輸出。

## Pod 狀態機(排錯練習)
| 條件 | 結果 |
|---|---|
| 一般 | `ContainerCreating` → `Running` |
| 映像名稱含 `nonexistent`,或 tag 不在 `world.images[…].tags` | `ErrImagePull` → `ImagePullBackOff`(Events 有真實的 `Failed to pull image …`) |
| 映像 `crash: true`、command 含 `exit 1`、或缺少 `requireEnvAny` 的環境變數 | `Error` → `CrashLoopBackOff`,RESTARTS 遞增,`logs`/`logs --previous` 有內容 |
| `resources.requests` 超過所有節點剩餘容量 | `Pending`,Events `FailedScheduling: 0/3 nodes are available: …Insufficient cpu…` |
| 有 `nodeSelector`/taint 對不上 | `Pending`,Events 說明 `didn't match Pod's node affinity/selector` / `untolerated taint` |
| `readinessProbe` 失敗(路徑不在 `paths`、埠不在 `ports`、`healthy:false`) | `Running` 但 `0/1`,Events `Readiness probe failed: …`(404 / connection refused) |
| `livenessProbe` 失敗 | 重啟次數遞增 → `CrashLoopBackOff` |
| `env.valueFrom.configMapKeyRef/secretKeyRef`(或 envFrom)指向不存在的 ConfigMap/Secret/key | `CreateContainerConfigError`;補建之後自動恢復 |
| 以 `configMap`/`secret` volume 掛載不存在的物件 | 卡在 `ContainerCreating`,Events `FailedMount` |
| 掛載不存在的 PVC / PVC 尚未 Bound | `Pending`(`persistentvolumeclaim "x" not found` / `unbound immediate PersistentVolumeClaims`) |
| `command` 跑完就結束 | `restartPolicy: Never` → `Completed`;`Always` → `Completed` 後 `CrashLoopBackOff`(Job/`kubectl run --restart=Never` 常用 `sh -c "echo hi"`) |
| 有 `initContainers` | 先 `Init:0/N` 再往下走 |

command 中的 `sleep N`(N 小於 100)會讓容器 N 秒後結束,`sleep 3600`、`tail -f`、`while true` 則視為長期執行;`echo xxx` 會成為 `kubectl logs` 的內容。

其他行為:Deployment 滾動更新(maxSurge/maxUnavailable,預設 25%)、`Recreate`、revision 與 `rollout undo`(會沿用舊 ReplicaSet)、壞映像讓更新卡住而舊 Pod 保持服務;StatefulSet 依序啟動並建立 `volumeClaimTemplates` 的 PVC;DaemonSet 每個符合條件的節點一個 Pod;CronJob 依 `*/N * * * *` 每 N 分鐘(6N 個 tick)產生 Job;PVC 動態配置/綁定靜態 PV/`WaitForFirstConsumer`;Service endpoints 即時依 selector 與 Pod 就緒狀態計算,`targetPort` 可用名稱;`curl` 到 Service 會輪流打到各個 Pod。
資源建立時的常見錯誤都會回真實風格的訊息:selector 與 template labels 不符、缺 selector、apiVersion 不對(`no matches for kind`)、欄位拼錯(`strict decoding error: unknown field "spec.replica"`)、YAML 縮排錯(`error converting YAML to JSON: yaml: line N: …`)、`replicas: "3"` 型別錯、名稱不合法、Job restartPolicy 不合法、requests 大於 limits、volumeMount 找不到 volume、namespace 不存在、AlreadyExists、NotFound(`Error from server (NotFound): deployments.apps "x" not found`)。

## helm(簡化版)
`repo add|list|update|remove`、`search repo`、`install`、`upgrade [--install]`、`uninstall`、`list [-A]`、`status`、`template`、`get manifest|values`、`version`。選項:`--set a.b=c,d=e`、`-f values.yaml`(讀虛擬檔案系統)、`-n`、`--create-namespace`、`--dry-run`。
chart 來源:`world.k8s.charts` 的 `repo/名稱`(需先 `helm repo add`),或虛擬檔案系統裡含 `Chart.yaml`、`values.yaml`、`templates/` 的目錄(`helm install x ./mychart`)。
範本語法只支援:`{{ .Values.x.y }}`、`.Release.Name/Namespace/Revision`、`.Chart.Name/Version/AppVersion`、`if / else if / else / end`、`{{-`/`-}}` 去空白、函式 `default quote squote upper lower title trim trunc toString int toYaml nindent indent replace required printf not eq ne and or b64enc`(可用管線 `|`)。`range`、`with`、`define`、`include`、`template` 會回報「練習環境不支援」。
`helm install` 會真的把渲染後的資源建立到叢集(`kubectl get` 看得到),`uninstall` 會刪除。`rollback`、`history`、`create`、`lint`、`package` 未支援。

## check 類型
checks 在 `tasks[].check` 或 `tasks[].checks`(全部成立才算)使用。`namespace` 省略時為 `default`。`kind` 可寫 `deployment`、`pod`、`svc` 等簡稱或全名。

| type | 欄位 | 說明 |
|---|---|---|
| `resource` | `kind`, `name`, `namespace`, `exists`(預設 true;false = 不存在) | 資源存在/不存在。`namePrefix` 可取代 `name` 做前綴比對 |
| `ready` | `kind`(deployment/statefulset/daemonset/replicaset), `name`, `namespace`, `replicas` | 期望副本數等於 `replicas`,且就緒的 Pod 數 ≥ `replicas`。省略 `replicas` = 全部就緒 |
| `podstatus` | `selector`(標籤選擇器)或 `name`(Pod 名稱前綴,亦可用 `prefix`), `namespace`, `status`, `count`, `ready`(如 `1/1`) | 符合的 Pod 中,STATUS 等於 `status`(`Running`、`CrashLoopBackOff`、`ImagePullBackOff`、`Pending`、`Completed`…)的數量恰為 `count`(省略 count = 至少 1 個) |
| `endpoints` | `service`(或 `name`), `namespace`, `count` | Service 的就緒 endpoints 數量等於 `count`(預設 1) |
| `field` | `kind`, `name`, `namespace`, `path`, `equals`(或 `contains`) | 取 `kubectl get -o yaml` 物件的欄位比較,`path` 如 `spec.replicas`、`spec.template.spec.containers[0].image`、`spec.type`、`status.phase`、`data.LOG_LEVEL` |
| `image` | `kind`(deployment/pod/statefulset/daemonset/cronjob…), `name`, `namespace`, `equals`, 可選 `container` | 容器映像等於 `equals`(kind=pod 且找不到該名稱時,以名稱前綴比對所有 Pod) |
| `labelled` | `kind`, `name`, `namespace`, `label`(`k=v` 或 `k=v,k2=v2`,只寫 `k` 表示有此標籤)或 `labels`(物件) | 資源帶有指定標籤 |
| `rescount` | `kind`, `namespace`, 可選 `selector`, `equals` | 資源數量(例如某標籤的 Pod 數量) |
| `helm` | `name`, `namespace`, `exists`, `status` | helm release 存在(預設)/不存在 |

核心內建的 `ran`(指令樣式)、`out`(輸出樣式)、`contains`/`equals`/`exists`(虛擬檔案系統)仍可搭配使用,例如檢查學員有把 YAML 存成檔案:`['type' => 'exists', 'path' => '~/k8s-lab/api.yaml']`。注意核心已佔用 `count`、`equals`、`contains` 等名稱,所以資源數量檢查叫 `rescount`。

## 完整範例(terminal 單元)
```php
['title' => '部署、擴充與排錯', 'type' => 'terminal', 'xp' => 40,
 'content' => <<<'TXT'
你剛接手一個小叢集,~/k8s-lab 裡有兩份 YAML:web.yaml 是網站的 Deployment(2 個副本),broken.yaml 是一個一直重啟的 Pod。
請先把網站部署起來並等它就緒,再替它建立 Service,接著做一次不中斷的映像升級與擴充,最後找出 broken Pod 為什麼起不來並修好它。
提示的觀念:apply 之後 Pod 需要一點時間才會 Running(再執行一次 get 看看);logs 與 describe 是排錯的第一步;set image 可以更新映像。
TXT,
 'config' => [
    'cwd' => '~/k8s-lab',
    'modules' => ['k8s'],
    'fs' => ['home' => ['student' => ['k8s-lab' => [
        'web.yaml' => "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: nginx\n        image: nginx:1.25\n        ports:\n        - containerPort: 80\n",
        'broken.yaml' => "apiVersion: v1\nkind: Pod\nmetadata:\n  name: broken\nspec:\n  containers:\n  - name: app\n    image: myapp:1\n",
    ]]]],
    'world' => ['k8s' => ['images' => ['myapp' => ['tags' => ['1'], 'crash' => true, 'logs' => ['panic: DATABASE_URL is not set']]]]],
    'tasks' => [
        ['title' => '用 apply 部署 web Deployment', 'hint' => 'kubectl apply -f web.yaml', 'check' => ['type' => 'resource', 'kind' => 'deployment', 'name' => 'web']],
        ['title' => '等 web 的 2 個 Pod 都就緒', 'hint' => 'kubectl rollout status deployment/web', 'check' => ['type' => 'ready', 'kind' => 'deployment', 'name' => 'web', 'replicas' => 2]],
        ['title' => '建立 Service web,並確認有 2 個 endpoints', 'hint' => 'kubectl expose deployment web --port=80', 'checks' => [['type' => 'resource', 'kind' => 'service', 'name' => 'web'], ['type' => 'endpoints', 'service' => 'web', 'count' => 2]]],
        ['title' => '把 web 升級到 nginx:1.26', 'hint' => 'kubectl set image deployment/web nginx=nginx:1.26', 'check' => ['type' => 'image', 'kind' => 'deployment', 'name' => 'web', 'equals' => 'nginx:1.26']],
        ['title' => '修好 CrashLoopBackOff 的 broken Pod 使它 Running', 'hint' => '先 kubectl apply -f broken.yaml,用 logs 看原因,再 kubectl set image pod/broken app=nginx', 'check' => ['type' => 'podstatus', 'name' => 'broken', 'status' => 'Running', 'count' => 1]],
        ['title' => '把 web 擴充到 3 個副本', 'hint' => 'kubectl scale deployment web --replicas=3', 'checks' => [['type' => 'field', 'kind' => 'deployment', 'name' => 'web', 'path' => 'spec.replicas', 'equals' => 3], ['type' => 'ready', 'kind' => 'deployment', 'name' => 'web', 'replicas' => 3]]],
        ['title' => '替 web 加上標籤 tier=frontend', 'hint' => 'kubectl label deployment web tier=frontend', 'check' => ['type' => 'labelled', 'kind' => 'deployment', 'name' => 'web', 'label' => 'tier=frontend']],
    ],
    'solution' => [
        'kubectl apply -f broken.yaml', 'kubectl apply -f web.yaml', 'kubectl get pods', 'kubectl logs broken',
        'kubectl rollout status deployment/web', 'kubectl expose deployment web --port=80',
        'kubectl set image deployment/web nginx=nginx:1.26', 'kubectl rollout status deployment/web',
        'kubectl set image pod/broken app=nginx', 'kubectl scale deployment web --replicas=3',
        'kubectl label deployment web tier=frontend', 'kubectl rollout status deployment/web',
        'kubectl get pods', 'kubectl get pods',
    ],
 ],
],
```

## 作者注意事項
- 任務在**一開始不能已經成立**:例如 `resource ... exists=false` 對還沒建立的東西一開始就是真的,請搭配其他條件(如 `ran`)。
- 解答最後多放 `kubectl get pods`,因為檢查不推進時間(見上)。
- 想讓學員看到 `ImagePullBackOff` 最簡單:映像寫 `nonexistent/app:1.0` 或不存在的 tag(例如 `nginx:9.9`);想看 `CrashLoopBackOff`:在 `world.images` 定義 `crash: true`,或讓 mysql 不設 `MYSQL_ROOT_PASSWORD`;想看 `Pending`:requests 設 `cpu: "8"`。
- 學員用 `echo "..." > f.yaml` 寫多行 YAML 不方便(核心沒有 heredoc、`\n` 要用 `echo -e`),建議預先放好檔案,或請學員用 `--dry-run=client -o yaml > f.yaml` 產生。
- 輸出中的 Pod 名稱後綴(如 `web-5d4c8b7d9-x7k2p`)是依叢集狀態雜湊出的,同樣的操作序列每次都一樣,但不要在 hint 裡寫死;需要時請讓學員用 `kubectl get pods` 自己看。
