cache.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. #
  4. # BitBake Cache implementation
  5. #
  6. # Caching of bitbake variables before task execution
  7. # Copyright (C) 2006 Richard Purdie
  8. # Copyright (C) 2012 Intel Corporation
  9. # but small sections based on code from bin/bitbake:
  10. # Copyright (C) 2003, 2004 Chris Larson
  11. # Copyright (C) 2003, 2004 Phil Blundell
  12. # Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
  13. # Copyright (C) 2005 Holger Hans Peter Freyther
  14. # Copyright (C) 2005 ROAD GmbH
  15. #
  16. # This program is free software; you can redistribute it and/or modify
  17. # it under the terms of the GNU General Public License version 2 as
  18. # published by the Free Software Foundation.
  19. #
  20. # This program is distributed in the hope that it will be useful,
  21. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. # GNU General Public License for more details.
  24. #
  25. # You should have received a copy of the GNU General Public License along
  26. # with this program; if not, write to the Free Software Foundation, Inc.,
  27. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  28. import os
  29. import 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__ = "150"
  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, expand = True):
  73. return metadata.getVar(var, expand) 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_extrainfo = self.flaglist('stamp-extra-info', self.tasks, metadata)
  107. self.file_checksums = self.flaglist('file-checksums', self.tasks, metadata, True)
  108. self.packages_dynamic = self.listvar('PACKAGES_DYNAMIC', metadata)
  109. self.depends = self.depvar('DEPENDS', metadata)
  110. self.provides = self.depvar('PROVIDES', metadata)
  111. self.rdepends = self.depvar('RDEPENDS', metadata)
  112. self.rprovides = self.depvar('RPROVIDES', metadata)
  113. self.rrecommends = self.depvar('RRECOMMENDS', metadata)
  114. self.rprovides_pkg = self.pkgvar('RPROVIDES', self.packages, metadata)
  115. self.rdepends_pkg = self.pkgvar('RDEPENDS', self.packages, metadata)
  116. self.rrecommends_pkg = self.pkgvar('RRECOMMENDS', self.packages, metadata)
  117. self.inherits = self.getvar('__inherit_cache', metadata, expand=False)
  118. self.fakerootenv = self.getvar('FAKEROOTENV', metadata)
  119. self.fakerootdirs = self.getvar('FAKEROOTDIRS', metadata)
  120. self.fakerootnoenv = self.getvar('FAKEROOTNOENV', metadata)
  121. self.extradepsfunc = self.getvar('calculate_extra_depends', metadata)
  122. @classmethod
  123. def init_cacheData(cls, cachedata):
  124. # CacheData in Core RecipeInfo Class
  125. cachedata.task_deps = {}
  126. cachedata.pkg_fn = {}
  127. cachedata.pkg_pn = defaultdict(list)
  128. cachedata.pkg_pepvpr = {}
  129. cachedata.pkg_dp = {}
  130. cachedata.stamp = {}
  131. cachedata.stampclean = {}
  132. cachedata.stamp_extrainfo = {}
  133. cachedata.file_checksums = {}
  134. cachedata.fn_provides = {}
  135. cachedata.pn_provides = defaultdict(list)
  136. cachedata.all_depends = []
  137. cachedata.deps = defaultdict(list)
  138. cachedata.packages = defaultdict(list)
  139. cachedata.providers = defaultdict(list)
  140. cachedata.rproviders = defaultdict(list)
  141. cachedata.packages_dynamic = defaultdict(list)
  142. cachedata.rundeps = defaultdict(lambda: defaultdict(list))
  143. cachedata.runrecs = defaultdict(lambda: defaultdict(list))
  144. cachedata.possible_world = []
  145. cachedata.universe_target = []
  146. cachedata.hashfn = {}
  147. cachedata.basetaskhash = {}
  148. cachedata.inherits = {}
  149. cachedata.fakerootenv = {}
  150. cachedata.fakerootnoenv = {}
  151. cachedata.fakerootdirs = {}
  152. cachedata.extradepsfunc = {}
  153. def add_cacheData(self, cachedata, fn):
  154. cachedata.task_deps[fn] = self.task_deps
  155. cachedata.pkg_fn[fn] = self.pn
  156. cachedata.pkg_pn[self.pn].append(fn)
  157. cachedata.pkg_pepvpr[fn] = (self.pe, self.pv, self.pr)
  158. cachedata.pkg_dp[fn] = self.defaultpref
  159. cachedata.stamp[fn] = self.stamp
  160. cachedata.stampclean[fn] = self.stampclean
  161. cachedata.stamp_extrainfo[fn] = self.stamp_extrainfo
  162. cachedata.file_checksums[fn] = self.file_checksums
  163. provides = [self.pn]
  164. for provide in self.provides:
  165. if provide not in provides:
  166. provides.append(provide)
  167. cachedata.fn_provides[fn] = provides
  168. for provide in provides:
  169. cachedata.providers[provide].append(fn)
  170. if provide not in cachedata.pn_provides[self.pn]:
  171. cachedata.pn_provides[self.pn].append(provide)
  172. for dep in self.depends:
  173. if dep not in cachedata.deps[fn]:
  174. cachedata.deps[fn].append(dep)
  175. if dep not in cachedata.all_depends:
  176. cachedata.all_depends.append(dep)
  177. rprovides = self.rprovides
  178. for package in self.packages:
  179. cachedata.packages[package].append(fn)
  180. rprovides += self.rprovides_pkg[package]
  181. for rprovide in rprovides:
  182. if fn not in cachedata.rproviders[rprovide]:
  183. cachedata.rproviders[rprovide].append(fn)
  184. for package in self.packages_dynamic:
  185. cachedata.packages_dynamic[package].append(fn)
  186. # Build hash of runtime depends and recommends
  187. for package in self.packages + [self.pn]:
  188. cachedata.rundeps[fn][package] = list(self.rdepends) + self.rdepends_pkg[package]
  189. cachedata.runrecs[fn][package] = list(self.rrecommends) + self.rrecommends_pkg[package]
  190. # Collect files we may need for possible world-dep
  191. # calculations
  192. if self.not_world:
  193. logger.debug(1, "EXCLUDE FROM WORLD: %s", fn)
  194. else:
  195. cachedata.possible_world.append(fn)
  196. # create a collection of all targets for sanity checking
  197. # tasks, such as upstream versions, license, and tools for
  198. # task and image creation.
  199. cachedata.universe_target.append(self.pn)
  200. cachedata.hashfn[fn] = self.hashfilename
  201. for task, taskhash in self.basetaskhashes.iteritems():
  202. identifier = '%s.%s' % (fn, task)
  203. cachedata.basetaskhash[identifier] = taskhash
  204. cachedata.inherits[fn] = self.inherits
  205. cachedata.fakerootenv[fn] = self.fakerootenv
  206. cachedata.fakerootnoenv[fn] = self.fakerootnoenv
  207. cachedata.fakerootdirs[fn] = self.fakerootdirs
  208. cachedata.extradepsfunc[fn] = self.extradepsfunc
  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 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 key in self.depends_cache:
  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. fl = fl.strip()
  442. while fl:
  443. # A .split() would be simpler but means spaces or colons in filenames would break
  444. a = fl.find(":True")
  445. b = fl.find(":False")
  446. if ((a < 0) and b) or ((b > 0) and (b < a)):
  447. f = fl[:b+6]
  448. fl = fl[b+7:]
  449. elif ((b < 0) and a) or ((a > 0) and (a < b)):
  450. f = fl[:a+5]
  451. fl = fl[a+6:]
  452. else:
  453. break
  454. fl = fl.strip()
  455. if "*" in f:
  456. continue
  457. f, exist = f.split(":")
  458. if (exist == "True" and not os.path.exists(f)) or (exist == "False" and os.path.exists(f)):
  459. logger.debug(2, "Cache: %s's file checksum list file %s changed",
  460. fn, f)
  461. self.remove(fn)
  462. return False
  463. if appends != info_array[0].appends:
  464. logger.debug(2, "Cache: appends for %s changed", fn)
  465. logger.debug(2, "%s to %s" % (str(appends), str(info_array[0].appends)))
  466. self.remove(fn)
  467. return False
  468. invalid = False
  469. for cls in info_array[0].variants:
  470. virtualfn = self.realfn2virtual(fn, cls)
  471. self.clean.add(virtualfn)
  472. if virtualfn not in self.depends_cache:
  473. logger.debug(2, "Cache: %s is not cached", virtualfn)
  474. invalid = True
  475. # If any one of the variants is not present, mark as invalid for all
  476. if invalid:
  477. for cls in info_array[0].variants:
  478. virtualfn = self.realfn2virtual(fn, cls)
  479. if virtualfn in self.clean:
  480. logger.debug(2, "Cache: Removing %s from cache", virtualfn)
  481. self.clean.remove(virtualfn)
  482. if fn in self.clean:
  483. logger.debug(2, "Cache: Marking %s as not clean", fn)
  484. self.clean.remove(fn)
  485. return False
  486. self.clean.add(fn)
  487. return True
  488. def remove(self, fn):
  489. """
  490. Remove a fn from the cache
  491. Called from the parser in error cases
  492. """
  493. if fn in self.depends_cache:
  494. logger.debug(1, "Removing %s from cache", fn)
  495. del self.depends_cache[fn]
  496. if fn in self.clean:
  497. logger.debug(1, "Marking %s as unclean", fn)
  498. self.clean.remove(fn)
  499. def sync(self):
  500. """
  501. Save the cache
  502. Called from the parser when complete (or exiting)
  503. """
  504. if not self.has_cache:
  505. return
  506. if self.cacheclean:
  507. logger.debug(2, "Cache is clean, not saving.")
  508. return
  509. file_dict = {}
  510. pickler_dict = {}
  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. cachefile = getCacheFile(self.cachedir, cache_class.cachefile, self.data_hash)
  515. file_dict[cache_class_name] = open(cachefile, "wb")
  516. pickler_dict[cache_class_name] = pickle.Pickler(file_dict[cache_class_name], pickle.HIGHEST_PROTOCOL)
  517. pickler_dict['CoreRecipeInfo'].dump(__cache_version__)
  518. pickler_dict['CoreRecipeInfo'].dump(bb.__version__)
  519. try:
  520. for key, info_array in self.depends_cache.iteritems():
  521. for info in info_array:
  522. if isinstance(info, RecipeInfoCommon):
  523. cache_class_name = info.__class__.__name__
  524. pickler_dict[cache_class_name].dump(key)
  525. pickler_dict[cache_class_name].dump(info)
  526. finally:
  527. for cache_class in self.caches_array:
  528. if type(cache_class) is type and issubclass(cache_class, RecipeInfoCommon):
  529. cache_class_name = cache_class.__name__
  530. file_dict[cache_class_name].close()
  531. del self.depends_cache
  532. @staticmethod
  533. def mtime(cachefile):
  534. return bb.parse.cached_mtime_noerror(cachefile)
  535. def add_info(self, filename, info_array, cacheData, parsed=None, watcher=None):
  536. if isinstance(info_array[0], CoreRecipeInfo) and (not info_array[0].skipped):
  537. cacheData.add_from_recipeinfo(filename, info_array)
  538. if watcher:
  539. watcher(info_array[0].file_depends)
  540. if not self.has_cache:
  541. return
  542. if (info_array[0].skipped or 'SRCREVINACTION' not in info_array[0].pv) and not info_array[0].nocache:
  543. if parsed:
  544. self.cacheclean = False
  545. self.depends_cache[filename] = info_array
  546. def add(self, file_name, data, cacheData, parsed=None):
  547. """
  548. Save data we need into the cache
  549. """
  550. realfn = self.virtualfn2realfn(file_name)[0]
  551. info_array = []
  552. for cache_class in self.caches_array:
  553. if type(cache_class) is type and issubclass(cache_class, RecipeInfoCommon):
  554. info_array.append(cache_class(realfn, data))
  555. self.add_info(file_name, info_array, cacheData, parsed)
  556. @staticmethod
  557. def load_bbfile(bbfile, appends, config):
  558. """
  559. Load and parse one .bb build file
  560. Return the data and whether parsing resulted in the file being skipped
  561. """
  562. chdir_back = False
  563. from bb import parse
  564. # expand tmpdir to include this topdir
  565. config.setVar('TMPDIR', config.getVar('TMPDIR', True) or "")
  566. bbfile_loc = os.path.abspath(os.path.dirname(bbfile))
  567. oldpath = os.path.abspath(os.getcwd())
  568. parse.cached_mtime_noerror(bbfile_loc)
  569. bb_data = config.createCopy()
  570. # The ConfHandler first looks if there is a TOPDIR and if not
  571. # then it would call getcwd().
  572. # Previously, we chdir()ed to bbfile_loc, called the handler
  573. # and finally chdir()ed back, a couple of thousand times. We now
  574. # just fill in TOPDIR to point to bbfile_loc if there is no TOPDIR yet.
  575. if not bb_data.getVar('TOPDIR', False):
  576. chdir_back = True
  577. bb_data.setVar('TOPDIR', bbfile_loc)
  578. try:
  579. if appends:
  580. bb_data.setVar('__BBAPPEND', " ".join(appends))
  581. bb_data = parse.handle(bbfile, bb_data)
  582. if chdir_back:
  583. os.chdir(oldpath)
  584. return bb_data
  585. except:
  586. if chdir_back:
  587. os.chdir(oldpath)
  588. raise
  589. def init(cooker):
  590. """
  591. The Objective: Cache the minimum amount of data possible yet get to the
  592. stage of building packages (i.e. tryBuild) without reparsing any .bb files.
  593. To do this, we intercept getVar calls and only cache the variables we see
  594. being accessed. We rely on the cache getVar calls being made for all
  595. variables bitbake might need to use to reach this stage. For each cached
  596. file we need to track:
  597. * Its mtime
  598. * The mtimes of all its dependencies
  599. * Whether it caused a parse.SkipRecipe exception
  600. Files causing parsing errors are evicted from the cache.
  601. """
  602. return Cache(cooker.configuration.data, cooker.configuration.data_hash)
  603. class CacheData(object):
  604. """
  605. The data structures we compile from the cached data
  606. """
  607. def __init__(self, caches_array):
  608. self.caches_array = caches_array
  609. for cache_class in self.caches_array:
  610. if type(cache_class) is type and issubclass(cache_class, RecipeInfoCommon):
  611. cache_class.init_cacheData(self)
  612. # Direct cache variables
  613. self.task_queues = {}
  614. self.preferred = {}
  615. self.tasks = {}
  616. # Indirect Cache variables (set elsewhere)
  617. self.ignored_dependencies = []
  618. self.world_target = set()
  619. self.bbfile_priority = {}
  620. def add_from_recipeinfo(self, fn, info_array):
  621. for info in info_array:
  622. info.add_cacheData(self, fn)
  623. class MultiProcessCache(object):
  624. """
  625. BitBake multi-process cache implementation
  626. Used by the codeparser & file checksum caches
  627. """
  628. def __init__(self):
  629. self.cachefile = None
  630. self.cachedata = self.create_cachedata()
  631. self.cachedata_extras = self.create_cachedata()
  632. def init_cache(self, d, cache_file_name=None):
  633. cachedir = (d.getVar("PERSISTENT_DIR", True) or
  634. d.getVar("CACHE", True))
  635. if cachedir in [None, '']:
  636. return
  637. bb.utils.mkdirhier(cachedir)
  638. self.cachefile = os.path.join(cachedir,
  639. cache_file_name or self.__class__.cache_file_name)
  640. logger.debug(1, "Using cache in '%s'", self.cachefile)
  641. glf = bb.utils.lockfile(self.cachefile + ".lock")
  642. try:
  643. with open(self.cachefile, "rb") as f:
  644. p = pickle.Unpickler(f)
  645. data, version = p.load()
  646. except:
  647. bb.utils.unlockfile(glf)
  648. return
  649. bb.utils.unlockfile(glf)
  650. if version != self.__class__.CACHE_VERSION:
  651. return
  652. self.cachedata = data
  653. def create_cachedata(self):
  654. data = [{}]
  655. return data
  656. def save_extras(self):
  657. if not self.cachefile:
  658. return
  659. glf = bb.utils.lockfile(self.cachefile + ".lock", shared=True)
  660. i = os.getpid()
  661. lf = None
  662. while not lf:
  663. lf = bb.utils.lockfile(self.cachefile + ".lock." + str(i), retry=False)
  664. if not lf or os.path.exists(self.cachefile + "-" + str(i)):
  665. if lf:
  666. bb.utils.unlockfile(lf)
  667. lf = None
  668. i = i + 1
  669. continue
  670. with open(self.cachefile + "-" + str(i), "wb") as f:
  671. p = pickle.Pickler(f, -1)
  672. p.dump([self.cachedata_extras, self.__class__.CACHE_VERSION])
  673. bb.utils.unlockfile(lf)
  674. bb.utils.unlockfile(glf)
  675. def merge_data(self, source, dest):
  676. for j in range(0,len(dest)):
  677. for h in source[j]:
  678. if h not in dest[j]:
  679. dest[j][h] = source[j][h]
  680. def save_merge(self):
  681. if not self.cachefile:
  682. return
  683. glf = bb.utils.lockfile(self.cachefile + ".lock")
  684. data = self.cachedata
  685. for f in [y for y in os.listdir(os.path.dirname(self.cachefile)) if y.startswith(os.path.basename(self.cachefile) + '-')]:
  686. f = os.path.join(os.path.dirname(self.cachefile), f)
  687. try:
  688. with open(f, "rb") as fd:
  689. p = pickle.Unpickler(fd)
  690. extradata, version = p.load()
  691. except (IOError, EOFError):
  692. os.unlink(f)
  693. continue
  694. if version != self.__class__.CACHE_VERSION:
  695. os.unlink(f)
  696. continue
  697. self.merge_data(extradata, data)
  698. os.unlink(f)
  699. with open(self.cachefile, "wb") as f:
  700. p = pickle.Pickler(f, -1)
  701. p.dump([data, self.__class__.CACHE_VERSION])
  702. bb.utils.unlockfile(glf)