获取Kubernetes Pod的状态、CPU和内存资源的方法

首先

大家好!!!
本次我们来讲解一下Kubernetes中Pod资源的获取方法!
我们将重点关注获取内容状态、CPU和内存的指标。

如果你不了解Kubernetes,请看这个。

获取Pod状态的方法

我们有一个方便的库,可以用于获取Pod的值,那就是kubernetes客户端。让我们使用以下命令进行安装!

$ pip3 install kubernetes

用这个你就会会使用了。

下一步,让我们使用Python来获取Pod的状态。
作为示例,我已准备了以下代码。

from kubernetes import client, config #kubernetes #クライアントモジュールのインストール

config.load_kube_config("/home/review2/kube/config") #パスの指定 

v1 = client.CoreV1Api()

pod_list = v1.list_namespaced_pod("bookman") #namespaceの指定
for pod in pod_list.items:
print(pod.status.phase)

运行结果

Running
Running
Running
Running

虽然非常简单,但状态已显示出来了。

CPU的数值获取方式

接下来是获取CPU指标的方法!我们来编写以下代码。

from kubernetes import client, config
import json
file = "/home/review2/kube/config"
config.load_kube_config(file)
api = client.CustomObjectsApi()
v1 = client.CoreV1Api()
resource = api.list_namespaced_custom_object(group="metrics.k8s.io",version="v1beta1", namespace="bookman", plural="pods")

all_array = []

#print(json.dumps(resource,ensure_ascii=False, indent=4, sort_keys=True, separators=(',', ': ')))
for pod in resource["items"]:
    s=pod["metadata"]["name"],pod['containers'][0]["usage"]["cpu"].replace('n','')
    all_array.append(s)
    print(s)

max=None
max_name=""
for container in all_array:
    if max is None:
        max = int(container[1])
    elif int(container[1])<max:
        max=int(container[1])
        max_name=container[0]
print(max_name,max)

# Configs can be set in Configuration class directly or using helper utility
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    if 'replicas-deployment' in i.metadata.name:

        print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

那么就会得到这样的输出。嗯,感觉很不错!

('mysql-test-79489b6494-46hrp', '266171')
('wordpress-test-667846cf96-dcgcj', '20848')
('wordpress-test-667846cf96-njdcc', '19222')
('wordpress-test-667846cf96-qvkbd', '20063')

最后我会附上关于Memory的获取方法!

获取存储器的方法

from kubernetes import client, config

config.load_kube_config()
api = client.CustomObjectsApi()
v1 = client.CoreV1Api()
resource = api.list_namespaced_custom_object(group="metrics.k8s.io", version="v1beta1", namespace="test", plural="pods")

all_array = []

for pod in resource["items"]:
    container_name = pod["metadata"]["name"]
    memory_usage = pod['containers'][0]["usage"]["memory"]
    
    # 単位を取り除いて数値に変換
    memory_value = int(memory_usage[:-2]) * 1024  # 'Ki'を取り除いて数値に変換し、バイトに変換する
    
    all_array.append((container_name, memory_value))
    print((container_name, memory_value))

max_memory = None
max_container = ""
for container in all_array:
    if max_memory is None:
        max_memory = container[1]
    elif container[1] > max_memory:
        max_memory = container[1]
        max_container = container[0]
        
print(f"Container with highest memory usage: {max_container}, Memory: {max_memory} bytes")

# Podの情報を表示
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    if 'replicas-deployment' in i.metadata.name:
        print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

这样就可以获得内存的度量了!

('mysql-test-79489b6494-46hrp', 4087808)
('wordpress-test-667846cf96-dcgcj', 3260416)
('wordpress-test-667846cf96-njdcc', 3059712)
('wordpress-test-667846cf96-qvkbd', 11759616)

最终最后

如果你们也愿意的话,可以试试这样取得度量指标,就像这样取得度量指标一样!

广告
将在 10 秒后关闭
bannerAds