PageRenderTime 50ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/couchjs/scons/scons-local-2.0.1/SCons/Job.py

http://github.com/cloudant/bigcouch
Python | 435 lines | 362 code | 15 blank | 58 comment | 0 complexity | 7f96548c3be6969debf52ce93f86e2a0 MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Job
  2. This module defines the Serial and Parallel classes that execute tasks to
  3. complete a build. The Jobs class provides a higher level interface to start,
  4. stop, and wait on jobs.
  5. """
  6. #
  7. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  8. #
  9. # Permission is hereby granted, free of charge, to any person obtaining
  10. # a copy of this software and associated documentation files (the
  11. # "Software"), to deal in the Software without restriction, including
  12. # without limitation the rights to use, copy, modify, merge, publish,
  13. # distribute, sublicense, and/or sell copies of the Software, and to
  14. # permit persons to whom the Software is furnished to do so, subject to
  15. # the following conditions:
  16. #
  17. # The above copyright notice and this permission notice shall be included
  18. # in all copies or substantial portions of the Software.
  19. #
  20. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  21. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  22. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. #
  28. __revision__ = "src/engine/SCons/Job.py 5134 2010/08/16 23:02:40 bdeegan"
  29. import SCons.compat
  30. import os
  31. import signal
  32. import SCons.Errors
  33. # The default stack size (in kilobytes) of the threads used to execute
  34. # jobs in parallel.
  35. #
  36. # We use a stack size of 256 kilobytes. The default on some platforms
  37. # is too large and prevents us from creating enough threads to fully
  38. # parallelized the build. For example, the default stack size on linux
  39. # is 8 MBytes.
  40. explicit_stack_size = None
  41. default_stack_size = 256
  42. interrupt_msg = 'Build interrupted.'
  43. class InterruptState(object):
  44. def __init__(self):
  45. self.interrupted = False
  46. def set(self):
  47. self.interrupted = True
  48. def __call__(self):
  49. return self.interrupted
  50. class Jobs(object):
  51. """An instance of this class initializes N jobs, and provides
  52. methods for starting, stopping, and waiting on all N jobs.
  53. """
  54. def __init__(self, num, taskmaster):
  55. """
  56. create 'num' jobs using the given taskmaster.
  57. If 'num' is 1 or less, then a serial job will be used,
  58. otherwise a parallel job with 'num' worker threads will
  59. be used.
  60. The 'num_jobs' attribute will be set to the actual number of jobs
  61. allocated. If more than one job is requested but the Parallel
  62. class can't do it, it gets reset to 1. Wrapping interfaces that
  63. care should check the value of 'num_jobs' after initialization.
  64. """
  65. self.job = None
  66. if num > 1:
  67. stack_size = explicit_stack_size
  68. if stack_size is None:
  69. stack_size = default_stack_size
  70. try:
  71. self.job = Parallel(taskmaster, num, stack_size)
  72. self.num_jobs = num
  73. except NameError:
  74. pass
  75. if self.job is None:
  76. self.job = Serial(taskmaster)
  77. self.num_jobs = 1
  78. def run(self, postfunc=lambda: None):
  79. """Run the jobs.
  80. postfunc() will be invoked after the jobs has run. It will be
  81. invoked even if the jobs are interrupted by a keyboard
  82. interrupt (well, in fact by a signal such as either SIGINT,
  83. SIGTERM or SIGHUP). The execution of postfunc() is protected
  84. against keyboard interrupts and is guaranteed to run to
  85. completion."""
  86. self._setup_sig_handler()
  87. try:
  88. self.job.start()
  89. finally:
  90. postfunc()
  91. self._reset_sig_handler()
  92. def were_interrupted(self):
  93. """Returns whether the jobs were interrupted by a signal."""
  94. return self.job.interrupted()
  95. def _setup_sig_handler(self):
  96. """Setup an interrupt handler so that SCons can shutdown cleanly in
  97. various conditions:
  98. a) SIGINT: Keyboard interrupt
  99. b) SIGTERM: kill or system shutdown
  100. c) SIGHUP: Controlling shell exiting
  101. We handle all of these cases by stopping the taskmaster. It
  102. turns out that it very difficult to stop the build process
  103. by throwing asynchronously an exception such as
  104. KeyboardInterrupt. For example, the python Condition
  105. variables (threading.Condition) and queue's do not seem to
  106. asynchronous-exception-safe. It would require adding a whole
  107. bunch of try/finally block and except KeyboardInterrupt all
  108. over the place.
  109. Note also that we have to be careful to handle the case when
  110. SCons forks before executing another process. In that case, we
  111. want the child to exit immediately.
  112. """
  113. def handler(signum, stack, self=self, parentpid=os.getpid()):
  114. if os.getpid() == parentpid:
  115. self.job.taskmaster.stop()
  116. self.job.interrupted.set()
  117. else:
  118. os._exit(2)
  119. self.old_sigint = signal.signal(signal.SIGINT, handler)
  120. self.old_sigterm = signal.signal(signal.SIGTERM, handler)
  121. try:
  122. self.old_sighup = signal.signal(signal.SIGHUP, handler)
  123. except AttributeError:
  124. pass
  125. def _reset_sig_handler(self):
  126. """Restore the signal handlers to their previous state (before the
  127. call to _setup_sig_handler()."""
  128. signal.signal(signal.SIGINT, self.old_sigint)
  129. signal.signal(signal.SIGTERM, self.old_sigterm)
  130. try:
  131. signal.signal(signal.SIGHUP, self.old_sighup)
  132. except AttributeError:
  133. pass
  134. class Serial(object):
  135. """This class is used to execute tasks in series, and is more efficient
  136. than Parallel, but is only appropriate for non-parallel builds. Only
  137. one instance of this class should be in existence at a time.
  138. This class is not thread safe.
  139. """
  140. def __init__(self, taskmaster):
  141. """Create a new serial job given a taskmaster.
  142. The taskmaster's next_task() method should return the next task
  143. that needs to be executed, or None if there are no more tasks. The
  144. taskmaster's executed() method will be called for each task when it
  145. is successfully executed or failed() will be called if it failed to
  146. execute (e.g. execute() raised an exception)."""
  147. self.taskmaster = taskmaster
  148. self.interrupted = InterruptState()
  149. def start(self):
  150. """Start the job. This will begin pulling tasks from the taskmaster
  151. and executing them, and return when there are no more tasks. If a task
  152. fails to execute (i.e. execute() raises an exception), then the job will
  153. stop."""
  154. while True:
  155. task = self.taskmaster.next_task()
  156. if task is None:
  157. break
  158. try:
  159. task.prepare()
  160. if task.needs_execute():
  161. task.execute()
  162. except:
  163. if self.interrupted():
  164. try:
  165. raise SCons.Errors.BuildError(
  166. task.targets[0], errstr=interrupt_msg)
  167. except:
  168. task.exception_set()
  169. else:
  170. task.exception_set()
  171. # Let the failed() callback function arrange for the
  172. # build to stop if that's appropriate.
  173. task.failed()
  174. else:
  175. task.executed()
  176. task.postprocess()
  177. self.taskmaster.cleanup()
  178. # Trap import failure so that everything in the Job module but the
  179. # Parallel class (and its dependent classes) will work if the interpreter
  180. # doesn't support threads.
  181. try:
  182. import queue
  183. import threading
  184. except ImportError:
  185. pass
  186. else:
  187. class Worker(threading.Thread):
  188. """A worker thread waits on a task to be posted to its request queue,
  189. dequeues the task, executes it, and posts a tuple including the task
  190. and a boolean indicating whether the task executed successfully. """
  191. def __init__(self, requestQueue, resultsQueue, interrupted):
  192. threading.Thread.__init__(self)
  193. self.setDaemon(1)
  194. self.requestQueue = requestQueue
  195. self.resultsQueue = resultsQueue
  196. self.interrupted = interrupted
  197. self.start()
  198. def run(self):
  199. while True:
  200. task = self.requestQueue.get()
  201. if task is None:
  202. # The "None" value is used as a sentinel by
  203. # ThreadPool.cleanup(). This indicates that there
  204. # are no more tasks, so we should quit.
  205. break
  206. try:
  207. if self.interrupted():
  208. raise SCons.Errors.BuildError(
  209. task.targets[0], errstr=interrupt_msg)
  210. task.execute()
  211. except:
  212. task.exception_set()
  213. ok = False
  214. else:
  215. ok = True
  216. self.resultsQueue.put((task, ok))
  217. class ThreadPool(object):
  218. """This class is responsible for spawning and managing worker threads."""
  219. def __init__(self, num, stack_size, interrupted):
  220. """Create the request and reply queues, and 'num' worker threads.
  221. One must specify the stack size of the worker threads. The
  222. stack size is specified in kilobytes.
  223. """
  224. self.requestQueue = queue.Queue(0)
  225. self.resultsQueue = queue.Queue(0)
  226. try:
  227. prev_size = threading.stack_size(stack_size*1024)
  228. except AttributeError, e:
  229. # Only print a warning if the stack size has been
  230. # explicitly set.
  231. if not explicit_stack_size is None:
  232. msg = "Setting stack size is unsupported by this version of Python:\n " + \
  233. e.args[0]
  234. SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
  235. except ValueError, e:
  236. msg = "Setting stack size failed:\n " + str(e)
  237. SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
  238. # Create worker threads
  239. self.workers = []
  240. for _ in range(num):
  241. worker = Worker(self.requestQueue, self.resultsQueue, interrupted)
  242. self.workers.append(worker)
  243. if 'prev_size' in locals():
  244. threading.stack_size(prev_size)
  245. def put(self, task):
  246. """Put task into request queue."""
  247. self.requestQueue.put(task)
  248. def get(self):
  249. """Remove and return a result tuple from the results queue."""
  250. return self.resultsQueue.get()
  251. def preparation_failed(self, task):
  252. self.resultsQueue.put((task, False))
  253. def cleanup(self):
  254. """
  255. Shuts down the thread pool, giving each worker thread a
  256. chance to shut down gracefully.
  257. """
  258. # For each worker thread, put a sentinel "None" value
  259. # on the requestQueue (indicating that there's no work
  260. # to be done) so that each worker thread will get one and
  261. # terminate gracefully.
  262. for _ in self.workers:
  263. self.requestQueue.put(None)
  264. # Wait for all of the workers to terminate.
  265. #
  266. # If we don't do this, later Python versions (2.4, 2.5) often
  267. # seem to raise exceptions during shutdown. This happens
  268. # in requestQueue.get(), as an assertion failure that
  269. # requestQueue.not_full is notified while not acquired,
  270. # seemingly because the main thread has shut down (or is
  271. # in the process of doing so) while the workers are still
  272. # trying to pull sentinels off the requestQueue.
  273. #
  274. # Normally these terminations should happen fairly quickly,
  275. # but we'll stick a one-second timeout on here just in case
  276. # someone gets hung.
  277. for worker in self.workers:
  278. worker.join(1.0)
  279. self.workers = []
  280. class Parallel(object):
  281. """This class is used to execute tasks in parallel, and is somewhat
  282. less efficient than Serial, but is appropriate for parallel builds.
  283. This class is thread safe.
  284. """
  285. def __init__(self, taskmaster, num, stack_size):
  286. """Create a new parallel job given a taskmaster.
  287. The taskmaster's next_task() method should return the next
  288. task that needs to be executed, or None if there are no more
  289. tasks. The taskmaster's executed() method will be called
  290. for each task when it is successfully executed or failed()
  291. will be called if the task failed to execute (i.e. execute()
  292. raised an exception).
  293. Note: calls to taskmaster are serialized, but calls to
  294. execute() on distinct tasks are not serialized, because
  295. that is the whole point of parallel jobs: they can execute
  296. multiple tasks simultaneously. """
  297. self.taskmaster = taskmaster
  298. self.interrupted = InterruptState()
  299. self.tp = ThreadPool(num, stack_size, self.interrupted)
  300. self.maxjobs = num
  301. def start(self):
  302. """Start the job. This will begin pulling tasks from the
  303. taskmaster and executing them, and return when there are no
  304. more tasks. If a task fails to execute (i.e. execute() raises
  305. an exception), then the job will stop."""
  306. jobs = 0
  307. while True:
  308. # Start up as many available tasks as we're
  309. # allowed to.
  310. while jobs < self.maxjobs:
  311. task = self.taskmaster.next_task()
  312. if task is None:
  313. break
  314. try:
  315. # prepare task for execution
  316. task.prepare()
  317. except:
  318. task.exception_set()
  319. task.failed()
  320. task.postprocess()
  321. else:
  322. if task.needs_execute():
  323. # dispatch task
  324. self.tp.put(task)
  325. jobs = jobs + 1
  326. else:
  327. task.executed()
  328. task.postprocess()
  329. if not task and not jobs: break
  330. # Let any/all completed tasks finish up before we go
  331. # back and put the next batch of tasks on the queue.
  332. while True:
  333. task, ok = self.tp.get()
  334. jobs = jobs - 1
  335. if ok:
  336. task.executed()
  337. else:
  338. if self.interrupted():
  339. try:
  340. raise SCons.Errors.BuildError(
  341. task.targets[0], errstr=interrupt_msg)
  342. except:
  343. task.exception_set()
  344. # Let the failed() callback function arrange
  345. # for the build to stop if that's appropriate.
  346. task.failed()
  347. task.postprocess()
  348. if self.tp.resultsQueue.empty():
  349. break
  350. self.tp.cleanup()
  351. self.taskmaster.cleanup()
  352. # Local Variables:
  353. # tab-width:4
  354. # indent-tabs-mode:nil
  355. # End:
  356. # vim: set expandtab tabstop=4 shiftwidth=4: