本章重点: 从源码角度分析hpa的计算逻辑
1. hpa介绍
1.1 hpa是什么
hpa指的是 Pod 水平自动扩缩,全名是Horizontal Pod Autoscaler简称HPA。它可以基于 CPU 利用率或其他指标自动扩缩 ReplicationController、Deployment 和 ReplicaSet 中的 Pod 数量。
用处: 用户可以通过设置hpa,实现deploy pod数量的自动扩缩容。比如流量大的时候,pod数量多一些。流量小的时候,Pod数量降下来,避免资源浪费。
1.2 hpa如何用起来
(1)需要一个deploy/svc等,可以参考社区
(2)需要对应的hpa
举例:
(1) 创建1个deploy。这里只有1个副本
apiVersion: apps/v1 kind: Deployment metadata: labels: app: zx-hpa-test name: zx-hpa spec: strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 replicas: 2 selector: matchLabels: app: zx-hpa-test template: metadata: labels: app: zx-hpa-test name: zx-hpa-test spec: terminationGracePeriodSeconds: 5 containers: - name: busybox image: busybox:latest imagePullPolicy: IfNotPresent command: - sleep - "3600"
(2)创建对应的hpa。
apiVersion: autoscaling/v2beta1 kind: HorizontalPodAutoscaler metadata: name: nginx-hpa-zx-1 annotations: metric-containerName: zx-hpa spec: scaleTargetRef: apiVersion: apps/v1 // 这里必须指定需要监控那个对象 kind: Deployment name: zx-hpa minReplicas: 1 // deploy最小的Pod数量 maxReplicas: 3 // deploy最大的Pod数量 metrics: - type: Pods pods: metricName: pod_cpu_1m targetAverageValue: 60
hpa是从同命名空间下,找对应的deploy。所以yaml中指定deploy的时候不要指定namespaces。这也就要求,hpa 和deploy必须在同一命名空间。
这里我使用的 pod_cpu_1m这个指标。这是一个自定义指标。接下来就是分析
创建好之后,观察hpa,当deploy的cpu利用率变化时,deploy的副本会随之改变。
2. hpa 源码分析
2.1 启动参数介绍
hpa controller随controller manager的初始化而启动,hpa controller将以下flag添加到controller manager的flag中,通过controller manager的CLI端暴露给用户:
// AddFlags adds flags related to HPAController for controller manager to the specified FlagSet. func (o *HPAControllerOptions) AddFlags(fs *pflag.FlagSet) { if o == nil { return } fs.DurationVar(&o.HorizontalPodAutoscalerSyncPeriod.Duration, "horizontal-pod-autoscaler-sync-period", o.HorizontalPodAutoscalerSyncPeriod.Duration, "The period for syncing the number of pods in horizontal pod autoscaler.") fs.DurationVar(&o.HorizontalPodAutoscalerUpscaleForbiddenWindow.Duration, "horizontal-pod-autoscaler-upscale-delay", o.HorizontalPodAutoscalerUpscaleForbiddenWindow.Duration, "The period since last upscale, before another upscale can be performed in horizontal pod autoscaler.") fs.MarkDeprecated("horizontal-pod-autoscaler-upscale-delay", "This flag is currently no-op and will be deleted.") fs.DurationVar(&o.HorizontalPodAutosc