xref: /cloud-hypervisor/scripts/dev_cli.sh (revision 4552d07a80dcdd93cf4ff8c466592a36497d0c51)
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="20220223-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 [--unit|--cargo|--all] [--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 "        --cargo                      Run the cargo tests."
190    echo "        --integration                Run the integration tests."
191    echo "        --integration-sgx            Run the SGX integration tests."
192    echo "        --integration-vfio           Run the VFIO integration tests."
193    echo "        --integration-windows        Run the Windows guest integration tests."
194    echo "        --integration-live-migration Run the live-migration integration tests."
195    echo "        --libc                       Select the C library Cloud Hypervisor will be built against. Default is gnu"
196    echo "        --metrics                    Generate performance metrics"
197    echo "        --volumes                    Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
198    echo "        --hypervisor                 Underlying hypervisor. Options kvm, mshv"
199    echo "        --all                        Run all tests."
200    echo ""
201    echo "    build-container [--type]"
202    echo "        Build the Cloud Hypervisor container."
203    echo ""
204    echo "    clean [<cargo args>]]"
205    echo "        Remove the Cloud Hypervisor artifacts."
206    echo ""
207    echo "    shell"
208    echo "        Run the development container into an interactive, privileged BASH shell."
209    echo "        --volumes             Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
210    echo ""
211    echo "    help"
212    echo "        Display this help message."
213    echo ""
214}
215
216cmd_build() {
217    build="debug"
218    libc="gnu"
219    hypervisor="kvm"
220    features_build=""
221    exported_device="/dev/kvm"
222    while [ $# -gt 0 ]; do
223        case "$1" in
224        "-h" | "--help") {
225            cmd_help
226            exit 1
227        } ;;
228        "--debug") { build="debug"; } ;;
229        "--release") { build="release"; } ;;
230        "--libc")
231            shift
232            [[ "$1" =~ ^(musl|gnu)$ ]] ||
233                die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
234            libc="$1"
235            ;;
236        "--volumes")
237            shift
238            arg_vols="$1"
239            ;;
240        "--hypervisor")
241            shift
242            hypervisor="$1"
243            ;;
244        "--") {
245            shift
246            break
247        } ;;
248        *)
249            die "Unknown build argument: $1. Please use --help for help."
250            ;;
251        esac
252        shift
253    done
254
255    ensure_build_dir
256    ensure_latest_ctr
257
258    process_volumes_args
259    if [[ ! ("$hypervisor" = "kvm" || "$hypervisor" = "mshv") ]]; then
260        die "Hypervisor value must be kvm or mshv"
261    fi
262    if [[ "$hypervisor" = "mshv" ]]; then
263        exported_device="/dev/mshv"
264    fi
265    target="$(uname -m)-unknown-linux-${libc}"
266
267    cargo_args=("$@")
268    [ $build = "release" ] && cargo_args+=("--release")
269    cargo_args+=(--target "$target")
270    [ "$(uname -m)" = "aarch64" ] && cargo_args+=("--no-default-features")
271    [ "$(uname -m)" = "aarch64" ] && cargo_args+=(--features "$hypervisor")
272
273    rustflags=""
274    if [ "$(uname -m)" = "aarch64" ] && [ "$libc" = "musl" ]; then
275        rustflags="-C link-arg=-lgcc -C link_arg=-specs -C link_arg=/usr/lib/aarch64-linux-musl/musl-gcc.specs"
276    fi
277
278    $DOCKER_RUNTIME run \
279        --user "$(id -u):$(id -g)" \
280        --workdir "$CTR_CLH_ROOT_DIR" \
281        --rm \
282        --volume $exported_device \
283        --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
284        --env RUSTFLAGS="$rustflags" \
285        "$CTR_IMAGE" \
286        cargo build --all "$features_build" \
287        --target-dir "$CTR_CLH_CARGO_TARGET" \
288        "${cargo_args[@]}" && say "Binaries placed under $CLH_CARGO_TARGET/$target/$build"
289}
290
291cmd_clean() {
292    cargo_args=("$@")
293
294    ensure_build_dir
295    ensure_latest_ctr
296
297    $DOCKER_RUNTIME run \
298        --user "$(id -u):$(id -g)" \
299        --workdir "$CTR_CLH_ROOT_DIR" \
300        --rm \
301        --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
302        "$CTR_IMAGE" \
303        cargo clean \
304        --target-dir "$CTR_CLH_CARGO_TARGET" \
305        "${cargo_args[@]}"
306}
307
308cmd_tests() {
309    unit=false
310    cargo=false
311    integration=false
312    integration_sgx=false
313    integration_vfio=false
314    integration_windows=false
315    integration_live_migration=false
316    metrics=false
317    libc="gnu"
318    arg_vols=""
319    hypervisor="kvm"
320    exported_device="/dev/kvm"
321    while [ $# -gt 0 ]; do
322        case "$1" in
323        "-h" | "--help") {
324            cmd_help
325            exit 1
326        } ;;
327        "--unit") { unit=true; } ;;
328        "--cargo") { cargo=true; } ;;
329        "--integration") { integration=true; } ;;
330        "--integration-sgx") { integration_sgx=true; } ;;
331        "--integration-vfio") { integration_vfio=true; } ;;
332        "--integration-windows") { integration_windows=true; } ;;
333        "--integration-live-migration") { integration_live_migration=true; } ;;
334        "--metrics") { metrics=true; } ;;
335        "--libc")
336            shift
337            [[ "$1" =~ ^(musl|gnu)$ ]] ||
338                die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
339            libc="$1"
340            ;;
341        "--volumes")
342            shift
343            arg_vols="$1"
344            ;;
345        "--hypervisor")
346            shift
347            hypervisor="$1"
348            ;;
349        "--all") {
350            cargo=true
351            unit=true
352            integration=true
353        } ;;
354        "--") {
355            shift
356            break
357        } ;;
358        *)
359            die "Unknown tests argument: $1. Please use --help for help."
360            ;;
361        esac
362        shift
363    done
364    if [[ ! ("$hypervisor" = "kvm" || "$hypervisor" = "mshv") ]]; then
365        die "Hypervisor value must be kvm or mshv"
366    fi
367
368    if [[ "$hypervisor" = "mshv" ]]; then
369        exported_device="/dev/mshv"
370    fi
371
372    set -- '--hypervisor' "$hypervisor" "$@"
373
374    ensure_build_dir
375    ensure_latest_ctr
376
377    process_volumes_args
378    target="$(uname -m)-unknown-linux-${libc}"
379
380    if [[ "$unit" = true ]]; then
381        say "Running unit tests for $target..."
382        $DOCKER_RUNTIME run \
383            --workdir "$CTR_CLH_ROOT_DIR" \
384            --rm \
385            --device $exported_device \
386            --device /dev/net/tun \
387            --cap-add net_admin \
388            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
389            --env BUILD_TARGET="$target" \
390            "$CTR_IMAGE" \
391            ./scripts/run_unit_tests.sh "$@" || fix_dir_perms $? || exit $?
392    fi
393
394    if [ "$cargo" = true ]; then
395        say "Running cargo tests..."
396        $DOCKER_RUNTIME run \
397            --workdir "$CTR_CLH_ROOT_DIR" \
398            --rm \
399            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
400            "$CTR_IMAGE" \
401            ./scripts/run_cargo_tests.sh "$@" || fix_dir_perms $? || exit $?
402    fi
403
404    if [ "$integration" = true ]; then
405        say "Running integration tests for $target..."
406        $DOCKER_RUNTIME run \
407            --workdir "$CTR_CLH_ROOT_DIR" \
408            --rm \
409            --privileged \
410            --security-opt seccomp=unconfined \
411            --ipc=host \
412            --net="$CTR_CLH_NET" \
413            --mount type=tmpfs,destination=/tmp \
414            --volume /dev:/dev \
415            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
416            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
417            --env USER="root" \
418            --env CH_LIBC="${libc}" \
419            "$CTR_IMAGE" \
420            ./scripts/run_integration_tests_"$(uname -m)".sh "$@" || fix_dir_perms $? || exit $?
421    fi
422
423    if [ "$integration_sgx" = true ]; then
424        say "Running SGX integration tests for $target..."
425        $DOCKER_RUNTIME run \
426            --workdir "$CTR_CLH_ROOT_DIR" \
427            --rm \
428            --privileged \
429            --security-opt seccomp=unconfined \
430            --ipc=host \
431            --net="$CTR_CLH_NET" \
432            --mount type=tmpfs,destination=/tmp \
433            --volume /dev:/dev \
434            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
435            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
436            --env USER="root" \
437            --env CH_LIBC="${libc}" \
438            "$CTR_IMAGE" \
439            ./scripts/run_integration_tests_sgx.sh "$@" || fix_dir_perms $? || exit $?
440    fi
441
442    if [ "$integration_vfio" = true ]; then
443        say "Running VFIO integration tests for $target..."
444        $DOCKER_RUNTIME run \
445            --workdir "$CTR_CLH_ROOT_DIR" \
446            --rm \
447            --privileged \
448            --security-opt seccomp=unconfined \
449            --ipc=host \
450            --net="$CTR_CLH_NET" \
451            --mount type=tmpfs,destination=/tmp \
452            --volume /dev:/dev \
453            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
454            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
455            --env USER="root" \
456            --env CH_LIBC="${libc}" \
457            "$CTR_IMAGE" \
458            ./scripts/run_integration_tests_vfio.sh "$@" || fix_dir_perms $? || exit $?
459    fi
460
461    if [ "$integration_windows" = true ]; then
462        say "Running Windows integration tests for $target..."
463        $DOCKER_RUNTIME run \
464            --workdir "$CTR_CLH_ROOT_DIR" \
465            --rm \
466            --privileged \
467            --security-opt seccomp=unconfined \
468            --ipc=host \
469            --net="$CTR_CLH_NET" \
470            --mount type=tmpfs,destination=/tmp \
471            --volume /dev:/dev \
472            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
473            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
474            --env USER="root" \
475            --env CH_LIBC="${libc}" \
476            "$CTR_IMAGE" \
477            ./scripts/run_integration_tests_windows.sh "$@" || fix_dir_perms $? || exit $?
478    fi
479
480    if [ "$integration_live_migration" = true ]; then
481        say "Running 'live migration' integration tests for $target..."
482        $DOCKER_RUNTIME run \
483            --workdir "$CTR_CLH_ROOT_DIR" \
484            --rm \
485            --privileged \
486            --security-opt seccomp=unconfined \
487            --ipc=host \
488            --net="$CTR_CLH_NET" \
489            --mount type=tmpfs,destination=/tmp \
490            --volume /dev:/dev \
491            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
492            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
493            --env USER="root" \
494            --env CH_LIBC="${libc}" \
495            "$CTR_IMAGE" \
496            ./scripts/run_integration_tests_live_migration.sh "$@" || fix_dir_perms $? || exit $?
497    fi
498
499    if [ "$metrics" = true ]; then
500        say "Generating performance metrics for $target..."
501        $DOCKER_RUNTIME run \
502            --workdir "$CTR_CLH_ROOT_DIR" \
503            --rm \
504            --privileged \
505            --security-opt seccomp=unconfined \
506            --ipc=host \
507            --net="$CTR_CLH_NET" \
508            --mount type=tmpfs,destination=/tmp \
509            --volume /dev:/dev \
510            --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
511            --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
512            --env USER="root" \
513            --env CH_LIBC="${libc}" \
514            "$CTR_IMAGE" \
515            ./scripts/run_metrics.sh "$@" || fix_dir_perms $? || exit $?
516    fi
517
518    fix_dir_perms $?
519}
520
521build_container() {
522    ensure_build_dir
523
524    BUILD_DIR=/tmp/cloud-hypervisor/container/
525
526    mkdir -p $BUILD_DIR
527    cp "$CLH_DOCKERFILE" $BUILD_DIR
528
529    [ "$(uname -m)" = "aarch64" ] && TARGETARCH="arm64"
530    [ "$(uname -m)" = "x86_64" ] && TARGETARCH="amd64"
531
532    $DOCKER_RUNTIME build \
533        --target dev \
534        -t $CTR_IMAGE \
535        -f $BUILD_DIR/Dockerfile \
536        --build-arg TARGETARCH=$TARGETARCH \
537        $BUILD_DIR
538}
539
540cmd_build-container() {
541    while [ $# -gt 0 ]; do
542        case "$1" in
543        "-h" | "--help") {
544            cmd_help
545            exit 1
546        } ;;
547        "--") {
548            shift
549            break
550        } ;;
551        *)
552            die "Unknown build-container argument: $1. Please use --help for help."
553            ;;
554        esac
555        shift
556    done
557
558    build_container
559}
560
561cmd_shell() {
562    while [ $# -gt 0 ]; do
563        case "$1" in
564        "-h" | "--help") {
565            cmd_help
566            exit 1
567        } ;;
568        "--volumes")
569            shift
570            arg_vols="$1"
571            ;;
572        "--") {
573            shift
574            break
575        } ;;
576        *) ;;
577
578        esac
579        shift
580    done
581    ensure_build_dir
582    ensure_latest_ctr
583    process_volumes_args
584    say_warn "Starting a privileged shell prompt as root ..."
585    say_warn "WARNING: Your $CLH_ROOT_DIR folder will be bind-mounted in the container under $CTR_CLH_ROOT_DIR"
586    $DOCKER_RUNTIME run \
587        -ti \
588        --workdir "$CTR_CLH_ROOT_DIR" \
589        --rm \
590        --privileged \
591        --security-opt seccomp=unconfined \
592        --ipc=host \
593        --net="$CTR_CLH_NET" \
594        --tmpfs /tmp:exec \
595        --volume /dev:/dev \
596        --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
597        --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
598        --env USER="root" \
599        --entrypoint bash \
600        "$CTR_IMAGE"
601
602    fix_dir_perms $?
603}
604
605# Parse main command line args.
606#
607while [ $# -gt 0 ]; do
608    case "$1" in
609    -h | --help) {
610        cmd_help
611        exit 1
612    } ;;
613    --local) {
614        CTR_IMAGE_VERSION="local"
615        CTR_IMAGE="${CTR_IMAGE_TAG}:${CTR_IMAGE_VERSION}"
616    } ;;
617    -*)
618        die "Unknown arg: $1. Please use \`$0 help\` for help."
619        ;;
620    *)
621        break
622        ;;
623    esac
624    shift
625done
626
627# $1 is now a command name. Check if it is a valid command and, if so,
628# run it.
629#
630declare -f "cmd_$1" >/dev/null
631ok_or_die "Unknown command: $1. Please use \`$0 help\` for help."
632
633cmd=cmd_$1
634shift
635
636$cmd "$@"
637