cooker.py 85 KB

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