cooker.py 88 KB

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