cooker.py 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160
  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 - 2007 Richard Purdie
  9. #
  10. # SPDX-License-Identifier: GPL-2.0-only
  11. #
  12. import sys, os, glob, os.path, re, time
  13. import atexit
  14. import itertools
  15. import logging
  16. import multiprocessing
  17. import sre_constants
  18. import threading
  19. from io import StringIO, UnsupportedOperation
  20. from contextlib import closing
  21. from functools import wraps
  22. from collections import defaultdict, namedtuple
  23. import bb, bb.exceptions, bb.command
  24. from bb import utils, data, parse, event, cache, providers, taskdata, runqueue, build
  25. import queue
  26. import signal
  27. import subprocess
  28. import errno
  29. import prserv.serv
  30. import pyinotify
  31. import json
  32. import pickle
  33. import codecs
  34. logger = logging.getLogger("BitBake")
  35. collectlog = logging.getLogger("BitBake.Collection")
  36. buildlog = logging.getLogger("BitBake.Build")
  37. parselog = logging.getLogger("BitBake.Parsing")
  38. providerlog = logging.getLogger("BitBake.Provider")
  39. class NoSpecificMatch(bb.BBHandledException):
  40. """
  41. Exception raised when no or multiple file matches are found
  42. """
  43. class NothingToBuild(Exception):
  44. """
  45. Exception raised when there is nothing to build
  46. """
  47. class CollectionError(bb.BBHandledException):
  48. """
  49. Exception raised when layer configuration is incorrect
  50. """
  51. class state:
  52. initial, parsing, running, shutdown, forceshutdown, stopped, error = list(range(7))
  53. @classmethod
  54. def get_name(cls, code):
  55. for name in dir(cls):
  56. value = getattr(cls, name)
  57. if type(value) == type(cls.initial) and value == code:
  58. return name
  59. raise ValueError("Invalid status code: %s" % code)
  60. class SkippedPackage:
  61. def __init__(self, info = None, reason = None):
  62. self.pn = None
  63. self.skipreason = None
  64. self.provides = None
  65. self.rprovides = None
  66. if info:
  67. self.pn = info.pn
  68. self.skipreason = info.skipreason
  69. self.provides = info.provides
  70. self.rprovides = info.rprovides
  71. elif reason:
  72. self.skipreason = reason
  73. class CookerFeatures(object):
  74. _feature_list = [HOB_EXTRA_CACHES, BASEDATASTORE_TRACKING, SEND_SANITYEVENTS] = list(range(3))
  75. def __init__(self):
  76. self._features=set()
  77. def setFeature(self, f):
  78. # validate we got a request for a feature we support
  79. if f not in CookerFeatures._feature_list:
  80. return
  81. self._features.add(f)
  82. def __contains__(self, f):
  83. return f in self._features
  84. def __iter__(self):
  85. return self._features.__iter__()
  86. def __next__(self):
  87. return next(self._features)
  88. class EventWriter:
  89. def __init__(self, cooker, eventfile):
  90. self.file_inited = None
  91. self.cooker = cooker
  92. self.eventfile = eventfile
  93. self.event_queue = []
  94. def write_event(self, event):
  95. with open(self.eventfile, "a") as f:
  96. try:
  97. str_event = codecs.encode(pickle.dumps(event), 'base64').decode('utf-8')
  98. f.write("%s\n" % json.dumps({"class": event.__module__ + "." + event.__class__.__name__,
  99. "vars": str_event}))
  100. except Exception as err:
  101. import traceback
  102. print(err, traceback.format_exc())
  103. def send(self, event):
  104. if self.file_inited:
  105. # we have the file, just write the event
  106. self.write_event(event)
  107. else:
  108. # init on bb.event.BuildStarted
  109. name = "%s.%s" % (event.__module__, event.__class__.__name__)
  110. if name in ("bb.event.BuildStarted", "bb.cooker.CookerExit"):
  111. with open(self.eventfile, "w") as f:
  112. f.write("%s\n" % json.dumps({ "allvariables" : self.cooker.getAllKeysWithFlags(["doc", "func"])}))
  113. self.file_inited = True
  114. # write pending events
  115. for evt in self.event_queue:
  116. self.write_event(evt)
  117. # also write the current event
  118. self.write_event(event)
  119. else:
  120. # queue all events until the file is inited
  121. self.event_queue.append(event)
  122. #============================================================================#
  123. # BBCooker
  124. #============================================================================#
  125. class BBCooker:
  126. """
  127. Manages one bitbake build run
  128. """
  129. def __init__(self, configuration, featureSet=None):
  130. self.recipecaches = None
  131. self.skiplist = {}
  132. self.featureset = CookerFeatures()
  133. if featureSet:
  134. for f in featureSet:
  135. self.featureset.setFeature(f)
  136. self.configuration = configuration
  137. bb.debug(1, "BBCooker starting %s" % time.time())
  138. sys.stdout.flush()
  139. self.configwatcher = pyinotify.WatchManager()
  140. bb.debug(1, "BBCooker pyinotify1 %s" % time.time())
  141. sys.stdout.flush()
  142. self.configwatcher.bbseen = []
  143. self.configwatcher.bbwatchedfiles = []
  144. self.confignotifier = pyinotify.Notifier(self.configwatcher, self.config_notifications)
  145. bb.debug(1, "BBCooker pyinotify2 %s" % time.time())
  146. sys.stdout.flush()
  147. self.watchmask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_CREATE | pyinotify.IN_DELETE | \
  148. pyinotify.IN_DELETE_SELF | pyinotify.IN_MODIFY | pyinotify.IN_MOVE_SELF | \
  149. pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO
  150. self.watcher = pyinotify.WatchManager()
  151. bb.debug(1, "BBCooker pyinotify3 %s" % time.time())
  152. sys.stdout.flush()
  153. self.watcher.bbseen = []
  154. self.watcher.bbwatchedfiles = []
  155. self.notifier = pyinotify.Notifier(self.watcher, self.notifications)
  156. bb.debug(1, "BBCooker pyinotify complete %s" % time.time())
  157. sys.stdout.flush()
  158. # If being called by something like tinfoil, we need to clean cached data
  159. # which may now be invalid
  160. bb.parse.clear_cache()
  161. bb.parse.BBHandler.cached_statements = {}
  162. self.ui_cmdline = None
  163. self.initConfigurationData()
  164. bb.debug(1, "BBCooker parsed base configuration %s" % time.time())
  165. sys.stdout.flush()
  166. # we log all events to a file if so directed
  167. if self.configuration.writeeventlog:
  168. # register the log file writer as UI Handler
  169. writer = EventWriter(self, self.configuration.writeeventlog)
  170. EventLogWriteHandler = namedtuple('EventLogWriteHandler', ['event'])
  171. bb.event.register_UIHhandler(EventLogWriteHandler(writer))
  172. self.inotify_modified_files = []
  173. def _process_inotify_updates(server, cooker, abort):
  174. cooker.process_inotify_updates()
  175. return 1.0
  176. self.configuration.server_register_idlecallback(_process_inotify_updates, self)
  177. # TOSTOP must not be set or our children will hang when they output
  178. try:
  179. fd = sys.stdout.fileno()
  180. if os.isatty(fd):
  181. import termios
  182. tcattr = termios.tcgetattr(fd)
  183. if tcattr[3] & termios.TOSTOP:
  184. buildlog.info("The terminal had the TOSTOP bit set, clearing...")
  185. tcattr[3] = tcattr[3] & ~termios.TOSTOP
  186. termios.tcsetattr(fd, termios.TCSANOW, tcattr)
  187. except UnsupportedOperation:
  188. pass
  189. self.command = bb.command.Command(self)
  190. self.state = state.initial
  191. self.parser = None
  192. signal.signal(signal.SIGTERM, self.sigterm_exception)
  193. # Let SIGHUP exit as SIGTERM
  194. signal.signal(signal.SIGHUP, self.sigterm_exception)
  195. bb.debug(1, "BBCooker startup complete %s" % time.time())
  196. sys.stdout.flush()
  197. def process_inotify_updates(self):
  198. for n in [self.confignotifier, self.notifier]:
  199. if n.check_events(timeout=0):
  200. # read notified events and enqeue them
  201. n.read_events()
  202. n.process_events()
  203. def config_notifications(self, event):
  204. if event.maskname == "IN_Q_OVERFLOW":
  205. bb.warn("inotify event queue overflowed, invalidating caches.")
  206. self.parsecache_valid = False
  207. self.baseconfig_valid = False
  208. bb.parse.clear_cache()
  209. return
  210. if not event.pathname in self.configwatcher.bbwatchedfiles:
  211. return
  212. if not event.pathname in self.inotify_modified_files:
  213. self.inotify_modified_files.append(event.pathname)
  214. self.baseconfig_valid = False
  215. def notifications(self, event):
  216. if event.maskname == "IN_Q_OVERFLOW":
  217. bb.warn("inotify event queue overflowed, invalidating caches.")
  218. self.parsecache_valid = False
  219. bb.parse.clear_cache()
  220. return
  221. if event.pathname.endswith("bitbake-cookerdaemon.log") \
  222. or event.pathname.endswith("bitbake.lock"):
  223. return
  224. if not event.pathname in self.inotify_modified_files:
  225. self.inotify_modified_files.append(event.pathname)
  226. self.parsecache_valid = False
  227. def add_filewatch(self, deps, watcher=None, dirs=False):
  228. if not watcher:
  229. watcher = self.watcher
  230. for i in deps:
  231. watcher.bbwatchedfiles.append(i[0])
  232. if dirs:
  233. f = i[0]
  234. else:
  235. f = os.path.dirname(i[0])
  236. if f in watcher.bbseen:
  237. continue
  238. watcher.bbseen.append(f)
  239. watchtarget = None
  240. while True:
  241. # We try and add watches for files that don't exist but if they did, would influence
  242. # the parser. The parent directory of these files may not exist, in which case we need
  243. # to watch any parent that does exist for changes.
  244. try:
  245. watcher.add_watch(f, self.watchmask, quiet=False)
  246. if watchtarget:
  247. watcher.bbwatchedfiles.append(watchtarget)
  248. break
  249. except pyinotify.WatchManagerError as e:
  250. if 'ENOENT' in str(e):
  251. watchtarget = f
  252. f = os.path.dirname(f)
  253. if f in watcher.bbseen:
  254. break
  255. watcher.bbseen.append(f)
  256. continue
  257. if 'ENOSPC' in str(e):
  258. providerlog.error("No space left on device or exceeds fs.inotify.max_user_watches?")
  259. providerlog.error("To check max_user_watches: sysctl -n fs.inotify.max_user_watches.")
  260. providerlog.error("To modify max_user_watches: sysctl -n -w fs.inotify.max_user_watches=<value>.")
  261. providerlog.error("Root privilege is required to modify max_user_watches.")
  262. raise
  263. def sigterm_exception(self, signum, stackframe):
  264. if signum == signal.SIGTERM:
  265. bb.warn("Cooker received SIGTERM, shutting down...")
  266. elif signum == signal.SIGHUP:
  267. bb.warn("Cooker received SIGHUP, shutting down...")
  268. self.state = state.forceshutdown
  269. def setFeatures(self, features):
  270. # we only accept a new feature set if we're in state initial, so we can reset without problems
  271. if not self.state in [state.initial, state.shutdown, state.forceshutdown, state.stopped, state.error]:
  272. raise Exception("Illegal state for feature set change")
  273. original_featureset = list(self.featureset)
  274. for feature in features:
  275. self.featureset.setFeature(feature)
  276. bb.debug(1, "Features set %s (was %s)" % (original_featureset, list(self.featureset)))
  277. if (original_featureset != list(self.featureset)) and self.state != state.error:
  278. self.reset()
  279. def initConfigurationData(self):
  280. self.state = state.initial
  281. self.caches_array = []
  282. # Need to preserve BB_CONSOLELOG over resets
  283. consolelog = None
  284. if hasattr(self, "data"):
  285. consolelog = self.data.getVar("BB_CONSOLELOG")
  286. if CookerFeatures.BASEDATASTORE_TRACKING in self.featureset:
  287. self.enableDataTracking()
  288. all_extra_cache_names = []
  289. # We hardcode all known cache types in a single place, here.
  290. if CookerFeatures.HOB_EXTRA_CACHES in self.featureset:
  291. all_extra_cache_names.append("bb.cache_extra:HobRecipeInfo")
  292. caches_name_array = ['bb.cache:CoreRecipeInfo'] + all_extra_cache_names
  293. # At least CoreRecipeInfo will be loaded, so caches_array will never be empty!
  294. # This is the entry point, no further check needed!
  295. for var in caches_name_array:
  296. try:
  297. module_name, cache_name = var.split(':')
  298. module = __import__(module_name, fromlist=(cache_name,))
  299. self.caches_array.append(getattr(module, cache_name))
  300. except ImportError as exc:
  301. logger.critical("Unable to import extra RecipeInfo '%s' from '%s': %s" % (cache_name, module_name, exc))
  302. sys.exit("FATAL: Failed to import extra cache class '%s'." % cache_name)
  303. self.databuilder = bb.cookerdata.CookerDataBuilder(self.configuration, False)
  304. self.databuilder.parseBaseConfiguration()
  305. self.data = self.databuilder.data
  306. self.data_hash = self.databuilder.data_hash
  307. self.extraconfigdata = {}
  308. if consolelog:
  309. self.data.setVar("BB_CONSOLELOG", consolelog)
  310. self.data.setVar('BB_CMDLINE', self.ui_cmdline)
  311. #
  312. # Copy of the data store which has been expanded.
  313. # Used for firing events and accessing variables where expansion needs to be accounted for
  314. #
  315. bb.parse.init_parser(self.data)
  316. if CookerFeatures.BASEDATASTORE_TRACKING in self.featureset:
  317. self.disableDataTracking()
  318. self.data.renameVar("__depends", "__base_depends")
  319. self.add_filewatch(self.data.getVar("__base_depends", False), self.configwatcher)
  320. self.baseconfig_valid = True
  321. self.parsecache_valid = False
  322. def handlePRServ(self):
  323. # Setup a PR Server based on the new configuration
  324. try:
  325. self.prhost = prserv.serv.auto_start(self.data)
  326. except prserv.serv.PRServiceConfigError as e:
  327. bb.fatal("Unable to start PR Server, exitting")
  328. def enableDataTracking(self):
  329. self.configuration.tracking = True
  330. if hasattr(self, "data"):
  331. self.data.enableTracking()
  332. def disableDataTracking(self):
  333. self.configuration.tracking = False
  334. if hasattr(self, "data"):
  335. self.data.disableTracking()
  336. def parseConfiguration(self):
  337. # Set log file verbosity
  338. verboselogs = bb.utils.to_boolean(self.data.getVar("BB_VERBOSE_LOGS", False))
  339. if verboselogs:
  340. bb.msg.loggerVerboseLogs = True
  341. # Change nice level if we're asked to
  342. nice = self.data.getVar("BB_NICE_LEVEL")
  343. if nice:
  344. curnice = os.nice(0)
  345. nice = int(nice) - curnice
  346. buildlog.verbose("Renice to %s " % os.nice(nice))
  347. if self.recipecaches:
  348. del self.recipecaches
  349. self.multiconfigs = self.databuilder.mcdata.keys()
  350. self.recipecaches = {}
  351. for mc in self.multiconfigs:
  352. self.recipecaches[mc] = bb.cache.CacheData(self.caches_array)
  353. self.handleCollections(self.data.getVar("BBFILE_COLLECTIONS"))
  354. self.parsecache_valid = False
  355. def updateConfigOpts(self, options, environment, cmdline):
  356. self.ui_cmdline = cmdline
  357. clean = True
  358. for o in options:
  359. if o in ['prefile', 'postfile']:
  360. # Only these options may require a reparse
  361. try:
  362. if getattr(self.configuration, o) == options[o]:
  363. # Value is the same, no need to mark dirty
  364. continue
  365. except AttributeError:
  366. pass
  367. logger.debug(1, "Marking as dirty due to '%s' option change to '%s'" % (o, options[o]))
  368. print("Marking as dirty due to '%s' option change to '%s'" % (o, options[o]))
  369. clean = False
  370. setattr(self.configuration, o, options[o])
  371. for k in bb.utils.approved_variables():
  372. if k in environment and k not in self.configuration.env:
  373. logger.debug(1, "Updating new environment variable %s to %s" % (k, environment[k]))
  374. self.configuration.env[k] = environment[k]
  375. clean = False
  376. if k in self.configuration.env and k not in environment:
  377. logger.debug(1, "Updating environment variable %s (deleted)" % (k))
  378. del self.configuration.env[k]
  379. clean = False
  380. if k not in self.configuration.env and k not in environment:
  381. continue
  382. if environment[k] != self.configuration.env[k]:
  383. logger.debug(1, "Updating environment variable %s from %s to %s" % (k, self.configuration.env[k], environment[k]))
  384. self.configuration.env[k] = environment[k]
  385. clean = False
  386. if not clean:
  387. logger.debug(1, "Base environment change, triggering reparse")
  388. self.reset()
  389. def runCommands(self, server, data, abort):
  390. """
  391. Run any queued asynchronous command
  392. This is done by the idle handler so it runs in true context rather than
  393. tied to any UI.
  394. """
  395. return self.command.runAsyncCommand()
  396. def showVersions(self):
  397. (latest_versions, preferred_versions) = self.findProviders()
  398. logger.plain("%-35s %25s %25s", "Recipe Name", "Latest Version", "Preferred Version")
  399. logger.plain("%-35s %25s %25s\n", "===========", "==============", "=================")
  400. for p in sorted(self.recipecaches[''].pkg_pn):
  401. pref = preferred_versions[p]
  402. latest = latest_versions[p]
  403. prefstr = pref[0][0] + ":" + pref[0][1] + '-' + pref[0][2]
  404. lateststr = latest[0][0] + ":" + latest[0][1] + "-" + latest[0][2]
  405. if pref == latest:
  406. prefstr = ""
  407. logger.plain("%-35s %25s %25s", p, lateststr, prefstr)
  408. def showEnvironment(self, buildfile=None, pkgs_to_build=None):
  409. """
  410. Show the outer or per-recipe environment
  411. """
  412. fn = None
  413. envdata = None
  414. if not pkgs_to_build:
  415. pkgs_to_build = []
  416. orig_tracking = self.configuration.tracking
  417. if not orig_tracking:
  418. self.enableDataTracking()
  419. self.reset()
  420. if buildfile:
  421. # Parse the configuration here. We need to do it explicitly here since
  422. # this showEnvironment() code path doesn't use the cache
  423. self.parseConfiguration()
  424. fn, cls, mc = bb.cache.virtualfn2realfn(buildfile)
  425. fn = self.matchFile(fn)
  426. fn = bb.cache.realfn2virtual(fn, cls, mc)
  427. elif len(pkgs_to_build) == 1:
  428. ignore = self.data.getVar("ASSUME_PROVIDED") or ""
  429. if pkgs_to_build[0] in set(ignore.split()):
  430. bb.fatal("%s is in ASSUME_PROVIDED" % pkgs_to_build[0])
  431. taskdata, runlist = self.buildTaskData(pkgs_to_build, None, self.configuration.abort, allowincomplete=True)
  432. mc = runlist[0][0]
  433. fn = runlist[0][3]
  434. else:
  435. envdata = self.data
  436. data.expandKeys(envdata)
  437. parse.ast.runAnonFuncs(envdata)
  438. if fn:
  439. try:
  440. bb_cache = bb.cache.Cache(self.databuilder, self.data_hash, self.caches_array)
  441. envdata = bb_cache.loadDataFull(fn, self.collection.get_file_appends(fn))
  442. except Exception as e:
  443. parselog.exception("Unable to read %s", fn)
  444. raise
  445. # Display history
  446. with closing(StringIO()) as env:
  447. self.data.inchistory.emit(env)
  448. logger.plain(env.getvalue())
  449. # emit variables and shell functions
  450. with closing(StringIO()) as env:
  451. data.emit_env(env, envdata, True)
  452. logger.plain(env.getvalue())
  453. # emit the metadata which isnt valid shell
  454. for e in sorted(envdata.keys()):
  455. if envdata.getVarFlag(e, 'func', False) and envdata.getVarFlag(e, 'python', False):
  456. logger.plain("\npython %s () {\n%s}\n", e, envdata.getVar(e, False))
  457. if not orig_tracking:
  458. self.disableDataTracking()
  459. self.reset()
  460. def buildTaskData(self, pkgs_to_build, task, abort, allowincomplete=False):
  461. """
  462. Prepare a runqueue and taskdata object for iteration over pkgs_to_build
  463. """
  464. bb.event.fire(bb.event.TreeDataPreparationStarted(), self.data)
  465. # A task of None means use the default task
  466. if task is None:
  467. task = self.configuration.cmd
  468. if not task.startswith("do_"):
  469. task = "do_%s" % task
  470. targetlist = self.checkPackages(pkgs_to_build, task)
  471. fulltargetlist = []
  472. defaulttask_implicit = ''
  473. defaulttask_explicit = False
  474. wildcard = False
  475. # Wild card expansion:
  476. # Replace string such as "multiconfig:*:bash"
  477. # into "multiconfig:A:bash multiconfig:B:bash bash"
  478. for k in targetlist:
  479. if k.startswith("multiconfig:"):
  480. if wildcard:
  481. bb.fatal('multiconfig conflict')
  482. if k.split(":")[1] == "*":
  483. wildcard = True
  484. for mc in self.multiconfigs:
  485. if mc:
  486. fulltargetlist.append(k.replace('*', mc))
  487. # implicit default task
  488. else:
  489. defaulttask_implicit = k.split(":")[2]
  490. else:
  491. fulltargetlist.append(k)
  492. else:
  493. defaulttask_explicit = True
  494. fulltargetlist.append(k)
  495. if not defaulttask_explicit and defaulttask_implicit != '':
  496. fulltargetlist.append(defaulttask_implicit)
  497. bb.debug(1,"Target list: %s" % (str(fulltargetlist)))
  498. taskdata = {}
  499. localdata = {}
  500. for mc in self.multiconfigs:
  501. taskdata[mc] = bb.taskdata.TaskData(abort, skiplist=self.skiplist, allowincomplete=allowincomplete)
  502. localdata[mc] = data.createCopy(self.databuilder.mcdata[mc])
  503. bb.data.expandKeys(localdata[mc])
  504. current = 0
  505. runlist = []
  506. for k in fulltargetlist:
  507. mc = ""
  508. if k.startswith("multiconfig:"):
  509. mc = k.split(":")[1]
  510. k = ":".join(k.split(":")[2:])
  511. ktask = task
  512. if ":do_" in k:
  513. k2 = k.split(":do_")
  514. k = k2[0]
  515. ktask = k2[1]
  516. taskdata[mc].add_provider(localdata[mc], self.recipecaches[mc], k)
  517. current += 1
  518. if not ktask.startswith("do_"):
  519. ktask = "do_%s" % ktask
  520. if k not in taskdata[mc].build_targets or not taskdata[mc].build_targets[k]:
  521. # e.g. in ASSUME_PROVIDED
  522. continue
  523. fn = taskdata[mc].build_targets[k][0]
  524. runlist.append([mc, k, ktask, fn])
  525. bb.event.fire(bb.event.TreeDataPreparationProgress(current, len(fulltargetlist)), self.data)
  526. # No need to do check providers if there are no mcdeps or not an mc build
  527. if len(self.multiconfigs) > 1:
  528. seen = set()
  529. new = True
  530. # Make sure we can provide the multiconfig dependency
  531. while new:
  532. mcdeps = set()
  533. # Add unresolved first, so we can get multiconfig indirect dependencies on time
  534. for mc in self.multiconfigs:
  535. taskdata[mc].add_unresolved(localdata[mc], self.recipecaches[mc])
  536. mcdeps |= set(taskdata[mc].get_mcdepends())
  537. new = False
  538. for mc in self.multiconfigs:
  539. for k in mcdeps:
  540. if k in seen:
  541. continue
  542. l = k.split(':')
  543. depmc = l[2]
  544. if depmc not in self.multiconfigs:
  545. bb.fatal("Multiconfig dependency %s depends on nonexistent mc configuration %s" % (k,depmc))
  546. else:
  547. logger.debug(1, "Adding providers for multiconfig dependency %s" % l[3])
  548. taskdata[depmc].add_provider(localdata[depmc], self.recipecaches[depmc], l[3])
  549. seen.add(k)
  550. new = True
  551. for mc in self.multiconfigs:
  552. taskdata[mc].add_unresolved(localdata[mc], self.recipecaches[mc])
  553. bb.event.fire(bb.event.TreeDataPreparationCompleted(len(fulltargetlist)), self.data)
  554. return taskdata, runlist
  555. def prepareTreeData(self, pkgs_to_build, task):
  556. """
  557. Prepare a runqueue and taskdata object for iteration over pkgs_to_build
  558. """
  559. # We set abort to False here to prevent unbuildable targets raising
  560. # an exception when we're just generating data
  561. taskdata, runlist = self.buildTaskData(pkgs_to_build, task, False, allowincomplete=True)
  562. return runlist, taskdata
  563. ######## WARNING : this function requires cache_extra to be enabled ########
  564. def generateTaskDepTreeData(self, pkgs_to_build, task):
  565. """
  566. Create a dependency graph of pkgs_to_build including reverse dependency
  567. information.
  568. """
  569. if not task.startswith("do_"):
  570. task = "do_%s" % task
  571. runlist, taskdata = self.prepareTreeData(pkgs_to_build, task)
  572. rq = bb.runqueue.RunQueue(self, self.data, self.recipecaches, taskdata, runlist)
  573. rq.rqdata.prepare()
  574. return self.buildDependTree(rq, taskdata)
  575. @staticmethod
  576. def add_mc_prefix(mc, pn):
  577. if mc:
  578. return "multiconfig:%s:%s" % (mc, pn)
  579. return pn
  580. def buildDependTree(self, rq, taskdata):
  581. seen_fns = []
  582. depend_tree = {}
  583. depend_tree["depends"] = {}
  584. depend_tree["tdepends"] = {}
  585. depend_tree["pn"] = {}
  586. depend_tree["rdepends-pn"] = {}
  587. depend_tree["packages"] = {}
  588. depend_tree["rdepends-pkg"] = {}
  589. depend_tree["rrecs-pkg"] = {}
  590. depend_tree['providermap'] = {}
  591. depend_tree["layer-priorities"] = self.bbfile_config_priorities
  592. for mc in taskdata:
  593. for name, fn in list(taskdata[mc].get_providermap().items()):
  594. pn = self.recipecaches[mc].pkg_fn[fn]
  595. pn = self.add_mc_prefix(mc, pn)
  596. if name != pn:
  597. version = "%s:%s-%s" % self.recipecaches[mc].pkg_pepvpr[fn]
  598. depend_tree['providermap'][name] = (pn, version)
  599. for tid in rq.rqdata.runtaskentries:
  600. (mc, fn, taskname, taskfn) = bb.runqueue.split_tid_mcfn(tid)
  601. pn = self.recipecaches[mc].pkg_fn[taskfn]
  602. pn = self.add_mc_prefix(mc, pn)
  603. version = "%s:%s-%s" % self.recipecaches[mc].pkg_pepvpr[taskfn]
  604. if pn not in depend_tree["pn"]:
  605. depend_tree["pn"][pn] = {}
  606. depend_tree["pn"][pn]["filename"] = taskfn
  607. depend_tree["pn"][pn]["version"] = version
  608. depend_tree["pn"][pn]["inherits"] = self.recipecaches[mc].inherits.get(taskfn, None)
  609. # if we have extra caches, list all attributes they bring in
  610. extra_info = []
  611. for cache_class in self.caches_array:
  612. if type(cache_class) is type and issubclass(cache_class, bb.cache.RecipeInfoCommon) and hasattr(cache_class, 'cachefields'):
  613. cachefields = getattr(cache_class, 'cachefields', [])
  614. extra_info = extra_info + cachefields
  615. # for all attributes stored, add them to the dependency tree
  616. for ei in extra_info:
  617. depend_tree["pn"][pn][ei] = vars(self.recipecaches[mc])[ei][taskfn]
  618. dotname = "%s.%s" % (pn, bb.runqueue.taskname_from_tid(tid))
  619. if not dotname in depend_tree["tdepends"]:
  620. depend_tree["tdepends"][dotname] = []
  621. for dep in rq.rqdata.runtaskentries[tid].depends:
  622. (depmc, depfn, _, deptaskfn) = bb.runqueue.split_tid_mcfn(dep)
  623. deppn = self.recipecaches[depmc].pkg_fn[deptaskfn]
  624. depend_tree["tdepends"][dotname].append("%s.%s" % (deppn, bb.runqueue.taskname_from_tid(dep)))
  625. if taskfn not in seen_fns:
  626. seen_fns.append(taskfn)
  627. packages = []
  628. depend_tree["depends"][pn] = []
  629. for dep in taskdata[mc].depids[taskfn]:
  630. depend_tree["depends"][pn].append(dep)
  631. depend_tree["rdepends-pn"][pn] = []
  632. for rdep in taskdata[mc].rdepids[taskfn]:
  633. depend_tree["rdepends-pn"][pn].append(rdep)
  634. rdepends = self.recipecaches[mc].rundeps[taskfn]
  635. for package in rdepends:
  636. depend_tree["rdepends-pkg"][package] = []
  637. for rdepend in rdepends[package]:
  638. depend_tree["rdepends-pkg"][package].append(rdepend)
  639. packages.append(package)
  640. rrecs = self.recipecaches[mc].runrecs[taskfn]
  641. for package in rrecs:
  642. depend_tree["rrecs-pkg"][package] = []
  643. for rdepend in rrecs[package]:
  644. depend_tree["rrecs-pkg"][package].append(rdepend)
  645. if not package in packages:
  646. packages.append(package)
  647. for package in packages:
  648. if package not in depend_tree["packages"]:
  649. depend_tree["packages"][package] = {}
  650. depend_tree["packages"][package]["pn"] = pn
  651. depend_tree["packages"][package]["filename"] = taskfn
  652. depend_tree["packages"][package]["version"] = version
  653. return depend_tree
  654. ######## WARNING : this function requires cache_extra to be enabled ########
  655. def generatePkgDepTreeData(self, pkgs_to_build, task):
  656. """
  657. Create a dependency tree of pkgs_to_build, returning the data.
  658. """
  659. if not task.startswith("do_"):
  660. task = "do_%s" % task
  661. _, taskdata = self.prepareTreeData(pkgs_to_build, task)
  662. seen_fns = []
  663. depend_tree = {}
  664. depend_tree["depends"] = {}
  665. depend_tree["pn"] = {}
  666. depend_tree["rdepends-pn"] = {}
  667. depend_tree["rdepends-pkg"] = {}
  668. depend_tree["rrecs-pkg"] = {}
  669. # if we have extra caches, list all attributes they bring in
  670. extra_info = []
  671. for cache_class in self.caches_array:
  672. if type(cache_class) is type and issubclass(cache_class, bb.cache.RecipeInfoCommon) and hasattr(cache_class, 'cachefields'):
  673. cachefields = getattr(cache_class, 'cachefields', [])
  674. extra_info = extra_info + cachefields
  675. tids = []
  676. for mc in taskdata:
  677. for tid in taskdata[mc].taskentries:
  678. tids.append(tid)
  679. for tid in tids:
  680. (mc, fn, taskname, taskfn) = bb.runqueue.split_tid_mcfn(tid)
  681. pn = self.recipecaches[mc].pkg_fn[taskfn]
  682. pn = self.add_mc_prefix(mc, pn)
  683. if pn not in depend_tree["pn"]:
  684. depend_tree["pn"][pn] = {}
  685. depend_tree["pn"][pn]["filename"] = taskfn
  686. version = "%s:%s-%s" % self.recipecaches[mc].pkg_pepvpr[taskfn]
  687. depend_tree["pn"][pn]["version"] = version
  688. rdepends = self.recipecaches[mc].rundeps[taskfn]
  689. rrecs = self.recipecaches[mc].runrecs[taskfn]
  690. depend_tree["pn"][pn]["inherits"] = self.recipecaches[mc].inherits.get(taskfn, None)
  691. # for all extra attributes stored, add them to the dependency tree
  692. for ei in extra_info:
  693. depend_tree["pn"][pn][ei] = vars(self.recipecaches[mc])[ei][taskfn]
  694. if taskfn not in seen_fns:
  695. seen_fns.append(taskfn)
  696. depend_tree["depends"][pn] = []
  697. for dep in taskdata[mc].depids[taskfn]:
  698. pn_provider = ""
  699. if dep in taskdata[mc].build_targets and taskdata[mc].build_targets[dep]:
  700. fn_provider = taskdata[mc].build_targets[dep][0]
  701. pn_provider = self.recipecaches[mc].pkg_fn[fn_provider]
  702. else:
  703. pn_provider = dep
  704. pn_provider = self.add_mc_prefix(mc, pn_provider)
  705. depend_tree["depends"][pn].append(pn_provider)
  706. depend_tree["rdepends-pn"][pn] = []
  707. for rdep in taskdata[mc].rdepids[taskfn]:
  708. pn_rprovider = ""
  709. if rdep in taskdata[mc].run_targets and taskdata[mc].run_targets[rdep]:
  710. fn_rprovider = taskdata[mc].run_targets[rdep][0]
  711. pn_rprovider = self.recipecaches[mc].pkg_fn[fn_rprovider]
  712. else:
  713. pn_rprovider = rdep
  714. pn_rprovider = self.add_mc_prefix(mc, pn_rprovider)
  715. depend_tree["rdepends-pn"][pn].append(pn_rprovider)
  716. depend_tree["rdepends-pkg"].update(rdepends)
  717. depend_tree["rrecs-pkg"].update(rrecs)
  718. return depend_tree
  719. def generateDepTreeEvent(self, pkgs_to_build, task):
  720. """
  721. Create a task dependency graph of pkgs_to_build.
  722. Generate an event with the result
  723. """
  724. depgraph = self.generateTaskDepTreeData(pkgs_to_build, task)
  725. bb.event.fire(bb.event.DepTreeGenerated(depgraph), self.data)
  726. def generateDotGraphFiles(self, pkgs_to_build, task):
  727. """
  728. Create a task dependency graph of pkgs_to_build.
  729. Save the result to a set of .dot files.
  730. """
  731. depgraph = self.generateTaskDepTreeData(pkgs_to_build, task)
  732. with open('pn-buildlist', 'w') as f:
  733. for pn in depgraph["pn"]:
  734. f.write(pn + "\n")
  735. logger.info("PN build list saved to 'pn-buildlist'")
  736. # Remove old format output files to ensure no confusion with stale data
  737. try:
  738. os.unlink('pn-depends.dot')
  739. except FileNotFoundError:
  740. pass
  741. try:
  742. os.unlink('package-depends.dot')
  743. except FileNotFoundError:
  744. pass
  745. with open('task-depends.dot', 'w') as f:
  746. f.write("digraph depends {\n")
  747. for task in sorted(depgraph["tdepends"]):
  748. (pn, taskname) = task.rsplit(".", 1)
  749. fn = depgraph["pn"][pn]["filename"]
  750. version = depgraph["pn"][pn]["version"]
  751. f.write('"%s.%s" [label="%s %s\\n%s\\n%s"]\n' % (pn, taskname, pn, taskname, version, fn))
  752. for dep in sorted(depgraph["tdepends"][task]):
  753. f.write('"%s" -> "%s"\n' % (task, dep))
  754. f.write("}\n")
  755. logger.info("Task dependencies saved to 'task-depends.dot'")
  756. with open('recipe-depends.dot', 'w') as f:
  757. f.write("digraph depends {\n")
  758. pndeps = {}
  759. for task in sorted(depgraph["tdepends"]):
  760. (pn, taskname) = task.rsplit(".", 1)
  761. if pn not in pndeps:
  762. pndeps[pn] = set()
  763. for dep in sorted(depgraph["tdepends"][task]):
  764. (deppn, deptaskname) = dep.rsplit(".", 1)
  765. pndeps[pn].add(deppn)
  766. for pn in sorted(pndeps):
  767. fn = depgraph["pn"][pn]["filename"]
  768. version = depgraph["pn"][pn]["version"]
  769. f.write('"%s" [label="%s\\n%s\\n%s"]\n' % (pn, pn, version, fn))
  770. for dep in sorted(pndeps[pn]):
  771. if dep == pn:
  772. continue
  773. f.write('"%s" -> "%s"\n' % (pn, dep))
  774. f.write("}\n")
  775. logger.info("Flattened recipe dependencies saved to 'recipe-depends.dot'")
  776. def show_appends_with_no_recipes(self):
  777. # Determine which bbappends haven't been applied
  778. # First get list of recipes, including skipped
  779. recipefns = list(self.recipecaches[''].pkg_fn.keys())
  780. recipefns.extend(self.skiplist.keys())
  781. # Work out list of bbappends that have been applied
  782. applied_appends = []
  783. for fn in recipefns:
  784. applied_appends.extend(self.collection.get_file_appends(fn))
  785. appends_without_recipes = []
  786. for _, appendfn in self.collection.bbappends:
  787. if not appendfn in applied_appends:
  788. appends_without_recipes.append(appendfn)
  789. if appends_without_recipes:
  790. msg = 'No recipes available for:\n %s' % '\n '.join(appends_without_recipes)
  791. warn_only = self.data.getVar("BB_DANGLINGAPPENDS_WARNONLY", \
  792. False) or "no"
  793. if warn_only.lower() in ("1", "yes", "true"):
  794. bb.warn(msg)
  795. else:
  796. bb.fatal(msg)
  797. def handlePrefProviders(self):
  798. for mc in self.multiconfigs:
  799. localdata = data.createCopy(self.databuilder.mcdata[mc])
  800. bb.data.expandKeys(localdata)
  801. # Handle PREFERRED_PROVIDERS
  802. for p in (localdata.getVar('PREFERRED_PROVIDERS') or "").split():
  803. try:
  804. (providee, provider) = p.split(':')
  805. except:
  806. providerlog.critical("Malformed option in PREFERRED_PROVIDERS variable: %s" % p)
  807. continue
  808. if providee in self.recipecaches[mc].preferred and self.recipecaches[mc].preferred[providee] != provider:
  809. providerlog.error("conflicting preferences for %s: both %s and %s specified", providee, provider, self.recipecaches[mc].preferred[providee])
  810. self.recipecaches[mc].preferred[providee] = provider
  811. def findConfigFilePath(self, configfile):
  812. """
  813. Find the location on disk of configfile and if it exists and was parsed by BitBake
  814. emit the ConfigFilePathFound event with the path to the file.
  815. """
  816. path = bb.cookerdata.findConfigFile(configfile, self.data)
  817. if not path:
  818. return
  819. # Generate a list of parsed configuration files by searching the files
  820. # listed in the __depends and __base_depends variables with a .conf suffix.
  821. conffiles = []
  822. dep_files = self.data.getVar('__base_depends', False) or []
  823. dep_files = dep_files + (self.data.getVar('__depends', False) or [])
  824. for f in dep_files:
  825. if f[0].endswith(".conf"):
  826. conffiles.append(f[0])
  827. _, conf, conffile = path.rpartition("conf/")
  828. match = os.path.join(conf, conffile)
  829. # Try and find matches for conf/conffilename.conf as we don't always
  830. # have the full path to the file.
  831. for cfg in conffiles:
  832. if cfg.endswith(match):
  833. bb.event.fire(bb.event.ConfigFilePathFound(path),
  834. self.data)
  835. break
  836. def findFilesMatchingInDir(self, filepattern, directory):
  837. """
  838. Searches for files containing the substring 'filepattern' which are children of
  839. 'directory' in each BBPATH. i.e. to find all rootfs package classes available
  840. to BitBake one could call findFilesMatchingInDir(self, 'rootfs_', 'classes')
  841. or to find all machine configuration files one could call:
  842. findFilesMatchingInDir(self, '.conf', 'conf/machine')
  843. """
  844. matches = []
  845. bbpaths = self.data.getVar('BBPATH').split(':')
  846. for path in bbpaths:
  847. dirpath = os.path.join(path, directory)
  848. if os.path.exists(dirpath):
  849. for root, dirs, files in os.walk(dirpath):
  850. for f in files:
  851. if filepattern in f:
  852. matches.append(f)
  853. if matches:
  854. bb.event.fire(bb.event.FilesMatchingFound(filepattern, matches), self.data)
  855. def findProviders(self, mc=''):
  856. return bb.providers.findProviders(self.data, self.recipecaches[mc], self.recipecaches[mc].pkg_pn)
  857. def findBestProvider(self, pn, mc=''):
  858. if pn in self.recipecaches[mc].providers:
  859. filenames = self.recipecaches[mc].providers[pn]
  860. eligible, foundUnique = bb.providers.filterProviders(filenames, pn, self.data, self.recipecaches[mc])
  861. filename = eligible[0]
  862. return None, None, None, filename
  863. elif pn in self.recipecaches[mc].pkg_pn:
  864. return bb.providers.findBestProvider(pn, self.data, self.recipecaches[mc], self.recipecaches[mc].pkg_pn)
  865. else:
  866. return None, None, None, None
  867. def findConfigFiles(self, varname):
  868. """
  869. Find config files which are appropriate values for varname.
  870. i.e. MACHINE, DISTRO
  871. """
  872. possible = []
  873. var = varname.lower()
  874. data = self.data
  875. # iterate configs
  876. bbpaths = data.getVar('BBPATH').split(':')
  877. for path in bbpaths:
  878. confpath = os.path.join(path, "conf", var)
  879. if os.path.exists(confpath):
  880. for root, dirs, files in os.walk(confpath):
  881. # get all child files, these are appropriate values
  882. for f in files:
  883. val, sep, end = f.rpartition('.')
  884. if end == 'conf':
  885. possible.append(val)
  886. if possible:
  887. bb.event.fire(bb.event.ConfigFilesFound(var, possible), self.data)
  888. def findInheritsClass(self, klass):
  889. """
  890. Find all recipes which inherit the specified class
  891. """
  892. pkg_list = []
  893. for pfn in self.recipecaches[''].pkg_fn:
  894. inherits = self.recipecaches[''].inherits.get(pfn, None)
  895. if inherits and klass in inherits:
  896. pkg_list.append(self.recipecaches[''].pkg_fn[pfn])
  897. return pkg_list
  898. def generateTargetsTree(self, klass=None, pkgs=None):
  899. """
  900. Generate a dependency tree of buildable targets
  901. Generate an event with the result
  902. """
  903. # if the caller hasn't specified a pkgs list default to universe
  904. if not pkgs:
  905. pkgs = ['universe']
  906. # if inherited_class passed ensure all recipes which inherit the
  907. # specified class are included in pkgs
  908. if klass:
  909. extra_pkgs = self.findInheritsClass(klass)
  910. pkgs = pkgs + extra_pkgs
  911. # generate a dependency tree for all our packages
  912. tree = self.generatePkgDepTreeData(pkgs, 'build')
  913. bb.event.fire(bb.event.TargetsTreeGenerated(tree), self.data)
  914. def interactiveMode( self ):
  915. """Drop off into a shell"""
  916. try:
  917. from bb import shell
  918. except ImportError:
  919. parselog.exception("Interactive mode not available")
  920. sys.exit(1)
  921. else:
  922. shell.start( self )
  923. def handleCollections(self, collections):
  924. """Handle collections"""
  925. errors = False
  926. self.bbfile_config_priorities = []
  927. if collections:
  928. collection_priorities = {}
  929. collection_depends = {}
  930. collection_list = collections.split()
  931. min_prio = 0
  932. for c in collection_list:
  933. bb.debug(1,'Processing %s in collection list' % (c))
  934. # Get collection priority if defined explicitly
  935. priority = self.data.getVar("BBFILE_PRIORITY_%s" % c)
  936. if priority:
  937. try:
  938. prio = int(priority)
  939. except ValueError:
  940. parselog.error("invalid value for BBFILE_PRIORITY_%s: \"%s\"", c, priority)
  941. errors = True
  942. if min_prio == 0 or prio < min_prio:
  943. min_prio = prio
  944. collection_priorities[c] = prio
  945. else:
  946. collection_priorities[c] = None
  947. # Check dependencies and store information for priority calculation
  948. deps = self.data.getVar("LAYERDEPENDS_%s" % c)
  949. if deps:
  950. try:
  951. depDict = bb.utils.explode_dep_versions2(deps)
  952. except bb.utils.VersionStringException as vse:
  953. bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
  954. for dep, oplist in list(depDict.items()):
  955. if dep in collection_list:
  956. for opstr in oplist:
  957. layerver = self.data.getVar("LAYERVERSION_%s" % dep)
  958. (op, depver) = opstr.split()
  959. if layerver:
  960. try:
  961. res = bb.utils.vercmp_string_op(layerver, depver, op)
  962. except bb.utils.VersionStringException as vse:
  963. bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
  964. if not res:
  965. parselog.error("Layer '%s' depends on version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep, layerver)
  966. errors = True
  967. else:
  968. parselog.error("Layer '%s' depends on version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep)
  969. errors = True
  970. else:
  971. parselog.error("Layer '%s' depends on layer '%s', but this layer is not enabled in your configuration", c, dep)
  972. errors = True
  973. collection_depends[c] = list(depDict.keys())
  974. else:
  975. collection_depends[c] = []
  976. # Check recommends and store information for priority calculation
  977. recs = self.data.getVar("LAYERRECOMMENDS_%s" % c)
  978. if recs:
  979. try:
  980. recDict = bb.utils.explode_dep_versions2(recs)
  981. except bb.utils.VersionStringException as vse:
  982. bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
  983. for rec, oplist in list(recDict.items()):
  984. if rec in collection_list:
  985. if oplist:
  986. opstr = oplist[0]
  987. layerver = self.data.getVar("LAYERVERSION_%s" % rec)
  988. if layerver:
  989. (op, recver) = opstr.split()
  990. try:
  991. res = bb.utils.vercmp_string_op(layerver, recver, op)
  992. except bb.utils.VersionStringException as vse:
  993. bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
  994. if not res:
  995. parselog.debug(3,"Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec, layerver)
  996. continue
  997. else:
  998. parselog.debug(3,"Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec)
  999. continue
  1000. parselog.debug(3,"Layer '%s' recommends layer '%s', so we are adding it", c, rec)
  1001. collection_depends[c].append(rec)
  1002. else:
  1003. parselog.debug(3,"Layer '%s' recommends layer '%s', but this layer is not enabled in your configuration", c, rec)
  1004. # Recursively work out collection priorities based on dependencies
  1005. def calc_layer_priority(collection):
  1006. if not collection_priorities[collection]:
  1007. max_depprio = min_prio
  1008. for dep in collection_depends[collection]:
  1009. calc_layer_priority(dep)
  1010. depprio = collection_priorities[dep]
  1011. if depprio > max_depprio:
  1012. max_depprio = depprio
  1013. max_depprio += 1
  1014. parselog.debug(1, "Calculated priority of layer %s as %d", collection, max_depprio)
  1015. collection_priorities[collection] = max_depprio
  1016. # Calculate all layer priorities using calc_layer_priority and store in bbfile_config_priorities
  1017. for c in collection_list:
  1018. calc_layer_priority(c)
  1019. regex = self.data.getVar("BBFILE_PATTERN_%s" % c)
  1020. if regex == None:
  1021. parselog.error("BBFILE_PATTERN_%s not defined" % c)
  1022. errors = True
  1023. continue
  1024. elif regex == "":
  1025. parselog.debug(1, "BBFILE_PATTERN_%s is empty" % c)
  1026. cre = re.compile('^NULL$')
  1027. errors = False
  1028. else:
  1029. try:
  1030. cre = re.compile(regex)
  1031. except re.error:
  1032. parselog.error("BBFILE_PATTERN_%s \"%s\" is not a valid regular expression", c, regex)
  1033. errors = True
  1034. continue
  1035. self.bbfile_config_priorities.append((c, regex, cre, collection_priorities[c]))
  1036. if errors:
  1037. # We've already printed the actual error(s)
  1038. raise CollectionError("Errors during parsing layer configuration")
  1039. def buildSetVars(self):
  1040. """
  1041. Setup any variables needed before starting a build
  1042. """
  1043. t = time.gmtime()
  1044. for mc in self.databuilder.mcdata:
  1045. ds = self.databuilder.mcdata[mc]
  1046. if not ds.getVar("BUILDNAME", False):
  1047. ds.setVar("BUILDNAME", "${DATE}${TIME}")
  1048. ds.setVar("BUILDSTART", time.strftime('%m/%d/%Y %H:%M:%S', t))
  1049. ds.setVar("DATE", time.strftime('%Y%m%d', t))
  1050. ds.setVar("TIME", time.strftime('%H%M%S', t))
  1051. def reset_mtime_caches(self):
  1052. """
  1053. Reset mtime caches - this is particularly important when memory resident as something
  1054. which is cached is not unlikely to have changed since the last invocation (e.g. a
  1055. file associated with a recipe might have been modified by the user).
  1056. """
  1057. build.reset_cache()
  1058. bb.fetch._checksum_cache.mtime_cache.clear()
  1059. siggen_cache = getattr(bb.parse.siggen, 'checksum_cache', None)
  1060. if siggen_cache:
  1061. bb.parse.siggen.checksum_cache.mtime_cache.clear()
  1062. def matchFiles(self, bf):
  1063. """
  1064. Find the .bb files which match the expression in 'buildfile'.
  1065. """
  1066. if bf.startswith("/") or bf.startswith("../"):
  1067. bf = os.path.abspath(bf)
  1068. self.collection = CookerCollectFiles(self.bbfile_config_priorities)
  1069. filelist, masked, searchdirs = self.collection.collect_bbfiles(self.data, self.data)
  1070. try:
  1071. os.stat(bf)
  1072. bf = os.path.abspath(bf)
  1073. return [bf]
  1074. except OSError:
  1075. regexp = re.compile(bf)
  1076. matches = []
  1077. for f in filelist:
  1078. if regexp.search(f) and os.path.isfile(f):
  1079. matches.append(f)
  1080. return matches
  1081. def matchFile(self, buildfile):
  1082. """
  1083. Find the .bb file which matches the expression in 'buildfile'.
  1084. Raise an error if multiple files
  1085. """
  1086. matches = self.matchFiles(buildfile)
  1087. if len(matches) != 1:
  1088. if matches:
  1089. msg = "Unable to match '%s' to a specific recipe file - %s matches found:" % (buildfile, len(matches))
  1090. if matches:
  1091. for f in matches:
  1092. msg += "\n %s" % f
  1093. parselog.error(msg)
  1094. else:
  1095. parselog.error("Unable to find any recipe file matching '%s'" % buildfile)
  1096. raise NoSpecificMatch
  1097. return matches[0]
  1098. def buildFile(self, buildfile, task):
  1099. """
  1100. Build the file matching regexp buildfile
  1101. """
  1102. bb.event.fire(bb.event.BuildInit(), self.data)
  1103. # Too many people use -b because they think it's how you normally
  1104. # specify a target to be built, so show a warning
  1105. bb.warn("Buildfile specified, dependencies will not be handled. If this is not what you want, do not use -b / --buildfile.")
  1106. self.buildFileInternal(buildfile, task)
  1107. def buildFileInternal(self, buildfile, task, fireevents=True, quietlog=False):
  1108. """
  1109. Build the file matching regexp buildfile
  1110. """
  1111. # Parse the configuration here. We need to do it explicitly here since
  1112. # buildFile() doesn't use the cache
  1113. self.parseConfiguration()
  1114. # If we are told to do the None task then query the default task
  1115. if (task == None):
  1116. task = self.configuration.cmd
  1117. if not task.startswith("do_"):
  1118. task = "do_%s" % task
  1119. fn, cls, mc = bb.cache.virtualfn2realfn(buildfile)
  1120. fn = self.matchFile(fn)
  1121. self.buildSetVars()
  1122. self.reset_mtime_caches()
  1123. bb_cache = bb.cache.Cache(self.databuilder, self.data_hash, self.caches_array)
  1124. infos = bb_cache.parse(fn, self.collection.get_file_appends(fn))
  1125. infos = dict(infos)
  1126. fn = bb.cache.realfn2virtual(fn, cls, mc)
  1127. try:
  1128. info_array = infos[fn]
  1129. except KeyError:
  1130. bb.fatal("%s does not exist" % fn)
  1131. if info_array[0].skipped:
  1132. bb.fatal("%s was skipped: %s" % (fn, info_array[0].skipreason))
  1133. self.recipecaches[mc].add_from_recipeinfo(fn, info_array)
  1134. # Tweak some variables
  1135. item = info_array[0].pn
  1136. self.recipecaches[mc].ignored_dependencies = set()
  1137. self.recipecaches[mc].bbfile_priority[fn] = 1
  1138. self.configuration.limited_deps = True
  1139. # Remove external dependencies
  1140. self.recipecaches[mc].task_deps[fn]['depends'] = {}
  1141. self.recipecaches[mc].deps[fn] = []
  1142. self.recipecaches[mc].rundeps[fn] = defaultdict(list)
  1143. self.recipecaches[mc].runrecs[fn] = defaultdict(list)
  1144. # Invalidate task for target if force mode active
  1145. if self.configuration.force:
  1146. logger.verbose("Invalidate task %s, %s", task, fn)
  1147. bb.parse.siggen.invalidate_task(task, self.recipecaches[mc], fn)
  1148. # Setup taskdata structure
  1149. taskdata = {}
  1150. taskdata[mc] = bb.taskdata.TaskData(self.configuration.abort)
  1151. taskdata[mc].add_provider(self.databuilder.mcdata[mc], self.recipecaches[mc], item)
  1152. if quietlog:
  1153. rqloglevel = bb.runqueue.logger.getEffectiveLevel()
  1154. bb.runqueue.logger.setLevel(logging.WARNING)
  1155. buildname = self.databuilder.mcdata[mc].getVar("BUILDNAME")
  1156. if fireevents:
  1157. bb.event.fire(bb.event.BuildStarted(buildname, [item]), self.databuilder.mcdata[mc])
  1158. # Execute the runqueue
  1159. runlist = [[mc, item, task, fn]]
  1160. rq = bb.runqueue.RunQueue(self, self.data, self.recipecaches, taskdata, runlist)
  1161. def buildFileIdle(server, rq, abort):
  1162. msg = None
  1163. interrupted = 0
  1164. if abort or self.state == state.forceshutdown:
  1165. rq.finish_runqueue(True)
  1166. msg = "Forced shutdown"
  1167. interrupted = 2
  1168. elif self.state == state.shutdown:
  1169. rq.finish_runqueue(False)
  1170. msg = "Stopped build"
  1171. interrupted = 1
  1172. failures = 0
  1173. try:
  1174. retval = rq.execute_runqueue()
  1175. except runqueue.TaskFailure as exc:
  1176. failures += len(exc.args)
  1177. retval = False
  1178. except SystemExit as exc:
  1179. self.command.finishAsyncCommand(str(exc))
  1180. if quietlog:
  1181. bb.runqueue.logger.setLevel(rqloglevel)
  1182. return False
  1183. if not retval:
  1184. if fireevents:
  1185. bb.event.fire(bb.event.BuildCompleted(len(rq.rqdata.runtaskentries), buildname, item, failures, interrupted), self.databuilder.mcdata[mc])
  1186. self.command.finishAsyncCommand(msg)
  1187. # We trashed self.recipecaches above
  1188. self.parsecache_valid = False
  1189. self.configuration.limited_deps = False
  1190. bb.parse.siggen.reset(self.data)
  1191. if quietlog:
  1192. bb.runqueue.logger.setLevel(rqloglevel)
  1193. return False
  1194. if retval is True:
  1195. return True
  1196. return retval
  1197. self.configuration.server_register_idlecallback(buildFileIdle, rq)
  1198. def buildTargets(self, targets, task):
  1199. """
  1200. Attempt to build the targets specified
  1201. """
  1202. def buildTargetsIdle(server, rq, abort):
  1203. msg = None
  1204. interrupted = 0
  1205. if abort or self.state == state.forceshutdown:
  1206. rq.finish_runqueue(True)
  1207. msg = "Forced shutdown"
  1208. interrupted = 2
  1209. elif self.state == state.shutdown:
  1210. rq.finish_runqueue(False)
  1211. msg = "Stopped build"
  1212. interrupted = 1
  1213. failures = 0
  1214. try:
  1215. retval = rq.execute_runqueue()
  1216. except runqueue.TaskFailure as exc:
  1217. failures += len(exc.args)
  1218. retval = False
  1219. except SystemExit as exc:
  1220. self.command.finishAsyncCommand(str(exc))
  1221. return False
  1222. if not retval:
  1223. try:
  1224. for mc in self.multiconfigs:
  1225. bb.event.fire(bb.event.BuildCompleted(len(rq.rqdata.runtaskentries), buildname, targets, failures, interrupted), self.databuilder.mcdata[mc])
  1226. finally:
  1227. self.command.finishAsyncCommand(msg)
  1228. return False
  1229. if retval is True:
  1230. return True
  1231. return retval
  1232. self.reset_mtime_caches()
  1233. self.buildSetVars()
  1234. # If we are told to do the None task then query the default task
  1235. if (task == None):
  1236. task = self.configuration.cmd
  1237. if not task.startswith("do_"):
  1238. task = "do_%s" % task
  1239. packages = [target if ':' in target else '%s:%s' % (target, task) for target in targets]
  1240. bb.event.fire(bb.event.BuildInit(packages), self.data)
  1241. taskdata, runlist = self.buildTaskData(targets, task, self.configuration.abort)
  1242. buildname = self.data.getVar("BUILDNAME", False)
  1243. # make targets to always look as <target>:do_<task>
  1244. ntargets = []
  1245. for target in runlist:
  1246. if target[0]:
  1247. ntargets.append("multiconfig:%s:%s:%s" % (target[0], target[1], target[2]))
  1248. ntargets.append("%s:%s" % (target[1], target[2]))
  1249. for mc in self.multiconfigs:
  1250. bb.event.fire(bb.event.BuildStarted(buildname, ntargets), self.databuilder.mcdata[mc])
  1251. rq = bb.runqueue.RunQueue(self, self.data, self.recipecaches, taskdata, runlist)
  1252. if 'universe' in targets:
  1253. rq.rqdata.warn_multi_bb = True
  1254. self.configuration.server_register_idlecallback(buildTargetsIdle, rq)
  1255. def getAllKeysWithFlags(self, flaglist):
  1256. dump = {}
  1257. for k in self.data.keys():
  1258. try:
  1259. expand = True
  1260. flags = self.data.getVarFlags(k)
  1261. if flags and "func" in flags and "python" in flags:
  1262. expand = False
  1263. v = self.data.getVar(k, expand)
  1264. if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart):
  1265. dump[k] = {
  1266. 'v' : str(v) ,
  1267. 'history' : self.data.varhistory.variable(k),
  1268. }
  1269. for d in flaglist:
  1270. if flags and d in flags:
  1271. dump[k][d] = flags[d]
  1272. else:
  1273. dump[k][d] = None
  1274. except Exception as e:
  1275. print(e)
  1276. return dump
  1277. def updateCacheSync(self):
  1278. if self.state == state.running:
  1279. return
  1280. # reload files for which we got notifications
  1281. for p in self.inotify_modified_files:
  1282. bb.parse.update_cache(p)
  1283. if p in bb.parse.BBHandler.cached_statements:
  1284. del bb.parse.BBHandler.cached_statements[p]
  1285. self.inotify_modified_files = []
  1286. if not self.baseconfig_valid:
  1287. logger.debug(1, "Reloading base configuration data")
  1288. self.initConfigurationData()
  1289. self.handlePRServ()
  1290. # This is called for all async commands when self.state != running
  1291. def updateCache(self):
  1292. if self.state == state.running:
  1293. return
  1294. if self.state in (state.shutdown, state.forceshutdown, state.error):
  1295. if hasattr(self.parser, 'shutdown'):
  1296. self.parser.shutdown(clean=False, force = True)
  1297. raise bb.BBHandledException()
  1298. if self.state != state.parsing:
  1299. self.updateCacheSync()
  1300. if self.state != state.parsing and not self.parsecache_valid:
  1301. bb.parse.siggen.reset(self.data)
  1302. self.parseConfiguration ()
  1303. if CookerFeatures.SEND_SANITYEVENTS in self.featureset:
  1304. for mc in self.multiconfigs:
  1305. bb.event.fire(bb.event.SanityCheck(False), self.databuilder.mcdata[mc])
  1306. for mc in self.multiconfigs:
  1307. ignore = self.databuilder.mcdata[mc].getVar("ASSUME_PROVIDED") or ""
  1308. self.recipecaches[mc].ignored_dependencies = set(ignore.split())
  1309. for dep in self.configuration.extra_assume_provided:
  1310. self.recipecaches[mc].ignored_dependencies.add(dep)
  1311. self.collection = CookerCollectFiles(self.bbfile_config_priorities)
  1312. (filelist, masked, searchdirs) = self.collection.collect_bbfiles(self.data, self.data)
  1313. # Add inotify watches for directories searched for bb/bbappend files
  1314. for dirent in searchdirs:
  1315. self.add_filewatch([[dirent]], dirs=True)
  1316. self.parser = CookerParser(self, filelist, masked)
  1317. self.parsecache_valid = True
  1318. self.state = state.parsing
  1319. if not self.parser.parse_next():
  1320. collectlog.debug(1, "parsing complete")
  1321. if self.parser.error:
  1322. raise bb.BBHandledException()
  1323. self.show_appends_with_no_recipes()
  1324. self.handlePrefProviders()
  1325. for mc in self.multiconfigs:
  1326. self.recipecaches[mc].bbfile_priority = self.collection.collection_priorities(self.recipecaches[mc].pkg_fn, self.data)
  1327. self.state = state.running
  1328. # Send an event listing all stamps reachable after parsing
  1329. # which the metadata may use to clean up stale data
  1330. for mc in self.multiconfigs:
  1331. event = bb.event.ReachableStamps(self.recipecaches[mc].stamp)
  1332. bb.event.fire(event, self.databuilder.mcdata[mc])
  1333. return None
  1334. return True
  1335. def checkPackages(self, pkgs_to_build, task=None):
  1336. # Return a copy, don't modify the original
  1337. pkgs_to_build = pkgs_to_build[:]
  1338. if len(pkgs_to_build) == 0:
  1339. raise NothingToBuild
  1340. ignore = (self.data.getVar("ASSUME_PROVIDED") or "").split()
  1341. for pkg in pkgs_to_build:
  1342. if pkg in ignore:
  1343. parselog.warning("Explicit target \"%s\" is in ASSUME_PROVIDED, ignoring" % pkg)
  1344. if 'world' in pkgs_to_build:
  1345. pkgs_to_build.remove('world')
  1346. for mc in self.multiconfigs:
  1347. bb.providers.buildWorldTargetList(self.recipecaches[mc], task)
  1348. for t in self.recipecaches[mc].world_target:
  1349. if mc:
  1350. t = "multiconfig:" + mc + ":" + t
  1351. pkgs_to_build.append(t)
  1352. if 'universe' in pkgs_to_build:
  1353. parselog.verbnote("The \"universe\" target is only intended for testing and may produce errors.")
  1354. parselog.debug(1, "collating packages for \"universe\"")
  1355. pkgs_to_build.remove('universe')
  1356. for mc in self.multiconfigs:
  1357. for t in self.recipecaches[mc].universe_target:
  1358. if task:
  1359. foundtask = False
  1360. for provider_fn in self.recipecaches[mc].providers[t]:
  1361. if task in self.recipecaches[mc].task_deps[provider_fn]['tasks']:
  1362. foundtask = True
  1363. break
  1364. if not foundtask:
  1365. bb.debug(1, "Skipping %s for universe tasks as task %s doesn't exist" % (t, task))
  1366. continue
  1367. if mc:
  1368. t = "multiconfig:" + mc + ":" + t
  1369. pkgs_to_build.append(t)
  1370. return pkgs_to_build
  1371. def pre_serve(self):
  1372. # We now are in our own process so we can call this here.
  1373. # PRServ exits if its parent process exits
  1374. self.handlePRServ()
  1375. return
  1376. def post_serve(self):
  1377. prserv.serv.auto_shutdown()
  1378. bb.event.fire(CookerExit(), self.data)
  1379. def shutdown(self, force = False):
  1380. if force:
  1381. self.state = state.forceshutdown
  1382. else:
  1383. self.state = state.shutdown
  1384. if self.parser:
  1385. self.parser.shutdown(clean=not force, force=force)
  1386. def finishcommand(self):
  1387. self.state = state.initial
  1388. def reset(self):
  1389. self.initConfigurationData()
  1390. def clientComplete(self):
  1391. """Called when the client is done using the server"""
  1392. self.finishcommand()
  1393. self.extraconfigdata = {}
  1394. self.command.reset()
  1395. self.databuilder.reset()
  1396. self.data = self.databuilder.data
  1397. class CookerExit(bb.event.Event):
  1398. """
  1399. Notify clients of the Cooker shutdown
  1400. """
  1401. def __init__(self):
  1402. bb.event.Event.__init__(self)
  1403. class CookerCollectFiles(object):
  1404. def __init__(self, priorities):
  1405. self.bbappends = []
  1406. # Priorities is a list of tupples, with the second element as the pattern.
  1407. # We need to sort the list with the longest pattern first, and so on to
  1408. # the shortest. This allows nested layers to be properly evaluated.
  1409. self.bbfile_config_priorities = sorted(priorities, key=lambda tup: tup[1], reverse=True)
  1410. def calc_bbfile_priority( self, filename, matched = None ):
  1411. for _, _, regex, pri in self.bbfile_config_priorities:
  1412. if regex.match(filename):
  1413. if matched != None:
  1414. if not regex in matched:
  1415. matched.add(regex)
  1416. return pri
  1417. return 0
  1418. def get_bbfiles(self):
  1419. """Get list of default .bb files by reading out the current directory"""
  1420. path = os.getcwd()
  1421. contents = os.listdir(path)
  1422. bbfiles = []
  1423. for f in contents:
  1424. if f.endswith(".bb"):
  1425. bbfiles.append(os.path.abspath(os.path.join(path, f)))
  1426. return bbfiles
  1427. def find_bbfiles(self, path):
  1428. """Find all the .bb and .bbappend files in a directory"""
  1429. found = []
  1430. for dir, dirs, files in os.walk(path):
  1431. for ignored in ('SCCS', 'CVS', '.svn'):
  1432. if ignored in dirs:
  1433. dirs.remove(ignored)
  1434. found += [os.path.join(dir, f) for f in files if (f.endswith(['.bb', '.bbappend']))]
  1435. return found
  1436. def collect_bbfiles(self, config, eventdata):
  1437. """Collect all available .bb build files"""
  1438. masked = 0
  1439. collectlog.debug(1, "collecting .bb files")
  1440. files = (config.getVar( "BBFILES") or "").split()
  1441. config.setVar("BBFILES", " ".join(files))
  1442. # Sort files by priority
  1443. files.sort( key=lambda fileitem: self.calc_bbfile_priority(fileitem) )
  1444. if not len(files):
  1445. files = self.get_bbfiles()
  1446. if not len(files):
  1447. collectlog.error("no recipe files to build, check your BBPATH and BBFILES?")
  1448. bb.event.fire(CookerExit(), eventdata)
  1449. # We need to track where we look so that we can add inotify watches. There
  1450. # is no nice way to do this, this is horrid. We intercept the os.listdir()
  1451. # (or os.scandir() for python 3.6+) calls while we run glob().
  1452. origlistdir = os.listdir
  1453. if hasattr(os, 'scandir'):
  1454. origscandir = os.scandir
  1455. searchdirs = []
  1456. def ourlistdir(d):
  1457. searchdirs.append(d)
  1458. return origlistdir(d)
  1459. def ourscandir(d):
  1460. searchdirs.append(d)
  1461. return origscandir(d)
  1462. os.listdir = ourlistdir
  1463. if hasattr(os, 'scandir'):
  1464. os.scandir = ourscandir
  1465. try:
  1466. # Can't use set here as order is important
  1467. newfiles = []
  1468. for f in files:
  1469. if os.path.isdir(f):
  1470. dirfiles = self.find_bbfiles(f)
  1471. for g in dirfiles:
  1472. if g not in newfiles:
  1473. newfiles.append(g)
  1474. else:
  1475. globbed = glob.glob(f)
  1476. if not globbed and os.path.exists(f):
  1477. globbed = [f]
  1478. # glob gives files in order on disk. Sort to be deterministic.
  1479. for g in sorted(globbed):
  1480. if g not in newfiles:
  1481. newfiles.append(g)
  1482. finally:
  1483. os.listdir = origlistdir
  1484. if hasattr(os, 'scandir'):
  1485. os.scandir = origscandir
  1486. bbmask = config.getVar('BBMASK')
  1487. if bbmask:
  1488. # First validate the individual regular expressions and ignore any
  1489. # that do not compile
  1490. bbmasks = []
  1491. for mask in bbmask.split():
  1492. # When constructing an older style single regex, it's possible for BBMASK
  1493. # to end up beginning with '|', which matches and masks _everything_.
  1494. if mask.startswith("|"):
  1495. collectlog.warn("BBMASK contains regular expression beginning with '|', fixing: %s" % mask)
  1496. mask = mask[1:]
  1497. try:
  1498. re.compile(mask)
  1499. bbmasks.append(mask)
  1500. except sre_constants.error:
  1501. collectlog.critical("BBMASK contains an invalid regular expression, ignoring: %s" % mask)
  1502. # Then validate the combined regular expressions. This should never
  1503. # fail, but better safe than sorry...
  1504. bbmask = "|".join(bbmasks)
  1505. try:
  1506. bbmask_compiled = re.compile(bbmask)
  1507. except sre_constants.error:
  1508. collectlog.critical("BBMASK is not a valid regular expression, ignoring: %s" % bbmask)
  1509. bbmask = None
  1510. bbfiles = []
  1511. bbappend = []
  1512. for f in newfiles:
  1513. if bbmask and bbmask_compiled.search(f):
  1514. collectlog.debug(1, "skipping masked file %s", f)
  1515. masked += 1
  1516. continue
  1517. if f.endswith('.bb'):
  1518. bbfiles.append(f)
  1519. elif f.endswith('.bbappend'):
  1520. bbappend.append(f)
  1521. else:
  1522. collectlog.debug(1, "skipping %s: unknown file extension", f)
  1523. # Build a list of .bbappend files for each .bb file
  1524. for f in bbappend:
  1525. base = os.path.basename(f).replace('.bbappend', '.bb')
  1526. self.bbappends.append((base, f))
  1527. # Find overlayed recipes
  1528. # bbfiles will be in priority order which makes this easy
  1529. bbfile_seen = dict()
  1530. self.overlayed = defaultdict(list)
  1531. for f in reversed(bbfiles):
  1532. base = os.path.basename(f)
  1533. if base not in bbfile_seen:
  1534. bbfile_seen[base] = f
  1535. else:
  1536. topfile = bbfile_seen[base]
  1537. self.overlayed[topfile].append(f)
  1538. return (bbfiles, masked, searchdirs)
  1539. def get_file_appends(self, fn):
  1540. """
  1541. Returns a list of .bbappend files to apply to fn
  1542. """
  1543. filelist = []
  1544. f = os.path.basename(fn)
  1545. for b in self.bbappends:
  1546. (bbappend, filename) = b
  1547. if (bbappend == f) or ('%' in bbappend and bbappend.startswith(f[:bbappend.index('%')])):
  1548. filelist.append(filename)
  1549. return filelist
  1550. def collection_priorities(self, pkgfns, d):
  1551. priorities = {}
  1552. # Calculate priorities for each file
  1553. matched = set()
  1554. for p in pkgfns:
  1555. realfn, cls, mc = bb.cache.virtualfn2realfn(p)
  1556. priorities[p] = self.calc_bbfile_priority(realfn, matched)
  1557. unmatched = set()
  1558. for _, _, regex, pri in self.bbfile_config_priorities:
  1559. if not regex in matched:
  1560. unmatched.add(regex)
  1561. # Don't show the warning if the BBFILE_PATTERN did match .bbappend files
  1562. def find_bbappend_match(regex):
  1563. for b in self.bbappends:
  1564. (bbfile, append) = b
  1565. if regex.match(append):
  1566. # If the bbappend is matched by already "matched set", return False
  1567. for matched_regex in matched:
  1568. if matched_regex.match(append):
  1569. return False
  1570. return True
  1571. return False
  1572. for unmatch in unmatched.copy():
  1573. if find_bbappend_match(unmatch):
  1574. unmatched.remove(unmatch)
  1575. for collection, pattern, regex, _ in self.bbfile_config_priorities:
  1576. if regex in unmatched:
  1577. if d.getVar('BBFILE_PATTERN_IGNORE_EMPTY_%s' % collection) != '1':
  1578. collectlog.warning("No bb files matched BBFILE_PATTERN_%s '%s'" % (collection, pattern))
  1579. return priorities
  1580. class ParsingFailure(Exception):
  1581. def __init__(self, realexception, recipe):
  1582. self.realexception = realexception
  1583. self.recipe = recipe
  1584. Exception.__init__(self, realexception, recipe)
  1585. class Parser(multiprocessing.Process):
  1586. def __init__(self, jobs, results, quit, init, profile):
  1587. self.jobs = jobs
  1588. self.results = results
  1589. self.quit = quit
  1590. self.init = init
  1591. multiprocessing.Process.__init__(self)
  1592. self.context = bb.utils.get_context().copy()
  1593. self.handlers = bb.event.get_class_handlers().copy()
  1594. self.profile = profile
  1595. def run(self):
  1596. if not self.profile:
  1597. self.realrun()
  1598. return
  1599. try:
  1600. import cProfile as profile
  1601. except:
  1602. import profile
  1603. prof = profile.Profile()
  1604. try:
  1605. profile.Profile.runcall(prof, self.realrun)
  1606. finally:
  1607. logfile = "profile-parse-%s.log" % multiprocessing.current_process().name
  1608. prof.dump_stats(logfile)
  1609. def realrun(self):
  1610. if self.init:
  1611. self.init()
  1612. pending = []
  1613. while True:
  1614. try:
  1615. self.quit.get_nowait()
  1616. except queue.Empty:
  1617. pass
  1618. else:
  1619. self.results.cancel_join_thread()
  1620. break
  1621. if pending:
  1622. result = pending.pop()
  1623. else:
  1624. try:
  1625. job = self.jobs.pop()
  1626. except IndexError:
  1627. break
  1628. result = self.parse(*job)
  1629. try:
  1630. self.results.put(result, timeout=0.25)
  1631. except queue.Full:
  1632. pending.append(result)
  1633. def parse(self, filename, appends):
  1634. try:
  1635. # Record the filename we're parsing into any events generated
  1636. def parse_filter(self, record):
  1637. record.taskpid = bb.event.worker_pid
  1638. record.fn = filename
  1639. return True
  1640. # Reset our environment and handlers to the original settings
  1641. bb.utils.set_context(self.context.copy())
  1642. bb.event.set_class_handlers(self.handlers.copy())
  1643. bb.event.LogHandler.filter = parse_filter
  1644. return True, self.bb_cache.parse(filename, appends)
  1645. except Exception as exc:
  1646. tb = sys.exc_info()[2]
  1647. exc.recipe = filename
  1648. exc.traceback = list(bb.exceptions.extract_traceback(tb, context=3))
  1649. return True, exc
  1650. # Need to turn BaseExceptions into Exceptions here so we gracefully shutdown
  1651. # and for example a worker thread doesn't just exit on its own in response to
  1652. # a SystemExit event for example.
  1653. except BaseException as exc:
  1654. return True, ParsingFailure(exc, filename)
  1655. class CookerParser(object):
  1656. def __init__(self, cooker, filelist, masked):
  1657. self.filelist = filelist
  1658. self.cooker = cooker
  1659. self.cfgdata = cooker.data
  1660. self.cfghash = cooker.data_hash
  1661. self.cfgbuilder = cooker.databuilder
  1662. # Accounting statistics
  1663. self.parsed = 0
  1664. self.cached = 0
  1665. self.error = 0
  1666. self.masked = masked
  1667. self.skipped = 0
  1668. self.virtuals = 0
  1669. self.total = len(filelist)
  1670. self.current = 0
  1671. self.process_names = []
  1672. self.bb_cache = bb.cache.Cache(self.cfgbuilder, self.cfghash, cooker.caches_array)
  1673. self.fromcache = []
  1674. self.willparse = []
  1675. for filename in self.filelist:
  1676. appends = self.cooker.collection.get_file_appends(filename)
  1677. if not self.bb_cache.cacheValid(filename, appends):
  1678. self.willparse.append((filename, appends))
  1679. else:
  1680. self.fromcache.append((filename, appends))
  1681. self.toparse = self.total - len(self.fromcache)
  1682. self.progress_chunk = int(max(self.toparse / 100, 1))
  1683. self.num_processes = min(int(self.cfgdata.getVar("BB_NUMBER_PARSE_THREADS") or
  1684. multiprocessing.cpu_count()), len(self.willparse))
  1685. self.start()
  1686. self.haveshutdown = False
  1687. def start(self):
  1688. self.results = self.load_cached()
  1689. self.processes = []
  1690. if self.toparse:
  1691. bb.event.fire(bb.event.ParseStarted(self.toparse), self.cfgdata)
  1692. def init():
  1693. Parser.bb_cache = self.bb_cache
  1694. bb.utils.set_process_name(multiprocessing.current_process().name)
  1695. multiprocessing.util.Finalize(None, bb.codeparser.parser_cache_save, exitpriority=1)
  1696. multiprocessing.util.Finalize(None, bb.fetch.fetcher_parse_save, exitpriority=1)
  1697. self.parser_quit = multiprocessing.Queue(maxsize=self.num_processes)
  1698. self.result_queue = multiprocessing.Queue()
  1699. def chunkify(lst,n):
  1700. return [lst[i::n] for i in range(n)]
  1701. self.jobs = chunkify(self.willparse, self.num_processes)
  1702. for i in range(0, self.num_processes):
  1703. parser = Parser(self.jobs[i], self.result_queue, self.parser_quit, init, self.cooker.configuration.profile)
  1704. parser.start()
  1705. self.process_names.append(parser.name)
  1706. self.processes.append(parser)
  1707. self.results = itertools.chain(self.results, self.parse_generator())
  1708. def shutdown(self, clean=True, force=False):
  1709. if not self.toparse:
  1710. return
  1711. if self.haveshutdown:
  1712. return
  1713. self.haveshutdown = True
  1714. if clean:
  1715. event = bb.event.ParseCompleted(self.cached, self.parsed,
  1716. self.skipped, self.masked,
  1717. self.virtuals, self.error,
  1718. self.total)
  1719. bb.event.fire(event, self.cfgdata)
  1720. for process in self.processes:
  1721. self.parser_quit.put(None)
  1722. else:
  1723. self.parser_quit.cancel_join_thread()
  1724. for process in self.processes:
  1725. self.parser_quit.put(None)
  1726. for process in self.processes:
  1727. if force:
  1728. process.join(.1)
  1729. process.terminate()
  1730. else:
  1731. process.join()
  1732. sync = threading.Thread(target=self.bb_cache.sync)
  1733. sync.start()
  1734. multiprocessing.util.Finalize(None, sync.join, exitpriority=-100)
  1735. bb.codeparser.parser_cache_savemerge()
  1736. bb.fetch.fetcher_parse_done()
  1737. if self.cooker.configuration.profile:
  1738. profiles = []
  1739. for i in self.process_names:
  1740. logfile = "profile-parse-%s.log" % i
  1741. if os.path.exists(logfile):
  1742. profiles.append(logfile)
  1743. pout = "profile-parse.log.processed"
  1744. bb.utils.process_profilelog(profiles, pout = pout)
  1745. print("Processed parsing statistics saved to %s" % (pout))
  1746. def load_cached(self):
  1747. for filename, appends in self.fromcache:
  1748. cached, infos = self.bb_cache.load(filename, appends)
  1749. yield not cached, infos
  1750. def parse_generator(self):
  1751. while True:
  1752. if self.parsed >= self.toparse:
  1753. break
  1754. try:
  1755. result = self.result_queue.get(timeout=0.25)
  1756. except queue.Empty:
  1757. pass
  1758. else:
  1759. value = result[1]
  1760. if isinstance(value, BaseException):
  1761. raise value
  1762. else:
  1763. yield result
  1764. def parse_next(self):
  1765. result = []
  1766. parsed = None
  1767. try:
  1768. parsed, result = next(self.results)
  1769. except StopIteration:
  1770. self.shutdown()
  1771. return False
  1772. except bb.BBHandledException as exc:
  1773. self.error += 1
  1774. logger.error('Failed to parse recipe: %s' % exc.recipe)
  1775. self.shutdown(clean=False)
  1776. return False
  1777. except ParsingFailure as exc:
  1778. self.error += 1
  1779. logger.error('Unable to parse %s: %s' %
  1780. (exc.recipe, bb.exceptions.to_string(exc.realexception)))
  1781. self.shutdown(clean=False)
  1782. return False
  1783. except bb.parse.ParseError as exc:
  1784. self.error += 1
  1785. logger.error(str(exc))
  1786. self.shutdown(clean=False)
  1787. return False
  1788. except bb.data_smart.ExpansionError as exc:
  1789. self.error += 1
  1790. bbdir = os.path.dirname(__file__) + os.sep
  1791. etype, value, _ = sys.exc_info()
  1792. tb = list(itertools.dropwhile(lambda e: e.filename.startswith(bbdir), exc.traceback))
  1793. logger.error('ExpansionError during parsing %s', value.recipe,
  1794. exc_info=(etype, value, tb))
  1795. self.shutdown(clean=False)
  1796. return False
  1797. except Exception as exc:
  1798. self.error += 1
  1799. etype, value, tb = sys.exc_info()
  1800. if hasattr(value, "recipe"):
  1801. logger.error('Unable to parse %s' % value.recipe,
  1802. exc_info=(etype, value, exc.traceback))
  1803. else:
  1804. # Most likely, an exception occurred during raising an exception
  1805. import traceback
  1806. logger.error('Exception during parse: %s' % traceback.format_exc())
  1807. self.shutdown(clean=False)
  1808. return False
  1809. self.current += 1
  1810. self.virtuals += len(result)
  1811. if parsed:
  1812. self.parsed += 1
  1813. if self.parsed % self.progress_chunk == 0:
  1814. bb.event.fire(bb.event.ParseProgress(self.parsed, self.toparse),
  1815. self.cfgdata)
  1816. else:
  1817. self.cached += 1
  1818. for virtualfn, info_array in result:
  1819. if info_array[0].skipped:
  1820. self.skipped += 1
  1821. self.cooker.skiplist[virtualfn] = SkippedPackage(info_array[0])
  1822. (fn, cls, mc) = bb.cache.virtualfn2realfn(virtualfn)
  1823. self.bb_cache.add_info(virtualfn, info_array, self.cooker.recipecaches[mc],
  1824. parsed=parsed, watcher = self.cooker.add_filewatch)
  1825. return True
  1826. def reparse(self, filename):
  1827. infos = self.bb_cache.parse(filename, self.cooker.collection.get_file_appends(filename))
  1828. for vfn, info_array in infos:
  1829. (fn, cls, mc) = bb.cache.virtualfn2realfn(vfn)
  1830. self.cooker.recipecaches[mc].add_from_recipeinfo(vfn, info_array)