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