sstate.bbclass 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. SSTATE_VERSION = "3"
  2. SSTATE_MANIFESTS ?= "${TMPDIR}/sstate-control"
  3. SSTATE_MANFILEPREFIX = "${SSTATE_MANIFESTS}/manifest-${SSTATE_MANMACH}-${PN}"
  4. def generate_sstatefn(spec, hash, taskname, siginfo, d):
  5. if taskname is None:
  6. return ""
  7. extension = ".tgz"
  8. # 8 chars reserved for siginfo
  9. limit = 254 - 8
  10. if siginfo:
  11. limit = 254
  12. extension = ".tgz.siginfo"
  13. if not hash:
  14. hash = "INVALID"
  15. fn = spec + hash + "_" + taskname + extension
  16. # If the filename is too long, attempt to reduce it
  17. if len(fn) > limit:
  18. components = spec.split(":")
  19. # Fields 0,5,6 are mandatory, 1 is most useful, 2,3,4 are just for information
  20. # 7 is for the separators
  21. avail = (254 - len(hash + "_" + taskname + extension) - len(components[0]) - len(components[1]) - len(components[5]) - len(components[6]) - 7) // 3
  22. components[2] = components[2][:avail]
  23. components[3] = components[3][:avail]
  24. components[4] = components[4][:avail]
  25. spec = ":".join(components)
  26. fn = spec + hash + "_" + taskname + extension
  27. if len(fn) > limit:
  28. bb.fatal("Unable to reduce sstate name to less than 255 chararacters")
  29. return hash[:2] + "/" + hash[2:4] + "/" + fn
  30. SSTATE_PKGARCH = "${PACKAGE_ARCH}"
  31. SSTATE_PKGSPEC = "sstate:${PN}:${PACKAGE_ARCH}${TARGET_VENDOR}-${TARGET_OS}:${PV}:${PR}:${SSTATE_PKGARCH}:${SSTATE_VERSION}:"
  32. SSTATE_SWSPEC = "sstate:${PN}::${PV}:${PR}::${SSTATE_VERSION}:"
  33. SSTATE_PKGNAME = "${SSTATE_EXTRAPATH}${@generate_sstatefn(d.getVar('SSTATE_PKGSPEC'), d.getVar('BB_UNIHASH'), d.getVar('SSTATE_CURRTASK'), False, d)}"
  34. SSTATE_PKG = "${SSTATE_DIR}/${SSTATE_PKGNAME}"
  35. SSTATE_EXTRAPATH = ""
  36. SSTATE_EXTRAPATHWILDCARD = ""
  37. SSTATE_PATHSPEC = "${SSTATE_DIR}/${SSTATE_EXTRAPATHWILDCARD}*/*/${SSTATE_PKGSPEC}*_${SSTATE_PATH_CURRTASK}.tgz*"
  38. # explicitly make PV to depend on evaluated value of PV variable
  39. PV[vardepvalue] = "${PV}"
  40. # We don't want the sstate to depend on things like the distro string
  41. # of the system, we let the sstate paths take care of this.
  42. SSTATE_EXTRAPATH[vardepvalue] = ""
  43. SSTATE_EXTRAPATHWILDCARD[vardepvalue] = ""
  44. # For multilib rpm the allarch packagegroup files can overwrite (in theory they're identical)
  45. SSTATE_DUPWHITELIST = "${DEPLOY_DIR}/licenses/"
  46. # Avoid docbook/sgml catalog warnings for now
  47. SSTATE_DUPWHITELIST += "${STAGING_ETCDIR_NATIVE}/sgml ${STAGING_DATADIR_NATIVE}/sgml"
  48. # sdk-provides-dummy-nativesdk and nativesdk-buildtools-perl-dummy overlap for different SDKMACHINE
  49. SSTATE_DUPWHITELIST += "${DEPLOY_DIR_RPM}/sdk_provides_dummy_nativesdk/ ${DEPLOY_DIR_IPK}/sdk-provides-dummy-nativesdk/"
  50. SSTATE_DUPWHITELIST += "${DEPLOY_DIR_RPM}/buildtools_dummy_nativesdk/ ${DEPLOY_DIR_IPK}/buildtools-dummy-nativesdk/"
  51. # target-sdk-provides-dummy overlaps that allarch is disabled when multilib is used
  52. SSTATE_DUPWHITELIST += "${COMPONENTS_DIR}/sdk-provides-dummy-target/ ${DEPLOY_DIR_RPM}/sdk_provides_dummy_target/ ${DEPLOY_DIR_IPK}/sdk-provides-dummy-target/"
  53. # Archive the sources for many architectures in one deploy folder
  54. SSTATE_DUPWHITELIST += "${DEPLOY_DIR_SRC}"
  55. # ovmf/grub-efi/systemd-boot/intel-microcode multilib recipes can generate identical overlapping files
  56. SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/ovmf"
  57. SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/grub-efi"
  58. SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/systemd-boot"
  59. SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/microcode"
  60. SSTATE_SCAN_FILES ?= "*.la *-config *_config postinst-*"
  61. SSTATE_SCAN_CMD ??= 'find ${SSTATE_BUILDDIR} \( -name "${@"\" -o -name \"".join(d.getVar("SSTATE_SCAN_FILES").split())}" \) -type f'
  62. SSTATE_SCAN_CMD_NATIVE ??= 'grep -Irl -e ${RECIPE_SYSROOT} -e ${RECIPE_SYSROOT_NATIVE} -e ${HOSTTOOLS_DIR} ${SSTATE_BUILDDIR}'
  63. BB_HASHFILENAME = "False ${SSTATE_PKGSPEC} ${SSTATE_SWSPEC}"
  64. SSTATE_ARCHS = " \
  65. ${BUILD_ARCH} \
  66. ${BUILD_ARCH}_${SDK_ARCH}_${SDK_OS} \
  67. ${BUILD_ARCH}_${TARGET_ARCH} \
  68. ${SDK_ARCH}_${SDK_OS} \
  69. ${SDK_ARCH}_${PACKAGE_ARCH} \
  70. allarch \
  71. ${PACKAGE_ARCH} \
  72. ${PACKAGE_EXTRA_ARCHS} \
  73. ${MACHINE_ARCH}"
  74. SSTATE_MANMACH ?= "${SSTATE_PKGARCH}"
  75. SSTATECREATEFUNCS = "sstate_hardcode_path"
  76. SSTATECREATEFUNCS[vardeps] = "SSTATE_SCAN_FILES"
  77. SSTATEPOSTCREATEFUNCS = ""
  78. SSTATEPREINSTFUNCS = ""
  79. SSTATEPOSTUNPACKFUNCS = "sstate_hardcode_path_unpack"
  80. SSTATEPOSTINSTFUNCS = ""
  81. EXTRA_STAGING_FIXMES ?= "HOSTTOOLS_DIR"
  82. # Check whether sstate exists for tasks that support sstate and are in the
  83. # locked signatures file.
  84. SIGGEN_LOCKEDSIGS_SSTATE_EXISTS_CHECK ?= 'error'
  85. # Check whether the task's computed hash matches the task's hash in the
  86. # locked signatures file.
  87. SIGGEN_LOCKEDSIGS_TASKSIG_CHECK ?= "error"
  88. # The GnuPG key ID and passphrase to use to sign sstate archives (or unset to
  89. # not sign)
  90. SSTATE_SIG_KEY ?= ""
  91. SSTATE_SIG_PASSPHRASE ?= ""
  92. # Whether to verify the GnUPG signatures when extracting sstate archives
  93. SSTATE_VERIFY_SIG ?= "0"
  94. SSTATE_HASHEQUIV_METHOD ?= "oe.sstatesig.OEOuthashBasic"
  95. SSTATE_HASHEQUIV_METHOD[doc] = "The fully-qualified function used to calculate \
  96. the output hash for a task, which in turn is used to determine equivalency. \
  97. "
  98. SSTATE_HASHEQUIV_REPORT_TASKDATA ?= "0"
  99. SSTATE_HASHEQUIV_REPORT_TASKDATA[doc] = "Report additional useful data to the \
  100. hash equivalency server, such as PN, PV, taskname, etc. This information \
  101. is very useful for developers looking at task data, but may leak sensitive \
  102. data if the equivalence server is public. \
  103. "
  104. python () {
  105. if bb.data.inherits_class('native', d):
  106. d.setVar('SSTATE_PKGARCH', d.getVar('BUILD_ARCH', False))
  107. elif bb.data.inherits_class('crosssdk', d):
  108. d.setVar('SSTATE_PKGARCH', d.expand("${BUILD_ARCH}_${SDK_ARCH}_${SDK_OS}"))
  109. elif bb.data.inherits_class('cross', d):
  110. d.setVar('SSTATE_PKGARCH', d.expand("${BUILD_ARCH}_${TARGET_ARCH}"))
  111. elif bb.data.inherits_class('nativesdk', d):
  112. d.setVar('SSTATE_PKGARCH', d.expand("${SDK_ARCH}_${SDK_OS}"))
  113. elif bb.data.inherits_class('cross-canadian', d):
  114. d.setVar('SSTATE_PKGARCH', d.expand("${SDK_ARCH}_${PACKAGE_ARCH}"))
  115. elif bb.data.inherits_class('allarch', d) and d.getVar("PACKAGE_ARCH") == "all":
  116. d.setVar('SSTATE_PKGARCH', "allarch")
  117. else:
  118. d.setVar('SSTATE_MANMACH', d.expand("${PACKAGE_ARCH}"))
  119. if bb.data.inherits_class('native', d) or bb.data.inherits_class('crosssdk', d) or bb.data.inherits_class('cross', d):
  120. d.setVar('SSTATE_EXTRAPATH', "${NATIVELSBSTRING}/")
  121. d.setVar('BB_HASHFILENAME', "True ${SSTATE_PKGSPEC} ${SSTATE_SWSPEC}")
  122. d.setVar('SSTATE_EXTRAPATHWILDCARD', "${NATIVELSBSTRING}/")
  123. unique_tasks = sorted(set((d.getVar('SSTATETASKS') or "").split()))
  124. d.setVar('SSTATETASKS', " ".join(unique_tasks))
  125. for task in unique_tasks:
  126. d.prependVarFlag(task, 'prefuncs', "sstate_task_prefunc ")
  127. d.appendVarFlag(task, 'postfuncs', " sstate_task_postfunc")
  128. }
  129. def sstate_init(task, d):
  130. ss = {}
  131. ss['task'] = task
  132. ss['dirs'] = []
  133. ss['plaindirs'] = []
  134. ss['lockfiles'] = []
  135. ss['lockfiles-shared'] = []
  136. return ss
  137. def sstate_state_fromvars(d, task = None):
  138. if task is None:
  139. task = d.getVar('BB_CURRENTTASK')
  140. if not task:
  141. bb.fatal("sstate code running without task context?!")
  142. task = task.replace("_setscene", "")
  143. if task.startswith("do_"):
  144. task = task[3:]
  145. inputs = (d.getVarFlag("do_" + task, 'sstate-inputdirs') or "").split()
  146. outputs = (d.getVarFlag("do_" + task, 'sstate-outputdirs') or "").split()
  147. plaindirs = (d.getVarFlag("do_" + task, 'sstate-plaindirs') or "").split()
  148. lockfiles = (d.getVarFlag("do_" + task, 'sstate-lockfile') or "").split()
  149. lockfilesshared = (d.getVarFlag("do_" + task, 'sstate-lockfile-shared') or "").split()
  150. interceptfuncs = (d.getVarFlag("do_" + task, 'sstate-interceptfuncs') or "").split()
  151. fixmedir = d.getVarFlag("do_" + task, 'sstate-fixmedir') or ""
  152. if not task or len(inputs) != len(outputs):
  153. bb.fatal("sstate variables not setup correctly?!")
  154. if task == "populate_lic":
  155. d.setVar("SSTATE_PKGSPEC", "${SSTATE_SWSPEC}")
  156. d.setVar("SSTATE_EXTRAPATH", "")
  157. d.setVar('SSTATE_EXTRAPATHWILDCARD', "")
  158. ss = sstate_init(task, d)
  159. for i in range(len(inputs)):
  160. sstate_add(ss, inputs[i], outputs[i], d)
  161. ss['lockfiles'] = lockfiles
  162. ss['lockfiles-shared'] = lockfilesshared
  163. ss['plaindirs'] = plaindirs
  164. ss['interceptfuncs'] = interceptfuncs
  165. ss['fixmedir'] = fixmedir
  166. return ss
  167. def sstate_add(ss, source, dest, d):
  168. if not source.endswith("/"):
  169. source = source + "/"
  170. if not dest.endswith("/"):
  171. dest = dest + "/"
  172. source = os.path.normpath(source)
  173. dest = os.path.normpath(dest)
  174. srcbase = os.path.basename(source)
  175. ss['dirs'].append([srcbase, source, dest])
  176. return ss
  177. def sstate_install(ss, d):
  178. import oe.path
  179. import oe.sstatesig
  180. import subprocess
  181. sharedfiles = []
  182. shareddirs = []
  183. bb.utils.mkdirhier(d.expand("${SSTATE_MANIFESTS}"))
  184. sstateinst = d.expand("${WORKDIR}/sstate-install-%s/" % ss['task'])
  185. manifest, d2 = oe.sstatesig.sstate_get_manifest_filename(ss['task'], d)
  186. if os.access(manifest, os.R_OK):
  187. bb.fatal("Package already staged (%s)?!" % manifest)
  188. d.setVar("SSTATE_INST_POSTRM", manifest + ".postrm")
  189. locks = []
  190. for lock in ss['lockfiles-shared']:
  191. locks.append(bb.utils.lockfile(lock, True))
  192. for lock in ss['lockfiles']:
  193. locks.append(bb.utils.lockfile(lock))
  194. for state in ss['dirs']:
  195. bb.debug(2, "Staging files from %s to %s" % (state[1], state[2]))
  196. for walkroot, dirs, files in os.walk(state[1]):
  197. for file in files:
  198. srcpath = os.path.join(walkroot, file)
  199. dstpath = srcpath.replace(state[1], state[2])
  200. #bb.debug(2, "Staging %s to %s" % (srcpath, dstpath))
  201. sharedfiles.append(dstpath)
  202. for dir in dirs:
  203. srcdir = os.path.join(walkroot, dir)
  204. dstdir = srcdir.replace(state[1], state[2])
  205. #bb.debug(2, "Staging %s to %s" % (srcdir, dstdir))
  206. if os.path.islink(srcdir):
  207. sharedfiles.append(dstdir)
  208. continue
  209. if not dstdir.endswith("/"):
  210. dstdir = dstdir + "/"
  211. shareddirs.append(dstdir)
  212. # Check the file list for conflicts against files which already exist
  213. whitelist = (d.getVar("SSTATE_DUPWHITELIST") or "").split()
  214. match = []
  215. for f in sharedfiles:
  216. if os.path.exists(f) and not os.path.islink(f):
  217. f = os.path.normpath(f)
  218. realmatch = True
  219. for w in whitelist:
  220. w = os.path.normpath(w)
  221. if f.startswith(w):
  222. realmatch = False
  223. break
  224. if realmatch:
  225. match.append(f)
  226. sstate_search_cmd = "grep -rlF '%s' %s --exclude=master.list | sed -e 's:^.*/::'" % (f, d.expand("${SSTATE_MANIFESTS}"))
  227. search_output = subprocess.Popen(sstate_search_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
  228. if search_output:
  229. match.append(" (matched in %s)" % search_output.decode('utf-8').rstrip())
  230. else:
  231. match.append(" (not matched to any task)")
  232. if match:
  233. bb.error("The recipe %s is trying to install files into a shared " \
  234. "area when those files already exist. Those files and their manifest " \
  235. "location are:\n %s\nPlease verify which recipe should provide the " \
  236. "above files.\n\nThe build has stopped, as continuing in this scenario WILL " \
  237. "break things - if not now, possibly in the future (we've seen builds fail " \
  238. "several months later). If the system knew how to recover from this " \
  239. "automatically it would, however there are several different scenarios " \
  240. "which can result in this and we don't know which one this is. It may be " \
  241. "you have switched providers of something like virtual/kernel (e.g. from " \
  242. "linux-yocto to linux-yocto-dev), in that case you need to execute the " \
  243. "clean task for both recipes and it will resolve this error. It may be " \
  244. "you changed DISTRO_FEATURES from systemd to udev or vice versa. Cleaning " \
  245. "those recipes should again resolve this error, however switching " \
  246. "DISTRO_FEATURES on an existing build directory is not supported - you " \
  247. "should really clean out tmp and rebuild (reusing sstate should be safe). " \
  248. "It could be the overlapping files detected are harmless in which case " \
  249. "adding them to SSTATE_DUPWHITELIST may be the correct solution. It could " \
  250. "also be your build is including two different conflicting versions of " \
  251. "things (e.g. bluez 4 and bluez 5 and the correct solution for that would " \
  252. "be to resolve the conflict. If in doubt, please ask on the mailing list, " \
  253. "sharing the error and filelist above." % \
  254. (d.getVar('PN'), "\n ".join(match)))
  255. bb.fatal("If the above message is too much, the simpler version is you're advised to wipe out tmp and rebuild (reusing sstate is fine). That will likely fix things in most (but not all) cases.")
  256. if ss['fixmedir'] and os.path.exists(ss['fixmedir'] + "/fixmepath.cmd"):
  257. sharedfiles.append(ss['fixmedir'] + "/fixmepath.cmd")
  258. sharedfiles.append(ss['fixmedir'] + "/fixmepath")
  259. # Write out the manifest
  260. f = open(manifest, "w")
  261. for file in sharedfiles:
  262. f.write(file + "\n")
  263. # We want to ensure that directories appear at the end of the manifest
  264. # so that when we test to see if they should be deleted any contents
  265. # added by the task will have been removed first.
  266. dirs = sorted(shareddirs, key=len)
  267. # Must remove children first, which will have a longer path than the parent
  268. for di in reversed(dirs):
  269. f.write(di + "\n")
  270. f.close()
  271. # Append to the list of manifests for this PACKAGE_ARCH
  272. i = d2.expand("${SSTATE_MANIFESTS}/index-${SSTATE_MANMACH}")
  273. l = bb.utils.lockfile(i + ".lock")
  274. filedata = d.getVar("STAMP") + " " + d2.getVar("SSTATE_MANFILEPREFIX") + " " + d.getVar("WORKDIR") + "\n"
  275. manifests = []
  276. if os.path.exists(i):
  277. with open(i, "r") as f:
  278. manifests = f.readlines()
  279. if filedata not in manifests:
  280. with open(i, "a+") as f:
  281. f.write(filedata)
  282. bb.utils.unlockfile(l)
  283. # Run the actual file install
  284. for state in ss['dirs']:
  285. if os.path.exists(state[1]):
  286. oe.path.copyhardlinktree(state[1], state[2])
  287. for postinst in (d.getVar('SSTATEPOSTINSTFUNCS') or '').split():
  288. # All hooks should run in the SSTATE_INSTDIR
  289. bb.build.exec_func(postinst, d, (sstateinst,))
  290. for lock in locks:
  291. bb.utils.unlockfile(lock)
  292. sstate_install[vardepsexclude] += "SSTATE_DUPWHITELIST STATE_MANMACH SSTATE_MANFILEPREFIX"
  293. sstate_install[vardeps] += "${SSTATEPOSTINSTFUNCS}"
  294. def sstate_installpkg(ss, d):
  295. from oe.gpg_sign import get_signer
  296. sstateinst = d.expand("${WORKDIR}/sstate-install-%s/" % ss['task'])
  297. d.setVar("SSTATE_CURRTASK", ss['task'])
  298. sstatefetch = d.getVar('SSTATE_PKGNAME')
  299. sstatepkg = d.getVar('SSTATE_PKG')
  300. if not os.path.exists(sstatepkg):
  301. pstaging_fetch(sstatefetch, d)
  302. if not os.path.isfile(sstatepkg):
  303. bb.note("Sstate package %s does not exist" % sstatepkg)
  304. return False
  305. sstate_clean(ss, d)
  306. d.setVar('SSTATE_INSTDIR', sstateinst)
  307. if bb.utils.to_boolean(d.getVar("SSTATE_VERIFY_SIG"), False):
  308. if not os.path.isfile(sstatepkg + '.sig'):
  309. bb.warn("No signature file for sstate package %s, skipping acceleration..." % sstatepkg)
  310. return False
  311. signer = get_signer(d, 'local')
  312. if not signer.verify(sstatepkg + '.sig'):
  313. bb.warn("Cannot verify signature on sstate package %s, skipping acceleration..." % sstatepkg)
  314. return False
  315. # Empty sstateinst directory, ensure its clean
  316. if os.path.exists(sstateinst):
  317. oe.path.remove(sstateinst)
  318. bb.utils.mkdirhier(sstateinst)
  319. sstateinst = d.getVar("SSTATE_INSTDIR")
  320. d.setVar('SSTATE_FIXMEDIR', ss['fixmedir'])
  321. for f in (d.getVar('SSTATEPREINSTFUNCS') or '').split() + ['sstate_unpack_package']:
  322. # All hooks should run in the SSTATE_INSTDIR
  323. bb.build.exec_func(f, d, (sstateinst,))
  324. return sstate_installpkgdir(ss, d)
  325. def sstate_installpkgdir(ss, d):
  326. import oe.path
  327. import subprocess
  328. sstateinst = d.getVar("SSTATE_INSTDIR")
  329. d.setVar('SSTATE_FIXMEDIR', ss['fixmedir'])
  330. for f in (d.getVar('SSTATEPOSTUNPACKFUNCS') or '').split():
  331. # All hooks should run in the SSTATE_INSTDIR
  332. bb.build.exec_func(f, d, (sstateinst,))
  333. def prepdir(dir):
  334. # remove dir if it exists, ensure any parent directories do exist
  335. if os.path.exists(dir):
  336. oe.path.remove(dir)
  337. bb.utils.mkdirhier(dir)
  338. oe.path.remove(dir)
  339. for state in ss['dirs']:
  340. prepdir(state[1])
  341. os.rename(sstateinst + state[0], state[1])
  342. sstate_install(ss, d)
  343. for plain in ss['plaindirs']:
  344. workdir = d.getVar('WORKDIR')
  345. sharedworkdir = os.path.join(d.getVar('TMPDIR'), "work-shared")
  346. src = sstateinst + "/" + plain.replace(workdir, '')
  347. if sharedworkdir in plain:
  348. src = sstateinst + "/" + plain.replace(sharedworkdir, '')
  349. dest = plain
  350. bb.utils.mkdirhier(src)
  351. prepdir(dest)
  352. os.rename(src, dest)
  353. return True
  354. python sstate_hardcode_path_unpack () {
  355. # Fixup hardcoded paths
  356. #
  357. # Note: The logic below must match the reverse logic in
  358. # sstate_hardcode_path(d)
  359. import subprocess
  360. sstateinst = d.getVar('SSTATE_INSTDIR')
  361. sstatefixmedir = d.getVar('SSTATE_FIXMEDIR')
  362. fixmefn = sstateinst + "fixmepath"
  363. if os.path.isfile(fixmefn):
  364. staging_target = d.getVar('RECIPE_SYSROOT')
  365. staging_host = d.getVar('RECIPE_SYSROOT_NATIVE')
  366. if bb.data.inherits_class('native', d) or bb.data.inherits_class('cross-canadian', d):
  367. sstate_sed_cmd = "sed -i -e 's:FIXMESTAGINGDIRHOST:%s:g'" % (staging_host)
  368. elif bb.data.inherits_class('cross', d) or bb.data.inherits_class('crosssdk', d):
  369. sstate_sed_cmd = "sed -i -e 's:FIXMESTAGINGDIRTARGET:%s:g; s:FIXMESTAGINGDIRHOST:%s:g'" % (staging_target, staging_host)
  370. else:
  371. sstate_sed_cmd = "sed -i -e 's:FIXMESTAGINGDIRTARGET:%s:g'" % (staging_target)
  372. extra_staging_fixmes = d.getVar('EXTRA_STAGING_FIXMES') or ''
  373. for fixmevar in extra_staging_fixmes.split():
  374. fixme_path = d.getVar(fixmevar)
  375. sstate_sed_cmd += " -e 's:FIXME_%s:%s:g'" % (fixmevar, fixme_path)
  376. # Add sstateinst to each filename in fixmepath, use xargs to efficiently call sed
  377. sstate_hardcode_cmd = "sed -e 's:^:%s:g' %s | xargs %s" % (sstateinst, fixmefn, sstate_sed_cmd)
  378. # Defer do_populate_sysroot relocation command
  379. if sstatefixmedir:
  380. bb.utils.mkdirhier(sstatefixmedir)
  381. with open(sstatefixmedir + "/fixmepath.cmd", "w") as f:
  382. sstate_hardcode_cmd = sstate_hardcode_cmd.replace(fixmefn, sstatefixmedir + "/fixmepath")
  383. sstate_hardcode_cmd = sstate_hardcode_cmd.replace(sstateinst, "FIXMEFINALSSTATEINST")
  384. sstate_hardcode_cmd = sstate_hardcode_cmd.replace(staging_host, "FIXMEFINALSSTATEHOST")
  385. sstate_hardcode_cmd = sstate_hardcode_cmd.replace(staging_target, "FIXMEFINALSSTATETARGET")
  386. f.write(sstate_hardcode_cmd)
  387. bb.utils.copyfile(fixmefn, sstatefixmedir + "/fixmepath")
  388. return
  389. bb.note("Replacing fixme paths in sstate package: %s" % (sstate_hardcode_cmd))
  390. subprocess.check_call(sstate_hardcode_cmd, shell=True)
  391. # Need to remove this or we'd copy it into the target directory and may
  392. # conflict with another writer
  393. os.remove(fixmefn)
  394. }
  395. def sstate_clean_cachefile(ss, d):
  396. import oe.path
  397. if d.getVarFlag('do_%s' % ss['task'], 'task'):
  398. d.setVar("SSTATE_PATH_CURRTASK", ss['task'])
  399. sstatepkgfile = d.getVar('SSTATE_PATHSPEC')
  400. bb.note("Removing %s" % sstatepkgfile)
  401. oe.path.remove(sstatepkgfile)
  402. def sstate_clean_cachefiles(d):
  403. for task in (d.getVar('SSTATETASKS') or "").split():
  404. ld = d.createCopy()
  405. ss = sstate_state_fromvars(ld, task)
  406. sstate_clean_cachefile(ss, ld)
  407. def sstate_clean_manifest(manifest, d, prefix=None):
  408. import oe.path
  409. mfile = open(manifest)
  410. entries = mfile.readlines()
  411. mfile.close()
  412. for entry in entries:
  413. entry = entry.strip()
  414. if prefix and not entry.startswith("/"):
  415. entry = prefix + "/" + entry
  416. bb.debug(2, "Removing manifest: %s" % entry)
  417. # We can race against another package populating directories as we're removing them
  418. # so we ignore errors here.
  419. try:
  420. if entry.endswith("/"):
  421. if os.path.islink(entry[:-1]):
  422. os.remove(entry[:-1])
  423. elif os.path.exists(entry) and len(os.listdir(entry)) == 0:
  424. os.rmdir(entry[:-1])
  425. else:
  426. os.remove(entry)
  427. except OSError:
  428. pass
  429. postrm = manifest + ".postrm"
  430. if os.path.exists(manifest + ".postrm"):
  431. import subprocess
  432. os.chmod(postrm, 0o755)
  433. subprocess.check_call(postrm, shell=True)
  434. oe.path.remove(postrm)
  435. oe.path.remove(manifest)
  436. def sstate_clean(ss, d):
  437. import oe.path
  438. import glob
  439. d2 = d.createCopy()
  440. stamp_clean = d.getVar("STAMPCLEAN")
  441. extrainf = d.getVarFlag("do_" + ss['task'], 'stamp-extra-info')
  442. if extrainf:
  443. d2.setVar("SSTATE_MANMACH", extrainf)
  444. wildcard_stfile = "%s.do_%s*.%s" % (stamp_clean, ss['task'], extrainf)
  445. else:
  446. wildcard_stfile = "%s.do_%s*" % (stamp_clean, ss['task'])
  447. manifest = d2.expand("${SSTATE_MANFILEPREFIX}.%s" % ss['task'])
  448. if os.path.exists(manifest):
  449. locks = []
  450. for lock in ss['lockfiles-shared']:
  451. locks.append(bb.utils.lockfile(lock))
  452. for lock in ss['lockfiles']:
  453. locks.append(bb.utils.lockfile(lock))
  454. sstate_clean_manifest(manifest, d)
  455. for lock in locks:
  456. bb.utils.unlockfile(lock)
  457. # Remove the current and previous stamps, but keep the sigdata.
  458. #
  459. # The glob() matches do_task* which may match multiple tasks, for
  460. # example: do_package and do_package_write_ipk, so we need to
  461. # exactly match *.do_task.* and *.do_task_setscene.*
  462. rm_stamp = '.do_%s.' % ss['task']
  463. rm_setscene = '.do_%s_setscene.' % ss['task']
  464. # For BB_SIGNATURE_HANDLER = "noop"
  465. rm_nohash = ".do_%s" % ss['task']
  466. for stfile in glob.glob(wildcard_stfile):
  467. # Keep the sigdata
  468. if ".sigdata." in stfile or ".sigbasedata." in stfile:
  469. continue
  470. # Preserve taint files in the stamps directory
  471. if stfile.endswith('.taint'):
  472. continue
  473. if rm_stamp in stfile or rm_setscene in stfile or \
  474. stfile.endswith(rm_nohash):
  475. oe.path.remove(stfile)
  476. sstate_clean[vardepsexclude] = "SSTATE_MANFILEPREFIX"
  477. CLEANFUNCS += "sstate_cleanall"
  478. python sstate_cleanall() {
  479. bb.note("Removing shared state for package %s" % d.getVar('PN'))
  480. manifest_dir = d.getVar('SSTATE_MANIFESTS')
  481. if not os.path.exists(manifest_dir):
  482. return
  483. tasks = d.getVar('SSTATETASKS').split()
  484. for name in tasks:
  485. ld = d.createCopy()
  486. shared_state = sstate_state_fromvars(ld, name)
  487. sstate_clean(shared_state, ld)
  488. }
  489. python sstate_hardcode_path () {
  490. import subprocess, platform
  491. # Need to remove hardcoded paths and fix these when we install the
  492. # staging packages.
  493. #
  494. # Note: the logic in this function needs to match the reverse logic
  495. # in sstate_installpkg(ss, d)
  496. staging_target = d.getVar('RECIPE_SYSROOT')
  497. staging_host = d.getVar('RECIPE_SYSROOT_NATIVE')
  498. sstate_builddir = d.getVar('SSTATE_BUILDDIR')
  499. sstate_sed_cmd = "sed -i -e 's:%s:FIXMESTAGINGDIRHOST:g'" % staging_host
  500. if bb.data.inherits_class('native', d) or bb.data.inherits_class('cross-canadian', d):
  501. sstate_grep_cmd = "grep -l -e '%s'" % (staging_host)
  502. elif bb.data.inherits_class('cross', d) or bb.data.inherits_class('crosssdk', d):
  503. sstate_grep_cmd = "grep -l -e '%s' -e '%s'" % (staging_target, staging_host)
  504. sstate_sed_cmd += " -e 's:%s:FIXMESTAGINGDIRTARGET:g'" % staging_target
  505. else:
  506. sstate_grep_cmd = "grep -l -e '%s' -e '%s'" % (staging_target, staging_host)
  507. sstate_sed_cmd += " -e 's:%s:FIXMESTAGINGDIRTARGET:g'" % staging_target
  508. extra_staging_fixmes = d.getVar('EXTRA_STAGING_FIXMES') or ''
  509. for fixmevar in extra_staging_fixmes.split():
  510. fixme_path = d.getVar(fixmevar)
  511. sstate_sed_cmd += " -e 's:%s:FIXME_%s:g'" % (fixme_path, fixmevar)
  512. sstate_grep_cmd += " -e '%s'" % (fixme_path)
  513. fixmefn = sstate_builddir + "fixmepath"
  514. sstate_scan_cmd = d.getVar('SSTATE_SCAN_CMD')
  515. sstate_filelist_cmd = "tee %s" % (fixmefn)
  516. # fixmepath file needs relative paths, drop sstate_builddir prefix
  517. sstate_filelist_relative_cmd = "sed -i -e 's:^%s::g' %s" % (sstate_builddir, fixmefn)
  518. xargs_no_empty_run_cmd = '--no-run-if-empty'
  519. if platform.system() == 'Darwin':
  520. xargs_no_empty_run_cmd = ''
  521. # Limit the fixpaths and sed operations based on the initial grep search
  522. # This has the side effect of making sure the vfs cache is hot
  523. sstate_hardcode_cmd = "%s | xargs %s | %s | xargs %s %s" % (sstate_scan_cmd, sstate_grep_cmd, sstate_filelist_cmd, xargs_no_empty_run_cmd, sstate_sed_cmd)
  524. bb.note("Removing hardcoded paths from sstate package: '%s'" % (sstate_hardcode_cmd))
  525. subprocess.check_output(sstate_hardcode_cmd, shell=True, cwd=sstate_builddir)
  526. # If the fixmefn is empty, remove it..
  527. if os.stat(fixmefn).st_size == 0:
  528. os.remove(fixmefn)
  529. else:
  530. bb.note("Replacing absolute paths in fixmepath file: '%s'" % (sstate_filelist_relative_cmd))
  531. subprocess.check_output(sstate_filelist_relative_cmd, shell=True)
  532. }
  533. def sstate_package(ss, d):
  534. import oe.path
  535. tmpdir = d.getVar('TMPDIR')
  536. sstatebuild = d.expand("${WORKDIR}/sstate-build-%s/" % ss['task'])
  537. d.setVar("SSTATE_CURRTASK", ss['task'])
  538. bb.utils.remove(sstatebuild, recurse=True)
  539. bb.utils.mkdirhier(sstatebuild)
  540. for state in ss['dirs']:
  541. if not os.path.exists(state[1]):
  542. continue
  543. srcbase = state[0].rstrip("/").rsplit('/', 1)[0]
  544. # Find and error for absolute symlinks. We could attempt to relocate but its not
  545. # clear where the symlink is relative to in this context. We could add that markup
  546. # to sstate tasks but there aren't many of these so better just avoid them entirely.
  547. for walkroot, dirs, files in os.walk(state[1]):
  548. for file in files + dirs:
  549. srcpath = os.path.join(walkroot, file)
  550. if not os.path.islink(srcpath):
  551. continue
  552. link = os.readlink(srcpath)
  553. if not os.path.isabs(link):
  554. continue
  555. if not link.startswith(tmpdir):
  556. continue
  557. bb.error("sstate found an absolute path symlink %s pointing at %s. Please replace this with a relative link." % (srcpath, link))
  558. bb.debug(2, "Preparing tree %s for packaging at %s" % (state[1], sstatebuild + state[0]))
  559. os.rename(state[1], sstatebuild + state[0])
  560. workdir = d.getVar('WORKDIR')
  561. sharedworkdir = os.path.join(d.getVar('TMPDIR'), "work-shared")
  562. for plain in ss['plaindirs']:
  563. pdir = plain.replace(workdir, sstatebuild)
  564. if sharedworkdir in plain:
  565. pdir = plain.replace(sharedworkdir, sstatebuild)
  566. bb.utils.mkdirhier(plain)
  567. bb.utils.mkdirhier(pdir)
  568. os.rename(plain, pdir)
  569. d.setVar('SSTATE_BUILDDIR', sstatebuild)
  570. d.setVar('SSTATE_INSTDIR', sstatebuild)
  571. if d.getVar('SSTATE_SKIP_CREATION') == '1':
  572. return
  573. sstate_create_package = ['sstate_report_unihash', 'sstate_create_package']
  574. if d.getVar('SSTATE_SIG_KEY'):
  575. sstate_create_package.append('sstate_sign_package')
  576. for f in (d.getVar('SSTATECREATEFUNCS') or '').split() + \
  577. sstate_create_package + \
  578. (d.getVar('SSTATEPOSTCREATEFUNCS') or '').split():
  579. # All hooks should run in SSTATE_BUILDDIR.
  580. bb.build.exec_func(f, d, (sstatebuild,))
  581. # SSTATE_PKG may have been changed by sstate_report_unihash
  582. siginfo = d.getVar('SSTATE_PKG') + ".siginfo"
  583. if not os.path.exists(siginfo):
  584. bb.siggen.dump_this_task(siginfo, d)
  585. else:
  586. try:
  587. os.utime(siginfo, None)
  588. except PermissionError:
  589. pass
  590. return
  591. def pstaging_fetch(sstatefetch, d):
  592. import bb.fetch2
  593. # Only try and fetch if the user has configured a mirror
  594. mirrors = d.getVar('SSTATE_MIRRORS')
  595. if not mirrors:
  596. return
  597. # Copy the data object and override DL_DIR and SRC_URI
  598. localdata = bb.data.createCopy(d)
  599. dldir = localdata.expand("${SSTATE_DIR}")
  600. bb.utils.mkdirhier(dldir)
  601. localdata.delVar('MIRRORS')
  602. localdata.setVar('FILESPATH', dldir)
  603. localdata.setVar('DL_DIR', dldir)
  604. localdata.setVar('PREMIRRORS', mirrors)
  605. # if BB_NO_NETWORK is set but we also have SSTATE_MIRROR_ALLOW_NETWORK,
  606. # we'll want to allow network access for the current set of fetches.
  607. if bb.utils.to_boolean(localdata.getVar('BB_NO_NETWORK')) and \
  608. bb.utils.to_boolean(localdata.getVar('SSTATE_MIRROR_ALLOW_NETWORK')):
  609. localdata.delVar('BB_NO_NETWORK')
  610. # Try a fetch from the sstate mirror, if it fails just return and
  611. # we will build the package
  612. uris = ['file://{0};downloadfilename={0}'.format(sstatefetch),
  613. 'file://{0}.siginfo;downloadfilename={0}.siginfo'.format(sstatefetch)]
  614. if bb.utils.to_boolean(d.getVar("SSTATE_VERIFY_SIG"), False):
  615. uris += ['file://{0}.sig;downloadfilename={0}.sig'.format(sstatefetch)]
  616. for srcuri in uris:
  617. localdata.setVar('SRC_URI', srcuri)
  618. try:
  619. fetcher = bb.fetch2.Fetch([srcuri], localdata, cache=False)
  620. fetcher.checkstatus()
  621. fetcher.download()
  622. except bb.fetch2.BBFetchException:
  623. pass
  624. def sstate_setscene(d):
  625. shared_state = sstate_state_fromvars(d)
  626. accelerate = sstate_installpkg(shared_state, d)
  627. if not accelerate:
  628. bb.fatal("No suitable staging package found")
  629. python sstate_task_prefunc () {
  630. shared_state = sstate_state_fromvars(d)
  631. sstate_clean(shared_state, d)
  632. }
  633. sstate_task_prefunc[dirs] = "${WORKDIR}"
  634. python sstate_task_postfunc () {
  635. shared_state = sstate_state_fromvars(d)
  636. for intercept in shared_state['interceptfuncs']:
  637. bb.build.exec_func(intercept, d, (d.getVar("WORKDIR"),))
  638. omask = os.umask(0o002)
  639. if omask != 0o002:
  640. bb.note("Using umask 0o002 (not %0o) for sstate packaging" % omask)
  641. sstate_package(shared_state, d)
  642. os.umask(omask)
  643. sstateinst = d.getVar("SSTATE_INSTDIR")
  644. d.setVar('SSTATE_FIXMEDIR', shared_state['fixmedir'])
  645. sstate_installpkgdir(shared_state, d)
  646. bb.utils.remove(d.getVar("SSTATE_BUILDDIR"), recurse=True)
  647. }
  648. sstate_task_postfunc[dirs] = "${WORKDIR}"
  649. #
  650. # Shell function to generate a sstate package from a directory
  651. # set as SSTATE_BUILDDIR. Will be run from within SSTATE_BUILDDIR.
  652. #
  653. sstate_create_package () {
  654. # Exit early if it already exists
  655. if [ -e ${SSTATE_PKG} ]; then
  656. [ ! -w ${SSTATE_PKG} ] || touch ${SSTATE_PKG}
  657. return
  658. fi
  659. mkdir --mode=0775 -p `dirname ${SSTATE_PKG}`
  660. TFILE=`mktemp ${SSTATE_PKG}.XXXXXXXX`
  661. # Use pigz if available
  662. OPT="-czS"
  663. if [ -x "$(command -v pigz)" ]; then
  664. OPT="-I pigz -cS"
  665. fi
  666. # Need to handle empty directories
  667. if [ "$(ls -A)" ]; then
  668. set +e
  669. tar $OPT -f $TFILE *
  670. ret=$?
  671. if [ $ret -ne 0 ] && [ $ret -ne 1 ]; then
  672. exit 1
  673. fi
  674. set -e
  675. else
  676. tar $OPT --file=$TFILE --files-from=/dev/null
  677. fi
  678. chmod 0664 $TFILE
  679. # Skip if it was already created by some other process
  680. if [ ! -e ${SSTATE_PKG} ]; then
  681. # Move into place using ln to attempt an atomic op.
  682. # Abort if it already exists
  683. ln $TFILE ${SSTATE_PKG} && rm $TFILE
  684. else
  685. rm $TFILE
  686. fi
  687. [ ! -w ${SSTATE_PKG} ] || touch ${SSTATE_PKG}
  688. }
  689. python sstate_sign_package () {
  690. from oe.gpg_sign import get_signer
  691. signer = get_signer(d, 'local')
  692. sstate_pkg = d.getVar('SSTATE_PKG')
  693. if os.path.exists(sstate_pkg + '.sig'):
  694. os.unlink(sstate_pkg + '.sig')
  695. signer.detach_sign(sstate_pkg, d.getVar('SSTATE_SIG_KEY', False), None,
  696. d.getVar('SSTATE_SIG_PASSPHRASE'), armor=False)
  697. }
  698. python sstate_report_unihash() {
  699. report_unihash = getattr(bb.parse.siggen, 'report_unihash', None)
  700. if report_unihash:
  701. ss = sstate_state_fromvars(d)
  702. report_unihash(os.getcwd(), ss['task'], d)
  703. }
  704. #
  705. # Shell function to decompress and prepare a package for installation
  706. # Will be run from within SSTATE_INSTDIR.
  707. #
  708. sstate_unpack_package () {
  709. tar -xvzf ${SSTATE_PKG}
  710. # update .siginfo atime on local/NFS mirror
  711. [ -O ${SSTATE_PKG}.siginfo ] && [ -w ${SSTATE_PKG}.siginfo ] && [ -h ${SSTATE_PKG}.siginfo ] && touch -a ${SSTATE_PKG}.siginfo
  712. # Use "! -w ||" to return true for read only files
  713. [ ! -w ${SSTATE_PKG} ] || touch --no-dereference ${SSTATE_PKG}
  714. [ ! -w ${SSTATE_PKG}.sig ] || [ ! -e ${SSTATE_PKG}.sig ] || touch --no-dereference ${SSTATE_PKG}.sig
  715. [ ! -w ${SSTATE_PKG}.siginfo ] || [ ! -e ${SSTATE_PKG}.siginfo ] || touch --no-dereference ${SSTATE_PKG}.siginfo
  716. }
  717. BB_HASHCHECK_FUNCTION = "sstate_checkhashes"
  718. def sstate_checkhashes(sq_data, d, siginfo=False, currentcount=0, summary=True, **kwargs):
  719. found = set()
  720. missed = set()
  721. def gethash(task):
  722. return sq_data['unihash'][task]
  723. def getpathcomponents(task, d):
  724. # Magic data from BB_HASHFILENAME
  725. splithashfn = sq_data['hashfn'][task].split(" ")
  726. spec = splithashfn[1]
  727. if splithashfn[0] == "True":
  728. extrapath = d.getVar("NATIVELSBSTRING") + "/"
  729. else:
  730. extrapath = ""
  731. tname = bb.runqueue.taskname_from_tid(task)[3:]
  732. if tname in ["fetch", "unpack", "patch", "populate_lic", "preconfigure"] and splithashfn[2]:
  733. spec = splithashfn[2]
  734. extrapath = ""
  735. return spec, extrapath, tname
  736. for tid in sq_data['hash']:
  737. spec, extrapath, tname = getpathcomponents(tid, d)
  738. sstatefile = d.expand("${SSTATE_DIR}/" + extrapath + generate_sstatefn(spec, gethash(tid), tname, siginfo, d))
  739. if os.path.exists(sstatefile):
  740. bb.debug(2, "SState: Found valid sstate file %s" % sstatefile)
  741. found.add(tid)
  742. continue
  743. else:
  744. missed.add(tid)
  745. bb.debug(2, "SState: Looked for but didn't find file %s" % sstatefile)
  746. mirrors = d.getVar("SSTATE_MIRRORS")
  747. if mirrors:
  748. # Copy the data object and override DL_DIR and SRC_URI
  749. localdata = bb.data.createCopy(d)
  750. dldir = localdata.expand("${SSTATE_DIR}")
  751. localdata.delVar('MIRRORS')
  752. localdata.setVar('FILESPATH', dldir)
  753. localdata.setVar('DL_DIR', dldir)
  754. localdata.setVar('PREMIRRORS', mirrors)
  755. bb.debug(2, "SState using premirror of: %s" % mirrors)
  756. # if BB_NO_NETWORK is set but we also have SSTATE_MIRROR_ALLOW_NETWORK,
  757. # we'll want to allow network access for the current set of fetches.
  758. if bb.utils.to_boolean(localdata.getVar('BB_NO_NETWORK')) and \
  759. bb.utils.to_boolean(localdata.getVar('SSTATE_MIRROR_ALLOW_NETWORK')):
  760. localdata.delVar('BB_NO_NETWORK')
  761. from bb.fetch2 import FetchConnectionCache
  762. def checkstatus_init(thread_worker):
  763. thread_worker.connection_cache = FetchConnectionCache()
  764. def checkstatus_end(thread_worker):
  765. thread_worker.connection_cache.close_connections()
  766. def checkstatus(thread_worker, arg):
  767. (tid, sstatefile) = arg
  768. localdata2 = bb.data.createCopy(localdata)
  769. srcuri = "file://" + sstatefile
  770. localdata.setVar('SRC_URI', srcuri)
  771. bb.debug(2, "SState: Attempting to fetch %s" % srcuri)
  772. try:
  773. fetcher = bb.fetch2.Fetch(srcuri.split(), localdata2,
  774. connection_cache=thread_worker.connection_cache)
  775. fetcher.checkstatus()
  776. bb.debug(2, "SState: Successful fetch test for %s" % srcuri)
  777. found.add(tid)
  778. if tid in missed:
  779. missed.remove(tid)
  780. except:
  781. missed.add(tid)
  782. bb.debug(2, "SState: Unsuccessful fetch test for %s" % srcuri)
  783. pass
  784. if len(tasklist) >= min_tasks:
  785. bb.event.fire(bb.event.ProcessProgress(msg, len(tasklist) - thread_worker.tasks.qsize()), d)
  786. tasklist = []
  787. min_tasks = 100
  788. for tid in sq_data['hash']:
  789. if tid in found:
  790. continue
  791. spec, extrapath, tname = getpathcomponents(tid, d)
  792. sstatefile = d.expand(extrapath + generate_sstatefn(spec, gethash(tid), tname, siginfo, d))
  793. tasklist.append((tid, sstatefile))
  794. if tasklist:
  795. if len(tasklist) >= min_tasks:
  796. msg = "Checking sstate mirror object availability"
  797. bb.event.fire(bb.event.ProcessStarted(msg, len(tasklist)), d)
  798. import multiprocessing
  799. nproc = min(multiprocessing.cpu_count(), len(tasklist))
  800. bb.event.enable_threadlock()
  801. pool = oe.utils.ThreadedPool(nproc, len(tasklist),
  802. worker_init=checkstatus_init, worker_end=checkstatus_end)
  803. for t in tasklist:
  804. pool.add_task(checkstatus, t)
  805. pool.start()
  806. pool.wait_completion()
  807. bb.event.disable_threadlock()
  808. if len(tasklist) >= min_tasks:
  809. bb.event.fire(bb.event.ProcessFinished(msg), d)
  810. inheritlist = d.getVar("INHERIT")
  811. if "toaster" in inheritlist:
  812. evdata = {'missed': [], 'found': []};
  813. for tid in missed:
  814. spec, extrapath, tname = getpathcomponents(tid, d)
  815. sstatefile = d.expand(extrapath + generate_sstatefn(spec, gethash(tid), tname, False, d))
  816. evdata['missed'].append((bb.runqueue.fn_from_tid(tid), bb.runqueue.taskname_from_tid(tid), gethash(tid), sstatefile ) )
  817. for tid in found:
  818. spec, extrapath, tname = getpathcomponents(tid, d)
  819. sstatefile = d.expand(extrapath + generate_sstatefn(spec, gethash(tid), tname, False, d))
  820. evdata['found'].append((bb.runqueue.fn_from_tid(tid), bb.runqueue.taskname_from_tid(tid), gethash(tid), sstatefile ) )
  821. bb.event.fire(bb.event.MetadataEvent("MissedSstate", evdata), d)
  822. if summary:
  823. # Print some summary statistics about the current task completion and how much sstate
  824. # reuse there was. Avoid divide by zero errors.
  825. total = len(sq_data['hash'])
  826. complete = 0
  827. if currentcount:
  828. complete = (len(found) + currentcount) / (total + currentcount) * 100
  829. match = 0
  830. if total:
  831. match = len(found) / total * 100
  832. bb.plain("Sstate summary: Wanted %d Found %d Missed %d Current %d (%d%% match, %d%% complete)" % (total, len(found), len(missed), currentcount, match, complete))
  833. if hasattr(bb.parse.siggen, "checkhashes"):
  834. bb.parse.siggen.checkhashes(sq_data, missed, found, d)
  835. return found
  836. BB_SETSCENE_DEPVALID = "setscene_depvalid"
  837. def setscene_depvalid(task, taskdependees, notneeded, d, log=None):
  838. # taskdependees is a dict of tasks which depend on task, each being a 3 item list of [PN, TASKNAME, FILENAME]
  839. # task is included in taskdependees too
  840. # Return - False - We need this dependency
  841. # - True - We can skip this dependency
  842. import re
  843. def logit(msg, log):
  844. if log is not None:
  845. log.append(msg)
  846. else:
  847. bb.debug(2, msg)
  848. logit("Considering setscene task: %s" % (str(taskdependees[task])), log)
  849. def isNativeCross(x):
  850. return x.endswith("-native") or "-cross-" in x or "-crosssdk" in x or x.endswith("-cross")
  851. # We only need to trigger populate_lic through direct dependencies
  852. if taskdependees[task][1] == "do_populate_lic":
  853. return True
  854. # stash_locale and gcc_stash_builddir are never needed as a dependency for built objects
  855. if taskdependees[task][1] == "do_stash_locale" or taskdependees[task][1] == "do_gcc_stash_builddir":
  856. return True
  857. # We only need to trigger packagedata through direct dependencies
  858. # but need to preserve packagedata on packagedata links
  859. if taskdependees[task][1] == "do_packagedata":
  860. for dep in taskdependees:
  861. if taskdependees[dep][1] == "do_packagedata":
  862. return False
  863. return True
  864. for dep in taskdependees:
  865. logit(" considering dependency: %s" % (str(taskdependees[dep])), log)
  866. if task == dep:
  867. continue
  868. if dep in notneeded:
  869. continue
  870. # do_package_write_* and do_package doesn't need do_package
  871. if taskdependees[task][1] == "do_package" and taskdependees[dep][1] in ['do_package', 'do_package_write_deb', 'do_package_write_ipk', 'do_package_write_rpm', 'do_packagedata', 'do_package_qa']:
  872. continue
  873. # do_package_write_* need do_populate_sysroot as they're mainly postinstall dependencies
  874. if taskdependees[task][1] == "do_populate_sysroot" and taskdependees[dep][1] in ['do_package_write_deb', 'do_package_write_ipk', 'do_package_write_rpm']:
  875. return False
  876. # do_package/packagedata/package_qa don't need do_populate_sysroot
  877. if taskdependees[task][1] == "do_populate_sysroot" and taskdependees[dep][1] in ['do_package', 'do_packagedata', 'do_package_qa']:
  878. continue
  879. # Native/Cross packages don't exist and are noexec anyway
  880. if isNativeCross(taskdependees[dep][0]) and taskdependees[dep][1] in ['do_package_write_deb', 'do_package_write_ipk', 'do_package_write_rpm', 'do_packagedata', 'do_package', 'do_package_qa']:
  881. continue
  882. # This is due to the [depends] in useradd.bbclass complicating matters
  883. # The logic *is* reversed here due to the way hard setscene dependencies are injected
  884. if (taskdependees[task][1] == 'do_package' or taskdependees[task][1] == 'do_populate_sysroot') and taskdependees[dep][0].endswith(('shadow-native', 'shadow-sysroot', 'base-passwd', 'pseudo-native')) and taskdependees[dep][1] == 'do_populate_sysroot':
  885. continue
  886. # Consider sysroot depending on sysroot tasks
  887. if taskdependees[task][1] == 'do_populate_sysroot' and taskdependees[dep][1] == 'do_populate_sysroot':
  888. # Allow excluding certain recursive dependencies. If a recipe needs it should add a
  889. # specific dependency itself, rather than relying on one of its dependees to pull
  890. # them in.
  891. # See also http://lists.openembedded.org/pipermail/openembedded-core/2018-January/146324.html
  892. not_needed = False
  893. excludedeps = d.getVar('_SSTATE_EXCLUDEDEPS_SYSROOT')
  894. if excludedeps is None:
  895. # Cache the regular expressions for speed
  896. excludedeps = []
  897. for excl in (d.getVar('SSTATE_EXCLUDEDEPS_SYSROOT') or "").split():
  898. excludedeps.append((re.compile(excl.split('->', 1)[0]), re.compile(excl.split('->', 1)[1])))
  899. d.setVar('_SSTATE_EXCLUDEDEPS_SYSROOT', excludedeps)
  900. for excl in excludedeps:
  901. if excl[0].match(taskdependees[dep][0]):
  902. if excl[1].match(taskdependees[task][0]):
  903. not_needed = True
  904. break
  905. if not_needed:
  906. continue
  907. # For meta-extsdk-toolchain we want all sysroot dependencies
  908. if taskdependees[dep][0] == 'meta-extsdk-toolchain':
  909. return False
  910. # Native/Cross populate_sysroot need their dependencies
  911. if isNativeCross(taskdependees[task][0]) and isNativeCross(taskdependees[dep][0]):
  912. return False
  913. # Target populate_sysroot depended on by cross tools need to be installed
  914. if isNativeCross(taskdependees[dep][0]):
  915. return False
  916. # Native/cross tools depended upon by target sysroot are not needed
  917. # Add an exception for shadow-native as required by useradd.bbclass
  918. if isNativeCross(taskdependees[task][0]) and taskdependees[task][0] != 'shadow-native':
  919. continue
  920. # Target populate_sysroot need their dependencies
  921. return False
  922. if taskdependees[task][1] == 'do_shared_workdir':
  923. continue
  924. if taskdependees[dep][1] == "do_populate_lic":
  925. continue
  926. # Safe fallthrough default
  927. logit(" Default setscene dependency fall through due to dependency: %s" % (str(taskdependees[dep])), log)
  928. return False
  929. return True
  930. addhandler sstate_eventhandler
  931. sstate_eventhandler[eventmask] = "bb.build.TaskSucceeded"
  932. python sstate_eventhandler() {
  933. d = e.data
  934. writtensstate = d.getVar('SSTATE_CURRTASK')
  935. if not writtensstate:
  936. taskname = d.getVar("BB_RUNTASK")[3:]
  937. spec = d.getVar('SSTATE_PKGSPEC')
  938. swspec = d.getVar('SSTATE_SWSPEC')
  939. if taskname in ["fetch", "unpack", "patch", "populate_lic", "preconfigure"] and swspec:
  940. d.setVar("SSTATE_PKGSPEC", "${SSTATE_SWSPEC}")
  941. d.setVar("SSTATE_EXTRAPATH", "")
  942. d.setVar("SSTATE_CURRTASK", taskname)
  943. siginfo = d.getVar('SSTATE_PKG') + ".siginfo"
  944. if not os.path.exists(siginfo):
  945. bb.siggen.dump_this_task(siginfo, d)
  946. else:
  947. try:
  948. os.utime(siginfo, None)
  949. except PermissionError:
  950. pass
  951. }
  952. SSTATE_PRUNE_OBSOLETEWORKDIR ?= "1"
  953. # Event handler which removes manifests and stamps file for
  954. # recipes which are no longer reachable in a build where they
  955. # once were.
  956. # Also optionally removes the workdir of those tasks/recipes
  957. #
  958. addhandler sstate_eventhandler2
  959. sstate_eventhandler2[eventmask] = "bb.event.ReachableStamps"
  960. python sstate_eventhandler2() {
  961. import glob
  962. d = e.data
  963. stamps = e.stamps.values()
  964. removeworkdir = (d.getVar("SSTATE_PRUNE_OBSOLETEWORKDIR", False) == "1")
  965. preservestampfile = d.expand('${SSTATE_MANIFESTS}/preserve-stamps')
  966. preservestamps = []
  967. if os.path.exists(preservestampfile):
  968. with open(preservestampfile, 'r') as f:
  969. preservestamps = f.readlines()
  970. seen = []
  971. # The machine index contains all the stamps this machine has ever seen in this build directory.
  972. # We should only remove things which this machine once accessed but no longer does.
  973. machineindex = set()
  974. bb.utils.mkdirhier(d.expand("${SSTATE_MANIFESTS}"))
  975. mi = d.expand("${SSTATE_MANIFESTS}/index-machine-${MACHINE}")
  976. if os.path.exists(mi):
  977. with open(mi, "r") as f:
  978. machineindex = set(line.strip() for line in f.readlines())
  979. for a in sorted(list(set(d.getVar("SSTATE_ARCHS").split()))):
  980. toremove = []
  981. i = d.expand("${SSTATE_MANIFESTS}/index-" + a)
  982. if not os.path.exists(i):
  983. continue
  984. with open(i, "r") as f:
  985. lines = f.readlines()
  986. for l in lines:
  987. try:
  988. (stamp, manifest, workdir) = l.split()
  989. if stamp not in stamps and stamp not in preservestamps and stamp in machineindex:
  990. toremove.append(l)
  991. if stamp not in seen:
  992. bb.debug(2, "Stamp %s is not reachable, removing related manifests" % stamp)
  993. seen.append(stamp)
  994. except ValueError:
  995. bb.fatal("Invalid line '%s' in sstate manifest '%s'" % (l, i))
  996. if toremove:
  997. msg = "Removing %d recipes from the %s sysroot" % (len(toremove), a)
  998. bb.event.fire(bb.event.ProcessStarted(msg, len(toremove)), d)
  999. removed = 0
  1000. for r in toremove:
  1001. (stamp, manifest, workdir) = r.split()
  1002. for m in glob.glob(manifest + ".*"):
  1003. if m.endswith(".postrm"):
  1004. continue
  1005. sstate_clean_manifest(m, d)
  1006. bb.utils.remove(stamp + "*")
  1007. if removeworkdir:
  1008. bb.utils.remove(workdir, recurse = True)
  1009. lines.remove(r)
  1010. removed = removed + 1
  1011. bb.event.fire(bb.event.ProcessProgress(msg, removed), d)
  1012. bb.event.fire(bb.event.ProcessFinished(msg), d)
  1013. with open(i, "w") as f:
  1014. for l in lines:
  1015. f.write(l)
  1016. machineindex |= set(stamps)
  1017. with open(mi, "w") as f:
  1018. for l in machineindex:
  1019. f.write(l + "\n")
  1020. if preservestamps:
  1021. os.remove(preservestampfile)
  1022. }