最新文章

Kubernetes 源码解析 - HPA 水平自动伸缩如何工作

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实例。

翻译:多运行时微服务架构

翻译:多运行时微服务架构

这样文章通过Google翻译和人工逐字修改的方式完成的,某些位置也加上自己的理解。如有错误,请指出。

翻译这篇文章的目的其实是为了自己加深对微服务、分布式架构以及多运行时架构的理解。整篇文章从”战略“上分析了微服务”从古至今“解决的问题,以 …