xref: /cloud-hypervisor/scripts/dev_cli.sh (revision 9af2968a7dc47b89bf07ea9dc5e735084efcfa3a)
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="latest"
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    $DOCKER_RUNTIME pull "$CTR_IMAGE"
122
123    ok_or_die "Error pulling container image. Aborting."
124}
125
126# Fix main directory permissions after a container ran as root.
127# Since the container ran as root, any files it creates will be owned by root.
128# This fixes that by recursively changing the ownership of /cloud-hypervisor to the
129# current user.
130#
131fix_dir_perms() {
132    # Yes, running Docker to get elevated privileges, just to chown some files
133    # is a dirty hack.
134    $DOCKER_RUNTIME run \
135	--workdir "$CTR_CLH_ROOT_DIR" \
136	   --rm \
137	   --volume /dev:/dev \
138	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
139	   "$CTR_IMAGE" \
140           chown -R "$(id -u):$(id -g)" "$CTR_CLH_ROOT_DIR"
141
142    return $1
143}
144# Process exported volumes argument, separate the volumes and make docker compatible
145# Sample input: --volumes /a:/a#/b:/b
146# Sample output: --volume /a:/a --volume /b:/b
147#
148process_volumes_args() {
149    if [ -z "$arg_vols" ]; then
150        return
151    fi
152    exported_volumes=""
153    arr_vols=(${arg_vols//#/ })
154    for var in "${arr_vols[@]}"
155    do
156        parts=(${var//:/ })
157        if [[ ! -e "${parts[0]}" ]]; then
158            echo "The volume ${parts[0]} does not exist."
159            exit 1
160        fi
161        exported_volumes="$exported_volumes --volume $var"
162    done
163}
164cmd_help() {
165    echo ""
166    echo "Cloud Hypervisor $(basename $0)"
167    echo "Usage: $(basename $0) <command> [<command args>]"
168    echo ""
169    echo "Available commands:"
170    echo ""
171    echo "    build [--debug|--release] [--libc musl|gnu] [-- [<cargo args>]]"
172    echo "        Build the Cloud Hypervisor binaries."
173    echo "        --debug               Build the debug binaries. This is the default."
174    echo "        --release             Build the release binaries."
175    echo "        --libc                Select the C library Cloud Hypervisor will be built against. Default is gnu"
176    echo "        --volumes             Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
177    echo "        --hypervisor          Underlying hypervisor. Options kvm, mshv"
178    echo ""
179    echo "    tests [--unit|--cargo|--all] [--libc musl|gnu] [-- [<cargo test args>]]"
180    echo "        Run the Cloud Hypervisor tests."
181    echo "        --unit                Run the unit tests."
182    echo "        --cargo               Run the cargo tests."
183    echo "        --integration         Run the integration tests."
184    echo "        --integration-sgx     Run the SGX integration tests."
185    echo "        --integration-vfio    Run the VFIO integration tests."
186    echo "        --integration-windows Run the Windows guest integration tests."
187    echo "        --libc                Select the C library Cloud Hypervisor will be built against. Default is gnu"
188    echo "        --volumes             Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
189    echo "        --hypervisor          Underlying hypervisor. Options kvm, mshv"
190    echo "        --all                 Run all tests."
191    echo ""
192    echo "    build-container [--type]"
193    echo "        Build the Cloud Hypervisor container."
194    echo "        --dev                Build dev container. This is the default."
195    echo ""
196    echo "    clean [<cargo args>]]"
197    echo "        Remove the Cloud Hypervisor artifacts."
198    echo ""
199    echo "    shell"
200    echo "        Run the development container into an interactive, privileged BASH shell."
201    echo "        --volumes             Hash separated volumes to be exported. Example --volumes /mnt:/mnt#/myvol:/myvol"
202    echo ""
203    echo "    help"
204    echo "        Display this help message."
205    echo ""
206}
207
208cmd_build() {
209    build="debug"
210    libc="gnu"
211    hypervisor="kvm"
212    features_build=""
213    exported_device="/dev/kvm"
214    while [ $# -gt 0 ]; do
215	case "$1" in
216            "-h"|"--help")  { cmd_help; exit 1; } ;;
217            "--debug")      { build="debug"; } ;;
218            "--release")    { build="release"; } ;;
219            "--libc")
220                shift
221                [[ "$1" =~ ^(musl|gnu)$ ]] || \
222                    die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
223                libc="$1"
224                ;;
225            "--volumes")
226                shift
227                arg_vols="$1"
228                ;;
229            "--hypervisor")
230                shift
231                hypervisor="$1"
232                ;;
233            "--")           { shift; break; } ;;
234            *)
235		die "Unknown build argument: $1. Please use --help for help."
236		;;
237	esac
238	shift
239    done
240
241    ensure_build_dir
242    if [ $(uname -m) = "x86_64" ]; then
243	ensure_latest_ctr
244    fi
245
246    process_volumes_args
247    if [[ "$hypervisor" != "kvm" ]]; then
248        die "Hypervisor value must be kvm"
249    fi
250    if [[ "$hypervisor" = "mshv" ]]; then
251        exported_device="/dev/mshv"
252    fi
253    target="$(uname -m)-unknown-linux-${libc}"
254
255    cargo_args=("$@")
256    [ $build = "release" ] && cargo_args+=("--release")
257    cargo_args+=(--target "$target")
258    [ $(uname -m) = "aarch64" ] && cargo_args+=("--no-default-features")
259    [ $(uname -m) = "aarch64" ] && cargo_args+=(--features $hypervisor)
260
261    rustflags=""
262    if [ $(uname -m) = "aarch64" ] && [ $libc = "musl" ] ; then
263        rustflags="-C link-arg=-lgcc -C link_arg=-specs -C link_arg=/usr/lib/aarch64-linux-musl/musl-gcc.specs"
264    fi
265
266    $DOCKER_RUNTIME run \
267	   --user "$(id -u):$(id -g)" \
268	   --workdir "$CTR_CLH_ROOT_DIR" \
269	   --rm \
270	   --volume $exported_device \
271	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
272	   --env RUSTFLAGS="$rustflags" \
273	   "$CTR_IMAGE" \
274	   cargo build --all $features_build \
275	         --target-dir "$CTR_CLH_CARGO_TARGET" \
276	         "${cargo_args[@]}" && say "Binaries placed under $CLH_CARGO_TARGET/$target/$build"
277}
278
279cmd_clean() {
280    cargo_args=("$@")
281
282    ensure_build_dir
283    if [ $(uname -m) = "x86_64" ]; then
284	ensure_latest_ctr
285    fi
286
287    $DOCKER_RUNTIME run \
288	   --user "$(id -u):$(id -g)" \
289	   --workdir "$CTR_CLH_ROOT_DIR" \
290	   --rm \
291	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
292	   "$CTR_IMAGE" \
293	   cargo clean \
294	         --target-dir "$CTR_CLH_CARGO_TARGET" \
295	         "${cargo_args[@]}"
296    }
297
298cmd_tests() {
299    unit=false
300    cargo=false
301    integration=false
302    integration_sgx=false
303    integration_vfio=false
304    integration_windows=false
305    libc="gnu"
306    arg_vols=""
307    hypervisor="kvm"
308    exported_device="/dev/kvm"
309    while [ $# -gt 0 ]; do
310	case "$1" in
311            "-h"|"--help")           { cmd_help; exit 1; } ;;
312            "--unit")                { unit=true; } ;;
313            "--cargo")               { cargo=true; } ;;
314            "--integration")         { integration=true; } ;;
315            "--integration-sgx")     { integration_sgx=true; } ;;
316            "--integration-vfio")    { integration_vfio=true; } ;;
317            "--integration-windows") { integration_windows=true; } ;;
318            "--libc")
319                shift
320                [[ "$1" =~ ^(musl|gnu)$ ]] || \
321                    die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
322                libc="$1"
323                ;;
324            "--volumes")
325                shift
326                arg_vols="$1"
327                ;;
328            "--hypervisor")
329                shift
330                hypervisor="$1"
331                ;;
332	    "--all")                 { cargo=true; unit=true; integration=true; } ;;
333            "--")                    { shift; break; } ;;
334            *)
335		die "Unknown tests argument: $1. Please use --help for help."
336		;;
337	esac
338	shift
339    done
340    if [[ "$hypervisor" != "kvm" ]]; then
341        die "Hypervisor value must be kvm"
342    fi
343    if [[ "$hypervisor" = "mshv" ]]; then
344        exported_device="/dev/mshv"
345    fi
346    set -- "$@" '--hypervisor' $hypervisor
347
348    ensure_build_dir
349    if [ $(uname -m) = "x86_64" ]; then
350	ensure_latest_ctr
351    fi
352
353    process_volumes_args
354    target="$(uname -m)-unknown-linux-${libc}"
355    cflags=""
356    target_cc=""
357    if [[ "$target" == "x86_64-unknown-linux-musl" ]]; then
358	target_cc="musl-gcc"
359	cflags="-I /usr/include/x86_64-linux-musl/ -idirafter /usr/include/"
360    fi
361
362    if [[ "$unit" = true  ]] ;  then
363	say "Running unit tests for $target..."
364	$DOCKER_RUNTIME run \
365	       --workdir "$CTR_CLH_ROOT_DIR" \
366	       --rm \
367	       --device $exported_device \
368	       --device /dev/net/tun \
369	       --cap-add net_admin \
370	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
371	       --env BUILD_TARGET="$target" \
372	       --env CFLAGS="$cflags" \
373	       --env TARGET_CC="$target_cc" \
374	       "$CTR_IMAGE" \
375	       ./scripts/run_unit_tests.sh "$@" || fix_dir_perms $? || exit $?
376    fi
377
378    if [ "$cargo" = true ] ;  then
379	say "Running cargo tests..."
380	$DOCKER_RUNTIME run \
381	       --workdir "$CTR_CLH_ROOT_DIR" \
382	       --rm \
383	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
384	       "$CTR_IMAGE" \
385	       ./scripts/run_cargo_tests.sh "$@"  || fix_dir_perms $? || exit $?
386    fi
387
388    if [ "$integration" = true ] ;  then
389	say "Running integration tests for $target..."
390	$DOCKER_RUNTIME run \
391	       --workdir "$CTR_CLH_ROOT_DIR" \
392	       --rm \
393	       --privileged \
394	       --security-opt seccomp=unconfined \
395	       --ipc=host \
396	       --net="$CTR_CLH_NET" \
397	       --mount type=tmpfs,destination=/tmp \
398	       --volume /dev:/dev \
399	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
400	       --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
401	       --env USER="root" \
402	       --env CH_LIBC="${libc}" \
403	       "$CTR_IMAGE" \
404	       ./scripts/run_integration_tests_$(uname -m).sh "$@" || fix_dir_perms $? || exit $?
405    fi
406
407    if [ "$integration_sgx" = true ] ;  then
408	say "Running SGX integration tests for $target..."
409	$DOCKER_RUNTIME run \
410	       --workdir "$CTR_CLH_ROOT_DIR" \
411	       --rm \
412	       --privileged \
413	       --security-opt seccomp=unconfined \
414	       --ipc=host \
415	       --net="$CTR_CLH_NET" \
416	       --mount type=tmpfs,destination=/tmp \
417	       --volume /dev:/dev \
418	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
419	       --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
420	       --env USER="root" \
421	       --env CH_LIBC="${libc}" \
422	       "$CTR_IMAGE" \
423	       ./scripts/run_integration_tests_sgx.sh "$@" || fix_dir_perms $? || exit $?
424    fi
425
426    if [ "$integration_vfio" = true ] ;  then
427	say "Running VFIO integration tests for $target..."
428	$DOCKER_RUNTIME run \
429	       --workdir "$CTR_CLH_ROOT_DIR" \
430	       --rm \
431	       --privileged \
432	       --security-opt seccomp=unconfined \
433	       --ipc=host \
434	       --net="$CTR_CLH_NET" \
435	       --mount type=tmpfs,destination=/tmp \
436	       --volume /dev:/dev \
437	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
438	       --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
439	       --env USER="root" \
440	       --env CH_LIBC="${libc}" \
441	       "$CTR_IMAGE" \
442	       ./scripts/run_integration_tests_vfio.sh "$@" || fix_dir_perms $? || exit $?
443    fi
444
445    if [ "$integration_windows" = true ] ;  then
446	say "Running Windows integration tests for $target..."
447	$DOCKER_RUNTIME run \
448	       --workdir "$CTR_CLH_ROOT_DIR" \
449	       --rm \
450	       --privileged \
451	       --security-opt seccomp=unconfined \
452	       --ipc=host \
453	       --net="$CTR_CLH_NET" \
454	       --mount type=tmpfs,destination=/tmp \
455	       --volume /dev:/dev \
456	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR"  $exported_volumes \
457	       --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
458	       --env USER="root" \
459	       --env CH_LIBC="${libc}" \
460	       "$CTR_IMAGE" \
461	       ./scripts/run_integration_tests_windows.sh "$@" || fix_dir_perms $? || exit $?
462    fi
463    fix_dir_perms $?
464}
465
466cmd_build-container() {
467    container_type="dev"
468
469    while [ $# -gt 0 ]; do
470	case "$1" in
471            "-h"|"--help")  { cmd_help; exit 1; } ;;
472            "--dev")        { container_type="dev"; } ;;
473            "--")           { shift; break; } ;;
474            *)
475		die "Unknown build-container argument: $1. Please use --help for help."
476		;;
477	esac
478	shift
479    done
480
481    ensure_build_dir
482    if [ $(uname -m) = "x86_64" ]; then
483	ensure_latest_ctr
484    fi
485
486    BUILD_DIR=/tmp/cloud-hypervisor/container/
487
488    mkdir -p $BUILD_DIR
489    cp $CLH_DOCKERFILE $BUILD_DIR
490
491    [ $(uname -m) = "aarch64" ] && TARGETARCH="arm64"
492    [ $(uname -m) = "x86_64" ] && TARGETARCH="amd64"
493
494    $DOCKER_RUNTIME build \
495	   --target $container_type \
496	   -t $CTR_IMAGE \
497	   -f $BUILD_DIR/Dockerfile \
498	   --build-arg TARGETARCH=$TARGETARCH \
499	   $BUILD_DIR
500}
501
502cmd_shell() {
503    while [ $# -gt 0 ]; do
504	case "$1" in
505            "-h"|"--help")  { cmd_help; exit 1; } ;;
506            "--volumes")
507                shift
508                arg_vols="$1"
509                ;;
510            "--")           { shift; break; } ;;
511            *)
512		;;
513	esac
514	shift
515    done
516    ensure_build_dir
517    if [ $(uname -m) = "x86_64" ]; then
518	ensure_latest_ctr
519    fi
520    process_volumes_args
521    say_warn "Starting a privileged shell prompt as root ..."
522    say_warn "WARNING: Your $CLH_ROOT_DIR folder will be bind-mounted in the container under $CTR_CLH_ROOT_DIR"
523    $DOCKER_RUNTIME run \
524	   -ti \
525	   --workdir "$CTR_CLH_ROOT_DIR" \
526	   --rm \
527	   --privileged \
528	   --security-opt seccomp=unconfined \
529	   --ipc=host \
530	   --net="$CTR_CLH_NET" \
531	   --tmpfs /tmp:exec \
532	   --volume /dev:/dev \
533	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" $exported_volumes \
534	   --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
535	   --env USER="root" \
536	   --entrypoint bash \
537	   "$CTR_IMAGE"
538
539    fix_dir_perms $?
540}
541
542# Parse main command line args.
543#
544while [ $# -gt 0 ]; do
545    case "$1" in
546        -h|--help)              { cmd_help; exit 1; } ;;
547        -y|--unattended)        { OPT_UNATTENDED=true; } ;;
548        -*)
549            die "Unknown arg: $1. Please use \`$0 help\` for help."
550            ;;
551        *)
552            break
553            ;;
554    esac
555    shift
556done
557
558# $1 is now a command name. Check if it is a valid command and, if so,
559# run it.
560#
561declare -f "cmd_$1" > /dev/null
562ok_or_die "Unknown command: $1. Please use \`$0 help\` for help."
563
564cmd=cmd_$1
565shift
566
567
568$cmd "$@"
569