Skip to content

Instantly share code, notes, and snippets.

@rooftopcellist
Created November 22, 2023 20:34
Show Gist options
  • Save rooftopcellist/682e666d808c5af3ef114b7fa7b0c655 to your computer and use it in GitHub Desktop.
Save rooftopcellist/682e666d808c5af3ef114b7fa7b0c655 to your computer and use it in GitHub Desktop.
Provide a report of the operator pod's resource utilzation over time
'''
Purpose:
To provide a report of the operator pod's resource utilzation over time
Usage:
python monitor-operator-pod-usage.py --deployment_name "awx-operator-controller-manager" --namespace "awx" --total_time 300
'''
import subprocess
import time
from tabulate import tabulate
import argparse
# Setup command line arguments
parser = argparse.ArgumentParser(description="Monitor Kubernetes pod resource usage.")
parser.add_argument("--deployment_name", type=str, default="resource-operator-controller-manager",
help="Name of the deployment")
parser.add_argument("--namespace", type=str, default="resource",
help="Namespace of the deployment")
parser.add_argument("--total_time", type=int, default=300,
help="Total time to monitor in seconds")
# Parse arguments
args = parser.parse_args()
# Use command line arguments or defaults
deployment_name = args.deployment_name
namespace = args.namespace
total_time = args.total_time
# Function to get the pod name
def get_pod_name():
cmd = f"oc get pod -n {namespace} | grep '{deployment_name}' | awk '{{print $1}}'"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
raise Exception(f"Error in getting pod name: {result.stderr.strip()}")
return result.stdout.strip().rstrip()
# Function to convert CPU to millicores
def convert_cpu_to_millicores(cpu):
if 'm' in cpu:
return int(cpu.replace('m', ''))
elif 'cpu' in cpu:
return int(float(cpu.replace('cpu', '')) * 1000)
return int(cpu)
# Function to convert memory to Mi
def convert_memory_to_mi(memory):
if 'Mi' in memory:
return int(memory.replace('Mi', ''))
elif 'Gi' in memory:
return int(float(memory.replace('Gi', '')) * 1024)
return int(memory)
# Function to get CPU and memory usage
def get_usage_stats(pod_name):
cmd = f"kubectl top pod {pod_name} -n {namespace} --no-headers"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
raise Exception(f"Error in getting usage stats: {result.stderr.strip()}")
cpu, memory = result.stdout.split()[1], result.stdout.split()[2]
return convert_cpu_to_millicores(cpu), convert_memory_to_mi(memory)
# Function to calculate average, minimum, and maximum
def calculate_stats(data):
return sum(data) / len(data), min(data), max(data)
try:
pod_name = get_pod_name()
print(f"Monitoring Pod: {pod_name}")
cpu_usage, memory_usage = [], []
start_time = time.time()
while time.time() - start_time < total_time:
cpu, memory = get_usage_stats(pod_name)
cpu_usage.append(cpu)
memory_usage.append(memory)
time.sleep(5)
cpu_stats = calculate_stats(cpu_usage)
memory_stats = calculate_stats(memory_usage)
# Creating table
headers = ["Resource", "Average", "Minimum", "Maximum"]
table = [
["CPU (millicores)", *cpu_stats],
["Memory (Mi)", *memory_stats]
]
print(tabulate(table, headers, tablefmt="grid"))
except Exception as e:
print(f"Error: {str(e)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment