cache.py 35 KB

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