cooker.py 81 KB

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