How to display the CPU usage, pod name, and IP address of a pod created with Kubernetes

Introduction

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.

Creating a pod

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

How to display the CPU usage, pod name, and IP address of a pod created with Kubernetes
[Linux] [C / C ++] How to get the return address value of a function and the function name of the caller
A tool to insert the country name and country code in the IP address part
[Linux] How to display CPU usage, display header, and not display grep process with ps command
How to display a list of installable versions with pyenv
How to insert a specific process at the start and end of spider with scrapy
How to find the memory address of a Pandas dataframe value
To improve the reusability and maintainability of workflows created with Luigi
[Python] How to specify the window display position and size of matplotlib
How to calculate the volatility of a brand
Connect to the console of Raspberry PI and display local IP and SD information
I made you to express the end of the IP address with L Chika
How to count the number of elements in Django and output to a template
How to apply updlock, rowlock, etc. with a combination of SQLAlchemy and SQLServer
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
How to display the modification date of a file in C language up to nanoseconds
How to create a submenu with the [Blender] plugin
How to identify the element with the smallest number of characters in a Python list?
[pyqtgraph] Created a class to display the crosshairs that follow the cursor and their coordinates
A memo on how to overcome the difficult problem of capturing FX with AI
How to create a kubernetes pod from python code
How to output the number of VIEWs, likes, and stocks of articles posted on Qiita to CSV (created with "Python + Qiita API v2")
How to display the regional mesh of the official statistics window (eStat) in a web browser
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
[Super easy! ] How to display the contents of dictionaries and lists including Japanese in Python
How to change the MAC address of an automatically created virtual NIC to be event driven
How to plot a lot of legends by changing the color of the graph continuously with matplotlib
A story about porting the code of "Try and understand how Linux works" to Rust
[Ubuntu] How to delete the entire contents of a directory
A network diagram was created with the data of COVID-19.
Get the id of a GPU with low memory usage
How to find the scaling factor of a biorthogonal wavelet
How to connect the contents of a list into a string
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
How to intercept or tamper with the SSL communication of the actual iOS device by a proxy
Learn the flow of Bayesian estimation and how to use Pystan through a simple regression model
How to set a shortcut to switch full-width and half-width with IBus
How to display a specified column of files in Linux (awk)
Overview of how to create a server socket and how to establish a client socket
How to determine the existence of a selenium element in Python
[Introduction to Python] How to split a character string with the split function
How to get the ID of Type2Tag NXP NTAG213 with nfcpy
How to check the memory size of a variable in Python
[Python] How to get the first and last days of the month
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
How to make a command to read the configuration file with pyramid
How to make a surveillance camera (Security Camera) with Opencv and Python
[Memo] How to use BeautifulSoup4 (2) Display the article headline with Requests
How to output the output result of the Linux man command to a file
How to monitor the execution status of sqlldr with the pv command
Get the URL of a JIRA ticket created with the jira-python library
How to get the vertex coordinates of a feature in ArcPy
I summarized how to change the boot parameters of GRUB and GRUB2
Node.js: How to kill offspring of a process started with child_process.fork ()
[Memo] How to use BeautifulSoup4 (3) Display the article headline with class_
How to send a request to the DMM (FANZA) API with python
[NNabla] How to remove the middle tier of a pre-built network
How to display bytes in the same way in Java and Python
[Rails 6] Embed Google Map in the app and add a marker to the entered address. [Confirmation of details]
Introduction and usage of Python bottle ・ Try to set up a simple web server with login function