166 lines
8.8 KiB
Python
166 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
||
"""K3S 部署清单的结构验收(不连集群,纯文件校验)。
|
||
|
||
python3 backend/scripts/check_k8s_manifest.py
|
||
|
||
踩过的两个坑都在这儿钉着:
|
||
|
||
1. **控制台导入报** ``解析错误 undefined : TypeError: Cannot read properties of null
|
||
(reading 'metadata')``——界面是把整份文件切成一篇篇文档再逐篇读 ``metadata`` 的,
|
||
所以任何一篇"只有注释、没有对象"的空文档都能把它顶翻。最典型就是夹在两个 ``---``
|
||
之间的一段注释(比如注释掉的 PVC)。这里按 ``---`` 切段,逐段确认去掉注释还剩真内容。
|
||
2. **PVC 重复导入报** ``spec is immutable ... "VolumeName": ""``——PVC 一旦 Bound 就
|
||
不能再声明,所以清单默认不导它,改放文件最底下整段注释。这里钉住"默认注释"与
|
||
"Deployment 引用的 PVC 名与注释里那个名字对得上",放开时才建得出着落。
|
||
|
||
顺带把 selector / 端口 / Ingress 后端 / 卷与挂载点 / ConfigMap 与 Secret 引用这些
|
||
"错了就起不来或流量进不去"的对应关系一起核一遍——本机没有集群可 dry-run,
|
||
能自动核的就别再靠眼睛。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import yaml
|
||
|
||
#: 脚本在 backend/scripts 下,仓库根在上一层的上一层
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
MANIFEST = ROOT / "deploy/k8s/unis-oa.yaml"
|
||
README = ROOT / "deploy/k8s/README.md"
|
||
|
||
FAILS: list[str] = []
|
||
PASSED = 0
|
||
|
||
|
||
def check(label: str, condition, detail="") -> None:
|
||
global PASSED
|
||
if condition:
|
||
PASSED += 1
|
||
print(f"[通过] {label}")
|
||
else:
|
||
FAILS.append(label)
|
||
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
|
||
|
||
|
||
def body_of(chunk: str) -> str:
|
||
"""一段文档去掉整行注释与空行之后的剩下的内容(判断它是不是空文档)。"""
|
||
kept = [line for line in chunk.splitlines() if line.strip() and not line.lstrip().startswith("#")]
|
||
return "\n".join(kept).strip()
|
||
|
||
|
||
def main() -> int:
|
||
text = MANIFEST.read_text(encoding="utf-8")
|
||
# 按 --- 切段:这是界面与 js-yaml 的切法,与 yaml.safe_load_all 的"篇"一一对应
|
||
chunks = re.split(r"(?m)^---\s*$", text)
|
||
empty = [index for index, chunk in enumerate(chunks) if not body_of(chunk)]
|
||
check("每一段都有真对象(纯注释段会解析成 null 文档,顶翻导入界面)",
|
||
not empty, f"空文档段号:{empty}")
|
||
check("文件不以 --- 收尾(收尾那个分隔符后面必然跟一篇空文档)",
|
||
not text.rstrip().endswith("---"))
|
||
|
||
docs = [d for d in yaml.safe_load_all(text) if d]
|
||
check("yaml 解析出来的文档数与分段数一致(没有 null 篇)",
|
||
len(list(yaml.safe_load_all(text))) == len(docs) == len(chunks),
|
||
(len(list(yaml.safe_load_all(text))), len(docs), len(chunks)))
|
||
|
||
by = {(d["kind"], d["metadata"]["name"]): d for d in docs}
|
||
want = {("Namespace", "unis-oa"), ("Secret", "unis-oa-registry"), ("ConfigMap", "unis-oa-config"),
|
||
("Secret", "unis-oa-secret"), ("Deployment", "unis-oa"), ("Service", "unis-oa"),
|
||
("Ingress", "unis-oa")}
|
||
check("该有的一次到位、不该多的一个不多", set(by) == want, sorted(set(by) ^ want))
|
||
check("除 Namespace 外每个对象都写死了命名空间(界面导入按文件里的 namespace 落)",
|
||
{d["metadata"].get("namespace") for d in docs if d["kind"] != "Namespace"} == {"unis-oa"})
|
||
|
||
dep = by[("Deployment", "unis-oa")]
|
||
pod = dep["spec"]["template"]
|
||
spec = pod["spec"]
|
||
container = spec["containers"][0]
|
||
check("selector / Pod labels / Deployment labels 三层对得上",
|
||
dep["spec"]["selector"]["matchLabels"] == pod["metadata"]["labels"] == {"app": "unis-oa"},
|
||
(dep["spec"]["selector"]["matchLabels"], pod["metadata"]["labels"]))
|
||
|
||
svc = by[("Service", "unis-oa")]
|
||
port_names = [p.get("name") for p in container["ports"]]
|
||
check("Service 选得到 Pod 且端口指到容器端口名",
|
||
svc["spec"]["selector"] == {"app": "unis-oa"}
|
||
and svc["spec"]["ports"][0]["targetPort"] in port_names,
|
||
svc["spec"]["ports"])
|
||
check("容器端口是 8000(后端 API 与前端静态页同源那一个)",
|
||
[p["containerPort"] for p in container["ports"]] == [8000], container["ports"])
|
||
|
||
ing = by[("Ingress", "unis-oa")]
|
||
check("Ingress 指到这个 Service 与它的 http 端口",
|
||
ing["spec"]["rules"][0]["http"]["paths"][0]["backend"]["service"]
|
||
== {"name": "unis-oa", "port": {"name": "http"}},
|
||
ing["spec"]["rules"][0]["http"]["paths"][0]["backend"]["service"])
|
||
|
||
mounts, volumes = container["volumeMounts"], spec["volumes"]
|
||
check("挂载点与卷一一对应(名字对不上就是挂不上,容器起不来)",
|
||
sorted(m["name"] for m in mounts) == sorted(v["name"] for v in volumes),
|
||
(sorted(m["name"] for m in mounts), sorted(v["name"] for v in volumes)))
|
||
referenced = {v["configMap"]["name"] for v in volumes if "configMap" in v}
|
||
check("引用的 ConfigMap / Secret / 拉取凭证都在文件里",
|
||
referenced == {"unis-oa-config"}
|
||
and container["envFrom"][0]["secretRef"]["name"] == "unis-oa-secret"
|
||
and spec["imagePullSecrets"][0]["name"] == "unis-oa-registry",
|
||
(referenced, container.get("envFrom"), spec.get("imagePullSecrets")))
|
||
|
||
sc = spec.get("securityContext") or {}
|
||
check("以非 root 的 unisoa(uid 10001)跑,且 fsGroup 就位(挂进来的卷才写得动)",
|
||
sc.get("runAsUser") == 10001 and sc.get("runAsGroup") == 10001 and sc.get("fsGroup") == 10001, sc)
|
||
check("RWO 卷配的是 Recreate,副本数按住 1(滚动更新会卡在卷被旧 Pod 占着)",
|
||
dep["spec"]["strategy"]["type"] == "Recreate" and dep["spec"]["replicas"] == 1,
|
||
(dep["spec"]["strategy"], dep["spec"]["replicas"]))
|
||
|
||
probes = container
|
||
check("readiness 真连一次库(只打匿名接口的话,库断了照样算健康)",
|
||
probes["readinessProbe"].get("exec", {}).get("command", [])[-1].strip().startswith("from app.db import engine"),
|
||
probes["readinessProbe"])
|
||
check("startup / liveness 打匿名接口,冷启动给足时间",
|
||
probes["startupProbe"]["httpGet"]["path"] == "/api/v1/settings/public"
|
||
and probes["livenessProbe"]["httpGet"]["path"] == "/api/v1/settings/public")
|
||
|
||
# ---- PVC:默认不导,但 Deployment 引用它,放开时必须有名字对得上的那一段
|
||
claim = [v["persistentVolumeClaim"]["claimName"] for v in volumes if "persistentVolumeClaim" in v]
|
||
pvc_docs = [d for d in docs if d["kind"] == "PersistentVolumeClaim"]
|
||
commented = re.search(r"(?m)^#\s*kind:\s*PersistentVolumeClaim\b", text)
|
||
check("PVC 默认是注释掉的(Bound 之后再导必报 spec is immutable)",
|
||
not pvc_docs and commented is not None, [d["metadata"]["name"] for d in pvc_docs])
|
||
if commented is not None:
|
||
named = re.search(r"(?m)^#\s*name:\s*(\S+)", text[commented.start():])
|
||
check("放开注释就能建出 Deployment 引用的那只 PVC(名字两边一致)",
|
||
claim == [named.group(1)] if named else False, (claim, named and named.group(1)))
|
||
check("注释块自带它上面那行 ---(放开即成一篇真文档,不会挤进邻居文档里)",
|
||
0 < text.rfind("# ---", 0, commented.start()) < commented.start(), "找不到被注释掉的分隔符")
|
||
live = "\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#"))
|
||
check("生效行里只认这一只 PVC:claimName 只有一处,旧名 unis-oa-storage 只剩注释在讲历史",
|
||
live.count("claimName:") == 1 and "unis-oa-storage" not in live and claim, (claim,))
|
||
|
||
# ---- tag:清单钉的与 README 写的必须是一句话,回滚时才找得到人
|
||
image = container["image"]
|
||
tag = image.rsplit(":", 1)[-1]
|
||
check("镜像是仓库里的 unis_oa,tag 是 12 位时间戳(钉 tag 才有得回滚)",
|
||
image.startswith("docker.oa.unissense.tech/public/unis_oa:") and re.fullmatch(r"\d{12}", tag),
|
||
image)
|
||
readme = README.read_text(encoding="utf-8")
|
||
documented = re.search(r"当前 `(\d{12})`", readme)
|
||
check("README 里写的当前 tag 与清单钉的同一个",
|
||
documented is not None and documented.group(1) == tag, (documented and documented.group(1), tag))
|
||
check("README 也写明了构建与推送的指令", "docker buildx build --platform linux/amd64" in readme)
|
||
|
||
print()
|
||
if FAILS:
|
||
print(f"{len(FAILS)} 条没对上:")
|
||
for item in FAILS:
|
||
print(f" - {item}")
|
||
return 1
|
||
print(f"全部 {PASSED} 条对上:{MANIFEST.relative_to(ROOT)}({len(docs)} 个对象,无空文档)")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|