PythonExecutor.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #!/usr/bin/env python
  2. '''
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. '''
  17. import json
  18. import logging
  19. import os
  20. import subprocess
  21. import pprint
  22. import threading
  23. import platform
  24. from threading import Thread
  25. import time
  26. from BackgroundCommandExecutionHandle import BackgroundCommandExecutionHandle
  27. from ambari_commons.os_check import OSConst, OSCheck
  28. from Grep import Grep
  29. import sys
  30. from ambari_commons import shell
  31. logger = logging.getLogger()
  32. class PythonExecutor:
  33. """
  34. Performs functionality for executing python scripts.
  35. Warning: class maintains internal state. As a result, instances should not be
  36. used as a singleton for a concurrent execution of python scripts
  37. """
  38. NO_ERROR = "none"
  39. grep = Grep()
  40. event = threading.Event()
  41. python_process_has_been_killed = False
  42. def __init__(self, tmpDir, config):
  43. self.tmpDir = tmpDir
  44. self.config = config
  45. pass
  46. def open_subprocess_files(self, tmpoutfile, tmperrfile, override_output_files):
  47. if override_output_files: # Recreate files
  48. tmpout = open(tmpoutfile, 'w')
  49. tmperr = open(tmperrfile, 'w')
  50. else: # Append to files
  51. tmpout = open(tmpoutfile, 'a')
  52. tmperr = open(tmperrfile, 'a')
  53. return tmpout, tmperr
  54. def run_file(self, script, script_params, tmp_dir, tmpoutfile, tmperrfile,
  55. timeout, tmpstructedoutfile, logger_level, callback, task_id,
  56. override_output_files = True, handle = None):
  57. """
  58. Executes the specified python file in a separate subprocess.
  59. Method returns only when the subprocess is finished.
  60. Params arg is a list of script parameters
  61. Timeout meaning: how many seconds should pass before script execution
  62. is forcibly terminated
  63. override_output_files option defines whether stdout/stderr files will be
  64. recreated or appended.
  65. The structured out file, however, is preserved during multiple invocations that use the same file.
  66. """
  67. script_params += [tmpstructedoutfile, logger_level, tmp_dir]
  68. pythonCommand = self.python_command(script, script_params)
  69. logger.info("Running command " + pprint.pformat(pythonCommand))
  70. if handle is None:
  71. tmpout, tmperr = self.open_subprocess_files(tmpoutfile, tmperrfile, override_output_files)
  72. process = self.launch_python_subprocess(pythonCommand, tmpout, tmperr)
  73. # map task_id to pid
  74. callback(task_id, process.pid)
  75. logger.debug("Launching watchdog thread")
  76. self.event.clear()
  77. self.python_process_has_been_killed = False
  78. thread = Thread(target = self.python_watchdog_func, args = (process, timeout))
  79. thread.start()
  80. # Waiting for the process to be either finished or killed
  81. process.communicate()
  82. self.event.set()
  83. thread.join()
  84. return self.prepare_process_result(process, tmpoutfile, tmperrfile, tmpstructedoutfile, timeout=timeout)
  85. else:
  86. holder = Holder(pythonCommand, tmpoutfile, tmperrfile, tmpstructedoutfile, handle)
  87. background = BackgroundThread(holder, self)
  88. background.start()
  89. return {"exitcode": 777}
  90. def prepare_process_result(self, process, tmpoutfile, tmperrfile, tmpstructedoutfile, timeout=None):
  91. out, error, structured_out = self.read_result_from_files(tmpoutfile, tmperrfile, tmpstructedoutfile)
  92. # Building results
  93. returncode = process.returncode
  94. if self.python_process_has_been_killed:
  95. error = str(error) + "\n Python script has been killed due to timeout" + \
  96. (" after waiting %s secs" % str(timeout) if timeout else "")
  97. returncode = 999
  98. result = self.condenseOutput(out, error, returncode, structured_out)
  99. logger.info("Result: %s" % result)
  100. return result
  101. def read_result_from_files(self, out_path, err_path, structured_out_path):
  102. out = open(out_path, 'r').read()
  103. error = open(err_path, 'r').read()
  104. try:
  105. with open(structured_out_path, 'r') as fp:
  106. structured_out = json.load(fp)
  107. except Exception:
  108. if os.path.exists(structured_out_path):
  109. errMsg = 'Unable to read structured output from ' + structured_out_path
  110. structured_out = {
  111. 'msg' : errMsg
  112. }
  113. logger.warn(structured_out)
  114. else:
  115. structured_out = {}
  116. return out, error, structured_out
  117. def launch_python_subprocess(self, command, tmpout, tmperr):
  118. """
  119. Creates subprocess with given parameters. This functionality was moved to separate method
  120. to make possible unit testing
  121. """
  122. close_fds = None if OSCheck.get_os_family() == OSConst.WINSRV_FAMILY else True
  123. if OSCheck.get_os_family() == OSConst.WINSRV_FAMILY:
  124. command_env = dict(os.environ)
  125. command_env["PYTHONPATH"] = os.pathsep.join(sys.path)
  126. for k, v in command_env.iteritems():
  127. command_env[k] = str(v)
  128. else:
  129. command_env = None
  130. return subprocess.Popen(command,
  131. stdout=tmpout,
  132. stderr=tmperr, close_fds=close_fds, env=command_env)
  133. def isSuccessfull(self, returncode):
  134. return not self.python_process_has_been_killed and returncode == 0
  135. def python_command(self, script, script_params):
  136. #we need manually pass python executable on windows because sys.executable will return service wrapper
  137. python_binary = os.environ['PYTHON_EXE'] if 'PYTHON_EXE' in os.environ else sys.executable
  138. python_command = [python_binary, script] + script_params
  139. return python_command
  140. def condenseOutput(self, stdout, stderr, retcode, structured_out):
  141. log_lines_count = self.config.get('heartbeat', 'log_lines_count')
  142. grep = self.grep
  143. result = {
  144. "exitcode": retcode,
  145. "stdout": grep.tail(stdout, log_lines_count) if log_lines_count else stdout,
  146. "stderr": grep.tail(stderr, log_lines_count) if log_lines_count else stderr,
  147. "structuredOut" : structured_out
  148. }
  149. return result
  150. def python_watchdog_func(self, python, timeout):
  151. self.event.wait(timeout)
  152. if python.returncode is None:
  153. logger.error("Subprocess timed out and will be killed")
  154. shell.kill_process_with_children(python.pid)
  155. self.python_process_has_been_killed = True
  156. pass
  157. class Holder:
  158. def __init__(self, command, out_file, err_file, structured_out_file, handle):
  159. self.command = command
  160. self.out_file = out_file
  161. self.err_file = err_file
  162. self.structured_out_file = structured_out_file
  163. self.handle = handle
  164. class BackgroundThread(threading.Thread):
  165. def __init__(self, holder, pythonExecutor):
  166. threading.Thread.__init__(self)
  167. self.holder = holder
  168. self.pythonExecutor = pythonExecutor
  169. def run(self):
  170. process_out, process_err = self.pythonExecutor.open_subprocess_files(self.holder.out_file, self.holder.err_file, True)
  171. logger.info("Starting process command %s" % self.holder.command)
  172. process = self.pythonExecutor.launch_python_subprocess(self.holder.command, process_out, process_err)
  173. logger.info("Process has been started. Pid = %s" % process.pid)
  174. self.holder.handle.pid = process.pid
  175. self.holder.handle.status = BackgroundCommandExecutionHandle.RUNNING_STATUS
  176. self.holder.handle.on_background_command_started(self.holder.handle.command['taskId'], process.pid)
  177. process.communicate()
  178. self.holder.handle.exitCode = process.returncode
  179. process_condensed_result = self.pythonExecutor.prepare_process_result(process, self.holder.out_file, self.holder.err_file, self.holder.structured_out_file)
  180. logger.info("Calling callback with args %s" % process_condensed_result)
  181. self.holder.handle.on_background_command_complete_callback(process_condensed_result, self.holder.handle)
  182. logger.info("Exiting from thread for holder pid %s" % self.holder.handle.pid)