xref: /freebsd/release/tools/vmimage.subr (revision f9bc005b8ef3b507a5ecbc2d7fe4411ef70eff38)
1#!/bin/sh
2#
3#
4#
5# Common functions for virtual machine image build scripts.
6#
7
8scriptdir=$(dirname $(realpath $0))
9. ${scriptdir}/../scripts/tools.subr
10. ${scriptdir}/../../tools/boot/install-boot.sh
11
12export PATH="/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
13trap "cleanup" INT QUIT TRAP ABRT TERM
14
15# Platform-specific large-scale setup
16# Most platforms use GPT, so put that as default, then special cases
17PARTSCHEME=gpt
18ROOTLABEL="gpt"
19case "${TARGET}:${TARGET_ARCH}" in
20	powerpc:powerpc*)
21		PARTSCHEME=mbr
22		ROOTLABEL="ufs"
23		NOSWAP=yes # Can't label swap partition with MBR, so no swap
24	;;
25esac
26
27err() {
28	printf "${@}\n"
29	cleanup
30	return 1
31}
32
33cleanup() {
34	if [ -c "${DESTDIR}/dev/null" ]; then
35		umount_loop ${DESTDIR}/dev 2>/dev/null
36	fi
37
38	return 0
39}
40
41metalog_add_data() {
42	local file mode type
43
44	file=$1
45	if [ -f ${DESTDIR}/${file} ]; then
46		type=file
47		mode=${2:-0644}
48	elif [ -d ${DESTDIR}/${file} ]; then
49		type=dir
50		mode=${2:-0755}
51	else
52		echo "metalog_add_data: ${file} not found" >&2
53		return 1
54	fi
55	echo "${file} type=${type} uname=root gname=wheel mode=${mode}" >> \
56	    ${DESTDIR}/METALOG
57}
58
59vm_create_base() {
60
61	mkdir -p ${DESTDIR}
62
63	return 0
64}
65
66vm_copy_base() {
67	# Defunct
68	return 0
69}
70
71vm_base_packages_list() {
72	# Output a list of package sets equivalent to what we get from
73	# "installworld installkernel distribution", aka. the full base
74	# system.
75	echo FreeBSD-set-base
76	[ -z "${WITHOUT_DEBUG_FILES}" ] && echo FreeBSD-set-base-dbg
77	echo FreeBSD-set-kernels
78	[ -z "${WITHOUT_KERNEL_SYMBOLS}" ] && echo FreeBSD-set-kernels-dbg
79	case ${TARGET_ARCH} in
80	amd64 | aarch64 | powerpc64)
81		echo FreeBSD-set-lib32
82		[ -z "${WITHOUT_DEBUG_FILES}" ] && echo FreeBSD-set-lib32-dbg
83	esac
84	[ -n "${WITH_SRC}" ] && echo FreeBSD-set-src
85	echo FreeBSD-set-tests
86	# Also install pkg, since systems with a packaged base system should
87	# have the tools to upgrade themselves.
88	echo pkg
89}
90
91vm_extra_filter_base_packages() {
92	# Prototype. When overridden, allows further filtering of base system
93	# packages, reading package names from stdin and writing to stdout.
94	cat
95}
96
97vm_install_base() {
98	# Installs the FreeBSD userland/kernel to the virtual machine disk.
99
100	if [ -z "${NOPKGBASE}" ]; then
101		local pkg_cmd
102		pkg_cmd="${PKG_CMD} --rootdir ${DESTDIR} --repo-conf-dir ${PKGBASE_REPO_DIR}
103			-o ASSUME_ALWAYS_YES=yes -o IGNORE_OSVERSION=yes
104			-o ABI=${PKG_ABI} -o INSTALL_AS_USER=yes "
105		pkg_cmd="$pkg_cmd -o METALOG=METALOG"
106		$pkg_cmd update
107		selected=$(vm_base_packages_list | vm_extra_filter_base_packages)
108		$pkg_cmd install -U -r FreeBSD-base $selected
109		metalog_add_data ./var/db/pkg/local.sqlite
110		mkdir -p ${DESTDIR}/usr/local/etc/pkg/repos
111		echo 'FreeBSD-base: { enabled: yes }' > ${DESTDIR}/usr/local/etc/pkg/repos/FreeBSD.conf
112		metalog_add_data ./usr/local/etc/pkg/repos
113		metalog_add_data ./usr/local/etc/pkg/repos/FreeBSD.conf
114	else
115		cd ${WORLDDIR} && \
116			make DESTDIR=${DESTDIR} ${INSTALLOPTS} \
117			installworld installkernel distribution || \
118			err "\n\nCannot install the base system to ${DESTDIR}."
119	fi
120
121	# Bootstrap etcupdate(8) database.
122	mkdir -p ${DESTDIR}/var/db/etcupdate
123	etcupdate extract -B \
124		-M "TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH}" \
125		-s ${WORLDDIR} -d ${DESTDIR}/var/db/etcupdate \
126		-L /dev/stdout -N
127	# Reroot etcupdate's internal METALOG to the whole tree
128	sed -n 's,^\.,./var/db/etcupdate/current,p' \
129	    ${DESTDIR}/var/db/etcupdate/current/METALOG | \
130	    env -i LC_COLLATE=C sort >> ${DESTDIR}/METALOG
131	rm ${DESTDIR}/var/db/etcupdate/current/METALOG
132
133	echo '# Custom /etc/fstab for FreeBSD VM images' \
134		> ${DESTDIR}/etc/fstab
135	if [ "${VMFS}" != zfs ]; then
136		echo "/dev/${ROOTLABEL}/rootfs   /       ${VMFS}   rw,noatime      1       1" \
137			>> ${DESTDIR}/etc/fstab
138	fi
139	if [ -z "${NOSWAP}" ]; then
140		echo '/dev/gpt/swapfs  none    swap    sw      0       0' \
141			>> ${DESTDIR}/etc/fstab
142	fi
143	metalog_add_data ./etc/fstab
144
145	local hostname
146	hostname="$(echo $(uname -o) | tr '[:upper:]' '[:lower:]')"
147	echo "hostname=\"${hostname}\"" >> ${DESTDIR}/etc/rc.conf
148	metalog_add_data ./etc/rc.conf
149	if [ "${VMFS}" = zfs ]; then
150		echo "zfs_enable=\"YES\"" >> ${DESTDIR}/etc/rc.conf
151		echo "zpool_reguid=\"zroot\"" >> ${DESTDIR}/etc/rc.conf
152		echo "zpool_upgrade=\"zroot\"" >> ${DESTDIR}/etc/rc.conf
153		echo "kern.geom.label.disk_ident.enable=0" >> ${DESTDIR}/boot/loader.conf
154		echo "zfs_load=YES" >> ${DESTDIR}/boot/loader.conf
155		metalog_add_data ./boot/loader.conf
156	fi
157
158	return 0
159}
160
161vm_emulation_setup() {
162	if [ -n "${WITHOUT_QEMU}" ]; then
163		return 0
164	fi
165	if [ -n "${QEMUSTATIC}" ]; then
166		export EMULATOR=/qemu
167		cp ${QEMUSTATIC} ${DESTDIR}/${EMULATOR}
168	fi
169
170	mkdir -p ${DESTDIR}/dev
171	mount -t devfs devfs ${DESTDIR}/dev
172	chroot ${DESTDIR} ${EMULATOR} /bin/sh /etc/rc.d/ldconfig forcestart
173	cp /etc/resolv.conf ${DESTDIR}/etc/resolv.conf
174
175	return 0
176}
177
178vm_extra_install_base() {
179	# Prototype.  When overridden, runs extra post-installworld commands
180	# as needed, based on the target virtual machine image or cloud
181	# provider image target.
182
183	return 0
184}
185
186vm_extra_enable_services() {
187	if [ -n "${VM_RC_LIST}" ]; then
188		for _rcvar in ${VM_RC_LIST}; do
189			echo ${_rcvar}_enable="YES" >> ${DESTDIR}/etc/rc.conf
190		done
191	fi
192
193	if [ -z "${VMCONFIG}" -o -c "${VMCONFIG}" ]; then
194		echo 'ifconfig_DEFAULT="DHCP inet6 accept_rtadv"' >> \
195			${DESTDIR}/etc/rc.conf
196		# Expand the filesystem to fill the disk.
197		echo 'growfs_enable="YES"' >> ${DESTDIR}/etc/rc.conf
198	fi
199
200	return 0
201}
202
203vm_extra_install_packages() {
204	if [ -z "${VM_EXTRA_PACKAGES}" ]; then
205		return 0
206	fi
207	for pkg in ${VM_EXTRA_PACKAGES}; do
208		INSTALL_AS_USER=yes \
209		    ${PKG_CMD} \
210		    -o ABI=${PKG_ABI} \
211		    -o METALOG=${DESTDIR}/METALOG.pkg \
212		    -o REPOS_DIR=${PKG_REPOS_DIR} \
213		    -o PKG_DBDIR=${DESTDIR}/var/db/pkg \
214		    -r ${DESTDIR} \
215		    install -y -r ${PKG_REPO_NAME} $pkg
216	done
217	if [ -n "${NOPKGBASE}" ]; then
218		metalog_add_data ./var/db/pkg/local.sqlite
219	fi
220
221	return 0
222}
223
224vm_extra_install_ports() {
225	# Prototype.  When overridden, installs additional ports within the
226	# virtual machine environment.
227
228	return 0
229}
230
231vm_extra_pre_umount() {
232	# Prototype.  When overridden, performs additional tasks within the
233	# virtual machine environment prior to unmounting the filesystem.
234
235	return 0
236}
237
238vm_emulation_cleanup() {
239	if [ -n "${WITHOUT_QEMU}" ]; then
240		return 0
241	fi
242
243	if ! [ -z "${QEMUSTATIC}" ]; then
244		rm -f ${DESTDIR}/${EMULATOR}
245	fi
246	rm -f ${DESTDIR}/etc/resolv.conf
247	umount_loop ${DESTDIR}/dev
248	return 0
249}
250
251vm_extra_pkg_rmcache() {
252	${PKG_CMD} \
253	    -o ASSUME_ALWAYS_YES=yes \
254	    -o INSTALL_AS_USER=yes \
255	    -r ${DESTDIR} \
256	    clean -y -a
257
258	return 0
259}
260
261buildfs() {
262	local md tmppool
263
264	# Copy entries from METALOG.pkg into METALOG, but first check to
265	# make sure that filesystem objects still exist; some things may
266	# have been logged which no longer exist if a package was removed.
267	if [ -f ${DESTDIR}/METALOG.pkg ]; then
268		while read F REST; do
269			if [ -e "${DESTDIR}/${F}" ] ||
270			    [ -L "${DESTDIR}/${F}" ]; then
271				echo "${F} ${REST}" >> ${DESTDIR}/METALOG
272			fi
273		done < ${DESTDIR}/METALOG.pkg
274	fi
275
276	# Check for any directories in the staging tree which weren't
277	# recorded in METALOG, and record them now.  This is a quick hack
278	# to avoid creating unusable VM images and should go away once
279	# the bugs which produce such unlogged directories are gone.
280	grep type=dir ${DESTDIR}/METALOG |
281	    cut -f 1 -d ' ' |
282	    sort -u > ${DESTDIR}/METALOG.dirs
283	( cd ${DESTDIR} && find . -type d ) |
284	    sort |
285	    comm -23 - ${DESTDIR}/METALOG.dirs > ${DESTDIR}/METALOG.missingdirs
286	if [ -s ${DESTDIR}/METALOG.missingdirs ]; then
287		echo "WARNING: Directories exist but were not in METALOG"
288		cat ${DESTDIR}/METALOG.missingdirs
289	fi
290	while read DIR; do
291		metalog_add_data ${DIR}
292	done < ${DESTDIR}/METALOG.missingdirs
293
294	if [ -z "${NOPKGBASE}" ]; then
295		# Add some database files which are created by pkg triggers;
296		# at some point in the future the tools which create these
297		# files should probably learn how to record them in METALOG
298		# (which would simplify no-root installworld as well).
299		metalog_add_data ./etc/login.conf.db
300		metalog_add_data ./etc/passwd
301		metalog_add_data ./etc/pwd.db
302		metalog_add_data ./etc/spwd.db 600
303		metalog_add_data ./var/db/services.db
304	fi
305
306	if [ -n "${MISSING_METALOGS}" ]; then
307		# Hack to allow VM configurations to add files which
308		# weren't being added to METALOG appropriately.  This
309		# is mainly a workaround for the @sample bug and it
310		# should go away before FreeBSD 15.1 ships.
311		for P in ${MISSING_METALOGS}; do
312			metalog_add_data ${P}
313		done
314	fi
315
316	# Sort METALOG file; makefs produces directories with 000 permissions
317	# if their contents are seen before the directories themselves.
318	env -i LC_COLLATE=C sort -u ${DESTDIR}/METALOG > ${DESTDIR}/METALOG.sorted
319	mv ${DESTDIR}/METALOG.sorted ${DESTDIR}/METALOG
320
321	case "${VMFS}" in
322	ufs)
323		cd ${DESTDIR} && ${MAKEFS} ${MAKEFSARGS} -o label=rootfs -o version=2 -o softupdates=1 \
324			${VMBASE} ./METALOG
325		;;
326	zfs)
327		cd ${DESTDIR} && ${MAKEFS} -t zfs ${MAKEFSARGS} \
328			-o poolname=zroot -o bootfs=zroot/ROOT/default -o rootpath=/ \
329			-o fs=zroot\;mountpoint=none \
330			-o fs=zroot/ROOT\;mountpoint=none \
331			-o fs=zroot/ROOT/default\;mountpoint=/\;canmount=noauto \
332			-o fs=zroot/home\;mountpoint=/home \
333			-o fs=zroot/tmp\;mountpoint=/tmp\;exec=on\;setuid=off \
334			-o fs=zroot/usr\;mountpoint=/usr\;canmount=off \
335			-o fs=zroot/usr/ports\;setuid=off \
336			-o fs=zroot/usr/src \
337			-o fs=zroot/usr/obj \
338			-o fs=zroot/var\;mountpoint=/var\;canmount=off \
339			-o fs=zroot/var/audit\;setuid=off\;exec=off \
340			-o fs=zroot/var/crash\;setuid=off\;exec=off \
341			-o fs=zroot/var/log\;setuid=off\;exec=off \
342			-o fs=zroot/var/mail\;atime=on \
343			-o fs=zroot/var/tmp\;setuid=off \
344			${VMBASE} ./METALOG
345		;;
346	*)
347		echo "Unexpected VMFS value '${VMFS}'"
348		exit 1
349		;;
350	esac
351}
352
353umount_loop() {
354	DIR=$1
355	i=0
356	sync
357	while ! umount ${DIR}; do
358		i=$(( $i + 1 ))
359		if [ $i -ge 10 ]; then
360			# This should never happen.  But, it has happened.
361			echo "Cannot umount(8) ${DIR}"
362			echo "Something has gone horribly wrong."
363			return 1
364		fi
365		sleep 1
366	done
367
368	return 0
369}
370
371vm_create_disk() {
372	local BOOTFILES BOOTPARTSOFFSET FSPARTTYPE X86GPTBOOTFILE
373
374	if [ -z "${NOSWAP}" ]; then
375		SWAPOPT="-p freebsd-swap/swapfs::${SWAPSIZE}"
376	fi
377
378	if [ -n "${VM_BOOTPARTSOFFSET}" ]; then
379		BOOTPARTSOFFSET=":${VM_BOOTPARTSOFFSET}"
380	fi
381
382	if [ -n "${CONFIG_DRIVE}" ]; then
383		CONFIG_DRIVE="-p freebsd/config-drive::${CONFIG_DRIVE_SIZE}"
384	fi
385
386	case "${VMFS}" in
387	ufs)
388		FSPARTTYPE=freebsd-ufs
389		X86GPTBOOTFILE=i386/gptboot/gptboot
390		;;
391	zfs)
392		FSPARTTYPE=freebsd-zfs
393		X86GPTBOOTFILE=i386/gptzfsboot/gptzfsboot
394		;;
395	*)
396		echo "Unexpected VMFS value '${VMFS}'"
397		return 1
398		;;
399	esac
400
401	echo "Creating image...  Please wait."
402	echo
403
404	BOOTFILES="$(env TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH} \
405		WITH_UNIFIED_OBJDIR=yes \
406		make -C ${WORLDDIR}/stand -V .OBJDIR)"
407	BOOTFILES="$(realpath ${BOOTFILES})"
408	MAKEFSARGS="-s ${VMSIZE} -D -N ${DESTDIR}/etc"
409
410	case "${TARGET}:${TARGET_ARCH}" in
411		amd64:amd64 | i386:i386)
412			ESP=yes
413			BOOTPARTS="-b ${BOOTFILES}/i386/pmbr/pmbr \
414				   -p freebsd-boot/bootfs:=${BOOTFILES}/${X86GPTBOOTFILE}${BOOTPARTSOFFSET}"
415			ROOTFSPART="-p ${FSPARTTYPE}/rootfs:=${VMBASE}"
416			MAKEFSARGS="$MAKEFSARGS -B little"
417			;;
418		arm:armv7 | arm64:aarch64 | riscv:riscv64*)
419			ESP=yes
420			BOOTPARTS=
421			ROOTFSPART="-p ${FSPARTTYPE}/rootfs:=${VMBASE}"
422			MAKEFSARGS="$MAKEFSARGS -B little"
423			;;
424		powerpc:powerpc*)
425			ESP=no
426			BOOTPARTS="-p prepboot:=${BOOTFILES}/powerpc/boot1.chrp/boot1.elf -a 1"
427			ROOTFSPART="-p freebsd:=${VMBASE}"
428			if [ ${TARGET_ARCH} = powerpc64le ]; then
429				MAKEFSARGS="$MAKEFSARGS -B little"
430			else
431				MAKEFSARGS="$MAKEFSARGS -B big"
432			fi
433			;;
434		*)
435			echo "vmimage.subr: unsupported target '${TARGET}:${TARGET_ARCH}'" >&2
436			exit 1
437			;;
438	esac
439
440	if [ ${ESP} = "yes" ]; then
441		# Create an ESP
442		espfilename=$(mktemp /tmp/efiboot.XXXXXX)
443		make_esp_file ${espfilename} ${fat32min} ${BOOTFILES}/efi/loader_lua/loader_lua.efi
444		espsuffix=""
445		if [ -z "${BOOTPARTS}" ]; then
446			espsuffix="${BOOTPARTSOFFSET}"
447		fi
448		BOOTPARTS="${BOOTPARTS} -p efi/efiboot0:=${espfilename}${espsuffix}"
449
450		# Add this to fstab
451		mkdir -p ${DESTDIR}/boot/efi
452		echo "/dev/${ROOTLABEL}/efiboot0	/boot/efi       msdosfs     rw      2       2" \
453			>> ${DESTDIR}/etc/fstab
454	fi
455
456	# Add a marker file which indicates that this image has never
457	# been booted.  Some services run only upon the first boot.
458	touch ${DESTDIR}/firstboot
459	metalog_add_data ./firstboot
460
461	echo "Building filesystem...  Please wait."
462	buildfs
463
464	echo "Building final disk image...  Please wait."
465	${MKIMG} -s ${PARTSCHEME} -f ${VMFORMAT} \
466		${BOOTPARTS} \
467		${SWAPOPT} \
468		${CONFIG_DRIVE} \
469		${ROOTFSPART} \
470		-o ${VMIMAGE}
471
472	echo "Disk image ${VMIMAGE} created."
473
474	if [ ${ESP} = "yes" ]; then
475		rm ${espfilename}
476	fi
477
478	return 0
479}
480
481vm_extra_create_disk() {
482
483	return 0
484}
485