phase 5 part 4: java-spring awareness, k8s basics with validated manifests, run_examples supports single-file Java
This commit is contained in:
1 parent
075872e31e
commit
f695bbd7cc
18 files changed
+1192
-23
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# 非敏感配置。敏感信息(模型 API Key、数据库密码)放 Secret,并且不要提交到仓库
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: agent-api-config
|
||||
labels:
|
||||
app.kubernetes.io/name: agent-api
|
||||
data:
|
||||
LOG_LEVEL: "info"
|
||||
MODEL_TIMEOUT_SECONDS: "60"
|
||||
REDIS_URL: "redis://redis.default.svc.cluster.local:6379/0"
|
||||
@@ -0,0 +1,75 @@
|
||||
# AI Agent API 的 Deployment:滚动更新、三种探针、资源限制、非 root 运行、优雅退出
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: agent-api
|
||||
labels:
|
||||
app.kubernetes.io/name: agent-api
|
||||
spec:
|
||||
replicas: 3
|
||||
revisionHistoryLimit: 5
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: agent-api
|
||||
strategy:
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxSurge: 1 # 更新时最多多出 1 个 Pod
|
||||
maxUnavailable: 0 # 更新过程中可用 Pod 数不减少
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: agent-api
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 90 # 留时间让正在进行的流式回答结束
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 10001
|
||||
containers:
|
||||
- name: api
|
||||
image: registry.example.com/agent-api:1.4.2 # 使用固定版本,不用 latest
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 8000
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: agent-api-config
|
||||
env:
|
||||
- name: LLM_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: agent-api-secrets # 由运维或密钥管理系统创建,不在仓库中
|
||||
key: llm-api-key
|
||||
resources:
|
||||
requests:
|
||||
cpu: "250m"
|
||||
memory: "256Mi"
|
||||
limits:
|
||||
memory: "512Mi" # 内存设上限防止拖垮节点;CPU 不设上限避免被限流(按团队规范)
|
||||
startupProbe: # 启动慢(加载模型配置、预热连接)时,避免被存活探针误杀
|
||||
httpGet:
|
||||
path: /healthz
|
||||
port: http
|
||||
periodSeconds: 5
|
||||
failureThreshold: 24
|
||||
readinessProbe: # 未就绪时不接收流量(例如依赖的 Redis 不可用)
|
||||
httpGet:
|
||||
path: /readyz
|
||||
port: http
|
||||
periodSeconds: 5
|
||||
failureThreshold: 3
|
||||
livenessProbe: # 进程卡死时重启;不要检查外部依赖,否则依赖故障会引发全体重启
|
||||
httpGet:
|
||||
path: /healthz
|
||||
port: http
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
lifecycle:
|
||||
preStop: # 先等负载均衡摘除,再收到 SIGTERM。sleep 动作需要较新的 Kubernetes(1.30+,以官方文档为准),旧版本用 exec sleep
|
||||
sleep:
|
||||
seconds: 5
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
@@ -0,0 +1,33 @@
|
||||
# 按 CPU 自动扩缩容。AI 服务多为 I/O 等待,CPU 不一定能反映负载,可改用自定义指标(并发请求数、队列长度)
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
metadata:
|
||||
name: agent-api
|
||||
spec:
|
||||
scaleTargetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: agent-api
|
||||
minReplicas: 3
|
||||
maxReplicas: 10
|
||||
metrics:
|
||||
- type: Resource
|
||||
resource:
|
||||
name: cpu
|
||||
target:
|
||||
type: Utilization
|
||||
averageUtilization: 70
|
||||
behavior:
|
||||
scaleDown:
|
||||
stabilizationWindowSeconds: 300 # 缩容慢一点,避免抖动
|
||||
---
|
||||
# 节点维护(驱逐)时至少保留 2 个可用 Pod
|
||||
apiVersion: policy/v1
|
||||
kind: PodDisruptionBudget
|
||||
metadata:
|
||||
name: agent-api
|
||||
spec:
|
||||
minAvailable: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: agent-api
|
||||
@@ -0,0 +1,24 @@
|
||||
# 以 ingress-nginx 为例:SSE 流式接口要关闭缓冲、加长读超时。注解名称以所用 Ingress 控制器的文档为准
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: agent-api
|
||||
annotations:
|
||||
nginx.ingress.kubernetes.io/proxy-buffering: "off"
|
||||
nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
|
||||
spec:
|
||||
ingressClassName: nginx
|
||||
tls:
|
||||
- hosts: ["agent.example.com"]
|
||||
secretName: agent-example-tls
|
||||
rules:
|
||||
- host: agent.example.com
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: agent-api
|
||||
port:
|
||||
name: http
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: agent-api
|
||||
labels:
|
||||
app.kubernetes.io/name: agent-api
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app.kubernetes.io/name: agent-api # 必须和 Pod 的标签一致,否则 Service 没有后端
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: http
|
||||
@@ -0,0 +1,63 @@
|
||||
# requires: yaml
|
||||
"""对清单做团队规范检查(kubeconform 只校验结构,这里检查“写对了但不合规范”的问题)。
|
||||
|
||||
运行:pytest -q test_manifests.py
|
||||
结构校验(可选):kubeconform -strict -summary *.yaml
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
|
||||
|
||||
def load_all() -> list[dict]:
|
||||
docs = []
|
||||
for f in sorted(HERE.glob("*.yaml")):
|
||||
docs += [d for d in yaml.safe_load_all(f.read_text(encoding="utf-8")) if d]
|
||||
return docs
|
||||
|
||||
|
||||
DOCS = load_all()
|
||||
|
||||
|
||||
def by_kind(kind: str) -> list[dict]:
|
||||
return [d for d in DOCS if d["kind"] == kind]
|
||||
|
||||
|
||||
def test_selector_matches_pod_labels():
|
||||
for dep in by_kind("Deployment"):
|
||||
sel = dep["spec"]["selector"]["matchLabels"]
|
||||
labels = dep["spec"]["template"]["metadata"]["labels"]
|
||||
assert sel.items() <= labels.items()
|
||||
for svc in by_kind("Service"):
|
||||
assert svc["spec"]["selector"].items() <= labels.items(), "Service 选择器和 Pod 标签不一致"
|
||||
|
||||
|
||||
def test_containers_follow_rules():
|
||||
for dep in by_kind("Deployment"):
|
||||
for c in dep["spec"]["template"]["spec"]["containers"]:
|
||||
image = c["image"]
|
||||
assert ":" in image.rsplit("/", 1)[-1] and not image.endswith(":latest"), "镜像必须固定版本"
|
||||
assert "requests" in c["resources"] and "memory" in c["resources"].get("limits", {})
|
||||
for probe in ("readinessProbe", "livenessProbe"):
|
||||
assert probe in c, f"缺少 {probe}"
|
||||
assert c["securityContext"]["allowPrivilegeEscalation"] is False
|
||||
for e in c.get("env", []):
|
||||
assert "value" not in e or "KEY" not in e["name"].upper(), "密钥不能明文写在清单中"
|
||||
|
||||
|
||||
def test_rolling_update_keeps_capacity():
|
||||
for dep in by_kind("Deployment"):
|
||||
ru = dep["spec"]["strategy"]["rollingUpdate"]
|
||||
assert ru["maxUnavailable"] == 0
|
||||
|
||||
|
||||
def test_pdb_lower_than_min_replicas():
|
||||
hpa_min = min(h["spec"]["minReplicas"] for h in by_kind("HorizontalPodAutoscaler"))
|
||||
for pdb in by_kind("PodDisruptionBudget"):
|
||||
assert pdb["spec"]["minAvailable"] < hpa_min, "PDB 要求的可用数不小于副本数会导致节点无法驱逐"
|
||||
|
||||
|
||||
def test_no_secret_objects_in_repo():
|
||||
assert not by_kind("Secret"), "Secret 不应提交到仓库"
|
||||
Reference in new issue
Block a user