cooker.py 86 KB

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