cooker.py 86 KB

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