3 # Thomas Nagy, 2005-2018 (ita)
6 Runner.py: Task scheduling and execution
9 import heapq
, traceback
11 from queue
import Queue
, PriorityQueue
13 from Queue
import Queue
15 from Queue
import PriorityQueue
17 class PriorityQueue(Queue
):
18 def _init(self
, maxsize
):
19 self
.maxsize
= maxsize
22 heapq
.heappush(self
.queue
, item
)
24 return heapq
.heappop(self
.queue
)
26 from waflib
import Utils
, Task
, Errors
, Logs
30 Wait for at least ``GAP * njobs`` before trying to enqueue more tasks to run
33 class PriorityTasks(object):
41 return 'PriorityTasks: [%s]' % '\n '.join(str(x
) for x
in self
.lst
)
44 def append(self
, task
):
45 heapq
.heappush(self
.lst
, task
)
46 def appendleft(self
, task
):
47 "Deprecated, do not use"
48 heapq
.heappush(self
.lst
, task
)
50 return heapq
.heappop(self
.lst
)
51 def extend(self
, lst
):
56 if isinstance(lst
, list):
62 class Consumer(Utils
.threading
.Thread
):
64 Daemon thread object that executes a task. It shares a semaphore with
65 the coordinator :py:class:`waflib.Runner.Spawner`. There is one
66 instance per task to consume.
68 def __init__(self
, spawner
, task
):
69 Utils
.threading
.Thread
.__init
__(self
)
72 self
.spawner
= spawner
73 """Coordinator object"""
78 Processes a single task
81 if not self
.spawner
.master
.stop
:
82 self
.spawner
.master
.process_task(self
.task
)
84 self
.spawner
.sem
.release()
85 self
.spawner
.master
.out
.put(self
.task
)
89 class Spawner(Utils
.threading
.Thread
):
91 Daemon thread that consumes tasks from :py:class:`waflib.Runner.Parallel` producer and
92 spawns a consuming thread :py:class:`waflib.Runner.Consumer` for each
93 :py:class:`waflib.Task.Task` instance.
95 def __init__(self
, master
):
96 Utils
.threading
.Thread
.__init
__(self
)
98 """:py:class:`waflib.Runner.Parallel` producer instance"""
99 self
.sem
= Utils
.threading
.Semaphore(master
.numjobs
)
100 """Bounded semaphore that prevents spawning more than *n* concurrent consumers"""
105 Spawns new consumers to execute tasks by delegating to :py:meth:`waflib.Runner.Spawner.loop`
110 # Python 2 prints unnecessary messages when shutting down
111 # we also want to stop the thread properly
115 Consumes task objects from the producer; ends when the producer has no more
120 task
= master
.ready
.get()
123 task
.log_display(task
.generator
.bld
)
126 class Parallel(object):
128 Schedule the tasks obtained from the build context for execution.
130 def __init__(self
, bld
, j
=2):
132 The initialization requires a build context reference
133 for computing the total number of jobs.
138 Amount of parallel consumers to use
143 Instance of :py:class:`waflib.Build.BuildContext`
146 self
.outstanding
= PriorityTasks()
147 """Heap of :py:class:`waflib.Task.Task` that may be ready to be executed"""
149 self
.postponed
= PriorityTasks()
150 """Heap of :py:class:`waflib.Task.Task` which are not ready to run for non-DAG reasons"""
152 self
.incomplete
= set()
153 """List of :py:class:`waflib.Task.Task` waiting for dependent tasks to complete (DAG)"""
155 self
.ready
= PriorityQueue(0)
156 """List of :py:class:`waflib.Task.Task` ready to be executed by consumers"""
159 """List of :py:class:`waflib.Task.Task` returned by the task consumers"""
162 """Amount of tasks that may be processed by :py:class:`waflib.Runner.TaskConsumer`"""
165 """Amount of tasks processed"""
168 """Error flag to stop the build"""
171 """Tasks that could not be executed"""
174 """Task iterator which must give groups of parallelizable tasks when calling ``next()``"""
178 Flag that indicates that the build cache must be saved when a task was executed
179 (calls :py:meth:`waflib.Build.BuildContext.store`)"""
181 self
.revdeps
= Utils
.defaultdict(set)
183 The reverse dependency graph of dependencies obtained from Task.run_after
188 Coordinating daemon thread that spawns thread consumers
191 self
.spawner
= Spawner(self
)
193 def get_next_task(self
):
195 Obtains the next Task instance to run
197 :rtype: :py:class:`waflib.Task.Task`
199 if not self
.outstanding
:
201 return self
.outstanding
.pop()
203 def postpone(self
, tsk
):
205 Adds the task to the list :py:attr:`waflib.Runner.Parallel.postponed`.
206 The order is scrambled so as to consume as many tasks in parallel as possible.
208 :param tsk: task instance
209 :type tsk: :py:class:`waflib.Task.Task`
211 self
.postponed
.append(tsk
)
213 def refill_task_list(self
):
215 Pulls a next group of tasks to execute in :py:attr:`waflib.Runner.Parallel.outstanding`.
216 Ensures that all tasks in the current build group are complete before processing the next one.
218 while self
.count
> self
.numjobs
* GAP
:
221 while not self
.outstanding
:
228 cond
= self
.deadlock
== self
.processed
229 except AttributeError:
233 # The most common reason is conflicting build order declaration
234 # for example: "X run_after Y" and "Y run_after X"
235 # Another can be changing "run_after" dependencies while the build is running
236 # for example: updating "tsk.run_after" in the "runnable_status" method
238 for tsk
in self
.postponed
:
239 deps
= [id(x
) for x
in tsk
.run_after
if not x
.hasrun
]
240 lst
.append('%s\t-> %r' % (repr(tsk
), deps
))
242 lst
.append('\n task %r dependencies are done, check its *runnable_status*?' % id(tsk
))
243 raise Errors
.WafError('Deadlock detected: check the task build order%s' % ''.join(lst
))
244 self
.deadlock
= self
.processed
247 self
.outstanding
.extend(self
.postponed
)
248 self
.postponed
.clear()
251 for x
in self
.incomplete
:
252 for k
in x
.run_after
:
256 # dependency added after the build started without updating revdeps
257 self
.incomplete
.remove(x
)
258 self
.outstanding
.append(x
)
261 if self
.stop
or self
.error
:
263 raise Errors
.WafError('Broken revdeps detected on %r' % self
.incomplete
)
265 tasks
= next(self
.biter
)
266 ready
, waiting
= self
.prio_and_split(tasks
)
267 self
.outstanding
.extend(ready
)
268 self
.incomplete
.update(waiting
)
269 self
.total
= self
.bld
.total()
272 def add_more_tasks(self
, tsk
):
274 If a task provides :py:attr:`waflib.Task.Task.more_tasks`, then the tasks contained
275 in that list are added to the current build and will be processed before the next build group.
277 The priorities for dependent tasks are not re-calculated globally
279 :param tsk: task instance
280 :type tsk: :py:attr:`waflib.Task.Task`
282 if getattr(tsk
, 'more_tasks', None):
283 more
= set(tsk
.more_tasks
)
291 # Update the dependency tree
292 # this assumes that task.run_after values were updated
293 for x
in iteri(self
.outstanding
, self
.incomplete
):
294 for k
in x
.run_after
:
295 if isinstance(k
, Task
.TaskGroup
):
296 if k
not in groups_done
:
298 for j
in k
.prev
& more
:
299 self
.revdeps
[j
].add(k
)
301 self
.revdeps
[k
].add(x
)
303 ready
, waiting
= self
.prio_and_split(tsk
.more_tasks
)
304 self
.outstanding
.extend(ready
)
305 self
.incomplete
.update(waiting
)
306 self
.total
+= len(tsk
.more_tasks
)
308 def mark_finished(self
, tsk
):
310 # DAG ancestors are likely to be in the incomplete set
311 # This assumes that the run_after contents have not changed
312 # after the build starts, else a deadlock may occur
313 if x
in self
.incomplete
:
314 # TODO remove dependencies to free some memory?
315 # x.run_after.remove(tsk)
316 for k
in x
.run_after
:
320 self
.incomplete
.remove(x
)
321 self
.outstanding
.append(x
)
323 if tsk
in self
.revdeps
:
324 for x
in self
.revdeps
[tsk
]:
325 if isinstance(x
, Task
.TaskGroup
):
329 # TODO necessary optimization?
330 k
.run_after
.remove(x
)
332 # TODO necessary optimization?
336 del self
.revdeps
[tsk
]
338 if hasattr(tsk
, 'semaphore'):
346 while sem
.waiting
and not sem
.is_locked():
347 # take a frozen task, make it ready to run
348 x
= sem
.waiting
.pop()
353 Waits for a Task that task consumers add to :py:attr:`waflib.Runner.Parallel.out` after execution.
354 Adds more Tasks if necessary through :py:attr:`waflib.Runner.Parallel.add_more_tasks`.
356 :rtype: :py:attr:`waflib.Task.Task`
360 self
.add_more_tasks(tsk
)
361 self
.mark_finished(tsk
)
367 def add_task(self
, tsk
):
369 Enqueue a Task to :py:attr:`waflib.Runner.Parallel.ready` so that consumers can run them.
371 :param tsk: task instance
372 :type tsk: :py:attr:`waflib.Task.Task`
374 # TODO change in waf 2.1
377 def _add_task(self
, tsk
):
378 if hasattr(tsk
, 'semaphore'):
388 if self
.numjobs
== 1:
389 tsk
.log_display(tsk
.generator
.bld
)
391 self
.process_task(tsk
)
397 def process_task(self
, tsk
):
399 Processes a task and attempts to stop the build in case of errors
402 if tsk
.hasrun
!= Task
.SUCCESS
:
403 self
.error_handler(tsk
)
407 Mark a task as skipped/up-to-date
409 tsk
.hasrun
= Task
.SKIPPED
410 self
.mark_finished(tsk
)
412 def cancel(self
, tsk
):
414 Mark a task as failed because of unsatisfiable dependencies
416 tsk
.hasrun
= Task
.CANCELED
417 self
.mark_finished(tsk
)
419 def error_handler(self
, tsk
):
421 Called when a task cannot be executed. The flag :py:attr:`waflib.Runner.Parallel.stop` is set,
422 unless the build is executed with::
426 :param tsk: task instance
427 :type tsk: :py:attr:`waflib.Task.Task`
429 if not self
.bld
.keep
:
431 self
.error
.append(tsk
)
433 def task_status(self
, tsk
):
435 Obtains the task status to decide whether to run it immediately or not.
437 :return: the exit status, for example :py:attr:`waflib.Task.ASK_LATER`
441 return tsk
.runnable_status()
444 tsk
.err_msg
= traceback
.format_exc()
445 if not self
.stop
and self
.bld
.keep
:
447 if self
.bld
.keep
== 1:
448 # if -k stop on the first exception, if -kk try to go as far as possible
449 if Logs
.verbose
> 1 or not self
.error
:
450 self
.error
.append(tsk
)
454 self
.error
.append(tsk
)
455 return Task
.EXCEPTION
457 tsk
.hasrun
= Task
.EXCEPTION
458 self
.error_handler(tsk
)
460 return Task
.EXCEPTION
464 Obtains Task instances from the BuildContext instance and adds the ones that need to be executed to
465 :py:class:`waflib.Runner.Parallel.ready` so that the :py:class:`waflib.Runner.Spawner` consumer thread
466 has them executed. Obtains the executed Tasks back from :py:class:`waflib.Runner.Parallel.out`
467 and marks the build as failed by setting the ``stop`` flag.
468 If only one job is used, then executes the tasks one by one, without consumers.
470 self
.total
= self
.bld
.total()
474 self
.refill_task_list()
476 # consider the next task
477 tsk
= self
.get_next_task()
480 # tasks may add new ones after they are run
483 # no tasks to run, no tasks running, time to exit
487 # if the task is marked as "run", just skip it
491 if self
.stop
: # stop immediately after a failure is detected
494 st
= self
.task_status(tsk
)
495 if st
== Task
.RUN_ME
:
497 elif st
== Task
.ASK_LATER
:
499 elif st
== Task
.SKIP_ME
:
502 self
.add_more_tasks(tsk
)
503 elif st
== Task
.CANCEL_ME
:
504 # A dependency problem has occurred, and the
505 # build is most likely run with `waf -k`
507 self
.error
.append(tsk
)
511 # self.count represents the tasks that have been made available to the consumer threads
512 # collect all the tasks after an error else the message may be incomplete
513 while self
.error
and self
.count
:
518 assert not self
.count
519 assert not self
.postponed
520 assert not self
.incomplete
522 def prio_and_split(self
, tasks
):
524 Label input tasks with priority values, and return a pair containing
525 the tasks that are ready to run and the tasks that are necessarily
526 waiting for other tasks to complete.
528 The priority system is really meant as an optional layer for optimization:
529 dependency cycles are found quickly, and builds should be more efficient.
530 A high priority number means that a task is processed first.
532 This method can be overridden to disable the priority system::
534 def prio_and_split(self, tasks):
537 :return: A pair of task lists
545 reverse
= self
.revdeps
549 for k
in x
.run_after
:
550 if isinstance(k
, Task
.TaskGroup
):
551 if k
not in groups_done
:
558 # the priority number is not the tree depth
560 if isinstance(n
, Task
.TaskGroup
):
561 return sum(visit(k
) for k
in n
.next
)
568 n
.prio_order
= n
.tree_weight
+ len(rev
) + sum(visit(k
) for k
in rev
)
570 n
.prio_order
= n
.tree_weight
574 raise Errors
.WafError('Dependency cycle found!')
579 # must visit all to detect cycles
583 except Errors
.WafError
:
584 self
.debug_cycles(tasks
, reverse
)
589 for k
in x
.run_after
:
595 return (ready
, waiting
)
597 def debug_cycles(self
, tasks
, reverse
):
603 if isinstance(n
, Task
.TaskGroup
):
609 for k
in reverse
.get(n
, []):
615 lst
.append(repr(tsk
))
617 # exclude prior nodes, we want the minimum cycle
619 raise Errors
.WafError('Task dependency cycle in "run_after" constraints: %s' % ''.join(lst
))