cache.py 31 KB

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