xref: /cloud-hypervisor/scripts/dev_cli.sh (revision b440cb7d2330770cd415b63544a371d4caa2db3a)
1#!/bin/bash
2
3# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4# Copyright © 2020 Intel Corporation
5# SPDX-License-Identifier: Apache-2.0
6
7CLI_NAME="Cloud Hypervisor"
8
9CTR_IMAGE_TAG="cloudhypervisor/dev"
10CTR_IMAGE_VERSION="20220705-0"
11CTR_IMAGE="${CTR_IMAGE_TAG}:${CTR_IMAGE_VERSION}"
12
13DOCKER_RUNTIME="docker"
14
15# Host paths
16CLH_SCRIPTS_DIR=$(cd "$(dirname "$0")" && pwd)
17CLH_ROOT_DIR=$(cd "${CLH_SCRIPTS_DIR}/.." && pwd)
18CLH_BUILD_DIR="${CLH_ROOT_DIR}/build"
19CLH_CARGO_TARGET="${CLH_BUILD_DIR}/cargo_target"
20CLH_DOCKERFILE="${CLH_SCRIPTS_DIR}/../resources/Dockerfile"
21CLH_CTR_BUILD_DIR="/tmp/cloud-hypervisor/ctr-build"
22CLH_INTEGRATION_WORKLOADS="${HOME}/workloads"
23
24# Container paths
25CTR_CLH_ROOT_DIR="/cloud-hypervisor"
26CTR_CLH_CARGO_BUILT_DIR="${CTR_CLH_ROOT_DIR}/build"
27CTR_CLH_CARGO_TARGET="${CTR_CLH_CARGO_BUILT_DIR}/cargo_target"
28CTR_CLH_INTEGRATION_WORKLOADS="/root/workloads"
29
30# Container networking option
31CTR_CLH_NET="bridge"
32
33# Cargo paths
34# Full path to the cargo registry dir on the host. This appears on the host
35# because we want to persist the cargo registry across container invocations.
36# Otherwise, any rust crates from crates.io would be downloaded again each time
37# we build or test.
38CARGO_REGISTRY_DIR="${CLH_BUILD_DIR}/cargo_registry"
39
40# Full path to the cargo git registry on the host. This serves the same purpose
41# as CARGO_REGISTRY_DIR, for crates downloaded from GitHub repos instead of
42# crates.io.
43CARGO_GIT_REGISTRY_DIR="${CLH_BUILD_DIR}/cargo_git_registry"
44
45# Full path to the cargo target dir on the host.
46CARGO_TARGET_DIR="${CLH_BUILD_DIR}/cargo_target"
47
48# Send a decorated message to stdout, followed by a new line
49#
50say() {
51    [ -t 1 ] && [ -n "$TERM" ] &&
52        echo "$(tput setaf 2)[$CLI_NAME]$(tput sgr0) $*" ||
53        echo "[$CLI_NAME] $*"
54}
55
56# Send a decorated message to stdout, without a trailing new line
57#
58say_noln() {
59    [ -t 1 ] && [ -n "$TERM" ] &&
60        echo -n "$(tput setaf 2)[$CLI_NAME]$(tput sgr0) $*" ||
61        echo "[$CLI_NAME] $*"
62}
63
64# Send a text message to stderr
65#
66say_err() {
67    [ -t 2 ] && [ -n "$TERM" ] &&
68        echo "$(tput setaf 1)[$CLI_NAME] $*$(tput sgr0)" 1>&2 ||
69        echo "[$CLI_NAME] $*" 1>&2
70}
71
72# Send a warning-highlighted text to stdout
73say_warn() {
74    [ -t 1 ] && [ -n "$TERM" ] &&
75        echo "$(tput setaf 3)[$CLI_NAME] $*$(tput sgr0)" ||
76        echo "[$CLI_NAME] $*"
77}
78
79# Exit with an error message and (optional) code
80# Usage: die [-c <error code>] <error message>
81#
82die() {
83    code=1
84    [[ "$1" = "-c" ]] && {
85        code="$2"
86        shift 2
87    }
88    say_err "$@"
89    exit "$code"
90}
91
92# Exit with an error message if the last exit code is not 0
93#
94ok_or_die() {
95    code=$?
96    [[ $code -eq 0 ]] || die -c $code "$@"
97}
98
99# Make sure the build/ dirs are available. Exit if we can't create them.
100# Upon returning from this call, the caller can be certain the build/ dirs exist.
101#
102ensure_build_dir() {
103    for dir in "$CLH_BUILD_DIR" \
104        "$CLH_INTEGRATION_WORKLOADS" \
105        "$CLH_CTR_BUILD_DIR" \
106        "$CARGO_TARGET_DIR" \
107        "$CARGO_REGISTRY_DIR" \
108        "$CARGO_GIT_REGISTRY_DIR"; do
109        mkdir -p "$dir" || die "Error: cannot create dir $dir"
110        [ -x "$dir" ] && [ -w "$dir" ] ||
111            {
112                say "Wrong permissions for $dir. Attempting to fix them ..."
113                chmod +x+w "$dir"
114            } ||
115            die "Error: wrong permissions for $dir. Should be +x+w"
116    done
117}
118
119# Make sure we're using the latest dev container, by just pulling it.
120ensure_latest_ctr() {
121    if [ "$CTR_IMAGE_VERSION" = "local" ]; then
122        build_container
123    else
124        $DOCKER_RUNTIME pull "$CTR_IMAGE"
125
126        if [ $? -ne 0 ]; then
127            build_container
128        fi
129
130        ok_or_die "Error pulling/building container image. Aborting."
131    fi
132}
133
134# Fix main directory permissions after a container ran as root.
135# Since the container ran as root, any files it creates will be owned by root.
136# This fixes that by recursively changing the ownership of /cloud-hypervisor to the
137# current user.
138#
139fix_dir_perms() {
140    # Yes, running Docker to get elevated privileges, just to chown some files
141    # is a dirty hack.
142    $DOCKER_RUNTIME run \
143        --workdir "$CTR_CLH_ROOT_DIR" \
144        --rm \
145        --volume /dev:/dev \
146        --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
147        "$CTR_IMAGE" \
148        chown -R "$(id -u):$(id -g)" "$CTR_CLH_ROOT_DIR"
149
150    return "$1"
151}
152# Process exported volumes argument, separate the volumes and make docker compatible
153# Sample input: --volumes /a:/a#/b:/b
154# Sample output: --volume /a:/a --volume /b:/b
155#
156process_volumes_args() {
157    if [ -z "$arg_vols" ]; then
158        return
159    fi
160    exported_volumes=""
161    arr_vols=(${arg_vols//#/ })
162    for var in "${arr_vols[@]}"; do
163        parts=(${var//:/ })
164        if [[ ! -e "${parts[0]}" ]]; then
165            echo "The volume ${parts[0]} does not exist."
166            exit 1
167        fi
168        exported_volumes="$exported_volumes --volume $var"
169    done
170}
171cmd_help() {
172    echo ""
173    echo "Cloud Hypervisor $(basename "$0")"
174    echo "Usage: $(basename "$0") <command> [<command args>]"
175    echo ""
176    echo "Available commands:"
177    echo ""
178    echo "    build [--debug|--release] [--libc musl|gnu] [-- [<cargo args>]]"
179    echo "        Build the Cloud Hypervisor binaries."
180    echo "        --debug               Build the debug binaries. This is the default."
181    echo "        --release             Build the release binaries."
182    echo "        --libc                Select the C library Cloud Hypervisor will be built against. Default is gnu"
183    echo "        --volumes             Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
184    echo "        --hypervisor          Underlying hypervisor. Options kvm, mshv"
185    echo ""
186    echo "    tests [<test type (see below)>] [--libc musl|gnu] [-- [<test scripts args>] [-- [<test binary args>]]] "
187    echo "        Run the Cloud Hypervisor tests."
188    echo "        --unit                       Run the unit tests."
189    echo "        --integration                Run the integration tests."
190    echo "        --integration-sgx            Run the SGX integration tests."
191    echo "        --integration-vfio           Run the VFIO integration tests."
192    echo "        --integration-windows        Run the Windows guest integration tests."
193    echo "        --integration-live-migration Run the live-migration integration tests."
194    echo "        --libc                       Select the C library Cloud Hypervisor will be built against. Default is gnu"
195    echo "        --metrics                    Generate performance metrics"
196    echo "        --volumes                    Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
197    echo "        --hypervisor                 Underlying hypervisor. Options kvm, mshv"
198    echo "        --all                        Run all tests."
199    echo ""
200    echo "    build-container [--type]"
201    echo "        Build the Cloud Hypervisor container."
202    echo ""
203    echo "    clean [<cargo args>]]"
204    echo "        Remove the Cloud Hypervisor artifacts."
205    echo ""
206    echo "    shell"
207    echo "        Run the development container into an interactive, privileged BASH shell."
208    echo "        --volumes             Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
209    echo ""
210    echo "    help"
211    echo "        Display this help message."
212    echo ""
213}
214
215cmd_build() {
216    build="debug"
217    libc="gnu"
218    hypervisor="kvm"
219    features_build=""
220    exported_device="/dev/kvm"
221    while [ $# -gt 0 ]; do
222        case "$1" in
223        "-h" | "--help") {
224            cmd_help
225            exit 1
226        } ;;
227        "--debug") { build="debug"; } ;;
228        "--release") { build="release"; } ;;
229        "--runtime")
230	    shift
231	    DOCKER_RUNTIME="$1"
232	    export DOCKER_RUNTIME
233	    ;;
234        "--libc")
235            shift
236            [[ "$1" =~ ^(musl|gnu)$ ]] ||
237                die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
238            libc="$1"
239            ;;
240        "--volumes")
241            shift
242            arg_vols="$1"
243            ;;
244        "--hypervisor")
245            shift
246            hypervisor="$1"
247            ;;
248        "--features")
249            shift
250            features_build="--features $1"
251            ;;
252        "--") {
253            shift
254            break
255        } ;;
256        *)
257            die "Unknown build argument: $1. Please use --help for help."
258            ;;
259        esac
260        shift
261    done
262
263    ensure_build_dir
264    ensure_latest_ctr
265
266    process_volumes_args
267    if [[ ! ("$hypervisor" = "kvm" || "$hypervisor" = "mshv") ]]; then
268        die "Hypervisor value must be kvm or mshv"
269    fi
270    if [[ "$hypervisor" = "mshv" ]]; then
271        exported_device="/dev/mshv"
272    fi
273    target="$(uname -m)-unknown-linux-${libc}"
274
275    cargo_args=("$@")
276    [ $build = "release" ] && cargo_args+=("--release")
277    cargo_args+=(--target "$target")
278
279    rustflags=""
280    target_cc=""
281    if [ "$(uname -m)" = "aarch64" ] && [ "$libc" = "musl" ]; then
282        rustflags="-C link-arg=-lgcc -C link_arg=-specs -C link_arg=/usr/lib/aarch64-linux-musl/musl-gcc.specs"
283        target_cc="musl-gcc"
284    fi
285
286    $DOCKER_RUNTIME run \
287        --user "$(id -u):$(id -g)" \
288        --workdir "$CTR_CLH_ROOT_DIR" \
289        --rm \
290        --volume $exported_device \
291        --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
292        --env RUSTFLAGS="$rustflags" \
293        --env TARGET_CC="$target_cc" \
294        "$CTR_IMAGE" \
295        cargo build --all $features_build \
296        --target-dir "$CTR_CLH_CARGO_TARGET" \
297        "${cargo_args[@]}" && say "Binaries placed under $CLH_CARGO_TARGET/$target/$build"
298}
299
300cmd_clean() {
301    cargo_args=("$@")
302
303    ensure_build_dir
304    ensure_latest_ctr
305
306    $DOCKER_RUNTIME run \
307        --user "$(id -u):$(id -g)" \
308        --workdir "$CTR_CLH_ROOT_DIR" \
309        --rm \
310        --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
311        "$CTR_IMAGE" \
312        cargo clean \
313        --target-dir "$CTR_CLH_CARGO_TARGET" \
314        "${cargo_args[@]}"
315}
316
317cmd_tests() {
318    unit=false
319    integration=false
320    integration_sgx=false
321    integration_vfio=false
322    integration_windows=false
323    integration_live_migration=false
324    metrics=false
325    libc="gnu"
326    arg_vols=""
327    hypervisor="kvm"
328    exported_device="/dev/kvm"
329    while [ $# -gt 0 ]; do
330        case "$1" in
331        "-h" | "--help") {
332            cmd_help
333            exit 1
334        } ;;
335        "--unit") { unit=true; } ;;
336        "--integration") { integration=true; } ;;
337        "--integration-sgx") { integration_sgx=true; } ;;
338        "--integration-vfio") { integration_vfio=true; } ;;
339        "--integration-windows") { integration_windows=true; } ;;
340        "--integration-live-migration") { integration_live_migration=true; } ;;
341        "--metrics") { metrics=true; } ;;
342        "--libc")
343            shift
344            [[ "$1" =~ ^(musl|gnu)$ ]] ||
345                die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
346            libc="$1"
347            ;;
348        "--volumes")
349            shift
350            arg_vols="$1"
351            ;;
352        "--hypervisor")
353            shift
354            hypervisor="$1"
355            ;;
356        "--all") {
357            cargo=true
358            unit=true
359            integration=true
360        } ;;
361        "--") {
362            shift
363            break
364        } ;;
365        *)
366            die "Unknown tests argument: $1. Please use --help for help."
367            ;;
368        esac
369        shift
370    done
371    if [[ ! ("$hypervisor" = "kvm" || "$hypervisor" = "mshv") ]]; then
372        die "Hypervisor value must be kvm or mshv"
373    fi
374
375    if [[ "$hypervisor" = "mshv" ]]; then
376        exported_device="/dev/mshv"
377    fi
378
379    set -- '--hypervisor' "$hypervisor" "$@"
380
381    ensure_build_dir
382    ensure_latest_ctr
383
384    process_volumes_args
385    target="$(uname -m)-unknown-linux-${libc}"
386
387    if [[ "$unit" = true ]]; then
388        say "Running unit tests for $target..."
389        $DOCKER_RUNTIME run \
390            --workdir "$CTR_CLH_ROOT_DIR" \
391            --rm \
392            --device $exported_device \
393            --device /dev/net/tun \
394            --cap-add net_admin \
395            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
396            --env BUILD_TARGET="$target" \
397            "$CTR_IMAGE" \
398            ./scripts/run_unit_tests.sh "$@" || fix_dir_perms $? || exit $?
399    fi
400
401    if [ "$integration" = true ]; then
402        say "Running integration tests for $target..."
403        $DOCKER_RUNTIME run \
404            --workdir "$CTR_CLH_ROOT_DIR" \
405            --rm \
406            --privileged \
407            --security-opt seccomp=unconfined \
408            --ipc=host \
409            --net="$CTR_CLH_NET" \
410            --mount type=tmpfs,destination=/tmp \
411            --volume /dev:/dev \
412            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
413            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
414            --env USER="root" \
415            --env CH_LIBC="${libc}" \
416            "$CTR_IMAGE" \
417            ./scripts/run_integration_tests_"$(uname -m)".sh "$@" || fix_dir_perms $? || exit $?
418    fi
419
420    if [ "$integration_sgx" = true ]; then
421        say "Running SGX integration tests for $target..."
422        $DOCKER_RUNTIME run \
423            --workdir "$CTR_CLH_ROOT_DIR" \
424            --rm \
425            --privileged \
426            --security-opt seccomp=unconfined \
427            --ipc=host \
428            --net="$CTR_CLH_NET" \
429            --mount type=tmpfs,destination=/tmp \
430            --volume /dev:/dev \
431            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
432            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
433            --env USER="root" \
434            --env CH_LIBC="${libc}" \
435            "$CTR_IMAGE" \
436            ./scripts/run_integration_tests_sgx.sh "$@" || fix_dir_perms $? || exit $?
437    fi
438
439    if [ "$integration_vfio" = true ]; then
440        say "Running VFIO integration tests for $target..."
441        $DOCKER_RUNTIME run \
442            --workdir "$CTR_CLH_ROOT_DIR" \
443            --rm \
444            --privileged \
445            --security-opt seccomp=unconfined \
446            --ipc=host \
447            --net="$CTR_CLH_NET" \
448            --mount type=tmpfs,destination=/tmp \
449            --volume /dev:/dev \
450            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
451            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
452            --env USER="root" \
453            --env CH_LIBC="${libc}" \
454            "$CTR_IMAGE" \
455            ./scripts/run_integration_tests_vfio.sh "$@" || fix_dir_perms $? || exit $?
456    fi
457
458    if [ "$integration_windows" = true ]; then
459        say "Running Windows integration tests for $target..."
460        $DOCKER_RUNTIME run \
461            --workdir "$CTR_CLH_ROOT_DIR" \
462            --rm \
463            --privileged \
464            --security-opt seccomp=unconfined \
465            --ipc=host \
466            --net="$CTR_CLH_NET" \
467            --mount type=tmpfs,destination=/tmp \
468            --volume /dev:/dev \
469            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
470            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
471            --env USER="root" \
472            --env CH_LIBC="${libc}" \
473            "$CTR_IMAGE" \
474            ./scripts/run_integration_tests_windows.sh "$@" || fix_dir_perms $? || exit $?
475    fi
476
477    if [ "$integration_live_migration" = true ]; then
478        say "Running 'live migration' integration tests for $target..."
479        $DOCKER_RUNTIME run \
480            --workdir "$CTR_CLH_ROOT_DIR" \
481            --rm \
482            --privileged \
483            --security-opt seccomp=unconfined \
484            --ipc=host \
485            --net="$CTR_CLH_NET" \
486            --mount type=tmpfs,destination=/tmp \
487            --volume /dev:/dev \
488            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
489            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
490            --env USER="root" \
491            --env CH_LIBC="${libc}" \
492            "$CTR_IMAGE" \
493            ./scripts/run_integration_tests_live_migration.sh "$@" || fix_dir_perms $? || exit $?
494    fi
495
496    if [ "$metrics" = true ]; then
497        say "Generating performance metrics for $target..."
498        $DOCKER_RUNTIME run \
499            --workdir "$CTR_CLH_ROOT_DIR" \
500            --rm \
501            --privileged \
502            --security-opt seccomp=unconfined \
503            --ipc=host \
504            --net="$CTR_CLH_NET" \
505            --mount type=tmpfs,destination=/tmp \
506            --volume /dev:/dev \
507            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
508            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
509            --env USER="root" \
510            --env CH_LIBC="${libc}" \
511            "$CTR_IMAGE" \
512            ./scripts/run_metrics.sh "$@" || fix_dir_perms $? || exit $?
513    fi
514
515    fix_dir_perms $?
516}
517
518build_container() {
519    ensure_build_dir
520
521    BUILD_DIR=/tmp/cloud-hypervisor/container/
522
523    mkdir -p $BUILD_DIR
524    cp "$CLH_DOCKERFILE" $BUILD_DIR
525
526    [ "$(uname -m)" = "aarch64" ] && TARGETARCH="arm64"
527    [ "$(uname -m)" = "x86_64" ] && TARGETARCH="amd64"
528
529    $DOCKER_RUNTIME build \
530        --target dev \
531        -t $CTR_IMAGE \
532        -f $BUILD_DIR/Dockerfile \
533        --build-arg TARGETARCH=$TARGETARCH \
534        $BUILD_DIR
535}
536
537cmd_build-container() {
538    while [ $# -gt 0 ]; do
539        case "$1" in
540        "-h" | "--help") {
541            cmd_help
542            exit 1
543        } ;;
544        "--") {
545            shift
546            break
547        } ;;
548        *)
549            die "Unknown build-container argument: $1. Please use --help for help."
550            ;;
551        esac
552        shift
553    done
554
555    build_container
556}
557
558cmd_shell() {
559    while [ $# -gt 0 ]; do
560        case "$1" in
561        "-h" | "--help") {
562            cmd_help
563            exit 1
564        } ;;
565        "--volumes")
566            shift
567            arg_vols="$1"
568            ;;
569        "--") {
570            shift
571            break
572        } ;;
573        *) ;;
574
575        esac
576        shift
577    done
578    ensure_build_dir
579    ensure_latest_ctr
580    process_volumes_args
581    say_warn "Starting a privileged shell prompt as root ..."
582    say_warn "WARNING: Your $CLH_ROOT_DIR folder will be bind-mounted in the container under $CTR_CLH_ROOT_DIR"
583    $DOCKER_RUNTIME run \
584        -ti \
585        --workdir "$CTR_CLH_ROOT_DIR" \
586        --rm \
587        --privileged \
588        --security-opt seccomp=unconfined \
589        --ipc=host \
590        --net="$CTR_CLH_NET" \
591        --tmpfs /tmp:exec \
592        --volume /dev:/dev \
593        --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
594        --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
595        --env USER="root" \
596        --entrypoint bash \
597        "$CTR_IMAGE"
598
599    fix_dir_perms $?
600}
601
602# Parse main command line args.
603#
604while [ $# -gt 0 ]; do
605    case "$1" in
606    -h | --help) {
607        cmd_help
608        exit 1
609    } ;;
610    --local) {
611        CTR_IMAGE_VERSION="local"
612        CTR_IMAGE="${CTR_IMAGE_TAG}:${CTR_IMAGE_VERSION}"
613    } ;;
614    -*)
615        die "Unknown arg: $1. Please use \`$0 help\` for help."
616        ;;
617    *)
618        break
619        ;;
620    esac
621    shift
622done
623
624# $1 is now a command name. Check if it is a valid command and, if so,
625# run it.
626#
627declare -f "cmd_$1" >/dev/null
628ok_or_die "Unknown command: $1. Please use \`$0 help\` for help."
629
630cmd=cmd_$1
631shift
632
633$cmd "$@"
634