这里介绍下如何在K8s设置多个自定义计量。K8s 默认的可用于PHA(Pod Horizon Autoscaling)只有CPU,自定义的计量feature一直处于alpha 测试阶段,而且不稳定,在某些版本未实现custom metric,比如1.6.2。
这里以1.5.7 版本为例,首先部署K8s,heapster,grafana,influxdb。部署方法可参考https://github.com/kubernetes/heapster/tree/master/deploy/kube-config/influxdb
在kubelet 启动参数里要加上--enable-custom-metrics=true,kubelet会根据这个参数在容器启动时,对容器加label"io.cadvisor.metric.prometheus":"/etc/custom-metrics/definition.json", 在1.6.2 版本里,就是因为不再使用/pkg/kubelet/dockertools 管理容器 ,而是使用新的/pkg/kubelet/dockershim,而在dockershim中,还未实现加这中label,导致未实现custom metric。有了这个label后,
要支持custom metric,对容器也有要求,如果容器内/etc/custom-metrics/definition.json要有API endpoint 供 cAdvisor获取。
cat/etc/custom-metrics/definition.json
{"endpoint":"http://192.168.10.2:8080/metrics"}
这个文件里面的IP是动态写入的,在容器初始化时写入PodIP。具体可参考https://medium.com/@marko.luksa/kubernetes-autoscaling-based-on-custom-metrics-without-using-a-host-port-b783ed6241ac。具体yaml文件如下
apiVersion:extensions/v1beta1
kind: Deployment
metadata:
name: kubia
spec:
replicas: 1
template:
metadata:
name: kubia
labels:
app: kubia
annotations:
pod.beta.kubernetes.io/init-containers:'[
{
"name":"setup",
"image":"busybox",
"imagePullPolicy":"IfNotPresent",
"command":["sh", "-c", "echo \"{\\\"endpoint\\\":\\\"http://$POD_IP:8080/metrics\\\"}\" >/etc/custom-metrics/definition.json"],
"env": [{
"name":"POD_IP",
"valueFrom": {
"fieldRef": {
"apiVersion":"v1",
"fieldPath":"status.podIP"
}
}
}],
"volumeMounts": [
{
"name":"config",
"mountPath":"/etc/custom-metrics"
}
]
}
]'
spec:
containers:
- image: luksa/kubia:qps
name: nodejs
ports:
- containerPort: 8080
volumeMounts:
- name: config
mountPath: /etc/custom-metrics
这样容器启动时,容器内就有/etc/custom-metrics/definition.json文件里。
在容器里要提供一个restAPI 服务,服务地址就是definition.json所标记地址。可以尝试curl 这个地址,看是否正常获取数据。
curl http://192.168.10.2:8080/metrics
# TYPE qpsgauge //不能忽略该行,否则未知类型的数据会被heapster抛弃
qps 0
# TYPE testmetricgauge //不能忽略该行,否则未知类型的数据会被heapster抛弃
testmetric 0.41291926987469196
然后两种方法确认cAdvisor是否正常获取该数据。
第一种curl cAdvisor地址:
curl10.140.163.102:4194/api/v1.0/containers/docker/44d52b9acfc334233f685c81f130cd44538602980a8bff16495d1067bf3dfe5d
确认是否存在
"custom_metrics":[{
"name": "qps",
"type": "gauge",
"format": "float",
"units": ""
},
{
"name": "testmetric",
"type": "gauge",
"format": "float",
"units": ""
}],
还有是否存在
"custom_metrics": {
"qps": [{
"label": "__name__=qps",
"timestamp": "2017-06-02T15:43:54.146+08:00"
}],
"testmetric": [{
"label": "__name__=testmetric",
"timestamp": "2017-06-02T15:43:54.146+08:00",
"float_value": 4.7396062151528895
}]
}
第二种方法访问cAdvisor GUI:
然后确认heapster是否正常采集到数据