cooker.py 87 KB

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