xref: /openbmc/openbmc/poky/meta/classes-recipe/rootfs-postcommands.bbclass (revision c9537f57ab488bf5d90132917b0184e2527970a5)
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 systemd_handle_machine_id", "", 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
176systemd_handle_machine_id() {
177    if ${@bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", "true", "false", d)}; then
178        # Create machine-id
179        # 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
180        touch ${IMAGE_ROOTFS}${sysconfdir}/machine-id
181    fi
182    # In order to be backward compatible with the previous OE-core specific (re)implementation of systemctl
183    # we need to touch machine-id when handling presets and when the rootfs is NOT stateless
184    if ${@ 'true' if not bb.utils.contains('IMAGE_FEATURES', 'stateless-rootfs', True, False, d) else 'false'}; then
185        touch ${IMAGE_ROOTFS}${sysconfdir}/machine-id
186        if [ -e ${IMAGE_ROOTFS}${root_prefix}/lib/systemd/systemd ]; then
187            systemctl --root="${IMAGE_ROOTFS}" --preset-mode=enable-only preset-all
188            systemctl --root="${IMAGE_ROOTFS}" --global --preset-mode=enable-only preset-all
189        fi
190    fi
191}
192
193#
194# A hook function to support read-only-rootfs IMAGE_FEATURES
195#
196read_only_rootfs_hook () {
197	# Tweak the mount option and fs_passno for rootfs in fstab
198	if [ -f ${IMAGE_ROOTFS}/etc/fstab ]; then
199		sed -i -e '/^[#[:space:]]*\/dev\/root/{s/defaults/ro/;s/\([[:space:]]*[[:digit:]]\)\([[:space:]]*\)[[:digit:]]$/\1\20/}' ${IMAGE_ROOTFS}/etc/fstab
200	fi
201
202	# Tweak the "mount -o remount,rw /" command in busybox-inittab inittab
203	if [ -f ${IMAGE_ROOTFS}/etc/inittab ]; then
204		sed -i 's|/bin/mount -o remount,rw /|/bin/mount -o remount,ro /|' ${IMAGE_ROOTFS}/etc/inittab
205	fi
206
207	# If we're using openssh and the /etc/ssh directory has no pre-generated keys,
208	# we should configure openssh to use the configuration file /etc/ssh/sshd_config_readonly
209	# and the keys under /var/run/ssh.
210	# If overlayfs-etc is used this is not done as /etc is treated as writable
211	# If stateless-rootfs is enabled this is always done as we don't want to save keys then
212	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
213		if [ -d ${IMAGE_ROOTFS}/etc/ssh ]; then
214			if [ -e ${IMAGE_ROOTFS}/etc/ssh/ssh_host_rsa_key ]; then
215				echo "SYSCONFDIR=\${SYSCONFDIR:-/etc/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
216				echo "SSHD_OPTS=" >> ${IMAGE_ROOTFS}/etc/default/ssh
217			else
218				echo "SYSCONFDIR=\${SYSCONFDIR:-/var/run/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
219				echo "SSHD_OPTS='-f /etc/ssh/sshd_config_readonly'" >> ${IMAGE_ROOTFS}/etc/default/ssh
220			fi
221		fi
222
223		# Also tweak the key location for dropbear in the same way.
224		if [ -d ${IMAGE_ROOTFS}/etc/dropbear ]; then
225			if [ ! -e ${IMAGE_ROOTFS}/etc/dropbear/dropbear_rsa_host_key ]; then
226				if ! grep -q "^DROPBEAR_RSAKEY_DIR=" ${IMAGE_ROOTFS}/etc/default/dropbear ; then
227					echo "DROPBEAR_RSAKEY_DIR=/var/lib/dropbear" >> ${IMAGE_ROOTFS}/etc/default/dropbear
228				fi
229			fi
230		fi
231	fi
232
233	if ${@bb.utils.contains("DISTRO_FEATURES", "sysvinit", "true", "false", d)}; then
234		# Change the value of ROOTFS_READ_ONLY in /etc/default/rcS to yes
235		if [ -e ${IMAGE_ROOTFS}/etc/default/rcS ]; then
236			sed -i 's/ROOTFS_READ_ONLY=no/ROOTFS_READ_ONLY=yes/' ${IMAGE_ROOTFS}/etc/default/rcS
237		fi
238		# Run populate-volatile.sh at rootfs time to set up basic files
239		# and directories to support read-only rootfs.
240		if [ -x ${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh ]; then
241			${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh
242		fi
243	fi
244}
245
246#
247# This function disallows empty root passwords
248#
249zap_empty_root_password () {
250	if [ -e ${IMAGE_ROOTFS}/etc/shadow ]; then
251		sed --follow-symlinks -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/shadow
252        fi
253	if [ -e ${IMAGE_ROOTFS}/etc/passwd ]; then
254		sed --follow-symlinks -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/passwd
255	fi
256}
257
258#
259# allow dropbear/openssh to accept logins from accounts with an empty password string
260#
261ssh_allow_empty_password () {
262	for config in sshd_config sshd_config_readonly; do
263		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
264			sed -i 's/^[#[:space:]]*PermitEmptyPasswords.*/PermitEmptyPasswords yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
265		fi
266	done
267
268	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
269		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
270			if ! grep -q "DROPBEAR_EXTRA_ARGS=.*-B" ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear ; then
271				sed -i 's/^DROPBEAR_EXTRA_ARGS="*\([^"]*\)"*/DROPBEAR_EXTRA_ARGS="\1 -B"/' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
272			fi
273		else
274			printf '\nDROPBEAR_EXTRA_ARGS="-B"\n' >> ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
275		fi
276	fi
277
278	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/pam.d ] ; then
279		for f in `find ${IMAGE_ROOTFS}${sysconfdir}/pam.d/* -type f -exec test -e {} \; -print`
280		do
281			sed -i 's/nullok_secure/nullok/' $f
282		done
283	fi
284}
285
286#
287# allow dropbear/openssh to accept root logins
288#
289ssh_allow_root_login () {
290	for config in sshd_config sshd_config_readonly; do
291		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
292			sed -i 's/^[#[:space:]]*PermitRootLogin.*/PermitRootLogin yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
293		fi
294	done
295
296	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
297		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
298			sed -i '/^DROPBEAR_EXTRA_ARGS=/ s/-w//' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
299			sed -i '/^# Disallow root/d' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
300		fi
301	fi
302}
303
304#
305# Autologin the 'root' user on the serial terminal,
306# if empty-root-password' AND 'serial-autologin-root are enabled
307#
308serial_autologin_root () {
309	if ${@bb.utils.contains("DISTRO_FEATURES", "sysvinit", "true", "false", d)}; then
310		# add autologin option to util-linux getty only
311		sed -i 's/options="/&--autologin root /' \
312			"${IMAGE_ROOTFS}${base_bindir}/start_getty"
313	elif ${@bb.utils.contains("DISTRO_FEATURES", "systemd", "true", "false", d)}; then
314		if [ -e ${IMAGE_ROOTFS}${systemd_system_unitdir}/serial-getty@.service ]; then
315			sed -i '/^\s*ExecStart\b/ s/getty /&--autologin root /' \
316				"${IMAGE_ROOTFS}${systemd_system_unitdir}/serial-getty@.service"
317		fi
318	fi
319}
320
321python tidy_shadowutils_files () {
322    import oe.rootfspostcommands
323    oe.rootfspostcommands.tidy_shadowutils_files(d.expand('${IMAGE_ROOTFS}${sysconfdir}'))
324}
325
326python sort_passwd () {
327    """
328    Deprecated in the favour of tidy_shadowutils_files.
329    """
330    import oe.rootfspostcommands
331    bb.warn('[sort_passwd] You are using a deprecated function for '
332        'SORT_PASSWD_POSTPROCESS_COMMAND. The default one is now called '
333        '"tidy_shadowutils_files".')
334    oe.rootfspostcommands.tidy_shadowutils_files(d.expand('${IMAGE_ROOTFS}${sysconfdir}'))
335}
336
337#
338# Enable postinst logging
339#
340postinst_enable_logging () {
341	mkdir -p ${IMAGE_ROOTFS}${sysconfdir}/default
342	echo "POSTINST_LOGGING=1" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
343	echo "LOGFILE=${POSTINST_LOGFILE}" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
344}
345
346#
347# Modify systemd default target
348#
349set_systemd_default_target () {
350	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/systemd/system -a -e ${IMAGE_ROOTFS}${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ]; then
351		ln -sf ${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ${IMAGE_ROOTFS}${sysconfdir}/systemd/system/default.target
352	fi
353}
354
355# If /var/volatile is not empty, we have seen problems where programs such as the
356# journal make assumptions based on the contents of /var/volatile. The journal
357# would then write to /var/volatile before it was mounted, thus hiding the
358# items previously written.
359#
360# This change is to attempt to fix those types of issues in a way that doesn't
361# affect users that may not be using /var/volatile.
362empty_var_volatile () {
363	if [ -e ${IMAGE_ROOTFS}/etc/fstab ]; then
364		match=`awk '$1 !~ "#" && $2 ~ /\/var\/volatile/{print $2}' ${IMAGE_ROOTFS}/etc/fstab 2> /dev/null`
365		if [ -n "$match" ]; then
366			find ${IMAGE_ROOTFS}/var/volatile -mindepth 1 -delete
367		fi
368	fi
369}
370
371# Turn any symbolic /sbin/init link into a file
372remove_init_link () {
373	if [ -h ${IMAGE_ROOTFS}/sbin/init ]; then
374		LINKFILE=${IMAGE_ROOTFS}`readlink ${IMAGE_ROOTFS}/sbin/init`
375		rm ${IMAGE_ROOTFS}/sbin/init
376		cp $LINKFILE ${IMAGE_ROOTFS}/sbin/init
377	fi
378}
379
380python write_image_manifest () {
381    from oe.rootfs import image_list_installed_packages
382    from oe.utils import format_pkg_list
383
384    deploy_dir = d.getVar('IMGDEPLOYDIR')
385    link_name = d.getVar('IMAGE_LINK_NAME')
386    manifest_name = d.getVar('IMAGE_MANIFEST')
387
388    if not manifest_name:
389        return
390
391    pkgs = image_list_installed_packages(d)
392    with open(manifest_name, 'w+') as image_manifest:
393        image_manifest.write(format_pkg_list(pkgs, "ver"))
394
395    if os.path.exists(manifest_name) and link_name:
396        manifest_link = deploy_dir + "/" + link_name + ".manifest"
397        if manifest_link != manifest_name:
398            if os.path.lexists(manifest_link):
399                os.remove(manifest_link)
400            os.symlink(os.path.basename(manifest_name), manifest_link)
401}
402
403# Can be used to create /etc/timestamp during image construction to give a reasonably
404# sane default time setting
405rootfs_update_timestamp () {
406	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
407		# Convert UTC into %4Y%2m%2d%2H%2M%2S
408		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
409	else
410		sformatted=`date -u +%4Y%2m%2d%2H%2M%2S`
411	fi
412	echo $sformatted > ${IMAGE_ROOTFS}/etc/timestamp
413	bbnote "rootfs_update_timestamp: set /etc/timestamp to $sformatted"
414}
415
416# Prevent X from being started
417rootfs_no_x_startup () {
418	if [ -f ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm ]; then
419		chmod a-x ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm
420	fi
421}
422
423rootfs_trim_schemas () {
424	for schema in ${IMAGE_ROOTFS}/etc/gconf/schemas/*.schemas
425	do
426		# Need this in case no files exist
427		if [ -e $schema ]; then
428			oe-trim-schemas $schema > $schema.new
429			mv $schema.new $schema
430		fi
431	done
432}
433
434rootfs_check_host_user_contaminated () {
435	contaminated="${S}/host-user-contaminated.txt"
436	HOST_USER_UID="$(PSEUDO_UNLOAD=1 id -u)"
437	HOST_USER_GID="$(PSEUDO_UNLOAD=1 id -g)"
438
439	find "${IMAGE_ROOTFS}" -path "${IMAGE_ROOTFS}/home" -prune -o \
440	    -user "$HOST_USER_UID" -print -o -group "$HOST_USER_GID" -print >"$contaminated"
441
442	sed -e "s,${IMAGE_ROOTFS},," $contaminated | while read line; do
443		bbwarn "Path in the rootfs is owned by the same user or group as the user running bitbake:" $line `ls -lan ${IMAGE_ROOTFS}/$line`
444	done
445
446	if [ -s "$contaminated" ]; then
447		bbwarn "/etc/passwd:" `cat ${IMAGE_ROOTFS}/etc/passwd`
448		bbwarn "/etc/group:" `cat ${IMAGE_ROOTFS}/etc/group`
449	fi
450}
451
452# Make any absolute links in a sysroot relative
453rootfs_sysroot_relativelinks () {
454	sysroot-relativelinks.py ${SDK_OUTPUT}/${SDKTARGETSYSROOT}
455}
456
457# Generated test data json file
458python write_image_test_data() {
459    from oe.data import export2json
460
461    deploy_dir = d.getVar('IMGDEPLOYDIR')
462    link_name = d.getVar('IMAGE_LINK_NAME')
463    testdata_name = os.path.join(deploy_dir, "%s.testdata.json" % d.getVar('IMAGE_NAME'))
464
465    searchString = "%s/"%(d.getVar("TOPDIR")).replace("//","/")
466    export2json(d, testdata_name, searchString=searchString, replaceString="")
467
468    if os.path.exists(testdata_name) and link_name:
469        testdata_link = os.path.join(deploy_dir, "%s.testdata.json" % link_name)
470        if testdata_link != testdata_name:
471            if os.path.lexists(testdata_link):
472                os.remove(testdata_link)
473            os.symlink(os.path.basename(testdata_name), testdata_link)
474}
475write_image_test_data[vardepsexclude] += "TOPDIR"
476
477# Check for unsatisfied recommendations (RRECOMMENDS)
478python rootfs_log_check_recommends() {
479    log_path = d.expand("${T}/log.do_rootfs")
480    with open(log_path, 'r') as log:
481        for line in log:
482            if 'log_check' in line:
483                continue
484
485            if 'unsatisfied recommendation for' in line:
486                bb.warn('[log_check] %s: %s' % (d.getVar('PN'), line))
487}
488
489# Perform any additional adjustments needed to make rootf binary reproducible
490rootfs_reproducible () {
491	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
492		# Convert UTC into %4Y%2m%2d%2H%2M%2S
493		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
494		echo $sformatted > ${IMAGE_ROOTFS}/etc/version
495		bbnote "rootfs_reproducible: set /etc/version to $sformatted"
496
497		if [ -d ${IMAGE_ROOTFS}${sysconfdir}/gconf ]; then
498			find ${IMAGE_ROOTFS}${sysconfdir}/gconf -name '%gconf.xml' -print0 | xargs -0r \
499			sed -i -e 's@\bmtime="[0-9][0-9]*"@mtime="'${REPRODUCIBLE_TIMESTAMP_ROOTFS}'"@g'
500		fi
501
502		if [ -f ${IMAGE_ROOTFS}${localstatedir}/lib/opkg/status ]; then
503			sed -i 's/^Installed-Time: .*/Installed-Time: ${REPRODUCIBLE_TIMESTAMP_ROOTFS}/' ${IMAGE_ROOTFS}${localstatedir}/lib/opkg/status
504		fi
505	fi
506}
507
508# Perform a dumb check for unit existence, not its validity
509python overlayfs_qa_check() {
510    from oe.overlayfs import mountUnitName
511
512    overlayMountPoints = d.getVarFlags("OVERLAYFS_MOUNT_POINT") or {}
513    imagepath = d.getVar("IMAGE_ROOTFS")
514    sysconfdir = d.getVar("sysconfdir")
515    searchpaths = [oe.path.join(imagepath, sysconfdir, "systemd", "system"),
516                   oe.path.join(imagepath, d.getVar("systemd_system_unitdir"))]
517    fstabpath = oe.path.join(imagepath, sysconfdir, "fstab")
518
519    if not any(os.path.exists(path) for path in [*searchpaths, fstabpath]):
520        return
521
522    fstabDevices = []
523    if os.path.isfile(fstabpath):
524        with open(fstabpath, 'r') as f:
525            for line in f:
526                if line[0] == '#':
527                    continue
528                path = line.split(maxsplit=2)
529                if len(path) > 2:
530                    fstabDevices.append(path[1])
531
532    allUnitExist = True;
533    for mountPoint in overlayMountPoints:
534        qaSkip = (d.getVarFlag("OVERLAYFS_QA_SKIP", mountPoint) or "").split()
535        if "mount-configured" in qaSkip:
536            continue
537
538        mountPath = d.getVarFlag('OVERLAYFS_MOUNT_POINT', mountPoint)
539        if mountPath in fstabDevices:
540            continue
541
542        mountUnit = mountUnitName(mountPath)
543        if any(os.path.isfile(oe.path.join(dirpath, mountUnit))
544               for dirpath in searchpaths):
545            continue
546
547        bb.warn(f'Mount path {mountPath} not found in fstab and unit '
548                f'{mountUnit} not found in systemd unit directories.')
549        bb.warn(f'Skip this check by setting OVERLAYFS_QA_SKIP[{mountPoint}] = '
550                '"mount-configured"')
551        allUnitExist = False;
552
553    if not allUnitExist:
554        bb.fatal('Not all mount paths and units are installed in the image')
555}
556
557python overlayfs_postprocess() {
558    import shutil
559
560    # install helper script
561    helperScriptName = "overlayfs-create-dirs.sh"
562    helperScriptSource = oe.path.join(d.getVar("COREBASE"), "meta/files", helperScriptName)
563    helperScriptDest = oe.path.join(d.getVar("IMAGE_ROOTFS"), "/usr/sbin/", helperScriptName)
564    shutil.copyfile(helperScriptSource, helperScriptDest)
565    os.chmod(helperScriptDest, 0o755)
566}
567