sstate.bbclass 55 KB

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