sstate.bbclass 54 KB

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