<?php
/**
* Teardown function for message queue processes.
*
* This function iterates through configured message queues and gracefully
* terminates their associated processes. Includes defensive checks
* to prevent errors and ensure proper cleanup.
*/
function teardownMessageQueues(): void
{
// Configuration: Replace with your actual queue configuration.
$queues = [
'queue1' => ['process_path' => '/usr/local/bin/queue1', 'pid_file' => '/var/run/queue1.pid'],
'queue2' => ['process_path' => '/usr/local/bin/queue2', 'pid_file' => '/var/run/queue2.pid'],
];
foreach ($queues as $queueName => $queueConfig) {
$processPath = $queueConfig['process_path'];
$pidFile = $queueConfig['pid_file'];
// Defensive check: Ensure process path exists.
if (!file_exists($processPath)) {
error_log("ERROR: Process path '$processPath' does not exist for queue '$queueName'. Skipping.");
continue;
}
// Defensive check: Ensure PID file exists.
if (!file_exists($pidFile)) {
error_log("WARNING: PID file '$pidFile' does not exist for queue '$queueName'. Skipping.");
continue;
}
// Read the PID from the PID file.
if (file_exists($pidFile)) {
$pid = (int) file_get_contents($pidFile); // Cast to integer for safety.
} else {
error_log("ERROR: Could not read PID from '$pidFile' for queue '$queueName'. Skipping.");
continue;
}
// Check if the process exists.
if (ps($pid)) { // Using ps() to check if PID is valid
try {
// Terminate the process gracefully.
echo "Terminating process '$queueName' (PID: $pid)...\n";
kill($pid, SIGTERM); // Send SIGTERM first
usleep(500000); // Wait 0.5 seconds for graceful shutdown
if (kill($pid, SIGKILL) === false) {
error_log("ERROR: Failed to kill process '$queueName' (PID: $pid) using SIGKILL.");
} else {
echo "Process '$queueName' (PID: $pid) terminated successfully.\n";
}
} catch (Exception $e) {
error_log("ERROR: Exception occurred while terminating process '$queueName' (PID: $pid): " . $e->getMessage());
}
} else {
echo "Process '$queueName' (PID: $pid) does not exist. Skipping.\n";
}
}
echo "Message queue teardown completed.\n";
}
// Example usage:
// teardownMessageQueues();
?>
Add your comment