cache.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. #
  4. # BitBake Cache implementation
  5. #
  6. # Caching of bitbake variables before task execution
  7. # Copyright (C) 2006 Richard Purdie
  8. # Copyright (C) 2012 Intel Corporation
  9. # but small sections based on code from bin/bitbake:
  10. # Copyright (C) 2003, 2004 Chris Larson
  11. # Copyright (C) 2003, 2004 Phil Blundell
  12. # Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
  13. # Copyright (C) 2005 Holger Hans Peter Freyther
  14. # Copyright (C) 2005 ROAD GmbH
  15. #
  16. # SPDX-License-Identifier: GPL-2.0-only
  17. #
  18. # This program is free software; you can redistribute it and/or modify
  19. # it under the terms of the GNU General Public License version 2 as
  20. # published by the Free Software Foundation.
  21. #
  22. # This program is distributed in the hope that it will be useful,
  23. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. # GNU General Public License for more details.
  26. #
  27. # You should have received a copy of the GNU General Public License along
  28. # with this program; if not, write to the Free Software Foundation, Inc.,
  29. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  30. import os
  31. import sys
  32. import logging
  33. import pickle
  34. from collections import defaultdict
  35. import bb.utils
  36. logger = logging.getLogger("BitBake.Cache")
  37. __cache_version__ = "152"
  38. def getCacheFile(path, filename, data_hash):
  39. return os.path.join(path, filename + "." + data_hash)
  40. # RecipeInfoCommon defines common data retrieving methods
  41. # from meta data for caches. CoreRecipeInfo as well as other
  42. # Extra RecipeInfo needs to inherit this class
  43. class RecipeInfoCommon(object):
  44. @classmethod
  45. def listvar(cls, var, metadata):
  46. return cls.getvar(var, metadata).split()
  47. @classmethod
  48. def intvar(cls, var, metadata):
  49. return int(cls.getvar(var, metadata) or 0)
  50. @classmethod
  51. def depvar(cls, var, metadata):
  52. return bb.utils.explode_deps(cls.getvar(var, metadata))
  53. @classmethod
  54. def pkgvar(cls, var, packages, metadata):
  55. return dict((pkg, cls.depvar("%s_%s" % (var, pkg), metadata))
  56. for pkg in packages)
  57. @classmethod
  58. def taskvar(cls, var, tasks, metadata):
  59. return dict((task, cls.getvar("%s_task-%s" % (var, task), metadata))
  60. for task in tasks)
  61. @classmethod
  62. def flaglist(cls, flag, varlist, metadata, squash=False):
  63. out_dict = dict((var, metadata.getVarFlag(var, flag))
  64. for var in varlist)
  65. if squash:
  66. return dict((k,v) for (k,v) in out_dict.items() if v)
  67. else:
  68. return out_dict
  69. @classmethod
  70. def getvar(cls, var, metadata, expand = True):
  71. return metadata.getVar(var, expand) or ''
  72. class CoreRecipeInfo(RecipeInfoCommon):
  73. __slots__ = ()
  74. cachefile = "bb_cache.dat"
  75. def __init__(self, filename, metadata):
  76. self.file_depends = metadata.getVar('__depends', False)
  77. self.timestamp = bb.parse.cached_mtime(filename)
  78. self.variants = self.listvar('__VARIANTS', metadata) + ['']
  79. self.appends = self.listvar('__BBAPPEND', metadata)
  80. self.nocache = self.getvar('BB_DONT_CACHE', metadata)
  81. self.skipreason = self.getvar('__SKIPPED', metadata)
  82. if self.skipreason:
  83. self.pn = self.getvar('PN', metadata) or bb.parse.vars_from_file(filename,metadata)[0]
  84. self.skipped = True
  85. self.provides = self.depvar('PROVIDES', metadata)
  86. self.rprovides = self.depvar('RPROVIDES', metadata)
  87. return
  88. self.tasks = metadata.getVar('__BBTASKS', False)
  89. self.pn = self.getvar('PN', metadata)
  90. self.packages = self.listvar('PACKAGES', metadata)
  91. if not self.packages:
  92. self.packages.append(self.pn)
  93. self.basetaskhashes = self.taskvar('BB_BASEHASH', self.tasks, metadata)
  94. self.hashfilename = self.getvar('BB_HASHFILENAME', metadata)
  95. self.task_deps = metadata.getVar('_task_deps', False) or {'tasks': [], 'parents': {}}
  96. self.skipped = False
  97. self.pe = self.getvar('PE', metadata)
  98. self.pv = self.getvar('PV', metadata)
  99. self.pr = self.getvar('PR', metadata)
  100. self.defaultpref = self.intvar('DEFAULT_PREFERENCE', metadata)
  101. self.not_world = self.getvar('EXCLUDE_FROM_WORLD', metadata)
  102. self.stamp = self.getvar('STAMP', metadata)
  103. self.stampclean = self.getvar('STAMPCLEAN', metadata)
  104. self.stamp_extrainfo = self.flaglist('stamp-extra-info', self.tasks, metadata)
  105. self.file_checksums = self.flaglist('file-checksums', self.tasks, metadata, True)
  106. self.packages_dynamic = self.listvar('PACKAGES_DYNAMIC', metadata)
  107. self.depends = self.depvar('DEPENDS', metadata)
  108. self.provides = self.depvar('PROVIDES', metadata)
  109. self.rdepends = self.depvar('RDEPENDS', metadata)
  110. self.rprovides = self.depvar('RPROVIDES', metadata)
  111. self.rrecommends = self.depvar('RRECOMMENDS', metadata)
  112. self.rprovides_pkg = self.pkgvar('RPROVIDES', self.packages, metadata)
  113. self.rdepends_pkg = self.pkgvar('RDEPENDS', self.packages, metadata)
  114. self.rrecommends_pkg = self.pkgvar('RRECOMMENDS', self.packages, metadata)
  115. self.inherits = self.getvar('__inherit_cache', metadata, expand=False)
  116. self.fakerootenv = self.getvar('FAKEROOTENV', metadata)
  117. self.fakerootdirs = self.getvar('FAKEROOTDIRS', metadata)
  118. self.fakerootnoenv = self.getvar('FAKEROOTNOENV', metadata)
  119. self.extradepsfunc = self.getvar('calculate_extra_depends', metadata)
  120. @classmethod
  121. def init_cacheData(cls, cachedata):
  122. # CacheData in Core RecipeInfo Class
  123. cachedata.task_deps = {}
  124. cachedata.pkg_fn = {}
  125. cachedata.pkg_pn = defaultdict(list)
  126. cachedata.pkg_pepvpr = {}
  127. cachedata.pkg_dp = {}
  128. cachedata.stamp = {}
  129. cachedata.stampclean = {}
  130. cachedata.stamp_extrainfo = {}
  131. cachedata.file_checksums = {}
  132. cachedata.fn_provides = {}
  133. cachedata.pn_provides = defaultdict(list)
  134. cachedata.all_depends = []
  135. cachedata.deps = defaultdict(list)
  136. cachedata.packages = defaultdict(list)
  137. cachedata.providers = defaultdict(list)
  138. cachedata.rproviders = defaultdict(list)
  139. cachedata.packages_dynamic = defaultdict(list)
  140. cachedata.rundeps = defaultdict(lambda: defaultdict(list))
  141. cachedata.runrecs = defaultdict(lambda: defaultdict(list))
  142. cachedata.possible_world = []
  143. cachedata.universe_target = []
  144. cachedata.hashfn = {}
  145. cachedata.basetaskhash = {}
  146. cachedata.inherits = {}
  147. cachedata.fakerootenv = {}
  148. cachedata.fakerootnoenv = {}
  149. cachedata.fakerootdirs = {}
  150. cachedata.extradepsfunc = {}
  151. def add_cacheData(self, cachedata, fn):
  152. cachedata.task_deps[fn] = self.task_deps
  153. cachedata.pkg_fn[fn] = self.pn
  154. cachedata.pkg_pn[self.pn].append(fn)
  155. cachedata.pkg_pepvpr[fn] = (self.pe, self.pv, self.pr)
  156. cachedata.pkg_dp[fn] = self.defaultpref
  157. cachedata.stamp[fn] = self.stamp
  158. cachedata.stampclean[fn] = self.stampclean
  159. cachedata.stamp_extrainfo[fn] = self.stamp_extrainfo
  160. cachedata.file_checksums[fn] = self.file_checksums
  161. provides = [self.pn]
  162. for provide in self.provides:
  163. if provide not in provides:
  164. provides.append(provide)
  165. cachedata.fn_provides[fn] = provides
  166. for provide in provides:
  167. cachedata.providers[provide].append(fn)
  168. if provide not in cachedata.pn_provides[self.pn]:
  169. cachedata.pn_provides[self.pn].append(provide)
  170. for dep in self.depends:
  171. if dep not in cachedata.deps[fn]:
  172. cachedata.deps[fn].append(dep)
  173. if dep not in cachedata.all_depends:
  174. cachedata.all_depends.append(dep)
  175. rprovides = self.rprovides
  176. for package in self.packages:
  177. cachedata.packages[package].append(fn)
  178. rprovides += self.rprovides_pkg[package]
  179. for rprovide in rprovides:
  180. if fn not in cachedata.rproviders[rprovide]:
  181. cachedata.rproviders[rprovide].append(fn)
  182. for package in self.packages_dynamic:
  183. cachedata.packages_dynamic[package].append(fn)
  184. # Build hash of runtime depends and recommends
  185. for package in self.packages:
  186. cachedata.rundeps[fn][package] = list(self.rdepends) + self.rdepends_pkg[package]
  187. cachedata.runrecs[fn][package] = list(self.rrecommends) + self.rrecommends_pkg[package]
  188. # Collect files we may need for possible world-dep
  189. # calculations
  190. if self.not_world:
  191. logger.debug(1, "EXCLUDE FROM WORLD: %s", fn)
  192. else:
  193. cachedata.possible_world.append(fn)
  194. # create a collection of all targets for sanity checking
  195. # tasks, such as upstream versions, license, and tools for
  196. # task and image creation.
  197. cachedata.universe_target.append(self.pn)
  198. cachedata.hashfn[fn] = self.hashfilename
  199. for task, taskhash in self.basetaskhashes.items():
  200. identifier = '%s.%s' % (fn, task)
  201. cachedata.basetaskhash[identifier] = taskhash
  202. cachedata.inherits[fn] = self.inherits
  203. cachedata.fakerootenv[fn] = self.fakerootenv
  204. cachedata.fakerootnoenv[fn] = self.fakerootnoenv
  205. cachedata.fakerootdirs[fn] = self.fakerootdirs
  206. cachedata.extradepsfunc[fn] = self.extradepsfunc
  207. def virtualfn2realfn(virtualfn):
  208. """
  209. Convert a virtual file name to a real one + the associated subclass keyword
  210. """
  211. mc = ""
  212. if virtualfn.startswith('multiconfig:'):
  213. elems = virtualfn.split(':')
  214. mc = elems[1]
  215. virtualfn = ":".join(elems[2:])
  216. fn = virtualfn
  217. cls = ""
  218. if virtualfn.startswith('virtual:'):
  219. elems = virtualfn.split(':')
  220. cls = ":".join(elems[1:-1])
  221. fn = elems[-1]
  222. return (fn, cls, mc)
  223. def realfn2virtual(realfn, cls, mc):
  224. """
  225. Convert a real filename + the associated subclass keyword to a virtual filename
  226. """
  227. if cls:
  228. realfn = "virtual:" + cls + ":" + realfn
  229. if mc:
  230. realfn = "multiconfig:" + mc + ":" + realfn
  231. return realfn
  232. def variant2virtual(realfn, variant):
  233. """
  234. Convert a real filename + the associated subclass keyword to a virtual filename
  235. """
  236. if variant == "":
  237. return realfn
  238. if variant.startswith("multiconfig:"):
  239. elems = variant.split(":")
  240. if elems[2]:
  241. return "multiconfig:" + elems[1] + ":virtual:" + ":".join(elems[2:]) + ":" + realfn
  242. return "multiconfig:" + elems[1] + ":" + realfn
  243. return "virtual:" + variant + ":" + realfn
  244. def parse_recipe(bb_data, bbfile, appends, mc=''):
  245. """
  246. Parse a recipe
  247. """
  248. chdir_back = False
  249. bb_data.setVar("__BBMULTICONFIG", mc)
  250. # expand tmpdir to include this topdir
  251. bb_data.setVar('TMPDIR', bb_data.getVar('TMPDIR') or "")
  252. bbfile_loc = os.path.abspath(os.path.dirname(bbfile))
  253. oldpath = os.path.abspath(os.getcwd())
  254. bb.parse.cached_mtime_noerror(bbfile_loc)
  255. # The ConfHandler first looks if there is a TOPDIR and if not
  256. # then it would call getcwd().
  257. # Previously, we chdir()ed to bbfile_loc, called the handler
  258. # and finally chdir()ed back, a couple of thousand times. We now
  259. # just fill in TOPDIR to point to bbfile_loc if there is no TOPDIR yet.
  260. if not bb_data.getVar('TOPDIR', False):
  261. chdir_back = True
  262. bb_data.setVar('TOPDIR', bbfile_loc)
  263. try:
  264. if appends:
  265. bb_data.setVar('__BBAPPEND', " ".join(appends))
  266. bb_data = bb.parse.handle(bbfile, bb_data)
  267. if chdir_back:
  268. os.chdir(oldpath)
  269. return bb_data
  270. except:
  271. if chdir_back:
  272. os.chdir(oldpath)
  273. raise
  274. class NoCache(object):
  275. def __init__(self, databuilder):
  276. self.databuilder = databuilder
  277. self.data = databuilder.data
  278. def loadDataFull(self, virtualfn, appends):
  279. """
  280. Return a complete set of data for fn.
  281. To do this, we need to parse the file.
  282. """
  283. logger.debug(1, "Parsing %s (full)" % virtualfn)
  284. (fn, virtual, mc) = virtualfn2realfn(virtualfn)
  285. bb_data = self.load_bbfile(virtualfn, appends, virtonly=True)
  286. return bb_data[virtual]
  287. def load_bbfile(self, bbfile, appends, virtonly = False):
  288. """
  289. Load and parse one .bb build file
  290. Return the data and whether parsing resulted in the file being skipped
  291. """
  292. if virtonly:
  293. (bbfile, virtual, mc) = virtualfn2realfn(bbfile)
  294. bb_data = self.databuilder.mcdata[mc].createCopy()
  295. bb_data.setVar("__ONLYFINALISE", virtual or "default")
  296. datastores = parse_recipe(bb_data, bbfile, appends, mc)
  297. return datastores
  298. bb_data = self.data.createCopy()
  299. datastores = parse_recipe(bb_data, bbfile, appends)
  300. for mc in self.databuilder.mcdata:
  301. if not mc:
  302. continue
  303. bb_data = self.databuilder.mcdata[mc].createCopy()
  304. newstores = parse_recipe(bb_data, bbfile, appends, mc)
  305. for ns in newstores:
  306. datastores["multiconfig:%s:%s" % (mc, ns)] = newstores[ns]
  307. return datastores
  308. class Cache(NoCache):
  309. """
  310. BitBake Cache implementation
  311. """
  312. def __init__(self, databuilder, data_hash, caches_array):
  313. super().__init__(databuilder)
  314. data = databuilder.data
  315. # Pass caches_array information into Cache Constructor
  316. # It will be used later for deciding whether we
  317. # need extra cache file dump/load support
  318. self.caches_array = caches_array
  319. self.cachedir = data.getVar("CACHE")
  320. self.clean = set()
  321. self.checked = set()
  322. self.depends_cache = {}
  323. self.data_fn = None
  324. self.cacheclean = True
  325. self.data_hash = data_hash
  326. if self.cachedir in [None, '']:
  327. self.has_cache = False
  328. logger.info("Not using a cache. "
  329. "Set CACHE = <directory> to enable.")
  330. return
  331. self.has_cache = True
  332. self.cachefile = getCacheFile(self.cachedir, "bb_cache.dat", self.data_hash)
  333. logger.debug(1, "Cache dir: %s", self.cachedir)
  334. bb.utils.mkdirhier(self.cachedir)
  335. cache_ok = True
  336. if self.caches_array:
  337. for cache_class in self.caches_array:
  338. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  339. cache_ok = cache_ok and os.path.exists(cachefile)
  340. cache_class.init_cacheData(self)
  341. if cache_ok:
  342. self.load_cachefile()
  343. elif os.path.isfile(self.cachefile):
  344. logger.info("Out of date cache found, rebuilding...")
  345. else:
  346. logger.debug(1, "Cache file %s not found, building..." % self.cachefile)
  347. def load_cachefile(self):
  348. cachesize = 0
  349. previous_progress = 0
  350. previous_percent = 0
  351. # Calculate the correct cachesize of all those cache files
  352. for cache_class in self.caches_array:
  353. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  354. with open(cachefile, "rb") as cachefile:
  355. cachesize += os.fstat(cachefile.fileno()).st_size
  356. bb.event.fire(bb.event.CacheLoadStarted(cachesize), self.data)
  357. for cache_class in self.caches_array:
  358. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  359. logger.debug(1, 'Loading cache file: %s' % cachefile)
  360. with open(cachefile, "rb") as cachefile:
  361. pickled = pickle.Unpickler(cachefile)
  362. # Check cache version information
  363. try:
  364. cache_ver = pickled.load()
  365. bitbake_ver = pickled.load()
  366. except Exception:
  367. logger.info('Invalid cache, rebuilding...')
  368. return
  369. if cache_ver != __cache_version__:
  370. logger.info('Cache version mismatch, rebuilding...')
  371. return
  372. elif bitbake_ver != bb.__version__:
  373. logger.info('Bitbake version mismatch, rebuilding...')
  374. return
  375. # Load the rest of the cache file
  376. current_progress = 0
  377. while cachefile:
  378. try:
  379. key = pickled.load()
  380. value = pickled.load()
  381. except Exception:
  382. break
  383. if not isinstance(key, str):
  384. bb.warn("%s from extras cache is not a string?" % key)
  385. break
  386. if not isinstance(value, RecipeInfoCommon):
  387. bb.warn("%s from extras cache is not a RecipeInfoCommon class?" % value)
  388. break
  389. if key in self.depends_cache:
  390. self.depends_cache[key].append(value)
  391. else:
  392. self.depends_cache[key] = [value]
  393. # only fire events on even percentage boundaries
  394. current_progress = cachefile.tell() + previous_progress
  395. if current_progress > cachesize:
  396. # we might have calculated incorrect total size because a file
  397. # might've been written out just after we checked its size
  398. cachesize = current_progress
  399. current_percent = 100 * current_progress / cachesize
  400. if current_percent > previous_percent:
  401. previous_percent = current_percent
  402. bb.event.fire(bb.event.CacheLoadProgress(current_progress, cachesize),
  403. self.data)
  404. previous_progress += current_progress
  405. # Note: depends cache number is corresponding to the parsing file numbers.
  406. # The same file has several caches, still regarded as one item in the cache
  407. bb.event.fire(bb.event.CacheLoadCompleted(cachesize,
  408. len(self.depends_cache)),
  409. self.data)
  410. def parse(self, filename, appends):
  411. """Parse the specified filename, returning the recipe information"""
  412. logger.debug(1, "Parsing %s", filename)
  413. infos = []
  414. datastores = self.load_bbfile(filename, appends)
  415. depends = []
  416. variants = []
  417. # Process the "real" fn last so we can store variants list
  418. for variant, data in sorted(datastores.items(),
  419. key=lambda i: i[0],
  420. reverse=True):
  421. virtualfn = variant2virtual(filename, variant)
  422. variants.append(variant)
  423. depends = depends + (data.getVar("__depends", False) or [])
  424. if depends and not variant:
  425. data.setVar("__depends", depends)
  426. if virtualfn == filename:
  427. data.setVar("__VARIANTS", " ".join(variants))
  428. info_array = []
  429. for cache_class in self.caches_array:
  430. info = cache_class(filename, data)
  431. info_array.append(info)
  432. infos.append((virtualfn, info_array))
  433. return infos
  434. def load(self, filename, appends):
  435. """Obtain the recipe information for the specified filename,
  436. using cached values if available, otherwise parsing.
  437. Note that if it does parse to obtain the info, it will not
  438. automatically add the information to the cache or to your
  439. CacheData. Use the add or add_info method to do so after
  440. running this, or use loadData instead."""
  441. cached = self.cacheValid(filename, appends)
  442. if cached:
  443. infos = []
  444. # info_array item is a list of [CoreRecipeInfo, XXXRecipeInfo]
  445. info_array = self.depends_cache[filename]
  446. for variant in info_array[0].variants:
  447. virtualfn = variant2virtual(filename, variant)
  448. infos.append((virtualfn, self.depends_cache[virtualfn]))
  449. else:
  450. return self.parse(filename, appends, configdata, self.caches_array)
  451. return cached, infos
  452. def loadData(self, fn, appends, cacheData):
  453. """Load the recipe info for the specified filename,
  454. parsing and adding to the cache if necessary, and adding
  455. the recipe information to the supplied CacheData instance."""
  456. skipped, virtuals = 0, 0
  457. cached, infos = self.load(fn, appends)
  458. for virtualfn, info_array in infos:
  459. if info_array[0].skipped:
  460. logger.debug(1, "Skipping %s: %s", virtualfn, info_array[0].skipreason)
  461. skipped += 1
  462. else:
  463. self.add_info(virtualfn, info_array, cacheData, not cached)
  464. virtuals += 1
  465. return cached, skipped, virtuals
  466. def cacheValid(self, fn, appends):
  467. """
  468. Is the cache valid for fn?
  469. Fast version, no timestamps checked.
  470. """
  471. if fn not in self.checked:
  472. self.cacheValidUpdate(fn, appends)
  473. # Is cache enabled?
  474. if not self.has_cache:
  475. return False
  476. if fn in self.clean:
  477. return True
  478. return False
  479. def cacheValidUpdate(self, fn, appends):
  480. """
  481. Is the cache valid for fn?
  482. Make thorough (slower) checks including timestamps.
  483. """
  484. # Is cache enabled?
  485. if not self.has_cache:
  486. return False
  487. self.checked.add(fn)
  488. # File isn't in depends_cache
  489. if not fn in self.depends_cache:
  490. logger.debug(2, "Cache: %s is not cached", fn)
  491. return False
  492. mtime = bb.parse.cached_mtime_noerror(fn)
  493. # Check file still exists
  494. if mtime == 0:
  495. logger.debug(2, "Cache: %s no longer exists", fn)
  496. self.remove(fn)
  497. return False
  498. info_array = self.depends_cache[fn]
  499. # Check the file's timestamp
  500. if mtime != info_array[0].timestamp:
  501. logger.debug(2, "Cache: %s changed", fn)
  502. self.remove(fn)
  503. return False
  504. # Check dependencies are still valid
  505. depends = info_array[0].file_depends
  506. if depends:
  507. for f, old_mtime in depends:
  508. fmtime = bb.parse.cached_mtime_noerror(f)
  509. # Check if file still exists
  510. if old_mtime != 0 and fmtime == 0:
  511. logger.debug(2, "Cache: %s's dependency %s was removed",
  512. fn, f)
  513. self.remove(fn)
  514. return False
  515. if (fmtime != old_mtime):
  516. logger.debug(2, "Cache: %s's dependency %s changed",
  517. fn, f)
  518. self.remove(fn)
  519. return False
  520. if hasattr(info_array[0], 'file_checksums'):
  521. for _, fl in info_array[0].file_checksums.items():
  522. fl = fl.strip()
  523. while fl:
  524. # A .split() would be simpler but means spaces or colons in filenames would break
  525. a = fl.find(":True")
  526. b = fl.find(":False")
  527. if ((a < 0) and b) or ((b > 0) and (b < a)):
  528. f = fl[:b+6]
  529. fl = fl[b+7:]
  530. elif ((b < 0) and a) or ((a > 0) and (a < b)):
  531. f = fl[:a+5]
  532. fl = fl[a+6:]
  533. else:
  534. break
  535. fl = fl.strip()
  536. if "*" in f:
  537. continue
  538. f, exist = f.split(":")
  539. if (exist == "True" and not os.path.exists(f)) or (exist == "False" and os.path.exists(f)):
  540. logger.debug(2, "Cache: %s's file checksum list file %s changed",
  541. fn, f)
  542. self.remove(fn)
  543. return False
  544. if appends != info_array[0].appends:
  545. logger.debug(2, "Cache: appends for %s changed", fn)
  546. logger.debug(2, "%s to %s" % (str(appends), str(info_array[0].appends)))
  547. self.remove(fn)
  548. return False
  549. invalid = False
  550. for cls in info_array[0].variants:
  551. virtualfn = variant2virtual(fn, cls)
  552. self.clean.add(virtualfn)
  553. if virtualfn not in self.depends_cache:
  554. logger.debug(2, "Cache: %s is not cached", virtualfn)
  555. invalid = True
  556. elif len(self.depends_cache[virtualfn]) != len(self.caches_array):
  557. logger.debug(2, "Cache: Extra caches missing for %s?" % virtualfn)
  558. invalid = True
  559. # If any one of the variants is not present, mark as invalid for all
  560. if invalid:
  561. for cls in info_array[0].variants:
  562. virtualfn = variant2virtual(fn, cls)
  563. if virtualfn in self.clean:
  564. logger.debug(2, "Cache: Removing %s from cache", virtualfn)
  565. self.clean.remove(virtualfn)
  566. if fn in self.clean:
  567. logger.debug(2, "Cache: Marking %s as not clean", fn)
  568. self.clean.remove(fn)
  569. return False
  570. self.clean.add(fn)
  571. return True
  572. def remove(self, fn):
  573. """
  574. Remove a fn from the cache
  575. Called from the parser in error cases
  576. """
  577. if fn in self.depends_cache:
  578. logger.debug(1, "Removing %s from cache", fn)
  579. del self.depends_cache[fn]
  580. if fn in self.clean:
  581. logger.debug(1, "Marking %s as unclean", fn)
  582. self.clean.remove(fn)
  583. def sync(self):
  584. """
  585. Save the cache
  586. Called from the parser when complete (or exiting)
  587. """
  588. if not self.has_cache:
  589. return
  590. if self.cacheclean:
  591. logger.debug(2, "Cache is clean, not saving.")
  592. return
  593. for cache_class in self.caches_array:
  594. cache_class_name = cache_class.__name__
  595. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  596. with open(cachefile, "wb") as f:
  597. p = pickle.Pickler(f, pickle.HIGHEST_PROTOCOL)
  598. p.dump(__cache_version__)
  599. p.dump(bb.__version__)
  600. for key, info_array in self.depends_cache.items():
  601. for info in info_array:
  602. if isinstance(info, RecipeInfoCommon) and info.__class__.__name__ == cache_class_name:
  603. p.dump(key)
  604. p.dump(info)
  605. del self.depends_cache
  606. @staticmethod
  607. def mtime(cachefile):
  608. return bb.parse.cached_mtime_noerror(cachefile)
  609. def add_info(self, filename, info_array, cacheData, parsed=None, watcher=None):
  610. if isinstance(info_array[0], CoreRecipeInfo) and (not info_array[0].skipped):
  611. cacheData.add_from_recipeinfo(filename, info_array)
  612. if watcher:
  613. watcher(info_array[0].file_depends)
  614. if not self.has_cache:
  615. return
  616. if (info_array[0].skipped or 'SRCREVINACTION' not in info_array[0].pv) and not info_array[0].nocache:
  617. if parsed:
  618. self.cacheclean = False
  619. self.depends_cache[filename] = info_array
  620. def add(self, file_name, data, cacheData, parsed=None):
  621. """
  622. Save data we need into the cache
  623. """
  624. realfn = virtualfn2realfn(file_name)[0]
  625. info_array = []
  626. for cache_class in self.caches_array:
  627. info_array.append(cache_class(realfn, data))
  628. self.add_info(file_name, info_array, cacheData, parsed)
  629. def init(cooker):
  630. """
  631. The Objective: Cache the minimum amount of data possible yet get to the
  632. stage of building packages (i.e. tryBuild) without reparsing any .bb files.
  633. To do this, we intercept getVar calls and only cache the variables we see
  634. being accessed. We rely on the cache getVar calls being made for all
  635. variables bitbake might need to use to reach this stage. For each cached
  636. file we need to track:
  637. * Its mtime
  638. * The mtimes of all its dependencies
  639. * Whether it caused a parse.SkipRecipe exception
  640. Files causing parsing errors are evicted from the cache.
  641. """
  642. return Cache(cooker.configuration.data, cooker.configuration.data_hash)
  643. class CacheData(object):
  644. """
  645. The data structures we compile from the cached data
  646. """
  647. def __init__(self, caches_array):
  648. self.caches_array = caches_array
  649. for cache_class in self.caches_array:
  650. if not issubclass(cache_class, RecipeInfoCommon):
  651. bb.error("Extra cache data class %s should subclass RecipeInfoCommon class" % cache_class)
  652. cache_class.init_cacheData(self)
  653. # Direct cache variables
  654. self.task_queues = {}
  655. self.preferred = {}
  656. self.tasks = {}
  657. # Indirect Cache variables (set elsewhere)
  658. self.ignored_dependencies = []
  659. self.world_target = set()
  660. self.bbfile_priority = {}
  661. def add_from_recipeinfo(self, fn, info_array):
  662. for info in info_array:
  663. info.add_cacheData(self, fn)
  664. class MultiProcessCache(object):
  665. """
  666. BitBake multi-process cache implementation
  667. Used by the codeparser & file checksum caches
  668. """
  669. def __init__(self):
  670. self.cachefile = None
  671. self.cachedata = self.create_cachedata()
  672. self.cachedata_extras = self.create_cachedata()
  673. def init_cache(self, d, cache_file_name=None):
  674. cachedir = (d.getVar("PERSISTENT_DIR") or
  675. d.getVar("CACHE"))
  676. if cachedir in [None, '']:
  677. return
  678. bb.utils.mkdirhier(cachedir)
  679. self.cachefile = os.path.join(cachedir,
  680. cache_file_name or self.__class__.cache_file_name)
  681. logger.debug(1, "Using cache in '%s'", self.cachefile)
  682. glf = bb.utils.lockfile(self.cachefile + ".lock")
  683. try:
  684. with open(self.cachefile, "rb") as f:
  685. p = pickle.Unpickler(f)
  686. data, version = p.load()
  687. except:
  688. bb.utils.unlockfile(glf)
  689. return
  690. bb.utils.unlockfile(glf)
  691. if version != self.__class__.CACHE_VERSION:
  692. return
  693. self.cachedata = data
  694. def create_cachedata(self):
  695. data = [{}]
  696. return data
  697. def save_extras(self):
  698. if not self.cachefile:
  699. return
  700. glf = bb.utils.lockfile(self.cachefile + ".lock", shared=True)
  701. i = os.getpid()
  702. lf = None
  703. while not lf:
  704. lf = bb.utils.lockfile(self.cachefile + ".lock." + str(i), retry=False)
  705. if not lf or os.path.exists(self.cachefile + "-" + str(i)):
  706. if lf:
  707. bb.utils.unlockfile(lf)
  708. lf = None
  709. i = i + 1
  710. continue
  711. with open(self.cachefile + "-" + str(i), "wb") as f:
  712. p = pickle.Pickler(f, -1)
  713. p.dump([self.cachedata_extras, self.__class__.CACHE_VERSION])
  714. bb.utils.unlockfile(lf)
  715. bb.utils.unlockfile(glf)
  716. def merge_data(self, source, dest):
  717. for j in range(0,len(dest)):
  718. for h in source[j]:
  719. if h not in dest[j]:
  720. dest[j][h] = source[j][h]
  721. def save_merge(self):
  722. if not self.cachefile:
  723. return
  724. glf = bb.utils.lockfile(self.cachefile + ".lock")
  725. data = self.cachedata
  726. for f in [y for y in os.listdir(os.path.dirname(self.cachefile)) if y.startswith(os.path.basename(self.cachefile) + '-')]:
  727. f = os.path.join(os.path.dirname(self.cachefile), f)
  728. try:
  729. with open(f, "rb") as fd:
  730. p = pickle.Unpickler(fd)
  731. extradata, version = p.load()
  732. except (IOError, EOFError):
  733. os.unlink(f)
  734. continue
  735. if version != self.__class__.CACHE_VERSION:
  736. os.unlink(f)
  737. continue
  738. self.merge_data(extradata, data)
  739. os.unlink(f)
  740. with open(self.cachefile, "wb") as f:
  741. p = pickle.Pickler(f, -1)
  742. p.dump([data, self.__class__.CACHE_VERSION])
  743. bb.utils.unlockfile(glf)