cooker.py 86 KB

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