xref: /aosp_15_r20/external/crosvm/tools/examples/example_simple (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1#!/bin/bash
2# Copyright 2022 The ChromiumOS Authors
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6# Example VM with a simple ubuntu guest OS but no UI, audio or networking.
7
8set -e
9
10SRC=$(realpath "$(dirname "${BASH_SOURCE[0]}")")
11mkdir -p "$SRC/images/simple" && cd "$_"
12
13if ! [ -f rootfs ]; then
14    # ANCHOR: build
15    # Build a simple ubuntu image and create a user with no password.
16    virt-builder ubuntu-20.04 \
17        --run-command "useradd -m -g sudo -p '' $USER ; chage -d 0 $USER" \
18        -o ./rootfs
19    # Packages can be pre-installed to the image using
20    # --install PACKAGE_NAME
21    # Ex: virt-builder ubuntu-20.04 ... --install openssh-server,ncat
22    # In this example, the ubuntu image will come pre-installed with OpenSSH-server and with Ncat.
23    # ANCHOR_END: build
24
25    # ANCHOR: kernel
26    virt-builder --get-kernel ./rootfs -o .
27    # ANCHOR_END: kernel
28fi
29
30if [ "$(groups | grep kvm -c)" -eq 0 ]; then
31    echo "Adding user $USER to the kvm group to grant access to /dev/kvm"
32    # ANCHOR: kvm
33    sudo adduser "$USER" kvm
34    # ANCHOR_END: kvm
35    echo "Please logout and log back in to reflect the kvm group."
36    exit 1
37fi
38
39# ANCHOR: run
40# Create `/var/empty` where crosvm can do chroot for jailing each virtio device.
41# Devices can't be jailed if /var/empty doesn't exist.
42# You can change this directory(/var/empty) by setting the environment variable: DEFAULT_PIVOT_ROOT
43sudo mkdir -p /var/empty
44# Run crosvm.
45# The rootfs is an image of a partitioned hard drive, so we need to tell
46# the kernel which partition to use (vda5 in case of ubuntu-20.04).
47cargo run --no-default-features -- run \
48    --rwdisk ./rootfs \
49    --initrd ./initrd.img-* \
50    -p "root=/dev/vda5" \
51    ./vmlinuz-*
52# ANCHOR_END: run
53