Kubernetes Python 客户端 V1HorizontalPodAutoscalerStatus 模型详解:HPA 状态字段、序列化与 API 读取实战

原创2026-10-09 23:44:421,611 阅读
文章标签:云原生后端

Kubernetes Python 客户端 V1HorizontalPodAutoscalerStatus 模型详解:HPA 状态字段、序列化与 API 读取实战

本文围绕官方 Kubernetes Python 客户端(同步版 kubernetes.client 与异步版 kubernetes.aio.client)中的 V1HorizontalPodAutoscalerStatus 模型展开,完整讲解 HorizontalPodAutoscaler(HPA)status 子对象的五个核心字段、Pydantic 字段别名机制、JSON/字典双向序列化方法,并结合 autoscaling API 源码展示如何从集群读取真实 HPA 状态。读完本文,你将能准确理解 HPA 状态数据结构,并写出可运行的查询与解析代码。

一、模型在 HPA 对象中的位置

在 Kubernetes autoscaling/v1 API 中,一个 HorizontalPodAutoscaler 对象由三部分组成:spec(期望配置)、status(当前状态)与 metadata(元数据)。在仓库的 V1HorizontalPodAutoscaler 模型源码 中可以看到其完整字段构成:

字段 类型 必填
api_version str 可选
kind str 可选
metadata V1ObjectMeta 可选
spec V1HorizontalPodAutoscalerSpec 必填
status V1HorizontalPodAutoscalerStatus 可选

也就是说,status 是挂在 HPA 主对象下的可选子对象,由 API Server 根据 HPA 控制器的实际运行情况回填,客户端通常只负责读取。而 spec 则定义了伸缩的期望边界——相关定义见 V1HorizontalPodAutoscalerSpec 源码,包括 maxReplicas(必填,副本上限)、minReplicas(可选,默认 1)、scaleTargetRef(必填,被伸缩对象引用)以及 targetCPUUtilizationPercentage(可选,目标 CPU 利用率百分比)。

二、V1HorizontalPodAutoscalerStatus 的五个状态字段

V1HorizontalPodAutoscalerStatus 类的完整定义位于 同步版源码 与 异步版源码,两者字段与行为完全一致。其类注释为 "current status of a horizontal pod autoscaler",共包含 5 个字段,字段表如下:

字段(Python 属性名) 类型 必填性 对应 JSON 键
current_cpu_utilization_percentage int 可选 currentCPUUtilizationPercentage
current_replicas int 必填 currentReplicas
desired_replicas int 必填 desiredReplicas
last_scale_time datetime 可选 lastScaleTime
observed_generation int 可选 observedGeneration

2.1 current_cpu_utilization_percentage(可选)

当前所有 Pod 的平均 CPU 利用率,表示为请求 CPU 的百分比。例如值为 70 表示平均每个 Pod 当前使用了其请求 CPU 的 70%。当 HPA 未配置 CPU 指标或指标暂不可用时该字段可能为空(None)。

2.2 current_replicas(必填)

该自动伸缩器当前管理的 Pod 副本实际数量。这是状态对象中两个必填字段之一,只要 HPA 对象存在,API Server 就会回填该值。

2.3 desired_replicas(必填)

期望的 Pod 副本数量,由 HPA 控制器根据当前指标与目标值计算得出。它是判断"当前是否正在扩缩容"的关键依据:当 desired_replicas != current_replicas 时,说明伸缩仍在进行中。

2.4 last_scale_time(可选,datetime 类型)

最近一次 HPA 实际改变 Pod 副本数量的时间。该时间戳被控制器用来控制副本变更的最小间隔(即冷却/速控逻辑),避免频繁抖动。

2.5 observed_generation(可选)

该自动伸缩器观察到的最新 generation。通过对比 metadata.generation 与 observed_generation,可以判断控制器是否已处理完最近的配置变更——两者不一致通常意味着 HPA 还在收敛中。

三、字段别名机制:snake_case 与 camelCase 的无缝切换

Kubernetes API 的 wire 格式(JSON/YAML)使用驼峰命名(如 currentReplicas),而 Python 代码规范使用下划线命名(如 current_replicas)。本模型的源码通过 Pydantic 的 AliasChoices 同时支持两种输入形式:

current_replicas: StrictInt = Field(
    validation_alias=AliasChoices("currentReplicas", "current_replicas"),
    serialization_alias="currentReplicas",
    description="currentReplicas is the current number of replicas of pods managed by this autoscaler.",
)

这意味着:

  • 反序列化时(JSON/dict → 模型),无论收到 currentReplicas 还是 current_replicas,都能被正确识别;
  • 序列化时,统一输出为驼峰命名的 wire 键名(currentReplicas、lastScaleTime 等),保证与 API Server 交互时格式正确。

同时,模型的 ConfigDict 配置为 validate_by_name=True、validate_by_alias=True、validate_assignment=True、extra="forbid",即:属性赋值时也会触发校验,且传入未知字段会直接报错,避免拼错键名导致静默丢字段。

四、序列化与反序列化:from_json / to_json / from_dict / to_dict

仓库为每个模型统一生成了一套 JSON 与字典双向转换方法,V1HorizontalPodAutoscalerStatus 同样完整实现了它们(见 异步版源码):

方法 作用
from_json(json_str) 从 JSON 字符串创建模型实例
to_json() 输出使用驼峰别名的 JSON 字符串表示
from_dict(dict) 从字典创建模型实例(自动规范化 snake_case/camelCase 键名)
to_dict() 返回字段字典(默认用 Python 属性名,serialize=True 时用 wire 别名)
to_str() / __repr__ 格式化可读字符串表示
__eq__ / __ne__ 基于 to_dict() 结果做值比较

其中 from_dict 会先经过 __preprocess_input_names 将下划线键名规范化为驼峰键名,再交给 Pydantic 的 model_validate 完成类型校验与实例化。官方文档示例(见 kubernetes/docs/V1HorizontalPodAutoscalerStatus.md)展示了标准用法:

from kubernetes.aio.client.models.v1_horizontal_pod_autoscaler_status import V1HorizontalPodAutoscalerStatus

# 从 JSON 字符串创建实例
json_str = '{"currentReplicas": 3, "desiredReplicas": 5}'
status = V1HorizontalPodAutoscalerStatus.from_json(json_str)
print(status.desired_replicas)   # 5

# 序列化为 JSON 字符串
print(V1HorizontalPodAutoscalerStatus.to_json())

# 转 dict 后再从 dict 还原
status_dict = status.to_dict()
status_from_dict = V1HorizontalPodAutoscalerStatus.from_dict(status_dict)

注意:current_replicas 与 desired_replicas 是必填字段,构造实例时缺省会触发校验错误;其余三个字段允许省略。

五、从集群读取真实 HPA 状态的实战示例

HPA 状态不会凭空产生,需要通过 autoscaling API 从集群读取。以 autoscaling/v2 为例,仓库中 autoscaling_v2_api.py 提供了 list_namespaced_horizontal_pod_autoscaler(同步版)与 read_namespaced_horizontal_pod_autoscaler 等方法,其返回类型为 V2HorizontalPodAutoscalerList 或 V2HorizontalPodAutoscaler。

一个完整的查询示例:

from kubernetes import config
from kubernetes.client import AutoscalingV2Api

# 加载集群配置(集群内或 kubeconfig,见 examples/out_of_cluster_config.py)
config.load_kube_config()
api = AutoscalingV2Api()

# 列出 default 命名空间下的全部 HPA
hpa_list = api.list_namespaced_horizontal_pod_autoscaler(namespace="default")

for hpa in hpa_list.items:
    status = hpa.status            # V2HorizontalPodAutoscalerStatus / V1HorizontalPodAutoscalerStatus
    if status is None:
        print(f"{hpa.metadata.name}: 状态尚未生成")
        continue
    print(f"HPA: {hpa.metadata.name}")
    print(f"  当前副本数   : {status.current_replicas}")
    print(f"  期望副本数   : {status.desired_replicas}")
    print(f"  CPU 利用率 % : {status.current_cpu_utilization_percentage}")
    print(f"  上次扩容时间 : {status.last_scale_time}")
    print(f"  已观测代次   : {status.observed_generation}")

autoscaling/v1(AutoscalingV1Api)与 autoscaling/v2(AutoscalingV2Api)都实现了同一套 HPA 列表/读取接口,v2 是当前推荐版本,支持更丰富的指标维度;v1 的 V1HorizontalPodAutoscalerStatus 结构更精简,即本文核心对象。

异步(asyncio)用法

该模型同时存在于异步客户端中,异步版 API 位于 kubernetes/aio/client/api/autoscaling_v2_api.py,同样返回带有 V2HorizontalPodAutoscalerStatus 状态字段的模型对象:

import asyncio
from kubernetes import config
from kubernetes.aio.client import AutoscalingV2Api

async def main():
    await config.load_kube_config()          # 异步版配置加载
    async with AutoscalingV2Api() as api:    # 支持 async context manager
        hpa_list = await api.list_namespaced_horizontal_pod_autoscaler(namespace="default")
        for hpa in hpa_list.items:
            if hpa.status:
                print(hpa.metadata.name, hpa.status.desired_replicas)

asyncio.run(main())

六、调试与诊断技巧

结合状态字段可以在业务代码中实现 HPA 健康度巡检:

  1. 判断是否收敛:status.observed_generation < metadata.generation 说明控制器尚未处理最新配置;
  2. 判断是否扩容中:status.desired_replicas > status.current_replicas 表示正在扩容,反之正在缩容;
  3. 判断 CPU 指标状态:current_cpu_utilization_percentage is None 通常表示指标暂不可用(例如 Pod 尚无 CPU 采样),可据此告警;
  4. JSON 调试:使用 hpa.status.to_dict() 或 hpa.status.to_json() 快速输出可读结构,配合打印排查字段对齐问题(注意 to_dict() 默认输出 snake_case 键名)。

七、延伸阅读

以上字段定义、类型与行为均以当前仓库基于 Kubernetes OpenAPI release-1.37 生成的代码为准;若你使用的集群版本更旧(如 autoscaling/v1 早期实现),个别字段的必填性或语义可能略有差异,建议以目标集群实际的 API 返回为准。

登录后查看全文
python