cookerdata.py 17 KB

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