cache.py 33 KB

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