LoginSignup
1

More than 3 years have passed since last update.

Kubernetesで作成したPodのCPU使用量,Pod名,IPアドレスを表示させる方法

Last updated at Posted at 2021-01-06

はじめに

Podを使った実験の評価をする上でデータ取得は重要な作業である。
この記事ではPodの名前とIPアドレス、CPU使用率を取得するプログラムを書いていく。

Podの作成

kubernetesのDeploymentを使ってPodの複製をする
reprica.yamlはレプリカ数を4に設定。コンテナはnginxイメージでWebアプリを表示させるプログラム。

reprica.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: replicas-deployment
spec:
  replicas: 4
  selector:
    matchLabels:
      app: server-app
  template:
    metadata:
      labels:
        app: server-app
    spec:
      containers:
        - name: nginx-container
          image: nogisora/serverimage
          ports:
            - containerPort: 80
~                              

作成したPodはこのように表示できた。

kubectl get pod
NAME                                   READY   STATUS    RESTARTS   AGE
replicas-deployment-5b669df64c-wnfbp   1/1     Running   2          34d
replicas-deployment-5b669df64c-csscv   1/1     Running   2          34d
replicas-deployment-5b669df64c-fj6kr   1/1     Running   2          34d
replicas-deployment-5b669df64c-l8k7x   1/1     Running   2          34d

次にこのPodのデータを取得するプログラムを書く。
api_cpu.pyではCPU使用率、IPアドレス、Pod名を取得できるようにしている。
さらに、CPU使用率の一番低いPodを下に表示させるようにもなっている。
※jsonの部分はコメントアウトになっているのは実験上必要がなかった為

api_cpu.py

from kubernetes import client, config
import json

config.load_kube_config()
api = client.CustomObjectsApi()
v1 = client.CoreV1Api()
resource = api.list_namespaced_custom_object(group="metrics.k8s.io",version="v1beta1", namespace="c0118220", 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))
~                                                                                ~                                                            

実行結果は以下のようになった。
負荷は負荷実験ツールのLocustでかけている。
取得したデータは表示できている。

('replicas-deployment-5b669df64c-fj6kr', '28540182')
('replicas-deployment-5b669df64c-l8k7x', '30169433')
('replicas-deployment-5b669df64c-wnfbp', '31286353')
('replicas-deployment-5b669df64c-csscv', '27848575')
replicas-deployment-5b669df64c-csscv 27848575
Listing pods with their IPs:
10.42.1.112     c0118220        replicas-deployment-5b669df64c-wnfbp
10.42.1.113     c0118220        replicas-deployment-5b669df64c-csscv
10.42.2.191     c0118220        replicas-deployment-5b669df64c-fj6kr
10.42.2.198     c0118220        replicas-deployment-5b669df64c-l8k7x

以上でこの記事を終わりとする。
今後は、CPU使用率の一番低いPodのみを表示させられるようなプログラムを追記したいと考えてる。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1