Designing Python daemon logic
The daemon will repeatedly read /proc/stat to compute CPU steal and iowait percentages by comparing cumulative counters over intervals; it will read /proc/meminfo to track memory usage and, if usage exceeds 90%, identify and log the PID and command line of the process with the highest OOM score by scanning relevant /proc entries. It will use robust exception handling and standard logging, running in a loop with a sleep interval suitable for systemd service deployment.
On a modern Linux system all the inputs you need live under /proc:
- The first line of
/proc/stat has accumulated CPU time counters in “jiffies”. The fields are, in order: user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice. To turn those counters into a rate or percentage you need to take two snapshots and look at the deltas.
/proc/meminfo exposes MemTotal and MemAvailable; (1‑MemAvailable/MemTotal) gives you a rough memory utilisation percentage.
- Every process has an
oom_score and a cmdline file under its /proc/<pid> directory.
A minimal daemon can be written in Python as a long–running loop that periodically samples these files. If memory utilisation crosses your threshold, it scans /proc for the process with the highest OOM score and logs its PID and command line.
Here's a complete example:
#!/usr/bin/env python3
import logging
import os
import signal
import time
LOG_FILE = '/var/log/resmon_daemon.log'
MEM_THRESHOLD = 0.90 # 90%
INTERVAL = 5.0 # seconds between samples
logging.basicConfig(filename=LOG_FILE,
level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s')
def read_cpu_times():
"""Read the cumulative CPU times from /proc/stat."""
with open('/proc/stat', 'r') as f:
for line in f:
if line.startswith('cpu '):
parts = line.split()
# parts[0] is 'cpu', the next fields are times
values = list(map(int, parts[1:]))
# user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice
return {
'user': values[0], 'nice': values[1], 'system': values[2],
'idle': values[3], 'iowait': values[4], 'irq': values[5],
'softirq': values[6], 'steal': values[7]
}
raise RuntimeError("No 'cpu' line in /proc/stat")
def cpu_percentages(prev, cur):
"""Compute percentages for steal and iowait between two samples."""
prev_total = sum(prev.values())
cur_total = sum(cur.values())
total_diff = cur_total - prev_total
if total_diff <= 0:
return 0.0, 0.0
steal_pct = (cur['steal'] - prev['steal']) * 100.0 / total_diff
iowait_pct = (cur['iowait'] - prev['iowait']) * 100.0 / total_diff
return steal_pct, iowait_pct
def read_mem_usage():
"""Return memory usage as a fraction between 0 and 1."""
mem_total = mem_available = None
with open('/proc/meminfo', 'r') as f:
for line in f:
if line.startswith('MemTotal:'):
mem_total = int(line.split()[1]) # kB
elif line.startswith('MemAvailable:'):
mem_available = int(line.split()[1]) # kB
if mem_total is not None and mem_available is not None:
break
if mem_total is None or mem_available is None:
raise RuntimeError("Could not read MemTotal/MemAvailable")
used = mem_total - mem_available
return used / mem_total
def find_highest_oom():
"""Find the process with the highest oom_score; return (pid, cmdline)."""
max_score = -1
max_pid = None
for entry in os.listdir('/proc'):
if not entry.isdigit():
continue
pid = entry
try:
with open(f'/proc/{pid}/oom_score', 'r') as f:
score = int(f.read().strip())
except (FileNotFoundError, ProcessLookupError, PermissionError):
continue # process exited or not accessible
if score > max_score:
max_score = score
max_pid = pid
if max_pid is None:
return None, None
# read command line
try:
with open(f'/proc/{max_pid}/cmdline', 'rb') as f:
raw = f.read()
cmdline = raw.replace(b'\x00', b' ').decode('utf-8', errors='replace').strip()
except (FileNotFoundError, ProcessLookupError, PermissionError):
cmdline = ''
return max_pid, cmdline
def main():
running = True
def handle_signal(signum, frame):
nonlocal running
running = False
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
prev_cpu = read_cpu_times()
while running:
time.sleep(INTERVAL)
cur_cpu = read_cpu_times()
steal_pct, iowait_pct = cpu_percentages(prev_cpu, cur_cpu)
logging.info("CPU steal: %.2f%%, I/O wait: %.2f%%", steal_pct, iowait_pct)
prev_cpu = cur_cpu
try:
mem_usage = read_mem_usage()
except RuntimeError as e:
logging.error("Failed to read memory usage: %s", e)
continue
if mem_usage >= MEM_THRESHOLD:
pid, cmdline = find_highest_oom()
if pid:
logging.warning("Memory usage at %.1f%%; highest OOM score: PID %s CMD '%s'",
mem_usage*100, pid, cmdline)
else:
logging.warning("Memory usage at %.1f%%; no process found", mem_usage*100)
if __name__ == '__main__':
main()
Save this as, for example, /usr/local/bin/resmon_daemon.py, make it executable, and run it under a process supervisor or a systemd service so it will be started at boot and restarted on failure. A simple resmon_daemon.service unit might look like:
[Unit]
Description=Resource Monitor Daemon
[Service]
ExecStart=/usr/bin/python3 /usr/local/bin/resmon_daemon.py
Restart=always
[Install]
WantedBy=multi-user.target
Enable it with systemctl enable --now resmon_daemon.service. The daemon will then periodically log CPU steal and I/O wait percentages, and if memory usage exceeds 90 %, it will log the PID and command line of the process with the highest OOM score.