Kubernetes 源码解析 - HPA 水平自动伸缩如何工作
HPA - Horizontal Pod Autoscaler 的缩写,Pod 水平自动伸缩。通过对 Pod 负载的监控,来自动增加或者减少 Pod 的副本数量。
从字面意思来看,其主要包含了两部分:
- 监控 Pod 的负载
- 控制 Pod 的副本数量
那具体是如何实现的呢?以下基于1.17 源码,来分析下 HPA 如何工作。
注意:文章中的代码在源码的基础上进行了精简:删掉了注释、序列化等信息,或保留了部分核心代码,加上新的注释。
资源
HPA 的资源是HorizontalPodAutoscaler,在v1版本中,只支持基于 CPU 指标的计算;在v2beta2版本中加入了基于内存和自定义指标的计算。
v1
//staging/src/k8s.io/api/autoscaling/v1/types.go
type HorizontalPodAutoscaler struct {
metav1.TypeMeta
metav1.ObjectMeta
Spec HorizontalPodAutoscalerSpec
Status HorizontalPodAutoscalerStatus
}
type HorizontalPodAutoscalerSpec struct {
ScaleTargetRef CrossVersionObjectReference //监控的目标资源
MinReplicas *int32 //最小副本数
MaxReplicas int32 //最大副本数
TargetCPUUtilizationPercentage *int32 //触发调整的CPU 使用率
}
v2
//staging/src/k8s.io/api/autoscaling/v2beta2/types.go
type HorizontalPodAutoscaler struct {
metav1.TypeMeta
metav1.ObjectMeta
Spec HorizontalPodAutoscalerSpec
Status HorizontalPodAutoscalerStatus
}
type HorizontalPodAutoscalerSpec struct {
ScaleTargetRef CrossVersionObjectReference //监控的目标资源
MinReplicas *int32
MaxReplicas int32
Metrics []MetricSpec //新加入的自定义指标
}
type MetricSpec struct {
Type MetricSourceType //指标源的类型:Object(基于某个对象)、Pods(基于pod 数)、Resource(基于资源使用计算,比如v1 版本中cpu)、External(基于外部的指标)。对应 MetricsClient 接口的四个方法
Object *ObjectMetricSource //对应 Object 类型的指标源
Pods *PodsMetricSource //对应 Pod 类型的指标源
Resource *ResourceMetricSource //对应 Resource 类型的指标源
External *ExternalMetricSource //对应 External 类型的指标源
}
type ObjectMetricSource struct {
DescribedObject CrossVersionObjectReference //目标对象
Target MetricTarget //指定指标的目标值、平均值或者平均使用率
Metric MetricIdentifier //指标标识:名字、label选择器
}
type PodsMetricSource struct {
Metric MetricIdentifier
Target MetricTarget
}
type ResourceMetricSource struct {
Name v1.ResourceName
Target MetricTarget
}
type ExternalMetricSource struct {
Metric MetricIdentifier
Target MetricTarget
}
type MetricTarget struct {
Type MetricTargetType //类型:Utilization、Value、AverageValue
Value *resource.Quantity
AverageValue *resource.Quantity
AverageUtilization *int32
}
控制器 HorizontalController
HorizontalController被通过 key horizontalpodautoscaling 加入到 controller manager 中。用来控制HorizontalPodAutoscaler实例。




