cooker.py 83 KB

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