cooker.py 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254
  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, UnsupportedOperation
  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 in ("bb.event.BuildStarted", "bb.cooker.CookerExit"):
  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. try:
  196. fd = sys.stdout.fileno()
  197. if os.isatty(fd):
  198. import termios
  199. tcattr = termios.tcgetattr(fd)
  200. if tcattr[3] & termios.TOSTOP:
  201. buildlog.info("The terminal had the TOSTOP bit set, clearing...")
  202. tcattr[3] = tcattr[3] & ~termios.TOSTOP
  203. termios.tcsetattr(fd, termios.TCSANOW, tcattr)
  204. except UnsupportedOperation:
  205. pass
  206. self.command = bb.command.Command(self)
  207. self.state = state.initial
  208. self.parser = None
  209. signal.signal(signal.SIGTERM, self.sigterm_exception)
  210. # Let SIGHUP exit as SIGTERM
  211. signal.signal(signal.SIGHUP, self.sigterm_exception)
  212. def config_notifications(self, event):
  213. if not event.pathname in self.configwatcher.bbwatchedfiles:
  214. return
  215. if not event.pathname in self.inotify_modified_files:
  216. self.inotify_modified_files.append(event.pathname)
  217. self.baseconfig_valid = False
  218. def notifications(self, event):
  219. if not event.pathname in self.inotify_modified_files:
  220. self.inotify_modified_files.append(event.pathname)
  221. self.parsecache_valid = False
  222. def add_filewatch(self, deps, watcher=None):
  223. if not watcher:
  224. watcher = self.watcher
  225. for i in deps:
  226. watcher.bbwatchedfiles.append(i[0])
  227. f = os.path.dirname(i[0])
  228. if f in watcher.bbseen:
  229. continue
  230. watcher.bbseen.append(f)
  231. watchtarget = None
  232. while True:
  233. # We try and add watches for files that don't exist but if they did, would influence
  234. # the parser. The parent directory of these files may not exist, in which case we need
  235. # to watch any parent that does exist for changes.
  236. try:
  237. watcher.add_watch(f, self.watchmask, quiet=False)
  238. if watchtarget:
  239. watcher.bbwatchedfiles.append(watchtarget)
  240. break
  241. except pyinotify.WatchManagerError as e:
  242. if 'ENOENT' in str(e):
  243. watchtarget = f
  244. f = os.path.dirname(f)
  245. if f in watcher.bbseen:
  246. break
  247. watcher.bbseen.append(f)
  248. continue
  249. if 'ENOSPC' in str(e):
  250. providerlog.error("No space left on device or exceeds fs.inotify.max_user_watches?")
  251. providerlog.error("To check max_user_watches: sysctl -n fs.inotify.max_user_watches.")
  252. providerlog.error("To modify max_user_watches: sysctl -n -w fs.inotify.max_user_watches=<value>.")
  253. providerlog.error("Root privilege is required to modify max_user_watches.")
  254. raise
  255. def sigterm_exception(self, signum, stackframe):
  256. if signum == signal.SIGTERM:
  257. bb.warn("Cooker received SIGTERM, shutting down...")
  258. elif signum == signal.SIGHUP:
  259. bb.warn("Cooker received SIGHUP, shutting down...")
  260. self.state = state.forceshutdown
  261. def setFeatures(self, features):
  262. # we only accept a new feature set if we're in state initial, so we can reset without problems
  263. if not self.state in [state.initial, state.shutdown, state.forceshutdown, state.stopped, state.error]:
  264. raise Exception("Illegal state for feature set change")
  265. original_featureset = list(self.featureset)
  266. for feature in features:
  267. self.featureset.setFeature(feature)
  268. bb.debug(1, "Features set %s (was %s)" % (original_featureset, list(self.featureset)))
  269. if (original_featureset != list(self.featureset)) and self.state != state.error:
  270. self.reset()
  271. def initConfigurationData(self):
  272. self.state = state.initial
  273. self.caches_array = []
  274. # Need to preserve BB_CONSOLELOG over resets
  275. consolelog = None
  276. if hasattr(self, "data"):
  277. consolelog = self.data.getVar("BB_CONSOLELOG")
  278. if CookerFeatures.BASEDATASTORE_TRACKING in self.featureset:
  279. self.enableDataTracking()
  280. all_extra_cache_names = []
  281. # We hardcode all known cache types in a single place, here.
  282. if CookerFeatures.HOB_EXTRA_CACHES in self.featureset:
  283. all_extra_cache_names.append("bb.cache_extra:HobRecipeInfo")
  284. caches_name_array = ['bb.cache:CoreRecipeInfo'] + all_extra_cache_names
  285. # At least CoreRecipeInfo will be loaded, so caches_array will never be empty!
  286. # This is the entry point, no further check needed!
  287. for var in caches_name_array:
  288. try:
  289. module_name, cache_name = var.split(':')
  290. module = __import__(module_name, fromlist=(cache_name,))
  291. self.caches_array.append(getattr(module, cache_name))
  292. except ImportError as exc:
  293. logger.critical("Unable to import extra RecipeInfo '%s' from '%s': %s" % (cache_name, module_name, exc))
  294. sys.exit("FATAL: Failed to import extra cache class '%s'." % cache_name)
  295. self.databuilder = bb.cookerdata.CookerDataBuilder(self.configuration, False)
  296. self.databuilder.parseBaseConfiguration()
  297. self.data = self.databuilder.data
  298. self.data_hash = self.databuilder.data_hash
  299. if consolelog:
  300. self.data.setVar("BB_CONSOLELOG", consolelog)
  301. #
  302. # Copy of the data store which has been expanded.
  303. # Used for firing events and accessing variables where expansion needs to be accounted for
  304. #
  305. self.expanded_data = bb.data.createCopy(self.data)
  306. bb.data.update_data(self.expanded_data)
  307. bb.parse.init_parser(self.expanded_data)
  308. if CookerFeatures.BASEDATASTORE_TRACKING in self.featureset:
  309. self.disableDataTracking()
  310. self.data.renameVar("__depends", "__base_depends")
  311. self.add_filewatch(self.data.getVar("__base_depends", False), self.configwatcher)
  312. def enableDataTracking(self):
  313. self.configuration.tracking = True
  314. if hasattr(self, "data"):
  315. self.data.enableTracking()
  316. def disableDataTracking(self):
  317. self.configuration.tracking = False
  318. if hasattr(self, "data"):
  319. self.data.disableTracking()
  320. def modifyConfigurationVar(self, var, val, default_file, op):
  321. if op == "append":
  322. self.appendConfigurationVar(var, val, default_file)
  323. elif op == "set":
  324. self.saveConfigurationVar(var, val, default_file, "=")
  325. elif op == "earlyAssign":
  326. self.saveConfigurationVar(var, val, default_file, "?=")
  327. def appendConfigurationVar(self, var, val, default_file):
  328. #add append var operation to the end of default_file
  329. default_file = bb.cookerdata.findConfigFile(default_file, self.data)
  330. total = "#added by hob"
  331. total += "\n%s += \"%s\"\n" % (var, val)
  332. with open(default_file, 'a') as f:
  333. f.write(total)
  334. #add to history
  335. loginfo = {"op":"append", "file":default_file, "line":total.count("\n")}
  336. self.data.appendVar(var, val, **loginfo)
  337. def saveConfigurationVar(self, var, val, default_file, op):
  338. replaced = False
  339. #do not save if nothing changed
  340. if str(val) == self.data.getVar(var, False):
  341. return
  342. conf_files = self.data.varhistory.get_variable_files(var)
  343. #format the value when it is a list
  344. if isinstance(val, list):
  345. listval = ""
  346. for value in val:
  347. listval += "%s " % value
  348. val = listval
  349. topdir = self.data.getVar("TOPDIR", False)
  350. #comment or replace operations made on var
  351. for conf_file in conf_files:
  352. if topdir in conf_file:
  353. with open(conf_file, 'r') as f:
  354. contents = f.readlines()
  355. lines = self.data.varhistory.get_variable_lines(var, conf_file)
  356. for line in lines:
  357. total = ""
  358. i = 0
  359. for c in contents:
  360. total += c
  361. i = i + 1
  362. if i==int(line):
  363. end_index = len(total)
  364. index = total.rfind(var, 0, end_index)
  365. begin_line = total.count("\n",0,index)
  366. end_line = int(line)
  367. #check if the variable was saved before in the same way
  368. #if true it replace the place where the variable was declared
  369. #else it comments it
  370. if contents[begin_line-1]== "#added by hob\n":
  371. contents[begin_line] = "%s %s \"%s\"\n" % (var, op, val)
  372. replaced = True
  373. else:
  374. for ii in range(begin_line, end_line):
  375. contents[ii] = "#" + contents[ii]
  376. with open(conf_file, 'w') as f:
  377. f.writelines(contents)
  378. if replaced == False:
  379. #remove var from history
  380. self.data.varhistory.del_var_history(var)
  381. #add var to the end of default_file
  382. default_file = bb.cookerdata.findConfigFile(default_file, self.data)
  383. #add the variable on a single line, to be easy to replace the second time
  384. total = "\n#added by hob"
  385. total += "\n%s %s \"%s\"\n" % (var, op, val)
  386. with open(default_file, 'a') as f:
  387. f.write(total)
  388. #add to history
  389. loginfo = {"op":"set", "file":default_file, "line":total.count("\n")}
  390. self.data.setVar(var, val, **loginfo)
  391. def removeConfigurationVar(self, var):
  392. conf_files = self.data.varhistory.get_variable_files(var)
  393. topdir = self.data.getVar("TOPDIR", False)
  394. for conf_file in conf_files:
  395. if topdir in conf_file:
  396. with open(conf_file, 'r') as f:
  397. contents = f.readlines()
  398. lines = self.data.varhistory.get_variable_lines(var, conf_file)
  399. for line in lines:
  400. total = ""
  401. i = 0
  402. for c in contents:
  403. total += c
  404. i = i + 1
  405. if i==int(line):
  406. end_index = len(total)
  407. index = total.rfind(var, 0, end_index)
  408. begin_line = total.count("\n",0,index)
  409. #check if the variable was saved before in the same way
  410. if contents[begin_line-1]== "#added by hob\n":
  411. contents[begin_line-1] = contents[begin_line] = "\n"
  412. else:
  413. contents[begin_line] = "\n"
  414. #remove var from history
  415. self.data.varhistory.del_var_history(var, conf_file, line)
  416. #remove variable
  417. self.data.delVar(var)
  418. with open(conf_file, 'w') as f:
  419. f.writelines(contents)
  420. def createConfigFile(self, name):
  421. path = os.getcwd()
  422. confpath = os.path.join(path, "conf", name)
  423. open(confpath, 'w').close()
  424. def parseConfiguration(self):
  425. # Set log file verbosity
  426. verboselogs = bb.utils.to_boolean(self.data.getVar("BB_VERBOSE_LOGS", False))
  427. if verboselogs:
  428. bb.msg.loggerVerboseLogs = True
  429. # Change nice level if we're asked to
  430. nice = self.data.getVar("BB_NICE_LEVEL")
  431. if nice:
  432. curnice = os.nice(0)
  433. nice = int(nice) - curnice
  434. buildlog.verbose("Renice to %s " % os.nice(nice))
  435. if self.recipecaches:
  436. del self.recipecaches
  437. self.multiconfigs = self.databuilder.mcdata.keys()
  438. self.recipecaches = {}
  439. for mc in self.multiconfigs:
  440. self.recipecaches[mc] = bb.cache.CacheData(self.caches_array)
  441. self.handleCollections(self.data.getVar("BBFILE_COLLECTIONS"))
  442. def updateConfigOpts(self, options, environment):
  443. clean = True
  444. for o in options:
  445. if o in ['prefile', 'postfile']:
  446. clean = False
  447. server_val = getattr(self.configuration, "%s_server" % o)
  448. if not options[o] and server_val:
  449. # restore value provided on server start
  450. setattr(self.configuration, o, server_val)
  451. continue
  452. setattr(self.configuration, o, options[o])
  453. for k in bb.utils.approved_variables():
  454. if k in environment and k not in self.configuration.env:
  455. logger.debug(1, "Updating environment variable %s to %s" % (k, environment[k]))
  456. self.configuration.env[k] = environment[k]
  457. clean = False
  458. if k in self.configuration.env and k not in environment:
  459. logger.debug(1, "Updating environment variable %s (deleted)" % (k))
  460. del self.configuration.env[k]
  461. clean = False
  462. if k not in self.configuration.env and k not in environment:
  463. continue
  464. if environment[k] != self.configuration.env[k]:
  465. logger.debug(1, "Updating environment variable %s to %s" % (k, environment[k]))
  466. self.configuration.env[k] = environment[k]
  467. clean = False
  468. if not clean:
  469. logger.debug(1, "Base environment change, triggering reparse")
  470. self.baseconfig_valid = False
  471. self.reset()
  472. def runCommands(self, server, data, abort):
  473. """
  474. Run any queued asynchronous command
  475. This is done by the idle handler so it runs in true context rather than
  476. tied to any UI.
  477. """
  478. return self.command.runAsyncCommand()
  479. def showVersions(self):
  480. pkg_pn = self.recipecaches[''].pkg_pn
  481. (latest_versions, preferred_versions) = bb.providers.findProviders(self.data, self.recipecaches[''], pkg_pn)
  482. logger.plain("%-35s %25s %25s", "Recipe Name", "Latest Version", "Preferred Version")
  483. logger.plain("%-35s %25s %25s\n", "===========", "==============", "=================")
  484. for p in sorted(pkg_pn):
  485. pref = preferred_versions[p]
  486. latest = latest_versions[p]
  487. prefstr = pref[0][0] + ":" + pref[0][1] + '-' + pref[0][2]
  488. lateststr = latest[0][0] + ":" + latest[0][1] + "-" + latest[0][2]
  489. if pref == latest:
  490. prefstr = ""
  491. logger.plain("%-35s %25s %25s", p, lateststr, prefstr)
  492. def showEnvironment(self, buildfile=None, pkgs_to_build=None):
  493. """
  494. Show the outer or per-recipe environment
  495. """
  496. fn = None
  497. envdata = None
  498. if not pkgs_to_build:
  499. pkgs_to_build = []
  500. if buildfile:
  501. # Parse the configuration here. We need to do it explicitly here since
  502. # this showEnvironment() code path doesn't use the cache
  503. self.parseConfiguration()
  504. fn, cls, mc = bb.cache.virtualfn2realfn(buildfile)
  505. fn = self.matchFile(fn)
  506. fn = bb.cache.realfn2virtual(fn, cls, mc)
  507. elif len(pkgs_to_build) == 1:
  508. ignore = self.expanded_data.getVar("ASSUME_PROVIDED") or ""
  509. if pkgs_to_build[0] in set(ignore.split()):
  510. bb.fatal("%s is in ASSUME_PROVIDED" % pkgs_to_build[0])
  511. taskdata, runlist = self.buildTaskData(pkgs_to_build, None, self.configuration.abort, allowincomplete=True)
  512. mc = runlist[0][0]
  513. fn = runlist[0][3]
  514. else:
  515. envdata = self.data
  516. if fn:
  517. try:
  518. bb_cache = bb.cache.Cache(self.databuilder, self.data_hash, self.caches_array)
  519. envdata = bb_cache.loadDataFull(fn, self.collection.get_file_appends(fn))
  520. except Exception as e:
  521. parselog.exception("Unable to read %s", fn)
  522. raise
  523. # Display history
  524. with closing(StringIO()) as env:
  525. self.data.inchistory.emit(env)
  526. logger.plain(env.getvalue())
  527. # emit variables and shell functions
  528. data.update_data(envdata)
  529. with closing(StringIO()) as env:
  530. data.emit_env(env, envdata, True)
  531. logger.plain(env.getvalue())
  532. # emit the metadata which isnt valid shell
  533. data.expandKeys(envdata)
  534. for e in envdata.keys():
  535. if envdata.getVarFlag(e, 'func', False) and envdata.getVarFlag(e, 'python', False):
  536. logger.plain("\npython %s () {\n%s}\n", e, envdata.getVar(e, False))
  537. def buildTaskData(self, pkgs_to_build, task, abort, allowincomplete=False):
  538. """
  539. Prepare a runqueue and taskdata object for iteration over pkgs_to_build
  540. """
  541. bb.event.fire(bb.event.TreeDataPreparationStarted(), self.data)
  542. # A task of None means use the default task
  543. if task is None:
  544. task = self.configuration.cmd
  545. fulltargetlist = self.checkPackages(pkgs_to_build, task)
  546. taskdata = {}
  547. localdata = {}
  548. for mc in self.multiconfigs:
  549. taskdata[mc] = bb.taskdata.TaskData(abort, skiplist=self.skiplist, allowincomplete=allowincomplete)
  550. localdata[mc] = data.createCopy(self.databuilder.mcdata[mc])
  551. bb.data.update_data(localdata[mc])
  552. bb.data.expandKeys(localdata[mc])
  553. current = 0
  554. runlist = []
  555. for k in fulltargetlist:
  556. mc = ""
  557. if k.startswith("multiconfig:"):
  558. mc = k.split(":")[1]
  559. k = ":".join(k.split(":")[2:])
  560. ktask = task
  561. if ":do_" in k:
  562. k2 = k.split(":do_")
  563. k = k2[0]
  564. ktask = k2[1]
  565. taskdata[mc].add_provider(localdata[mc], self.recipecaches[mc], k)
  566. current += 1
  567. if not ktask.startswith("do_"):
  568. ktask = "do_%s" % ktask
  569. if k not in taskdata[mc].build_targets or not taskdata[mc].build_targets[k]:
  570. # e.g. in ASSUME_PROVIDED
  571. continue
  572. fn = taskdata[mc].build_targets[k][0]
  573. runlist.append([mc, k, ktask, fn])
  574. bb.event.fire(bb.event.TreeDataPreparationProgress(current, len(fulltargetlist)), self.data)
  575. for mc in self.multiconfigs:
  576. taskdata[mc].add_unresolved(localdata[mc], self.recipecaches[mc])
  577. bb.event.fire(bb.event.TreeDataPreparationCompleted(len(fulltargetlist)), self.data)
  578. return taskdata, runlist
  579. def prepareTreeData(self, pkgs_to_build, task):
  580. """
  581. Prepare a runqueue and taskdata object for iteration over pkgs_to_build
  582. """
  583. # We set abort to False here to prevent unbuildable targets raising
  584. # an exception when we're just generating data
  585. taskdata, runlist = self.buildTaskData(pkgs_to_build, task, False, allowincomplete=True)
  586. return runlist, taskdata
  587. ######## WARNING : this function requires cache_extra to be enabled ########
  588. def generateTaskDepTreeData(self, pkgs_to_build, task):
  589. """
  590. Create a dependency graph of pkgs_to_build including reverse dependency
  591. information.
  592. """
  593. runlist, taskdata = self.prepareTreeData(pkgs_to_build, task)
  594. rq = bb.runqueue.RunQueue(self, self.data, self.recipecaches, taskdata, runlist)
  595. rq.rqdata.prepare()
  596. return self.buildDependTree(rq, taskdata)
  597. @staticmethod
  598. def add_mc_prefix(mc, pn):
  599. if mc:
  600. return "multiconfig:%s.%s" % (mc, pn)
  601. return pn
  602. def buildDependTree(self, rq, taskdata):
  603. seen_fns = []
  604. depend_tree = {}
  605. depend_tree["depends"] = {}
  606. depend_tree["tdepends"] = {}
  607. depend_tree["pn"] = {}
  608. depend_tree["rdepends-pn"] = {}
  609. depend_tree["packages"] = {}
  610. depend_tree["rdepends-pkg"] = {}
  611. depend_tree["rrecs-pkg"] = {}
  612. depend_tree['providermap'] = {}
  613. depend_tree["layer-priorities"] = self.bbfile_config_priorities
  614. for mc in taskdata:
  615. for name, fn in list(taskdata[mc].get_providermap().items()):
  616. pn = self.recipecaches[mc].pkg_fn[fn]
  617. pn = self.add_mc_prefix(mc, pn)
  618. if name != pn:
  619. version = "%s:%s-%s" % self.recipecaches[mc].pkg_pepvpr[fn]
  620. depend_tree['providermap'][name] = (pn, version)
  621. for tid in rq.rqdata.runtaskentries:
  622. (mc, fn, taskname, taskfn) = bb.runqueue.split_tid_mcfn(tid)
  623. pn = self.recipecaches[mc].pkg_fn[taskfn]
  624. pn = self.add_mc_prefix(mc, pn)
  625. version = "%s:%s-%s" % self.recipecaches[mc].pkg_pepvpr[taskfn]
  626. if pn not in depend_tree["pn"]:
  627. depend_tree["pn"][pn] = {}
  628. depend_tree["pn"][pn]["filename"] = taskfn
  629. depend_tree["pn"][pn]["version"] = version
  630. depend_tree["pn"][pn]["inherits"] = self.recipecaches[mc].inherits.get(taskfn, None)
  631. # if we have extra caches, list all attributes they bring in
  632. extra_info = []
  633. for cache_class in self.caches_array:
  634. if type(cache_class) is type and issubclass(cache_class, bb.cache.RecipeInfoCommon) and hasattr(cache_class, 'cachefields'):
  635. cachefields = getattr(cache_class, 'cachefields', [])
  636. extra_info = extra_info + cachefields
  637. # for all attributes stored, add them to the dependency tree
  638. for ei in extra_info:
  639. depend_tree["pn"][pn][ei] = vars(self.recipecaches[mc])[ei][taskfn]
  640. for dep in rq.rqdata.runtaskentries[tid].depends:
  641. (depmc, depfn, deptaskname, deptaskfn) = bb.runqueue.split_tid_mcfn(dep)
  642. deppn = self.recipecaches[mc].pkg_fn[deptaskfn]
  643. dotname = "%s.%s" % (pn, bb.runqueue.taskname_from_tid(tid))
  644. if not dotname in depend_tree["tdepends"]:
  645. depend_tree["tdepends"][dotname] = []
  646. depend_tree["tdepends"][dotname].append("%s.%s" % (deppn, bb.runqueue.taskname_from_tid(dep)))
  647. if taskfn not in seen_fns:
  648. seen_fns.append(taskfn)
  649. packages = []
  650. depend_tree["depends"][pn] = []
  651. for dep in taskdata[mc].depids[taskfn]:
  652. depend_tree["depends"][pn].append(dep)
  653. depend_tree["rdepends-pn"][pn] = []
  654. for rdep in taskdata[mc].rdepids[taskfn]:
  655. depend_tree["rdepends-pn"][pn].append(rdep)
  656. rdepends = self.recipecaches[mc].rundeps[taskfn]
  657. for package in rdepends:
  658. depend_tree["rdepends-pkg"][package] = []
  659. for rdepend in rdepends[package]:
  660. depend_tree["rdepends-pkg"][package].append(rdepend)
  661. packages.append(package)
  662. rrecs = self.recipecaches[mc].runrecs[taskfn]
  663. for package in rrecs:
  664. depend_tree["rrecs-pkg"][package] = []
  665. for rdepend in rrecs[package]:
  666. depend_tree["rrecs-pkg"][package].append(rdepend)
  667. if not package in packages:
  668. packages.append(package)
  669. for package in packages:
  670. if package not in depend_tree["packages"]:
  671. depend_tree["packages"][package] = {}
  672. depend_tree["packages"][package]["pn"] = pn
  673. depend_tree["packages"][package]["filename"] = taskfn
  674. depend_tree["packages"][package]["version"] = version
  675. return depend_tree
  676. ######## WARNING : this function requires cache_extra to be enabled ########
  677. def generatePkgDepTreeData(self, pkgs_to_build, task):
  678. """
  679. Create a dependency tree of pkgs_to_build, returning the data.
  680. """
  681. _, taskdata = self.prepareTreeData(pkgs_to_build, task)
  682. seen_fns = []
  683. depend_tree = {}
  684. depend_tree["depends"] = {}
  685. depend_tree["pn"] = {}
  686. depend_tree["rdepends-pn"] = {}
  687. depend_tree["rdepends-pkg"] = {}
  688. depend_tree["rrecs-pkg"] = {}
  689. # if we have extra caches, list all attributes they bring in
  690. extra_info = []
  691. for cache_class in self.caches_array:
  692. if type(cache_class) is type and issubclass(cache_class, bb.cache.RecipeInfoCommon) and hasattr(cache_class, 'cachefields'):
  693. cachefields = getattr(cache_class, 'cachefields', [])
  694. extra_info = extra_info + cachefields
  695. tids = []
  696. for mc in taskdata:
  697. for tid in taskdata[mc].taskentries:
  698. tids.append(tid)
  699. for tid in tids:
  700. (mc, fn, taskname, taskfn) = bb.runqueue.split_tid_mcfn(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') 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') 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').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').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. bb.debug(1,'Processing %s in collection list' % (c))
  962. # Get collection priority if defined explicitly
  963. priority = self.data.getVar("BBFILE_PRIORITY_%s" % c)
  964. if priority:
  965. try:
  966. prio = int(priority)
  967. except ValueError:
  968. parselog.error("invalid value for BBFILE_PRIORITY_%s: \"%s\"", c, priority)
  969. errors = True
  970. if min_prio == 0 or prio < min_prio:
  971. min_prio = prio
  972. collection_priorities[c] = prio
  973. else:
  974. collection_priorities[c] = None
  975. # Check dependencies and store information for priority calculation
  976. deps = self.data.getVar("LAYERDEPENDS_%s" % c)
  977. if deps:
  978. try:
  979. depDict = bb.utils.explode_dep_versions2(deps)
  980. except bb.utils.VersionStringException as vse:
  981. bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
  982. for dep, oplist in list(depDict.items()):
  983. if dep in collection_list:
  984. for opstr in oplist:
  985. layerver = self.data.getVar("LAYERVERSION_%s" % dep)
  986. (op, depver) = opstr.split()
  987. if layerver:
  988. try:
  989. res = bb.utils.vercmp_string_op(layerver, depver, op)
  990. except bb.utils.VersionStringException as vse:
  991. bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
  992. if not res:
  993. 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)
  994. errors = True
  995. else:
  996. 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)
  997. errors = True
  998. else:
  999. parselog.error("Layer '%s' depends on layer '%s', but this layer is not enabled in your configuration", c, dep)
  1000. errors = True
  1001. collection_depends[c] = list(depDict.keys())
  1002. else:
  1003. collection_depends[c] = []
  1004. # Check recommends and store information for priority calculation
  1005. recs = self.data.getVar("LAYERRECOMMENDS_%s" % c)
  1006. if recs:
  1007. try:
  1008. recDict = bb.utils.explode_dep_versions2(recs)
  1009. except bb.utils.VersionStringException as vse:
  1010. bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
  1011. for rec, oplist in list(recDict.items()):
  1012. if rec in collection_list:
  1013. if oplist:
  1014. opstr = oplist[0]
  1015. layerver = self.data.getVar("LAYERVERSION_%s" % rec)
  1016. if layerver:
  1017. (op, recver) = opstr.split()
  1018. try:
  1019. res = bb.utils.vercmp_string_op(layerver, recver, op)
  1020. except bb.utils.VersionStringException as vse:
  1021. bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
  1022. if not res:
  1023. parselog.debug(3,"Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec, layerver)
  1024. continue
  1025. else:
  1026. parselog.debug(3,"Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec)
  1027. continue
  1028. parselog.debug(3,"Layer '%s' recommends layer '%s', so we are adding it", c, rec)
  1029. collection_depends[c].append(rec)
  1030. else:
  1031. parselog.debug(3,"Layer '%s' recommends layer '%s', but this layer is not enabled in your configuration", c, rec)
  1032. # Recursively work out collection priorities based on dependencies
  1033. def calc_layer_priority(collection):
  1034. if not collection_priorities[collection]:
  1035. max_depprio = min_prio
  1036. for dep in collection_depends[collection]:
  1037. calc_layer_priority(dep)
  1038. depprio = collection_priorities[dep]
  1039. if depprio > max_depprio:
  1040. max_depprio = depprio
  1041. max_depprio += 1
  1042. parselog.debug(1, "Calculated priority of layer %s as %d", collection, max_depprio)
  1043. collection_priorities[collection] = max_depprio
  1044. # Calculate all layer priorities using calc_layer_priority and store in bbfile_config_priorities
  1045. for c in collection_list:
  1046. calc_layer_priority(c)
  1047. regex = self.data.getVar("BBFILE_PATTERN_%s" % c)
  1048. if regex == None:
  1049. parselog.error("BBFILE_PATTERN_%s not defined" % c)
  1050. errors = True
  1051. continue
  1052. elif regex == "":
  1053. parselog.debug(1, "BBFILE_PATTERN_%s is empty" % c)
  1054. errors = False
  1055. continue
  1056. try:
  1057. cre = re.compile(regex)
  1058. except re.error:
  1059. parselog.error("BBFILE_PATTERN_%s \"%s\" is not a valid regular expression", c, regex)
  1060. errors = True
  1061. continue
  1062. self.bbfile_config_priorities.append((c, regex, cre, collection_priorities[c]))
  1063. if errors:
  1064. # We've already printed the actual error(s)
  1065. raise CollectionError("Errors during parsing layer configuration")
  1066. def buildSetVars(self):
  1067. """
  1068. Setup any variables needed before starting a build
  1069. """
  1070. t = time.gmtime()
  1071. if not self.data.getVar("BUILDNAME", False):
  1072. self.data.setVar("BUILDNAME", "${DATE}${TIME}")
  1073. self.data.setVar("BUILDSTART", time.strftime('%m/%d/%Y %H:%M:%S', t))
  1074. self.data.setVar("DATE", time.strftime('%Y%m%d', t))
  1075. self.data.setVar("TIME", time.strftime('%H%M%S', t))
  1076. def matchFiles(self, bf):
  1077. """
  1078. Find the .bb files which match the expression in 'buildfile'.
  1079. """
  1080. if bf.startswith("/") or bf.startswith("../"):
  1081. bf = os.path.abspath(bf)
  1082. self.collection = CookerCollectFiles(self.bbfile_config_priorities)
  1083. filelist, masked = self.collection.collect_bbfiles(self.data, self.expanded_data)
  1084. try:
  1085. os.stat(bf)
  1086. bf = os.path.abspath(bf)
  1087. return [bf]
  1088. except OSError:
  1089. regexp = re.compile(bf)
  1090. matches = []
  1091. for f in filelist:
  1092. if regexp.search(f) and os.path.isfile(f):
  1093. matches.append(f)
  1094. return matches
  1095. def matchFile(self, buildfile):
  1096. """
  1097. Find the .bb file which matches the expression in 'buildfile'.
  1098. Raise an error if multiple files
  1099. """
  1100. matches = self.matchFiles(buildfile)
  1101. if len(matches) != 1:
  1102. if matches:
  1103. msg = "Unable to match '%s' to a specific recipe file - %s matches found:" % (buildfile, len(matches))
  1104. if matches:
  1105. for f in matches:
  1106. msg += "\n %s" % f
  1107. parselog.error(msg)
  1108. else:
  1109. parselog.error("Unable to find any recipe file matching '%s'" % buildfile)
  1110. raise NoSpecificMatch
  1111. return matches[0]
  1112. def buildFile(self, buildfile, task):
  1113. """
  1114. Build the file matching regexp buildfile
  1115. """
  1116. bb.event.fire(bb.event.BuildInit(), self.expanded_data)
  1117. # Too many people use -b because they think it's how you normally
  1118. # specify a target to be built, so show a warning
  1119. bb.warn("Buildfile specified, dependencies will not be handled. If this is not what you want, do not use -b / --buildfile.")
  1120. # Parse the configuration here. We need to do it explicitly here since
  1121. # buildFile() doesn't use the cache
  1122. self.parseConfiguration()
  1123. # If we are told to do the None task then query the default task
  1124. if (task == None):
  1125. task = self.configuration.cmd
  1126. fn, cls, mc = bb.cache.virtualfn2realfn(buildfile)
  1127. fn = self.matchFile(fn)
  1128. self.buildSetVars()
  1129. bb_cache = bb.cache.Cache(self.databuilder, self.data_hash, self.caches_array)
  1130. infos = bb_cache.parse(fn, self.collection.get_file_appends(fn))
  1131. infos = dict(infos)
  1132. fn = bb.cache.realfn2virtual(fn, cls, mc)
  1133. try:
  1134. info_array = infos[fn]
  1135. except KeyError:
  1136. bb.fatal("%s does not exist" % fn)
  1137. if info_array[0].skipped:
  1138. bb.fatal("%s was skipped: %s" % (fn, info_array[0].skipreason))
  1139. self.recipecaches[mc].add_from_recipeinfo(fn, info_array)
  1140. # Tweak some variables
  1141. item = info_array[0].pn
  1142. self.recipecaches[mc].ignored_dependencies = set()
  1143. self.recipecaches[mc].bbfile_priority[fn] = 1
  1144. # Remove external dependencies
  1145. self.recipecaches[mc].task_deps[fn]['depends'] = {}
  1146. self.recipecaches[mc].deps[fn] = []
  1147. self.recipecaches[mc].rundeps[fn] = []
  1148. self.recipecaches[mc].runrecs[fn] = []
  1149. # Invalidate task for target if force mode active
  1150. if self.configuration.force:
  1151. logger.verbose("Invalidate task %s, %s", task, fn)
  1152. if not task.startswith("do_"):
  1153. task = "do_%s" % task
  1154. bb.parse.siggen.invalidate_task(task, self.recipecaches[mc], fn)
  1155. # Setup taskdata structure
  1156. taskdata = {}
  1157. taskdata[mc] = bb.taskdata.TaskData(self.configuration.abort)
  1158. taskdata[mc].add_provider(self.data, self.recipecaches[mc], item)
  1159. buildname = self.data.getVar("BUILDNAME")
  1160. bb.event.fire(bb.event.BuildStarted(buildname, [item]), self.expanded_data)
  1161. # Execute the runqueue
  1162. if not task.startswith("do_"):
  1163. task = "do_%s" % task
  1164. runlist = [[mc, item, task, fn]]
  1165. rq = bb.runqueue.RunQueue(self, self.data, self.recipecaches, taskdata, runlist)
  1166. def buildFileIdle(server, rq, abort):
  1167. msg = None
  1168. interrupted = 0
  1169. if abort or self.state == state.forceshutdown:
  1170. rq.finish_runqueue(True)
  1171. msg = "Forced shutdown"
  1172. interrupted = 2
  1173. elif self.state == state.shutdown:
  1174. rq.finish_runqueue(False)
  1175. msg = "Stopped build"
  1176. interrupted = 1
  1177. failures = 0
  1178. try:
  1179. retval = rq.execute_runqueue()
  1180. except runqueue.TaskFailure as exc:
  1181. failures += len(exc.args)
  1182. retval = False
  1183. except SystemExit as exc:
  1184. self.command.finishAsyncCommand(str(exc))
  1185. return False
  1186. if not retval:
  1187. bb.event.fire(bb.event.BuildCompleted(len(rq.rqdata.runtaskentries), buildname, item, failures, interrupted), self.expanded_data)
  1188. self.command.finishAsyncCommand(msg)
  1189. return False
  1190. if retval is True:
  1191. return True
  1192. return retval
  1193. self.configuration.server_register_idlecallback(buildFileIdle, rq)
  1194. def buildTargets(self, targets, task):
  1195. """
  1196. Attempt to build the targets specified
  1197. """
  1198. def buildTargetsIdle(server, rq, abort):
  1199. msg = None
  1200. interrupted = 0
  1201. if abort or self.state == state.forceshutdown:
  1202. rq.finish_runqueue(True)
  1203. msg = "Forced shutdown"
  1204. interrupted = 2
  1205. elif self.state == state.shutdown:
  1206. rq.finish_runqueue(False)
  1207. msg = "Stopped build"
  1208. interrupted = 1
  1209. failures = 0
  1210. try:
  1211. retval = rq.execute_runqueue()
  1212. except runqueue.TaskFailure as exc:
  1213. failures += len(exc.args)
  1214. retval = False
  1215. except SystemExit as exc:
  1216. self.command.finishAsyncCommand(str(exc))
  1217. return False
  1218. if not retval:
  1219. bb.event.fire(bb.event.BuildCompleted(len(rq.rqdata.runtaskentries), buildname, targets, failures, interrupted), self.data)
  1220. self.command.finishAsyncCommand(msg)
  1221. return False
  1222. if retval is True:
  1223. return True
  1224. return retval
  1225. build.reset_cache()
  1226. self.buildSetVars()
  1227. # If we are told to do the None task then query the default task
  1228. if (task == None):
  1229. task = self.configuration.cmd
  1230. if not task.startswith("do_"):
  1231. task = "do_%s" % task
  1232. packages = [target if ':' in target else '%s:%s' % (target, task) for target in targets]
  1233. bb.event.fire(bb.event.BuildInit(packages), self.expanded_data)
  1234. taskdata, runlist = self.buildTaskData(targets, task, self.configuration.abort)
  1235. buildname = self.data.getVar("BUILDNAME", False)
  1236. # make targets to always look as <target>:do_<task>
  1237. ntargets = []
  1238. for target in runlist:
  1239. if target[0]:
  1240. ntargets.append("multiconfig:%s:%s:%s" % (target[0], target[1], target[2]))
  1241. ntargets.append("%s:%s" % (target[1], target[2]))
  1242. bb.event.fire(bb.event.BuildStarted(buildname, ntargets), self.data)
  1243. rq = bb.runqueue.RunQueue(self, self.data, self.recipecaches, taskdata, runlist)
  1244. if 'universe' in targets:
  1245. rq.rqdata.warn_multi_bb = True
  1246. self.configuration.server_register_idlecallback(buildTargetsIdle, rq)
  1247. def getAllKeysWithFlags(self, flaglist):
  1248. dump = {}
  1249. for k in self.data.keys():
  1250. try:
  1251. expand = True
  1252. flags = self.data.getVarFlags(k)
  1253. if flags and "func" in flags and "python" in flags:
  1254. expand = False
  1255. v = self.data.getVar(k, expand)
  1256. if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart):
  1257. dump[k] = {
  1258. 'v' : v ,
  1259. 'history' : self.data.varhistory.variable(k),
  1260. }
  1261. for d in flaglist:
  1262. if flags and d in flags:
  1263. dump[k][d] = flags[d]
  1264. else:
  1265. dump[k][d] = None
  1266. except Exception as e:
  1267. print(e)
  1268. return dump
  1269. def generateNewImage(self, image, base_image, package_queue, timestamp, description):
  1270. '''
  1271. Create a new image with a "require"/"inherit" base_image statement
  1272. '''
  1273. if timestamp:
  1274. image_name = os.path.splitext(image)[0]
  1275. timestr = time.strftime("-%Y%m%d-%H%M%S")
  1276. dest = image_name + str(timestr) + ".bb"
  1277. else:
  1278. if not image.endswith(".bb"):
  1279. dest = image + ".bb"
  1280. else:
  1281. dest = image
  1282. basename = False
  1283. if base_image:
  1284. with open(base_image, 'r') as f:
  1285. require_line = f.readline()
  1286. p = re.compile("IMAGE_BASENAME *=")
  1287. for line in f:
  1288. if p.search(line):
  1289. basename = True
  1290. with open(dest, "w") as imagefile:
  1291. if base_image is None:
  1292. imagefile.write("inherit core-image\n")
  1293. else:
  1294. topdir = self.data.getVar("TOPDIR", False)
  1295. if topdir in base_image:
  1296. base_image = require_line.split()[1]
  1297. imagefile.write("require " + base_image + "\n")
  1298. image_install = "IMAGE_INSTALL = \""
  1299. for package in package_queue:
  1300. image_install += str(package) + " "
  1301. image_install += "\"\n"
  1302. imagefile.write(image_install)
  1303. description_var = "DESCRIPTION = \"" + description + "\"\n"
  1304. imagefile.write(description_var)
  1305. if basename:
  1306. # If this is overwritten in a inherited image, reset it to default
  1307. image_basename = "IMAGE_BASENAME = \"${PN}\"\n"
  1308. imagefile.write(image_basename)
  1309. self.state = state.initial
  1310. if timestamp:
  1311. return timestr
  1312. def updateCacheSync(self):
  1313. if self.state == state.running:
  1314. return
  1315. # reload files for which we got notifications
  1316. for p in self.inotify_modified_files:
  1317. bb.parse.update_cache(p)
  1318. if p in bb.parse.BBHandler.cached_statements:
  1319. del bb.parse.BBHandler.cached_statements[p]
  1320. self.inotify_modified_files = []
  1321. if not self.baseconfig_valid:
  1322. logger.debug(1, "Reloading base configuration data")
  1323. self.initConfigurationData()
  1324. self.baseconfig_valid = True
  1325. self.parsecache_valid = False
  1326. # This is called for all async commands when self.state != running
  1327. def updateCache(self):
  1328. if self.state == state.running:
  1329. return
  1330. if self.state in (state.shutdown, state.forceshutdown, state.error):
  1331. if hasattr(self.parser, 'shutdown'):
  1332. self.parser.shutdown(clean=False, force = True)
  1333. raise bb.BBHandledException()
  1334. if self.state != state.parsing:
  1335. self.updateCacheSync()
  1336. if self.state != state.parsing and not self.parsecache_valid:
  1337. self.parseConfiguration ()
  1338. if CookerFeatures.SEND_SANITYEVENTS in self.featureset:
  1339. bb.event.fire(bb.event.SanityCheck(False), self.data)
  1340. for mc in self.multiconfigs:
  1341. ignore = self.databuilder.mcdata[mc].getVar("ASSUME_PROVIDED") or ""
  1342. self.recipecaches[mc].ignored_dependencies = set(ignore.split())
  1343. for dep in self.configuration.extra_assume_provided:
  1344. self.recipecaches[mc].ignored_dependencies.add(dep)
  1345. self.collection = CookerCollectFiles(self.bbfile_config_priorities)
  1346. (filelist, masked) = self.collection.collect_bbfiles(self.data, self.expanded_data)
  1347. self.parser = CookerParser(self, filelist, masked)
  1348. self.parsecache_valid = True
  1349. self.state = state.parsing
  1350. if not self.parser.parse_next():
  1351. collectlog.debug(1, "parsing complete")
  1352. if self.parser.error:
  1353. raise bb.BBHandledException()
  1354. self.show_appends_with_no_recipes()
  1355. self.handlePrefProviders()
  1356. for mc in self.multiconfigs:
  1357. self.recipecaches[mc].bbfile_priority = self.collection.collection_priorities(self.recipecaches[mc].pkg_fn, self.data)
  1358. self.state = state.running
  1359. # Send an event listing all stamps reachable after parsing
  1360. # which the metadata may use to clean up stale data
  1361. for mc in self.multiconfigs:
  1362. event = bb.event.ReachableStamps(self.recipecaches[mc].stamp)
  1363. bb.event.fire(event, self.databuilder.mcdata[mc])
  1364. return None
  1365. return True
  1366. def checkPackages(self, pkgs_to_build, task=None):
  1367. # Return a copy, don't modify the original
  1368. pkgs_to_build = pkgs_to_build[:]
  1369. if len(pkgs_to_build) == 0:
  1370. raise NothingToBuild
  1371. ignore = (self.expanded_data.getVar("ASSUME_PROVIDED") or "").split()
  1372. for pkg in pkgs_to_build:
  1373. if pkg in ignore:
  1374. parselog.warning("Explicit target \"%s\" is in ASSUME_PROVIDED, ignoring" % pkg)
  1375. if 'world' in pkgs_to_build:
  1376. pkgs_to_build.remove('world')
  1377. for mc in self.multiconfigs:
  1378. bb.providers.buildWorldTargetList(self.recipecaches[mc], task)
  1379. for t in self.recipecaches[mc].world_target:
  1380. if mc:
  1381. t = "multiconfig:" + mc + ":" + t
  1382. pkgs_to_build.append(t)
  1383. if 'universe' in pkgs_to_build:
  1384. parselog.warning("The \"universe\" target is only intended for testing and may produce errors.")
  1385. parselog.debug(1, "collating packages for \"universe\"")
  1386. pkgs_to_build.remove('universe')
  1387. for mc in self.multiconfigs:
  1388. for t in self.recipecaches[mc].universe_target:
  1389. if mc:
  1390. t = "multiconfig:" + mc + ":" + t
  1391. pkgs_to_build.append(t)
  1392. return pkgs_to_build
  1393. def pre_serve(self):
  1394. # Empty the environment. The environment will be populated as
  1395. # necessary from the data store.
  1396. #bb.utils.empty_environment()
  1397. try:
  1398. self.prhost = prserv.serv.auto_start(self.data)
  1399. except prserv.serv.PRServiceConfigError:
  1400. bb.event.fire(CookerExit(), self.expanded_data)
  1401. self.state = state.error
  1402. return
  1403. def post_serve(self):
  1404. prserv.serv.auto_shutdown(self.data)
  1405. bb.event.fire(CookerExit(), self.expanded_data)
  1406. lockfile = self.lock.name
  1407. self.lock.close()
  1408. self.lock = None
  1409. while not self.lock:
  1410. with bb.utils.timeout(3):
  1411. self.lock = bb.utils.lockfile(lockfile, shared=False, retry=False, block=True)
  1412. if not self.lock:
  1413. # Some systems may not have lsof available
  1414. procs = None
  1415. try:
  1416. procs = subprocess.check_output(["lsof", '-w', lockfile], stderr=subprocess.STDOUT)
  1417. except OSError as e:
  1418. if e.errno != errno.ENOENT:
  1419. raise
  1420. if procs is None:
  1421. # Fall back to fuser if lsof is unavailable
  1422. try:
  1423. procs = subprocess.check_output(["fuser", '-v', lockfile], stderr=subprocess.STDOUT)
  1424. except OSError as e:
  1425. if e.errno != errno.ENOENT:
  1426. raise
  1427. msg = "Delaying shutdown due to active processes which appear to be holding bitbake.lock"
  1428. if procs:
  1429. msg += ":\n%s" % str(procs)
  1430. print(msg)
  1431. def shutdown(self, force = False):
  1432. if force:
  1433. self.state = state.forceshutdown
  1434. else:
  1435. self.state = state.shutdown
  1436. if self.parser:
  1437. self.parser.shutdown(clean=not force, force=force)
  1438. def finishcommand(self):
  1439. self.state = state.initial
  1440. def reset(self):
  1441. self.initConfigurationData()
  1442. def lockBitbake(self):
  1443. if not hasattr(self, 'lock'):
  1444. self.lock = None
  1445. if self.data:
  1446. lockfile = self.data.expand("${TOPDIR}/bitbake.lock")
  1447. if lockfile:
  1448. self.lock = bb.utils.lockfile(lockfile, False, False)
  1449. return self.lock
  1450. def unlockBitbake(self):
  1451. if hasattr(self, 'lock') and self.lock:
  1452. bb.utils.unlockfile(self.lock)
  1453. def server_main(cooker, func, *args):
  1454. cooker.pre_serve()
  1455. if cooker.configuration.profile:
  1456. try:
  1457. import cProfile as profile
  1458. except:
  1459. import profile
  1460. prof = profile.Profile()
  1461. ret = profile.Profile.runcall(prof, func, *args)
  1462. prof.dump_stats("profile.log")
  1463. bb.utils.process_profilelog("profile.log")
  1464. print("Raw profiling information saved to profile.log and processed statistics to profile.log.processed")
  1465. else:
  1466. ret = func(*args)
  1467. cooker.post_serve()
  1468. return ret
  1469. class CookerExit(bb.event.Event):
  1470. """
  1471. Notify clients of the Cooker shutdown
  1472. """
  1473. def __init__(self):
  1474. bb.event.Event.__init__(self)
  1475. class CookerCollectFiles(object):
  1476. def __init__(self, priorities):
  1477. self.bbappends = []
  1478. self.bbfile_config_priorities = priorities
  1479. def calc_bbfile_priority( self, filename, matched = None ):
  1480. for _, _, regex, pri in self.bbfile_config_priorities:
  1481. if regex.match(filename):
  1482. if matched != None:
  1483. if not regex in matched:
  1484. matched.add(regex)
  1485. return pri
  1486. return 0
  1487. def get_bbfiles(self):
  1488. """Get list of default .bb files by reading out the current directory"""
  1489. path = os.getcwd()
  1490. contents = os.listdir(path)
  1491. bbfiles = []
  1492. for f in contents:
  1493. if f.endswith(".bb"):
  1494. bbfiles.append(os.path.abspath(os.path.join(path, f)))
  1495. return bbfiles
  1496. def find_bbfiles(self, path):
  1497. """Find all the .bb and .bbappend files in a directory"""
  1498. found = []
  1499. for dir, dirs, files in os.walk(path):
  1500. for ignored in ('SCCS', 'CVS', '.svn'):
  1501. if ignored in dirs:
  1502. dirs.remove(ignored)
  1503. found += [os.path.join(dir, f) for f in files if (f.endswith(['.bb', '.bbappend']))]
  1504. return found
  1505. def collect_bbfiles(self, config, eventdata):
  1506. """Collect all available .bb build files"""
  1507. masked = 0
  1508. collectlog.debug(1, "collecting .bb files")
  1509. files = (config.getVar( "BBFILES") or "").split()
  1510. config.setVar("BBFILES", " ".join(files))
  1511. # Sort files by priority
  1512. files.sort( key=lambda fileitem: self.calc_bbfile_priority(fileitem) )
  1513. if not len(files):
  1514. files = self.get_bbfiles()
  1515. if not len(files):
  1516. collectlog.error("no recipe files to build, check your BBPATH and BBFILES?")
  1517. bb.event.fire(CookerExit(), eventdata)
  1518. # Can't use set here as order is important
  1519. newfiles = []
  1520. for f in files:
  1521. if os.path.isdir(f):
  1522. dirfiles = self.find_bbfiles(f)
  1523. for g in dirfiles:
  1524. if g not in newfiles:
  1525. newfiles.append(g)
  1526. else:
  1527. globbed = glob.glob(f)
  1528. if not globbed and os.path.exists(f):
  1529. globbed = [f]
  1530. # glob gives files in order on disk. Sort to be deterministic.
  1531. for g in sorted(globbed):
  1532. if g not in newfiles:
  1533. newfiles.append(g)
  1534. bbmask = config.getVar('BBMASK')
  1535. if bbmask:
  1536. # First validate the individual regular expressions and ignore any
  1537. # that do not compile
  1538. bbmasks = []
  1539. for mask in bbmask.split():
  1540. try:
  1541. re.compile(mask)
  1542. bbmasks.append(mask)
  1543. except sre_constants.error:
  1544. collectlog.critical("BBMASK contains an invalid regular expression, ignoring: %s" % mask)
  1545. # Then validate the combined regular expressions. This should never
  1546. # fail, but better safe than sorry...
  1547. bbmask = "|".join(bbmasks)
  1548. try:
  1549. bbmask_compiled = re.compile(bbmask)
  1550. except sre_constants.error:
  1551. collectlog.critical("BBMASK is not a valid regular expression, ignoring: %s" % bbmask)
  1552. bbmask = None
  1553. bbfiles = []
  1554. bbappend = []
  1555. for f in newfiles:
  1556. if bbmask and bbmask_compiled.search(f):
  1557. collectlog.debug(1, "skipping masked file %s", f)
  1558. masked += 1
  1559. continue
  1560. if f.endswith('.bb'):
  1561. bbfiles.append(f)
  1562. elif f.endswith('.bbappend'):
  1563. bbappend.append(f)
  1564. else:
  1565. collectlog.debug(1, "skipping %s: unknown file extension", f)
  1566. # Build a list of .bbappend files for each .bb file
  1567. for f in bbappend:
  1568. base = os.path.basename(f).replace('.bbappend', '.bb')
  1569. self.bbappends.append((base, f))
  1570. # Find overlayed recipes
  1571. # bbfiles will be in priority order which makes this easy
  1572. bbfile_seen = dict()
  1573. self.overlayed = defaultdict(list)
  1574. for f in reversed(bbfiles):
  1575. base = os.path.basename(f)
  1576. if base not in bbfile_seen:
  1577. bbfile_seen[base] = f
  1578. else:
  1579. topfile = bbfile_seen[base]
  1580. self.overlayed[topfile].append(f)
  1581. return (bbfiles, masked)
  1582. def get_file_appends(self, fn):
  1583. """
  1584. Returns a list of .bbappend files to apply to fn
  1585. """
  1586. filelist = []
  1587. f = os.path.basename(fn)
  1588. for b in self.bbappends:
  1589. (bbappend, filename) = b
  1590. if (bbappend == f) or ('%' in bbappend and bbappend.startswith(f[:bbappend.index('%')])):
  1591. filelist.append(filename)
  1592. return filelist
  1593. def collection_priorities(self, pkgfns, d):
  1594. priorities = {}
  1595. # Calculate priorities for each file
  1596. matched = set()
  1597. for p in pkgfns:
  1598. realfn, cls, mc = bb.cache.virtualfn2realfn(p)
  1599. priorities[p] = self.calc_bbfile_priority(realfn, matched)
  1600. # Don't show the warning if the BBFILE_PATTERN did match .bbappend files
  1601. unmatched = set()
  1602. for _, _, regex, pri in self.bbfile_config_priorities:
  1603. if not regex in matched:
  1604. unmatched.add(regex)
  1605. def findmatch(regex):
  1606. for b in self.bbappends:
  1607. (bbfile, append) = b
  1608. if regex.match(append):
  1609. return True
  1610. return False
  1611. for unmatch in unmatched.copy():
  1612. if findmatch(unmatch):
  1613. unmatched.remove(unmatch)
  1614. for collection, pattern, regex, _ in self.bbfile_config_priorities:
  1615. if regex in unmatched:
  1616. if d.getVar('BBFILE_PATTERN_IGNORE_EMPTY_%s' % collection) != '1':
  1617. collectlog.warning("No bb files matched BBFILE_PATTERN_%s '%s'" % (collection, pattern))
  1618. return priorities
  1619. class ParsingFailure(Exception):
  1620. def __init__(self, realexception, recipe):
  1621. self.realexception = realexception
  1622. self.recipe = recipe
  1623. Exception.__init__(self, realexception, recipe)
  1624. class Feeder(multiprocessing.Process):
  1625. def __init__(self, jobs, to_parsers, quit):
  1626. self.quit = quit
  1627. self.jobs = jobs
  1628. self.to_parsers = to_parsers
  1629. multiprocessing.Process.__init__(self)
  1630. def run(self):
  1631. while True:
  1632. try:
  1633. quit = self.quit.get_nowait()
  1634. except queue.Empty:
  1635. pass
  1636. else:
  1637. if quit == 'cancel':
  1638. self.to_parsers.cancel_join_thread()
  1639. break
  1640. try:
  1641. job = self.jobs.pop()
  1642. except IndexError:
  1643. break
  1644. try:
  1645. self.to_parsers.put(job, timeout=0.5)
  1646. except queue.Full:
  1647. self.jobs.insert(0, job)
  1648. continue
  1649. class Parser(multiprocessing.Process):
  1650. def __init__(self, jobs, results, quit, init, profile):
  1651. self.jobs = jobs
  1652. self.results = results
  1653. self.quit = quit
  1654. self.init = init
  1655. multiprocessing.Process.__init__(self)
  1656. self.context = bb.utils.get_context().copy()
  1657. self.handlers = bb.event.get_class_handlers().copy()
  1658. self.profile = profile
  1659. def run(self):
  1660. if not self.profile:
  1661. self.realrun()
  1662. return
  1663. try:
  1664. import cProfile as profile
  1665. except:
  1666. import profile
  1667. prof = profile.Profile()
  1668. try:
  1669. profile.Profile.runcall(prof, self.realrun)
  1670. finally:
  1671. logfile = "profile-parse-%s.log" % multiprocessing.current_process().name
  1672. prof.dump_stats(logfile)
  1673. def realrun(self):
  1674. if self.init:
  1675. self.init()
  1676. pending = []
  1677. while True:
  1678. try:
  1679. self.quit.get_nowait()
  1680. except queue.Empty:
  1681. pass
  1682. else:
  1683. self.results.cancel_join_thread()
  1684. break
  1685. if pending:
  1686. result = pending.pop()
  1687. else:
  1688. try:
  1689. job = self.jobs.get(timeout=0.25)
  1690. except queue.Empty:
  1691. continue
  1692. if job is None:
  1693. break
  1694. result = self.parse(*job)
  1695. try:
  1696. self.results.put(result, timeout=0.25)
  1697. except queue.Full:
  1698. pending.append(result)
  1699. def parse(self, filename, appends):
  1700. try:
  1701. # Record the filename we're parsing into any events generated
  1702. def parse_filter(self, record):
  1703. record.taskpid = bb.event.worker_pid
  1704. record.fn = filename
  1705. return True
  1706. # Reset our environment and handlers to the original settings
  1707. bb.utils.set_context(self.context.copy())
  1708. bb.event.set_class_handlers(self.handlers.copy())
  1709. bb.event.LogHandler.filter = parse_filter
  1710. return True, self.bb_cache.parse(filename, appends)
  1711. except Exception as exc:
  1712. tb = sys.exc_info()[2]
  1713. exc.recipe = filename
  1714. exc.traceback = list(bb.exceptions.extract_traceback(tb, context=3))
  1715. return True, exc
  1716. # Need to turn BaseExceptions into Exceptions here so we gracefully shutdown
  1717. # and for example a worker thread doesn't just exit on its own in response to
  1718. # a SystemExit event for example.
  1719. except BaseException as exc:
  1720. return True, ParsingFailure(exc, filename)
  1721. class CookerParser(object):
  1722. def __init__(self, cooker, filelist, masked):
  1723. self.filelist = filelist
  1724. self.cooker = cooker
  1725. self.cfgdata = cooker.data
  1726. self.cfghash = cooker.data_hash
  1727. self.cfgbuilder = cooker.databuilder
  1728. # Accounting statistics
  1729. self.parsed = 0
  1730. self.cached = 0
  1731. self.error = 0
  1732. self.masked = masked
  1733. self.skipped = 0
  1734. self.virtuals = 0
  1735. self.total = len(filelist)
  1736. self.current = 0
  1737. self.process_names = []
  1738. self.bb_cache = bb.cache.Cache(self.cfgbuilder, self.cfghash, cooker.caches_array)
  1739. self.fromcache = []
  1740. self.willparse = []
  1741. for filename in self.filelist:
  1742. appends = self.cooker.collection.get_file_appends(filename)
  1743. if not self.bb_cache.cacheValid(filename, appends):
  1744. self.willparse.append((filename, appends))
  1745. else:
  1746. self.fromcache.append((filename, appends))
  1747. self.toparse = self.total - len(self.fromcache)
  1748. self.progress_chunk = int(max(self.toparse / 100, 1))
  1749. self.num_processes = min(int(self.cfgdata.getVar("BB_NUMBER_PARSE_THREADS") or
  1750. multiprocessing.cpu_count()), len(self.willparse))
  1751. self.start()
  1752. self.haveshutdown = False
  1753. def start(self):
  1754. self.results = self.load_cached()
  1755. self.processes = []
  1756. if self.toparse:
  1757. bb.event.fire(bb.event.ParseStarted(self.toparse), self.cfgdata)
  1758. def init():
  1759. Parser.bb_cache = self.bb_cache
  1760. bb.utils.set_process_name(multiprocessing.current_process().name)
  1761. multiprocessing.util.Finalize(None, bb.codeparser.parser_cache_save, exitpriority=1)
  1762. multiprocessing.util.Finalize(None, bb.fetch.fetcher_parse_save, exitpriority=1)
  1763. self.feeder_quit = multiprocessing.Queue(maxsize=1)
  1764. self.parser_quit = multiprocessing.Queue(maxsize=self.num_processes)
  1765. self.jobs = multiprocessing.Queue(maxsize=self.num_processes)
  1766. self.result_queue = multiprocessing.Queue()
  1767. self.feeder = Feeder(self.willparse, self.jobs, self.feeder_quit)
  1768. self.feeder.start()
  1769. for i in range(0, self.num_processes):
  1770. parser = Parser(self.jobs, self.result_queue, self.parser_quit, init, self.cooker.configuration.profile)
  1771. parser.start()
  1772. self.process_names.append(parser.name)
  1773. self.processes.append(parser)
  1774. self.results = itertools.chain(self.results, self.parse_generator())
  1775. def shutdown(self, clean=True, force=False):
  1776. if not self.toparse:
  1777. return
  1778. if self.haveshutdown:
  1779. return
  1780. self.haveshutdown = True
  1781. if clean:
  1782. event = bb.event.ParseCompleted(self.cached, self.parsed,
  1783. self.skipped, self.masked,
  1784. self.virtuals, self.error,
  1785. self.total)
  1786. bb.event.fire(event, self.cfgdata)
  1787. self.feeder_quit.put(None)
  1788. for process in self.processes:
  1789. self.parser_quit.put(None)
  1790. else:
  1791. self.feeder_quit.put('cancel')
  1792. self.parser_quit.cancel_join_thread()
  1793. for process in self.processes:
  1794. self.parser_quit.put(None)
  1795. self.jobs.cancel_join_thread()
  1796. for process in self.processes:
  1797. if force:
  1798. process.join(.1)
  1799. process.terminate()
  1800. else:
  1801. process.join()
  1802. self.feeder.join()
  1803. sync = threading.Thread(target=self.bb_cache.sync)
  1804. sync.start()
  1805. multiprocessing.util.Finalize(None, sync.join, exitpriority=-100)
  1806. bb.codeparser.parser_cache_savemerge()
  1807. bb.fetch.fetcher_parse_done()
  1808. if self.cooker.configuration.profile:
  1809. profiles = []
  1810. for i in self.process_names:
  1811. logfile = "profile-parse-%s.log" % i
  1812. if os.path.exists(logfile):
  1813. profiles.append(logfile)
  1814. pout = "profile-parse.log.processed"
  1815. bb.utils.process_profilelog(profiles, pout = pout)
  1816. print("Processed parsing statistics saved to %s" % (pout))
  1817. def load_cached(self):
  1818. for filename, appends in self.fromcache:
  1819. cached, infos = self.bb_cache.load(filename, appends)
  1820. yield not cached, infos
  1821. def parse_generator(self):
  1822. while True:
  1823. if self.parsed >= self.toparse:
  1824. break
  1825. try:
  1826. result = self.result_queue.get(timeout=0.25)
  1827. except queue.Empty:
  1828. pass
  1829. else:
  1830. value = result[1]
  1831. if isinstance(value, BaseException):
  1832. raise value
  1833. else:
  1834. yield result
  1835. def parse_next(self):
  1836. result = []
  1837. parsed = None
  1838. try:
  1839. parsed, result = next(self.results)
  1840. except StopIteration:
  1841. self.shutdown()
  1842. return False
  1843. except bb.BBHandledException as exc:
  1844. self.error += 1
  1845. logger.error('Failed to parse recipe: %s' % exc.recipe)
  1846. self.shutdown(clean=False)
  1847. return False
  1848. except ParsingFailure as exc:
  1849. self.error += 1
  1850. logger.error('Unable to parse %s: %s' %
  1851. (exc.recipe, bb.exceptions.to_string(exc.realexception)))
  1852. self.shutdown(clean=False)
  1853. return False
  1854. except bb.parse.ParseError as exc:
  1855. self.error += 1
  1856. logger.error(str(exc))
  1857. self.shutdown(clean=False)
  1858. return False
  1859. except bb.data_smart.ExpansionError as exc:
  1860. self.error += 1
  1861. bbdir = os.path.dirname(__file__) + os.sep
  1862. etype, value, _ = sys.exc_info()
  1863. tb = list(itertools.dropwhile(lambda e: e.filename.startswith(bbdir), exc.traceback))
  1864. logger.error('ExpansionError during parsing %s', value.recipe,
  1865. exc_info=(etype, value, tb))
  1866. self.shutdown(clean=False)
  1867. return False
  1868. except Exception as exc:
  1869. self.error += 1
  1870. etype, value, tb = sys.exc_info()
  1871. if hasattr(value, "recipe"):
  1872. logger.error('Unable to parse %s' % value.recipe,
  1873. exc_info=(etype, value, exc.traceback))
  1874. else:
  1875. # Most likely, an exception occurred during raising an exception
  1876. import traceback
  1877. logger.error('Exception during parse: %s' % traceback.format_exc())
  1878. self.shutdown(clean=False)
  1879. return False
  1880. self.current += 1
  1881. self.virtuals += len(result)
  1882. if parsed:
  1883. self.parsed += 1
  1884. if self.parsed % self.progress_chunk == 0:
  1885. bb.event.fire(bb.event.ParseProgress(self.parsed, self.toparse),
  1886. self.cfgdata)
  1887. else:
  1888. self.cached += 1
  1889. for virtualfn, info_array in result:
  1890. if info_array[0].skipped:
  1891. self.skipped += 1
  1892. self.cooker.skiplist[virtualfn] = SkippedPackage(info_array[0])
  1893. (fn, cls, mc) = bb.cache.virtualfn2realfn(virtualfn)
  1894. self.bb_cache.add_info(virtualfn, info_array, self.cooker.recipecaches[mc],
  1895. parsed=parsed, watcher = self.cooker.add_filewatch)
  1896. return True
  1897. def reparse(self, filename):
  1898. infos = self.bb_cache.parse(filename, self.cooker.collection.get_file_appends(filename))
  1899. for vfn, info_array in infos:
  1900. (fn, cls, mc) = bb.cache.virtualfn2realfn(vfn)
  1901. self.cooker.recipecaches[mc].add_from_recipeinfo(vfn, info_array)