cache.py 32 KB

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