refactor: consolidate metric collection into single SSH calls and add support for SSH key authentication
This commit is contained in:
+14
-2
@@ -25,15 +25,27 @@ ini_set('display_errors', 1);
|
||||
ini_set('log_errors', 1);
|
||||
ini_set('error_log', '/var/log/metrics_collector_errors.log');
|
||||
|
||||
// Prevent multiple instances using flock (#42)
|
||||
$lockFile = '/var/run/collect_metrics.lock';
|
||||
$lockFp = fopen($lockFile, 'w');
|
||||
if (!$lockFp || !flock($lockFp, LOCK_EX | LOCK_NB)) {
|
||||
echo "[" . date('Y-m-d H:i:s') . "] Another collector instance is already running. Exiting.\n";
|
||||
exit(0);
|
||||
}
|
||||
|
||||
// Write PID file for monitoring
|
||||
$pidFile = '/var/run/collect_metrics.pid';
|
||||
file_put_contents($pidFile, getmypid());
|
||||
|
||||
// Register shutdown function to clean up PID file
|
||||
register_shutdown_function(function() use ($pidFile) {
|
||||
// Register shutdown function to clean up PID and lock files
|
||||
register_shutdown_function(function() use ($pidFile, $lockFp, $lockFile) {
|
||||
if (file_exists($pidFile)) {
|
||||
unlink($pidFile);
|
||||
}
|
||||
if ($lockFp) {
|
||||
flock($lockFp, LOCK_UN);
|
||||
fclose($lockFp);
|
||||
}
|
||||
});
|
||||
|
||||
echo "[" . date('Y-m-d H:i:s') . "] Metrics collector started (PID: " . getmypid() . ")\n";
|
||||
|
||||
Regular → Executable
+15
@@ -2,15 +2,24 @@
|
||||
|
||||
# Monitor and restart metrics collector if it's not running
|
||||
# This script checks if collect_metrics.php is running and restarts it if needed
|
||||
# Uses flock to prevent multiple instances (#42)
|
||||
|
||||
SCRIPT_PATH="/var/www/html/bin/collect_metrics.php"
|
||||
LOG_FILE="/var/log/metrics_monitor.log"
|
||||
PID_FILE="/var/run/collect_metrics.pid"
|
||||
LOCK_FILE="/var/run/collect_metrics.lock"
|
||||
|
||||
log_message() {
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
|
||||
}
|
||||
|
||||
# Use flock to prevent multiple monitor instances
|
||||
exec 200>"$LOCK_FILE"
|
||||
if ! flock -n 200; then
|
||||
log_message "Another monitor instance is running, exiting"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Check if the process is running
|
||||
is_running() {
|
||||
if [ -f "$PID_FILE" ]; then
|
||||
@@ -22,6 +31,12 @@ is_running() {
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
# Also check if any collect_metrics.php is running (catches orphan processes)
|
||||
if pgrep -f "collect_metrics.php" > /dev/null 2>&1; then
|
||||
# Update PID file with actual PID
|
||||
pgrep -f "collect_metrics.php" | head -1 > "$PID_FILE"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user