cooker.py 85 KB

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