daemon.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import logging
  4. import os
  5. import signal
  6. import tempfile
  7. import shutil
  8. import six
  9. try:
  10. from . import gdb
  11. except ValueError:
  12. import gdb
  13. from yatest.common import process, output_path, TimeoutError, cores
  14. MAX_IO_LEN = 1024 * 10
  15. GYGABYTES = 1 << 30
  16. logger = logging.getLogger(__name__)
  17. def run_daemon(command, check_exit_code=True, shell=False, timeout=5, cwd=None,
  18. env=None, stdin=None, stdout=None, stderr=None, creationflags=0):
  19. daemon = Daemon(command, check_exit_code, shell, timeout, cwd, env, stdin, stdout, stderr, creationflags)
  20. daemon.run()
  21. return daemon
  22. def get_free_space(path):
  23. stats = os.statvfs(path)
  24. return stats.f_bavail * stats.f_frsize
  25. class DaemonError(RuntimeError):
  26. def __init__(self, message, stdout=None, stderr=None, exit_code=None):
  27. lst = [
  28. "Daemon failed with message: {message}.".format(message=message),
  29. ]
  30. if exit_code is not None:
  31. lst.append(
  32. "Process exit_code = {exit_code}.".format(exit_code=exit_code)
  33. )
  34. if stdout is not None:
  35. lst.append(
  36. "Stdout: {stdout}".format(stdout=stdout)
  37. )
  38. if stderr is not None:
  39. lst.append(
  40. "Stderr: {stderr}".format(stderr=stderr)
  41. )
  42. super(DaemonError, self).__init__('\n'.join(lst))
  43. class Daemon(object):
  44. def __init__(self, command, check_exit_code=True, shell=False, timeout=5, cwd=None,
  45. env=None, stdin=None, stdout=None, stderr=None, creationflags=0):
  46. if cwd is None:
  47. cwd = tempfile.mkdtemp()
  48. self.cwd = cwd
  49. self.stdoutf = stdout or tempfile.NamedTemporaryFile(dir=self.cwd, prefix="stdout_", delete=False)
  50. self.stderrf = stderr or tempfile.NamedTemporaryFile(dir=self.cwd, prefix="stderr_", delete=False)
  51. self.stdinf = stdin or tempfile.NamedTemporaryFile(dir=self.cwd, prefix="stdin_", delete=False)
  52. self.cmd = command
  53. if isinstance(command, six.string_types):
  54. self.cmd = [arg for arg in command.split() if arg]
  55. self.daemon = None
  56. self.name = os.path.basename(self.cmd[0])
  57. self._shell = shell
  58. self._env = env
  59. self._creationflags = creationflags
  60. self._check_exit_code = check_exit_code
  61. self._timeout = timeout
  62. def before_start(self):
  63. pass
  64. def after_start(self):
  65. pass
  66. def before_stop(self):
  67. pass
  68. def after_stop(self):
  69. pass
  70. def is_alive(self):
  71. return self.daemon and self.daemon.running
  72. def required_args(self):
  73. return []
  74. def check_run(self):
  75. """This function checks that daemon is running. By default it
  76. checks only the process status. But you can override it to
  77. check your binary specific marks like 'port is busy' and
  78. others."""
  79. return self.is_alive()
  80. def run(self):
  81. if self.check_run():
  82. logger.error("Can't run %s.\nProcess already started" % self.cmd)
  83. raise DaemonError("daemon already started.")
  84. try:
  85. self.before_start()
  86. except Exception:
  87. logger.exception("Exception in user hook before_start")
  88. self.daemon = process.execute(self.cmd[:1] + self.required_args() + self.cmd[1:],
  89. False,
  90. shell=self._shell,
  91. cwd=self.cwd,
  92. env=self._env,
  93. stdin=self.stdinf,
  94. stdout=self.stdoutf,
  95. stderr=self.stderrf,
  96. creationflags=self._creationflags,
  97. wait=False)
  98. stdout, stderr = self.__communicate()
  99. timeout_reason_msg = "Failed to execute '{cmd}'.\n\tstdout: {out}\n\tstderr: {err}".format(
  100. cmd=" ".join(self.cmd),
  101. out=stdout,
  102. err=stderr)
  103. try:
  104. process.wait_for(self.check_run, self._timeout, timeout_reason_msg, sleep_time=0.1)
  105. except process.TimeoutError:
  106. self.raise_on_death(timeout_reason_msg)
  107. if not self.is_alive():
  108. self.raise_on_death("WHY? %s %s" % (self.daemon, self.daemon.running))
  109. try:
  110. self.after_start()
  111. except Exception as e:
  112. msg = "Exception in user hook after_start. Exception: %s" % str(e)
  113. logger.exception(msg)
  114. return self
  115. def raise_on_death(self, additional_text=""):
  116. stdout = "[NO STDOUT]"
  117. stderr = "[NO STDERR]"
  118. if self.stdoutf and self.stdinf:
  119. stdout, stderr = self.__communicate()
  120. if self.daemon and getattr(self.daemon, "process"):
  121. self.check_coredump()
  122. raise DaemonError(
  123. Daemon.__log_failed(
  124. "process {} unexpectedly finished. \n\n {}".format(self.cmd, additional_text),
  125. stdout,
  126. stderr
  127. )
  128. )
  129. def check_coredump(self):
  130. try:
  131. core_file = cores.recover_core_dump_file(self.cmd[0], self.cwd, self.daemon.process.pid)
  132. if core_file:
  133. logger.debug(core_file + " found, maybe this is our coredump file")
  134. self.save_coredump(core_file)
  135. else:
  136. logger.debug("Core dump file was not found")
  137. except Exception as e:
  138. logger.warn("While checking coredump: " + str(e))
  139. def save_coredump(self, core_file):
  140. output_core_dir = output_path("cores")
  141. shared_core_file = os.path.join(output_core_dir, os.path.basename(core_file))
  142. if not os.path.isdir(output_core_dir):
  143. os.mkdir(output_core_dir)
  144. short_bt, _ = gdb.dump_traceback(executable=self.cmd[0], core_file=core_file,
  145. output_file=shared_core_file + ".trace.txt")
  146. if short_bt:
  147. logger.error("Short backtrace = \n" + "=" * 80 + "\n" + short_bt + "\n" + "=" * 80)
  148. space_left = float(get_free_space(output_core_dir))
  149. if space_left > 5 * GYGABYTES:
  150. shutil.copy2(
  151. core_file,
  152. shared_core_file
  153. )
  154. os.chmod(shared_core_file, 0o755)
  155. logger.debug("Saved to " + output_core_dir)
  156. else:
  157. logger.error("Not enough space left on device (%s GB). Won't save %s file" % (float(space_left / GYGABYTES), core_file))
  158. def stop(self, kill=False):
  159. if not self.is_alive() and self.daemon.exit_code == 0:
  160. return
  161. if not self.is_alive():
  162. stdout, stderr = self.__communicate()
  163. self.check_coredump()
  164. try:
  165. self.after_stop()
  166. except Exception:
  167. logger.exception("Exception in user hook after_stop.")
  168. raise DaemonError(
  169. Daemon.__log_failed(
  170. "process {} unexpectedly finished with exit code {}.".format(self.cmd, self.daemon.exit_code),
  171. stdout,
  172. stderr
  173. ),
  174. exit_code=self.daemon.exit_code
  175. )
  176. try:
  177. self.before_stop()
  178. except Exception:
  179. logger.exception("Exception in user hook before_stop.")
  180. stderr, stdout = self.__communicate()
  181. timeout_reason_msg = "Cannot stop {cmd}.\n\tstdout: {out}\n\tstderr: {err}".format(
  182. cmd=" ".join(self.cmd),
  183. out=stdout,
  184. err=stderr)
  185. if not kill:
  186. self.daemon.process.send_signal(signal.SIGINT)
  187. try: # soft wait for. trying to kill with sigint
  188. process.wait_for(lambda: not self.is_alive(), self._timeout, timeout_reason_msg, sleep_time=0.1)
  189. except TimeoutError:
  190. pass
  191. is_killed = False
  192. if self.is_alive():
  193. self.daemon.process.send_signal(signal.SIGKILL)
  194. is_killed = True
  195. process.wait_for(lambda: not self.is_alive(), self._timeout, timeout_reason_msg, sleep_time=0.1)
  196. try:
  197. self.after_stop()
  198. except Exception:
  199. logger.exception("Exception in user hook after_stop")
  200. if self.daemon.running:
  201. stdout, stderr = self.__communicate()
  202. msg = "cannot stop daemon {cmd}\n\tstdout: {out}\n\tstderr: {err}".format(
  203. cmd=' '.join(self.cmd),
  204. out=stdout,
  205. err=stderr
  206. )
  207. logger.error(msg)
  208. raise DaemonError(msg, stdout=stdout, stderr=stderr, exit_code=self.daemon.exit_code)
  209. stdout, stderr = self.__communicate()
  210. logger.debug(
  211. "Process stopped: {cmd}.\n\tstdout:\n{out}\n\tstderr:\n{err}".format(
  212. cmd=" ".join(self.cmd),
  213. out=stdout,
  214. err=stderr
  215. )
  216. )
  217. if not is_killed:
  218. self.check_coredump()
  219. if self._check_exit_code and self.daemon.exit_code != 0:
  220. stdout, stderr = self.__communicate()
  221. raise DaemonError("Bad exit_code.", stdout=stdout, stderr=stderr, exit_code=self.daemon.exit_code)
  222. else:
  223. logger.warning("Exit code is not checked, cos binary was stopped by sigkill")
  224. def _read_io(self, file_obj):
  225. file_obj.flush()
  226. cur_pos = file_obj.tell()
  227. seek_pos_from_end = max(-cur_pos, -MAX_IO_LEN)
  228. file_obj.seek(seek_pos_from_end, os.SEEK_END)
  229. return file_obj.read()
  230. def __communicate(self):
  231. stderr = self._read_io(self.stderrf)
  232. stdout = self._read_io(self.stdoutf)
  233. return stdout, stderr
  234. @staticmethod
  235. def __log_failed(msg, stderr, stdout):
  236. final_msg = '{msg}\nstdout: {out}\nstderr: {err}'.format(
  237. msg=msg,
  238. out=stdout,
  239. err=stderr)
  240. logger.error(msg)
  241. return final_msg