cache.py 32 KB

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