jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

623 lines
16KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. Runner.py: Task scheduling and execution
  6. """
  7. import heapq, traceback
  8. try:
  9. from queue import Queue, PriorityQueue
  10. except ImportError:
  11. from Queue import Queue
  12. try:
  13. from Queue import PriorityQueue
  14. except ImportError:
  15. class PriorityQueue(Queue):
  16. def _init(self, maxsize):
  17. self.maxsize = maxsize
  18. self.queue = []
  19. def _put(self, item):
  20. heapq.heappush(self.queue, item)
  21. def _get(self):
  22. return heapq.heappop(self.queue)
  23. from waflib import Utils, Task, Errors, Logs
  24. GAP = 5
  25. """
  26. Wait for at least ``GAP * njobs`` before trying to enqueue more tasks to run
  27. """
  28. class PriorityTasks(object):
  29. def __init__(self):
  30. self.lst = []
  31. def __len__(self):
  32. return len(self.lst)
  33. def __iter__(self):
  34. return iter(self.lst)
  35. def __str__(self):
  36. return 'PriorityTasks: [%s]' % '\n '.join(str(x) for x in self.lst)
  37. def clear(self):
  38. self.lst = []
  39. def append(self, task):
  40. heapq.heappush(self.lst, task)
  41. def appendleft(self, task):
  42. "Deprecated, do not use"
  43. heapq.heappush(self.lst, task)
  44. def pop(self):
  45. return heapq.heappop(self.lst)
  46. def extend(self, lst):
  47. if self.lst:
  48. for x in lst:
  49. self.append(x)
  50. else:
  51. if isinstance(lst, list):
  52. self.lst = lst
  53. heapq.heapify(lst)
  54. else:
  55. self.lst = lst.lst
  56. class Consumer(Utils.threading.Thread):
  57. """
  58. Daemon thread object that executes a task. It shares a semaphore with
  59. the coordinator :py:class:`waflib.Runner.Spawner`. There is one
  60. instance per task to consume.
  61. """
  62. def __init__(self, spawner, task):
  63. Utils.threading.Thread.__init__(self)
  64. self.task = task
  65. """Task to execute"""
  66. self.spawner = spawner
  67. """Coordinator object"""
  68. self.daemon = True
  69. self.start()
  70. def run(self):
  71. """
  72. Processes a single task
  73. """
  74. try:
  75. if not self.spawner.master.stop:
  76. self.spawner.master.process_task(self.task)
  77. finally:
  78. self.spawner.sem.release()
  79. self.spawner.master.out.put(self.task)
  80. self.task = None
  81. self.spawner = None
  82. class Spawner(Utils.threading.Thread):
  83. """
  84. Daemon thread that consumes tasks from :py:class:`waflib.Runner.Parallel` producer and
  85. spawns a consuming thread :py:class:`waflib.Runner.Consumer` for each
  86. :py:class:`waflib.Task.Task` instance.
  87. """
  88. def __init__(self, master):
  89. Utils.threading.Thread.__init__(self)
  90. self.master = master
  91. """:py:class:`waflib.Runner.Parallel` producer instance"""
  92. self.sem = Utils.threading.Semaphore(master.numjobs)
  93. """Bounded semaphore that prevents spawning more than *n* concurrent consumers"""
  94. self.daemon = True
  95. self.start()
  96. def run(self):
  97. """
  98. Spawns new consumers to execute tasks by delegating to :py:meth:`waflib.Runner.Spawner.loop`
  99. """
  100. try:
  101. self.loop()
  102. except Exception:
  103. # Python 2 prints unnecessary messages when shutting down
  104. # we also want to stop the thread properly
  105. pass
  106. def loop(self):
  107. """
  108. Consumes task objects from the producer; ends when the producer has no more
  109. task to provide.
  110. """
  111. master = self.master
  112. while 1:
  113. task = master.ready.get()
  114. self.sem.acquire()
  115. if not master.stop:
  116. task.log_display(task.generator.bld)
  117. Consumer(self, task)
  118. class Parallel(object):
  119. """
  120. Schedule the tasks obtained from the build context for execution.
  121. """
  122. def __init__(self, bld, j=2):
  123. """
  124. The initialization requires a build context reference
  125. for computing the total number of jobs.
  126. """
  127. self.numjobs = j
  128. """
  129. Amount of parallel consumers to use
  130. """
  131. self.bld = bld
  132. """
  133. Instance of :py:class:`waflib.Build.BuildContext`
  134. """
  135. self.outstanding = PriorityTasks()
  136. """Heap of :py:class:`waflib.Task.Task` that may be ready to be executed"""
  137. self.postponed = PriorityTasks()
  138. """Heap of :py:class:`waflib.Task.Task` which are not ready to run for non-DAG reasons"""
  139. self.incomplete = set()
  140. """List of :py:class:`waflib.Task.Task` waiting for dependent tasks to complete (DAG)"""
  141. self.ready = PriorityQueue(0)
  142. """List of :py:class:`waflib.Task.Task` ready to be executed by consumers"""
  143. self.out = Queue(0)
  144. """List of :py:class:`waflib.Task.Task` returned by the task consumers"""
  145. self.count = 0
  146. """Amount of tasks that may be processed by :py:class:`waflib.Runner.TaskConsumer`"""
  147. self.processed = 0
  148. """Amount of tasks processed"""
  149. self.stop = False
  150. """Error flag to stop the build"""
  151. self.error = []
  152. """Tasks that could not be executed"""
  153. self.biter = None
  154. """Task iterator which must give groups of parallelizable tasks when calling ``next()``"""
  155. self.dirty = False
  156. """
  157. Flag that indicates that the build cache must be saved when a task was executed
  158. (calls :py:meth:`waflib.Build.BuildContext.store`)"""
  159. self.revdeps = Utils.defaultdict(set)
  160. """
  161. The reverse dependency graph of dependencies obtained from Task.run_after
  162. """
  163. self.spawner = None
  164. """
  165. Coordinating daemon thread that spawns thread consumers
  166. """
  167. if self.numjobs > 1:
  168. self.spawner = Spawner(self)
  169. def get_next_task(self):
  170. """
  171. Obtains the next Task instance to run
  172. :rtype: :py:class:`waflib.Task.Task`
  173. """
  174. if not self.outstanding:
  175. return None
  176. return self.outstanding.pop()
  177. def postpone(self, tsk):
  178. """
  179. Adds the task to the list :py:attr:`waflib.Runner.Parallel.postponed`.
  180. The order is scrambled so as to consume as many tasks in parallel as possible.
  181. :param tsk: task instance
  182. :type tsk: :py:class:`waflib.Task.Task`
  183. """
  184. self.postponed.append(tsk)
  185. def refill_task_list(self):
  186. """
  187. Pulls a next group of tasks to execute in :py:attr:`waflib.Runner.Parallel.outstanding`.
  188. Ensures that all tasks in the current build group are complete before processing the next one.
  189. """
  190. while self.count > self.numjobs * GAP:
  191. self.get_out()
  192. while not self.outstanding:
  193. if self.count:
  194. self.get_out()
  195. if self.outstanding:
  196. break
  197. elif self.postponed:
  198. try:
  199. cond = self.deadlock == self.processed
  200. except AttributeError:
  201. pass
  202. else:
  203. if cond:
  204. # The most common reason is conflicting build order declaration
  205. # for example: "X run_after Y" and "Y run_after X"
  206. # Another can be changing "run_after" dependencies while the build is running
  207. # for example: updating "tsk.run_after" in the "runnable_status" method
  208. lst = []
  209. for tsk in self.postponed:
  210. deps = [id(x) for x in tsk.run_after if not x.hasrun]
  211. lst.append('%s\t-> %r' % (repr(tsk), deps))
  212. if not deps:
  213. lst.append('\n task %r dependencies are done, check its *runnable_status*?' % id(tsk))
  214. raise Errors.WafError('Deadlock detected: check the task build order%s' % ''.join(lst))
  215. self.deadlock = self.processed
  216. if self.postponed:
  217. self.outstanding.extend(self.postponed)
  218. self.postponed.clear()
  219. elif not self.count:
  220. if self.incomplete:
  221. for x in self.incomplete:
  222. for k in x.run_after:
  223. if not k.hasrun:
  224. break
  225. else:
  226. # dependency added after the build started without updating revdeps
  227. self.incomplete.remove(x)
  228. self.outstanding.append(x)
  229. break
  230. else:
  231. if self.stop or self.error:
  232. break
  233. raise Errors.WafError('Broken revdeps detected on %r' % self.incomplete)
  234. else:
  235. tasks = next(self.biter)
  236. ready, waiting = self.prio_and_split(tasks)
  237. self.outstanding.extend(ready)
  238. self.incomplete.update(waiting)
  239. self.total = self.bld.total()
  240. break
  241. def add_more_tasks(self, tsk):
  242. """
  243. If a task provides :py:attr:`waflib.Task.Task.more_tasks`, then the tasks contained
  244. in that list are added to the current build and will be processed before the next build group.
  245. The priorities for dependent tasks are not re-calculated globally
  246. :param tsk: task instance
  247. :type tsk: :py:attr:`waflib.Task.Task`
  248. """
  249. if getattr(tsk, 'more_tasks', None):
  250. more = set(tsk.more_tasks)
  251. groups_done = set()
  252. def iteri(a, b):
  253. for x in a:
  254. yield x
  255. for x in b:
  256. yield x
  257. # Update the dependency tree
  258. # this assumes that task.run_after values were updated
  259. for x in iteri(self.outstanding, self.incomplete):
  260. for k in x.run_after:
  261. if isinstance(k, Task.TaskGroup):
  262. if k not in groups_done:
  263. groups_done.add(k)
  264. for j in k.prev & more:
  265. self.revdeps[j].add(k)
  266. elif k in more:
  267. self.revdeps[k].add(x)
  268. ready, waiting = self.prio_and_split(tsk.more_tasks)
  269. self.outstanding.extend(ready)
  270. self.incomplete.update(waiting)
  271. self.total += len(tsk.more_tasks)
  272. def mark_finished(self, tsk):
  273. def try_unfreeze(x):
  274. # DAG ancestors are likely to be in the incomplete set
  275. # This assumes that the run_after contents have not changed
  276. # after the build starts, else a deadlock may occur
  277. if x in self.incomplete:
  278. # TODO remove dependencies to free some memory?
  279. # x.run_after.remove(tsk)
  280. for k in x.run_after:
  281. if not k.hasrun:
  282. break
  283. else:
  284. self.incomplete.remove(x)
  285. self.outstanding.append(x)
  286. if tsk in self.revdeps:
  287. for x in self.revdeps[tsk]:
  288. if isinstance(x, Task.TaskGroup):
  289. x.prev.remove(tsk)
  290. if not x.prev:
  291. for k in x.next:
  292. # TODO necessary optimization?
  293. k.run_after.remove(x)
  294. try_unfreeze(k)
  295. # TODO necessary optimization?
  296. x.next = []
  297. else:
  298. try_unfreeze(x)
  299. del self.revdeps[tsk]
  300. if hasattr(tsk, 'semaphore'):
  301. sem = tsk.semaphore
  302. try:
  303. sem.release(tsk)
  304. except KeyError:
  305. # TODO
  306. pass
  307. else:
  308. while sem.waiting and not sem.is_locked():
  309. # take a frozen task, make it ready to run
  310. x = sem.waiting.pop()
  311. self._add_task(x)
  312. def get_out(self):
  313. """
  314. Waits for a Task that task consumers add to :py:attr:`waflib.Runner.Parallel.out` after execution.
  315. Adds more Tasks if necessary through :py:attr:`waflib.Runner.Parallel.add_more_tasks`.
  316. :rtype: :py:attr:`waflib.Task.Task`
  317. """
  318. tsk = self.out.get()
  319. if not self.stop:
  320. self.add_more_tasks(tsk)
  321. self.mark_finished(tsk)
  322. self.count -= 1
  323. self.dirty = True
  324. return tsk
  325. def add_task(self, tsk):
  326. """
  327. Enqueue a Task to :py:attr:`waflib.Runner.Parallel.ready` so that consumers can run them.
  328. :param tsk: task instance
  329. :type tsk: :py:attr:`waflib.Task.Task`
  330. """
  331. # TODO change in waf 2.1
  332. self.ready.put(tsk)
  333. def _add_task(self, tsk):
  334. if hasattr(tsk, 'semaphore'):
  335. sem = tsk.semaphore
  336. try:
  337. sem.acquire(tsk)
  338. except IndexError:
  339. sem.waiting.add(tsk)
  340. return
  341. self.count += 1
  342. self.processed += 1
  343. if self.numjobs == 1:
  344. tsk.log_display(tsk.generator.bld)
  345. try:
  346. self.process_task(tsk)
  347. finally:
  348. self.out.put(tsk)
  349. else:
  350. self.add_task(tsk)
  351. def process_task(self, tsk):
  352. """
  353. Processes a task and attempts to stop the build in case of errors
  354. """
  355. tsk.process()
  356. if tsk.hasrun != Task.SUCCESS:
  357. self.error_handler(tsk)
  358. def skip(self, tsk):
  359. """
  360. Mark a task as skipped/up-to-date
  361. """
  362. tsk.hasrun = Task.SKIPPED
  363. self.mark_finished(tsk)
  364. def cancel(self, tsk):
  365. """
  366. Mark a task as failed because of unsatisfiable dependencies
  367. """
  368. tsk.hasrun = Task.CANCELED
  369. self.mark_finished(tsk)
  370. def error_handler(self, tsk):
  371. """
  372. Called when a task cannot be executed. The flag :py:attr:`waflib.Runner.Parallel.stop` is set,
  373. unless the build is executed with::
  374. $ waf build -k
  375. :param tsk: task instance
  376. :type tsk: :py:attr:`waflib.Task.Task`
  377. """
  378. if not self.bld.keep:
  379. self.stop = True
  380. self.error.append(tsk)
  381. def task_status(self, tsk):
  382. """
  383. Obtains the task status to decide whether to run it immediately or not.
  384. :return: the exit status, for example :py:attr:`waflib.Task.ASK_LATER`
  385. :rtype: integer
  386. """
  387. try:
  388. return tsk.runnable_status()
  389. except Exception:
  390. self.processed += 1
  391. tsk.err_msg = traceback.format_exc()
  392. if not self.stop and self.bld.keep:
  393. self.skip(tsk)
  394. if self.bld.keep == 1:
  395. # if -k stop on the first exception, if -kk try to go as far as possible
  396. if Logs.verbose > 1 or not self.error:
  397. self.error.append(tsk)
  398. self.stop = True
  399. else:
  400. if Logs.verbose > 1:
  401. self.error.append(tsk)
  402. return Task.EXCEPTION
  403. tsk.hasrun = Task.EXCEPTION
  404. self.error_handler(tsk)
  405. return Task.EXCEPTION
  406. def start(self):
  407. """
  408. Obtains Task instances from the BuildContext instance and adds the ones that need to be executed to
  409. :py:class:`waflib.Runner.Parallel.ready` so that the :py:class:`waflib.Runner.Spawner` consumer thread
  410. has them executed. Obtains the executed Tasks back from :py:class:`waflib.Runner.Parallel.out`
  411. and marks the build as failed by setting the ``stop`` flag.
  412. If only one job is used, then executes the tasks one by one, without consumers.
  413. """
  414. self.total = self.bld.total()
  415. while not self.stop:
  416. self.refill_task_list()
  417. # consider the next task
  418. tsk = self.get_next_task()
  419. if not tsk:
  420. if self.count:
  421. # tasks may add new ones after they are run
  422. continue
  423. else:
  424. # no tasks to run, no tasks running, time to exit
  425. break
  426. if tsk.hasrun:
  427. # if the task is marked as "run", just skip it
  428. self.processed += 1
  429. continue
  430. if self.stop: # stop immediately after a failure is detected
  431. break
  432. st = self.task_status(tsk)
  433. if st == Task.RUN_ME:
  434. self._add_task(tsk)
  435. elif st == Task.ASK_LATER:
  436. self.postpone(tsk)
  437. elif st == Task.SKIP_ME:
  438. self.processed += 1
  439. self.skip(tsk)
  440. self.add_more_tasks(tsk)
  441. elif st == Task.CANCEL_ME:
  442. # A dependency problem has occurred, and the
  443. # build is most likely run with `waf -k`
  444. if Logs.verbose > 1:
  445. self.error.append(tsk)
  446. self.processed += 1
  447. self.cancel(tsk)
  448. # self.count represents the tasks that have been made available to the consumer threads
  449. # collect all the tasks after an error else the message may be incomplete
  450. while self.error and self.count:
  451. self.get_out()
  452. self.ready.put(None)
  453. if not self.stop:
  454. assert not self.count
  455. assert not self.postponed
  456. assert not self.incomplete
  457. def prio_and_split(self, tasks):
  458. """
  459. Label input tasks with priority values, and return a pair containing
  460. the tasks that are ready to run and the tasks that are necessarily
  461. waiting for other tasks to complete.
  462. The priority system is really meant as an optional layer for optimization:
  463. dependency cycles are found quickly, and builds should be more efficient.
  464. A high priority number means that a task is processed first.
  465. This method can be overridden to disable the priority system::
  466. def prio_and_split(self, tasks):
  467. return tasks, []
  468. :return: A pair of task lists
  469. :rtype: tuple
  470. """
  471. # to disable:
  472. #return tasks, []
  473. for x in tasks:
  474. x.visited = 0
  475. reverse = self.revdeps
  476. groups_done = set()
  477. for x in tasks:
  478. for k in x.run_after:
  479. if isinstance(k, Task.TaskGroup):
  480. if k not in groups_done:
  481. groups_done.add(k)
  482. for j in k.prev:
  483. reverse[j].add(k)
  484. else:
  485. reverse[k].add(x)
  486. # the priority number is not the tree depth
  487. def visit(n):
  488. if isinstance(n, Task.TaskGroup):
  489. return sum(visit(k) for k in n.next)
  490. if n.visited == 0:
  491. n.visited = 1
  492. if n in reverse:
  493. rev = reverse[n]
  494. n.prio_order = n.tree_weight + len(rev) + sum(visit(k) for k in rev)
  495. else:
  496. n.prio_order = n.tree_weight
  497. n.visited = 2
  498. elif n.visited == 1:
  499. raise Errors.WafError('Dependency cycle found!')
  500. return n.prio_order
  501. for x in tasks:
  502. if x.visited != 0:
  503. # must visit all to detect cycles
  504. continue
  505. try:
  506. visit(x)
  507. except Errors.WafError:
  508. self.debug_cycles(tasks, reverse)
  509. ready = []
  510. waiting = []
  511. for x in tasks:
  512. for k in x.run_after:
  513. if not k.hasrun:
  514. waiting.append(x)
  515. break
  516. else:
  517. ready.append(x)
  518. return (ready, waiting)
  519. def debug_cycles(self, tasks, reverse):
  520. tmp = {}
  521. for x in tasks:
  522. tmp[x] = 0
  523. def visit(n, acc):
  524. if isinstance(n, Task.TaskGroup):
  525. for k in n.next:
  526. visit(k, acc)
  527. return
  528. if tmp[n] == 0:
  529. tmp[n] = 1
  530. for k in reverse.get(n, []):
  531. visit(k, [n] + acc)
  532. tmp[n] = 2
  533. elif tmp[n] == 1:
  534. lst = []
  535. for tsk in acc:
  536. lst.append(repr(tsk))
  537. if tsk is n:
  538. # exclude prior nodes, we want the minimum cycle
  539. break
  540. raise Errors.WafError('Task dependency cycle in "run_after" constraints: %s' % ''.join(lst))
  541. for x in tasks:
  542. visit(x, [])