cooker.py 90 KB

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