cooker.py 89 KB

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