使用 Kubernetes Python 客户端操作 V1PodAntiAffinity:Pod 反亲和调度规则模型全解

原创2026-10-10 23:31:431,710 阅读
文章标签:云原生容器编排集群管理后端

使用 Kubernetes Python 客户端操作 V1PodAntiAffinity:Pod 反亲和调度规则模型全解

本文聚焦 Kubernetes 官方 Python 客户端库(本仓库 kubernetes 与 kubernetes.aio 两个实现)中 V1PodAntiAffinity 模型的完整 API:字段语义、取值约束、与 V1PodAffinityTerm、V1WeightedPodAffinityTerm、V1LabelSelector 的组装关系,以及序列化、反序列化与校验行为。读完本文,你将能在 V1PodSpec 的 affinity.podAntiAffinity 字段上准确构造“必须隔离/尽量隔离”两类 Pod 反亲和规则,并理解 wire(camelCase)与 Python(snake_case)两种命名之间的转换机制。

关联文档与模型定位

关联文档 doc/source/kubernetes.aio.client.models.v1_pod_anti_affinity.rst 是 Sphinx 的 automodule 指令页,它自动导入并渲染 kubernetes/aio/client/models/v1_pod_anti_affinity.py 模块的全部公开成员。因此,该文档实际承载的技术内容就是 V1PodAntiAffinity(pydantic BaseModel)的类定义与成员说明。同步存在非异步版本 kubernetes/client/models/v1_pod_anti_affinity.py,两者的字段与行为完全一致,仅 import 路径不同,异步版使用 from kubernetes.aio.client.models... 前缀。本仓库代码基于 OpenAPI Generator 由 Kubernetes release-1.37 的 OpenAPI 定义生成,因此下述字段对应 Kubernetes v1.37 API 的 PodAntiAffinity 结构。

V1PodAntiAffinity 在模型体系中的位置(从源码可确认的引用链):

  • V1Affinity 持有 pod_anti_affinity: Optional<a href="https://link.gitcode.com/i/b95e3c201beac2569fd676f07b7a2d0b" target="_blank">V1PodAntiAffinity] 字段(见 [v1_affinity.py),与 node_affinity、pod_affinity 并列;
  • V1PodSpec 持有 affinity: Optional<a href="https://link.gitcode.com/i/f0eae8761e35ccb1ab51a4ddd9ae226a" target="_blank">V1Affinity] 字段(见 [v1_pod_spec.py)。

即最终构造路径为 V1PodSpec(affinity=V1Affinity(pod_anti_affinity=...)),它是 Pod 调度规格(PodSpec)的一部分。

类签名与核心语义

V1PodAntiAffinity 的类 docstring 定义如下(源码 v1_pod_anti_affinity.py):

Pod anti affinity is a group of inter pod anti affinity scheduling rules.

它描述“一组 Pod 间反亲和调度规则”,其核心语义是:让当前 Pod 尽量不与 某些已存在的 Pod 落在同一拓扑域(如同一节点、同一可用区)中,用于实现高可用打散、故障域隔离、资源争用规避等场景。

类结构概览(异步版与同步版一致):

成员 类型 是否必填 说明
preferred_during_scheduling_ignored_during_execution Optional[List[V1WeightedPodAffinityTerm]] 否 软性反亲和(preferred),调度时按权重优选,可被打破
required_during_scheduling_ignored_during_execution Optional[List[V1PodAffinityTerm]] 否 硬性反亲和(required),调度时不满足则 Pod 不调度

两个字段均默认 None,模型通过 openapi_types 记录元素类型为 List[V1WeightedPodAffinityTerm] 与 List[V1PodAffinityTerm]。

字段逐一详解

required_during_scheduling_ignored_during_execution(硬性反亲和)

源码字段描述(见 v1_pod_anti_affinity.py):

  • 调度时刻,若该字段指定的反亲和需求未得到满足,Pod 不会被调度到该节点;
  • 运行期间,若反亲和需求不再满足(例如某个已存在 Pod 的 label 发生变化),系统可能、也可能不会尝试将 Pod 从所在节点驱逐("ignored during execution");
  • 当存在多个元素时,各 podAffinityTerm 对应的满足节点列表做交集,即所有 term 必须同时满足。

典型用途:强制将同一应用的多个副本分散到不同节点,或强制将相互冲突的工作负载(如占满端口的实例)分开。

preferred_during_scheduling_ignored_during_execution(软性反亲和)

源码字段描述(见 v1_pod_anti_affinity.py):

  • 调度器倾向于把 Pod 调度到满足反亲和表达式的节点,但允许打破其中一条或多条表达式;
  • 计分方式:对每个满足基本调度要求(资源请求、硬性反亲和表达式等)的节点,遍历该字段中的每个元素,若节点上存在与对应 podAffinityTerm 匹配的 Pod,则从总分中减去该元素的 weight;总分最高的节点最受青睐。

注意与亲和版本(V1PodAffinity)的差别:在 v1_pod_affinity.py 中,匹配 term 时是“加上 weight”,而反亲和是“减去 weight”。两者计分方向相反,这正是反亲和“避开”的体现。

典型用途:尽量将批处理任务与高优先级服务打散,但资源紧张时允许共存。

支撑模型:V1PodAffinityTerm 与 V1WeightedPodAffinityTerm

两个字段的元素类型分别是 V1PodAffinityTerm 和 V1WeightedPodAffinityTerm,定义于 v1_pod_affinity_term.py 与 v1_weighted_pod_affinity_term.py。

V1PodAffinityTerm:描述“与哪些 Pod 互斥”

该类 docstring 指出:它定义一组 Pod(即匹配 labelSelector、且位于指定 namespace(s) 中的 Pod),当前 Pod 与这组 Pod 应共置(affinity)或不应共置(anti-affinity),其中“共置”定义为:运行在某个节点上,该节点上 topologyKey 标签的值与目标 Pod 所在节点的该标签值相同。

字段清单(异步版 v1_pod_affinity_term.py):

字段 类型 必填 语义要点
label_selector Optional[V1LabelSelector] 否 选择参与反亲和计算的目标 Pod 集合
match_label_keys Optional[List[str]] 否 从入站 Pod 的 labels 中取出指定 key 的 value,与 labelSelector 合并为 key in (value) 条件;入站 Pod 中不存在的 key 被忽略;默认空;同一 key 禁止同时出现在 matchLabelKeys 与 labelSelector 中;未设置 labelSelector 时不允许设置
mismatch_label_keys Optional[List[str]] 否 同上,但合并条件为 key notin (value);其余约束与 match_label_keys 一致
namespace_selector Optional[V1LabelSelector] 否 按标签选择目标 Pod 所在的 namespace
namespaces Optional[List[str]] 否 静态 namespace 名称列表;与 namespaceSelector 取并集;两者均为 null/空时表示“当前 Pod 所在 namespace”
topology_key StrictStr 是 拓扑域划分的 label key,如 kubernetes.io/hostname、topology.kubernetes.io/zone;空字符串不允许

其中 matchLabelKeys 与 mismatchLabelKeys 是较新的能力,允许基于入站 Pod 自身标签动态圈定目标 Pod 集合,实现滚动更新场景下的“新副本避开旧副本”等效果。

V1LabelSelector:目标 Pod 的筛选器

label_selector 与 namespace_selector 的类型均为 V1LabelSelector,其两个字段(v1_label_selector.py):

  • match_labels: Optional[Dict[str, str]]:{key, value} 映射,每条等价于一个 matchExpressions 元素(key 字段为 key,操作符为 In,values 仅含该 value);多条要求为 AND 关系;
  • match_expressions: Optional[List[V1LabelSelectorRequirement]]:选择器需求列表,多条为 AND 关系。

V1WeightedPodAffinityTerm:软性规则的权重

用于 preferred_during_scheduling_ignored_during_execution,定义于 v1_weighted_pod_affinity_term.py,包含两个必填字段:

字段 类型 约束
pod_affinity_term V1PodAffinityTerm 必填
weight StrictInt 关联 podAffinityTerm 的权重,取值区间 1–100(见源码 v1_weighted_pod_affinity_term.py)

调度器按节点累加所有匹配项的权重(反亲和为减分),从而找出最受偏好的节点。

在 V1PodSpec 中的完整组装

V1PodAntiAffinity 位于 Pod 规格的 affinity.podAntiAffinity 下。从 v1_pod_spec.py 与 v1_affinity.py 的字段引用可以确认该嵌套结构,构建顺序如下:

from kubernetes.client import V1PodSpec, V1Affinity, V1PodAntiAffinity, \
    V1PodAffinityTerm, V1WeightedPodAffinityTerm, V1LabelSelector

# 1) 定义目标 Pod 的筛选条件
selector = V1LabelSelector(match_labels={"app": "web"})

# 2) 定义反亲和 term:在 hostname 拓扑域上避免与 app=web 的 Pod 同节点
term = V1PodAffinityTerm(
    label_selector=selector,
    topology_key="kubernetes.io/hostname",
)

# 3) 硬性反亲和:必须打散
anti_affinity = V1PodAntiAffinity(
    required_during_scheduling_ignored_during_execution=[term],
    preferred_during_scheduling_ignored_during_execution=[
        V1WeightedPodAffinityTerm(pod_affinity_term=term, weight=100),
    ],
)

# 4) 挂载到 Affinity,再挂载到 PodSpec
pod_spec = V1PodSpec(
    affinity=V1Affinity(pod_anti_affinity=anti_affinity),
    containers=[...],  # 其他必填字段
)

对应到 Kubernetes YAML,上述结构等价于:

spec:
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchLabels:
              app: web
          topologyKey: kubernetes.io/hostname
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 100
          podAffinityTerm:
            labelSelector:
              matchLabels:
                app: web
            topologyKey: kubernetes.io/hostname

命名转换:snake_case 与 camelCase 的自动映射

Kubernetes API 使用 camelCase(wire 名称),而 Python 属性使用 snake_case。V1PodAntiAffinity 通过 pydantic 的 AliasChoices 与 validation_alias / serialization_alias 实现双向映射(见 v1_pod_anti_affinity.py),其 attribute_map 定义:

attribute_map = {
    "preferred_during_scheduling_ignored_during_execution": "preferredDuringSchedulingIgnoredDuringExecution",
    "required_during_scheduling_ignored_during_execution": "requiredDuringSchedulingIgnoredDuringExecution",
}

同时,__preprocess_input_names(v1_pod_anti_affinity.py)会在反序列化前把 snake_case 键归一化为 camelCase 键,意味着两种写法都能被 from_dict 接受。

V1PodAffinityTerm 与 V1WeightedPodAffinityTerm 同样遵循该机制(见 v1_pod_affinity_term.py 与 v1_weighted_pod_affinity_term.py),例如 pod_affinity_term ↔ podAffinityTerm、topology_key ↔ topologyKey、match_label_keys ↔ matchLabelKeys。

序列化与反序列化 API

V1PodAntiAffinity 继承自 pydantic BaseModel,并提供以下常用方法(源码 v1_pod_anti_affinity.py):

方法 用途
to_dict(serialize=False) 返回 Python 字典;serialize=True 时使用 camelCase wire 名称,并递归调用子模型(如 V1WeightedPodAffinityTerm.to_dict)转换列表元素
to_json() 返回 JSON 字符串,使用 alias(camelCase)输出
from_json(json_str) 从 JSON 字符串构造实例
from_dict(obj) 从字典构造实例;内部先做输入名归一化,再递归调用 V1WeightedPodAffinityTerm.from_dict / V1PodAffinityTerm.from_dict 转换列表元素
to_str() / __repr__ 返回 pprint 格式的可读字符串表示
__eq__ / __ne__ 基于 to_dict() 结果比较两个实例是否相等

此外,模型通过 model_config 设置了 validate_by_name=True、validate_by_alias=True、validate_assignment=True、extra="forbid"、protected_namespaces=()(v1_pod_anti_affinity.py):

  • validate_assignment=True:实例创建之后再对属性赋值也会触发类型校验;
  • extra="forbid":传入未知字段会直接报错,保证与 OpenAPI schema 严格对齐;
  • 同时接受按属性名或按 alias 传参。

因此,构造时传入未定义的字段(如拼写错误的 requiredDuringScheduling)会被 pydantic 拒绝,这能提前暴露 YAML/字典与模型定义不一致的问题。

典型实战场景与注意事项

基于上述语义,V1PodAntiAffinity 常见的实战用法包括:

  1. 多副本高可用打散:StatefulSet/Deployment 副本间用 requiredDuringSchedulingIgnoredDuringExecution + topologyKey: kubernetes.io/hostname,确保同一工作负载副本不落在同一节点;进一步可用 topology.kubernetes.io/zone 打散到可用区。
  2. 故障域隔离:不同可用区之间用 zone 级反亲和,规避单可用区故障。
  3. 软性避让:低优先级批处理任务用 preferred... + 较低 weight 避开高优先级服务节点,集群资源紧张时允许共存。
  4. 滚动更新错峰:借助 matchLabelKeys 基于入站 Pod 的标签(如版本号)动态选择旧副本,实现“新 Pod 避开旧 Pod”的滚动反亲和(参考 v1_pod_affinity_term.py 中 matchLabelKeys 的描述)。

使用注意事项(均为源码 docstring 或模型配置可确认的约束):

  • topologyKey 必填且不允许为空字符串(v1_pod_affinity_term.py);
  • weight 取值范围为 1–100(v1_weighted_pod_affinity_term.py);
  • 硬性反亲和多条 term 之间为交集关系,条件过强可能导致 Pod 无法调度,需配合节点/资源情况评估;
  • matchLabelKeys/mismatchLabelKeys 与 labelSelector 存在互斥约束,且依赖 labelSelector 已设置(v1_pod_affinity_term.py);
  • “IgnoredDuringExecution” 意味着运行期不满足规则时不会强制驱逐,只会影响后续调度决策。

结语

V1PodAntiAffinity 是 Kubernetes Python 客户端中表达 Pod 反亲和调度策略的模型入口,其两个字段分别对应硬性(required)与软性(preferred)两类语义,配合 V1PodAffinityTerm 的标签选择与 topologyKey 拓扑划分,可以精确控制工作负载在节点、可用区等维度上的分布。结合本仓库 kubernetes/client 与 kubernetes.aio 中同步生成的模型代码,你可以在构造 V1PodSpec 时以类型安全、可校验的方式落地这些调度规则。

登录后查看全文
python