"""Read /proc host counters visible to the cloud agent; never inspect processes.""" import csv from datetime import datetime, timezone from pathlib import Path import shutil import signal import sys import time running = True def stop(*_): global running running = False signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) def cpu(): fields = [int(n) for n in Path('/proc/stat').read_text().splitlines()[0].split()[1:9]] return sum(fields), fields[3] + fields[4] last_total, last_idle = cpu() with open(sys.argv[1], 'w', newline='') as stream: writer = csv.writer(stream) writer.writerow(['utc','host_cpu_percent','host_mem_available_kib','filesystem_free_bytes']) while running: time.sleep(1) total, idle = cpu() memory = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines()) usage = 100 * (1 - (idle-last_idle) / max(1, total-last_total)) writer.writerow([datetime.now(timezone.utc).isoformat(),round(usage,2), int(memory['MemAvailable'].split()[0]),shutil.disk_usage('.').free]) stream.flush() last_total, last_idle = total, idle