Here's a comprehensive Python script that meets your requirements:
#!/usr/bin/env python3
"""
Persistent System Monitor with Inter-Process Communication
Runs continuously, monitors system resources, and can be controlled by other processes.
"""
import os
import sys
import time
import json
import signal
import logging
import threading
import multiprocessing
from datetime import datetime
from pathlib import Path
import psutil
import socket
from contextlib import contextmanager
class SystemMonitor:
def __init__(self, config_file='/etc/sysmonitor/config.json'):
self.config = self.load_config(config_file)
self.running = True
self.paused = False
# Setup logging
self.setup_logging()
# IPC mechanisms
self.setup_ipc()
# Signal handlers
signal.signal(signal.SIGTERM, self.signal_handler)
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGUSR1, self.toggle_pause)
self.logger.info("SystemMonitor initialized")
def load_config(self, config_file):
"""Load configuration from JSON file"""
default_config = {
"monitor_interval": 30, # seconds
"socket_path": "/tmp/sysmonitor.sock",
"log_file": "/var/log/sysmonitor.log",
"pid_file": "/var/run/sysmonitor.pid",
"thresholds": {
"cpu_warning": 80,
"memory_warning": 85,
"disk_warning": 90
}
}
try:
if os.path.exists(config_file):
with open(config_file, 'r') as f:
config = json.load(f)
# Merge with defaults
for key, value in default_config.items():
if key not in config:
config[key] = value
return config
except Exception as e:
print(f"Error loading config: {e}, using defaults")
return default_config
def setup_logging(self):
"""Setup logging configuration"""
log_dir = os.path.dirname(self.config['log_file'])
os.makedirs(log_dir, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(self.config['log_file']),
logging.StreamHandler(sys.stdout)
]
)
self.logger = logging.getLogger('SystemMonitor')
def setup_ipc(self):
"""Setup Inter-Process Communication mechanisms"""
# Unix domain socket for command interface
self.socket_path = self.config['socket_path']
if os.path.exists(self.socket_path):
os.unlink(self.socket_path)
self.server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.server_socket.bind(self.socket_path)
self.server_socket.listen(5)
self.server_socket.settimeout(1.0) # Non-blocking with timeout
# Shared memory for status
self.status_lock = threading.Lock()
self.status = {
'running': True,
'paused': False,
'last_update': None,
'system_stats': {}
}
def write_pid_file(self):
"""Write process ID to PID file"""
pid_dir = os.path.dirname(self.config['pid_file'])
os.makedirs(pid_dir, exist_ok=True)
with open(self.config['pid_file'], 'w') as f:
f.write(str(os.getpid()))
def cleanup_pid_file(self):
"""Remove PID file"""
try:
os.unlink(self.config['pid_file'])
except FileNotFoundError:
pass
def signal_handler(self, signum, frame):
"""Handle termination signals"""
self.logger.info(f"Received signal {signum}, shutting down...")
self.running = False
def toggle_pause(self, signum, frame):
"""Toggle pause state via SIGUSR1"""
self.paused = not self.paused
state = "paused" if self.paused else "resumed"
self.logger.info(f"Monitor {state} via signal")
def get_system_stats(self):
"""Collect system resource statistics"""
try:
stats = {
'timestamp': datetime.now().isoformat(),
'cpu': {
'percent': psutil.cpu_percent(interval=1),
'count': psutil.cpu_count(),
'load_avg': os.getloadavg() if hasattr(os, 'getloadavg') else None
},
'memory': {
'percent': psutil.virtual_memory().percent,
'available': psutil.virtual_memory().available,
'total': psutil.virtual_memory().total,
'used': psutil.virtual_memory().used
},
'disk': {
'percent': psutil.disk_usage('/').percent,
'free': psutil.disk_usage('/').free,
'total': psutil.disk_usage('/').total
},
'network': {
'bytes_sent': psutil.net_io_counters().bytes_sent,
'bytes_recv': psutil.net_io_counters().bytes_recv,
'packets_sent': psutil.net_io_counters().packets_sent,
'packets_recv': psutil.net_io_counters().packets_recv
}
}
# Check thresholds and log warnings
self.check_thresholds(stats)
return stats
except Exception as e:
self.logger.error(f"Error collecting system stats: {e}")
return None
def check_thresholds(self, stats):
"""Check if any metrics exceed warning thresholds"""
thresholds = self.config['thresholds']
if stats['cpu']['percent'] > thresholds['cpu_warning']:
self.logger.warning(f"High CPU usage: {stats['cpu']['percent']:.1f}%")
if stats['memory']['percent'] > thresholds['memory_warning']:
self.logger.warning(f"High memory usage: {stats['memory']['percent']:.1f}%")
if stats['disk']['percent'] > thresholds['disk_warning']:
self.logger.warning(f"High disk usage: {stats['disk']['percent']:.1f}%")
def handle_client_connection(self, client_socket):
"""Handle incoming client connections"""
try:
data = client_socket.recv(1024).decode('utf-8')
command = json.loads(data)
response = self.process_command(command)
client_socket.send(json.dumps(response).encode('utf-8'))
except Exception as e:
error_response = {'status': 'error', 'message': str(e)}
client_socket.send(json.dumps(error_response).encode('utf-8'))
finally:
client_socket.close()
def process_command(self, command):
"""Process commands from other processes"""
cmd_type = command.get('type', '')
if cmd_type == 'status':
with self.status_lock:
return {
'status': 'success',
'data': self.status.copy()
}
elif cmd_type == 'pause':
self.paused = True
self.logger.info("Monitor paused via command")
return {'status': 'success', 'message': 'Monitor paused'}
elif cmd_type == 'resume':
self.paused = False
self.logger.info("Monitor resumed via command")
return {'status': 'success', 'message': 'Monitor resumed'}
elif cmd_type == 'stop':
self.running = False
self.logger.info("Stop command received")
return {'status': 'success', 'message': 'Stopping monitor'}
elif cmd_type == 'stats':
stats = self.get_system_stats()
return {'status': 'success', 'data': stats}
else:
return {'status': 'error', 'message': f'Unknown command: {cmd_type}'}
def monitor_loop(self):
"""Main monitoring loop with regular intervals"""
while self.running:
if not self.paused:
# Collect system statistics
stats = self.get_system_stats()
if stats:
with self.status_lock:
self.status['system_stats'] = stats
self.status['last_update'] = datetime.now().isoformat()
self.logger.info(f"CPU: {stats['cpu']['percent']:.1f}%, "
f"Memory: {stats['memory']['percent']:.1f}%, "
f"Disk: {stats['disk']['percent']:.1f}%")
# Custom monitoring tasks can be added here
self.custom_monitoring_tasks()
# Blocking wait with timeout to release resources
self.wait_with_interruption(self.config['monitor_interval'])
def custom_monitoring_tasks(self):
"""Add your custom monitoring tasks here"""
# Example: Check specific processes, services, etc.
pass
def wait_with_interruption(self, timeout):
"""Wait with ability to be interrupted by IPC"""
start_time = time.time()
while time.time() - start_time < timeout and self.running:
# Check for incoming connections (non-blocking)
try:
client_socket, address = self.server_socket.accept()
# Handle in separate thread to avoid blocking
client_thread = threading.Thread(
target=self.handle_client_connection,
args=(client_socket,)
)
client_thread.daemon = True
client_thread.start()
except socket.timeout:
pass # No connection, continue waiting
except Exception as e:
self.logger.error(f"Socket error: {e}")
# Sleep briefly to release CPU
time.sleep(0.1)
def cleanup(self):
"""Cleanup resources"""
self.logger.info("Cleaning up resources...")
try:
self.server_socket.close()
except:
pass
try:
os.unlink(self.socket_path)
except:
pass
self.cleanup_pid_file()
def run(self):
"""Main run method"""
try:
self.write_pid_file()
self.logger.info("SystemMonitor started")
# Start the main monitoring loop
self.monitor_loop()
except Exception as e:
self.logger.error(f"Error in main loop: {e}")
finally:
self.cleanup()
self.logger.info("SystemMonitor stopped")
# Client utility functions for other processes
class SystemMonitorClient:
def __init__(self, socket_path='/tmp/sysmonitor.sock'):
self.socket_path = socket_path
def send_command(self, command):
"""Send command to the monitor process"""
try:
client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client_socket.connect(self.socket_path)
client_socket.send(json.dumps(command).encode('utf-8'))
response = client_socket.recv(4096).decode('utf-8')
client_socket.close()
return json.loads(response)
except Exception as e:
return {'status': 'error', 'message': str(e)}
def get_status(self):
return self.send_command({'type': 'status'})
def pause(self):
return self.send_command({'type': 'pause'})
def resume(self):
return self.send_command({'type': 'resume'})
def stop(self):
return self.send_command({'type': 'stop'})
def get_stats(self):
return self.send_command({'type': 'stats'})
if __name__ == '__main__':
# Install required package if not present
try:
import psutil
except ImportError:
print("Installing required package: psutil")
os.system("pip3 install psutil")
import psutil
monitor = SystemMonitor()
monitor.run()
Now, here's how to configure the system to run this script at boot time:
System Configuration for Boot-time Execution
1. Create the systemd service file:
sudo nano /etc/systemd/system/sysmonitor.service
Add the following content:
[Unit]
Description=System Monitor Service
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
Group=root
ExecStart=/usr/bin/python3 /opt/sysmonitor/sysmonitor.py
ExecReload=/bin/kill -USR1 $MAINPID
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=sysmonitor
# Security settings
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/log /var/run /tmp /etc/sysmonitor
[Install]
WantedBy=multi-user.target
2. Setup directories and files:
# Create directories
sudo mkdir -p /opt/sysmonitor
sudo mkdir -p /etc/sysmonitor
sudo mkdir -p /var/log/sysmonitor
# Copy the script
sudo cp sysmonitor.py /opt/sysmonitor/
sudo chmod +x /opt/sysmonitor/sysmonitor.py
# Create configuration file
sudo nano /etc/sysmonitor/config.json
Configuration file content:
{
"monitor_interval": 30,
"socket_path": "/tmp/sysmonitor.sock",
"log_file": "/var/log/sysmonitor/sysmonitor.log",
"pid_file": "/var/run/sysmonitor.pid",
"thresholds": {
"cpu_warning": 80,
"memory_warning": 85,
"disk_warning": 90
}
}
3. Install dependencies and enable service:
# Install Python package
sudo pip3 install psutil
# Enable and start the service
sudo systemctl daemon-reload
sudo systemctl enable sysmonitor.service
sudo systemctl start sysmonitor.service
# Check status
sudo systemctl status sysmonitor.service
4. Example client script to interact with the monitor:
#!/usr/bin/env python3
"""
Example client to interact with the system monitor
"""
from sysmonitor import SystemMonitorClient
def main():
client = SystemMonitorClient()
# Get current status
status = client.get_status()
print("Status:", status)
# Get system statistics
stats = client.get_stats()
print("Stats:", stats)
# Pause monitoring
# client.pause()
# Resume monitoring
# client.resume()
if __name__ == '__main__':
main()
Key Features Explained:
- Main Loop with Regular Intervals: The
monitor_loop() method runs continuously, collecting system stats at configurable intervals.