cache.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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. mc = ""
  210. if virtualfn.startswith('multiconfig:'):
  211. elems = virtualfn.split(':')
  212. mc = elems[1]
  213. virtualfn = ":".join(elems[2:])
  214. fn = virtualfn
  215. cls = ""
  216. if virtualfn.startswith('virtual:'):
  217. elems = virtualfn.split(':')
  218. cls = ":".join(elems[1:-1])
  219. fn = elems[-1]
  220. return (fn, cls, mc)
  221. def realfn2virtual(realfn, cls, mc):
  222. """
  223. Convert a real filename + the associated subclass keyword to a virtual filename
  224. """
  225. if cls:
  226. realfn = "virtual:" + cls + ":" + realfn
  227. if mc:
  228. realfn = "multiconfig:" + mc + ":" + realfn
  229. return realfn
  230. def variant2virtual(realfn, variant):
  231. """
  232. Convert a real filename + the associated subclass keyword to a virtual filename
  233. """
  234. if variant == "":
  235. return realfn
  236. if variant.startswith("multiconfig:"):
  237. elems = variant.split(":")
  238. if elems[2]:
  239. return "multiconfig:" + elems[1] + ":virtual:" + ":".join(elems[2:]) + ":" + realfn
  240. return "multiconfig:" + elems[1] + ":" + realfn
  241. return "virtual:" + variant + ":" + realfn
  242. class NoCache(object):
  243. def __init__(self, databuilder):
  244. self.databuilder = databuilder
  245. self.data = databuilder.data
  246. def loadDataFull(self, virtualfn, appends):
  247. """
  248. Return a complete set of data for fn.
  249. To do this, we need to parse the file.
  250. """
  251. logger.debug(1, "Parsing %s (full)" % virtualfn)
  252. (fn, virtual, mc) = virtualfn2realfn(virtualfn)
  253. bb_data = self.load_bbfile(virtualfn, appends, virtonly=True)
  254. return bb_data[virtual]
  255. def load_bbfile(self, bbfile, appends, virtonly = False):
  256. """
  257. Load and parse one .bb build file
  258. Return the data and whether parsing resulted in the file being skipped
  259. """
  260. if virtonly:
  261. (bbfile, virtual, mc) = virtualfn2realfn(bbfile)
  262. bb_data = self.databuilder.mcdata[mc].createCopy()
  263. bb_data.setVar("__BBMULTICONFIG", mc)
  264. bb_data.setVar("__ONLYFINALISE", virtual or "default")
  265. datastores = self._load_bbfile(bb_data, bbfile, appends)
  266. return datastores
  267. bb_data = self.data.createCopy()
  268. datastores = self._load_bbfile(bb_data, bbfile, appends)
  269. for mc in self.databuilder.mcdata:
  270. if not mc:
  271. continue
  272. bb_data = self.databuilder.mcdata[mc].createCopy()
  273. bb_data.setVar("__BBMULTICONFIG", mc)
  274. newstores = self._load_bbfile(bb_data, bbfile, appends)
  275. for ns in newstores:
  276. datastores["multiconfig:%s:%s" % (mc, ns)] = newstores[ns]
  277. return datastores
  278. def _load_bbfile(self, bb_data, bbfile, appends):
  279. chdir_back = False
  280. # expand tmpdir to include this topdir
  281. bb_data.setVar('TMPDIR', bb_data.getVar('TMPDIR', True) or "")
  282. bbfile_loc = os.path.abspath(os.path.dirname(bbfile))
  283. oldpath = os.path.abspath(os.getcwd())
  284. bb.parse.cached_mtime_noerror(bbfile_loc)
  285. # The ConfHandler first looks if there is a TOPDIR and if not
  286. # then it would call getcwd().
  287. # Previously, we chdir()ed to bbfile_loc, called the handler
  288. # and finally chdir()ed back, a couple of thousand times. We now
  289. # just fill in TOPDIR to point to bbfile_loc if there is no TOPDIR yet.
  290. if not bb_data.getVar('TOPDIR', False):
  291. chdir_back = True
  292. bb_data.setVar('TOPDIR', bbfile_loc)
  293. try:
  294. if appends:
  295. bb_data.setVar('__BBAPPEND', " ".join(appends))
  296. bb_data = bb.parse.handle(bbfile, bb_data)
  297. if chdir_back:
  298. os.chdir(oldpath)
  299. return bb_data
  300. except:
  301. if chdir_back:
  302. os.chdir(oldpath)
  303. raise
  304. class Cache(NoCache):
  305. """
  306. BitBake Cache implementation
  307. """
  308. def __init__(self, databuilder, data_hash, caches_array):
  309. super().__init__(databuilder)
  310. data = databuilder.data
  311. # Pass caches_array information into Cache Constructor
  312. # It will be used later for deciding whether we
  313. # need extra cache file dump/load support
  314. self.caches_array = caches_array
  315. self.cachedir = data.getVar("CACHE", True)
  316. self.clean = set()
  317. self.checked = set()
  318. self.depends_cache = {}
  319. self.data_fn = None
  320. self.cacheclean = True
  321. self.data_hash = data_hash
  322. if self.cachedir in [None, '']:
  323. self.has_cache = False
  324. logger.info("Not using a cache. "
  325. "Set CACHE = <directory> to enable.")
  326. return
  327. self.has_cache = True
  328. self.cachefile = getCacheFile(self.cachedir, "bb_cache.dat", self.data_hash)
  329. logger.debug(1, "Using cache in '%s'", self.cachedir)
  330. bb.utils.mkdirhier(self.cachedir)
  331. cache_ok = True
  332. if self.caches_array:
  333. for cache_class in self.caches_array:
  334. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  335. cache_ok = cache_ok and os.path.exists(cachefile)
  336. cache_class.init_cacheData(self)
  337. if cache_ok:
  338. self.load_cachefile()
  339. elif os.path.isfile(self.cachefile):
  340. logger.info("Out of date cache found, rebuilding...")
  341. def load_cachefile(self):
  342. cachesize = 0
  343. previous_progress = 0
  344. previous_percent = 0
  345. # Calculate the correct cachesize of all those cache files
  346. for cache_class in self.caches_array:
  347. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  348. with open(cachefile, "rb") as cachefile:
  349. cachesize += os.fstat(cachefile.fileno()).st_size
  350. bb.event.fire(bb.event.CacheLoadStarted(cachesize), self.data)
  351. for cache_class in self.caches_array:
  352. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  353. with open(cachefile, "rb") as cachefile:
  354. pickled = pickle.Unpickler(cachefile)
  355. # Check cache version information
  356. try:
  357. cache_ver = pickled.load()
  358. bitbake_ver = pickled.load()
  359. except Exception:
  360. logger.info('Invalid cache, rebuilding...')
  361. return
  362. if cache_ver != __cache_version__:
  363. logger.info('Cache version mismatch, rebuilding...')
  364. return
  365. elif bitbake_ver != bb.__version__:
  366. logger.info('Bitbake version mismatch, rebuilding...')
  367. return
  368. # Load the rest of the cache file
  369. current_progress = 0
  370. while cachefile:
  371. try:
  372. key = pickled.load()
  373. value = pickled.load()
  374. except Exception:
  375. break
  376. if not isinstance(key, str):
  377. bb.warn("%s from extras cache is not a string?" % key)
  378. break
  379. if not isinstance(value, RecipeInfoCommon):
  380. bb.warn("%s from extras cache is not a RecipeInfoCommon class?" % value)
  381. break
  382. if key in self.depends_cache:
  383. self.depends_cache[key].append(value)
  384. else:
  385. self.depends_cache[key] = [value]
  386. # only fire events on even percentage boundaries
  387. current_progress = cachefile.tell() + previous_progress
  388. current_percent = 100 * current_progress / cachesize
  389. if current_percent > previous_percent:
  390. previous_percent = current_percent
  391. bb.event.fire(bb.event.CacheLoadProgress(current_progress, cachesize),
  392. self.data)
  393. previous_progress += current_progress
  394. # Note: depends cache number is corresponding to the parsing file numbers.
  395. # The same file has several caches, still regarded as one item in the cache
  396. bb.event.fire(bb.event.CacheLoadCompleted(cachesize,
  397. len(self.depends_cache)),
  398. self.data)
  399. def parse(self, filename, appends):
  400. """Parse the specified filename, returning the recipe information"""
  401. logger.debug(1, "Parsing %s", filename)
  402. infos = []
  403. datastores = self.load_bbfile(filename, appends)
  404. depends = []
  405. variants = []
  406. # Process the "real" fn last so we can store variants list
  407. for variant, data in sorted(datastores.items(),
  408. key=lambda i: i[0],
  409. reverse=True):
  410. virtualfn = variant2virtual(filename, variant)
  411. variants.append(variant)
  412. depends = depends + (data.getVar("__depends", False) or [])
  413. if depends and not variant:
  414. data.setVar("__depends", depends)
  415. if virtualfn == filename:
  416. data.setVar("__VARIANTS", " ".join(variants))
  417. info_array = []
  418. for cache_class in self.caches_array:
  419. info = cache_class(filename, data)
  420. info_array.append(info)
  421. infos.append((virtualfn, info_array))
  422. return infos
  423. def load(self, filename, appends):
  424. """Obtain the recipe information for the specified filename,
  425. using cached values if available, otherwise parsing.
  426. Note that if it does parse to obtain the info, it will not
  427. automatically add the information to the cache or to your
  428. CacheData. Use the add or add_info method to do so after
  429. running this, or use loadData instead."""
  430. cached = self.cacheValid(filename, appends)
  431. if cached:
  432. infos = []
  433. # info_array item is a list of [CoreRecipeInfo, XXXRecipeInfo]
  434. info_array = self.depends_cache[filename]
  435. for variant in info_array[0].variants:
  436. virtualfn = variant2virtual(filename, variant)
  437. infos.append((virtualfn, self.depends_cache[virtualfn]))
  438. else:
  439. return self.parse(filename, appends, configdata, self.caches_array)
  440. return cached, infos
  441. def loadData(self, fn, appends, cacheData):
  442. """Load the recipe info for the specified filename,
  443. parsing and adding to the cache if necessary, and adding
  444. the recipe information to the supplied CacheData instance."""
  445. skipped, virtuals = 0, 0
  446. cached, infos = self.load(fn, appends)
  447. for virtualfn, info_array in infos:
  448. if info_array[0].skipped:
  449. logger.debug(1, "Skipping %s: %s", virtualfn, info_array[0].skipreason)
  450. skipped += 1
  451. else:
  452. self.add_info(virtualfn, info_array, cacheData, not cached)
  453. virtuals += 1
  454. return cached, skipped, virtuals
  455. def cacheValid(self, fn, appends):
  456. """
  457. Is the cache valid for fn?
  458. Fast version, no timestamps checked.
  459. """
  460. if fn not in self.checked:
  461. self.cacheValidUpdate(fn, appends)
  462. # Is cache enabled?
  463. if not self.has_cache:
  464. return False
  465. if fn in self.clean:
  466. return True
  467. return False
  468. def cacheValidUpdate(self, fn, appends):
  469. """
  470. Is the cache valid for fn?
  471. Make thorough (slower) checks including timestamps.
  472. """
  473. # Is cache enabled?
  474. if not self.has_cache:
  475. return False
  476. self.checked.add(fn)
  477. # File isn't in depends_cache
  478. if not fn in self.depends_cache:
  479. logger.debug(2, "Cache: %s is not cached", fn)
  480. return False
  481. mtime = bb.parse.cached_mtime_noerror(fn)
  482. # Check file still exists
  483. if mtime == 0:
  484. logger.debug(2, "Cache: %s no longer exists", fn)
  485. self.remove(fn)
  486. return False
  487. info_array = self.depends_cache[fn]
  488. # Check the file's timestamp
  489. if mtime != info_array[0].timestamp:
  490. logger.debug(2, "Cache: %s changed", fn)
  491. self.remove(fn)
  492. return False
  493. # Check dependencies are still valid
  494. depends = info_array[0].file_depends
  495. if depends:
  496. for f, old_mtime in depends:
  497. fmtime = bb.parse.cached_mtime_noerror(f)
  498. # Check if file still exists
  499. if old_mtime != 0 and fmtime == 0:
  500. logger.debug(2, "Cache: %s's dependency %s was removed",
  501. fn, f)
  502. self.remove(fn)
  503. return False
  504. if (fmtime != old_mtime):
  505. logger.debug(2, "Cache: %s's dependency %s changed",
  506. fn, f)
  507. self.remove(fn)
  508. return False
  509. if hasattr(info_array[0], 'file_checksums'):
  510. for _, fl in info_array[0].file_checksums.items():
  511. fl = fl.strip()
  512. while fl:
  513. # A .split() would be simpler but means spaces or colons in filenames would break
  514. a = fl.find(":True")
  515. b = fl.find(":False")
  516. if ((a < 0) and b) or ((b > 0) and (b < a)):
  517. f = fl[:b+6]
  518. fl = fl[b+7:]
  519. elif ((b < 0) and a) or ((a > 0) and (a < b)):
  520. f = fl[:a+5]
  521. fl = fl[a+6:]
  522. else:
  523. break
  524. fl = fl.strip()
  525. if "*" in f:
  526. continue
  527. f, exist = f.split(":")
  528. if (exist == "True" and not os.path.exists(f)) or (exist == "False" and os.path.exists(f)):
  529. logger.debug(2, "Cache: %s's file checksum list file %s changed",
  530. fn, f)
  531. self.remove(fn)
  532. return False
  533. if appends != info_array[0].appends:
  534. logger.debug(2, "Cache: appends for %s changed", fn)
  535. logger.debug(2, "%s to %s" % (str(appends), str(info_array[0].appends)))
  536. self.remove(fn)
  537. return False
  538. invalid = False
  539. for cls in info_array[0].variants:
  540. virtualfn = variant2virtual(fn, cls)
  541. self.clean.add(virtualfn)
  542. if virtualfn not in self.depends_cache:
  543. logger.debug(2, "Cache: %s is not cached", virtualfn)
  544. invalid = True
  545. elif len(self.depends_cache[virtualfn]) != len(self.caches_array):
  546. logger.debug(2, "Cache: Extra caches missing for %s?" % virtualfn)
  547. invalid = True
  548. # If any one of the variants is not present, mark as invalid for all
  549. if invalid:
  550. for cls in info_array[0].variants:
  551. virtualfn = variant2virtual(fn, cls)
  552. if virtualfn in self.clean:
  553. logger.debug(2, "Cache: Removing %s from cache", virtualfn)
  554. self.clean.remove(virtualfn)
  555. if fn in self.clean:
  556. logger.debug(2, "Cache: Marking %s as not clean", fn)
  557. self.clean.remove(fn)
  558. return False
  559. self.clean.add(fn)
  560. return True
  561. def remove(self, fn):
  562. """
  563. Remove a fn from the cache
  564. Called from the parser in error cases
  565. """
  566. if fn in self.depends_cache:
  567. logger.debug(1, "Removing %s from cache", fn)
  568. del self.depends_cache[fn]
  569. if fn in self.clean:
  570. logger.debug(1, "Marking %s as unclean", fn)
  571. self.clean.remove(fn)
  572. def sync(self):
  573. """
  574. Save the cache
  575. Called from the parser when complete (or exiting)
  576. """
  577. if not self.has_cache:
  578. return
  579. if self.cacheclean:
  580. logger.debug(2, "Cache is clean, not saving.")
  581. return
  582. for cache_class in self.caches_array:
  583. cache_class_name = cache_class.__name__
  584. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  585. with open(cachefile, "wb") as f:
  586. p = pickle.Pickler(f, pickle.HIGHEST_PROTOCOL)
  587. p.dump(__cache_version__)
  588. p.dump(bb.__version__)
  589. for key, info_array in self.depends_cache.items():
  590. for info in info_array:
  591. if isinstance(info, RecipeInfoCommon) and info.__class__.__name__ == cache_class_name:
  592. p.dump(key)
  593. p.dump(info)
  594. del self.depends_cache
  595. @staticmethod
  596. def mtime(cachefile):
  597. return bb.parse.cached_mtime_noerror(cachefile)
  598. def add_info(self, filename, info_array, cacheData, parsed=None, watcher=None):
  599. if isinstance(info_array[0], CoreRecipeInfo) and (not info_array[0].skipped):
  600. cacheData.add_from_recipeinfo(filename, info_array)
  601. if watcher:
  602. watcher(info_array[0].file_depends)
  603. if not self.has_cache:
  604. return
  605. if (info_array[0].skipped or 'SRCREVINACTION' not in info_array[0].pv) and not info_array[0].nocache:
  606. if parsed:
  607. self.cacheclean = False
  608. self.depends_cache[filename] = info_array
  609. def add(self, file_name, data, cacheData, parsed=None):
  610. """
  611. Save data we need into the cache
  612. """
  613. realfn = virtualfn2realfn(file_name)[0]
  614. info_array = []
  615. for cache_class in self.caches_array:
  616. info_array.append(cache_class(realfn, data))
  617. self.add_info(file_name, info_array, cacheData, parsed)
  618. def init(cooker):
  619. """
  620. The Objective: Cache the minimum amount of data possible yet get to the
  621. stage of building packages (i.e. tryBuild) without reparsing any .bb files.
  622. To do this, we intercept getVar calls and only cache the variables we see
  623. being accessed. We rely on the cache getVar calls being made for all
  624. variables bitbake might need to use to reach this stage. For each cached
  625. file we need to track:
  626. * Its mtime
  627. * The mtimes of all its dependencies
  628. * Whether it caused a parse.SkipRecipe exception
  629. Files causing parsing errors are evicted from the cache.
  630. """
  631. return Cache(cooker.configuration.data, cooker.configuration.data_hash)
  632. class CacheData(object):
  633. """
  634. The data structures we compile from the cached data
  635. """
  636. def __init__(self, caches_array):
  637. self.caches_array = caches_array
  638. for cache_class in self.caches_array:
  639. if not issubclass(cache_class, RecipeInfoCommon):
  640. bb.error("Extra cache data class %s should subclass RecipeInfoCommon class" % cache_class)
  641. cache_class.init_cacheData(self)
  642. # Direct cache variables
  643. self.task_queues = {}
  644. self.preferred = {}
  645. self.tasks = {}
  646. # Indirect Cache variables (set elsewhere)
  647. self.ignored_dependencies = []
  648. self.world_target = set()
  649. self.bbfile_priority = {}
  650. def add_from_recipeinfo(self, fn, info_array):
  651. for info in info_array:
  652. info.add_cacheData(self, fn)
  653. class MultiProcessCache(object):
  654. """
  655. BitBake multi-process cache implementation
  656. Used by the codeparser & file checksum caches
  657. """
  658. def __init__(self):
  659. self.cachefile = None
  660. self.cachedata = self.create_cachedata()
  661. self.cachedata_extras = self.create_cachedata()
  662. def init_cache(self, d, cache_file_name=None):
  663. cachedir = (d.getVar("PERSISTENT_DIR", True) or
  664. d.getVar("CACHE", True))
  665. if cachedir in [None, '']:
  666. return
  667. bb.utils.mkdirhier(cachedir)
  668. self.cachefile = os.path.join(cachedir,
  669. cache_file_name or self.__class__.cache_file_name)
  670. logger.debug(1, "Using cache in '%s'", self.cachefile)
  671. glf = bb.utils.lockfile(self.cachefile + ".lock")
  672. try:
  673. with open(self.cachefile, "rb") as f:
  674. p = pickle.Unpickler(f)
  675. data, version = p.load()
  676. except:
  677. bb.utils.unlockfile(glf)
  678. return
  679. bb.utils.unlockfile(glf)
  680. if version != self.__class__.CACHE_VERSION:
  681. return
  682. self.cachedata = data
  683. def create_cachedata(self):
  684. data = [{}]
  685. return data
  686. def save_extras(self):
  687. if not self.cachefile:
  688. return
  689. glf = bb.utils.lockfile(self.cachefile + ".lock", shared=True)
  690. i = os.getpid()
  691. lf = None
  692. while not lf:
  693. lf = bb.utils.lockfile(self.cachefile + ".lock." + str(i), retry=False)
  694. if not lf or os.path.exists(self.cachefile + "-" + str(i)):
  695. if lf:
  696. bb.utils.unlockfile(lf)
  697. lf = None
  698. i = i + 1
  699. continue
  700. with open(self.cachefile + "-" + str(i), "wb") as f:
  701. p = pickle.Pickler(f, -1)
  702. p.dump([self.cachedata_extras, self.__class__.CACHE_VERSION])
  703. bb.utils.unlockfile(lf)
  704. bb.utils.unlockfile(glf)
  705. def merge_data(self, source, dest):
  706. for j in range(0,len(dest)):
  707. for h in source[j]:
  708. if h not in dest[j]:
  709. dest[j][h] = source[j][h]
  710. def save_merge(self):
  711. if not self.cachefile:
  712. return
  713. glf = bb.utils.lockfile(self.cachefile + ".lock")
  714. data = self.cachedata
  715. for f in [y for y in os.listdir(os.path.dirname(self.cachefile)) if y.startswith(os.path.basename(self.cachefile) + '-')]:
  716. f = os.path.join(os.path.dirname(self.cachefile), f)
  717. try:
  718. with open(f, "rb") as fd:
  719. p = pickle.Unpickler(fd)
  720. extradata, version = p.load()
  721. except (IOError, EOFError):
  722. os.unlink(f)
  723. continue
  724. if version != self.__class__.CACHE_VERSION:
  725. os.unlink(f)
  726. continue
  727. self.merge_data(extradata, data)
  728. os.unlink(f)
  729. with open(self.cachefile, "wb") as f:
  730. p = pickle.Pickler(f, -1)
  731. p.dump([data, self.__class__.CACHE_VERSION])
  732. bb.utils.unlockfile(glf)