cooker.py 86 KB

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