File size: 7,405 Bytes
a7ae6b9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
#!/usr/bin/env python3
"""
Elizabeth Training Monitor
Monitors training processes and automatically restarts if needed
"""
import os
import sys
import time
import subprocess
import signal
import logging
from datetime import datetime
from pathlib import Path
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('/workspace/elizabeth_logs/training_monitor.log'),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
class TrainingMonitor:
"""Monitor and manage Elizabeth training processes"""
def __init__(self):
self.training_script = "/workspace/elizabeth-repo/src/elizabeth_main.py"
self.max_restarts = 10
self.restart_delay = 30 # seconds
self.process = None
self.restart_count = 0
# Ensure logs directory exists
os.makedirs("/workspace/elizabeth_logs", exist_ok=True)
def start_training(self):
"""Start the training process"""
try:
logger.info("Starting Elizabeth training session...")
# Start Elizabeth in interactive mode with enhanced capabilities
self.process = subprocess.Popen(
[
sys.executable, self.training_script,
"--interactive",
"--version", "v0.0.2"
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
logger.info(f"Training process started with PID: {self.process.pid}")
return True
except Exception as e:
logger.error(f"Failed to start training: {e}")
return False
def monitor_process(self):
"""Monitor the training process and handle output"""
try:
# Monitor stdout and stderr
while True:
if self.process.stdout:
output = self.process.stdout.readline()
if output:
logger.info(f"TRAINING: {output.strip()}")
if self.process.stderr:
error = self.process.stderr.readline()
if error:
logger.error(f"TRAINING_ERROR: {error.strip()}")
# Check if process is still alive
return_code = self.process.poll()
if return_code is not None:
logger.warning(f"Training process exited with code: {return_code}")
return return_code
time.sleep(1)
except Exception as e:
logger.error(f"Monitoring error: {e}")
return -1
def graceful_shutdown(self):
"""Gracefully shutdown the training process"""
if self.process:
try:
logger.info("Sending graceful shutdown signal...")
self.process.terminate()
# Wait for process to terminate
for _ in range(10):
if self.process.poll() is not None:
break
time.sleep(1)
# Force kill if still running
if self.process.poll() is None:
logger.warning("Process not terminating, forcing kill...")
self.process.kill()
logger.info("Training process shutdown complete")
except Exception as e:
logger.error(f"Shutdown error: {e}")
def run_monitoring_loop(self):
"""Main monitoring loop with automatic restarts"""
logger.info("🚀 Starting Elizabeth Training Monitor")
logger.info(f"Max restarts: {self.max_restarts}")
logger.info(f"Restart delay: {self.restart_delay}s")
while self.restart_count <= self.max_restarts:
try:
# Start training
if not self.start_training():
logger.error("Failed to start training process")
break
# Monitor process
return_code = self.monitor_process()
# Check if we should restart
if return_code == 0:
logger.info("Training completed successfully")
break
elif self.restart_count < self.max_restarts:
self.restart_count += 1
logger.warning(f"Restarting training ({self.restart_count}/{self.max_restarts})...")
logger.info(f"Waiting {self.restart_delay} seconds before restart...")
time.sleep(self.restart_delay)
else:
logger.error("Max restart attempts reached")
break
except KeyboardInterrupt:
logger.info("Received interrupt signal, shutting down...")
break
except Exception as e:
logger.error(f"Unexpected error in monitoring loop: {e}")
self.restart_count += 1
if self.restart_count <= self.max_restarts:
logger.info(f"Restarting after error... ({self.restart_count}/{self.max_restarts})")
time.sleep(self.restart_delay)
else:
break
# Cleanup
self.graceful_shutdown()
logger.info("Training monitor shutting down")
def get_status(self):
"""Get current monitoring status"""
return {
"restart_count": self.restart_count,
"max_restarts": self.max_restarts,
"process_active": self.process and self.process.poll() is None,
"process_pid": self.process.pid if self.process else None,
"timestamp": datetime.now().isoformat()
}
def main():
"""Command line interface"""
import argparse
parser = argparse.ArgumentParser(description="Elizabeth Training Monitor")
parser.add_argument("--start", action="store_true", help="Start monitoring")
parser.add_argument("--status", action="store_true", help="Show status")
parser.add_argument("--stop", action="store_true", help="Stop monitoring")
parser.add_argument("--max-restarts", type=int, default=10, help="Max restart attempts")
parser.add_argument("--restart-delay", type=int, default=30, help="Restart delay in seconds")
args = parser.parse_args()
monitor = TrainingMonitor()
monitor.max_restarts = args.max_restarts
monitor.restart_delay = args.restart_delay
if args.start:
monitor.run_monitoring_loop()
elif args.status:
status = monitor.get_status()
print("Training Monitor Status:")
for key, value in status.items():
print(f" {key}: {value}")
elif args.stop:
monitor.graceful_shutdown()
print("Shutdown signal sent")
else:
print("No action specified. Use --help for options.")
if __name__ == "__main__":
main() |