I'll provide you with a comprehensive Python script that meets all your requirements, along with instructions for configuring it to run at boot time on Ubuntu.
Python Script
#!/usr/bin/env python3
"""
Persistent service with async unblocking and system monitoring
"""
import os
import sys
import time
import socket
import select
import threading
import json
import logging
from datetime import datetime
from pathlib import Path
import psutil
# Configuration
SOCKET_PATH = "/tmp/service_control.sock"
LOG_FILE = "/var/log/persistent_service.log"
MONITOR_INTERVAL = 60 # seconds
TASK_INTERVAL = 300 # seconds (5 minutes)
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(LOG_FILE),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
class SystemMonitor:
"""Monitor system resources"""
def __init__(self):
self.cpu_count = psutil.cpu_count()
self.net_counters_prev = psutil.net_io_counters()
self.monitor_start_time = time.time()
def get_system_stats(self):
"""Collect current system statistics"""
# CPU utilization
cpu_percent = psutil.cpu_percent(interval=1)
cpu_per_core = psutil.cpu_percent(interval=0, percpu=True)
# Memory utilization
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
# Network utilization
net_counters = psutil.net_io_counters()
time_delta = time.time() - self.monitor_start_time
# Calculate network rates
bytes_sent_rate = (net_counters.bytes_sent - self.net_counters_prev.bytes_sent) / time_delta
bytes_recv_rate = (net_counters.bytes_recv - self.net_counters_prev.bytes_recv) / time_delta
# Update previous counters
self.net_counters_prev = net_counters
self.monitor_start_time = time.time()
# Disk usage
disk_usage = {}
for partition in psutil.disk_partitions():
if partition.mountpoint in ['/', '/home']:
usage = psutil.disk_usage(partition.mountpoint)
disk_usage[partition.mountpoint] = {
'total': usage.total,
'used': usage.used,
'free': usage.free,
'percent': usage.percent
}
return {
'timestamp': datetime.now().isoformat(),
'cpu': {
'percent': cpu_percent,
'per_core': cpu_per_core,
'count': self.cpu_count
},
'memory': {
'total': memory.total,
'available': memory.available,
'percent': memory.percent,
'used': memory.used,
'free': memory.free
},
'swap': {
'total': swap.total,
'used': swap.used,
'free': swap.free,
'percent': swap.percent
},
'network': {
'bytes_sent_rate': bytes_sent_rate,
'bytes_recv_rate': bytes_recv_rate,
'packets_sent': net_counters.packets_sent,
'packets_recv': net_counters.packets_recv
},
'disk': disk_usage
}
class PersistentService:
"""Main service class with blocking wait and async unblocking"""
def __init__(self):
self.running = True
self.socket_server = None
self.monitor = SystemMonitor()
self.last_task_time = 0
self.last_monitor_time = 0
self.setup_socket()
def setup_socket(self):
"""Setup Unix domain socket for IPC"""
# Remove socket file if it exists
if os.path.exists(SOCKET_PATH):
os.unlink(SOCKET_PATH)
# Create socket
self.socket_server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.socket_server.bind(SOCKET_PATH)
self.socket_server.listen(5)
self.socket_server.setblocking(False)
# Set permissions
os.chmod(SOCKET_PATH, 0o666)
logger.info(f"Socket server listening on {SOCKET_PATH}")
def handle_command(self, command):
"""Handle commands received via socket"""
logger.info(f"Received command: {command}")
if command == "STOP":
self.running = False
return "Service stopping"
elif command == "STATUS":
return json.dumps({
"running": self.running,
"uptime": time.time() - self.start_time,
"last_task": self.last_task_time,
"last_monitor": self.last_monitor_time
})
elif command == "STATS":
return json.dumps(self.monitor.get_system_stats())
elif command == "TRIGGER_TASK":
self.execute_scheduled_task()
return "Task triggered"
else:
return f"Unknown command: {command}"
def execute_scheduled_task(self):
"""Execute the scheduled task - override or extend this method"""
logger.info("Executing scheduled task")
# Example tasks - replace with your actual tasks
try:
# Task 1: Log system status
stats = self.monitor.get_system_stats()
logger.info(f"System stats: CPU={stats['cpu']['percent']}%, "
f"Memory={stats['memory']['percent']}%")
# Task 2: Cleanup temporary files (example)
# self.cleanup_temp_files()
# Task 3: Send heartbeat to monitoring service (example)
# self.send_heartbeat()
self.last_task_time = time.time()
except Exception as e:
logger.error(f"Error in scheduled task: {e}")
def monitor_system(self):
"""Log system statistics"""
try:
stats = self.monitor.get_system_stats()
logger.info(f"System Monitor: {json.dumps(stats, indent=2)}")
self.last_monitor_time = time.time()
except Exception as e:
logger.error(f"Error monitoring system: {e}")
def main_loop(self):
"""Main service loop with blocking wait"""
self.start_time = time.time()
logger.info("Service started")
while self.running:
current_time = time.time()
# Check if it's time to run scheduled task
if current_time - self.last_task_time >= TASK_INTERVAL:
self.execute_scheduled_task()
# Check if it's time to monitor system
if current_time - self.last_monitor_time >= MONITOR_INTERVAL:
self.monitor_system()
# Calculate time until next event
time_to_task = TASK_INTERVAL - (current_time - self.last_task_time)
time_to_monitor = MONITOR_INTERVAL - (current_time - self.last_monitor_time)
timeout = min(time_to_task, time_to_monitor, 1.0)
# Blocking wait with select (releases CPU)
try:
# Wait for socket activity or timeout
readable, _, _ = select.select([self.socket_server], [], [], timeout)
if readable:
# Handle incoming connection
conn, addr = self.socket_server.accept()
try:
data = conn.recv(1024).decode('utf-8').strip()
response = self.handle_command(data)
conn.send(response.encode('utf-8'))
except Exception as e:
logger.error(f"Error handling connection: {e}")
finally:
conn.close()
except Exception as e:
logger.error(f"Error in main loop: {e}")
def cleanup(self):
"""Cleanup resources"""
logger.info("Cleaning up...")
if self.socket_server:
self.socket_server.close()
if os.path.exists(SOCKET_PATH):
os.unlink(SOCKET_PATH)
def main():
"""Main entry point"""
service = PersistentService()
try:
service.main_loop()
except KeyboardInterrupt:
logger.info("Received interrupt signal")
except Exception as e:
logger.error(f"Unexpected error: {e}")
finally:
service.cleanup()
logger.info("Service stopped")
if __name__ == "__main__":
main()
Client Script to Control the Service
Create a control script to interact with the service:
#!/usr/bin/env python3
"""
Client to control the persistent service
"""
import socket
import sys
import json
SOCKET_PATH = "/tmp/service_control.sock"
def send_command(command):
"""Send command to the service"""
try:
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect(SOCKET_PATH)
client.send(command.encode('utf-8'))
response = client.recv(4096).decode('utf-8')
client.close()
return response
except Exception as e:
return f"Error: {e}"
def main():
if len(sys.argv) < 2:
print("Usage: service_control.py <command>")
print("Commands: STOP, STATUS, STATS, TRIGGER_TASK")
sys.exit(1)
command = sys.argv[1].upper()
response = send_command(command)
# Pretty print JSON responses
try:
data = json.loads(response)
print(json.dumps(data, indent=2))
except:
print(response)
if __name__ == "__main__":
main()
System Configuration for Boot-Time Execution
1. Install Required Dependencies
sudo apt update
sudo apt install python3-pip
sudo pip3 install psutil
2. Create Service Files
Create the main service script:
sudo mkdir -p /opt/persistent-service
sudo cp persistent_service.py /opt/persistent-service/
sudo cp service_control.py /opt/persistent-service/
sudo chmod +x /opt/persistent-service/*.py
3. Create Systemd Service Unit
Create /etc/systemd/system/persistent-service.service:
[Unit]
Description=Persistent Python Service with System Monitoring
After=network.target
[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/opt/persistent-service
ExecStart=/usr/bin/python3 /opt/persistent-service/persistent_service.py
Restart=always
RestartSec=10
# Security options (optional but recommended)
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/tmp /var/log
# Resource limits (optional)
CPUQuota=50%
MemoryMax=512M
# Environment variables
Environment="PYTHONUNBUFFERED=1"
[Install]
WantedBy=multi-user.target
4. Enable and Start the Service
# Reload systemd
sudo systemctl daemon-reload
# Enable service to start at boot
sudo systemctl enable persistent-service.service
# Start the service
sudo systemctl start persistent-service.service
# Check service status
sudo systemctl status persistent-service.service
# View logs
sudo journalctl -u persistent-service.service -f
5. Create Log Rotation Configuration
Create /etc/logrotate.d/persistent-service:
/var/log/persistent_service.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0644 root root
}
Usage Examples
Control the service from other Python programs or command line:
# Check service status
/opt/persistent-service/service_control.py STATUS
# Get system statistics
/opt/persistent-service/service_control.py STATS
# Trigger task execution
/opt/persistent-service/service_control.py TRIGGER_TASK
# Stop the service
/opt/persistent-service/service_control.py STOP
Key Features Explained
-
Main Loop with Blocking: The service uses select.select() which blocks until either a socket connection arrives or a timeout occurs, releasing CPU resources while waiting.
-
Asynchronous Unblocking: Other Python programs can send commands via Unix domain socket to unblock the service and trigger actions immediately.
-
System Monitoring: Uses the psutil library to monitor CPU, memory, network, and disk usage at regular intervals.
-
Resource Efficiency: The blocking wait ensures minimal CPU usage when idle, and the service only consumes resources when actively processing.
-
Boot-Time Execution: Systemd ensures the service starts automatically at boot and restarts if it crashes.
This architecture provides a robust, resource-efficient service that can be controlled asynchronously while continuously monitoring system resources.