Data acquisition is an important task in evaluating experiments using pods. In this article, I will write a program to get the pod name, IP address, and CPU usage.
Duplicate a pod using kubernetes Deployment
reprica.yaml
sets the number of replicas to 4. A container is a program that displays a web application with an nginx image.
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
~
The created pod could be displayed like this.
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
Next, write a program to get the data of this pod.
api_cpu.py
makes it possible to get the CPU usage rate, IP address, and pod name.
In addition, the pod with the lowest CPU usage is displayed below.
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))
~ ~
The execution result is as follows. The load is applied by the load experiment tool Locust. The acquired data can be displayed.
('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
This is the end of this article. In the future, I would like to add a program that can display only the pod with the lowest CPU usage.
Recommended Posts