cooker.py 83 KB

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