This is a comprehensive request for a Python daemon that monitors system resources. Let me break down what's needed:
- A daemon that runs continuously
- Monitors system resources (CPU, memory)
- Specifically calculates CPU steal time and I/O wait from /proc/stat
- When memory > 90%, identifies the process with highest OOM score
- Logs PID and command line of that process
I'll create a complete, production-ready solution with:
- Proper daemon implementation (using python-daemon or manual fork)
- Logging configuration
- /proc/stat parsing
- Memory monitoring
- OOM score reading
- Error handling
- Configuration file
- Systemd service file as an example
Let me write comprehensive code:
import os
import sys
import time
import logging
import signal
import subprocess
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Optional, Tuple
from datetime import datetime
import re
# Try to import python-daemon, fall back to manual implementation
try:
import daemon
HAS_DAEMON_LIBRARY = True
except ImportError:
HAS_DAEMON_LIBRARY = False
Let me create a well-structured solution with multiple files.
System Resource Monitoring Daemon
Here's a comprehensive Python daemon that monitors CPU steal time, I/O wait, and identifies high-OOM processes:
1. Main Daemon Implementation
#!/usr/bin/env python3
"""
System Resource Monitoring Daemon
Monitors CPU steal time, I/O wait, and memory usage
"""
import os
import sys
import time
import logging
import signal
import json
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Optional, Tuple
from datetime import datetime
import re
import psutil
# Configuration
DEFAULT_CONFIG_PATH = "/etc/sysmon-daemon/config.json"
DEFAULT_LOG_PATH = "/var/log/sysmon-daemon.log"
DEFAULT_PID_FILE = "/var/run/sysmon-daemon.pid"
@dataclass
class CPUStats:
"""CPU statistics from /proc/stat"""
user: int
nice: int
system: int
idle: int
iowait: int
irq: int
softirq: int
steal: int
guest: int
guest_nice: int
timestamp: float
@dataclass
class ResourceMetrics:
"""Current resource metrics"""
cpu_steal_percent: float
iowait_percent: float
memory_percent: float
memory_available: int
cpu_count: int
timestamp: float
class SystemResourceMonitor:
"""Monitor system resources and identify problematic processes"""
def __init__(self, config_path: str = DEFAULT_CONFIG_PATH):
self.config = self._load_config(config_path)
self.logger = self._setup_logging()
self.prev_cpu_stats: Optional[CPUStats] = None
self.running = True
# Signal handlers
signal.signal(signal.SIGTERM, self._handle_signal)
signal.signal(signal.SIGINT, self._handle_signal)
self.logger.info("SystemResourceMonitor initialized")
def _load_config(self, config_path: str) -> Dict:
"""Load configuration from JSON file"""
default_config = {
"check_interval": 5,
"memory_threshold": 90,
"log_level": "INFO",
"collect_cpu_data_points": 10,
"cpu_threshold": 50,
"io_threshold": 30
}
if Path(config_path).exists():
try:
with open(config_path, 'r') as f:
config = json.load(f)
return {**default_config, **config}
except Exception as e:
print(f"Error loading config: {e}, using defaults")
return default_config
def _setup_logging(self) -> logging.Logger:
"""Configure logging"""
logger = logging.getLogger(__name__)
log_level = getattr(logging, self.config.get("log_level", "INFO"))
logger.setLevel(log_level)
# File handler
fh = logging.FileHandler(DEFAULT_LOG_PATH)
fh.setLevel(log_level)
# Console handler
ch = logging.StreamHandler()
ch.setLevel(log_level)
# Formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
return logger
def _handle_signal(self, signum, frame):
"""Handle termination signals"""
self.logger.info(f"Received signal {signum}, shutting down")
self.running = False
def _parse_proc_stat(self) -> CPUStats:
"""
Parse /proc/stat to extract CPU statistics
Format: cpu user nice system idle iowait irq softirq steal guest guest_nice
"""
try:
with open('/proc/stat', 'r') as f:
line = f.readline().strip()
# Remove 'cpu' prefix and split
values = line.split()[1:11]
# Convert to integers
stats = [int(v) for v in values]
return CPUStats(
user=stats[0],
nice=stats[1],
system=stats[2],
idle=stats[3],
iowait=stats[4],
irq=stats[5],
softirq=stats[6],
steal=stats[7] if len(stats) > 7 else 0,
guest=stats[8] if len(stats) > 8 else 0,
guest_nice=stats[9] if len(stats) > 9 else 0,
timestamp=time.time()
)
except Exception as e:
self.logger.error(f"Error parsing /proc/stat: {e}")
return None
def _calculate_cpu_metrics(self, prev: CPUStats, curr: CPUStats) -> Tuple[float, float]:
"""
Calculate steal time and I/O wait percentages
Returns:
Tuple of (steal_percent, iowait_percent)
"""
# Calculate deltas
total_prev = (prev.user + prev.nice + prev.system + prev.idle +
prev.iowait + prev.irq + prev.softirq + prev.steal)
total_curr = (curr.user + curr.nice + curr.system + curr.idle +
curr.iowait + curr.irq + curr.softirq + curr.steal)
total_delta = total_curr - total_prev
if total_delta == 0:
return 0.0, 0.0
steal_delta = curr.steal - prev.steal
iowait_delta = curr.iowait - prev.iowait
steal_percent = (steal_delta / total_delta) * 100 if total_delta > 0 else 0
iowait_percent = (iowait_delta / total_delta) * 100 if total_delta > 0 else 0
return steal_percent, iowait_percent
def _get_memory_stats(self) -> Tuple[float, int]:
"""
Get current memory usage and available memory
Returns:
Tuple of (memory_percent, available_bytes)
"""
try:
mem = psutil.virtual_memory()
return mem.percent, mem.available
except Exception as e:
self.logger.error(f"Error getting memory stats: {e}")
return 0.0, 0
def _get_process_oom_score(self, pid: int) -> Optional[int]:
"""
Read OOM score for a process
Higher score = more likely to be killed
"""
try:
oom_score_path = f"/proc/{pid}/oom_score"
if Path(oom_score_path).exists():
with open(oom_score_path, 'r') as f:
return int(f.read().strip())
except (OSError, ValueError) as e:
pass
return None
def _find_highest_oom_process(self) -> Optional[Tuple[int, str, int]]:
"""
Find process with highest OOM score
Returns:
Tuple of (pid, command_line, oom_score) or None
"""
max_oom_score = -1
target_process = None
try:
for pid_dir in Path('/proc').iterdir():
if not pid_dir.is_dir():
continue
try:
pid = int(pid_dir.name)
except ValueError:
continue
# Get OOM score
oom_score = self._get_process_oom_score(pid)
if oom_score is None:
continue
if oom_score > max_oom_score:
max_oom_score = oom_score
# Get command line
try:
cmdline_path = f"/proc/{pid}/cmdline"
with open(cmdline_path, 'rb') as f:
cmdline = f.read().decode('utf-8', errors='ignore')
# Replace null bytes with spaces
cmdline = ' '.join(cmdline.split('\x00')).strip()
except:
cmdline = f"<PID {pid}>"
target_process = (pid, cmdline, oom_score)
except Exception as e:
self.logger.error(f"Error finding highest OOM process: {e}")
return target_process
def _get_metrics(self) -> Optional[ResourceMetrics]:
"""Collect all resource metrics"""
try:
# Get CPU stats
curr_cpu_stats = self._parse_proc_stat()
if curr_cpu_stats is None:
return None
steal_percent = 0.0
iowait_percent = 0.0
if self.prev_cpu_stats:
steal_percent, iowait_percent = self._calculate_cpu_metrics(
self.prev_cpu_stats, curr_cpu_stats
)
self.prev_cpu_stats = curr_cpu_stats
# Get memory stats
mem_percent, mem_available = self._get_memory_stats()
return ResourceMetrics(
cpu_steal_percent=steal_percent,
iowait_percent=iowait_percent,
memory_percent=mem_percent,
memory_available=mem_available,
cpu_count=os.cpu_count(),
timestamp=time.time()
)
except Exception as e:
self.logger.error(f"Error collecting metrics: {e}")
return None
def _log_metrics(self, metrics: ResourceMetrics):
"""Log resource metrics"""
self.logger.info(
f"CPU Steal: {metrics.cpu_steal_percent:.2f}% | "
f"I/O Wait: {metrics.iowait_percent:.2f}% | "
f"Memory: {metrics.memory_percent:.1f}%"
)
# Alert on high values
steal_threshold = self.config.get("steal_threshold", 10)
io_threshold = self.config.get("io_threshold", 30)
if metrics.cpu_steal_percent > steal_threshold:
self.logger.warning(
f"High CPU steal time detected: {metrics.cpu_steal_percent:.2f}%"
)
if metrics.iowait_percent > io_threshold:
self.logger.warning(
f"High I/O wait detected: {metrics.iowait_percent:.2f}%"
)
def _check_memory_threshold(self, metrics: ResourceMetrics):
"""Check if memory usage exceeds threshold"""
memory_threshold = self.config.get("memory_threshold", 90)
if metrics.memory_percent >= memory_threshold:
self.logger.warning(
f"Memory usage critical: {metrics.memory_percent:.1f}% "
f"(threshold: {memory_threshold}%)"
)
# Find highest OOM process
process_info = self._find_highest_oom_process()
if process_info:
pid, cmdline, oom_score = process_info
self.logger.critical(
f"Highest OOM Score Process: PID={pid}, "
f"OOM_Score={oom_score}, Command={cmdline}"
)
# Also write to separate OOM log
self._log_oom_event(pid, cmdline, oom_score, metrics.memory_percent)
def _log_oom_event(self, pid: int, cmdline: str, oom_score: int, memory_percent: float):
"""Log OOM events to a dedicated file"""
try:
oom_log_path = "/var/log/sysmon-oom-events.log"
with open(oom_log_path, 'a') as f:
timestamp = datetime.now().isoformat()
event = {
"timestamp": timestamp,
"pid": pid,
"command": cmdline,
"oom_score": oom_score,
"memory_percent": memory_percent
}
f.write(json.dumps(event) + '\n')
except Exception as e:
self.logger.error(f"Error logging OOM event: {e}")
def run(self):
"""Main daemon loop"""
self.logger.info("Starting system resource monitoring daemon")
check_interval = self.config.get("check_interval", 5)
try:
while self.running:
metrics = self._get_metrics()
if metrics:
self._log_metrics(metrics)
self._check_memory_threshold(metrics)
time.sleep(check_interval)
except KeyboardInterrupt:
self.logger.info("Daemon interrupted by user")
except Exception as e:
self.logger.error(f"Unexpected error in daemon loop: {e}", exc_info=True)
finally:
self.logger.info("System resource monitoring daemon stopped")
def start(self):
"""Start the daemon"""
self._write_pid_file()
self.run()
def stop(self):
"""Stop the daemon"""
self.running = False
self._remove_pid_file()
def _write_pid_file(self):
"""Write PID to file"""
try:
pid_dir = os.path.dirname(DEFAULT_PID_FILE)
os.makedirs(pid_dir, exist_ok=True)
with open(DEFAULT_PID_FILE, 'w') as f:
f.write(str(os.getpid()))
except Exception as e:
self.logger.error(f"Error writing PID file: {e}")
def _remove_pid_file(self):
"""Remove PID file"""
try:
Path(DEFAULT_PID_FILE).unlink(missing_ok=True)
except Exception as e:
self.logger.error(f"Error removing PID file: {e}")
def main():
"""Main entry point"""
if len(sys.argv) > 1:
config_path = sys.argv[1]
else:
config_path = DEFAULT_CONFIG_PATH
monitor = SystemResourceMonitor(config_path)
monitor.start()
if __name__ == '__main__':
main()
2. Configuration File
{
"check_interval": 5,
"memory_threshold": 90,
"steal_threshold": 10,
"io_threshold": 30,
"log_level": "INFO",
"collect_cpu_data_points": 10
}
Save as: /etc/sysmon-daemon/config.json
3. Systemd Service File
[Unit]
Description=System Resource Monitoring Daemon
After=network.target
Documentation=man:sysmon-daemon(8)
[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/sysmon-daemon
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=10s
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=sysmon-daemon
# Security
PrivateTmp=yes
NoNewPrivileges=true
# Resource limits
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
Save as: /etc/systemd/system/sysmon-daemon.service
4. Installation Script
#!/bin/bash
# install.sh - Install system resource monitoring daemon
set -e
INSTALL_USER="root"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Create directories
sudo mkdir -p /etc/sysmon-daemon
sudo mkdir -p /var/log
# Install main script
sudo cp sysmon_daemon.py /usr/local/bin/sysmon-daemon
sudo chmod +x /usr/local/bin/sysmon-daemon
# Install configuration
sudo cp config.json /etc/sysmon-daemon/config.json
sudo chmod 644 /etc/sysmon-daemon/config.json
# Install systemd service
sudo cp sysmon-daemon.service /etc/systemd/system/
sudo chmod 644 /etc/systemd/system/sysmon-daemon.service
# Reload systemd
sudo systemctl daemon-reload
echo "Installation complete!"
echo "Start daemon with: sudo systemctl start sysmon-daemon"
echo "Enable on boot with: sudo systemctl enable sysmon-daemon"
echo "View logs with: sudo journalctl -u sysmon-daemon -f"
5. Advanced Monitoring Script with Tests
#!/usr/bin/env python3
"""
Advanced monitoring utilities and testing
"""
import unittest
import time
from pathlib import Path
from sysmon_daemon import SystemResourceMonitor, CPUStats
class TestSystemResourceMonitor(unittest.TestCase):
"""Test cases for SystemResourceMonitor"""
def setUp(self):
"""Set up test fixtures"""
self.monitor = SystemResourceMonitor()
def test_parse_proc_stat(self):
"""Test /proc/stat parsing"""
stats = self.monitor._parse_proc_stat()
self.assertIsNotNone(stats)
self.assertGreater(stats.user, 0)
self.assertGreaterEqual(stats.steal, 0)
self.assertGreaterEqual(stats.iowait, 0)
def test_calculate_cpu_metrics(self):
"""Test CPU metrics calculation"""
# Get two samples
stats1 = self.monitor._parse_proc_stat()
time.sleep(0.5)
stats2 = self.monitor._parse_proc_stat()
steal, iowait = self.monitor._calculate_cpu_metrics(stats1, stats2)
self.assertGreaterEqual(steal, 0)
self.assertGreaterEqual(iowait, 0)
self.assertLess(steal, 100)
self.assertLess(iowait, 100)
def test_memory_stats(self):
"""Test memory statistics"""
mem_percent, mem_available = self.monitor._get_memory_stats()
self.assertGreater(mem_percent, 0)
self.assertLess(mem_percent, 101)
self.assertGreater(mem_available, 0)
def test_find_highest_oom_process(self):
"""Test finding highest OOM process"""
process_info = self.monitor._find_highest_oom_process()
self.assertIsNotNone(process_info)
pid, cmdline, oom_score = process_info
self.assertGreater(pid, 0)
self.assertIsInstance(cmdline, str)
self.assertGreaterEqual(oom_score, 0)
def test_get_process_oom_score(self):
"""Test individual process OOM score reading"""
import os
current_pid = os.getpid()
oom_score = self.monitor._get_process_oom_score(current_pid)
self.assertIsNotNone(oom_score)
self.assertGreaterEqual(oom_score, 0)
class MonitoringUtilities:
"""Utilities for interactive monitoring"""
@staticmethod
def display_cpu_stats():
"""Display current CPU stats"""
monitor = SystemResourceMonitor()
stats = monitor._parse_proc_stat()
print("Current CPU Statistics:")
print(f" User: {stats.user}")
print(f" Nice: {stats.nice}")
print(f" System: {stats.system}")
print(f" Idle: {stats.idle}")
print(f" I/O Wait: {stats.iowait}")
print(f" Steal: {stats.steal}")
print(f" IRQ: {stats.irq}")
print(f" Soft IRQ: {stats.softirq}")
@staticmethod
def display_top_oom_processes(count=10):
"""Display top OOM processes"""
monitor = SystemResourceMonitor()
oom_processes = []
for pid_dir in Path('/proc').iterdir():
if not pid_dir.is_dir():
continue
try:
pid = int(pid_dir.name)
except ValueError:
continue
oom_score = monitor._get_process_oom_score(pid)
if oom_score is None:
continue
try:
with open(f"/proc/{pid}/cmdline", 'rb') as f:
cmdline = f.read().decode('utf-8', errors='ignore')
cmdline = ' '.join(cmdline.split('\x00')).strip()
except:
cmdline = f"<PID {pid}>"
oom_processes.append((pid, cmdline, oom_score))
# Sort by OOM score
oom_processes.sort(key=lambda x: x[2], reverse=True)
print(f"\nTop {count} Processes by OOM Score:")
print(f"{'PID':<10} {'OOM Score':<12} Command")
print("-" * 80)
for pid, cmdline, oom_score in oom_processes[:count]:
# Truncate long commands
cmd_display = cmdline[:55] + "..." if len(cmdline) > 55 else cmdline
print(f"{pid:<10} {oom_score:<12} {cmd_display}")
@staticmethod
def monitor_live(duration=60, interval=5):
"""Live monitoring display"""
import os
monitor = SystemResourceMonitor()
print(f"Live Monitoring for {duration} seconds (updating every {interval}s)")
print("Press Ctrl+C to stop\n")
end_time = time.time() + duration
try:
while time.time() < end_time:
os.system('clear' if os.name == 'posix' else 'cls')
metrics = monitor._get_metrics()
if metrics:
print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
print(f"CPU Steal Time: {metrics.cpu_steal_percent:>6.2f}%")
print(f"I/O Wait Time: {metrics.iowait_percent:>6.2f}%")
print(f"Memory Usage: {metrics.memory_percent:>6.1f}%")
print(f"Memory Available: {metrics.memory_available / (1024**3):>5.1f} GB")
print(f"CPU Cores: {metrics.cpu_count:>6}")
time.sleep(interval)
except KeyboardInterrupt:
print("\n\nMonitoring stopped")
def main():
"""CLI interface"""
import argparse
parser = argparse.ArgumentParser(
description="System Resource Monitoring Utilities"
)
parser.add_argument(
'command',
choices=['cpu-stats', 'oom-processes', 'live', 'test'],
help='Command to execute'
)
parser.add_argument(
'--duration',
type=int,
default=60,
help='Duration for live monitoring (seconds)'
)
parser.add_argument(
'--interval',
type=int,
default=5,
help='Update interval (seconds)'
)
parser.add_argument(
'--count',
type=int,
default=10,
help='Number of processes to display'
)
args = parser.parse_args()
if args.command == 'cpu-stats':
MonitoringUtilities.display_cpu_stats()
elif args.command == 'oom-processes':
MonitoringUtilities.display_top_oom_processes(args.count)
elif args.command == 'live':
MonitoringUtilities.monitor_live(args.duration, args.interval)
elif args.command == 'test':
unittest.main(argv=[''], exit=False)
if __name__ == '__main__':
from datetime import datetime
main()
6. Usage Guide
Installation
# Make scripts executable
chmod +x install.sh
# Run installation
sudo ./install.sh
# Install Python dependencies
sudo pip install psutil
System Commands
# Start the daemon
sudo systemctl start sysmon-daemon
# Stop the daemon
sudo systemctl stop sysmon-daemon
# Enable on boot
sudo systemctl enable sysmon-daemon
# View logs
sudo journalctl -u sysmon-daemon -f
# View OOM events
sudo tail -f /var/log/sysmon-oom-events.log
# Check daemon status
sudo systemctl status sysmon-daemon
Monitoring Utilities
# Display current CPU statistics
python3 monitoring_utils.py cpu-stats
# Show top 10 OOM processes
python3 monitoring_utils.py oom-processes --count 20
# Live monitoring for 5 minutes
python3 monitoring_utils.py live --duration 300 --interval 5
# Run tests
python3 monitoring_utils.py test
7. Log Output Examples
2024-01-15 14:23:45 - __main__ - INFO - SystemResourceMonitor initialized
2024-01-15 14:23:50 - __main__ - INFO - CPU Steal: 0.15% | I/O Wait: 2.34% | Memory: 65.3%
2024-01-15 14:24:10 - __main__ - WARNING - Memory usage critical: 91.2% (threshold: 90%)
2024-01-15 14:24:10 - __main__ - CRITICAL - Highest OOM Score Process: PID=1234, OOM_Score=856, Command=/usr/bin/python3 /app/memory_hog.py
OOM Events Log:
{"timestamp": "2024-01-15T14:24:10.123456", "pid": 1234, "command": "/usr/bin/python3 /app/memory_hog.py", "oom_score": 856, "memory_percent": 91.2}
Key Features:
✅ Real-time CPU steal and I/O wait monitoring
✅ Memory threshold alerts
✅ OOM process identification
✅ Systemd integration
✅ Comprehensive logging
✅ Configuration file support
✅ Unit tests
✅ Interactive CLI utilities
✅ Production-ready error handling