是否有可能在我的应用程序中获得k8s pod限制?



我有一个在pod内运行kafka消费者的应用程序,内存限制为1.5GB。

你可能知道,我们需要写一些逻辑来阻止消费者获取消息,当我们即将达到内存限制。

当我的应用程序使用的内存超过内存限制的75%时,我想停止消费者。

所以我的问题是……是否有可能获得k8s内存限制运行时?我如何根据我有多少空闲内存来停止我的消费者?
this.consumer.on('message', (message) => {
checkApplicationMemoryUsage();
executeSomethingWithMessage(message);
});
function checkApplicationMemoryUsage() {
const appMemoryConsumption = process.memoryUsage().heapUsed;
const appMemoryLimit = <?????>;
if (appMemoryConsumption / appMemoryLimit > 0.75) this.consumer.pause();
else this.consumer.resume();
}

我正在考虑的解决方案是在部署规范上将限制作为环境变量传递给我的pod,但我希望有更好的方法

是的,Downward API提供了一种实现所需的方法。

apiVersion: v1
kind: Pod
metadata:
name: kubernetes-downwardapi-volume-example-2
spec:
containers:
- name: client-container
image: k8s.gcr.io/busybox:1.24
command: ["sh", "-c"]
args:
- while true; do
echo -en 'n';
if [[ -e /etc/podinfo/cpu_limit ]]; then
echo -en 'n'; cat /etc/podinfo/cpu_limit; fi;
if [[ -e /etc/podinfo/cpu_request ]]; then
echo -en 'n'; cat /etc/podinfo/cpu_request; fi;
if [[ -e /etc/podinfo/mem_limit ]]; then
echo -en 'n'; cat /etc/podinfo/mem_limit; fi;
if [[ -e /etc/podinfo/mem_request ]]; then
echo -en 'n'; cat /etc/podinfo/mem_request; fi;
sleep 5;
done;
resources:
requests:
memory: "32Mi"
cpu: "125m"
limits:
memory: "64Mi"
cpu: "250m"
volumeMounts:
- name: podinfo
mountPath: /etc/podinfo
volumes:
- name: podinfo
downwardAPI:
items:
- path: "cpu_limit"
resourceFieldRef:
containerName: client-container
resource: limits.cpu
divisor: 1m
- path: "cpu_request"
resourceFieldRef:
containerName: client-container
resource: requests.cpu
divisor: 1m
- path: "mem_limit"
resourceFieldRef:
containerName: client-container
resource: limits.memory
divisor: 1Mi
- path: "mem_request"
resourceFieldRef:
containerName: client-container
resource: requests.memory
divisor: 1Mi

请参阅K8s文档中的存储容器字段部分中的上述示例。

最新更新