1. <?php
  2. /**
  3. * Teardown function for message queue processes.
  4. *
  5. * This function iterates through configured message queues and gracefully
  6. * terminates their associated processes. Includes defensive checks
  7. * to prevent errors and ensure proper cleanup.
  8. */
  9. function teardownMessageQueues(): void
  10. {
  11. // Configuration: Replace with your actual queue configuration.
  12. $queues = [
  13. 'queue1' => ['process_path' => '/usr/local/bin/queue1', 'pid_file' => '/var/run/queue1.pid'],
  14. 'queue2' => ['process_path' => '/usr/local/bin/queue2', 'pid_file' => '/var/run/queue2.pid'],
  15. ];
  16. foreach ($queues as $queueName => $queueConfig) {
  17. $processPath = $queueConfig['process_path'];
  18. $pidFile = $queueConfig['pid_file'];
  19. // Defensive check: Ensure process path exists.
  20. if (!file_exists($processPath)) {
  21. error_log("ERROR: Process path '$processPath' does not exist for queue '$queueName'. Skipping.");
  22. continue;
  23. }
  24. // Defensive check: Ensure PID file exists.
  25. if (!file_exists($pidFile)) {
  26. error_log("WARNING: PID file '$pidFile' does not exist for queue '$queueName'. Skipping.");
  27. continue;
  28. }
  29. // Read the PID from the PID file.
  30. if (file_exists($pidFile)) {
  31. $pid = (int) file_get_contents($pidFile); // Cast to integer for safety.
  32. } else {
  33. error_log("ERROR: Could not read PID from '$pidFile' for queue '$queueName'. Skipping.");
  34. continue;
  35. }
  36. // Check if the process exists.
  37. if (ps($pid)) { // Using ps() to check if PID is valid
  38. try {
  39. // Terminate the process gracefully.
  40. echo "Terminating process '$queueName' (PID: $pid)...\n";
  41. kill($pid, SIGTERM); // Send SIGTERM first
  42. usleep(500000); // Wait 0.5 seconds for graceful shutdown
  43. if (kill($pid, SIGKILL) === false) {
  44. error_log("ERROR: Failed to kill process '$queueName' (PID: $pid) using SIGKILL.");
  45. } else {
  46. echo "Process '$queueName' (PID: $pid) terminated successfully.\n";
  47. }
  48. } catch (Exception $e) {
  49. error_log("ERROR: Exception occurred while terminating process '$queueName' (PID: $pid): " . $e->getMessage());
  50. }
  51. } else {
  52. echo "Process '$queueName' (PID: $pid) does not exist. Skipping.\n";
  53. }
  54. }
  55. echo "Message queue teardown completed.\n";
  56. }
  57. // Example usage:
  58. // teardownMessageQueues();
  59. ?>

Add your comment