cooker.py 86 KB

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