xref: /freebsd/release/tools/vmimage.subr (revision a259b98fa211ed87bfee58c575de4e2de94ee0fa)
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} ]; then
270				echo "${F} ${REST}" >> ${DESTDIR}/METALOG
271			fi
272		done < ${DESTDIR}/METALOG.pkg
273	fi
274
275	# Check for any directories in the staging tree which weren't
276	# recorded in METALOG, and record them now.  This is a quick hack
277	# to avoid creating unusable VM images and should go away once
278	# the bugs which produce such unlogged directories are gone.
279	grep type=dir ${DESTDIR}/METALOG |
280	    cut -f 1 -d ' ' |
281	    sort -u > ${DESTDIR}/METALOG.dirs
282	( cd ${DESTDIR} && find . -type d ) |
283	    sort |
284	    comm -23 - ${DESTDIR}/METALOG.dirs > ${DESTDIR}/METALOG.missingdirs
285	if [ -s ${DESTDIR}/METALOG.missingdirs ]; then
286		echo "WARNING: Directories exist but were not in METALOG"
287		cat ${DESTDIR}/METALOG.missingdirs
288	fi
289	while read DIR; do
290		metalog_add_data ${DIR}
291	done < ${DESTDIR}/METALOG.missingdirs
292
293	if [ -z "${NOPKGBASE}" ]; then
294		# Add some database files which are created by pkg triggers;
295		# at some point in the future the tools which create these
296		# files should probably learn how to record them in METALOG
297		# (which would simplify no-root installworld as well).
298		metalog_add_data ./etc/login.conf.db
299		metalog_add_data ./etc/passwd
300		metalog_add_data ./etc/pwd.db
301		metalog_add_data ./etc/spwd.db 600
302		metalog_add_data ./var/db/services.db
303	fi
304
305	if [ -n "${MISSING_METALOGS}" ]; then
306		# Hack to allow VM configurations to add files which
307		# weren't being added to METALOG appropriately.  This
308		# is mainly a workaround for the @sample bug and it
309		# should go away before FreeBSD 15.1 ships.
310		for P in ${MISSING_METALOGS}; do
311			metalog_add_data ${P}
312		done
313	fi
314
315	# Sort METALOG file; makefs produces directories with 000 permissions
316	# if their contents are seen before the directories themselves.
317	env -i LC_COLLATE=C sort -u ${DESTDIR}/METALOG > ${DESTDIR}/METALOG.sorted
318	mv ${DESTDIR}/METALOG.sorted ${DESTDIR}/METALOG
319
320	case "${VMFS}" in
321	ufs)
322		cd ${DESTDIR} && ${MAKEFS} ${MAKEFSARGS} -o label=rootfs -o version=2 -o softupdates=1 \
323			${VMBASE} ./METALOG
324		;;
325	zfs)
326		cd ${DESTDIR} && ${MAKEFS} -t zfs ${MAKEFSARGS} \
327			-o poolname=zroot -o bootfs=zroot/ROOT/default -o rootpath=/ \
328			-o fs=zroot\;mountpoint=none \
329			-o fs=zroot/ROOT\;mountpoint=none \
330			-o fs=zroot/ROOT/default\;mountpoint=/\;canmount=noauto \
331			-o fs=zroot/home\;mountpoint=/home \
332			-o fs=zroot/tmp\;mountpoint=/tmp\;exec=on\;setuid=off \
333			-o fs=zroot/usr\;mountpoint=/usr\;canmount=off \
334			-o fs=zroot/usr/ports\;setuid=off \
335			-o fs=zroot/usr/src \
336			-o fs=zroot/usr/obj \
337			-o fs=zroot/var\;mountpoint=/var\;canmount=off \
338			-o fs=zroot/var/audit\;setuid=off\;exec=off \
339			-o fs=zroot/var/crash\;setuid=off\;exec=off \
340			-o fs=zroot/var/log\;setuid=off\;exec=off \
341			-o fs=zroot/var/mail\;atime=on \
342			-o fs=zroot/var/tmp\;setuid=off \
343			${VMBASE} ./METALOG
344		;;
345	*)
346		echo "Unexpected VMFS value '${VMFS}'"
347		exit 1
348		;;
349	esac
350}
351
352umount_loop() {
353	DIR=$1
354	i=0
355	sync
356	while ! umount ${DIR}; do
357		i=$(( $i + 1 ))
358		if [ $i -ge 10 ]; then
359			# This should never happen.  But, it has happened.
360			echo "Cannot umount(8) ${DIR}"
361			echo "Something has gone horribly wrong."
362			return 1
363		fi
364		sleep 1
365	done
366
367	return 0
368}
369
370vm_create_disk() {
371	local BOOTFILES BOOTPARTSOFFSET FSPARTTYPE X86GPTBOOTFILE
372
373	if [ -z "${NOSWAP}" ]; then
374		SWAPOPT="-p freebsd-swap/swapfs::${SWAPSIZE}"
375	fi
376
377	if [ -n "${VM_BOOTPARTSOFFSET}" ]; then
378		BOOTPARTSOFFSET=":${VM_BOOTPARTSOFFSET}"
379	fi
380
381	if [ -n "${CONFIG_DRIVE}" ]; then
382		CONFIG_DRIVE="-p freebsd/config-drive::${CONFIG_DRIVE_SIZE}"
383	fi
384
385	case "${VMFS}" in
386	ufs)
387		FSPARTTYPE=freebsd-ufs
388		X86GPTBOOTFILE=i386/gptboot/gptboot
389		;;
390	zfs)
391		FSPARTTYPE=freebsd-zfs
392		X86GPTBOOTFILE=i386/gptzfsboot/gptzfsboot
393		;;
394	*)
395		echo "Unexpected VMFS value '${VMFS}'"
396		return 1
397		;;
398	esac
399
400	echo "Creating image...  Please wait."
401	echo
402
403	BOOTFILES="$(env TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH} \
404		WITH_UNIFIED_OBJDIR=yes \
405		make -C ${WORLDDIR}/stand -V .OBJDIR)"
406	BOOTFILES="$(realpath ${BOOTFILES})"
407	MAKEFSARGS="-s ${VMSIZE} -D -N ${DESTDIR}/etc"
408
409	case "${TARGET}:${TARGET_ARCH}" in
410		amd64:amd64 | i386:i386)
411			ESP=yes
412			BOOTPARTS="-b ${BOOTFILES}/i386/pmbr/pmbr \
413				   -p freebsd-boot/bootfs:=${BOOTFILES}/${X86GPTBOOTFILE}${BOOTPARTSOFFSET}"
414			ROOTFSPART="-p ${FSPARTTYPE}/rootfs:=${VMBASE}"
415			MAKEFSARGS="$MAKEFSARGS -B little"
416			;;
417		arm:armv7 | arm64:aarch64 | riscv:riscv64*)
418			ESP=yes
419			BOOTPARTS=
420			ROOTFSPART="-p ${FSPARTTYPE}/rootfs:=${VMBASE}"
421			MAKEFSARGS="$MAKEFSARGS -B little"
422			;;
423		powerpc:powerpc*)
424			ESP=no
425			BOOTPARTS="-p prepboot:=${BOOTFILES}/powerpc/boot1.chrp/boot1.elf -a 1"
426			ROOTFSPART="-p freebsd:=${VMBASE}"
427			if [ ${TARGET_ARCH} = powerpc64le ]; then
428				MAKEFSARGS="$MAKEFSARGS -B little"
429			else
430				MAKEFSARGS="$MAKEFSARGS -B big"
431			fi
432			;;
433		*)
434			echo "vmimage.subr: unsupported target '${TARGET}:${TARGET_ARCH}'" >&2
435			exit 1
436			;;
437	esac
438
439	if [ ${ESP} = "yes" ]; then
440		# Create an ESP
441		espfilename=$(mktemp /tmp/efiboot.XXXXXX)
442		make_esp_file ${espfilename} ${fat32min} ${BOOTFILES}/efi/loader_lua/loader_lua.efi
443		espsuffix=""
444		if [ -z "${BOOTPARTS}" ]; then
445			espsuffix="${BOOTPARTSOFFSET}"
446		fi
447		BOOTPARTS="${BOOTPARTS} -p efi/efiboot0:=${espfilename}${espsuffix}"
448
449		# Add this to fstab
450		mkdir -p ${DESTDIR}/boot/efi
451		echo "/dev/${ROOTLABEL}/efiboot0	/boot/efi       msdosfs     rw      2       2" \
452			>> ${DESTDIR}/etc/fstab
453	fi
454
455	# Add a marker file which indicates that this image has never
456	# been booted.  Some services run only upon the first boot.
457	touch ${DESTDIR}/firstboot
458	metalog_add_data ./firstboot
459
460	echo "Building filesystem...  Please wait."
461	buildfs
462
463	echo "Building final disk image...  Please wait."
464	${MKIMG} -s ${PARTSCHEME} -f ${VMFORMAT} \
465		${BOOTPARTS} \
466		${SWAPOPT} \
467		${CONFIG_DRIVE} \
468		${ROOTFSPART} \
469		-o ${VMIMAGE}
470
471	echo "Disk image ${VMIMAGE} created."
472
473	if [ ${ESP} = "yes" ]; then
474		rm ${espfilename}
475	fi
476
477	return 0
478}
479
480vm_extra_create_disk() {
481
482	return 0
483}
484