404ded1a481a3e09305bd1c2bd05f617436edca4
[scons.git] / src / engine / SCons / Taskmaster.py
1 """SCons.Taskmaster
2
3 Generic Taskmaster.
4
5 """
6
7 #
8 # __COPYRIGHT__
9 #
10 # Permission is hereby granted, free of charge, to any person obtaining
11 # a copy of this software and associated documentation files (the
12 # "Software"), to deal in the Software without restriction, including
13 # without limitation the rights to use, copy, modify, merge, publish,
14 # distribute, sublicense, and/or sell copies of the Software, and to
15 # permit persons to whom the Software is furnished to do so, subject to
16 # the following conditions:
17 #
18 # The above copyright notice and this permission notice shall be included
19 # in all copies or substantial portions of the Software.
20 #
21 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
22 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
23 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 #
29
30 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
31
32 import string
33 import sys
34 import traceback
35
36 import SCons.Node
37 import SCons.Errors
38
39 class Task:
40     """Default SCons build engine task.
41
42     This controls the interaction of the actual building of node
43     and the rest of the engine.
44
45     This is expected to handle all of the normally-customizable
46     aspects of controlling a build, so any given application
47     *should* be able to do what it wants by sub-classing this
48     class and overriding methods as appropriate.  If an application
49     needs to customze something by sub-classing Taskmaster (or
50     some other build engine class), we should first try to migrate
51     that functionality into this class.
52
53     Note that it's generally a good idea for sub-classes to call
54     these methods explicitly to update state, etc., rather than
55     roll their own interaction with Taskmaster from scratch."""
56     def __init__(self, tm, targets, top, node):
57         self.tm = tm
58         self.targets = targets
59         self.top = top
60         self.node = node
61         self.exc_clear()
62
63     def display(self, message):
64         """Allow the calling interface to display a message
65         """
66         pass
67
68     def prepare(self):
69         """Called just before the task is executed.
70
71         This unlinks all targets and makes all directories before
72         building anything."""
73
74         # Now that it's the appropriate time, give the TaskMaster a
75         # chance to raise any exceptions it encountered while preparing
76         # this task.
77         self.exception_raise()
78
79         if self.tm.message:
80             self.display(self.tm.message)
81             self.tm.message = None
82
83         for t in self.targets:
84             t.prepare()
85             for s in t.side_effects:
86                 s.prepare()
87
88     def execute(self):
89         """Called to execute the task.
90
91         This method is called from multiple threads in a parallel build,
92         so only do thread safe stuff here.  Do thread unsafe stuff in
93         prepare(), executed() or failed()."""
94
95         try:
96             everything_was_cached = 1
97             for t in self.targets:
98                 if not t.retrieve_from_cache():
99                     everything_was_cached = 0
100                     break
101             if not everything_was_cached:
102                 self.targets[0].build()
103         except KeyboardInterrupt:
104             raise
105         except SystemExit:
106             exc_value = sys.exc_info()[1]
107             raise SCons.Errors.ExplicitExit(self.targets[0], exc_value.code)
108         except SCons.Errors.UserError:
109             raise
110         except SCons.Errors.BuildError:
111             raise
112         except:
113             exc_type, exc_value, exc_traceback = sys.exc_info()
114             raise SCons.Errors.BuildError(self.targets[0],
115                                           "Exception",
116                                           exc_type,
117                                           exc_value,
118                                           exc_traceback)
119
120     def get_target(self):
121         """Fetch the target being built or updated by this task.
122         """
123         return self.node
124
125     def executed(self):
126         """Called when the task has been successfully executed.
127
128         This may have been a do-nothing operation (to preserve
129         build order), so check the node's state before updating
130         things.  Most importantly, this calls back to the
131         Taskmaster to put any node tasks waiting on this one
132         back on the pending list."""
133
134         if self.targets[0].get_state() == SCons.Node.executing:
135             for t in self.targets:
136                 for side_effect in t.side_effects:
137                     side_effect.set_state(None)
138                 t.set_state(SCons.Node.executed)
139                 t.built()
140         else:
141             for t in self.targets:
142                 t.visited()
143
144         self.tm.executed(self.node)
145
146     def failed(self):
147         """Default action when a task fails:  stop the build."""
148         self.fail_stop()
149
150     def fail_stop(self):
151         """Explicit stop-the-build failure."""
152         for t in self.targets:
153             t.set_state(SCons.Node.failed)
154         self.tm.failed(self.node)
155         next_top = self.tm.next_top_level_candidate()
156         self.tm.stop()
157
158         if next_top:
159             # We're stopping because of a build failure, but give the
160             # calling Task class a chance to postprocess() the top-level
161             # target under which the build failure occurred.
162             self.targets = [next_top]
163             self.top = 1
164
165     def fail_continue(self):
166         """Explicit continue-the-build failure.
167
168         This sets failure status on the target nodes and all of
169         their dependent parent nodes.
170         """
171         for t in self.targets:
172             # Set failure state on all of the parents that were dependent
173             # on this failed build.
174             def set_state(node): node.set_state(SCons.Node.failed)
175             t.call_for_all_waiting_parents(set_state)
176
177         self.tm.executed(self.node)
178
179     def mark_targets(self, state):
180         for t in self.targets:
181             t.set_state(state)
182
183     def mark_targets_and_side_effects(self, state):
184         for t in self.targets:
185             for side_effect in t.side_effects:
186                 side_effect.set_state(state)
187             t.set_state(state)
188
189     def make_ready_all(self):
190         """Mark all targets in a task ready for execution.
191
192         This is used when the interface needs every target Node to be
193         visited--the canonical example being the "scons -c" option.
194         """
195         self.out_of_date = self.targets[:]
196         self.mark_targets_and_side_effects(SCons.Node.executing)
197
198     def make_ready_current(self):
199         """Mark all targets in a task ready for execution if any target
200         is not current.
201
202         This is the default behavior for building only what's necessary.
203         """
204         self.out_of_date = []
205         for t in self.targets:
206             if not t.current():
207                 self.out_of_date.append(t)
208         if self.out_of_date:
209             self.mark_targets_and_side_effects(SCons.Node.executing)
210         else:
211             self.mark_targets(SCons.Node.up_to_date)
212
213     make_ready = make_ready_current
214
215     def postprocess(self):
216         """Post process a task after it's been executed."""
217         for t in self.targets:
218             t.postprocess()
219
220     def exc_info(self):
221         return self.exception
222
223     def exc_clear(self):
224         self.exception = (None, None, None)
225         self.exception_raise = self._no_exception_to_raise
226
227     def exception_set(self, exception=None):
228         if not exception:
229             exception = sys.exc_info()
230         self.exception = exception
231         self.exception_raise = self._exception_raise
232
233     def _no_exception_to_raise(self):
234         pass
235
236     def _exception_raise(self):
237         """Raise a pending exception that was recorded while
238         getting a Task ready for execution."""
239         self.tm.exception_raise(self.exc_info())
240
241
242 def order(dependencies):
243     """Re-order a list of dependencies (if we need to)."""
244     return dependencies
245
246
247 class Taskmaster:
248     """A generic Taskmaster for handling a bunch of targets.
249
250     Classes that override methods of this class should call
251     the base class method, so this class can do its thing.
252     """
253
254     def __init__(self, targets=[], tasker=Task, order=order):
255         self.targets = targets # top level targets
256         self.candidates = targets[:] # nodes that might be ready to be executed
257         self.candidates.reverse()
258         self.executing = [] # nodes that are currently executing
259         self.pending = [] # nodes that depend on a currently executing node
260         self.tasker = tasker
261         self.ready = None # the next task that is ready to be executed
262         self.order = order
263         self.message = None
264
265         # See if we can alter the target list to find any
266         # corresponding targets in linked build directories
267         for node in self.targets:
268             alt, message = node.alter_targets()
269             if alt:
270                 self.message = message
271                 self.candidates.extend(self.order(alt))
272                 continue
273
274     def _find_next_ready_node(self):
275         """Find the next node that is ready to be built"""
276
277         if self.ready:
278             return
279
280         self.ready_exc = None
281         
282         while self.candidates:
283             node = self.candidates[-1]
284             state = node.get_state()
285
286             # Skip this node if it has already been executed:
287             if state != None and state != SCons.Node.stack:
288                 self.candidates.pop()
289                 continue
290
291             # Mark this node as being on the execution stack:
292             node.set_state(SCons.Node.stack)
293
294             try:
295                 childinfo = map(lambda N: (N.get_state(),
296                                            N.is_derived() or N.is_pseudo_derived(),
297                                            N), node.children())
298             except SystemExit:
299                 exc_value = sys.exc_info()[1]
300                 e = SCons.Errors.ExplicitExit(node, exc_value.code)
301                 self.ready_exc = (SCons.Errors.ExplicitExit, e)
302                 self.candidates.pop()
303                 self.ready = node
304                 break
305             except KeyboardInterrupt:
306                 raise
307             except:
308                 # We had a problem just trying to figure out the
309                 # children (like a child couldn't be linked in to a
310                 # BuildDir, or a Scanner threw something).  Arrange to
311                 # raise the exception when the Task is "executed."
312                 self.ready_exc = sys.exc_info()
313                 self.candidates.pop()
314                 self.ready = node
315                 break
316
317             
318             # Skip this node if any of its children have failed.  This
319             # catches the case where we're descending a top-level target
320             # and one of our children failed while trying to be built
321             # by a *previous* descent of an earlier top-level target.
322             if filter(lambda I: I[0] == SCons.Node.failed, childinfo):
323                 node.set_state(SCons.Node.failed)
324                 self.candidates.pop()
325                 continue
326
327             # Detect dependency cycles:
328             cycle = filter(lambda I: I[0] == SCons.Node.stack, childinfo)
329             if cycle:
330                 nodes = filter(lambda N: N.get_state() == SCons.Node.stack,
331                                self.candidates) + \
332                                map(lambda I: I[2], cycle)
333                 nodes.reverse()
334                 desc = "Dependency cycle: " + string.join(map(str, nodes), " -> ")
335                 raise SCons.Errors.UserError, desc
336
337             # Find all of the derived dependencies (that is,
338             # children who have builders or are side effects):
339             # Add derived files that have not been built
340             # to the candidates list:
341             not_built = filter(lambda I: I[1] and not I[0], childinfo)
342             if not_built:
343                 # We're waiting on one more derived files that have not
344                 # yet been built.  Add this node to the waiting_parents
345                 # list of each of those derived files.
346                 map(lambda I, P=node: I[2].add_to_waiting_parents(P), not_built)
347                 not_built.reverse()
348                 self.candidates.extend(self.order(map(lambda I: I[2],
349                                                       not_built)))
350                 continue
351
352             # Skip this node if it has side-effects that are
353             # currently being built:
354             if reduce(lambda E,N:
355                       E or N.get_state() == SCons.Node.executing,
356                       node.side_effects,
357                       0):
358                 self.pending.append(node)
359                 node.set_state(SCons.Node.pending)
360                 self.candidates.pop()
361                 continue
362
363             # Skip this node if it is pending on a currently
364             # executing node:
365             if node.depends_on(self.executing) or node.depends_on(self.pending):
366                 self.pending.append(node)
367                 node.set_state(SCons.Node.pending)
368                 self.candidates.pop()
369                 continue
370
371             # The default when we've gotten through all of the checks above:
372             # this node is ready to be built.
373             self.candidates.pop()
374             self.ready = node
375             break
376
377     def next_task(self):
378         """Return the next task to be executed."""
379
380         self._find_next_ready_node()
381
382         node = self.ready
383
384         if node is None:
385             return None
386
387         try:
388             tlist = node.builder.targets(node)
389         except AttributeError:
390             tlist = [node]
391         self.executing.extend(tlist)
392         self.executing.extend(node.side_effects)
393         
394         task = self.tasker(self, tlist, node in self.targets, node)
395         try:
396             task.make_ready()
397         except KeyboardInterrupt:
398             raise
399         except:
400             # We had a problem just trying to get this task ready (like
401             # a child couldn't be linked in to a BuildDir when deciding
402             # whether this node is current).  Arrange to raise the
403             # exception when the Task is "executed."
404             self.ready_exc = sys.exc_info()
405
406         if self.ready_exc:
407             task.exception_set(self.ready_exc)
408
409         self.ready = None
410         self.ready_exc = None
411
412         return task
413
414     def is_blocked(self):
415         self._find_next_ready_node()
416
417         return not self.ready and (self.pending or self.executing)
418
419     def next_top_level_candidate(self):
420         candidates = self.candidates[:]
421         candidates.reverse()
422         for c in candidates:
423             if c in self.targets:
424                 return c
425         return None
426
427     def stop(self):
428         """Stop the current build completely."""
429         self.candidates = []
430         self.ready = None
431         self.pending = []
432
433     def failed(self, node):
434         try:
435             tlist = node.builder.targets(node)
436         except AttributeError:
437             tlist = [node]
438         for t in tlist:
439             self.executing.remove(t)
440         for side_effect in node.side_effects:
441             self.executing.remove(side_effect)
442
443     def executed(self, node):
444         try:
445             tlist = node.builder.targets(node)
446         except AttributeError:
447             tlist = [node]
448         for t in tlist:
449             self.executing.remove(t)
450         for side_effect in node.side_effects:
451             self.executing.remove(side_effect)
452
453         # move the current pending nodes to the candidates list:
454         # (they may not all be ready to build, but _find_next_ready_node()
455         #  will figure out which ones are really ready)
456         for node in self.pending:
457             node.set_state(None)
458         self.pending.reverse()
459         self.candidates.extend(self.pending)
460         self.pending = []
461
462     def exception_raise(self, exception):
463         exc = exception[:]
464         try:
465             exc_type, exc_value, exc_traceback = exc
466         except ValueError:
467             exc_type, exc_value = exc
468             exc_traceback = None
469         raise exc_type, exc_value, exc_traceback