Kubernetes
Wow 服务在 Kubernetes 上以一个 Deployment 运行:它的 Pod 就是服务的节点,它们通过服务的数据库互相发现,其他服务通过一个 headless Service 访问它们。别的都不需要:没有 Operator,没有 ZooKeeper,也没有 Kafka 消费组。Wow 的 Helm chart wow-service 为一个服务渲染出这些对象,随 Wow 发布,版本即 Wow 的版本。平台为每个服务各安装一次。本页用它安装 eShop 的 ordering 服务;背后的思路见部署模型。
安装一个服务
一个 release 取两个 values 文件,后一个覆盖前一个:
构建知道的 values。
./gradlew :<server>:generateWowHelmValues(assemble会运行它)按服务的契约把它们写进build/wow/helm/values.yaml:服务名,chart 以它命名每个对象;类路径上有契约的对端,各带托管它的服务(service.contractPeers);以及节点提供 Manifest 的路由。它们随代码变化,不要手抄。basket 的:yamlservice: name: "eshop-basket-service" contractPeers: - context: "eshop-ordering" service: "eshop-ordering-service" manifest: route: "/wow/manifest"部署自己的 values。 镜像、端口、副本数、所属平台、profile、存储及其密钥、资源。ordering 服务的,在
deploy/eshop-ordering中:
# The eshop-ordering service's own values for the wow-service chart (deploy/helm/wow-service), on MongoDB and Kafka:
# what the build does not know. Pass them after the values its build generates, so they override them:
#
# ./gradlew :eshop-ordering-server:generateWowHelmValues
# helm install eshop-ordering deploy/helm/wow-service \
# -f examples/eshop/ordering/ordering-server/build/wow/helm/values.yaml -f deploy/eshop-ordering/values.yaml
#
# values-postgres.yaml after these puts the service on PostgreSQL instead.
image:
# The image built from this repository (README.md).
repository: wow-eshop-ordering-server
tag: local
# The ports of the image's own configuration (application.yaml), which the chart sets on the pod.
ports:
http: 8083
internal: 9093
# The nodes share the partitions through leases in the service's database: no ZooKeeper, no consumer group.
replicas: 2
# The internal port admits the pods of the platform, labelled app.kubernetes.io/part-of: eshop.
partOf: eshop
config:
# The mongo profile keeps the service's data on MongoDB, the replica set at secret.yaml's URI (deploy/mongodb), in a
# database of its own; the kafka profile connects it to the other contexts through Kafka; the cosec profile takes the
# callers from the CoSec gateway in front of the service.
SPRING_PROFILES_ACTIVE: mongo,kafka,cosec
WOW_KAFKA_BOOTSTRAPSERVERS: kafka:9092
# The topics the service owns are created by the operator; the node only validates them. The kafka profile's auto
# is for trying the service out.
WOW_KAFKA_DDL: validate
# Fixed once the context's log holds entries; the command topic wow.eshop-ordering.commands has as many partitions.
WOW_LOG_PARTITIONS: "64"
# Traces and metrics: the node's spans and Micrometer meters go through the OpenTelemetry Java agent, which the
# OpenTelemetry Operator injects (podAnnotations, with an Instrumentation resource in the namespace). Without the
# agent they are no-ops. It exports to the collector below over OTLP, and bridges Micrometer's global registry.
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_INSTRUMENTATION_MICROMETER_ENABLED: "true"
# The database's connection: secret.yaml, an example to replace.
envFrom:
- secretRef:
name: eshop-ordering-service-mongo
podAnnotations:
instrumentation.opentelemetry.io/inject-java: "true"
resources:
requests:
cpu: 500m
memory: 768Mi
limits:
memory: 1Gi
# The public port admits the CoSec gateway's pods (app.kubernetes.io/component: gateway) of the release's own
# namespace, where this deployment runs its gateway: the chart renders only once the gateway's namespace is named. A
# gateway in a namespace of its own is named by it, in the entry's namespaceSelector:
# matchLabels:
# kubernetes.io/metadata.name: <the gateway's namespace>
networkPolicy:
public:
from:
- podSelector:
matchLabels:
app.kubernetes.io/component: gateway然后从 OCI 仓库按服务构建所用的 Wow 版本安装,或从仓库的检出(deploy/helm/wow-service)安装:
helm upgrade --install eshop-ordering oci://ghcr.io/ahoo-wang/wow-service --version <wow-version> \
-f examples/eshop/ordering/ordering-server/build/wow/helm/values.yaml \
-f deploy/eshop-ordering/values.yaml --waitchart 也在 oci://registry-1.docker.io/ahoowang/wow-service。它的 values.schema.json 只接受 chart 声明的键:拼错的键会让安装失败,正如节点拒绝它不认识的 wow.* 键。每个 value 的说明在 chart 的 values.yaml 里;它的 README 列出它渲染的对象。
安装之前
- 构建镜像并推送,或者把它加载到本地集群。
- 准备数据库;服务用到 Kafka 时,也准备 Kafka。
deploy/mongodb里有一个可作起点的 MongoDB 副本集;要用 PostgreSQL,就在values.yaml之后再传values-postgres.yaml,并按 PostgreSQL 设置服务端。 - 创建服务拥有的 Kafka 主题,因为
values.yaml设置了WOW_KAFKA_DDL=validate:命令主题的分区数必须与日志完全相同(Kafka)。 - 创建
envFrom指定的密钥,可以从 values 旁边的示例(secret.yaml、postgres-secret.yaml)创建,也可以来自你自己的存储。
deploy/eshop 安装整个 eShop,每个服务一个 release。
渲染出的对象
每个对象都以 service.name,即服务的 spring.application.name 命名,从不以 release 命名:
| 对象 | 名字 | 内容 |
|---|---|---|
| Deployment | <name> | 节点 |
| ConfigMap | <name>-config | config 作为环境变量,settings 作为 SPRING_APPLICATION_JSON,javaOpts,关闭的时限 |
| Service | <name> | 公开的 HTTP 端口 |
| Service | <name>-cluster | 内部端口,headless |
| NetworkPolicy | <name>-public、<name>-internal | 谁可以访问每个端口 |
| PodDisruptionBudget | <name> | 一次自愿中断可以带走几个节点 |
| ServiceAccount | <name> | 不挂载令牌:节点不调用 Kubernetes API |
| HorizontalPodAutoscaler 或 ScaledObject | <name> | 可选:伸缩 |
| ServiceMonitor 或 PodMonitor | <name> | 可选:监控;ServiceMonitor 另带一个 headless Service <name>-metrics |
标签
每个对象都带 chart 的标签:app.kubernetes.io/name(服务名)、app.kubernetes.io/instance、app.kubernetes.io/version、app.kubernetes.io/managed-by、helm.sh/chart,设置了 partOf 时还有 app.kubernetes.io/part-of。Pod 只按 app.kubernetes.io/name 选择:Deployment、两个 Service、中断预算、网络策略、监控对象和拓扑分布都按它选择这些 Pod,其他服务的内部网络策略也按它放行这些 Pod,正如平台的策略按 app.kubernetes.io/part-of 放行。
podLabels 给 Pod 加上你自己的标签,metrics.serviceMonitor.labels 和 metrics.podMonitor.labels 给监控对象加标签(例如 Prometheus Operator 据以挑选它们的 release 标签)。它们都不能设置 chart 自己的标签:渲染会失败,并指出那个键。Pod 上的 app.kubernetes.io/name 会让每个选择器都选不到 Pod,其他的则会渲染出同名的第二个键。
镜像
镜像在 JDK 25 基础镜像(按摘要钉住)上以数字非 root 用户运行服务的 Gradle 发行包(./gradlew :eshop-ordering-server:installDist),并暴露 HTTP 端口和内部端口。chart 在 Pod 上设置这两个端口(SERVER_PORT、WOW_INTERNAL_PORT,取自 ports),因此 Service、探针和镜像自己的配置不会不一致。
Pod 的用户
chart 让 Pod 以用户和组 10001 运行,即 Wow 镜像声明的那个(USER 10001),并在 Pod 和容器上都设置 runAsNonRoot(podSecurityContext、securityContext)。用户写在 Pod 上,是为了其他控制器加入的容器。instrumentation.opentelemetry.io/inject-java 请求的 OpenTelemetry Operator 的 Java agent,由一个 init 容器复制进来,它的镜像没有声明 USER。这个容器继承应用容器的安全上下文,其中包括 runAsNonRoot。Pod 上没有写用户时,它会以 root 运行,kubelet 就会拒绝这个 Pod:container has runAsNonRoot and image will run as root。有了 Pod 的用户,它以 10001 运行,Pod 就能启动。
镜像基于其他基础镜像构建、文件属于另一个 id 的服务,设置那个 id:
podSecurityContext:
runAsUser: 1001
runAsGroup: 1001两者都设为 null,就又把用户交给镜像决定。这时只要 Pod 里没有加入自身不带 USER 的容器,它就能启动。
JDK
Wow 为 JDK 21 构建,也能在 JDK 21 上运行,但生产环境请用 JDK 25。各后端在虚拟线程上执行阻塞的驱动调用(JDBC、MongoDB 和 Kafka 客户端)。JDK 24 之前,在 synchronized 代码中阻塞的虚拟线程(驱动和 Java agent 常常如此)会钉住它所在的载体线程。这样的线程一多,别的线程就没有载体可用:节点的每个存储和主题调用都不再返回,它的租约失效,其他节点接管它的分区。节点的存活检查随后在 wow.health.liveness.stall-timeout 之后失败,Kubernetes 重启它(健康)。JDK 24 及以后,这些线程可以卸载。运行在更早 JDK 上的节点启动时会就此警告一次。
内存
chart 默认的 javaOpts 是 -XX:MaxRAMPercentage=75.0 -XX:+ExitOnOutOfMemoryError:堆是容器内存上限的四分之三,OutOfMemoryError 会结束进程,于是 Kubernetes 重新启动这个 Pod,其间其他节点接手它的分区。Wow 构建的镜像也设置了 -XX:+ExitOnOutOfMemoryError。你自己的 javaOpts 会替换默认值:请在其中保留 -XX:+ExitOnOutOfMemoryError。没有它时,节点自身工作遇到 OutOfMemoryError 仍会退出它的租约组,其存活检查一直失败直到进程结束(致命错误),但进程中其他地方的错误(例如某个请求中的)就交给 JVM 了。
按节点高峰时持有的东西确定堆的大小,而不是按平均值:状态缓存,除非 wow.state-cache.capacity 限定了它,否则是堆的十分之一(Wow 推导的值);在途的命令,最多 wow.executor.max-in-flight 个,每个都带着它的聚合加载的状态,对于历史很长且近期没有快照的聚合,这意味着重放它的事件;以及每个订阅在它运行的每个分区中持有的条目,最多到它的在途上限。如果内存上限在负载下装不下这些,过载就会变成重启。
共用的设置
服务的每个节点都从 ConfigMap 获得相同的配置,以环境变量形式提供,由 Spring Boot 按宽松规则绑定:即 values 中的 config,如上面 ordering 的那样,写成规范形式(wow.log.partitions 写作 WOW_LOG_PARTITIONS)。环境变量写不出映射项名字里的短横线或点,所以这样的项(wow.peers.eshop-ordering、wow.aggregates.[shop.cart])以树的形式写在 settings 下,chart 把它渲染为 SPRING_APPLICATION_JSON。它覆盖所有变量,所以变量改不了树里已有的设置,只能用旧形式补上树里没有的设置,把键的每个短横线都写成下划线(与树里的 eshop-ordering 并存的 WOW_PEERS_ESHOP_ORDERING_TIMEOUT)。读不到任何项的变量,或给映射添加第二项的变量,宿主会拒绝(键会被检查)。数据库的连接来自一个 Secret,经 envFrom 提供。内部端口不需要密钥:网络就是它的边界。
Service 链接变量
除非 pod 设置 enableServiceLinks: false,Kubernetes 会为它所在命名空间的每个 Service 给它的容器一组变量。对集群 IP 为 10.96.0.12、第一个端口为 9092/TCP 的 Service wow-kafka,它们是 WOW_KAFKA_SERVICE_HOST=10.96.0.12、WOW_KAFKA_SERVICE_PORT=9092 和 WOW_KAFKA_PORT=tcp://10.96.0.12:9092。每个端口再加上 WOW_KAFKA_PORT_9092_TCP=tcp://10.96.0.12:9092 及其 _PROTO、_PORT、_ADDR,每个具名端口再加上 WOW_KAFKA_SERVICE_PORT_<NAME>。所以名为 wow-<分组> 的 Service 给出的变量以 Wow 的分组命名。
chart 设置了 enableServiceLinks: false,所以它的 pod 没有这些变量。chart 之外的 pod,在有这样的 Service 的命名空间里,会看到它们:
- 一个 Service 的变量齐全、彼此一致,如 Kubernetes 所写时,宿主不检查它们,并记录一次不检查的是哪些 Service。
- 形如这些变量、值却不一致的变量(
WOW_KAFKA_PORT=9092)是配置,照常检查,所以拼错的设置无法冒充 Service 链接变量。 - 若某个 Service 的变量被 Spring 读作一个键,启动会被拒绝:
wow-internal给出WOW_INTERNAL_PORT=tcp://10.96.0.5:9090,Spring 把它读作wow.internal.port。Spring Boot 在配置键检查运行之前就绑定这个设置,所以日志里是它的失败分析Failed to bind properties under 'wow.internal.port' to int,带有Origin: System Environment Property "WOW_INTERNAL_PORT"。检查之前没有任何绑定遇到的 Service 变量由检查拒绝,在Wow configuration keys read wrongly下,并指明这个 Service。在这样的 pod 上设置enableServiceLinks: false,或给 Service 换个名字。
节点
# A new node joins before an old one leaves: the partitions move to it through the leases, and none is left without
# an owner while the rollout runs.
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: {{ .Values.rollout.maxSurge }}
maxUnavailable: 0两个副本就是两个节点,它们通过数据库中的租约分担日志的分区。滚动更新先启动一个新 Pod,再停掉一个旧 Pod(maxUnavailable: 0),因此分区始终有属主。每个节点都需要一个身份和一个对端可达的地址,chart 从 Pod 给出:
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
# The ports the Services and the probes name: the chart's, whatever the image's configuration says.
- name: SERVER_PORT
value: {{ .Values.ports.http | quote }}
- name: WOW_INTERNAL_PORT
value: {{ .Values.ports.internal | quote }}
# The node id is the pod's name: a replaced pod is a new member.
- name: WOW_NODE_ID
value: $(POD_NAME)
# The internal port binds the pod's private address only, and the node advertises that address: a
# Deployment's pods have no DNS name of their own.
- name: WOW_INTERNAL_HOST
value: $(POD_IP)
# The namespace a peer's SRV name is in, unless wow.peer.dns.namespaces places the peer elsewhere.
- name: WOW_PEER_DNS_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
{{- with .Values.env }}
{{- toYaml . | nindent 12 }}
{{- end }}- 节点 ID 是 Pod 的名字。被替换的 Pod 作为新成员加入;旧 Pod 的租约到期失效。
- 内部端口绑定 Pod 自己的地址,节点对外公布这个地址,即
<pod IP>:<内部端口>:这是宿主的默认值,所以 chart 不设置wow.node.address。Deployment 的 Pod 没有属于自己的 DNS 名字:headless Service 只为设置了spec.hostname的 Pod 发布<pod>.<service>记录,而 Deployment 无法为每个 Pod 设置它。只有在 Pod 自己的地址不是对端所能访问的地址时才设置wow.node.address,例如 Pod 有固定名字(serviceName和hostname)的 StatefulSet,或有多块网卡的主机。 - 命名空间来自 Pod(
WOW_PEER_DNS_NAMESPACE):节点在这个命名空间里查找它的对端。
两个 Service
# The internal port's headless Service, named after the service with -cluster: its SRV records,
# _internal._tcp.<service>-cluster.<namespace>.svc, name every node's address, the address each node advertises (its pod
# IP), and the other services find the nodes through them. It publishes the nodes that are not ready, so a node that is
# starting or draining is still found. Never expose it outside the cluster: it takes no token, each node and service
# names itself on each request (Wow-Service), and the internal NetworkPolicy admits the platform's own pods alone.
apiVersion: v1
kind: Service
metadata:
name: {{ $name }}-cluster
labels:
{{- include "wow-service.labels" . | nindent 4 }}
spec:
clusterIP: None
publishNotReadyAddresses: true
selector:
{{- include "wow-service.selectorLabels" . | nindent 4 }}
ports:
- name: internal
port: {{ .Values.ports.internal }}
targetPort: internal
protocol: TCP两者都以服务命名。eshop-ordering-service 把公开端口提供给网关,客户端经网关访问它。eshop-ordering-service-cluster 是 headless 的:它的 SRV 记录 _internal._tcp.eshop-ordering-service-cluster.<namespace>.svc 列出每个节点的地址,其他服务只凭服务名就能通过它们找到这些节点(调用其他服务)。它也发布尚未就绪的节点,所以正在启动或排空的节点仍能被找到。
网络策略
绝不要把内部端口暴露到集群之外。它不用令牌:每个请求都声明自己的服务(Wow-Service),网络策略就是边界(保护部署):
networkPolicy:
enabled: true
public:
# Whether the chart tells CoSec that only the gateway can reach the public port
# (COSEC_PIPELINE_IDENTITY_ONLYGATEWAYCANREACH=true), the statement a service in wow.cosec.mode: gateway needs to
# start. It holds only while `from` names the gateway's pods alone: each pod `from` admits can claim any identity to
# such a service. The chart refuses it for an entry of `from` that names no pods by their labels (an empty or no
# podSelector, an ipBlock), which admits every pod it reaches, and for an entry that names no namespace: pod labels
# are their namespace's owner's to set, so a rule by labels in any namespace lets each namespace's owner pass as the
# gateway. Set it false when `from` admits anything else; a service in gateway mode then does not start until you
# state it yourself (where it is true) or change its mode.
onlyGateway: true
# Who reaches the public port: the gateway's pods, labelled app.kubernetes.io/component: gateway, in the gateway's
# namespace, which you name here (the chart does not render while onlyGateway is true and an entry names none). An
# entry names its namespace by kubernetes.io/metadata.name, the label Kubernetes sets to the namespace's name; leave
# the namespaceSelector out when the gateway runs in the release's own namespace.
from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ""
podSelector:
matchLabels:
app.kubernetes.io/component: gateway
internal:
# More pods that reach the internal port, besides the service's own, its platform's and its peers'.
from: []
metrics:
# Who scrapes the metrics port, when it is one of its own: Prometheus' pods, as kube-prometheus-stack labels them.
from:
- namespaceSelector: {}
podSelector:
matchLabels:
app.kubernetes.io/name: prometheus<name>-public只放行网关所在命名空间中、带app.kubernetes.io/component: gateway标签的网关 Pod 访问 HTTP 端口。要点名这个命名空间:不点名 chart 就不渲染,因为只按 Pod 标签、不限命名空间的规则让每个命名空间的所有者都能给一个 Pod 打上网关的标签,而在网关模式下这条规则是服务唯一的认证。一个条目用kubernetes.io/metadata.name(Kubernetes 设为命名空间名字的标签)点名命名空间,写在它的namespaceSelector的matchLabels里,或写成In表达式;不带namespaceSelector的条目放行 release 自己命名空间的 Pod。onlyGateway为真时每个条目都要点名命名空间;为假时任何规则都能渲染,只有默认值里未点名的那条不行,它不放行任何 Pod。给你的网关 Pod 打上这个标签,或者设置networkPolicy.public.from去匹配它们;空列表会放行所有 Pod,因此被拒绝。yamlnetworkPolicy: public: from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: gateway podSelector: matchLabels: app.kubernetes.io/component: gateway<name>-internal放行以下 Pod 访问内部端口:本服务的节点、它所属平台的 Pod(partOf,它给每个对象打上app.kubernetes.io/part-of标签)、它调用的对端的 Pod(对端会回送等待信号),以及networkPolicy.internal.from。
网络插件不执行 NetworkPolicy 时,这些策略不起作用;这时要用别的办法,让内部端口只在平台自己的网络上可达。
其他命名空间的对端
在其他命名空间的对端,在你的 values 文件中给 service.peers 写上它的 namespace:
service:
peers:
- context: eshop-payment
service: eshop-payment-service
namespace: paymentschart 按服务把你的 service.peers 与生成的 service.contractPeers 合并:你的条目取代生成的同一服务的条目,你的文件没有列出的生成的对端保留下来,因为 Helm 会整个替换一个列表。你的文件列出、契约没有列出的对端会被加上。chart 随后给节点设置 wow.peer.dns.namespaces.eshop-payment-service: payments,节点便到 _internal._tcp.eshop-payment-service-cluster.payments.svc 查找对端,内部策略也放行来自那个命名空间的对端 Pod。对端自己的内部策略也须放行本服务的 Pod:在它的 networkPolicy.internal.from 中加一个带 namespaceSelector 的条目。
不再答复的对端节点
无声消失的节点,例如被强制删除的 Pod 或宕掉的机器,它的地址可能只丢包、不回复位,而它还留在节点缓存 30 秒的 SRV 记录里。走到它的连接上的请求得不到答复:命令或调用到它的等待加一段宽限、查询到 wow.peer.timeout 时结束,结果是 wow.command.unknown、wow.query.timeout 或 wow.peer.unavailable。命令绝不会再发给这个节点:它最多以同一个请求 ID 再发一次,而且只发给该上下文的另一个仍在答复的节点,由它转给分区的属主,于是命令的结果以重复或提交了结;没有别的仍在答复的节点时,它只失败一次,结果是 wow.command.unknown。查询或 Saga 的调用不会被重发。在时限之内没能建立的连接(地址在连接建立之前而不是之后丢包)什么也没发出:请求像遇到被拒绝的连接那样转到下一个节点,最多比时限晚一秒,这个节点也不会被绕过。
之后节点的客户端会绕开这个节点:发往该上下文同一端口的后续请求改发给它的其他节点。Saga 的调用和服务模式客户端的命令、查询都发往对端的内部端口,所以它们共用这一点:一个没得到答复的查询,也会让调用绕开这个节点。用户模式客户端的请求发往对端的公开端口,那是另一份名单,各自结算:这个节点在那里答不答复,要由那个端口自己的请求来证明。所以消失的节点只让一个请求付出时限,而不是在记录重新读取之前轮到它的每个请求。这个节点在以下情况回来:
- 它答复了一个仍在途中的请求,不论答复什么;
- 记录重新读取后仍列着它:它重新接收请求,若仍不答复,就再让一个请求付出时限,并再次被绕开;
- 记录重新读取后不再列着它:它被移除;
- 没有任何东西重新读取记录时(例如固定的
url,或不给出查找代次的发现方式),过了记录的保留时长 30 秒。
只是接受了连接不会让它回来:一个接受连接却从不答复的节点也能通过这种判断。一个上下文的所有节点都被绕开时,请求照旧发往全部节点,就像没有绕开一样:请求绝不会因此不发。
它不是健康检查:不发任何探测,答复慢但在时限内的节点也绝不会被绕开。每次绕开和每次回归都由 me.ahoo.wow.client.SilentPeers 记一行日志,写明被绕开多久,并计入 wow.peer.bypass.notices(可观测性)。
每个可用区都有集群的 DNS
节点解析的每个名字都经过集群的 DNS:它的存储、Kafka broker、对端的 SRV 记录,以及网关到各服务的路由。让 DNS 在每个可用区运行,每个可用区至少一个副本,而且是必须,不只是倾向。在 topology.kubernetes.io/zone 上加一个 whenUnsatisfiable: DoNotSchedule 的拓扑分布约束即可做到。在一个三可用区的集群里,CoreDNS 的两个副本恰好落在同一个可用区;失去这个可用区之后,各服务有 256 秒互相解析不到,而每个 Wow 节点本身都是健康的:
- CoSec 网关对解析不到服务的调用答 500("Failed to resolve"),入口随之答 502;
- 这段时间里启动的 Wow 节点会退出,因为它的 Kafka 客户端找不到可以起步的地址("No resolvable bootstrap urls given in bootstrap.servers")。它被反复重启,直到名字重新能解析。
# CoreDNS,每个可用区一个副本:kubectl -n kube-system patch deployment coredns --type merge -p "$(cat this-file)"
spec:
replicas: 3
template:
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
k8s-app: kube-dns
# 只计这个 ReplicaSet 的 Pod,滚动时旧的 Pod 不会占满某个可用区。
matchLabelKeys: [pod-template-hash]探针
宿主把节点的健康状况交给 Spring Boot Actuator 的就绪与存活分组,在 HTTP 端口上:
startupProbe:
httpGet:
path: /actuator/health/readiness
port: http
periodSeconds: {{ .Values.probes.startup.periodSeconds }}
failureThreshold: {{ .Values.probes.startup.failureThreshold }}
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: http
periodSeconds: {{ .Values.probes.readiness.periodSeconds }}
failureThreshold: {{ .Values.probes.readiness.failureThreshold }}
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: http
periodSeconds: {{ .Values.probes.liveness.periodSeconds }}
failureThreshold: {{ .Values.probes.liveness.failureThreshold }}就绪检查在节点无法提供服务时失败:节点运行之前;它的日志、写入所需的存储(某个类型自己的快照存储)或租约存储宕机时;交接宽限期过后它仍不拥有自己应得的分区时;或者它读取的某个主题仍在加入时。存活检查只在节点卡住或遇到致命错误时失败(致命错误),从不因存储宕机而失败,排空期间也不会失败,所以一次宕机不会让所有 Pod 同时重启。启动探针给节点三分钟启动(probes.startup)。它不再是结束一次卡住的启动的唯一手段:调和在 wow.health.liveness.stall-timeout 内没有完成任何一步的启动中节点,存活检查也会失败(部署模型)。
优雅关闭
Kubernetes 停止一个 Pod 时,节点先完成仍未结束的等待,然后在进行中的命令完成后交出它的分区,保存检查点,最后关闭内部端口。宽限期必须覆盖这一切,所以 chart 用它交给节点的同一组 value 推导宽限期:
# The node's shutdown: the grace period is the preStop pause, the public server's longest wait, the node's stop bound
# from these values and the margin, one after the other; the chart sets wow.wait.max-timeout, wow.cluster.drain-timeout
# and wow.subscription.stop-timeout from them.
shutdown:
# Time for the endpoints to drop the pod before Spring Boot stops taking requests.
preStopSeconds: 5
# The longest wait the public server finishes before it stops (wow.wait.max-timeout); at least
# wow.wait.default-timeout (10 s unless set), or the node does not start.
waitMaxTimeoutSeconds: 60
# How long a hand-off waits for its partition's commands in flight (wow.cluster.drain-timeout).
drainTimeoutSeconds: 10
# How long a subscription's stop waits for its entries in flight (wow.subscription.stop-timeout).
subscriptionStopTimeoutSeconds: 10
# Room for the checkpoints to be saved and the JVM to exit.
marginSeconds: 15宽限期按关闭的各个步骤依次相加:preStop 停顿;公开服务器的优雅关闭,持续到它最长的请求(一次等待,waitMaxTimeout)结束,再多 2 秒后服务器会切断仍未结束的请求;节点的停止,最长为它的停止上限;以及余量,它也覆盖这 2 秒和服务器的关闭(最多 3 秒)。默认是 5 + 60 + 90 + 15 = 170 秒。停止上限是 max(waitMaxTimeout, 2 × subscriptionStopTimeout + drainTimeout) + 3 × drainTimeout,默认 90 秒,与 ServiceNodeOptions.stopBound 及宿主关闭阶段的公式相同(启动与停止)。它的等待从节点自己的停止开始计算,因此排在公开服务器的等待之后。chart 用这些 value 设置 wow.wait.max-timeout、wow.cluster.drain-timeout 和 wow.subscription.stop-timeout;在 config、settings 或 env 中设置其中任何一个都会被拒绝,每个键都按 Spring 的宽松绑定来读;chart 自己设置的端口和节点身份也一样(server.port、wow.internal.port、wow.internal.host、wow.node.id、wow.peer.dns.namespace,以及 env 中 Pod 的 POD_NAME 和 POD_IP)。你的 envFrom 中的 Secret 或 ConfigMap 里的键 chart 看不到:不要把这些键放进去。preStop 的短暂停顿让 endpoints 有时间摘掉 Pod,然后 Spring Boot 才停止接收请求。
伸缩
增加副本,分区就分散到更多节点;减少副本,分区就重新集中。成员加入或离开时,租约在节点之间迁移分区,每次大约迁移 N 分之一。迁移是有代价的:
- 交接。 离开的属主在
wow.cluster.drain-timeout内完成该分区进行中的命令,并保存其订阅的检查点。在此期间,它那些聚合的命令要么等待,要么在收到命令的节点上执行(部署模型)。 - 订阅在新属主上从检查点继续,所以处理函数可能再次见到它在上一个检查点之后处理过的内容。
- 新属主的状态缓存是冷的:每个聚合在那里的第一条命令要加载它的快照和之后的日志。
所以要依据持续的信号伸缩,并且要慢。超出分区数(默认 64)的节点不拥有任何分区,这也是分区数要预先选定的原因之一:副本数上限要低于它。值得依据的信号:
| 信号 | 含义 |
|---|---|
| CPU | 命令与查询的工作量,适用于处理函数做计算的服务 |
wow.subscription.backlog | 订阅落后于日志:投影、Saga、Sink |
wow.command.duration | 命令的延迟,前提是存储能及时应答 |
autoscaling.hpa 创建一个按 CPU(以及你自己的指标)伸缩的 HorizontalPodAutoscaler:
# A HorizontalPodAutoscaler on CPU, and metrics of your own. Exclusive with keda.
hpa:
enabled: false
minReplicas: 2
maxReplicas: 8
cpuUtilization: 70
metrics: []
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Pods
value: 1
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 600
policies:
- type: Pods
value: 1
periodSeconds: 300它的行为是每分钟至多增加一个节点,安静十分钟后每五分钟至多减少一个,免得一阵突发让分区来回迁移。装了 KEDA 时,autoscaling.keda 改为经 Prometheus 按积压伸缩;两者互斥。它的 minReplicas 至少是 1,和 HPA 的一样:积压是服务自己的 Pod 上报的序列,服务缩到零个节点时就没有积压可以据此扩容,schema 拒绝 0:
# A KEDA ScaledObject on the subscriptions' backlog, through Prometheus; needs KEDA installed. Exclusive with hpa.
keda:
enabled: false
# At least 1, as the HPA's: the only trigger is the backlog the service's own pods report, so nothing would scale
# the service up from zero.
minReplicas: 2
maxReplicas: 8
pollingInterval: 30
cooldownPeriod: 300
prometheus:
serverAddress: ""
# sum(wow_subscription_backlog{namespace="<namespace>", pod=~"<name>-.*"}) when empty.
query: ""
# The backlog per node above which a node is added.
threshold: 1000
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Pods
value: 1
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 600
policies:
- type: Pods
value: 1
periodSeconds: 300chart 两者都不要求:默认都关闭,此时副本数就是 replicas。
监控
节点的 span 与指标经 OpenTelemetry Java agent 输出(可观测性),由它经 OTLP 推送(eShop 的 values 就是这样设置的),或者在一个 Prometheus 端点上提供指标(OTEL_METRICS_EXPORTER=prometheus,端口 9464)。对 Prometheus Operator,chart 在该端点上加一个 ServiceMonitor 或 PodMonitor:
# Where Prometheus scrapes a node. The OpenTelemetry Java agent's Prometheus exporter (OTEL_METRICS_EXPORTER=prometheus,
# port 9464, /metrics) is a port of its own, admitted from networkPolicy.metrics.from alone: the scraper reaches the
# meters and nothing else. Actuator's endpoint on the HTTP port (port: the HTTP port, path: /actuator/prometheus) is on
# the public port: with the NetworkPolicies on, the scraper is admitted there only through networkPolicy.public.from,
# which admits it to the service's API too, and the public port believes the CoSec-Identity of whatever reaches it.
metrics:
port: 9464
path: /metrics
serviceMonitor:
enabled: false
interval: 30s
# The monitor's own labels, beside the chart's (release: kube-prometheus-stack, say, for the Prometheus that picks
# it). None of the chart's: they are refused.
labels: {}
podMonitor:
enabled: false
interval: 30s
# As serviceMonitor.labels.
labels: {}把指标放在 agent 的端口上。独立的指标端口会在 Pod 上打开,并由 <name>-public 只按 networkPolicy.metrics.from(默认是 Prometheus 的 Pod)放行:抓取方只能访问指标,别的都访问不到。监控对象读的是 agent 的 Prometheus exporter,它要设置 OTEL_METRICS_EXPORTER=prometheus 才会打开:eShop 的 values 用的是 OTLP 推送,所以启用监控对象之前,先在 config 里设置它。
指标放在 HTTP 端口上(metrics.port 等于 ports.http)且开启了网络策略时,抓取方只能经 networkPolicy.public.from 放行,而这同时把服务的 API 也向它放行:公开端口相信到达它的任何 CoSec-Identity。chart 渲染这种配置时,它的说明会指出这一点;要清楚后果再选它。
给监控对象加上你的 Prometheus 所选择的标签(labels)。要对什么告警,见可观测性。
中断预算
自愿中断(排空一个节点、升级集群)一次带走一个节点:离开的节点交出它的分区,其他节点经租约接管之后,下一个才离开。chart 的 PodDisruptionBudget 就是这样规定的,并把节点分散到各可用区和主机:
podDisruptionBudget:
enabled: true
# Or minAvailable, which wins when given.
maxUnavailable: 1
# AlwaysAllow lets a drain evict a node that is not ready, which a budget would otherwise hold.
unhealthyPodEvictionPolicy: AlwaysAllow
topologySpread:
enabled: true
maxSkew: 1
whenUnsatisfiable: ScheduleAnywayAlwaysAllow 让排空可以驱逐未就绪的节点,否则中断预算会一直挡住它。优先用 maxUnavailable 而不是 minAvailable:两个副本时,minAvailable: 2 会挡住每一次排空。
升级
chart 的版本就是 Wow 的版本,它的 appVersion 是镜像的默认 tag。把服务依赖的 Wow 和 chart 一起升级,然后:
helm upgrade eshop-ordering oci://ghcr.io/ahoo-wang/wow-service --version <new-wow-version> \
-f examples/eshop/ordering/ordering-server/build/wow/helm/values.yaml \
-f deploy/eshop-ordering/values.yaml --wait滚动更新一次替换一个节点,新节点就绪之后旧节点才离开,所以有一段时间两个版本并存:升级说明哪些可以并存,以及哪些设置永远不能改,日志的分区数就是其中之一。只改共用的设置也会滚动节点:Pod 带着 ConfigMap 的校验和。每次构建都重新生成构建的 values:代码里新增的对端随即被策略放行、被节点找到。
在保留的存储上重新安装
在保留下来的存储上卸载并重新安装一个 release 时,要等旧节点都离开之后,再启动新节点。helm uninstall --wait 在 release 的对象删除之后就返回,而它的 Pod 仍在优雅停止。这时就重新安装,会让两代节点同时运行在一个存储上;升级自身的滚动从不这样做:新节点只经由旧节点交出的租约加入。先等 Pod 全部消失:
helm uninstall eshop-ordering --wait
kubectl wait --for=delete pod -l app.kubernetes.io/instance=eshop-ordering --timeout=10m配合 Kustomize
服务有两种部署方式,都出自同一个 chart、同一份 values:
- 用 Helm 安装 chart,即上文所述:从 OCI 仓库
helm install、helm upgrade。适合运行 Helm 的平台:它的 release、release 的历史与回滚、总 chart。 - 构建渲染的 base 加一个 overlay:服务的构建用它生成的 values 和部署自己的 values,渲染插件自带的、与插件同版本的 chart,得到一个纯 YAML 的 Kustomize base;overlay 修改 chart 不派生的部分,用
kubectl apply -k应用。适合应用纯清单的部署,无论是手工应用,还是由读取 kustomization 的 GitOps 工具应用,运维方都不需要 Helm。
两种方式下对象都是 chart 的对象,所以凡是参与派生的值仍由 chart 的 schema 检查,安装 chart 的部署什么也不用改。GA 端到端测试每晚用第二种方式部署 eShop 的 basket(.github/ga-e2e/cluster.sh),与其他服务的 release 并列。本节以 basket 为例。
在服务器的构建中写明部署的 values 文件和命名空间。basket 的:
wow {
kubernetes {
values.from(rootProject.file("deploy/eshop-basket/values.yaml"))
values.from(
providers.gradleProperty("eshop.kubernetes.values").map { paths ->
paths.split(',').map(String::trim).filter(String::isNotEmpty).map(rootProject::file)
}.orElse(emptyList()),
)
namespace = providers.gradleProperty("eshop.kubernetes.namespace").orElse("eshop")
}
}generateWowKubernetes 负责渲染,一旦 values 写了文件,它就属于 assemble。这些 values 文件排在构建自己生成的(generateWowHelmValues)之后,后一个覆盖前一个,与 -f 参数一样。它写出 build/wow/k8s/:
build/wow/k8s/
├── kustomization.yaml 这些对象,以及渲染时所用的命名空间
├── configmap-eshop-basket-service-config.yaml
├── deployment-eshop-basket-service.yaml
├── networkpolicy-eshop-basket-service-internal.yaml
├── networkpolicy-eshop-basket-service-public.yaml
├── poddisruptionbudget-eshop-basket-service.yaml
├── service-eshop-basket-service-cluster.yaml
├── service-eshop-basket-service.yaml
└── serviceaccount-eshop-basket-service.yaml这个任务可以缓存:相同的 values、命名空间和 Wow 版本,在每台机器上渲染出相同的 base。构建无法渲染时会这样说:
| 错误 | 构建的输出 |
|---|---|
| 没有写 values | generateWowKubernetes renders the wow-service chart with the deployment's values, which the build names: wow { kubernetes { values.from("deploy/<service>/values.yaml") } }. |
| 没有命名空间 | generateWowKubernetes renders the service for the namespace it is deployed to, which the chart derives from (…): set wow { kubernetes { namespace = "<namespace>" } }. |
| values 文件不存在 | wow { kubernetes { values.from(…) } } names "…/deploy/eshop-basket/valeus.yaml", which does not exist: correct the path in values.from(…), or remove it. |
| schema 拒绝的值 | Helm refused to render the wow-service chart:,后面是 chart 自己的消息,例如 additional properties 'replicaz' not allowed |
生产环境的 overlay 修改镜像、副本数和一项限额:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../../examples/eshop/basket/basket-server/build/wow/k8s
images:
- name: wow-eshop-basket-server
newName: registry.example.com/eshop-basket
newTag: 1.4.2
replicas:
- name: eshop-basket-service
count: 3
patches:
- target:
kind: Deployment
name: eshop-basket-service
patch: |-
- op: replace
path: /spec/template/spec/containers/0/resources/limits/memory
value: 2Gi./gradlew :eshop-basket-server:assemble
kubectl apply -k deploy/eshop-basket/prod写进 values 还是补丁
参与派生的值写进 values 文件:chart 把它一次变成多个对象,并由 schema 检查。它们是:
- 命名空间,
kubernetes { namespace }; - 对端的命名空间,
service.peers[].namespace(其他命名空间的对端); partOf,它给 Pod 打标签,并让内部端口的网络策略放行平台;- 网关规则
networkPolicy.public.from与onlyGateway,CoSec 的声明随之而定; - 监控
metrics及其策略规则; - 自动伸缩
hpa或keda; - 停机时限
shutdown.*,宽限期是它们之和(优雅关闭); - 端口,Service、网络策略、探针和节点自己的设置共用它们。
其余的归 overlay:镜像、副本数、资源、额外的环境变量、标签与注解。除了 API server,没有任何东西检查补丁:只在一个对象里改了端口而其他对象没改,也会照写,探针在运行时失败。
overlay 不能把 base 挪到另一个命名空间。 chart 由命名空间派生(对端是否在另一个命名空间、自动伸缩的查询),被 overlay 的 namespace: 挪走的 base 会出错而不报任何错误。命名空间或上面列表中其他值不同的环境,要单独渲染一次:basket 的构建从属性读取这两者,GA 端到端测试就这样为它的集群渲染:
./gradlew :eshop-basket-server:generateWowKubernetes -Peshop.kubernetes.namespace=default \
-Peshop.kubernetes.values=.github/ga-e2e/services/values.yaml由构建获取的 Helm
运维方只需要 kubectl;构建用插件固定的 Helm v4.3.1 渲染。它在 generateWowKubernetes 运行时获取,构建配置时从不获取,来源是 https://get.helm.sh,存入 Gradle 用户目录(wow/helm/v4.3.1/<os>-<arch>/),每台机器一次。不论由谁提供,压缩包的 SHA-256 与插件持有的不符即被拒绝。插件为 Linux、macOS 和 Windows 的 amd64 与 arm64 获取它。两个 Gradle 属性(写在用户目录的 gradle.properties 中,或用 -P)改变它的来源:
| 属性 | 含义 |
|---|---|
wow.helm.mirror | https://get.helm.sh 的镜像,布局相同;压缩包仍对照插件的摘要检查 |
wow.helm.executable | 本机上的 Helm,只有恰好是 v4.3.1 才会使用;其他平台的构建设置它 |
PATH 上的 Helm 从不使用,所以 base 不依赖于机器。离线时,构建使用之前获取的二进制,没有则失败并指出这两个属性。
每次升级 Wow 都重新渲染:chart 是插件的,版本即插件的版本。
先用 Helm 渲染,再叠加 overlay
保留 Helm 用于渲染、但不用它应用的部署,用构建的 values 和自己的 values 渲染 OCI 仓库中的 chart,再把 overlay 叠加在输出上:
helm template eshop-ordering oci://ghcr.io/ahoo-wang/wow-service --version <wow-version> --namespace shop \
-f examples/eshop/ordering/ordering-server/build/wow/helm/values.yaml \
-f deploy/eshop-ordering/values.yaml > base/eshop-ordering.yaml把 eshop-ordering.yaml 列入 base/kustomization.yaml 的 resources,把它的 namespace: 设为渲染时所用的命名空间,每次升级、每次构建出新的 values 时重新渲染。哪些写进 values、哪些写进 overlay 与上文相同,命名空间也一样:overlay 不挪动它。
在总 chart 中
平台的 chart 为每个服务各引用一次本 chart,各用一个别名,每个服务的 values 写在它的别名下:
dependencies:
- name: wow-service
version: <wow-version>
repository: oci://ghcr.io/ahoo-wang
alias: ordering
- name: wow-service
version: <wow-version>
repository: oci://ghcr.io/ahoo-wang
alias: basketschema 接受总 chart 的 global values,本 chart 不读取它们。