cooker.py 86 KB

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