To accomplish this task, you can create a Python script that periodically calls kubectl top to get the resource usage and writes this data in a structured format (like CSV) to a file. Below is a basic script to achieve this:
import subprocess
import time
import csv
def get_kubectl_top_output():
# Call kubectl top to get CPU and memory usage
result = subprocess.run(['kubectl', 'top', 'pods'], capture_output=True, text=True)
return result.stdout.splitlines()
def process_kubectl_top_output(output_lines):
processed_data = []
for line in output_lines[1:]: # Skip the header
columns = line.split()
if len(columns) >= 3: # Verify the expected number of columns
pod_name = columns[0]
cpu_usage = columns[1]
memory_usage = columns[2]
processed_data.append([pod_name, cpu_usage, memory_usage])
return processed_data
def write_to_csv(file_path, data, write_header=False):
# Write the processed data to a CSV file
with open(file_path, 'a', newline='') as file:
writer = csv.writer(file)
if write_header:
writer.writerow(['Pod Name', 'CPU Usage', 'Memory Usage'])
writer.writerows(data)
def main():
csv_file = "kubectl_resource_usage.csv"
write_header = True
while True:
output_lines = get_kubectl_top_output()
processed_data = process_kubectl_top_output(output_lines)
write_to_csv(csv_file, processed_data, write_header)
write_header = False # Only write header once
time.sleep(1) # Wait for 1 second before the next output grab
if __name__ == "__main__":
main()
Explanation:
-
Import Required Modules: We import necessary Python modules for running subprocesses, handling time delays, and writing CSV files.
-
Run kubectl top pods: We call this command using subprocess.run() capturing the output.
-
Process Output: Process the output of the command by splitting lines and columns to extract pod name, CPU, and memory usage.
-
Write to CSV: Append this data into a CSV file. The CSV writer is set to append mode to continuously add new data without overwriting.
-
Loop with Delay: A while loop along with time.sleep(1) ensures that the process repeats every second. The header is written only once by using the write_header flag.
Notes:
-
CSV Format: Comma-separated values are a simple format that can be easily loaded into debugging tools or spreadsheet software for analysis.
-
Error Handling: There's room for improvement by adding error handling for the subprocess call and file operations.
-
Permissions: Ensure your script is run in an environment with sufficient permissions to execute Kubernetes commands. You might need to run it with a user that has appropriate privileges.
-
Python Environment: Make sure the Python environment has access to subprocess, csv modules, and that the kubectl command is available in the PATH.
-
Filtering: Customize the script further to fit specific labels or namespaces, or adapt it for different Kubernetes resources if needed.