xref: /openbmc/openbmc/poky/meta/classes-recipe/rootfs-postcommands.bbclass (revision 8460358c3d24c71d9d38fd126c745854a6301564)
1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7# Zap the root password if empty-root-password feature is not enabled
8ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", "empty-root-password", "", "zap_empty_root_password ",d)}'
9
10# Allow dropbear/openssh to accept logins from accounts with an empty password string if allow-empty-password is enabled
11ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", "allow-empty-password", "ssh_allow_empty_password ", "",d)}'
12
13# Allow dropbear/openssh to accept root logins if allow-root-login is enabled
14ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", "allow-root-login", "ssh_allow_root_login ", "",d)}'
15
16# Autologin the root user on the serial console, if empty-root-password and serial-autologin-root are active
17ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", [ 'empty-root-password', 'serial-autologin-root' ], "serial_autologin_root ", "",d)}'
18
19# Enable postinst logging if post-install-logging is enabled
20ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", "post-install-logging", "postinst_enable_logging ", "",d)}'
21
22# Create /etc/timestamp during image construction to give a reasonably sane default time setting
23ROOTFS_POSTPROCESS_COMMAND += "rootfs_update_timestamp "
24
25# Tweak files in /etc if read-only-rootfs is enabled
26ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", "read_only_rootfs_hook ", "",d)}'
27
28# We also need to do the same for the kernel boot parameters,
29# otherwise kernel or initramfs end up mounting the rootfs read/write
30# (the default) if supported by the underlying storage.
31#
32# We do this with :append because the default value might get set later with ?=
33# and we don't want to disable such a default that by setting a value here.
34APPEND:append = '${@bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", " ro", "", d)}'
35
36# Generates test data file with data store variables expanded in json format
37ROOTFS_POSTPROCESS_COMMAND += "write_image_test_data "
38
39# Write manifest
40IMAGE_MANIFEST = "${IMGDEPLOYDIR}/${IMAGE_NAME}.manifest"
41ROOTFS_POSTUNINSTALL_COMMAND =+ "write_image_manifest"
42# Set default postinst log file
43POSTINST_LOGFILE ?= "${localstatedir}/log/postinstall.log"
44# Set default target for systemd images
45SYSTEMD_DEFAULT_TARGET ?= '${@bb.utils.contains_any("IMAGE_FEATURES", [ "x11-base", "weston" ], "graphical.target", "multi-user.target", d)}'
46ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("DISTRO_FEATURES", "systemd", "set_systemd_default_target systemd_sysusers_check", "", d)}'
47
48ROOTFS_POSTPROCESS_COMMAND += 'empty_var_volatile'
49
50ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("DISTRO_FEATURES", "overlayfs", "overlayfs_qa_check overlayfs_postprocess", "", d)}'
51
52inherit image-artifact-names
53
54# Sort the user and group entries in /etc by ID in order to make the content
55# deterministic. Package installs are not deterministic, causing the ordering
56# of entries to change between builds. In case that this isn't desired,
57# the command can be overridden.
58SORT_PASSWD_POSTPROCESS_COMMAND ??= "tidy_shadowutils_files"
59ROOTFS_POSTPROCESS_COMMAND += '${SORT_PASSWD_POSTPROCESS_COMMAND}'
60
61#
62# Note that useradd-staticids.bbclass has to be used to ensure that
63# the numeric IDs of dynamically created entries remain stable.
64#
65ROOTFS_POSTPROCESS_COMMAND += 'rootfs_reproducible'
66
67# Resolve the ID as described in the sysusers.d(5) manual: ID can be a numeric
68# uid, a couple uid:gid or uid:groupname or it is '-' meaning leaving it
69# automatic or it can be a path. In the latter, the uid/gid matches the
70# user/group owner of that file.
71def resolve_sysusers_id(d, sid):
72    # If the id is a path, the uid/gid matchs to the target's uid/gid in the
73    # rootfs.
74    if '/' in sid:
75        try:
76            osstat = os.stat(os.path.join(d.getVar('IMAGE_ROOTFS'), sid))
77        except FileNotFoundError:
78            bb.error('sysusers.d: file %s is required but it does not exist in the rootfs', sid)
79            return ('-', '-')
80        return (osstat.st_uid, osstat.st_gid)
81    # Else it is a uid:gid or uid:groupname syntax
82    if ':' in sid:
83        return sid.split(':')
84    else:
85        return (sid, '-')
86
87# Check a user exists in the rootfs password file and return its properties
88def check_user_exists(d, uname=None, uid=None):
89    with open(os.path.join(d.getVar('IMAGE_ROOTFS'), 'etc/passwd'), 'r') as pwfile:
90        for line in pwfile:
91            (name, _, u_id, gid, comment, homedir, ushell) = line.strip().split(':')
92            if uname == name or uid == u_id:
93                return (name, u_id, gid, comment or '-', homedir or '/', ushell or '-')
94    return None
95
96# Check a group exists in the rootfs group file and return its properties
97def check_group_exists(d, gname=None, gid=None):
98    with open(os.path.join(d.getVar('IMAGE_ROOTFS'), 'etc/group'), 'r') as gfile:
99        for line in gfile:
100            (name, _, g_id, _) = line.strip().split(':')
101            if name == gname or g_id == gid:
102                return (name, g_id)
103    return None
104
105def compare_users(user, e_user):
106    # user and e_user must not have None values. Unset values must be '-'.
107    (name, uid, gid, comment, homedir, ushell) = user
108    (e_name, e_uid, e_gid, e_comment, e_homedir, e_ushell) = e_user
109    # Ignore 'uid', 'gid' or 'homedir' if they are not set
110    # Ignore 'shell' and 'ushell' if one is not set
111    return name == e_name \
112        and (uid == '-' or uid == e_uid) \
113        and (gid == '-' or gid == e_gid) \
114        and (homedir == '-' or e_homedir == '-' or homedir == e_homedir) \
115        and (ushell == '-' or e_ushell == '-' or ushell == e_ushell)
116
117# Open sysusers.d configuration files and parse each line to check the users and
118# groups are already defined in /etc/passwd and /etc/groups with similar
119# properties. Refer to the sysusers.d(5) manual for its syntax.
120python systemd_sysusers_check() {
121    import glob
122    import re
123
124    pattern_comment = r'(-|\"[^:\"]+\")'
125    pattern_word    = r'[^\s]+'
126    pattern_line   = r'(' + pattern_word + r')\s+(' + pattern_word + r')\s+(' + pattern_word + r')(\s+' \
127        + pattern_comment + r')?' + r'(\s+(' + pattern_word + r'))?' + r'(\s+(' + pattern_word + r'))?'
128
129    for conffile in glob.glob(os.path.join(d.getVar('IMAGE_ROOTFS'), 'usr/lib/sysusers.d/*.conf')):
130        with open(conffile, 'r') as f:
131            for line in f:
132                line = line.strip()
133                if not len(line) or line[0] == '#': continue
134                ret = re.fullmatch(pattern_line, line.strip())
135                if not ret: continue
136                (stype, sname, sid, _, scomment, _, shomedir, _, sshell) = ret.groups()
137                if stype == 'u':
138                    if sid:
139                        (suid, sgid) = resolve_sysusers_id(d, sid)
140                        if sgid.isalpha():
141                            sgid = check_group_exists(d, gname=sgid)
142                        elif sgid.isdigit():
143                            check_group_exists(d, gid=sgid)
144                        else:
145                            sgid = '-'
146                    else:
147                        suid = '-'
148                        sgid = '-'
149                    scomment = scomment.replace('"', '') if scomment else '-'
150                    shomedir = shomedir or '-'
151                    sshell = sshell or '-'
152                    e_user = check_user_exists(d, uname=sname)
153                    if not e_user:
154                        bb.warn('User %s has never been defined' % sname)
155                    elif not compare_users((sname, suid, sgid, scomment, shomedir, sshell), e_user):
156                        bb.warn('User %s has been defined as (%s) but sysusers.d expects it as (%s)'
157                                % (sname, ', '.join(e_user),
158                                ', '.join((sname, suid, sgid, scomment, shomedir, sshell))))
159                elif stype == 'g':
160                    gid = sid or '-'
161                    if '/' in gid:
162                        (_, gid) = resolve_sysusers_id(d, sid)
163                    e_group = check_group_exists(d, gname=sname)
164                    if not e_group:
165                        bb.warn('Group %s has never been defined' % sname)
166                    elif gid != '-':
167                        (_, e_gid) = e_group
168                        if gid != e_gid:
169                            bb.warn('Group %s has been defined with id (%s) but sysusers.d expects gid (%s)'
170                                    % (sname, e_gid, gid))
171                elif stype == 'm':
172                    check_user_exists(d, sname)
173                    check_group_exists(d, sid)
174}
175
176#
177# A hook function to support read-only-rootfs IMAGE_FEATURES
178#
179read_only_rootfs_hook () {
180	# Tweak the mount option and fs_passno for rootfs in fstab
181	if [ -f ${IMAGE_ROOTFS}/etc/fstab ]; then
182		sed -i -e '/^[#[:space:]]*\/dev\/root/{s/defaults/ro/;s/\([[:space:]]*[[:digit:]]\)\([[:space:]]*\)[[:digit:]]$/\1\20/}' ${IMAGE_ROOTFS}/etc/fstab
183	fi
184
185	# Tweak the "mount -o remount,rw /" command in busybox-inittab inittab
186	if [ -f ${IMAGE_ROOTFS}/etc/inittab ]; then
187		sed -i 's|/bin/mount -o remount,rw /|/bin/mount -o remount,ro /|' ${IMAGE_ROOTFS}/etc/inittab
188	fi
189
190	# If we're using openssh and the /etc/ssh directory has no pre-generated keys,
191	# we should configure openssh to use the configuration file /etc/ssh/sshd_config_readonly
192	# and the keys under /var/run/ssh.
193	# If overlayfs-etc is used this is not done as /etc is treated as writable
194	# If stateless-rootfs is enabled this is always done as we don't want to save keys then
195	if ${@ 'true' if not bb.utils.contains('IMAGE_FEATURES', 'overlayfs-etc', True, False, d) or bb.utils.contains('IMAGE_FEATURES', 'stateless-rootfs', True, False, d) else 'false'}; then
196		if [ -d ${IMAGE_ROOTFS}/etc/ssh ]; then
197			if [ -e ${IMAGE_ROOTFS}/etc/ssh/ssh_host_rsa_key ]; then
198				echo "SYSCONFDIR=\${SYSCONFDIR:-/etc/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
199				echo "SSHD_OPTS=" >> ${IMAGE_ROOTFS}/etc/default/ssh
200			else
201				echo "SYSCONFDIR=\${SYSCONFDIR:-/var/run/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
202				echo "SSHD_OPTS='-f /etc/ssh/sshd_config_readonly'" >> ${IMAGE_ROOTFS}/etc/default/ssh
203			fi
204		fi
205
206		# Also tweak the key location for dropbear in the same way.
207		if [ -d ${IMAGE_ROOTFS}/etc/dropbear ]; then
208			if [ ! -e ${IMAGE_ROOTFS}/etc/dropbear/dropbear_rsa_host_key ]; then
209				if ! grep -q "^DROPBEAR_RSAKEY_DIR=" ${IMAGE_ROOTFS}/etc/default/dropbear ; then
210					echo "DROPBEAR_RSAKEY_DIR=/var/lib/dropbear" >> ${IMAGE_ROOTFS}/etc/default/dropbear
211				fi
212			fi
213		fi
214	fi
215
216	if ${@bb.utils.contains("DISTRO_FEATURES", "sysvinit", "true", "false", d)}; then
217		# Change the value of ROOTFS_READ_ONLY in /etc/default/rcS to yes
218		if [ -e ${IMAGE_ROOTFS}/etc/default/rcS ]; then
219			sed -i 's/ROOTFS_READ_ONLY=no/ROOTFS_READ_ONLY=yes/' ${IMAGE_ROOTFS}/etc/default/rcS
220		fi
221		# Run populate-volatile.sh at rootfs time to set up basic files
222		# and directories to support read-only rootfs.
223		if [ -x ${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh ]; then
224			${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh
225		fi
226	fi
227
228	if ${@bb.utils.contains("DISTRO_FEATURES", "systemd", "true", "false", d)}; then
229	# Create machine-id
230	# 20:12 < mezcalero> koen: you have three options: a) run systemd-machine-id-setup at install time, b) have / read-only and an empty file there (for stateless) and c) boot with / writable
231		touch ${IMAGE_ROOTFS}${sysconfdir}/machine-id
232	fi
233}
234
235#
236# This function disallows empty root passwords
237#
238zap_empty_root_password () {
239	if [ -e ${IMAGE_ROOTFS}/etc/shadow ]; then
240		sed --follow-symlinks -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/shadow
241        fi
242	if [ -e ${IMAGE_ROOTFS}/etc/passwd ]; then
243		sed --follow-symlinks -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/passwd
244	fi
245}
246
247#
248# allow dropbear/openssh to accept logins from accounts with an empty password string
249#
250ssh_allow_empty_password () {
251	for config in sshd_config sshd_config_readonly; do
252		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
253			sed -i 's/^[#[:space:]]*PermitEmptyPasswords.*/PermitEmptyPasswords yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
254		fi
255	done
256
257	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
258		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
259			if ! grep -q "DROPBEAR_EXTRA_ARGS=.*-B" ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear ; then
260				sed -i 's/^DROPBEAR_EXTRA_ARGS="*\([^"]*\)"*/DROPBEAR_EXTRA_ARGS="\1 -B"/' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
261			fi
262		else
263			printf '\nDROPBEAR_EXTRA_ARGS="-B"\n' >> ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
264		fi
265	fi
266
267	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/pam.d ] ; then
268		for f in `find ${IMAGE_ROOTFS}${sysconfdir}/pam.d/* -type f -exec test -e {} \; -print`
269		do
270			sed -i 's/nullok_secure/nullok/' $f
271		done
272	fi
273}
274
275#
276# allow dropbear/openssh to accept root logins
277#
278ssh_allow_root_login () {
279	for config in sshd_config sshd_config_readonly; do
280		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
281			sed -i 's/^[#[:space:]]*PermitRootLogin.*/PermitRootLogin yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
282		fi
283	done
284
285	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
286		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
287			sed -i '/^DROPBEAR_EXTRA_ARGS=/ s/-w//' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
288			sed -i '/^# Disallow root/d' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
289		fi
290	fi
291}
292
293#
294# Autologin the 'root' user on the serial terminal,
295# if empty-root-password' AND 'serial-autologin-root are enabled
296#
297serial_autologin_root () {
298	if ${@bb.utils.contains("DISTRO_FEATURES", "sysvinit", "true", "false", d)}; then
299		# add autologin option to util-linux getty only
300		sed -i 's/options="/&--autologin root /' \
301			"${IMAGE_ROOTFS}${base_bindir}/start_getty"
302	elif ${@bb.utils.contains("DISTRO_FEATURES", "systemd", "true", "false", d)}; then
303		if [ -e ${IMAGE_ROOTFS}${systemd_system_unitdir}/serial-getty@.service ]; then
304			sed -i '/^\s*ExecStart\b/ s/getty /&--autologin root /' \
305				"${IMAGE_ROOTFS}${systemd_system_unitdir}/serial-getty@.service"
306		fi
307	fi
308}
309
310python tidy_shadowutils_files () {
311    import oe.rootfspostcommands
312    oe.rootfspostcommands.tidy_shadowutils_files(d.expand('${IMAGE_ROOTFS}${sysconfdir}'))
313}
314
315python sort_passwd () {
316    """
317    Deprecated in the favour of tidy_shadowutils_files.
318    """
319    import oe.rootfspostcommands
320    bb.warn('[sort_passwd] You are using a deprecated function for '
321        'SORT_PASSWD_POSTPROCESS_COMMAND. The default one is now called '
322        '"tidy_shadowutils_files".')
323    oe.rootfspostcommands.tidy_shadowutils_files(d.expand('${IMAGE_ROOTFS}${sysconfdir}'))
324}
325
326#
327# Enable postinst logging
328#
329postinst_enable_logging () {
330	mkdir -p ${IMAGE_ROOTFS}${sysconfdir}/default
331	echo "POSTINST_LOGGING=1" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
332	echo "LOGFILE=${POSTINST_LOGFILE}" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
333}
334
335#
336# Modify systemd default target
337#
338set_systemd_default_target () {
339	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/systemd/system -a -e ${IMAGE_ROOTFS}${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ]; then
340		ln -sf ${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ${IMAGE_ROOTFS}${sysconfdir}/systemd/system/default.target
341	fi
342}
343
344# If /var/volatile is not empty, we have seen problems where programs such as the
345# journal make assumptions based on the contents of /var/volatile. The journal
346# would then write to /var/volatile before it was mounted, thus hiding the
347# items previously written.
348#
349# This change is to attempt to fix those types of issues in a way that doesn't
350# affect users that may not be using /var/volatile.
351empty_var_volatile () {
352	if [ -e ${IMAGE_ROOTFS}/etc/fstab ]; then
353		match=`awk '$1 !~ "#" && $2 ~ /\/var\/volatile/{print $2}' ${IMAGE_ROOTFS}/etc/fstab 2> /dev/null`
354		if [ -n "$match" ]; then
355			find ${IMAGE_ROOTFS}/var/volatile -mindepth 1 -delete
356		fi
357	fi
358}
359
360# Turn any symbolic /sbin/init link into a file
361remove_init_link () {
362	if [ -h ${IMAGE_ROOTFS}/sbin/init ]; then
363		LINKFILE=${IMAGE_ROOTFS}`readlink ${IMAGE_ROOTFS}/sbin/init`
364		rm ${IMAGE_ROOTFS}/sbin/init
365		cp $LINKFILE ${IMAGE_ROOTFS}/sbin/init
366	fi
367}
368
369python write_image_manifest () {
370    from oe.rootfs import image_list_installed_packages
371    from oe.utils import format_pkg_list
372
373    deploy_dir = d.getVar('IMGDEPLOYDIR')
374    link_name = d.getVar('IMAGE_LINK_NAME')
375    manifest_name = d.getVar('IMAGE_MANIFEST')
376
377    if not manifest_name:
378        return
379
380    pkgs = image_list_installed_packages(d)
381    with open(manifest_name, 'w+') as image_manifest:
382        image_manifest.write(format_pkg_list(pkgs, "ver"))
383
384    if os.path.exists(manifest_name) and link_name:
385        manifest_link = deploy_dir + "/" + link_name + ".manifest"
386        if manifest_link != manifest_name:
387            if os.path.lexists(manifest_link):
388                os.remove(manifest_link)
389            os.symlink(os.path.basename(manifest_name), manifest_link)
390}
391
392# Can be used to create /etc/timestamp during image construction to give a reasonably
393# sane default time setting
394rootfs_update_timestamp () {
395	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
396		# Convert UTC into %4Y%2m%2d%2H%2M%2S
397		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
398	else
399		sformatted=`date -u +%4Y%2m%2d%2H%2M%2S`
400	fi
401	echo $sformatted > ${IMAGE_ROOTFS}/etc/timestamp
402	bbnote "rootfs_update_timestamp: set /etc/timestamp to $sformatted"
403}
404
405# Prevent X from being started
406rootfs_no_x_startup () {
407	if [ -f ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm ]; then
408		chmod a-x ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm
409	fi
410}
411
412rootfs_trim_schemas () {
413	for schema in ${IMAGE_ROOTFS}/etc/gconf/schemas/*.schemas
414	do
415		# Need this in case no files exist
416		if [ -e $schema ]; then
417			oe-trim-schemas $schema > $schema.new
418			mv $schema.new $schema
419		fi
420	done
421}
422
423rootfs_check_host_user_contaminated () {
424	contaminated="${S}/host-user-contaminated.txt"
425	HOST_USER_UID="$(PSEUDO_UNLOAD=1 id -u)"
426	HOST_USER_GID="$(PSEUDO_UNLOAD=1 id -g)"
427
428	find "${IMAGE_ROOTFS}" -path "${IMAGE_ROOTFS}/home" -prune -o \
429	    -user "$HOST_USER_UID" -print -o -group "$HOST_USER_GID" -print >"$contaminated"
430
431	sed -e "s,${IMAGE_ROOTFS},," $contaminated | while read line; do
432		bbwarn "Path in the rootfs is owned by the same user or group as the user running bitbake:" $line `ls -lan ${IMAGE_ROOTFS}/$line`
433	done
434
435	if [ -s "$contaminated" ]; then
436		bbwarn "/etc/passwd:" `cat ${IMAGE_ROOTFS}/etc/passwd`
437		bbwarn "/etc/group:" `cat ${IMAGE_ROOTFS}/etc/group`
438	fi
439}
440
441# Make any absolute links in a sysroot relative
442rootfs_sysroot_relativelinks () {
443	sysroot-relativelinks.py ${SDK_OUTPUT}/${SDKTARGETSYSROOT}
444}
445
446# Generated test data json file
447python write_image_test_data() {
448    from oe.data import export2json
449
450    deploy_dir = d.getVar('IMGDEPLOYDIR')
451    link_name = d.getVar('IMAGE_LINK_NAME')
452    testdata_name = os.path.join(deploy_dir, "%s.testdata.json" % d.getVar('IMAGE_NAME'))
453
454    searchString = "%s/"%(d.getVar("TOPDIR")).replace("//","/")
455    export2json(d, testdata_name, searchString=searchString, replaceString="")
456
457    if os.path.exists(testdata_name) and link_name:
458        testdata_link = os.path.join(deploy_dir, "%s.testdata.json" % link_name)
459        if testdata_link != testdata_name:
460            if os.path.lexists(testdata_link):
461                os.remove(testdata_link)
462            os.symlink(os.path.basename(testdata_name), testdata_link)
463}
464write_image_test_data[vardepsexclude] += "TOPDIR"
465
466# Check for unsatisfied recommendations (RRECOMMENDS)
467python rootfs_log_check_recommends() {
468    log_path = d.expand("${T}/log.do_rootfs")
469    with open(log_path, 'r') as log:
470        for line in log:
471            if 'log_check' in line:
472                continue
473
474            if 'unsatisfied recommendation for' in line:
475                bb.warn('[log_check] %s: %s' % (d.getVar('PN'), line))
476}
477
478# Perform any additional adjustments needed to make rootf binary reproducible
479rootfs_reproducible () {
480	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
481		# Convert UTC into %4Y%2m%2d%2H%2M%2S
482		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
483		echo $sformatted > ${IMAGE_ROOTFS}/etc/version
484		bbnote "rootfs_reproducible: set /etc/version to $sformatted"
485
486		if [ -d ${IMAGE_ROOTFS}${sysconfdir}/gconf ]; then
487			find ${IMAGE_ROOTFS}${sysconfdir}/gconf -name '%gconf.xml' -print0 | xargs -0r \
488			sed -i -e 's@\bmtime="[0-9][0-9]*"@mtime="'${REPRODUCIBLE_TIMESTAMP_ROOTFS}'"@g'
489		fi
490
491		if [ -f ${IMAGE_ROOTFS}${localstatedir}/lib/opkg/status ]; then
492			sed -i 's/^Installed-Time: .*/Installed-Time: ${REPRODUCIBLE_TIMESTAMP_ROOTFS}/' ${IMAGE_ROOTFS}${localstatedir}/lib/opkg/status
493		fi
494	fi
495}
496
497# Perform a dumb check for unit existence, not its validity
498python overlayfs_qa_check() {
499    from oe.overlayfs import mountUnitName
500
501    overlayMountPoints = d.getVarFlags("OVERLAYFS_MOUNT_POINT") or {}
502    imagepath = d.getVar("IMAGE_ROOTFS")
503    sysconfdir = d.getVar("sysconfdir")
504    searchpaths = [oe.path.join(imagepath, sysconfdir, "systemd", "system"),
505                   oe.path.join(imagepath, d.getVar("systemd_system_unitdir"))]
506    fstabpath = oe.path.join(imagepath, sysconfdir, "fstab")
507
508    if not any(os.path.exists(path) for path in [*searchpaths, fstabpath]):
509        return
510
511    fstabDevices = []
512    if os.path.isfile(fstabpath):
513        with open(fstabpath, 'r') as f:
514            for line in f:
515                if line[0] == '#':
516                    continue
517                path = line.split(maxsplit=2)
518                if len(path) > 2:
519                    fstabDevices.append(path[1])
520
521    allUnitExist = True;
522    for mountPoint in overlayMountPoints:
523        qaSkip = (d.getVarFlag("OVERLAYFS_QA_SKIP", mountPoint) or "").split()
524        if "mount-configured" in qaSkip:
525            continue
526
527        mountPath = d.getVarFlag('OVERLAYFS_MOUNT_POINT', mountPoint)
528        if mountPath in fstabDevices:
529            continue
530
531        mountUnit = mountUnitName(mountPath)
532        if any(os.path.isfile(oe.path.join(dirpath, mountUnit))
533               for dirpath in searchpaths):
534            continue
535
536        bb.warn(f'Mount path {mountPath} not found in fstab and unit '
537                f'{mountUnit} not found in systemd unit directories.')
538        bb.warn(f'Skip this check by setting OVERLAYFS_QA_SKIP[{mountPoint}] = '
539                '"mount-configured"')
540        allUnitExist = False;
541
542    if not allUnitExist:
543        bb.fatal('Not all mount paths and units are installed in the image')
544}
545
546python overlayfs_postprocess() {
547    import shutil
548
549    # install helper script
550    helperScriptName = "overlayfs-create-dirs.sh"
551    helperScriptSource = oe.path.join(d.getVar("COREBASE"), "meta/files", helperScriptName)
552    helperScriptDest = oe.path.join(d.getVar("IMAGE_ROOTFS"), "/usr/sbin/", helperScriptName)
553    shutil.copyfile(helperScriptSource, helperScriptDest)
554    os.chmod(helperScriptDest, 0o755)
555}
556