【云原生•监控】基于prometheus实现自定义指标弹性伸缩(hpa)
什么是弹性伸缩
「autoscaling即弹性伸缩,是kubernetes中的一种非常核心的功能,它可以根据给定的指标(例如 cpu 或内存)自动缩放pod副本,从而可以更好地管理和利用计算资源,提高系统的可用性和性能,同时减少开销和成本。弹性伸缩可以解决服务负载存在较大波动或资源实际使用与预估之间的差距。」
在kubernetes集群中提供了三种弹性伸缩技术:
「ca(cluster autoscaler)」:node级别自动扩/缩容
「hpa(horizontal pod autoscaler)」:pod个数自动扩/缩容
「vpa(vertical pod autoscaler)」:pod配置自动扩/缩容,主要是cpu、内存配置
「node自动扩/缩容」
cluster autoscaler定期检测是否有充足的资源来调度新创建的pod,当资源不足时会调用cloud provider创建新的node。cluster autoscaler也会定期监测 node的资源使用情况,当一个node长时间资源利用率都很低时(低于50%)自动将其所在虚拟机从集群中删除。此时,原来的pod会自动调度到其他node上面。
node的增减可能会影响整个kubernetes集群的稳定性,一旦出现问题会影响整个集群上部署的所有业务程序,所以,生产中针对node节点的扩缩容一般还是谨慎使用,当确实需要对node进行扩缩容时,往往通过人工执行脚本完成。
「pod的垂直扩/缩容(vpa)」
vpa全称vertical pod autoscaler,即pod的垂直自动伸缩,它根据容器资源使用率自动设置cpu和内存的requests,从而允许在节点上进行适当的调度,以便为每个pod提供适当的资源。它既可以缩小过度请求资源的容器,也可以根据其使用情况随时提升资源不足的容量。
「目前,vpa技术成熟度还不够,是kubernetes比较新的功能,更新正在运行的pod资源配置是vpa的一项试验性功能,会导致pod的重建和重启,而且有可能被调度到其他的节点上。」
「pod的水平扩/缩容(hpa)」
hpa全称horizontal pod autoscaler,即pod的水平自动伸缩,根据资源利用率或者自定义指标自动调整pod的副本数,实现pod的扩容、缩容,让部署的规模接近于实际服务的负载。
hpa弹性伸缩原理
horizontal pod autoscaler
功能最初是在kubernetes 1.1
中引入并不断发展,目前hpa
已经支持了autoscaling/v1
、autoscaling/v2beta1
和autoscaling/v2beta2
三个大版本。
常规场景下,比如晚上业务压力较小情况下,可以使用kubectl scale指令将pod副本数设置为1;当白天上班高分期业务压力大时使用kubectl scale指令将pod的副本数设置为3,但这些操作都是人为介入执行的。而hpa控制器则是基于业务的指标判断业务忙闲自动基于算法计算出当前多少pod副本数运行比较合适,自动调整pod的副本数。

kubernetes hpa v2
相对于v1
版本进行了一些重大改进。其中最显著的改进是引入了「多指标」自动扩缩容,即可以同时根据多种指标(如 cpu使用率、内存使用率、网络负载等)来进行自动扩缩容决策。此外,hpa v2
还增加了支持「自定义指标」的能力,使得用户可以根据自己的需求定义和使用自己的指标。总的来说,kubernetes hpa v2
是一个更加成熟、更加灵活和可定制的自动扩缩容机制。
「hpa弹性伸缩的核心机制:自动根据业务忙闲来调整业务工作负载的副本数。这里主要涉及到两个关键点:」
「如何识别业务的忙闲程度」
「使用控制pod副本数调整」

「我们先来看下第一个问题:如何识别业务的忙闲程度?」
之前介绍kubernetes集群监控时介绍过metrics-server组件可以从集群中所有节点的kubelet组件中cadvisor上获取到底层容器运行时指标,然后聚合后就可以通过kubectl top node/pod查看cpu、内存资源使用情况,也可以通过kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes
接口访问访问获取。所以,hpa控制器可以通过metrics-server组件获取pod的cpu、内存使用率识别业务忙闲。
kubernestes 1.7引入了聚合层(aggregator),允许第三方应用程序通过注册自己为api插件来扩展kubernestes api。metrics-server组件注册到聚合层然后就可以像访问kube-apiserver接口一样访问metrics-server后端服务的接口。
kubernetes在kube-apiserver服务中引入了一个api聚合层,用于将扩展api的访问请求转发到用户服务的功能。比如,当你访问apis/metrics.k8s.io/v1beta1
的时候,aggregator
组件会基于group
和version
转发到后端metrics-server
服务上,聚合层只是相当于代理层。通过这种方式,我们就可以很方便地扩展kubernetes
的api
。
从metrics-server获取cpu、内存指标比较单一,kubernetes集群监控事实标准是prometheus,如果可以从prometheus获取指标用来识别业务忙闲程度,弹性伸缩灵活性就会大大增加。prometheus-adapter组件就可以实现这个功能,它从prometheus拉取指标转换成kubernetes api接口识别的数据格式,并将其注册到聚合层,这样kubernetes集群中其它服务就可以通过/apis/访问。
「再来看第二个问题:如何控制pod副本数调整?」
hpa控制器会定期执行每个hpa对象的reconcile方法,主要包含如何操作:
获取当前指标数据:从metrics-server获取cpu使用率、内存使用率或从prometheus-adapter获取自定义指标数据;
pod副本数计算:将获取的指标数据和目标期望比较,判断是要扩容、缩容还是不变,若不需要要进行扩缩容调整就直接返回当前副本数,否则才使用hpa metrics 目标类型对应的算法来计算出deployment的目标副本数;
更新pod副本数:如果上步骤计算出的pod目标副本数与当前副本数量不一致时,即需要进行扩/缩容的情况,则hpa控制器就向deploymen发起scale操作,调整当前副本数,完成扩/缩容操作;
监控调整效果:最终实现尽可能将deployment下的每个pod的最终metrics指标(平均值)基本维持到用户期望的水平,hpa会继续监控新的pod副本数量对指标数据的影响,并根据需要进行进一步的调整。
基于cpu指标的hpa
hpa v1版本支持cpu使用率、内存使用率的弹性伸缩,内存使用率一般缓存影响很难真实反映系统负载,所以,一般使用cpu使用率指标来进行弹性伸缩。容器的cpu使用率可以通过聚合层api代理到后端metrics-server服务,metrics-server向所有的kubelet组件发送请求,通过cadvisor收集到所有容器的cpu、内存运行信息,这样hpa控制器就可以获取到pod的cpu使用率,然后基于cpu使用率进行弹性伸缩。

「1、基于deployment创建pod:」
#vi deploy-for-hpa_cpu.yml
apiversion: apps/v1
kind: deployment
metadata:
name: web
spec:
replicas: 1
selector:
matchlabels:
app: nginx-php
template:
metadata:
labels:
app: nginx-php
spec:
containers:
- image: lizhenliang/nginx-php
name: java
resources:
requests:
memory: "300mi"
cpu: "250m"
---
apiversion: v1
kind: service
metadata:
name: web
spec:
ports:
- port: 80
protocol: tcp
targetport: 80
selector:
app: nginx-php
「2、创建:」
[root@k8s-01 autoscaling]# kubectl apply -f deploy-for-hpa_cpu.yml -n demo01
[root@k8s-01 autoscaling]# kubectl get pod -n demo01
name ready status restarts age
web-84885d5959-fbtxt 1/1 running 0 29s
「3、hpa策略文件:」
# vi hpa_for_cpu.yml
apiversion: autoscaling/v1
kind: horizontalpodautoscaler
metadata:
name: web
spec:
#扩/缩容副本范围
maxreplicas: 3
minreplicas: 1
#指定扩容的deployment
scaletargetref:
apiversion: apps/v1
kind: deployment
name: web
targetcpuutilizationpercentage: 60
「4、创建hpa:」
[root@k8s-01 autoscaling]# kubectl apply -f hpa_for_cpu.yml -n demo01
horizontalpodautoscaler.autoscaling/web created
[root@k8s-01 autoscaling]# kubectl get hpa -n demo01
name reference targets minpods maxpods replicas age
web deployment/web 0%/60% 1 3 1 44s
「5、压测:」
[root@k8s-01 autoscaling]# yum install httpd-tools
[root@k8s-01 autoscaling]# kubectl get svc -n demo01
name type cluster-ip external-ip port(s) age
web clusterip 10.96.237.204 <none> 80/tcp 5d20h
[root@k8s-01 autoscaling]# ab -n 100000 -c 100 http://10.96.237.204/status.php
「6、观察扩/缩容:」
压测几十秒后,查看hpa后发现整体cpu使用率173%,超过60%目标值,但是replicas还是1,并没有扩容:
[root@k8s-01 autoscaling]# kubectl get hpa -n demo01
name reference targets minpods maxpods replicas age
metrics-app-hpa deployment/sample-httpserver2 200m/2 1 3 1 46h
web deployment/web 173%/60% 1 3 1 75s
再等会查看到replicas=3,触发了扩容操作:
[root@k8s-01 autoscaling]# kubectl get hpa -n demo01
name reference targets minpods maxpods replicas age
metrics-app-hpa deployment/sample-httpserver2 200m/2 1 3 1 46h
web deployment/web 15%/60% 1 3 3 76s
查看pod信息:
[root@k8s-01 autoscaling]# kubectl get pod -n demo01
name ready status restarts age
web-84885d5959-d9l4h 1/1 running 0 90s
web-84885d5959-fbtxt 1/1 running 0 6m9s
web-84885d5959-xgn4n 1/1 running 0 90s
kubectl describe hpa信息,可以看到有一条副本数扩到3的消息事件:

停止压测后,cpu使用率压力会降下来,大概等个几分钟后,又会触发缩容操作,replicas又会被设置成1:
[root@k8s-01 autoscaling]# kubectl get hpa -n demo01
name reference targets minpods maxpods replicas age
web deployment/web 0%/60% 1 3 1 7m59s
kubectl describe hpa查看hpa信息,会发现有两条缩容消息事件,一条显示是副本数从3缩容到2消息事件,另一条显示副本数从2缩容到1消息事件:

基于prometheus自定义指标的hpa
基于metrics-server组件获取的cpu使用率、内存使用率弹性伸缩灵活性稍差,如果想根据自定义指标,如http请求的qps、5xx错误数等,在云原生领域监控基本就是prometheus。自定义指标由prometheus来提供,再利用prometheus-adpater聚合到apiserver,实现从metric-server组件获取cpu、内存同样的效果。
基于prometheus自定义指标的hpa核心流程如下图:

prometheus-adapter组件部署
「1、安装prometheus-adapter
组件:」
[root@k8s-01 ~]# helm repo add stable http://mirror.azure.cn/kubernetes/charts
"prometheus-community" has been added to your repositories
[root@k8s-01 ~]# helm repo update
hang tight while we grab the latest from your chart repositories...
...successfully got an update from the "prometheus-community" chart repository
update complete. ⎈ happy helming!⎈
[root@k8s-01 ~]# helm repo list
name url
stable http://mirror.azure.cn/kubernetes/charts
[root@k8s-01 ~]# helm install prometheus-adapter stable/prometheus-adapter --namespace monitoring --set prometheus.url=http://prometheus,prometheus.port=9090
name: prometheus-adapter
last deployed: tue aug 1 23:44:08 2023
namespace: monitoring
status: deployed
revision: 1
test suite: none
notes:
prometheus-adapter has been deployed.
in a few minutes you should be able to list metrics using the following command(s):
kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1
「2、查看组件安装是否成功:」
[root@k8s-01 ~]# kubectl get pod -n monitoring
name ready status restarts age
prometheus-adapter-76d8fb4549-6vzzg 1/1 running 0 3m25s
[root@k8s-01 ~]# kubectl get apiservices
name service available age
...
v1beta1.custom.metrics.k8s.io monitoring/prometheus-adapter true 2m28s
[root@k8s-01 ~]# kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1 |jq|more
{
"kind": "apiresourcelist",
"apiversion": "v1",
"groupversion": "custom.metrics.k8s.io/v1beta1",
"resources": [
{
"name": "namespaces/file_descriptors",
"singularname": "",
"namespaced": false,
"kind": "metricvaluelist",
"verbs": [
"get"
]
},
{
"name": "namespaces/kube_ingress_annotations",
"singularname": "",
"namespaced": false,
"kind": "metricvaluelist",
"verbs": [
"get"
]
},
...
helm卸载操作如下:
[root@k8s-01 ~]# helm ls -n kube-system
name namespace revision updated status chart app version
prometheus-adapter kube-system 1 2023-08-01 23:44:08.027994527 +0800 cst deployed prometheus-adapter-4.3.0 v0.11.0
[root@k8s-01 ~]# helm uninstall prometheus-adapter -n kube-system
release "prometheus-adapter" uninstalled
部署golang应用
「1、初始化golang
项目工程:」
[root@swarm-manager ~]# mkdir metrics
[root@swarm-manager ~]# cd metrics/
[root@swarm-manager metrics]# go mod init metrics
「2、编写metrics.go
:」
package main
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
"strconv"
)
func main() {
metrics := prometheus.newcountervec(
prometheus.counteropts{
name: "http_requests_total",
help: "number of total http requests",
},
[]string{"status"},
)
prometheus.mustregister(metrics)
http.handlefunc("/", func(w http.responsewriter, r *http.request) {
path := r.url.path
statuscode := 200
switch path {
case "/metrics":
promhttp.handler().servehttp(w, r)
default:
w.writeheader(statuscode)
w.write([]byte("hello world!"))
}
metrics.withlabelvalues(strconv.itoa(statuscode)).inc()
})
http.listenandserve(":3000", nil)
}
「3、本地编译打包:」
[root@swarm-manager metrics]# go mod tidy
[root@swarm-manager metrics]# go build -o metrics metrics.go
「4、创建镜像,并推送docker hub上:」
编写dockerfile:
from golang:latest
maintainer simon "30743905@qq.com"
run mkdir -p /app
workdir /app
copy ./metrics /app
expose 3000
run chmod +x ./metrics
entrypoint ["./metrics"]
构建镜像:
docker build -t metrics .
「5、k8s部署:」
# sample-httpserver-deployment.yaml
apiversion: apps/v1
kind: deployment
metadata:
labels:
app: sample-httpserver
name: sample-httpserver
namespace: default
spec:
replicas: 1
selector:
matchlabels:
app: sample-httpserver
strategy: {}
template:
metadata:
annotations:
prometheus.io/scrape: "true"
prometheus.io/path: /metrics
prometheus.io/port: "3000"
labels:
app: sample-httpserver
spec:
containers:
- image: addozhang/httpserver-n-metrics:latest
name: httpserver-n-metrics
ports:
- containerport: 3000
resources:
requests:
memory: '300mi'
---
apiversion: v1
kind: service
metadata:
name: sample-httpserver
labels:
app: sample-httpserver
spec:
ports:
- name: web
port: 3000
targetport: 3000
selector:
app: sample-httpserver
「6、接口获取指标正常:」
[root@k8s-01 demo01]# kubectl get svc -n demo01
name type cluster-ip external-ip port(s) age
nginx-service clusterip none <none> 80/tcp 249d
sample-httpserver clusterip 10.96.153.13 <none> 3000/tcp 32s
tomcat-service clusterip none <none> 8080/tcp 249d
web clusterip 10.96.237.204 <none> 80/tcp 47h
[root@k8s-01 demo01]# curl 10.96.153.13:3000/metrics
# help go_gc_duration_seconds a summary of the pause duration of garbage collection cycles.
# type go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 3.5147e-05
go_gc_duration_seconds{quantile="0.25"} 3.8423e-05
go_gc_duration_seconds{quantile="0.5"} 4.1267e-05
go_gc_duration_seconds{quantile="0.75"} 5.0566e-05
go_gc_duration_seconds{quantile="1"} 9.0761e-05
go_gc_duration_seconds_sum 0.001240037
go_gc_duration_seconds_count 25
......
「7、prometheus配置抓取job:」
- job_name: 'app'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- action: keep
source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
regex: true
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
「8、指标抓取验证:」
在prometheus target可以查看到部署的应用指标接入成功:

使用promql查询:sum(rate(http_requests_total[30s])) by (pod)

hpa资源创建
「1、创建hpa:」
# vi app-hpa-v2.yml
apiversion: autoscaling/v2beta2
kind: horizontalpodautoscaler
metadata:
name: metrics-app-hpa
namespace: demo01
spec:
scaletargetref:
apiversion: apps/v1
kind: deployment
name: sample-httpserver
minreplicas: 1
maxreplicas: 3
metrics:
- type: pods
pods:
metric:
name: http_requests_qps
target:
type: averagevalue
averagevalue: 2000m # 2000m 即2个/秒
「2、prometheus-adapter
组件配置自定义指标的计算规则,告诉prometheus-adapter
如何从prometheus
获取指标并计算出我们需要的指标:kubectl edit cm prometheus-adapter -n monitoring
」

「3、可以访问api-server获取到prometheus-adapter计算生成的新指标:」
[root@k8s-01 ~]# kubectl get --raw '/apis/custom.metrics.k8s.io/v1beta1/namespaces/demo01/pods/*/http_requests_qps' | jq
{
"kind": "metricvaluelist",
"apiversion": "custom.metrics.k8s.io/v1beta1",
"metadata": {
"selflink": "/apis/custom.metrics.k8s.io/v1beta1/namespaces/demo01/pods/%2a/http_requests_qps"
},
"items": [
{
"describedobject": {
"kind": "pod",
"namespace": "demo01",
"name": "sample-httpserver-695f994dbd-s2s2g",
"apiversion": "/v1"
},
"metricname": "http_requests_qps",
"timestamp": "2023-08-02t15:32:56z",
"value": "66m",
"selector": null
}
]
}
「4、prometheus-adapter有了指标数据,就可以创建hpa基于该指标:kubectl apply -f app-hpa-v2.yml
」
# vi app-hpa-v2.yml
apiversion: autoscaling/v2beta2
kind: horizontalpodautoscaler
metadata:
name: metrics-app-hpa
namespace: demo01
spec:
scaletargetref:
apiversion: apps/v1
kind: deployment
name: sample-httpserver
minreplicas: 1
maxreplicas: 3
metrics:
- type: pods
pods:
metric:
name: http_requests_qps
target:
type: averagevalue
averagevalue: 2000m # 2000m 即2个/秒
「5、查看hpa从prometheus-adapter组件获取指标正常:」

当前pod副本数为1:

「6、接口压测:」
[root@k8s-01 ~]# kubectl get svc -n demo01
name type cluster-ip external-ip port(s) age
nginx-service clusterip none <none> 80/tcp 249d
sample-httpserver clusterip 10.96.153.13 <none> 3000/tcp 8m11s
[root@k8s-01 ~]# ab -n 100000 -c 30 http://10.96.153.13:3000/metrics
this is apachebench, version 2.3 <$revision: 1430300 $>
copyright 1996 adam twiss, zeus technology ltd, http://www.zeustech.net/
licensed to the apache software foundation, http://www.apache.org/
benchmarking 10.96.153.13 (be patient)
completed 10000 requests
completed 20000 requests
「7、弹性伸缩验证:」
查看hpa状态,targets一栏显示当前指标到达10900m左右,斜杠后面2表示到达2就要弹性伸缩,10900m/1000=10左右,明显超过2,则replicas一栏显示当前进行扩容到最大副本数3:

查看hpa描述信息,可以看到有条event清晰描述出有图http_requests_qps指标超过target设置的2,副本数设置为3:

再来看pod信息,发现副本数确实扩容到3个:

「8、弹性缩容验证:」
停止接口压测后,hpa指标下降,200m明显小于2,当大概平稳5分钟后,hpa开始进行缩容,将副本数从3降到1:

查看hpa描述信息,同样印证了hpa发生缩容:

再来确认下pod已经变成1个了:

发表评论