tcms_monitor 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env perl
  2. use FindBin::libs;
  3. use FindBin;
  4. use Proc::Daemon;
  5. use strict;
  6. use warnings;
  7. use Trog::Autoreload;
  8. # Note that we do not reload ourselves.
  9. sub cleanup {
  10. unlink 'run/monitor.pid';
  11. return 0;
  12. };
  13. $SIG{HUP} = sub {
  14. print "Recieved signal from tcms master process, restarting.\n";
  15. cleanup();
  16. exec $0;
  17. };
  18. sub get_master_pid {
  19. # Get the PID of the current master process
  20. my $ppf = 'run/tcms.pid';
  21. my $ppid;
  22. if (-f $ppf) {
  23. open(my $pidfile, '<', $ppf);
  24. read($pidfile, $ppid, 10000);
  25. close $pidfile;
  26. chomp $ppid;
  27. if (!-d "/proc/$ppid") {
  28. print "tCMS not running, but left a PIDFile behind. Exiting monitor.\n";
  29. exit 0 if -f "/run/$ppid";
  30. }
  31. } else {
  32. print "tCMS not running, exiting monitor.\n";
  33. exit 0;
  34. }
  35. return $ppid;
  36. }
  37. sub main {
  38. my $pf = 'run/monitor.pid';
  39. my $monitor_pid = Trog::Autoreload::monitor_pid();
  40. if ($monitor_pid) {
  41. print "Change monitor already running, killing and re-starting.\n";
  42. kill 'TERM', $monitor_pid;
  43. }
  44. # daemonize immediately. We are handling the pidfile ourselves, see below
  45. my $daemon = Proc::Daemon->new(
  46. work_dir => "$FindBin::Bin/..",
  47. pid_file => $pf,
  48. child_STDOUT => 'logs/monitor.log',
  49. child_STDERR => 'logs/monitor.err',
  50. );
  51. my $child_pid = $daemon->Init;
  52. return 0 if $child_pid;
  53. my $ppid = get_master_pid();
  54. # If we go here, we (probably) have a PID, so watch for the changes.
  55. my $status = Trog::Autoreload::watch_for_changes('lib', $ppid);
  56. if ($status) {
  57. # tCMS process went away. Bye bye!
  58. print "tCMS process went away, shutting down monitor\n";
  59. return cleanup();
  60. }
  61. # By now we should have recieved SIGHUP and are already dead, so exit anyways.
  62. return cleanup();
  63. }
  64. exit main(@ARGV) unless caller;