hot-restarter.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import os
  4. import signal
  5. import sys
  6. import time
  7. # The number of seconds to wait for children to gracefully exit after
  8. # propagating SIGTERM before force killing children.
  9. # NOTE: If using a shutdown mechanism such as runit's `force-stop` which sends
  10. # a KILL after a specified timeout period, it's important to ensure that this
  11. # constant is smaller than the KILL timeout
  12. TERM_WAIT_SECONDS = 30
  13. restart_epoch = 0
  14. pid_list = []
  15. def term_all_children():
  16. """ Iterate through all known child processes, send a TERM signal to each of
  17. them, and then wait up to TERM_WAIT_SECONDS for them to exit gracefully,
  18. exiting early if all children go away. If one or more children have not
  19. exited after TERM_WAIT_SECONDS, they will be forcibly killed """
  20. # First uninstall the SIGCHLD handler so that we don't get called again.
  21. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  22. global pid_list
  23. for pid in pid_list:
  24. print("sending TERM to PID={}".format(pid))
  25. try:
  26. os.kill(pid, signal.SIGTERM)
  27. except OSError:
  28. print("error sending TERM to PID={} continuing".format(pid))
  29. all_exited = False
  30. # wait for TERM_WAIT_SECONDS seconds for children to exit cleanly
  31. retries = 0
  32. while not all_exited and retries < TERM_WAIT_SECONDS:
  33. for pid in list(pid_list):
  34. ret_pid, exit_status = os.waitpid(pid, os.WNOHANG)
  35. if ret_pid == 0 and exit_status == 0:
  36. # the child is still running
  37. continue
  38. pid_list.remove(pid)
  39. if len(pid_list) == 0:
  40. all_exited = True
  41. else:
  42. retries += 1
  43. time.sleep(1)
  44. if all_exited:
  45. print("all children exited cleanly")
  46. else:
  47. for pid in pid_list:
  48. print("child PID={} did not exit cleanly, killing".format(pid))
  49. force_kill_all_children()
  50. sys.exit(1) # error status because a child did not exit cleanly
  51. def force_kill_all_children():
  52. """ Iterate through all known child processes and force kill them. Typically
  53. term_all_children() should be attempted first to give child processes an
  54. opportunity to clean up state before exiting """
  55. global pid_list
  56. for pid in pid_list:
  57. print("force killing PID={}".format(pid))
  58. try:
  59. os.kill(pid, signal.SIGKILL)
  60. except OSError:
  61. print("error force killing PID={} continuing".format(pid))
  62. pid_list = []
  63. def shutdown():
  64. """ Attempt to gracefully shutdown all child Envoy processes and then exit.
  65. See term_all_children() for further discussion. """
  66. term_all_children()
  67. sys.exit(0)
  68. def sigterm_handler(signum, frame):
  69. """ Handler for SIGTERM. """
  70. print("got SIGTERM")
  71. shutdown()
  72. def sigint_handler(signum, frame):
  73. """ Handler for SIGINT (ctrl-c). The same as the SIGTERM handler. """
  74. print("got SIGINT")
  75. shutdown()
  76. def sighup_handler(signum, frame):
  77. """ Handler for SIGUP. This signal is used to cause the restarter to fork and exec a new
  78. child. """
  79. print("got SIGHUP")
  80. fork_and_exec()
  81. def sigusr1_handler(signum, frame):
  82. """ Handler for SIGUSR1. Propagate SIGUSR1 to all of the child processes """
  83. global pid_list
  84. for pid in pid_list:
  85. print("sending SIGUSR1 to PID={}".format(pid))
  86. try:
  87. os.kill(pid, signal.SIGUSR1)
  88. except OSError:
  89. print("error in SIGUSR1 to PID={} continuing".format(pid))
  90. def sigchld_handler(signum, frame):
  91. """ Handler for SIGCHLD. Iterates through all of our known child processes and figures out whether
  92. the signal/exit was expected or not. Python doesn't have any of the native signal handlers
  93. ability to get the child process info directly from the signal handler so we need to iterate
  94. through all child processes and see what happened."""
  95. print("got SIGCHLD")
  96. kill_all_and_exit = False
  97. global pid_list
  98. pid_list_copy = list(pid_list)
  99. for pid in pid_list_copy:
  100. ret_pid, exit_status = os.waitpid(pid, os.WNOHANG)
  101. if ret_pid == 0 and exit_status == 0:
  102. # This child is still running.
  103. continue
  104. pid_list.remove(pid)
  105. # Now we see how the child exited.
  106. if os.WIFEXITED(exit_status):
  107. exit_code = os.WEXITSTATUS(exit_status)
  108. print("PID={} exited with code={}".format(ret_pid, exit_code))
  109. if exit_code == 0:
  110. # Normal exit. We assume this was on purpose.
  111. pass
  112. else:
  113. # Something bad happened. We need to tear everything down so that whoever started the
  114. # restarter can know about this situation and restart the whole thing.
  115. kill_all_and_exit = True
  116. elif os.WIFSIGNALED(exit_status):
  117. print("PID={} was killed with signal={}".format(ret_pid, os.WTERMSIG(exit_status)))
  118. kill_all_and_exit = True
  119. else:
  120. kill_all_and_exit = True
  121. if kill_all_and_exit:
  122. print("Due to abnormal exit, force killing all child processes and exiting")
  123. # First uninstall the SIGCHLD handler so that we don't get called again.
  124. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  125. force_kill_all_children()
  126. # Our last child died, so we have no purpose. Exit.
  127. if not pid_list:
  128. print("exiting due to lack of child processes")
  129. sys.exit(1 if kill_all_and_exit else 0)
  130. def fork_and_exec():
  131. """ This routine forks and execs a new child process and keeps track of its PID. Before we fork,
  132. set the current restart epoch in an env variable that processes can read if they care. """
  133. global restart_epoch
  134. os.environ['RESTART_EPOCH'] = str(restart_epoch)
  135. print("forking and execing new child process at epoch {}".format(restart_epoch))
  136. restart_epoch += 1
  137. child_pid = os.fork()
  138. if child_pid == 0:
  139. # Child process
  140. os.execl(sys.argv[1], sys.argv[1])
  141. else:
  142. # Parent process
  143. print("forked new child process with PID={}".format(child_pid))
  144. pid_list.append(child_pid)
  145. def main():
  146. """ Script main. This script is designed so that a process watcher like runit or monit can watch
  147. this process and take corrective action if it ever goes away. """
  148. print("starting hot-restarter with target: {}".format(sys.argv[1]))
  149. signal.signal(signal.SIGTERM, sigterm_handler)
  150. signal.signal(signal.SIGINT, sigint_handler)
  151. signal.signal(signal.SIGHUP, sighup_handler)
  152. signal.signal(signal.SIGCHLD, sigchld_handler)
  153. signal.signal(signal.SIGUSR1, sigusr1_handler)
  154. # Start the first child process and then go into an endless loop since everything else happens via
  155. # signals.
  156. fork_and_exec()
  157. while True:
  158. time.sleep(60)
  159. if __name__ == '__main__':
  160. main()