blob: 6e4eb09f8e7d24eb75a1b764770b9f66da8f7523 [file] [log] [blame]
Andrew Geisslereff27472021-10-29 15:35:00 -05001SSTATE_VERSION = "7"
2
3SSTATE_ZSTD_CLEVEL ??= "8"
Patrick Williamsc124f4f2015-09-15 14:41:29 -05004
5SSTATE_MANIFESTS ?= "${TMPDIR}/sstate-control"
6SSTATE_MANFILEPREFIX = "${SSTATE_MANIFESTS}/manifest-${SSTATE_MANMACH}-${PN}"
7
Andrew Geissler82c905d2020-04-13 13:39:40 -05008def generate_sstatefn(spec, hash, taskname, siginfo, d):
9 if taskname is None:
10 return ""
Andrew Geisslereff27472021-10-29 15:35:00 -050011 extension = ".tar.zst"
Andrew Geissler82c905d2020-04-13 13:39:40 -050012 # 8 chars reserved for siginfo
13 limit = 254 - 8
14 if siginfo:
15 limit = 254
Andrew Geisslereff27472021-10-29 15:35:00 -050016 extension = ".tar.zst.siginfo"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050017 if not hash:
18 hash = "INVALID"
Andrew Geissler82c905d2020-04-13 13:39:40 -050019 fn = spec + hash + "_" + taskname + extension
20 # If the filename is too long, attempt to reduce it
21 if len(fn) > limit:
22 components = spec.split(":")
23 # Fields 0,5,6 are mandatory, 1 is most useful, 2,3,4 are just for information
24 # 7 is for the separators
25 avail = (254 - len(hash + "_" + taskname + extension) - len(components[0]) - len(components[1]) - len(components[5]) - len(components[6]) - 7) // 3
26 components[2] = components[2][:avail]
27 components[3] = components[3][:avail]
28 components[4] = components[4][:avail]
29 spec = ":".join(components)
30 fn = spec + hash + "_" + taskname + extension
31 if len(fn) > limit:
32 bb.fatal("Unable to reduce sstate name to less than 255 chararacters")
33 return hash[:2] + "/" + hash[2:4] + "/" + fn
Patrick Williamsc124f4f2015-09-15 14:41:29 -050034
35SSTATE_PKGARCH = "${PACKAGE_ARCH}"
36SSTATE_PKGSPEC = "sstate:${PN}:${PACKAGE_ARCH}${TARGET_VENDOR}-${TARGET_OS}:${PV}:${PR}:${SSTATE_PKGARCH}:${SSTATE_VERSION}:"
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050037SSTATE_SWSPEC = "sstate:${PN}::${PV}:${PR}::${SSTATE_VERSION}:"
Andrew Geissler82c905d2020-04-13 13:39:40 -050038SSTATE_PKGNAME = "${SSTATE_EXTRAPATH}${@generate_sstatefn(d.getVar('SSTATE_PKGSPEC'), d.getVar('BB_UNIHASH'), d.getVar('SSTATE_CURRTASK'), False, d)}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050039SSTATE_PKG = "${SSTATE_DIR}/${SSTATE_PKGNAME}"
40SSTATE_EXTRAPATH = ""
41SSTATE_EXTRAPATHWILDCARD = ""
Andrew Geisslereff27472021-10-29 15:35:00 -050042SSTATE_PATHSPEC = "${SSTATE_DIR}/${SSTATE_EXTRAPATHWILDCARD}*/*/${SSTATE_PKGSPEC}*_${SSTATE_PATH_CURRTASK}.tar.zst*"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050043
Patrick Williamsc0f7c042017-02-23 20:41:17 -060044# explicitly make PV to depend on evaluated value of PV variable
45PV[vardepvalue] = "${PV}"
46
Patrick Williamsc124f4f2015-09-15 14:41:29 -050047# We don't want the sstate to depend on things like the distro string
48# of the system, we let the sstate paths take care of this.
49SSTATE_EXTRAPATH[vardepvalue] = ""
Brad Bishop19323692019-04-05 15:28:33 -040050SSTATE_EXTRAPATHWILDCARD[vardepvalue] = ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -050051
52# For multilib rpm the allarch packagegroup files can overwrite (in theory they're identical)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080053SSTATE_DUPWHITELIST = "${DEPLOY_DIR}/licenses/"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050054# Avoid docbook/sgml catalog warnings for now
55SSTATE_DUPWHITELIST += "${STAGING_ETCDIR_NATIVE}/sgml ${STAGING_DATADIR_NATIVE}/sgml"
Brad Bishop316dfdd2018-06-25 12:45:53 -040056# sdk-provides-dummy-nativesdk and nativesdk-buildtools-perl-dummy overlap for different SDKMACHINE
57SSTATE_DUPWHITELIST += "${DEPLOY_DIR_RPM}/sdk_provides_dummy_nativesdk/ ${DEPLOY_DIR_IPK}/sdk-provides-dummy-nativesdk/"
58SSTATE_DUPWHITELIST += "${DEPLOY_DIR_RPM}/buildtools_dummy_nativesdk/ ${DEPLOY_DIR_IPK}/buildtools-dummy-nativesdk/"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080059# target-sdk-provides-dummy overlaps that allarch is disabled when multilib is used
60SSTATE_DUPWHITELIST += "${COMPONENTS_DIR}/sdk-provides-dummy-target/ ${DEPLOY_DIR_RPM}/sdk_provides_dummy_target/ ${DEPLOY_DIR_IPK}/sdk-provides-dummy-target/"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050061# Archive the sources for many architectures in one deploy folder
62SSTATE_DUPWHITELIST += "${DEPLOY_DIR_SRC}"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080063# ovmf/grub-efi/systemd-boot/intel-microcode multilib recipes can generate identical overlapping files
64SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/ovmf"
65SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/grub-efi"
66SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/systemd-boot"
67SSTATE_DUPWHITELIST += "${DEPLOY_DIR_IMAGE}/microcode"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050068
Brad Bishop6e60e8b2018-02-01 10:27:11 -050069SSTATE_SCAN_FILES ?= "*.la *-config *_config postinst-*"
70SSTATE_SCAN_CMD ??= 'find ${SSTATE_BUILDDIR} \( -name "${@"\" -o -name \"".join(d.getVar("SSTATE_SCAN_FILES").split())}" \) -type f'
71SSTATE_SCAN_CMD_NATIVE ??= 'grep -Irl -e ${RECIPE_SYSROOT} -e ${RECIPE_SYSROOT_NATIVE} -e ${HOSTTOOLS_DIR} ${SSTATE_BUILDDIR}'
Patrick Williams93c203f2021-10-06 16:15:23 -050072SSTATE_HASHEQUIV_FILEMAP ?= " \
73 populate_sysroot:*/postinst-useradd-*:${TMPDIR} \
74 populate_sysroot:*/postinst-useradd-*:${COREBASE} \
75 populate_sysroot:*/postinst-useradd-*:regex-\s(PATH|PSEUDO_IGNORE_PATHS|HOME|LOGNAME|OMP_NUM_THREADS|USER)=.*\s \
76 populate_sysroot:*/crossscripts/*:${TMPDIR} \
77 populate_sysroot:*/crossscripts/*:${COREBASE} \
78 "
Patrick Williamsc124f4f2015-09-15 14:41:29 -050079
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050080BB_HASHFILENAME = "False ${SSTATE_PKGSPEC} ${SSTATE_SWSPEC}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050081
82SSTATE_ARCHS = " \
83 ${BUILD_ARCH} \
Andrew Geissler6ce62a22020-11-30 19:58:47 -060084 ${BUILD_ARCH}_${ORIGNATIVELSBSTRING} \
Patrick Williamsc124f4f2015-09-15 14:41:29 -050085 ${BUILD_ARCH}_${SDK_ARCH}_${SDK_OS} \
86 ${BUILD_ARCH}_${TARGET_ARCH} \
87 ${SDK_ARCH}_${SDK_OS} \
88 ${SDK_ARCH}_${PACKAGE_ARCH} \
89 allarch \
90 ${PACKAGE_ARCH} \
Brad Bishop316dfdd2018-06-25 12:45:53 -040091 ${PACKAGE_EXTRA_ARCHS} \
92 ${MACHINE_ARCH}"
Andrew Geissler6ce62a22020-11-30 19:58:47 -060093SSTATE_ARCHS[vardepsexclude] = "ORIGNATIVELSBSTRING"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050094
95SSTATE_MANMACH ?= "${SSTATE_PKGARCH}"
96
97SSTATECREATEFUNCS = "sstate_hardcode_path"
Brad Bishop19323692019-04-05 15:28:33 -040098SSTATECREATEFUNCS[vardeps] = "SSTATE_SCAN_FILES"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050099SSTATEPOSTCREATEFUNCS = ""
100SSTATEPREINSTFUNCS = ""
101SSTATEPOSTUNPACKFUNCS = "sstate_hardcode_path_unpack"
102SSTATEPOSTINSTFUNCS = ""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500103EXTRA_STAGING_FIXMES ?= "HOSTTOOLS_DIR"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500104
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500105# Check whether sstate exists for tasks that support sstate and are in the
106# locked signatures file.
107SIGGEN_LOCKEDSIGS_SSTATE_EXISTS_CHECK ?= 'error'
108
109# Check whether the task's computed hash matches the task's hash in the
110# locked signatures file.
111SIGGEN_LOCKEDSIGS_TASKSIG_CHECK ?= "error"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500112
113# The GnuPG key ID and passphrase to use to sign sstate archives (or unset to
114# not sign)
115SSTATE_SIG_KEY ?= ""
116SSTATE_SIG_PASSPHRASE ?= ""
117# Whether to verify the GnUPG signatures when extracting sstate archives
118SSTATE_VERIFY_SIG ?= "0"
Andrew Geisslereff27472021-10-29 15:35:00 -0500119# List of signatures to consider valid.
120SSTATE_VALID_SIGS ??= ""
121SSTATE_VALID_SIGS[vardepvalue] = ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500122
Brad Bishop19323692019-04-05 15:28:33 -0400123SSTATE_HASHEQUIV_METHOD ?= "oe.sstatesig.OEOuthashBasic"
124SSTATE_HASHEQUIV_METHOD[doc] = "The fully-qualified function used to calculate \
125 the output hash for a task, which in turn is used to determine equivalency. \
126 "
127
Brad Bishop19323692019-04-05 15:28:33 -0400128SSTATE_HASHEQUIV_REPORT_TASKDATA ?= "0"
129SSTATE_HASHEQUIV_REPORT_TASKDATA[doc] = "Report additional useful data to the \
130 hash equivalency server, such as PN, PV, taskname, etc. This information \
131 is very useful for developers looking at task data, but may leak sensitive \
132 data if the equivalence server is public. \
133 "
134
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500135python () {
136 if bb.data.inherits_class('native', d):
137 d.setVar('SSTATE_PKGARCH', d.getVar('BUILD_ARCH', False))
138 elif bb.data.inherits_class('crosssdk', d):
139 d.setVar('SSTATE_PKGARCH', d.expand("${BUILD_ARCH}_${SDK_ARCH}_${SDK_OS}"))
140 elif bb.data.inherits_class('cross', d):
141 d.setVar('SSTATE_PKGARCH', d.expand("${BUILD_ARCH}_${TARGET_ARCH}"))
142 elif bb.data.inherits_class('nativesdk', d):
143 d.setVar('SSTATE_PKGARCH', d.expand("${SDK_ARCH}_${SDK_OS}"))
144 elif bb.data.inherits_class('cross-canadian', d):
145 d.setVar('SSTATE_PKGARCH', d.expand("${SDK_ARCH}_${PACKAGE_ARCH}"))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500146 elif bb.data.inherits_class('allarch', d) and d.getVar("PACKAGE_ARCH") == "all":
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500147 d.setVar('SSTATE_PKGARCH', "allarch")
148 else:
149 d.setVar('SSTATE_MANMACH', d.expand("${PACKAGE_ARCH}"))
150
151 if bb.data.inherits_class('native', d) or bb.data.inherits_class('crosssdk', d) or bb.data.inherits_class('cross', d):
152 d.setVar('SSTATE_EXTRAPATH', "${NATIVELSBSTRING}/")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500153 d.setVar('BB_HASHFILENAME', "True ${SSTATE_PKGSPEC} ${SSTATE_SWSPEC}")
Brad Bishop19323692019-04-05 15:28:33 -0400154 d.setVar('SSTATE_EXTRAPATHWILDCARD', "${NATIVELSBSTRING}/")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500155
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500156 unique_tasks = sorted(set((d.getVar('SSTATETASKS') or "").split()))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500157 d.setVar('SSTATETASKS', " ".join(unique_tasks))
158 for task in unique_tasks:
159 d.prependVarFlag(task, 'prefuncs', "sstate_task_prefunc ")
160 d.appendVarFlag(task, 'postfuncs', " sstate_task_postfunc")
161}
162
163def sstate_init(task, d):
164 ss = {}
165 ss['task'] = task
166 ss['dirs'] = []
167 ss['plaindirs'] = []
168 ss['lockfiles'] = []
169 ss['lockfiles-shared'] = []
170 return ss
171
172def sstate_state_fromvars(d, task = None):
173 if task is None:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500174 task = d.getVar('BB_CURRENTTASK')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500175 if not task:
176 bb.fatal("sstate code running without task context?!")
177 task = task.replace("_setscene", "")
178
179 if task.startswith("do_"):
180 task = task[3:]
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500181 inputs = (d.getVarFlag("do_" + task, 'sstate-inputdirs') or "").split()
182 outputs = (d.getVarFlag("do_" + task, 'sstate-outputdirs') or "").split()
183 plaindirs = (d.getVarFlag("do_" + task, 'sstate-plaindirs') or "").split()
184 lockfiles = (d.getVarFlag("do_" + task, 'sstate-lockfile') or "").split()
185 lockfilesshared = (d.getVarFlag("do_" + task, 'sstate-lockfile-shared') or "").split()
186 interceptfuncs = (d.getVarFlag("do_" + task, 'sstate-interceptfuncs') or "").split()
187 fixmedir = d.getVarFlag("do_" + task, 'sstate-fixmedir') or ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500188 if not task or len(inputs) != len(outputs):
189 bb.fatal("sstate variables not setup correctly?!")
190
191 if task == "populate_lic":
192 d.setVar("SSTATE_PKGSPEC", "${SSTATE_SWSPEC}")
193 d.setVar("SSTATE_EXTRAPATH", "")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500194 d.setVar('SSTATE_EXTRAPATHWILDCARD', "")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500195
196 ss = sstate_init(task, d)
197 for i in range(len(inputs)):
198 sstate_add(ss, inputs[i], outputs[i], d)
199 ss['lockfiles'] = lockfiles
200 ss['lockfiles-shared'] = lockfilesshared
201 ss['plaindirs'] = plaindirs
202 ss['interceptfuncs'] = interceptfuncs
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500203 ss['fixmedir'] = fixmedir
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500204 return ss
205
206def sstate_add(ss, source, dest, d):
207 if not source.endswith("/"):
208 source = source + "/"
209 if not dest.endswith("/"):
210 dest = dest + "/"
211 source = os.path.normpath(source)
212 dest = os.path.normpath(dest)
213 srcbase = os.path.basename(source)
214 ss['dirs'].append([srcbase, source, dest])
215 return ss
216
217def sstate_install(ss, d):
218 import oe.path
219 import oe.sstatesig
220 import subprocess
221
222 sharedfiles = []
223 shareddirs = []
224 bb.utils.mkdirhier(d.expand("${SSTATE_MANIFESTS}"))
225
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500226 sstateinst = d.expand("${WORKDIR}/sstate-install-%s/" % ss['task'])
227
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500228 manifest, d2 = oe.sstatesig.sstate_get_manifest_filename(ss['task'], d)
229
230 if os.access(manifest, os.R_OK):
231 bb.fatal("Package already staged (%s)?!" % manifest)
232
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600233 d.setVar("SSTATE_INST_POSTRM", manifest + ".postrm")
234
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500235 locks = []
236 for lock in ss['lockfiles-shared']:
237 locks.append(bb.utils.lockfile(lock, True))
238 for lock in ss['lockfiles']:
239 locks.append(bb.utils.lockfile(lock))
240
241 for state in ss['dirs']:
242 bb.debug(2, "Staging files from %s to %s" % (state[1], state[2]))
243 for walkroot, dirs, files in os.walk(state[1]):
244 for file in files:
245 srcpath = os.path.join(walkroot, file)
246 dstpath = srcpath.replace(state[1], state[2])
247 #bb.debug(2, "Staging %s to %s" % (srcpath, dstpath))
248 sharedfiles.append(dstpath)
249 for dir in dirs:
250 srcdir = os.path.join(walkroot, dir)
251 dstdir = srcdir.replace(state[1], state[2])
252 #bb.debug(2, "Staging %s to %s" % (srcdir, dstdir))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500253 if os.path.islink(srcdir):
254 sharedfiles.append(dstdir)
255 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500256 if not dstdir.endswith("/"):
257 dstdir = dstdir + "/"
258 shareddirs.append(dstdir)
259
260 # Check the file list for conflicts against files which already exist
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500261 whitelist = (d.getVar("SSTATE_DUPWHITELIST") or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500262 match = []
263 for f in sharedfiles:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500264 if os.path.exists(f) and not os.path.islink(f):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500265 f = os.path.normpath(f)
266 realmatch = True
267 for w in whitelist:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600268 w = os.path.normpath(w)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500269 if f.startswith(w):
270 realmatch = False
271 break
272 if realmatch:
273 match.append(f)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500274 sstate_search_cmd = "grep -rlF '%s' %s --exclude=master.list | sed -e 's:^.*/::'" % (f, d.expand("${SSTATE_MANIFESTS}"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500275 search_output = subprocess.Popen(sstate_search_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500276 if search_output:
277 match.append(" (matched in %s)" % search_output.decode('utf-8').rstrip())
278 else:
279 match.append(" (not matched to any task)")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500280 if match:
281 bb.error("The recipe %s is trying to install files into a shared " \
282 "area when those files already exist. Those files and their manifest " \
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500283 "location are:\n %s\nPlease verify which recipe should provide the " \
284 "above files.\n\nThe build has stopped, as continuing in this scenario WILL " \
285 "break things - if not now, possibly in the future (we've seen builds fail " \
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500286 "several months later). If the system knew how to recover from this " \
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500287 "automatically it would, however there are several different scenarios " \
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500288 "which can result in this and we don't know which one this is. It may be " \
289 "you have switched providers of something like virtual/kernel (e.g. from " \
290 "linux-yocto to linux-yocto-dev), in that case you need to execute the " \
291 "clean task for both recipes and it will resolve this error. It may be " \
292 "you changed DISTRO_FEATURES from systemd to udev or vice versa. Cleaning " \
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500293 "those recipes should again resolve this error, however switching " \
294 "DISTRO_FEATURES on an existing build directory is not supported - you " \
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500295 "should really clean out tmp and rebuild (reusing sstate should be safe). " \
296 "It could be the overlapping files detected are harmless in which case " \
297 "adding them to SSTATE_DUPWHITELIST may be the correct solution. It could " \
298 "also be your build is including two different conflicting versions of " \
299 "things (e.g. bluez 4 and bluez 5 and the correct solution for that would " \
300 "be to resolve the conflict. If in doubt, please ask on the mailing list, " \
301 "sharing the error and filelist above." % \
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500302 (d.getVar('PN'), "\n ".join(match)))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500303 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.")
304
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500305 if ss['fixmedir'] and os.path.exists(ss['fixmedir'] + "/fixmepath.cmd"):
306 sharedfiles.append(ss['fixmedir'] + "/fixmepath.cmd")
307 sharedfiles.append(ss['fixmedir'] + "/fixmepath")
308
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500309 # Write out the manifest
310 f = open(manifest, "w")
311 for file in sharedfiles:
312 f.write(file + "\n")
313
314 # We want to ensure that directories appear at the end of the manifest
315 # so that when we test to see if they should be deleted any contents
316 # added by the task will have been removed first.
317 dirs = sorted(shareddirs, key=len)
318 # Must remove children first, which will have a longer path than the parent
319 for di in reversed(dirs):
320 f.write(di + "\n")
321 f.close()
322
323 # Append to the list of manifests for this PACKAGE_ARCH
324
325 i = d2.expand("${SSTATE_MANIFESTS}/index-${SSTATE_MANMACH}")
326 l = bb.utils.lockfile(i + ".lock")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500327 filedata = d.getVar("STAMP") + " " + d2.getVar("SSTATE_MANFILEPREFIX") + " " + d.getVar("WORKDIR") + "\n"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500328 manifests = []
329 if os.path.exists(i):
330 with open(i, "r") as f:
331 manifests = f.readlines()
William A. Kennington IIIac69b482021-06-02 12:28:27 -0700332 # We append new entries, we don't remove older entries which may have the same
333 # manifest name but different versions from stamp/workdir. See below.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500334 if filedata not in manifests:
335 with open(i, "a+") as f:
336 f.write(filedata)
337 bb.utils.unlockfile(l)
338
339 # Run the actual file install
340 for state in ss['dirs']:
341 if os.path.exists(state[1]):
342 oe.path.copyhardlinktree(state[1], state[2])
343
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500344 for postinst in (d.getVar('SSTATEPOSTINSTFUNCS') or '').split():
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500345 # All hooks should run in the SSTATE_INSTDIR
346 bb.build.exec_func(postinst, d, (sstateinst,))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347
348 for lock in locks:
349 bb.utils.unlockfile(lock)
350
351sstate_install[vardepsexclude] += "SSTATE_DUPWHITELIST STATE_MANMACH SSTATE_MANFILEPREFIX"
352sstate_install[vardeps] += "${SSTATEPOSTINSTFUNCS}"
353
354def sstate_installpkg(ss, d):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500355 from oe.gpg_sign import get_signer
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500356
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500357 sstateinst = d.expand("${WORKDIR}/sstate-install-%s/" % ss['task'])
Andrew Geissler82c905d2020-04-13 13:39:40 -0500358 d.setVar("SSTATE_CURRTASK", ss['task'])
359 sstatefetch = d.getVar('SSTATE_PKGNAME')
360 sstatepkg = d.getVar('SSTATE_PKG')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500361
362 if not os.path.exists(sstatepkg):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800363 pstaging_fetch(sstatefetch, d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500364
365 if not os.path.isfile(sstatepkg):
Brad Bishop08902b02019-08-20 09:16:51 -0400366 bb.note("Sstate package %s does not exist" % sstatepkg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500367 return False
368
369 sstate_clean(ss, d)
370
371 d.setVar('SSTATE_INSTDIR', sstateinst)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500372
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500373 if bb.utils.to_boolean(d.getVar("SSTATE_VERIFY_SIG"), False):
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500374 if not os.path.isfile(sstatepkg + '.sig'):
375 bb.warn("No signature file for sstate package %s, skipping acceleration..." % sstatepkg)
376 return False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500377 signer = get_signer(d, 'local')
Andrew Geisslereff27472021-10-29 15:35:00 -0500378 if not signer.verify(sstatepkg + '.sig', d.getVar("SSTATE_VALID_SIGS")):
Brad Bishop08902b02019-08-20 09:16:51 -0400379 bb.warn("Cannot verify signature on sstate package %s, skipping acceleration..." % sstatepkg)
380 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500381
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500382 # Empty sstateinst directory, ensure its clean
383 if os.path.exists(sstateinst):
384 oe.path.remove(sstateinst)
385 bb.utils.mkdirhier(sstateinst)
386
387 sstateinst = d.getVar("SSTATE_INSTDIR")
388 d.setVar('SSTATE_FIXMEDIR', ss['fixmedir'])
389
390 for f in (d.getVar('SSTATEPREINSTFUNCS') or '').split() + ['sstate_unpack_package']:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500391 # All hooks should run in the SSTATE_INSTDIR
392 bb.build.exec_func(f, d, (sstateinst,))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500393
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500394 return sstate_installpkgdir(ss, d)
395
396def sstate_installpkgdir(ss, d):
397 import oe.path
398 import subprocess
399
400 sstateinst = d.getVar("SSTATE_INSTDIR")
401 d.setVar('SSTATE_FIXMEDIR', ss['fixmedir'])
402
403 for f in (d.getVar('SSTATEPOSTUNPACKFUNCS') or '').split():
404 # All hooks should run in the SSTATE_INSTDIR
405 bb.build.exec_func(f, d, (sstateinst,))
406
407 def prepdir(dir):
408 # remove dir if it exists, ensure any parent directories do exist
409 if os.path.exists(dir):
410 oe.path.remove(dir)
411 bb.utils.mkdirhier(dir)
412 oe.path.remove(dir)
413
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500414 for state in ss['dirs']:
415 prepdir(state[1])
Andrew Geisslerc926e172021-05-07 16:11:35 -0500416 bb.utils.rename(sstateinst + state[0], state[1])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500417 sstate_install(ss, d)
418
419 for plain in ss['plaindirs']:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500420 workdir = d.getVar('WORKDIR')
Brad Bishop977dc1a2019-02-06 16:01:43 -0500421 sharedworkdir = os.path.join(d.getVar('TMPDIR'), "work-shared")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500422 src = sstateinst + "/" + plain.replace(workdir, '')
Brad Bishop977dc1a2019-02-06 16:01:43 -0500423 if sharedworkdir in plain:
424 src = sstateinst + "/" + plain.replace(sharedworkdir, '')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500425 dest = plain
426 bb.utils.mkdirhier(src)
427 prepdir(dest)
Andrew Geisslerc926e172021-05-07 16:11:35 -0500428 bb.utils.rename(src, dest)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500429
430 return True
431
432python sstate_hardcode_path_unpack () {
433 # Fixup hardcoded paths
434 #
435 # Note: The logic below must match the reverse logic in
436 # sstate_hardcode_path(d)
437 import subprocess
438
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500439 sstateinst = d.getVar('SSTATE_INSTDIR')
440 sstatefixmedir = d.getVar('SSTATE_FIXMEDIR')
441 fixmefn = sstateinst + "fixmepath"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500442 if os.path.isfile(fixmefn):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500443 staging_target = d.getVar('RECIPE_SYSROOT')
444 staging_host = d.getVar('RECIPE_SYSROOT_NATIVE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500445
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500446 if bb.data.inherits_class('native', d) or bb.data.inherits_class('cross-canadian', d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500447 sstate_sed_cmd = "sed -i -e 's:FIXMESTAGINGDIRHOST:%s:g'" % (staging_host)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500448 elif bb.data.inherits_class('cross', d) or bb.data.inherits_class('crosssdk', d):
449 sstate_sed_cmd = "sed -i -e 's:FIXMESTAGINGDIRTARGET:%s:g; s:FIXMESTAGINGDIRHOST:%s:g'" % (staging_target, staging_host)
450 else:
451 sstate_sed_cmd = "sed -i -e 's:FIXMESTAGINGDIRTARGET:%s:g'" % (staging_target)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500452
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500453 extra_staging_fixmes = d.getVar('EXTRA_STAGING_FIXMES') or ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500454 for fixmevar in extra_staging_fixmes.split():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500455 fixme_path = d.getVar(fixmevar)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500456 sstate_sed_cmd += " -e 's:FIXME_%s:%s:g'" % (fixmevar, fixme_path)
457
458 # Add sstateinst to each filename in fixmepath, use xargs to efficiently call sed
459 sstate_hardcode_cmd = "sed -e 's:^:%s:g' %s | xargs %s" % (sstateinst, fixmefn, sstate_sed_cmd)
460
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500461 # Defer do_populate_sysroot relocation command
462 if sstatefixmedir:
463 bb.utils.mkdirhier(sstatefixmedir)
464 with open(sstatefixmedir + "/fixmepath.cmd", "w") as f:
465 sstate_hardcode_cmd = sstate_hardcode_cmd.replace(fixmefn, sstatefixmedir + "/fixmepath")
466 sstate_hardcode_cmd = sstate_hardcode_cmd.replace(sstateinst, "FIXMEFINALSSTATEINST")
467 sstate_hardcode_cmd = sstate_hardcode_cmd.replace(staging_host, "FIXMEFINALSSTATEHOST")
468 sstate_hardcode_cmd = sstate_hardcode_cmd.replace(staging_target, "FIXMEFINALSSTATETARGET")
469 f.write(sstate_hardcode_cmd)
470 bb.utils.copyfile(fixmefn, sstatefixmedir + "/fixmepath")
471 return
472
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500473 bb.note("Replacing fixme paths in sstate package: %s" % (sstate_hardcode_cmd))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500474 subprocess.check_call(sstate_hardcode_cmd, shell=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500475
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800476 # Need to remove this or we'd copy it into the target directory and may
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500477 # conflict with another writer
478 os.remove(fixmefn)
479}
480
481def sstate_clean_cachefile(ss, d):
482 import oe.path
483
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300484 if d.getVarFlag('do_%s' % ss['task'], 'task'):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500485 d.setVar("SSTATE_PATH_CURRTASK", ss['task'])
486 sstatepkgfile = d.getVar('SSTATE_PATHSPEC')
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300487 bb.note("Removing %s" % sstatepkgfile)
488 oe.path.remove(sstatepkgfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500489
490def sstate_clean_cachefiles(d):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500491 for task in (d.getVar('SSTATETASKS') or "").split():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500492 ld = d.createCopy()
493 ss = sstate_state_fromvars(ld, task)
494 sstate_clean_cachefile(ss, ld)
495
Andrew Geissler5f350902021-07-23 13:09:54 -0400496def sstate_clean_manifest(manifest, d, canrace=False, prefix=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500497 import oe.path
498
499 mfile = open(manifest)
500 entries = mfile.readlines()
501 mfile.close()
502
503 for entry in entries:
504 entry = entry.strip()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500505 if prefix and not entry.startswith("/"):
506 entry = prefix + "/" + entry
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500507 bb.debug(2, "Removing manifest: %s" % entry)
508 # We can race against another package populating directories as we're removing them
509 # so we ignore errors here.
510 try:
511 if entry.endswith("/"):
512 if os.path.islink(entry[:-1]):
513 os.remove(entry[:-1])
Andrew Geissler5f350902021-07-23 13:09:54 -0400514 elif os.path.exists(entry) and len(os.listdir(entry)) == 0 and not canrace:
515 # Removing directories whilst builds are in progress exposes a race. Only
516 # do it in contexts where it is safe to do so.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500517 os.rmdir(entry[:-1])
518 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500519 os.remove(entry)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500520 except OSError:
521 pass
522
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600523 postrm = manifest + ".postrm"
524 if os.path.exists(manifest + ".postrm"):
525 import subprocess
526 os.chmod(postrm, 0o755)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500527 subprocess.check_call(postrm, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600528 oe.path.remove(postrm)
529
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500530 oe.path.remove(manifest)
531
532def sstate_clean(ss, d):
533 import oe.path
534 import glob
535
536 d2 = d.createCopy()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500537 stamp_clean = d.getVar("STAMPCLEAN")
538 extrainf = d.getVarFlag("do_" + ss['task'], 'stamp-extra-info')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500539 if extrainf:
540 d2.setVar("SSTATE_MANMACH", extrainf)
541 wildcard_stfile = "%s.do_%s*.%s" % (stamp_clean, ss['task'], extrainf)
542 else:
543 wildcard_stfile = "%s.do_%s*" % (stamp_clean, ss['task'])
544
545 manifest = d2.expand("${SSTATE_MANFILEPREFIX}.%s" % ss['task'])
546
547 if os.path.exists(manifest):
548 locks = []
549 for lock in ss['lockfiles-shared']:
550 locks.append(bb.utils.lockfile(lock))
551 for lock in ss['lockfiles']:
552 locks.append(bb.utils.lockfile(lock))
553
Andrew Geissler5f350902021-07-23 13:09:54 -0400554 sstate_clean_manifest(manifest, d, canrace=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500555
556 for lock in locks:
557 bb.utils.unlockfile(lock)
558
559 # Remove the current and previous stamps, but keep the sigdata.
560 #
561 # The glob() matches do_task* which may match multiple tasks, for
562 # example: do_package and do_package_write_ipk, so we need to
563 # exactly match *.do_task.* and *.do_task_setscene.*
564 rm_stamp = '.do_%s.' % ss['task']
565 rm_setscene = '.do_%s_setscene.' % ss['task']
566 # For BB_SIGNATURE_HANDLER = "noop"
567 rm_nohash = ".do_%s" % ss['task']
568 for stfile in glob.glob(wildcard_stfile):
569 # Keep the sigdata
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500570 if ".sigdata." in stfile or ".sigbasedata." in stfile:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500571 continue
572 # Preserve taint files in the stamps directory
573 if stfile.endswith('.taint'):
574 continue
575 if rm_stamp in stfile or rm_setscene in stfile or \
576 stfile.endswith(rm_nohash):
577 oe.path.remove(stfile)
578
579sstate_clean[vardepsexclude] = "SSTATE_MANFILEPREFIX"
580
581CLEANFUNCS += "sstate_cleanall"
582
583python sstate_cleanall() {
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500584 bb.note("Removing shared state for package %s" % d.getVar('PN'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500585
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500586 manifest_dir = d.getVar('SSTATE_MANIFESTS')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500587 if not os.path.exists(manifest_dir):
588 return
589
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500590 tasks = d.getVar('SSTATETASKS').split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500591 for name in tasks:
592 ld = d.createCopy()
593 shared_state = sstate_state_fromvars(ld, name)
594 sstate_clean(shared_state, ld)
595}
596
597python sstate_hardcode_path () {
598 import subprocess, platform
599
600 # Need to remove hardcoded paths and fix these when we install the
601 # staging packages.
602 #
603 # Note: the logic in this function needs to match the reverse logic
604 # in sstate_installpkg(ss, d)
605
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500606 staging_target = d.getVar('RECIPE_SYSROOT')
607 staging_host = d.getVar('RECIPE_SYSROOT_NATIVE')
608 sstate_builddir = d.getVar('SSTATE_BUILDDIR')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500609
Brad Bishop316dfdd2018-06-25 12:45:53 -0400610 sstate_sed_cmd = "sed -i -e 's:%s:FIXMESTAGINGDIRHOST:g'" % staging_host
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500611 if bb.data.inherits_class('native', d) or bb.data.inherits_class('cross-canadian', d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500612 sstate_grep_cmd = "grep -l -e '%s'" % (staging_host)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500613 elif bb.data.inherits_class('cross', d) or bb.data.inherits_class('crosssdk', d):
614 sstate_grep_cmd = "grep -l -e '%s' -e '%s'" % (staging_target, staging_host)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400615 sstate_sed_cmd += " -e 's:%s:FIXMESTAGINGDIRTARGET:g'" % staging_target
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500616 else:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400617 sstate_grep_cmd = "grep -l -e '%s' -e '%s'" % (staging_target, staging_host)
618 sstate_sed_cmd += " -e 's:%s:FIXMESTAGINGDIRTARGET:g'" % staging_target
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500619
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500620 extra_staging_fixmes = d.getVar('EXTRA_STAGING_FIXMES') or ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500621 for fixmevar in extra_staging_fixmes.split():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500622 fixme_path = d.getVar(fixmevar)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500623 sstate_sed_cmd += " -e 's:%s:FIXME_%s:g'" % (fixme_path, fixmevar)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500624 sstate_grep_cmd += " -e '%s'" % (fixme_path)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500625
626 fixmefn = sstate_builddir + "fixmepath"
627
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500628 sstate_scan_cmd = d.getVar('SSTATE_SCAN_CMD')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500629 sstate_filelist_cmd = "tee %s" % (fixmefn)
630
631 # fixmepath file needs relative paths, drop sstate_builddir prefix
632 sstate_filelist_relative_cmd = "sed -i -e 's:^%s::g' %s" % (sstate_builddir, fixmefn)
633
634 xargs_no_empty_run_cmd = '--no-run-if-empty'
635 if platform.system() == 'Darwin':
636 xargs_no_empty_run_cmd = ''
637
638 # Limit the fixpaths and sed operations based on the initial grep search
639 # This has the side effect of making sure the vfs cache is hot
640 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)
641
642 bb.note("Removing hardcoded paths from sstate package: '%s'" % (sstate_hardcode_cmd))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500643 subprocess.check_output(sstate_hardcode_cmd, shell=True, cwd=sstate_builddir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500644
645 # If the fixmefn is empty, remove it..
646 if os.stat(fixmefn).st_size == 0:
647 os.remove(fixmefn)
648 else:
649 bb.note("Replacing absolute paths in fixmepath file: '%s'" % (sstate_filelist_relative_cmd))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500650 subprocess.check_output(sstate_filelist_relative_cmd, shell=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500651}
652
653def sstate_package(ss, d):
654 import oe.path
Andrew Geissler5199d832021-09-24 16:47:35 -0500655 import time
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500656
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500657 tmpdir = d.getVar('TMPDIR')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500658
Andrew Geissler5199d832021-09-24 16:47:35 -0500659 fixtime = False
660 if ss['task'] == "package":
661 fixtime = True
662
663 def fixtimestamp(root, path):
664 f = os.path.join(root, path)
665 if os.lstat(f).st_mtime > sde:
666 os.utime(f, (sde, sde), follow_symlinks=False)
667
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500668 sstatebuild = d.expand("${WORKDIR}/sstate-build-%s/" % ss['task'])
Andrew Geissler5199d832021-09-24 16:47:35 -0500669 sde = int(d.getVar("SOURCE_DATE_EPOCH") or time.time())
Andrew Geissler82c905d2020-04-13 13:39:40 -0500670 d.setVar("SSTATE_CURRTASK", ss['task'])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500671 bb.utils.remove(sstatebuild, recurse=True)
672 bb.utils.mkdirhier(sstatebuild)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500673 for state in ss['dirs']:
674 if not os.path.exists(state[1]):
675 continue
676 srcbase = state[0].rstrip("/").rsplit('/', 1)[0]
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500677 # Find and error for absolute symlinks. We could attempt to relocate but its not
678 # clear where the symlink is relative to in this context. We could add that markup
679 # to sstate tasks but there aren't many of these so better just avoid them entirely.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500680 for walkroot, dirs, files in os.walk(state[1]):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500681 for file in files + dirs:
Andrew Geissler5199d832021-09-24 16:47:35 -0500682 if fixtime:
683 fixtimestamp(walkroot, file)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500684 srcpath = os.path.join(walkroot, file)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500685 if not os.path.islink(srcpath):
686 continue
687 link = os.readlink(srcpath)
688 if not os.path.isabs(link):
689 continue
690 if not link.startswith(tmpdir):
691 continue
692 bb.error("sstate found an absolute path symlink %s pointing at %s. Please replace this with a relative link." % (srcpath, link))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500693 bb.debug(2, "Preparing tree %s for packaging at %s" % (state[1], sstatebuild + state[0]))
Andrew Geisslerc926e172021-05-07 16:11:35 -0500694 bb.utils.rename(state[1], sstatebuild + state[0])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500695
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500696 workdir = d.getVar('WORKDIR')
Brad Bishop977dc1a2019-02-06 16:01:43 -0500697 sharedworkdir = os.path.join(d.getVar('TMPDIR'), "work-shared")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500698 for plain in ss['plaindirs']:
699 pdir = plain.replace(workdir, sstatebuild)
Brad Bishop977dc1a2019-02-06 16:01:43 -0500700 if sharedworkdir in plain:
701 pdir = plain.replace(sharedworkdir, sstatebuild)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500702 bb.utils.mkdirhier(plain)
703 bb.utils.mkdirhier(pdir)
Andrew Geisslerc926e172021-05-07 16:11:35 -0500704 bb.utils.rename(plain, pdir)
Andrew Geissler5199d832021-09-24 16:47:35 -0500705 if fixtime:
706 fixtimestamp(pdir, "")
707 for walkroot, dirs, files in os.walk(pdir):
708 for file in files + dirs:
709 fixtimestamp(walkroot, file)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500710
711 d.setVar('SSTATE_BUILDDIR', sstatebuild)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500712 d.setVar('SSTATE_INSTDIR', sstatebuild)
713
714 if d.getVar('SSTATE_SKIP_CREATION') == '1':
715 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500716
Brad Bishop08902b02019-08-20 09:16:51 -0400717 sstate_create_package = ['sstate_report_unihash', 'sstate_create_package']
718 if d.getVar('SSTATE_SIG_KEY'):
719 sstate_create_package.append('sstate_sign_package')
720
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500721 for f in (d.getVar('SSTATECREATEFUNCS') or '').split() + \
Brad Bishop08902b02019-08-20 09:16:51 -0400722 sstate_create_package + \
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500723 (d.getVar('SSTATEPOSTCREATEFUNCS') or '').split():
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500724 # All hooks should run in SSTATE_BUILDDIR.
725 bb.build.exec_func(f, d, (sstatebuild,))
726
Andrew Geissler82c905d2020-04-13 13:39:40 -0500727 # SSTATE_PKG may have been changed by sstate_report_unihash
728 siginfo = d.getVar('SSTATE_PKG') + ".siginfo"
729 if not os.path.exists(siginfo):
730 bb.siggen.dump_this_task(siginfo, d)
731 else:
Andrew Geisslerc182c622020-05-15 14:13:32 -0500732 try:
733 os.utime(siginfo, None)
734 except PermissionError:
735 pass
Andrew Geissler5f350902021-07-23 13:09:54 -0400736 except OSError as e:
737 # Handle read-only file systems gracefully
Patrick Williams0ca19cc2021-08-16 14:03:13 -0500738 import errno
Andrew Geissler5f350902021-07-23 13:09:54 -0400739 if e.errno != errno.EROFS:
740 raise e
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500741
742 return
743
William A. Kennington IIIac69b482021-06-02 12:28:27 -0700744sstate_package[vardepsexclude] += "SSTATE_SIG_KEY"
745
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800746def pstaging_fetch(sstatefetch, d):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500747 import bb.fetch2
748
749 # Only try and fetch if the user has configured a mirror
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500750 mirrors = d.getVar('SSTATE_MIRRORS')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500751 if not mirrors:
752 return
753
754 # Copy the data object and override DL_DIR and SRC_URI
755 localdata = bb.data.createCopy(d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500756
757 dldir = localdata.expand("${SSTATE_DIR}")
758 bb.utils.mkdirhier(dldir)
759
760 localdata.delVar('MIRRORS')
761 localdata.setVar('FILESPATH', dldir)
762 localdata.setVar('DL_DIR', dldir)
763 localdata.setVar('PREMIRRORS', mirrors)
Andrew Geissler5199d832021-09-24 16:47:35 -0500764 localdata.setVar('SRCPV', d.getVar('SRCPV'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500765
766 # if BB_NO_NETWORK is set but we also have SSTATE_MIRROR_ALLOW_NETWORK,
767 # we'll want to allow network access for the current set of fetches.
Brad Bishopd89cb5f2019-04-10 09:02:41 -0400768 if bb.utils.to_boolean(localdata.getVar('BB_NO_NETWORK')) and \
769 bb.utils.to_boolean(localdata.getVar('SSTATE_MIRROR_ALLOW_NETWORK')):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500770 localdata.delVar('BB_NO_NETWORK')
771
772 # Try a fetch from the sstate mirror, if it fails just return and
773 # we will build the package
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600774 uris = ['file://{0};downloadfilename={0}'.format(sstatefetch),
775 'file://{0}.siginfo;downloadfilename={0}.siginfo'.format(sstatefetch)]
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500776 if bb.utils.to_boolean(d.getVar("SSTATE_VERIFY_SIG"), False):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600777 uris += ['file://{0}.sig;downloadfilename={0}.sig'.format(sstatefetch)]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500778
779 for srcuri in uris:
780 localdata.setVar('SRC_URI', srcuri)
781 try:
782 fetcher = bb.fetch2.Fetch([srcuri], localdata, cache=False)
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500783 fetcher.checkstatus()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500784 fetcher.download()
785
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500786 except bb.fetch2.BBFetchException:
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500787 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500788
Andrew Geissler5199d832021-09-24 16:47:35 -0500789pstaging_fetch[vardepsexclude] += "SRCPV"
790
791
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500792def sstate_setscene(d):
793 shared_state = sstate_state_fromvars(d)
794 accelerate = sstate_installpkg(shared_state, d)
795 if not accelerate:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600796 bb.fatal("No suitable staging package found")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500797
798python sstate_task_prefunc () {
799 shared_state = sstate_state_fromvars(d)
800 sstate_clean(shared_state, d)
801}
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500802sstate_task_prefunc[dirs] = "${WORKDIR}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500803
804python sstate_task_postfunc () {
805 shared_state = sstate_state_fromvars(d)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500806
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500807 for intercept in shared_state['interceptfuncs']:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500808 bb.build.exec_func(intercept, d, (d.getVar("WORKDIR"),))
809
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600810 omask = os.umask(0o002)
811 if omask != 0o002:
812 bb.note("Using umask 0o002 (not %0o) for sstate packaging" % omask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500813 sstate_package(shared_state, d)
814 os.umask(omask)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500815
816 sstateinst = d.getVar("SSTATE_INSTDIR")
817 d.setVar('SSTATE_FIXMEDIR', shared_state['fixmedir'])
818
819 sstate_installpkgdir(shared_state, d)
820
821 bb.utils.remove(d.getVar("SSTATE_BUILDDIR"), recurse=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500822}
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500823sstate_task_postfunc[dirs] = "${WORKDIR}"
824
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500825
826#
827# Shell function to generate a sstate package from a directory
828# set as SSTATE_BUILDDIR. Will be run from within SSTATE_BUILDDIR.
829#
830sstate_create_package () {
Andrew Geissler82c905d2020-04-13 13:39:40 -0500831 # Exit early if it already exists
Brad Bishop08902b02019-08-20 09:16:51 -0400832 if [ -e ${SSTATE_PKG} ]; then
Andrew Geisslereff27472021-10-29 15:35:00 -0500833 touch ${SSTATE_PKG} 2>/dev/null || true
Brad Bishop08902b02019-08-20 09:16:51 -0400834 return
835 fi
836
Andrew Geisslerc3d88e42020-10-02 09:45:00 -0500837 mkdir --mode=0775 -p `dirname ${SSTATE_PKG}`
Andrew Geissler82c905d2020-04-13 13:39:40 -0500838 TFILE=`mktemp ${SSTATE_PKG}.XXXXXXXX`
839
Andrew Geisslereff27472021-10-29 15:35:00 -0500840 OPT="-cS"
841 ZSTD="zstd -${SSTATE_ZSTD_CLEVEL} -T${ZSTD_THREADS}"
842 # Use pzstd if available
843 if [ -x "$(command -v pzstd)" ]; then
844 ZSTD="pzstd -${SSTATE_ZSTD_CLEVEL} -p ${ZSTD_THREADS}"
Andrew Geissler82c905d2020-04-13 13:39:40 -0500845 fi
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800846
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500847 # Need to handle empty directories
848 if [ "$(ls -A)" ]; then
849 set +e
Andrew Geisslereff27472021-10-29 15:35:00 -0500850 tar -I "$ZSTD" $OPT -f $TFILE *
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500851 ret=$?
852 if [ $ret -ne 0 ] && [ $ret -ne 1 ]; then
853 exit 1
854 fi
855 set -e
856 else
Andrew Geisslereff27472021-10-29 15:35:00 -0500857 tar -I "$ZSTD" $OPT --file=$TFILE --files-from=/dev/null
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500858 fi
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500859 chmod 0664 $TFILE
Brad Bishop08902b02019-08-20 09:16:51 -0400860 # Skip if it was already created by some other process
861 if [ ! -e ${SSTATE_PKG} ]; then
Andrew Geissler82c905d2020-04-13 13:39:40 -0500862 # Move into place using ln to attempt an atomic op.
863 # Abort if it already exists
864 ln $TFILE ${SSTATE_PKG} && rm $TFILE
Brad Bishop08902b02019-08-20 09:16:51 -0400865 else
866 rm $TFILE
867 fi
Andrew Geisslereff27472021-10-29 15:35:00 -0500868 touch ${SSTATE_PKG} 2>/dev/null || true
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500869}
870
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500871python sstate_sign_package () {
872 from oe.gpg_sign import get_signer
873
Brad Bishop08902b02019-08-20 09:16:51 -0400874
875 signer = get_signer(d, 'local')
876 sstate_pkg = d.getVar('SSTATE_PKG')
877 if os.path.exists(sstate_pkg + '.sig'):
878 os.unlink(sstate_pkg + '.sig')
879 signer.detach_sign(sstate_pkg, d.getVar('SSTATE_SIG_KEY', False), None,
880 d.getVar('SSTATE_SIG_PASSPHRASE'), armor=False)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500881}
882
Brad Bishop19323692019-04-05 15:28:33 -0400883python sstate_report_unihash() {
884 report_unihash = getattr(bb.parse.siggen, 'report_unihash', None)
885
886 if report_unihash:
887 ss = sstate_state_fromvars(d)
888 report_unihash(os.getcwd(), ss['task'], d)
889}
890
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500891#
892# Shell function to decompress and prepare a package for installation
893# Will be run from within SSTATE_INSTDIR.
894#
895sstate_unpack_package () {
Andrew Geisslereff27472021-10-29 15:35:00 -0500896 ZSTD="zstd -T${ZSTD_THREADS}"
897 # Use pzstd if available
898 if [ -x "$(command -v pzstd)" ]; then
899 ZSTD="pzstd -p ${ZSTD_THREADS}"
900 fi
901
902 tar -I "$ZSTD" -xvf ${SSTATE_PKG}
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500903 # update .siginfo atime on local/NFS mirror
Andrew Geisslerc3d88e42020-10-02 09:45:00 -0500904 [ -O ${SSTATE_PKG}.siginfo ] && [ -w ${SSTATE_PKG}.siginfo ] && [ -h ${SSTATE_PKG}.siginfo ] && touch -a ${SSTATE_PKG}.siginfo
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500905 # Use "! -w ||" to return true for read only files
906 [ ! -w ${SSTATE_PKG} ] || touch --no-dereference ${SSTATE_PKG}
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500907 [ ! -w ${SSTATE_PKG}.sig ] || [ ! -e ${SSTATE_PKG}.sig ] || touch --no-dereference ${SSTATE_PKG}.sig
908 [ ! -w ${SSTATE_PKG}.siginfo ] || [ ! -e ${SSTATE_PKG}.siginfo ] || touch --no-dereference ${SSTATE_PKG}.siginfo
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500909}
910
911BB_HASHCHECK_FUNCTION = "sstate_checkhashes"
912
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500913def sstate_checkhashes(sq_data, d, siginfo=False, currentcount=0, summary=True, **kwargs):
Brad Bishop08902b02019-08-20 09:16:51 -0400914 found = set()
915 missed = set()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500916
Brad Bishop19323692019-04-05 15:28:33 -0400917 def gethash(task):
Brad Bishop08902b02019-08-20 09:16:51 -0400918 return sq_data['unihash'][task]
Brad Bishop19323692019-04-05 15:28:33 -0400919
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500920 def getpathcomponents(task, d):
921 # Magic data from BB_HASHFILENAME
Brad Bishop08902b02019-08-20 09:16:51 -0400922 splithashfn = sq_data['hashfn'][task].split(" ")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500923 spec = splithashfn[1]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500924 if splithashfn[0] == "True":
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500925 extrapath = d.getVar("NATIVELSBSTRING") + "/"
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500926 else:
927 extrapath = ""
Brad Bishop08902b02019-08-20 09:16:51 -0400928
929 tname = bb.runqueue.taskname_from_tid(task)[3:]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500930
931 if tname in ["fetch", "unpack", "patch", "populate_lic", "preconfigure"] and splithashfn[2]:
932 spec = splithashfn[2]
933 extrapath = ""
934
935 return spec, extrapath, tname
936
937
Brad Bishop08902b02019-08-20 09:16:51 -0400938 for tid in sq_data['hash']:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500939
Brad Bishop08902b02019-08-20 09:16:51 -0400940 spec, extrapath, tname = getpathcomponents(tid, d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500941
Andrew Geissler82c905d2020-04-13 13:39:40 -0500942 sstatefile = d.expand("${SSTATE_DIR}/" + extrapath + generate_sstatefn(spec, gethash(tid), tname, siginfo, d))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500943
944 if os.path.exists(sstatefile):
Brad Bishop08902b02019-08-20 09:16:51 -0400945 found.add(tid)
Andrew Geisslereff27472021-10-29 15:35:00 -0500946 bb.debug(2, "SState: Found valid sstate file %s" % sstatefile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500947 else:
Brad Bishop08902b02019-08-20 09:16:51 -0400948 missed.add(tid)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500949 bb.debug(2, "SState: Looked for but didn't find file %s" % sstatefile)
950
Andrew Geisslereff27472021-10-29 15:35:00 -0500951 foundLocal = len(found)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500952 mirrors = d.getVar("SSTATE_MIRRORS")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500953 if mirrors:
954 # Copy the data object and override DL_DIR and SRC_URI
955 localdata = bb.data.createCopy(d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500956
957 dldir = localdata.expand("${SSTATE_DIR}")
958 localdata.delVar('MIRRORS')
959 localdata.setVar('FILESPATH', dldir)
960 localdata.setVar('DL_DIR', dldir)
961 localdata.setVar('PREMIRRORS', mirrors)
962
963 bb.debug(2, "SState using premirror of: %s" % mirrors)
964
965 # if BB_NO_NETWORK is set but we also have SSTATE_MIRROR_ALLOW_NETWORK,
966 # we'll want to allow network access for the current set of fetches.
Brad Bishopd89cb5f2019-04-10 09:02:41 -0400967 if bb.utils.to_boolean(localdata.getVar('BB_NO_NETWORK')) and \
968 bb.utils.to_boolean(localdata.getVar('SSTATE_MIRROR_ALLOW_NETWORK')):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500969 localdata.delVar('BB_NO_NETWORK')
970
971 from bb.fetch2 import FetchConnectionCache
972 def checkstatus_init(thread_worker):
973 thread_worker.connection_cache = FetchConnectionCache()
974
975 def checkstatus_end(thread_worker):
976 thread_worker.connection_cache.close_connections()
977
978 def checkstatus(thread_worker, arg):
Brad Bishop08902b02019-08-20 09:16:51 -0400979 (tid, sstatefile) = arg
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500980
981 localdata2 = bb.data.createCopy(localdata)
982 srcuri = "file://" + sstatefile
983 localdata.setVar('SRC_URI', srcuri)
984 bb.debug(2, "SState: Attempting to fetch %s" % srcuri)
985
986 try:
987 fetcher = bb.fetch2.Fetch(srcuri.split(), localdata2,
988 connection_cache=thread_worker.connection_cache)
989 fetcher.checkstatus()
990 bb.debug(2, "SState: Successful fetch test for %s" % srcuri)
Brad Bishop08902b02019-08-20 09:16:51 -0400991 found.add(tid)
992 if tid in missed:
993 missed.remove(tid)
Andrew Geisslereff27472021-10-29 15:35:00 -0500994 except bb.fetch2.FetchError as e:
Brad Bishop08902b02019-08-20 09:16:51 -0400995 missed.add(tid)
Andrew Geisslereff27472021-10-29 15:35:00 -0500996 bb.debug(2, "SState: Unsuccessful fetch test for %s (%s)" % (srcuri, e))
997 except Exception as e:
998 bb.error("SState: cannot test %s: %s" % (srcuri, e))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500999 if len(tasklist) >= min_tasks:
1000 bb.event.fire(bb.event.ProcessProgress(msg, len(tasklist) - thread_worker.tasks.qsize()), d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001001
1002 tasklist = []
Andrew Geissler82c905d2020-04-13 13:39:40 -05001003 min_tasks = 100
Brad Bishop08902b02019-08-20 09:16:51 -04001004 for tid in sq_data['hash']:
1005 if tid in found:
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001006 continue
Brad Bishop08902b02019-08-20 09:16:51 -04001007 spec, extrapath, tname = getpathcomponents(tid, d)
Andrew Geissler82c905d2020-04-13 13:39:40 -05001008 sstatefile = d.expand(extrapath + generate_sstatefn(spec, gethash(tid), tname, siginfo, d))
Brad Bishop08902b02019-08-20 09:16:51 -04001009 tasklist.append((tid, sstatefile))
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001010
1011 if tasklist:
Andrew Geisslerd159c7f2021-09-02 21:05:58 -05001012 nproc = min(int(d.getVar("BB_NUMBER_THREADS")), len(tasklist))
1013
Andrew Geissler82c905d2020-04-13 13:39:40 -05001014 if len(tasklist) >= min_tasks:
1015 msg = "Checking sstate mirror object availability"
1016 bb.event.fire(bb.event.ProcessStarted(msg, len(tasklist)), d)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001017
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001018 bb.event.enable_threadlock()
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001019 pool = oe.utils.ThreadedPool(nproc, len(tasklist),
1020 worker_init=checkstatus_init, worker_end=checkstatus_end)
1021 for t in tasklist:
1022 pool.add_task(checkstatus, t)
1023 pool.start()
1024 pool.wait_completion()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001025 bb.event.disable_threadlock()
1026
Andrew Geissler82c905d2020-04-13 13:39:40 -05001027 if len(tasklist) >= min_tasks:
1028 bb.event.fire(bb.event.ProcessFinished(msg), d)
Brad Bishop96ff1982019-08-19 13:50:42 -04001029
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001030 inheritlist = d.getVar("INHERIT")
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001031 if "toaster" in inheritlist:
1032 evdata = {'missed': [], 'found': []};
Brad Bishop08902b02019-08-20 09:16:51 -04001033 for tid in missed:
1034 spec, extrapath, tname = getpathcomponents(tid, d)
Andrew Geissler82c905d2020-04-13 13:39:40 -05001035 sstatefile = d.expand(extrapath + generate_sstatefn(spec, gethash(tid), tname, False, d))
Brad Bishop08902b02019-08-20 09:16:51 -04001036 evdata['missed'].append((bb.runqueue.fn_from_tid(tid), bb.runqueue.taskname_from_tid(tid), gethash(tid), sstatefile ) )
1037 for tid in found:
1038 spec, extrapath, tname = getpathcomponents(tid, d)
Andrew Geissler82c905d2020-04-13 13:39:40 -05001039 sstatefile = d.expand(extrapath + generate_sstatefn(spec, gethash(tid), tname, False, d))
Brad Bishop08902b02019-08-20 09:16:51 -04001040 evdata['found'].append((bb.runqueue.fn_from_tid(tid), bb.runqueue.taskname_from_tid(tid), gethash(tid), sstatefile ) )
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001041 bb.event.fire(bb.event.MetadataEvent("MissedSstate", evdata), d)
1042
Brad Bishop1d80a2e2019-11-15 16:35:03 -05001043 if summary:
1044 # Print some summary statistics about the current task completion and how much sstate
1045 # reuse there was. Avoid divide by zero errors.
1046 total = len(sq_data['hash'])
1047 complete = 0
1048 if currentcount:
1049 complete = (len(found) + currentcount) / (total + currentcount) * 100
1050 match = 0
1051 if total:
1052 match = len(found) / total * 100
Andrew Geisslereff27472021-10-29 15:35:00 -05001053 bb.plain("Sstate summary: Wanted %d Local %d Mirrors %d Missed %d Current %d (%d%% match, %d%% complete)" %
1054 (total, foundLocal, len(found)-foundLocal, len(missed), currentcount, match, complete))
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001055
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001056 if hasattr(bb.parse.siggen, "checkhashes"):
Brad Bishop08902b02019-08-20 09:16:51 -04001057 bb.parse.siggen.checkhashes(sq_data, missed, found, d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001058
Brad Bishop08902b02019-08-20 09:16:51 -04001059 return found
Patrick Williams213cb262021-08-07 19:21:33 -05001060setscene_depvalid[vardepsexclude] = "SSTATE_EXCLUDEDEPS_SYSROOT"
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001061
1062BB_SETSCENE_DEPVALID = "setscene_depvalid"
1063
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001064def setscene_depvalid(task, taskdependees, notneeded, d, log=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001065 # taskdependees is a dict of tasks which depend on task, each being a 3 item list of [PN, TASKNAME, FILENAME]
1066 # task is included in taskdependees too
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001067 # Return - False - We need this dependency
1068 # - True - We can skip this dependency
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001069 import re
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001070
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001071 def logit(msg, log):
1072 if log is not None:
1073 log.append(msg)
1074 else:
1075 bb.debug(2, msg)
1076
1077 logit("Considering setscene task: %s" % (str(taskdependees[task])), log)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001078
Andrew Geissler5199d832021-09-24 16:47:35 -05001079 directtasks = ["do_populate_lic", "do_deploy_source_date_epoch", "do_shared_workdir", "do_stash_locale", "do_gcc_stash_builddir"]
1080
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001081 def isNativeCross(x):
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001082 return x.endswith("-native") or "-cross-" in x or "-crosssdk" in x or x.endswith("-cross")
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001083
Andrew Geissler5199d832021-09-24 16:47:35 -05001084 # We only need to trigger deploy_source_date_epoch through direct dependencies
1085 if taskdependees[task][1] in directtasks:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001086 return True
1087
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001088 # We only need to trigger packagedata through direct dependencies
1089 # but need to preserve packagedata on packagedata links
1090 if taskdependees[task][1] == "do_packagedata":
1091 for dep in taskdependees:
1092 if taskdependees[dep][1] == "do_packagedata":
1093 return False
1094 return True
1095
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001096 for dep in taskdependees:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001097 logit(" considering dependency: %s" % (str(taskdependees[dep])), log)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001098 if task == dep:
1099 continue
1100 if dep in notneeded:
1101 continue
1102 # do_package_write_* and do_package doesn't need do_package
1103 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']:
1104 continue
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001105 # do_package_write_* need do_populate_sysroot as they're mainly postinstall dependencies
1106 if taskdependees[task][1] == "do_populate_sysroot" and taskdependees[dep][1] in ['do_package_write_deb', 'do_package_write_ipk', 'do_package_write_rpm']:
1107 return False
Andrew Geissler5199d832021-09-24 16:47:35 -05001108 # do_package/packagedata/package_qa/deploy don't need do_populate_sysroot
1109 if taskdependees[task][1] == "do_populate_sysroot" and taskdependees[dep][1] in ['do_package', 'do_packagedata', 'do_package_qa', 'do_deploy']:
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001110 continue
1111 # Native/Cross packages don't exist and are noexec anyway
1112 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']:
1113 continue
1114
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001115 # This is due to the [depends] in useradd.bbclass complicating matters
1116 # The logic *is* reversed here due to the way hard setscene dependencies are injected
1117 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':
1118 continue
1119
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001120 # Consider sysroot depending on sysroot tasks
1121 if taskdependees[task][1] == 'do_populate_sysroot' and taskdependees[dep][1] == 'do_populate_sysroot':
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001122 # Allow excluding certain recursive dependencies. If a recipe needs it should add a
1123 # specific dependency itself, rather than relying on one of its dependees to pull
1124 # them in.
1125 # See also http://lists.openembedded.org/pipermail/openembedded-core/2018-January/146324.html
1126 not_needed = False
1127 excludedeps = d.getVar('_SSTATE_EXCLUDEDEPS_SYSROOT')
1128 if excludedeps is None:
1129 # Cache the regular expressions for speed
1130 excludedeps = []
1131 for excl in (d.getVar('SSTATE_EXCLUDEDEPS_SYSROOT') or "").split():
1132 excludedeps.append((re.compile(excl.split('->', 1)[0]), re.compile(excl.split('->', 1)[1])))
1133 d.setVar('_SSTATE_EXCLUDEDEPS_SYSROOT', excludedeps)
1134 for excl in excludedeps:
1135 if excl[0].match(taskdependees[dep][0]):
1136 if excl[1].match(taskdependees[task][0]):
1137 not_needed = True
1138 break
1139 if not_needed:
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001140 continue
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001141 # For meta-extsdk-toolchain we want all sysroot dependencies
1142 if taskdependees[dep][0] == 'meta-extsdk-toolchain':
1143 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001144 # Native/Cross populate_sysroot need their dependencies
1145 if isNativeCross(taskdependees[task][0]) and isNativeCross(taskdependees[dep][0]):
1146 return False
1147 # Target populate_sysroot depended on by cross tools need to be installed
1148 if isNativeCross(taskdependees[dep][0]):
1149 return False
1150 # Native/cross tools depended upon by target sysroot are not needed
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001151 # Add an exception for shadow-native as required by useradd.bbclass
1152 if isNativeCross(taskdependees[task][0]) and taskdependees[task][0] != 'shadow-native':
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001153 continue
1154 # Target populate_sysroot need their dependencies
1155 return False
1156
Andrew Geissler5199d832021-09-24 16:47:35 -05001157 if taskdependees[dep][1] in directtasks:
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001158 continue
1159
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001160 # Safe fallthrough default
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001161 logit(" Default setscene dependency fall through due to dependency: %s" % (str(taskdependees[dep])), log)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001162 return False
1163 return True
1164
1165addhandler sstate_eventhandler
1166sstate_eventhandler[eventmask] = "bb.build.TaskSucceeded"
1167python sstate_eventhandler() {
1168 d = e.data
Andrew Geissler82c905d2020-04-13 13:39:40 -05001169 writtensstate = d.getVar('SSTATE_CURRTASK')
1170 if not writtensstate:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001171 taskname = d.getVar("BB_RUNTASK")[3:]
1172 spec = d.getVar('SSTATE_PKGSPEC')
1173 swspec = d.getVar('SSTATE_SWSPEC')
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001174 if taskname in ["fetch", "unpack", "patch", "populate_lic", "preconfigure"] and swspec:
1175 d.setVar("SSTATE_PKGSPEC", "${SSTATE_SWSPEC}")
1176 d.setVar("SSTATE_EXTRAPATH", "")
Andrew Geissler82c905d2020-04-13 13:39:40 -05001177 d.setVar("SSTATE_CURRTASK", taskname)
1178 siginfo = d.getVar('SSTATE_PKG') + ".siginfo"
1179 if not os.path.exists(siginfo):
1180 bb.siggen.dump_this_task(siginfo, d)
1181 else:
Andrew Geisslerc182c622020-05-15 14:13:32 -05001182 try:
1183 os.utime(siginfo, None)
1184 except PermissionError:
1185 pass
Andrew Geissler5f350902021-07-23 13:09:54 -04001186 except OSError as e:
1187 # Handle read-only file systems gracefully
Patrick Williams0ca19cc2021-08-16 14:03:13 -05001188 import errno
Andrew Geissler5f350902021-07-23 13:09:54 -04001189 if e.errno != errno.EROFS:
1190 raise e
Andrew Geisslerc182c622020-05-15 14:13:32 -05001191
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001192}
1193
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001194SSTATE_PRUNE_OBSOLETEWORKDIR ?= "1"
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001195
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001196#
1197# Event handler which removes manifests and stamps file for recipes which are no
1198# longer 'reachable' in a build where they once were. 'Reachable' refers to
1199# whether a recipe is parsed so recipes in a layer which was removed would no
1200# longer be reachable. Switching between systemd and sysvinit where recipes
1201# became skipped would be another example.
1202#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001203# Also optionally removes the workdir of those tasks/recipes
1204#
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001205addhandler sstate_eventhandler_reachablestamps
1206sstate_eventhandler_reachablestamps[eventmask] = "bb.event.ReachableStamps"
1207python sstate_eventhandler_reachablestamps() {
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001208 import glob
1209 d = e.data
1210 stamps = e.stamps.values()
1211 removeworkdir = (d.getVar("SSTATE_PRUNE_OBSOLETEWORKDIR", False) == "1")
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001212 preservestampfile = d.expand('${SSTATE_MANIFESTS}/preserve-stamps')
1213 preservestamps = []
1214 if os.path.exists(preservestampfile):
1215 with open(preservestampfile, 'r') as f:
1216 preservestamps = f.readlines()
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001217 seen = []
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001218
1219 # The machine index contains all the stamps this machine has ever seen in this build directory.
1220 # We should only remove things which this machine once accessed but no longer does.
1221 machineindex = set()
1222 bb.utils.mkdirhier(d.expand("${SSTATE_MANIFESTS}"))
1223 mi = d.expand("${SSTATE_MANIFESTS}/index-machine-${MACHINE}")
1224 if os.path.exists(mi):
1225 with open(mi, "r") as f:
1226 machineindex = set(line.strip() for line in f.readlines())
1227
Brad Bishop316dfdd2018-06-25 12:45:53 -04001228 for a in sorted(list(set(d.getVar("SSTATE_ARCHS").split()))):
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001229 toremove = []
1230 i = d.expand("${SSTATE_MANIFESTS}/index-" + a)
1231 if not os.path.exists(i):
1232 continue
William A. Kennington IIIac69b482021-06-02 12:28:27 -07001233 manseen = set()
1234 ignore = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001235 with open(i, "r") as f:
1236 lines = f.readlines()
William A. Kennington IIIac69b482021-06-02 12:28:27 -07001237 for l in reversed(lines):
Brad Bishop19323692019-04-05 15:28:33 -04001238 try:
1239 (stamp, manifest, workdir) = l.split()
William A. Kennington IIIac69b482021-06-02 12:28:27 -07001240 # The index may have multiple entries for the same manifest as the code above only appends
1241 # new entries and there may be an entry with matching manifest but differing version in stamp/workdir.
1242 # The last entry in the list is the valid one, any earlier entries with matching manifests
1243 # should be ignored.
1244 if manifest in manseen:
1245 ignore.append(l)
1246 continue
1247 manseen.add(manifest)
Brad Bishop19323692019-04-05 15:28:33 -04001248 if stamp not in stamps and stamp not in preservestamps and stamp in machineindex:
1249 toremove.append(l)
1250 if stamp not in seen:
1251 bb.debug(2, "Stamp %s is not reachable, removing related manifests" % stamp)
1252 seen.append(stamp)
1253 except ValueError:
1254 bb.fatal("Invalid line '%s' in sstate manifest '%s'" % (l, i))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001255
1256 if toremove:
Brad Bishop316dfdd2018-06-25 12:45:53 -04001257 msg = "Removing %d recipes from the %s sysroot" % (len(toremove), a)
1258 bb.event.fire(bb.event.ProcessStarted(msg, len(toremove)), d)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001259
Brad Bishop316dfdd2018-06-25 12:45:53 -04001260 removed = 0
1261 for r in toremove:
1262 (stamp, manifest, workdir) = r.split()
1263 for m in glob.glob(manifest + ".*"):
1264 if m.endswith(".postrm"):
1265 continue
1266 sstate_clean_manifest(m, d)
1267 bb.utils.remove(stamp + "*")
1268 if removeworkdir:
1269 bb.utils.remove(workdir, recurse = True)
1270 lines.remove(r)
1271 removed = removed + 1
1272 bb.event.fire(bb.event.ProcessProgress(msg, removed), d)
1273
1274 bb.event.fire(bb.event.ProcessFinished(msg), d)
1275
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001276 with open(i, "w") as f:
1277 for l in lines:
William A. Kennington IIIac69b482021-06-02 12:28:27 -07001278 if l in ignore:
1279 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001280 f.write(l)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001281 machineindex |= set(stamps)
1282 with open(mi, "w") as f:
1283 for l in machineindex:
1284 f.write(l + "\n")
1285
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001286 if preservestamps:
1287 os.remove(preservestampfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001288}
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001289
1290
1291#
1292# Bitbake can generate an event showing which setscene tasks are 'stale',
1293# i.e. which ones will be rerun. These are ones where a stamp file is present but
1294# it is stable (e.g. taskhash doesn't match). With that list we can go through
1295# the manifests for matching tasks and "uninstall" those manifests now. We do
1296# this now rather than mid build since the distribution of files between sstate
1297# objects may have changed, new tasks may run first and if those new tasks overlap
1298# with the stale tasks, we'd see overlapping files messages and failures. Thankfully
1299# removing these files is fast.
1300#
1301addhandler sstate_eventhandler_stalesstate
1302sstate_eventhandler_stalesstate[eventmask] = "bb.event.StaleSetSceneTasks"
1303python sstate_eventhandler_stalesstate() {
1304 d = e.data
1305 tasks = e.tasks
1306
1307 bb.utils.mkdirhier(d.expand("${SSTATE_MANIFESTS}"))
1308
1309 for a in list(set(d.getVar("SSTATE_ARCHS").split())):
1310 toremove = []
1311 i = d.expand("${SSTATE_MANIFESTS}/index-" + a)
1312 if not os.path.exists(i):
1313 continue
1314 with open(i, "r") as f:
1315 lines = f.readlines()
1316 for l in lines:
1317 try:
1318 (stamp, manifest, workdir) = l.split()
1319 for tid in tasks:
1320 for s in tasks[tid]:
1321 if s.startswith(stamp):
1322 taskname = bb.runqueue.taskname_from_tid(tid)[3:]
1323 manname = manifest + "." + taskname
1324 if os.path.exists(manname):
1325 bb.debug(2, "Sstate for %s is stale, removing related manifest %s" % (tid, manname))
1326 toremove.append((manname, tid, tasks[tid]))
1327 break
1328 except ValueError:
1329 bb.fatal("Invalid line '%s' in sstate manifest '%s'" % (l, i))
1330
1331 if toremove:
1332 msg = "Removing %d stale sstate objects for arch %s" % (len(toremove), a)
1333 bb.event.fire(bb.event.ProcessStarted(msg, len(toremove)), d)
1334
1335 removed = 0
1336 for (manname, tid, stamps) in toremove:
1337 sstate_clean_manifest(manname, d)
1338 for stamp in stamps:
1339 bb.utils.remove(stamp)
1340 removed = removed + 1
1341 bb.event.fire(bb.event.ProcessProgress(msg, removed), d)
1342
1343 bb.event.fire(bb.event.ProcessFinished(msg), d)
1344}