cache.py 31 KB

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