cookerdata.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. # Copyright (C) 2003, 2004 Chris Larson
  6. # Copyright (C) 2003, 2004 Phil Blundell
  7. # Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
  8. # Copyright (C) 2005 Holger Hans Peter Freyther
  9. # Copyright (C) 2005 ROAD GmbH
  10. # Copyright (C) 2006 Richard Purdie
  11. #
  12. # This program is free software; you can redistribute it and/or modify
  13. # it under the terms of the GNU General Public License version 2 as
  14. # published by the Free Software Foundation.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. import logging
  25. import os
  26. import re
  27. import sys
  28. from functools import wraps
  29. import bb
  30. from bb import data
  31. import bb.parse
  32. logger = logging.getLogger("BitBake")
  33. parselog = logging.getLogger("BitBake.Parsing")
  34. class ConfigParameters(object):
  35. def __init__(self, argv=sys.argv):
  36. self.options, targets = self.parseCommandLine(argv)
  37. self.environment = self.parseEnvironment()
  38. self.options.pkgs_to_build = targets or []
  39. self.options.tracking = False
  40. if hasattr(self.options, "show_environment") and self.options.show_environment:
  41. self.options.tracking = True
  42. for key, val in self.options.__dict__.items():
  43. setattr(self, key, val)
  44. def parseCommandLine(self, argv=sys.argv):
  45. raise Exception("Caller must implement commandline option parsing")
  46. def parseEnvironment(self):
  47. return os.environ.copy()
  48. def updateFromServer(self, server):
  49. if not self.options.cmd:
  50. defaulttask, error = server.runCommand(["getVariable", "BB_DEFAULT_TASK"])
  51. if error:
  52. raise Exception("Unable to get the value of BB_DEFAULT_TASK from the server: %s" % error)
  53. self.options.cmd = defaulttask or "build"
  54. _, error = server.runCommand(["setConfig", "cmd", self.options.cmd])
  55. if error:
  56. raise Exception("Unable to set configuration option 'cmd' on the server: %s" % error)
  57. if not self.options.pkgs_to_build:
  58. bbpkgs, error = server.runCommand(["getVariable", "BBTARGETS"])
  59. if error:
  60. raise Exception("Unable to get the value of BBTARGETS from the server: %s" % error)
  61. if bbpkgs:
  62. self.options.pkgs_to_build.extend(bbpkgs.split())
  63. def updateToServer(self, server, environment):
  64. options = {}
  65. for o in ["abort", "tryaltconfigs", "force", "invalidate_stamp",
  66. "verbose", "debug", "dry_run", "dump_signatures",
  67. "debug_domains", "extra_assume_provided", "profile",
  68. "prefile", "postfile"]:
  69. options[o] = getattr(self.options, o)
  70. ret, error = server.runCommand(["updateConfig", options, environment])
  71. if error:
  72. raise Exception("Unable to update the server configuration with local parameters: %s" % error)
  73. def parseActions(self):
  74. # Parse any commandline into actions
  75. action = {'action':None, 'msg':None}
  76. if self.options.show_environment:
  77. if 'world' in self.options.pkgs_to_build:
  78. action['msg'] = "'world' is not a valid target for --environment."
  79. elif 'universe' in self.options.pkgs_to_build:
  80. action['msg'] = "'universe' is not a valid target for --environment."
  81. elif len(self.options.pkgs_to_build) > 1:
  82. action['msg'] = "Only one target can be used with the --environment option."
  83. elif self.options.buildfile and len(self.options.pkgs_to_build) > 0:
  84. action['msg'] = "No target should be used with the --environment and --buildfile options."
  85. elif len(self.options.pkgs_to_build) > 0:
  86. action['action'] = ["showEnvironmentTarget", self.options.pkgs_to_build]
  87. else:
  88. action['action'] = ["showEnvironment", self.options.buildfile]
  89. elif self.options.buildfile is not None:
  90. action['action'] = ["buildFile", self.options.buildfile, self.options.cmd]
  91. elif self.options.revisions_changed:
  92. action['action'] = ["compareRevisions"]
  93. elif self.options.show_versions:
  94. action['action'] = ["showVersions"]
  95. elif self.options.parse_only:
  96. action['action'] = ["parseFiles"]
  97. elif self.options.dot_graph:
  98. if self.options.pkgs_to_build:
  99. action['action'] = ["generateDotGraph", self.options.pkgs_to_build, self.options.cmd]
  100. else:
  101. action['msg'] = "Please specify a package name for dependency graph generation."
  102. else:
  103. if self.options.pkgs_to_build:
  104. action['action'] = ["buildTargets", self.options.pkgs_to_build, self.options.cmd]
  105. else:
  106. #action['msg'] = "Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information."
  107. action = None
  108. self.options.initialaction = action
  109. return action
  110. class CookerConfiguration(object):
  111. """
  112. Manages build options and configurations for one run
  113. """
  114. def __init__(self):
  115. self.debug_domains = []
  116. self.extra_assume_provided = []
  117. self.prefile = []
  118. self.postfile = []
  119. self.prefile_server = []
  120. self.postfile_server = []
  121. self.debug = 0
  122. self.cmd = None
  123. self.abort = True
  124. self.force = False
  125. self.profile = False
  126. self.nosetscene = False
  127. self.setsceneonly = False
  128. self.invalidate_stamp = False
  129. self.dump_signatures = []
  130. self.dry_run = False
  131. self.tracking = False
  132. self.interface = []
  133. self.writeeventlog = False
  134. self.env = {}
  135. def setConfigParameters(self, parameters):
  136. for key in self.__dict__.keys():
  137. if key in parameters.options.__dict__:
  138. setattr(self, key, parameters.options.__dict__[key])
  139. self.env = parameters.environment.copy()
  140. self.tracking = parameters.tracking
  141. def setServerRegIdleCallback(self, srcb):
  142. self.server_register_idlecallback = srcb
  143. def __getstate__(self):
  144. state = {}
  145. for key in self.__dict__.keys():
  146. if key == "server_register_idlecallback":
  147. state[key] = None
  148. else:
  149. state[key] = getattr(self, key)
  150. return state
  151. def __setstate__(self,state):
  152. for k in state:
  153. setattr(self, k, state[k])
  154. def catch_parse_error(func):
  155. """Exception handling bits for our parsing"""
  156. @wraps(func)
  157. def wrapped(fn, *args):
  158. try:
  159. return func(fn, *args)
  160. except IOError as exc:
  161. import traceback
  162. parselog.critical(traceback.format_exc())
  163. parselog.critical("Unable to parse %s: %s" % (fn, exc))
  164. sys.exit(1)
  165. except bb.data_smart.ExpansionError as exc:
  166. import traceback
  167. bbdir = os.path.dirname(__file__) + os.sep
  168. exc_class, exc, tb = sys.exc_info()
  169. for tb in iter(lambda: tb.tb_next, None):
  170. # Skip frames in bitbake itself, we only want the metadata
  171. fn, _, _, _ = traceback.extract_tb(tb, 1)[0]
  172. if not fn.startswith(bbdir):
  173. break
  174. parselog.critical("Unable to parse %s" % fn, exc_info=(exc_class, exc, tb))
  175. sys.exit(1)
  176. except bb.parse.ParseError as exc:
  177. parselog.critical(str(exc))
  178. sys.exit(1)
  179. return wrapped
  180. @catch_parse_error
  181. def parse_config_file(fn, data, include=True):
  182. return bb.parse.handle(fn, data, include)
  183. @catch_parse_error
  184. def _inherit(bbclass, data):
  185. bb.parse.BBHandler.inherit(bbclass, "configuration INHERITs", 0, data)
  186. return data
  187. def findConfigFile(configfile, data):
  188. search = []
  189. bbpath = data.getVar("BBPATH")
  190. if bbpath:
  191. for i in bbpath.split(":"):
  192. search.append(os.path.join(i, "conf", configfile))
  193. path = os.getcwd()
  194. while path != "/":
  195. search.append(os.path.join(path, "conf", configfile))
  196. path, _ = os.path.split(path)
  197. for i in search:
  198. if os.path.exists(i):
  199. return i
  200. return None
  201. class CookerDataBuilder(object):
  202. def __init__(self, cookercfg, worker = False):
  203. self.prefiles = cookercfg.prefile
  204. self.postfiles = cookercfg.postfile
  205. self.tracking = cookercfg.tracking
  206. bb.utils.set_context(bb.utils.clean_context())
  207. bb.event.set_class_handlers(bb.event.clean_class_handlers())
  208. self.basedata = bb.data.init()
  209. if self.tracking:
  210. self.basedata.enableTracking()
  211. # Keep a datastore of the initial environment variables and their
  212. # values from when BitBake was launched to enable child processes
  213. # to use environment variables which have been cleaned from the
  214. # BitBake processes env
  215. self.savedenv = bb.data.init()
  216. for k in cookercfg.env:
  217. self.savedenv.setVar(k, cookercfg.env[k])
  218. filtered_keys = bb.utils.approved_variables()
  219. bb.data.inheritFromOS(self.basedata, self.savedenv, filtered_keys)
  220. self.basedata.setVar("BB_ORIGENV", self.savedenv)
  221. if worker:
  222. self.basedata.setVar("BB_WORKERCONTEXT", "1")
  223. self.data = self.basedata
  224. self.mcdata = {}
  225. def parseBaseConfiguration(self):
  226. try:
  227. bb.parse.init_parser(self.basedata)
  228. self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
  229. if self.data.getVar("BB_WORKERCONTEXT", False) is None:
  230. bb.fetch.fetcher_init(self.data)
  231. bb.codeparser.parser_cache_init(self.data)
  232. bb.event.fire(bb.event.ConfigParsed(), self.data)
  233. reparse_cnt = 0
  234. while self.data.getVar("BB_INVALIDCONF", False) is True:
  235. if reparse_cnt > 20:
  236. logger.error("Configuration has been re-parsed over 20 times, "
  237. "breaking out of the loop...")
  238. raise Exception("Too deep config re-parse loop. Check locations where "
  239. "BB_INVALIDCONF is being set (ConfigParsed event handlers)")
  240. self.data.setVar("BB_INVALIDCONF", False)
  241. self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
  242. reparse_cnt += 1
  243. bb.event.fire(bb.event.ConfigParsed(), self.data)
  244. bb.parse.init_parser(self.data)
  245. self.data_hash = self.data.get_hash()
  246. self.mcdata[''] = self.data
  247. multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
  248. for config in multiconfig:
  249. mcdata = self.parseConfigurationFiles(['conf/multiconfig/%s.conf' % config] + self.prefiles, self.postfiles)
  250. bb.event.fire(bb.event.ConfigParsed(), mcdata)
  251. self.mcdata[config] = mcdata
  252. except (SyntaxError, bb.BBHandledException):
  253. raise bb.BBHandledException
  254. except bb.data_smart.ExpansionError as e:
  255. logger.error(str(e))
  256. raise bb.BBHandledException
  257. except Exception:
  258. logger.exception("Error parsing configuration files")
  259. raise bb.BBHandledException
  260. def _findLayerConf(self, data):
  261. return findConfigFile("bblayers.conf", data)
  262. def parseConfigurationFiles(self, prefiles, postfiles):
  263. data = bb.data.createCopy(self.basedata)
  264. # Parse files for loading *before* bitbake.conf and any includes
  265. for f in prefiles:
  266. data = parse_config_file(f, data)
  267. layerconf = self._findLayerConf(data)
  268. if layerconf:
  269. parselog.debug(2, "Found bblayers.conf (%s)", layerconf)
  270. # By definition bblayers.conf is in conf/ of TOPDIR.
  271. # We may have been called with cwd somewhere else so reset TOPDIR
  272. data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf)))
  273. data = parse_config_file(layerconf, data)
  274. layers = (data.getVar('BBLAYERS') or "").split()
  275. data = bb.data.createCopy(data)
  276. approved = bb.utils.approved_variables()
  277. for layer in layers:
  278. if not os.path.isdir(layer):
  279. parselog.critical("Layer directory '%s' does not exist! "
  280. "Please check BBLAYERS in %s" % (layer, layerconf))
  281. sys.exit(1)
  282. parselog.debug(2, "Adding layer %s", layer)
  283. if 'HOME' in approved and '~' in layer:
  284. layer = os.path.expanduser(layer)
  285. if layer.endswith('/'):
  286. layer = layer.rstrip('/')
  287. data.setVar('LAYERDIR', layer)
  288. data.setVar('LAYERDIR_RE', re.escape(layer))
  289. data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data)
  290. data.expandVarref('LAYERDIR')
  291. data.expandVarref('LAYERDIR_RE')
  292. data.delVar('LAYERDIR_RE')
  293. data.delVar('LAYERDIR')
  294. if not data.getVar("BBPATH"):
  295. msg = "The BBPATH variable is not set"
  296. if not layerconf:
  297. msg += (" and bitbake did not find a conf/bblayers.conf file in"
  298. " the expected location.\nMaybe you accidentally"
  299. " invoked bitbake from the wrong directory?")
  300. raise SystemExit(msg)
  301. data = parse_config_file(os.path.join("conf", "bitbake.conf"), data)
  302. # Parse files for loading *after* bitbake.conf and any includes
  303. for p in postfiles:
  304. data = parse_config_file(p, data)
  305. # Handle any INHERITs and inherit the base class
  306. bbclasses = ["base"] + (data.getVar('INHERIT') or "").split()
  307. for bbclass in bbclasses:
  308. data = _inherit(bbclass, data)
  309. # Nomally we only register event handlers at the end of parsing .bb files
  310. # We register any handlers we've found so far here...
  311. for var in data.getVar('__BBHANDLERS', False) or []:
  312. handlerfn = data.getVarFlag(var, "filename", False)
  313. if not handlerfn:
  314. parselog.critical("Undefined event handler function '%s'" % var)
  315. sys.exit(1)
  316. handlerln = int(data.getVarFlag(var, "lineno", False))
  317. bb.event.register(var, data.getVar(var, False), (data.getVarFlag(var, "eventmask") or "").split(), handlerfn, handlerln)
  318. data.setVar('BBINCLUDED',bb.parse.get_file_depends(data))
  319. return data