build.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #!/usr/bin/env python
  2. # ex:ts=4:sw=4:sts=4:et
  3. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  4. """
  5. BitBake 'Build' implementation
  6. Core code for function execution and task handling in the
  7. BitBake build tools.
  8. Copyright (C) 2003, 2004 Chris Larson
  9. Based on Gentoo's portage.py.
  10. This program is free software; you can redistribute it and/or modify it under
  11. the terms of the GNU General Public License as published by the Free Software
  12. Foundation; either version 2 of the License, or (at your option) any later
  13. version.
  14. This program is distributed in the hope that it will be useful, but WITHOUT
  15. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  16. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License along with
  18. Based on functions from the base bb module, Copyright 2003 Holger Schurig
  19. """
  20. from bb import debug, data, fetch, fatal, error, note, event, mkdirhier
  21. import bb, os
  22. # data holds flags and function name for a given task
  23. _task_data = data.init()
  24. # graph represents task interdependencies
  25. _task_graph = bb.digraph()
  26. # stack represents execution order, excepting dependencies
  27. _task_stack = []
  28. # events
  29. class FuncFailed(Exception):
  30. """Executed function failed"""
  31. class EventException(Exception):
  32. """Exception which is associated with an Event."""
  33. def __init__(self, msg, event):
  34. self.args = msg, event
  35. class TaskBase(event.Event):
  36. """Base class for task events"""
  37. def __init__(self, t, d ):
  38. self._task = t
  39. event.Event.__init__(self, d)
  40. def getTask(self):
  41. return self._task
  42. def setTask(self, task):
  43. self._task = task
  44. task = property(getTask, setTask, None, "task property")
  45. class TaskStarted(TaskBase):
  46. """Task execution started"""
  47. class TaskSucceeded(TaskBase):
  48. """Task execution completed"""
  49. class TaskFailed(TaskBase):
  50. """Task execution failed"""
  51. class InvalidTask(TaskBase):
  52. """Invalid Task"""
  53. # functions
  54. def init(data):
  55. global _task_data, _task_graph, _task_stack
  56. _task_data = data.init()
  57. _task_graph = bb.digraph()
  58. _task_stack = []
  59. def exec_func(func, d, dirs = None):
  60. """Execute an BB 'function'"""
  61. body = data.getVar(func, d)
  62. if not body:
  63. return
  64. if not dirs:
  65. dirs = (data.getVarFlag(func, 'dirs', d) or "").split()
  66. for adir in dirs:
  67. adir = data.expand(adir, d)
  68. mkdirhier(adir)
  69. if len(dirs) > 0:
  70. adir = dirs[-1]
  71. else:
  72. adir = data.getVar('B', d, 1)
  73. adir = data.expand(adir, d)
  74. try:
  75. prevdir = os.getcwd()
  76. except OSError:
  77. prevdir = data.expand('${TOPDIR}', d)
  78. if adir and os.access(adir, os.F_OK):
  79. os.chdir(adir)
  80. if data.getVarFlag(func, "python", d):
  81. exec_func_python(func, d)
  82. else:
  83. exec_func_shell(func, d)
  84. if os.path.exists(prevdir):
  85. os.chdir(prevdir)
  86. def exec_func_python(func, d):
  87. """Execute a python BB 'function'"""
  88. import re, os
  89. tmp = "def " + func + "():\n%s" % data.getVar(func, d)
  90. comp = compile(tmp + '\n' + func + '()', bb.data.getVar('FILE', d, 1) + ':' + func, "exec")
  91. prevdir = os.getcwd()
  92. g = {} # globals
  93. g['bb'] = bb
  94. g['os'] = os
  95. g['d'] = d
  96. exec comp in g
  97. if os.path.exists(prevdir):
  98. os.chdir(prevdir)
  99. def exec_func_shell(func, d):
  100. """Execute a shell BB 'function' Returns true if execution was successful.
  101. For this, it creates a bash shell script in the tmp dectory, writes the local
  102. data into it and finally executes. The output of the shell will end in a log file and stdout.
  103. Note on directory behavior. The 'dirs' varflag should contain a list
  104. of the directories you need created prior to execution. The last
  105. item in the list is where we will chdir/cd to.
  106. """
  107. import sys
  108. deps = data.getVarFlag(func, 'deps', d)
  109. check = data.getVarFlag(func, 'check', d)
  110. if check in globals():
  111. if globals()[check](func, deps):
  112. return
  113. global logfile
  114. t = data.getVar('T', d, 1)
  115. if not t:
  116. return 0
  117. mkdirhier(t)
  118. logfile = "%s/log.%s.%s" % (t, func, str(os.getpid()))
  119. runfile = "%s/run.%s.%s" % (t, func, str(os.getpid()))
  120. f = open(runfile, "w")
  121. f.write("#!/bin/sh -e\n")
  122. if bb.debug_level > 0: f.write("set -x\n")
  123. data.emit_env(f, d)
  124. f.write("cd %s\n" % os.getcwd())
  125. if func: f.write("%s\n" % func)
  126. f.close()
  127. os.chmod(runfile, 0775)
  128. if not func:
  129. error("Function not specified")
  130. raise FuncFailed()
  131. # open logs
  132. si = file('/dev/null', 'r')
  133. try:
  134. if bb.debug_level > 0:
  135. so = os.popen("tee \"%s\"" % logfile, "w")
  136. else:
  137. so = file(logfile, 'w')
  138. except OSError, e:
  139. bb.error("opening log file: %s" % e)
  140. pass
  141. se = so
  142. # dup the existing fds so we dont lose them
  143. osi = [os.dup(sys.stdin.fileno()), sys.stdin.fileno()]
  144. oso = [os.dup(sys.stdout.fileno()), sys.stdout.fileno()]
  145. ose = [os.dup(sys.stderr.fileno()), sys.stderr.fileno()]
  146. # replace those fds with our own
  147. os.dup2(si.fileno(), osi[1])
  148. os.dup2(so.fileno(), oso[1])
  149. os.dup2(se.fileno(), ose[1])
  150. # execute function
  151. prevdir = os.getcwd()
  152. if data.getVarFlag(func, "fakeroot", d):
  153. maybe_fakeroot = "PATH=\"%s\" fakeroot " % bb.data.getVar("PATH", d, 1)
  154. else:
  155. maybe_fakeroot = ''
  156. ret = os.system('%ssh -e %s' % (maybe_fakeroot, runfile))
  157. os.chdir(prevdir)
  158. # restore the backups
  159. os.dup2(osi[0], osi[1])
  160. os.dup2(oso[0], oso[1])
  161. os.dup2(ose[0], ose[1])
  162. # close our logs
  163. si.close()
  164. so.close()
  165. se.close()
  166. # close the backup fds
  167. os.close(osi[0])
  168. os.close(oso[0])
  169. os.close(ose[0])
  170. if ret==0:
  171. if bb.debug_level > 0:
  172. os.remove(runfile)
  173. # os.remove(logfile)
  174. return
  175. else:
  176. error("function %s failed" % func)
  177. if data.getVar("BBINCLUDELOGS", d):
  178. error("log data follows (%s)" % logfile)
  179. f = open(logfile, "r")
  180. while True:
  181. l = f.readline()
  182. if l == '':
  183. break
  184. l = l.rstrip()
  185. print '| %s' % l
  186. f.close()
  187. else:
  188. error("see log in %s" % logfile)
  189. raise FuncFailed( logfile )
  190. def exec_task(task, d):
  191. """Execute an BB 'task'
  192. The primary difference between executing a task versus executing
  193. a function is that a task exists in the task digraph, and therefore
  194. has dependencies amongst other tasks."""
  195. # check if the task is in the graph..
  196. task_graph = data.getVar('_task_graph', d)
  197. if not task_graph:
  198. task_graph = bb.digraph()
  199. data.setVar('_task_graph', task_graph, d)
  200. task_cache = data.getVar('_task_cache', d)
  201. if not task_cache:
  202. task_cache = []
  203. data.setVar('_task_cache', task_cache, d)
  204. if not task_graph.hasnode(task):
  205. raise EventException("Missing node in task graph", InvalidTask(task, d))
  206. # check whether this task needs executing..
  207. if not data.getVarFlag(task, 'force', d):
  208. if stamp_is_current(task, d):
  209. return 1
  210. # follow digraph path up, then execute our way back down
  211. def execute(graph, item):
  212. if data.getVarFlag(item, 'task', d):
  213. if item in task_cache:
  214. return 1
  215. if task != item:
  216. # deeper than toplevel, exec w/ deps
  217. exec_task(item, d)
  218. return 1
  219. try:
  220. debug(1, "Executing task %s" % item)
  221. old_overrides = data.getVar('OVERRIDES', d, 0)
  222. localdata = data.createCopy(d)
  223. data.setVar('OVERRIDES', 'task_%s:%s' % (item, old_overrides), localdata)
  224. data.update_data(localdata)
  225. event.fire(TaskStarted(item, localdata))
  226. exec_func(item, localdata)
  227. event.fire(TaskSucceeded(item, localdata))
  228. task_cache.append(item)
  229. data.setVar('_task_cache', task_cache, d)
  230. except FuncFailed, reason:
  231. note( "Task failed: %s" % reason )
  232. failedevent = TaskFailed(item, d)
  233. event.fire(failedevent)
  234. raise EventException("Function failed in task: %s" % reason, failedevent)
  235. # execute
  236. task_graph.walkdown(task, execute)
  237. # make stamp, or cause event and raise exception
  238. if not data.getVarFlag(task, 'nostamp', d):
  239. mkstamp(task, d)
  240. def stamp_is_current(task, d, checkdeps = 1):
  241. """Check status of a given task's stamp. returns 0 if it is not current and needs updating."""
  242. task_graph = data.getVar('_task_graph', d)
  243. if not task_graph:
  244. task_graph = bb.digraph()
  245. data.setVar('_task_graph', task_graph, d)
  246. stamp = data.getVar('STAMP', d)
  247. if not stamp:
  248. return 0
  249. stampfile = "%s.%s" % (data.expand(stamp, d), task)
  250. if not os.access(stampfile, os.F_OK):
  251. return 0
  252. if checkdeps == 0:
  253. return 1
  254. import stat
  255. tasktime = os.stat(stampfile)[stat.ST_MTIME]
  256. _deps = []
  257. def checkStamp(graph, task):
  258. # check for existance
  259. if data.getVarFlag(task, 'nostamp', d):
  260. return 1
  261. if not stamp_is_current(task, d, 0):
  262. return 0
  263. depfile = "%s.%s" % (data.expand(stamp, d), task)
  264. deptime = os.stat(depfile)[stat.ST_MTIME]
  265. if deptime > tasktime:
  266. return 0
  267. return 1
  268. return task_graph.walkdown(task, checkStamp)
  269. def md5_is_current(task):
  270. """Check if a md5 file for a given task is current"""
  271. def mkstamp(task, d):
  272. """Creates/updates a stamp for a given task"""
  273. stamp = data.getVar('STAMP', d)
  274. if not stamp:
  275. return
  276. stamp = "%s.%s" % (data.expand(stamp, d), task)
  277. mkdirhier(os.path.dirname(stamp))
  278. open(stamp, "w+")
  279. def add_task(task, deps, d):
  280. task_graph = data.getVar('_task_graph', d)
  281. if not task_graph:
  282. task_graph = bb.digraph()
  283. data.setVarFlag(task, 'task', 1, d)
  284. task_graph.addnode(task, None)
  285. for dep in deps:
  286. if not task_graph.hasnode(dep):
  287. task_graph.addnode(dep, None)
  288. task_graph.addnode(task, dep)
  289. # don't assume holding a reference
  290. data.setVar('_task_graph', task_graph, d)
  291. def remove_task(task, kill, d):
  292. """Remove an BB 'task'.
  293. If kill is 1, also remove tasks that depend on this task."""
  294. task_graph = data.getVar('_task_graph', d)
  295. if not task_graph:
  296. task_graph = bb.digraph()
  297. if not task_graph.hasnode(task):
  298. return
  299. data.delVarFlag(task, 'task', d)
  300. ref = 1
  301. if kill == 1:
  302. ref = 2
  303. task_graph.delnode(task, ref)
  304. data.setVar('_task_graph', task_graph, d)
  305. def task_exists(task, d):
  306. task_graph = data.getVar('_task_graph', d)
  307. if not task_graph:
  308. task_graph = bb.digraph()
  309. data.setVar('_task_graph', task_graph, d)
  310. return task_graph.hasnode(task)
  311. def get_task_data():
  312. return _task_data