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