PageRenderTime 38ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

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

http://github.com/cloudant/bigcouch
Python | 1017 lines | 995 code | 1 blank | 21 comment | 1 complexity | 68b1017e6279724f3b1e3f6b4f598f56 MD5 | raw file
Possible License(s): Apache-2.0
  1. #
  2. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining
  5. # a copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish,
  8. # distribute, sublicense, and/or sell copies of the Software, and to
  9. # permit persons to whom the Software is furnished to do so, subject to
  10. # the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  16. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  17. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. __doc__ = """
  23. Generic Taskmaster module for the SCons build engine.
  24. This module contains the primary interface(s) between a wrapping user
  25. interface and the SCons build engine. There are two key classes here:
  26. Taskmaster
  27. This is the main engine for walking the dependency graph and
  28. calling things to decide what does or doesn't need to be built.
  29. Task
  30. This is the base class for allowing a wrapping interface to
  31. decide what does or doesn't actually need to be done. The
  32. intention is for a wrapping interface to subclass this as
  33. appropriate for different types of behavior it may need.
  34. The canonical example is the SCons native Python interface,
  35. which has Task subclasses that handle its specific behavior,
  36. like printing "`foo' is up to date" when a top-level target
  37. doesn't need to be built, and handling the -c option by removing
  38. targets as its "build" action. There is also a separate subclass
  39. for suppressing this output when the -q option is used.
  40. The Taskmaster instantiates a Task object for each (set of)
  41. target(s) that it decides need to be evaluated and/or built.
  42. """
  43. __revision__ = "src/engine/SCons/Taskmaster.py 5134 2010/08/16 23:02:40 bdeegan"
  44. from itertools import chain
  45. import operator
  46. import sys
  47. import traceback
  48. import SCons.Errors
  49. import SCons.Node
  50. import SCons.Warnings
  51. StateString = SCons.Node.StateString
  52. NODE_NO_STATE = SCons.Node.no_state
  53. NODE_PENDING = SCons.Node.pending
  54. NODE_EXECUTING = SCons.Node.executing
  55. NODE_UP_TO_DATE = SCons.Node.up_to_date
  56. NODE_EXECUTED = SCons.Node.executed
  57. NODE_FAILED = SCons.Node.failed
  58. # A subsystem for recording stats about how different Nodes are handled by
  59. # the main Taskmaster loop. There's no external control here (no need for
  60. # a --debug= option); enable it by changing the value of CollectStats.
  61. CollectStats = None
  62. class Stats(object):
  63. """
  64. A simple class for holding statistics about the disposition of a
  65. Node by the Taskmaster. If we're collecting statistics, each Node
  66. processed by the Taskmaster gets one of these attached, in which case
  67. the Taskmaster records its decision each time it processes the Node.
  68. (Ideally, that's just once per Node.)
  69. """
  70. def __init__(self):
  71. """
  72. Instantiates a Taskmaster.Stats object, initializing all
  73. appropriate counters to zero.
  74. """
  75. self.considered = 0
  76. self.already_handled = 0
  77. self.problem = 0
  78. self.child_failed = 0
  79. self.not_built = 0
  80. self.side_effects = 0
  81. self.build = 0
  82. StatsNodes = []
  83. fmt = "%(considered)3d "\
  84. "%(already_handled)3d " \
  85. "%(problem)3d " \
  86. "%(child_failed)3d " \
  87. "%(not_built)3d " \
  88. "%(side_effects)3d " \
  89. "%(build)3d "
  90. def dump_stats():
  91. for n in sorted(StatsNodes, key=lambda a: str(a)):
  92. print (fmt % n.stats.__dict__) + str(n)
  93. class Task(object):
  94. """
  95. Default SCons build engine task.
  96. This controls the interaction of the actual building of node
  97. and the rest of the engine.
  98. This is expected to handle all of the normally-customizable
  99. aspects of controlling a build, so any given application
  100. *should* be able to do what it wants by sub-classing this
  101. class and overriding methods as appropriate. If an application
  102. needs to customze something by sub-classing Taskmaster (or
  103. some other build engine class), we should first try to migrate
  104. that functionality into this class.
  105. Note that it's generally a good idea for sub-classes to call
  106. these methods explicitly to update state, etc., rather than
  107. roll their own interaction with Taskmaster from scratch.
  108. """
  109. def __init__(self, tm, targets, top, node):
  110. self.tm = tm
  111. self.targets = targets
  112. self.top = top
  113. self.node = node
  114. self.exc_clear()
  115. def trace_message(self, method, node, description='node'):
  116. fmt = '%-20s %s %s\n'
  117. return fmt % (method + ':', description, self.tm.trace_node(node))
  118. def display(self, message):
  119. """
  120. Hook to allow the calling interface to display a message.
  121. This hook gets called as part of preparing a task for execution
  122. (that is, a Node to be built). As part of figuring out what Node
  123. should be built next, the actually target list may be altered,
  124. along with a message describing the alteration. The calling
  125. interface can subclass Task and provide a concrete implementation
  126. of this method to see those messages.
  127. """
  128. pass
  129. def prepare(self):
  130. """
  131. Called just before the task is executed.
  132. This is mainly intended to give the target Nodes a chance to
  133. unlink underlying files and make all necessary directories before
  134. the Action is actually called to build the targets.
  135. """
  136. T = self.tm.trace
  137. if T: T.write(self.trace_message(u'Task.prepare()', self.node))
  138. # Now that it's the appropriate time, give the TaskMaster a
  139. # chance to raise any exceptions it encountered while preparing
  140. # this task.
  141. self.exception_raise()
  142. if self.tm.message:
  143. self.display(self.tm.message)
  144. self.tm.message = None
  145. # Let the targets take care of any necessary preparations.
  146. # This includes verifying that all of the necessary sources
  147. # and dependencies exist, removing the target file(s), etc.
  148. #
  149. # As of April 2008, the get_executor().prepare() method makes
  150. # sure that all of the aggregate sources necessary to build this
  151. # Task's target(s) exist in one up-front check. The individual
  152. # target t.prepare() methods check that each target's explicit
  153. # or implicit dependencies exists, and also initialize the
  154. # .sconsign info.
  155. executor = self.targets[0].get_executor()
  156. executor.prepare()
  157. for t in executor.get_action_targets():
  158. t.prepare()
  159. for s in t.side_effects:
  160. s.prepare()
  161. def get_target(self):
  162. """Fetch the target being built or updated by this task.
  163. """
  164. return self.node
  165. def needs_execute(self):
  166. # TODO(deprecate): "return True" is the old default behavior;
  167. # change it to NotImplementedError (after running through the
  168. # Deprecation Cycle) so the desired behavior is explicitly
  169. # determined by which concrete subclass is used.
  170. #raise NotImplementedError
  171. msg = ('Taskmaster.Task is an abstract base class; instead of\n'
  172. '\tusing it directly, '
  173. 'derive from it and override the abstract methods.')
  174. SCons.Warnings.warn(SCons.Warnings.TaskmasterNeedsExecuteWarning, msg)
  175. return True
  176. def execute(self):
  177. """
  178. Called to execute the task.
  179. This method is called from multiple threads in a parallel build,
  180. so only do thread safe stuff here. Do thread unsafe stuff in
  181. prepare(), executed() or failed().
  182. """
  183. T = self.tm.trace
  184. if T: T.write(self.trace_message(u'Task.execute()', self.node))
  185. try:
  186. everything_was_cached = 1
  187. for t in self.targets:
  188. if t.retrieve_from_cache():
  189. # Call the .built() method without calling the
  190. # .push_to_cache() method, since we just got the
  191. # target from the cache and don't need to push
  192. # it back there.
  193. t.set_state(NODE_EXECUTED)
  194. t.built()
  195. else:
  196. everything_was_cached = 0
  197. break
  198. if not everything_was_cached:
  199. self.targets[0].build()
  200. except SystemExit:
  201. exc_value = sys.exc_info()[1]
  202. raise SCons.Errors.ExplicitExit(self.targets[0], exc_value.code)
  203. except SCons.Errors.UserError:
  204. raise
  205. except SCons.Errors.BuildError:
  206. raise
  207. except Exception, e:
  208. buildError = SCons.Errors.convert_to_BuildError(e)
  209. buildError.node = self.targets[0]
  210. buildError.exc_info = sys.exc_info()
  211. raise buildError
  212. def executed_without_callbacks(self):
  213. """
  214. Called when the task has been successfully executed
  215. and the Taskmaster instance doesn't want to call
  216. the Node's callback methods.
  217. """
  218. T = self.tm.trace
  219. if T: T.write(self.trace_message('Task.executed_without_callbacks()',
  220. self.node))
  221. for t in self.targets:
  222. if t.get_state() == NODE_EXECUTING:
  223. for side_effect in t.side_effects:
  224. side_effect.set_state(NODE_NO_STATE)
  225. t.set_state(NODE_EXECUTED)
  226. def executed_with_callbacks(self):
  227. """
  228. Called when the task has been successfully executed and
  229. the Taskmaster instance wants to call the Node's callback
  230. methods.
  231. This may have been a do-nothing operation (to preserve build
  232. order), so we must check the node's state before deciding whether
  233. it was "built", in which case we call the appropriate Node method.
  234. In any event, we always call "visited()", which will handle any
  235. post-visit actions that must take place regardless of whether
  236. or not the target was an actual built target or a source Node.
  237. """
  238. T = self.tm.trace
  239. if T: T.write(self.trace_message('Task.executed_with_callbacks()',
  240. self.node))
  241. for t in self.targets:
  242. if t.get_state() == NODE_EXECUTING:
  243. for side_effect in t.side_effects:
  244. side_effect.set_state(NODE_NO_STATE)
  245. t.set_state(NODE_EXECUTED)
  246. t.push_to_cache()
  247. t.built()
  248. t.visited()
  249. executed = executed_with_callbacks
  250. def failed(self):
  251. """
  252. Default action when a task fails: stop the build.
  253. Note: Although this function is normally invoked on nodes in
  254. the executing state, it might also be invoked on up-to-date
  255. nodes when using Configure().
  256. """
  257. self.fail_stop()
  258. def fail_stop(self):
  259. """
  260. Explicit stop-the-build failure.
  261. This sets failure status on the target nodes and all of
  262. their dependent parent nodes.
  263. Note: Although this function is normally invoked on nodes in
  264. the executing state, it might also be invoked on up-to-date
  265. nodes when using Configure().
  266. """
  267. T = self.tm.trace
  268. if T: T.write(self.trace_message('Task.failed_stop()', self.node))
  269. # Invoke will_not_build() to clean-up the pending children
  270. # list.
  271. self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED))
  272. # Tell the taskmaster to not start any new tasks
  273. self.tm.stop()
  274. # We're stopping because of a build failure, but give the
  275. # calling Task class a chance to postprocess() the top-level
  276. # target under which the build failure occurred.
  277. self.targets = [self.tm.current_top]
  278. self.top = 1
  279. def fail_continue(self):
  280. """
  281. Explicit continue-the-build failure.
  282. This sets failure status on the target nodes and all of
  283. their dependent parent nodes.
  284. Note: Although this function is normally invoked on nodes in
  285. the executing state, it might also be invoked on up-to-date
  286. nodes when using Configure().
  287. """
  288. T = self.tm.trace
  289. if T: T.write(self.trace_message('Task.failed_continue()', self.node))
  290. self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED))
  291. def make_ready_all(self):
  292. """
  293. Marks all targets in a task ready for execution.
  294. This is used when the interface needs every target Node to be
  295. visited--the canonical example being the "scons -c" option.
  296. """
  297. T = self.tm.trace
  298. if T: T.write(self.trace_message('Task.make_ready_all()', self.node))
  299. self.out_of_date = self.targets[:]
  300. for t in self.targets:
  301. t.disambiguate().set_state(NODE_EXECUTING)
  302. for s in t.side_effects:
  303. # add disambiguate here to mirror the call on targets above
  304. s.disambiguate().set_state(NODE_EXECUTING)
  305. def make_ready_current(self):
  306. """
  307. Marks all targets in a task ready for execution if any target
  308. is not current.
  309. This is the default behavior for building only what's necessary.
  310. """
  311. T = self.tm.trace
  312. if T: T.write(self.trace_message(u'Task.make_ready_current()',
  313. self.node))
  314. self.out_of_date = []
  315. needs_executing = False
  316. for t in self.targets:
  317. try:
  318. t.disambiguate().make_ready()
  319. is_up_to_date = not t.has_builder() or \
  320. (not t.always_build and t.is_up_to_date())
  321. except EnvironmentError, e:
  322. raise SCons.Errors.BuildError(node=t, errstr=e.strerror, filename=e.filename)
  323. if not is_up_to_date:
  324. self.out_of_date.append(t)
  325. needs_executing = True
  326. if needs_executing:
  327. for t in self.targets:
  328. t.set_state(NODE_EXECUTING)
  329. for s in t.side_effects:
  330. # add disambiguate here to mirror the call on targets in first loop above
  331. s.disambiguate().set_state(NODE_EXECUTING)
  332. else:
  333. for t in self.targets:
  334. # We must invoke visited() to ensure that the node
  335. # information has been computed before allowing the
  336. # parent nodes to execute. (That could occur in a
  337. # parallel build...)
  338. t.visited()
  339. t.set_state(NODE_UP_TO_DATE)
  340. make_ready = make_ready_current
  341. def postprocess(self):
  342. """
  343. Post-processes a task after it's been executed.
  344. This examines all the targets just built (or not, we don't care
  345. if the build was successful, or even if there was no build
  346. because everything was up-to-date) to see if they have any
  347. waiting parent Nodes, or Nodes waiting on a common side effect,
  348. that can be put back on the candidates list.
  349. """
  350. T = self.tm.trace
  351. if T: T.write(self.trace_message(u'Task.postprocess()', self.node))
  352. # We may have built multiple targets, some of which may have
  353. # common parents waiting for this build. Count up how many
  354. # targets each parent was waiting for so we can subtract the
  355. # values later, and so we *don't* put waiting side-effect Nodes
  356. # back on the candidates list if the Node is also a waiting
  357. # parent.
  358. targets = set(self.targets)
  359. pending_children = self.tm.pending_children
  360. parents = {}
  361. for t in targets:
  362. # A node can only be in the pending_children set if it has
  363. # some waiting_parents.
  364. if t.waiting_parents:
  365. if T: T.write(self.trace_message(u'Task.postprocess()',
  366. t,
  367. 'removing'))
  368. pending_children.discard(t)
  369. for p in t.waiting_parents:
  370. parents[p] = parents.get(p, 0) + 1
  371. for t in targets:
  372. for s in t.side_effects:
  373. if s.get_state() == NODE_EXECUTING:
  374. s.set_state(NODE_NO_STATE)
  375. for p in s.waiting_parents:
  376. parents[p] = parents.get(p, 0) + 1
  377. for p in s.waiting_s_e:
  378. if p.ref_count == 0:
  379. self.tm.candidates.append(p)
  380. for p, subtract in parents.items():
  381. p.ref_count = p.ref_count - subtract
  382. if T: T.write(self.trace_message(u'Task.postprocess()',
  383. p,
  384. 'adjusted parent ref count'))
  385. if p.ref_count == 0:
  386. self.tm.candidates.append(p)
  387. for t in targets:
  388. t.postprocess()
  389. # Exception handling subsystem.
  390. #
  391. # Exceptions that occur while walking the DAG or examining Nodes
  392. # must be raised, but must be raised at an appropriate time and in
  393. # a controlled manner so we can, if necessary, recover gracefully,
  394. # possibly write out signature information for Nodes we've updated,
  395. # etc. This is done by having the Taskmaster tell us about the
  396. # exception, and letting
  397. def exc_info(self):
  398. """
  399. Returns info about a recorded exception.
  400. """
  401. return self.exception
  402. def exc_clear(self):
  403. """
  404. Clears any recorded exception.
  405. This also changes the "exception_raise" attribute to point
  406. to the appropriate do-nothing method.
  407. """
  408. self.exception = (None, None, None)
  409. self.exception_raise = self._no_exception_to_raise
  410. def exception_set(self, exception=None):
  411. """
  412. Records an exception to be raised at the appropriate time.
  413. This also changes the "exception_raise" attribute to point
  414. to the method that will, in fact
  415. """
  416. if not exception:
  417. exception = sys.exc_info()
  418. self.exception = exception
  419. self.exception_raise = self._exception_raise
  420. def _no_exception_to_raise(self):
  421. pass
  422. def _exception_raise(self):
  423. """
  424. Raises a pending exception that was recorded while getting a
  425. Task ready for execution.
  426. """
  427. exc = self.exc_info()[:]
  428. try:
  429. exc_type, exc_value, exc_traceback = exc
  430. except ValueError:
  431. exc_type, exc_value = exc
  432. exc_traceback = None
  433. raise exc_type, exc_value, exc_traceback
  434. class AlwaysTask(Task):
  435. def needs_execute(self):
  436. """
  437. Always returns True (indicating this Task should always
  438. be executed).
  439. Subclasses that need this behavior (as opposed to the default
  440. of only executing Nodes that are out of date w.r.t. their
  441. dependencies) can use this as follows:
  442. class MyTaskSubclass(SCons.Taskmaster.Task):
  443. needs_execute = SCons.Taskmaster.Task.execute_always
  444. """
  445. return True
  446. class OutOfDateTask(Task):
  447. def needs_execute(self):
  448. """
  449. Returns True (indicating this Task should be executed) if this
  450. Task's target state indicates it needs executing, which has
  451. already been determined by an earlier up-to-date check.
  452. """
  453. return self.targets[0].get_state() == SCons.Node.executing
  454. def find_cycle(stack, visited):
  455. if stack[-1] in visited:
  456. return None
  457. visited.add(stack[-1])
  458. for n in stack[-1].waiting_parents:
  459. stack.append(n)
  460. if stack[0] == stack[-1]:
  461. return stack
  462. if find_cycle(stack, visited):
  463. return stack
  464. stack.pop()
  465. return None
  466. class Taskmaster(object):
  467. """
  468. The Taskmaster for walking the dependency DAG.
  469. """
  470. def __init__(self, targets=[], tasker=None, order=None, trace=None):
  471. self.original_top = targets
  472. self.top_targets_left = targets[:]
  473. self.top_targets_left.reverse()
  474. self.candidates = []
  475. if tasker is None:
  476. tasker = OutOfDateTask
  477. self.tasker = tasker
  478. if not order:
  479. order = lambda l: l
  480. self.order = order
  481. self.message = None
  482. self.trace = trace
  483. self.next_candidate = self.find_next_candidate
  484. self.pending_children = set()
  485. def find_next_candidate(self):
  486. """
  487. Returns the next candidate Node for (potential) evaluation.
  488. The candidate list (really a stack) initially consists of all of
  489. the top-level (command line) targets provided when the Taskmaster
  490. was initialized. While we walk the DAG, visiting Nodes, all the
  491. children that haven't finished processing get pushed on to the
  492. candidate list. Each child can then be popped and examined in
  493. turn for whether *their* children are all up-to-date, in which
  494. case a Task will be created for their actual evaluation and
  495. potential building.
  496. Here is where we also allow candidate Nodes to alter the list of
  497. Nodes that should be examined. This is used, for example, when
  498. invoking SCons in a source directory. A source directory Node can
  499. return its corresponding build directory Node, essentially saying,
  500. "Hey, you really need to build this thing over here instead."
  501. """
  502. try:
  503. return self.candidates.pop()
  504. except IndexError:
  505. pass
  506. try:
  507. node = self.top_targets_left.pop()
  508. except IndexError:
  509. return None
  510. self.current_top = node
  511. alt, message = node.alter_targets()
  512. if alt:
  513. self.message = message
  514. self.candidates.append(node)
  515. self.candidates.extend(self.order(alt))
  516. node = self.candidates.pop()
  517. return node
  518. def no_next_candidate(self):
  519. """
  520. Stops Taskmaster processing by not returning a next candidate.
  521. Note that we have to clean-up the Taskmaster candidate list
  522. because the cycle detection depends on the fact all nodes have
  523. been processed somehow.
  524. """
  525. while self.candidates:
  526. candidates = self.candidates
  527. self.candidates = []
  528. self.will_not_build(candidates)
  529. return None
  530. def _validate_pending_children(self):
  531. """
  532. Validate the content of the pending_children set. Assert if an
  533. internal error is found.
  534. This function is used strictly for debugging the taskmaster by
  535. checking that no invariants are violated. It is not used in
  536. normal operation.
  537. The pending_children set is used to detect cycles in the
  538. dependency graph. We call a "pending child" a child that is
  539. found in the "pending" state when checking the dependencies of
  540. its parent node.
  541. A pending child can occur when the Taskmaster completes a loop
  542. through a cycle. For example, lets imagine a graph made of
  543. three node (A, B and C) making a cycle. The evaluation starts
  544. at node A. The taskmaster first consider whether node A's
  545. child B is up-to-date. Then, recursively, node B needs to
  546. check whether node C is up-to-date. This leaves us with a
  547. dependency graph looking like:
  548. Next candidate \
  549. \
  550. Node A (Pending) --> Node B(Pending) --> Node C (NoState)
  551. ^ |
  552. | |
  553. +-------------------------------------+
  554. Now, when the Taskmaster examines the Node C's child Node A,
  555. it finds that Node A is in the "pending" state. Therefore,
  556. Node A is a pending child of node C.
  557. Pending children indicate that the Taskmaster has potentially
  558. loop back through a cycle. We say potentially because it could
  559. also occur when a DAG is evaluated in parallel. For example,
  560. consider the following graph:
  561. Node A (Pending) --> Node B(Pending) --> Node C (Pending) --> ...
  562. | ^
  563. | |
  564. +----------> Node D (NoState) --------+
  565. /
  566. Next candidate /
  567. The Taskmaster first evaluates the nodes A, B, and C and
  568. starts building some children of node C. Assuming, that the
  569. maximum parallel level has not been reached, the Taskmaster
  570. will examine Node D. It will find that Node C is a pending
  571. child of Node D.
  572. In summary, evaluating a graph with a cycle will always
  573. involve a pending child at one point. A pending child might
  574. indicate either a cycle or a diamond-shaped DAG. Only a
  575. fraction of the nodes ends-up being a "pending child" of
  576. another node. This keeps the pending_children set small in
  577. practice.
  578. We can differentiate between the two cases if we wait until
  579. the end of the build. At this point, all the pending children
  580. nodes due to a diamond-shaped DAG will have been properly
  581. built (or will have failed to build). But, the pending
  582. children involved in a cycle will still be in the pending
  583. state.
  584. The taskmaster removes nodes from the pending_children set as
  585. soon as a pending_children node moves out of the pending
  586. state. This also helps to keep the pending_children set small.
  587. """
  588. for n in self.pending_children:
  589. assert n.state in (NODE_PENDING, NODE_EXECUTING), \
  590. (str(n), StateString[n.state])
  591. assert len(n.waiting_parents) != 0, (str(n), len(n.waiting_parents))
  592. for p in n.waiting_parents:
  593. assert p.ref_count > 0, (str(n), str(p), p.ref_count)
  594. def trace_message(self, message):
  595. return 'Taskmaster: %s\n' % message
  596. def trace_node(self, node):
  597. return '<%-10s %-3s %s>' % (StateString[node.get_state()],
  598. node.ref_count,
  599. repr(str(node)))
  600. def _find_next_ready_node(self):
  601. """
  602. Finds the next node that is ready to be built.
  603. This is *the* main guts of the DAG walk. We loop through the
  604. list of candidates, looking for something that has no un-built
  605. children (i.e., that is a leaf Node or has dependencies that are
  606. all leaf Nodes or up-to-date). Candidate Nodes are re-scanned
  607. (both the target Node itself and its sources, which are always
  608. scanned in the context of a given target) to discover implicit
  609. dependencies. A Node that must wait for some children to be
  610. built will be put back on the candidates list after the children
  611. have finished building. A Node that has been put back on the
  612. candidates list in this way may have itself (or its sources)
  613. re-scanned, in order to handle generated header files (e.g.) and
  614. the implicit dependencies therein.
  615. Note that this method does not do any signature calculation or
  616. up-to-date check itself. All of that is handled by the Task
  617. class. This is purely concerned with the dependency graph walk.
  618. """
  619. self.ready_exc = None
  620. T = self.trace
  621. if T: T.write(u'\n' + self.trace_message('Looking for a node to evaluate'))
  622. while True:
  623. node = self.next_candidate()
  624. if node is None:
  625. if T: T.write(self.trace_message('No candidate anymore.') + u'\n')
  626. return None
  627. node = node.disambiguate()
  628. state = node.get_state()
  629. # For debugging only:
  630. #
  631. # try:
  632. # self._validate_pending_children()
  633. # except:
  634. # self.ready_exc = sys.exc_info()
  635. # return node
  636. if CollectStats:
  637. if not hasattr(node, 'stats'):
  638. node.stats = Stats()
  639. StatsNodes.append(node)
  640. S = node.stats
  641. S.considered = S.considered + 1
  642. else:
  643. S = None
  644. if T: T.write(self.trace_message(u' Considering node %s and its children:' % self.trace_node(node)))
  645. if state == NODE_NO_STATE:
  646. # Mark this node as being on the execution stack:
  647. node.set_state(NODE_PENDING)
  648. elif state > NODE_PENDING:
  649. # Skip this node if it has already been evaluated:
  650. if S: S.already_handled = S.already_handled + 1
  651. if T: T.write(self.trace_message(u' already handled (executed)'))
  652. continue
  653. executor = node.get_executor()
  654. try:
  655. children = executor.get_all_children()
  656. except SystemExit:
  657. exc_value = sys.exc_info()[1]
  658. e = SCons.Errors.ExplicitExit(node, exc_value.code)
  659. self.ready_exc = (SCons.Errors.ExplicitExit, e)
  660. if T: T.write(self.trace_message(' SystemExit'))
  661. return node
  662. except Exception, e:
  663. # We had a problem just trying to figure out the
  664. # children (like a child couldn't be linked in to a
  665. # VariantDir, or a Scanner threw something). Arrange to
  666. # raise the exception when the Task is "executed."
  667. self.ready_exc = sys.exc_info()
  668. if S: S.problem = S.problem + 1
  669. if T: T.write(self.trace_message(' exception %s while scanning children.\n' % e))
  670. return node
  671. children_not_visited = []
  672. children_pending = set()
  673. children_not_ready = []
  674. children_failed = False
  675. for child in chain(executor.get_all_prerequisites(), children):
  676. childstate = child.get_state()
  677. if T: T.write(self.trace_message(u' ' + self.trace_node(child)))
  678. if childstate == NODE_NO_STATE:
  679. children_not_visited.append(child)
  680. elif childstate == NODE_PENDING:
  681. children_pending.add(child)
  682. elif childstate == NODE_FAILED:
  683. children_failed = True
  684. if childstate <= NODE_EXECUTING:
  685. children_not_ready.append(child)
  686. # These nodes have not even been visited yet. Add
  687. # them to the list so that on some next pass we can
  688. # take a stab at evaluating them (or their children).
  689. children_not_visited.reverse()
  690. self.candidates.extend(self.order(children_not_visited))
  691. #if T and children_not_visited:
  692. # T.write(self.trace_message(' adding to candidates: %s' % map(str, children_not_visited)))
  693. # T.write(self.trace_message(' candidates now: %s\n' % map(str, self.candidates)))
  694. # Skip this node if any of its children have failed.
  695. #
  696. # This catches the case where we're descending a top-level
  697. # target and one of our children failed while trying to be
  698. # built by a *previous* descent of an earlier top-level
  699. # target.
  700. #
  701. # It can also occur if a node is reused in multiple
  702. # targets. One first descends though the one of the
  703. # target, the next time occurs through the other target.
  704. #
  705. # Note that we can only have failed_children if the
  706. # --keep-going flag was used, because without it the build
  707. # will stop before diving in the other branch.
  708. #
  709. # Note that even if one of the children fails, we still
  710. # added the other children to the list of candidate nodes
  711. # to keep on building (--keep-going).
  712. if children_failed:
  713. for n in executor.get_action_targets():
  714. n.set_state(NODE_FAILED)
  715. if S: S.child_failed = S.child_failed + 1
  716. if T: T.write(self.trace_message('****** %s\n' % self.trace_node(node)))
  717. continue
  718. if children_not_ready:
  719. for child in children_not_ready:
  720. # We're waiting on one or more derived targets
  721. # that have not yet finished building.
  722. if S: S.not_built = S.not_built + 1
  723. # Add this node to the waiting parents lists of
  724. # anything we're waiting on, with a reference
  725. # count so we can be put back on the list for
  726. # re-evaluation when they've all finished.
  727. node.ref_count = node.ref_count + child.add_to_waiting_parents(node)
  728. if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' %
  729. (self.trace_node(node), repr(str(child)))))
  730. if T:
  731. for pc in children_pending:
  732. T.write(self.trace_message(' adding %s to the pending children set\n' %
  733. self.trace_node(pc)))
  734. self.pending_children = self.pending_children | children_pending
  735. continue
  736. # Skip this node if it has side-effects that are
  737. # currently being built:
  738. wait_side_effects = False
  739. for se in executor.get_action_side_effects():
  740. if se.get_state() == NODE_EXECUTING:
  741. se.add_to_waiting_s_e(node)
  742. wait_side_effects = True
  743. if wait_side_effects:
  744. if S: S.side_effects = S.side_effects + 1
  745. continue
  746. # The default when we've gotten through all of the checks above:
  747. # this node is ready to be built.
  748. if S: S.build = S.build + 1
  749. if T: T.write(self.trace_message(u'Evaluating %s\n' %
  750. self.trace_node(node)))
  751. # For debugging only:
  752. #
  753. # try:
  754. # self._validate_pending_children()
  755. # except:
  756. # self.ready_exc = sys.exc_info()
  757. # return node
  758. return node
  759. return None
  760. def next_task(self):
  761. """
  762. Returns the next task to be executed.
  763. This simply asks for the next Node to be evaluated, and then wraps
  764. it in the specific Task subclass with which we were initialized.
  765. """
  766. node = self._find_next_ready_node()
  767. if node is None:
  768. return None
  769. tlist = node.get_executor().get_all_targets()
  770. task = self.tasker(self, tlist, node in self.original_top, node)
  771. try:
  772. task.make_ready()
  773. except:
  774. # We had a problem just trying to get this task ready (like
  775. # a child couldn't be linked in to a VariantDir when deciding
  776. # whether this node is current). Arrange to raise the
  777. # exception when the Task is "executed."
  778. self.ready_exc = sys.exc_info()
  779. if self.ready_exc:
  780. task.exception_set(self.ready_exc)
  781. self.ready_exc = None
  782. return task
  783. def will_not_build(self, nodes, node_func=lambda n: None):
  784. """
  785. Perform clean-up about nodes that will never be built. Invokes
  786. a user defined function on all of these nodes (including all
  787. of their parents).
  788. """
  789. T = self.trace
  790. pending_children = self.pending_children
  791. to_visit = set(nodes)
  792. pending_children = pending_children - to_visit
  793. if T:
  794. for n in nodes:
  795. T.write(self.trace_message(' removing node %s from the pending children set\n' %
  796. self.trace_node(n)))
  797. try:
  798. while len(to_visit):
  799. node = to_visit.pop()
  800. node_func(node)
  801. # Prune recursion by flushing the waiting children
  802. # list immediately.
  803. parents = node.waiting_parents
  804. node.waiting_parents = set()
  805. to_visit = to_visit | parents
  806. pending_children = pending_children - parents
  807. for p in parents:
  808. p.ref_count = p.ref_count - 1
  809. if T: T.write(self.trace_message(' removing parent %s from the pending children set\n' %
  810. self.trace_node(p)))
  811. except KeyError:
  812. # The container to_visit has been emptied.
  813. pass
  814. # We have the stick back the pending_children list into the
  815. # taskmaster because the python 1.5.2 compatibility does not
  816. # allow us to use in-place updates
  817. self.pending_children = pending_children
  818. def stop(self):
  819. """
  820. Stops the current build completely.
  821. """
  822. self.next_candidate = self.no_next_candidate
  823. def cleanup(self):
  824. """
  825. Check for dependency cycles.
  826. """
  827. if not self.pending_children:
  828. return
  829. nclist = [(n, find_cycle([n], set())) for n in self.pending_children]
  830. genuine_cycles = [
  831. node for node,cycle in nclist
  832. if cycle or node.get_state() != NODE_EXECUTED
  833. ]
  834. if not genuine_cycles:
  835. # All of the "cycles" found were single nodes in EXECUTED state,
  836. # which is to say, they really weren't cycles. Just return.
  837. return
  838. desc = 'Found dependency cycle(s):\n'
  839. for node, cycle in nclist:
  840. if cycle:
  841. desc = desc + " " + " -> ".join(map(str, cycle)) + "\n"
  842. else:
  843. desc = desc + \
  844. " Internal Error: no cycle found for node %s (%s) in state %s\n" % \
  845. (node, repr(node), StateString[node.get_state()])
  846. raise SCons.Errors.UserError(desc)
  847. # Local Variables:
  848. # tab-width:4
  849. # indent-tabs-mode:nil
  850. # End:
  851. # vim: set expandtab tabstop=4 shiftwidth=4: