xref: /cloud-hypervisor/scripts/dev_cli.sh (revision cf1b5156f45f4aeab6d3aa818c7632d63ea84b3e)
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="v4"
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="host"
32[ $(uname -m) = "aarch64" ] && CTR_CLH_NET="bridge"
33
34# Cargo paths
35# Full path to the cargo registry dir on the host. This appears on the host
36# because we want to persist the cargo registry across container invocations.
37# Otherwise, any rust crates from crates.io would be downloaded again each time
38# we build or test.
39CARGO_REGISTRY_DIR="${CLH_BUILD_DIR}/cargo_registry"
40
41# Full path to the cargo git registry on the host. This serves the same purpose
42# as CARGO_REGISTRY_DIR, for crates downloaded from GitHub repos instead of
43# crates.io.
44CARGO_GIT_REGISTRY_DIR="${CLH_BUILD_DIR}/cargo_git_registry"
45
46# Full path to the cargo target dir on the host.
47CARGO_TARGET_DIR="${CLH_BUILD_DIR}/cargo_target"
48
49# Send a decorated message to stdout, followed by a new line
50#
51say() {
52    [ -t 1 ] && [ -n "$TERM" ] \
53        && echo "$(tput setaf 2)[$CLI_NAME]$(tput sgr0) $*" \
54        || echo "[$CLI_NAME] $*"
55}
56
57# Send a decorated message to stdout, without a trailing new line
58#
59say_noln() {
60    [ -t 1 ] && [ -n "$TERM" ] \
61        && echo -n "$(tput setaf 2)[$CLI_NAME]$(tput sgr0) $*" \
62        || echo "[$CLI_NAME] $*"
63}
64
65# Send a text message to stderr
66#
67say_err() {
68    [ -t 2 ] && [ -n "$TERM" ] \
69        && echo "$(tput setaf 1)[$CLI_NAME] $*$(tput sgr0)" 1>&2 \
70        || echo "[$CLI_NAME] $*" 1>&2
71}
72
73# Send a warning-highlighted text to stdout
74say_warn() {
75    [ -t 1 ] && [ -n "$TERM" ] \
76        && echo "$(tput setaf 3)[$CLI_NAME] $*$(tput sgr0)" \
77        || echo "[$CLI_NAME] $*"
78}
79
80# Exit with an error message and (optional) code
81# Usage: die [-c <error code>] <error message>
82#
83die() {
84    code=1
85    [[ "$1" = "-c" ]] && {
86        code="$2"
87        shift 2
88    }
89    say_err "$@"
90    exit $code
91}
92
93# Exit with an error message if the last exit code is not 0
94#
95ok_or_die() {
96    code=$?
97    [[ $code -eq 0 ]] || die -c $code "$@"
98}
99
100# Make sure the build/ dirs are available. Exit if we can't create them.
101# Upon returning from this call, the caller can be certain the build/ dirs exist.
102#
103ensure_build_dir() {
104    for dir in "$CLH_BUILD_DIR" \
105		   "$CLH_INTEGRATION_WORKLOADS" \
106		   "$CLH_CTR_BUILD_DIR" \
107		   "$CARGO_TARGET_DIR" \
108		   "$CARGO_REGISTRY_DIR" \
109		   "$CARGO_GIT_REGISTRY_DIR"; do
110        mkdir -p "$dir" || die "Error: cannot create dir $dir"
111        [ -x "$dir" ] && [ -w "$dir" ] || \
112            {
113                say "Wrong permissions for $dir. Attempting to fix them ..."
114                chmod +x+w "$dir"
115            } || \
116            die "Error: wrong permissions for $dir. Should be +x+w"
117    done
118}
119
120# Make sure we're using the latest dev container, by just pulling it.
121ensure_latest_ctr() {
122    $DOCKER_RUNTIME pull "$CTR_IMAGE"
123
124    ok_or_die "Error pulling container image. Aborting."
125}
126
127# Fix main directory permissions after a container ran as root.
128# Since the container ran as root, any files it creates will be owned by root.
129# This fixes that by recursively changing the ownership of /cloud-hypervisor to the
130# current user.
131#
132fix_dir_perms() {
133    # Yes, running Docker to get elevated privileges, just to chown some files
134    # is a dirty hack.
135    $DOCKER_RUNTIME run \
136	--workdir "$CTR_CLH_ROOT_DIR" \
137	   --rm \
138	   --volume /dev:/dev \
139	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
140	   "$CTR_IMAGE" \
141           chown -R "$(id -u):$(id -g)" "$CTR_CLH_ROOT_DIR"
142
143    return $1
144}
145
146cmd_help() {
147    echo ""
148    echo "Cloud Hypervisor $(basename $0)"
149    echo "Usage: $(basename $0) <command> [<command args>]"
150    echo ""
151    echo "Available commands:"
152    echo ""
153    echo "    build [--debug|--release] [--libc musl|gnu] [-- [<cargo args>]]"
154    echo "        Build the Cloud Hypervisor binaries."
155    echo "        --debug               Build the debug binaries. This is the default."
156    echo "        --release             Build the release binaries."
157    echo "        --libc                Select the C library Cloud Hypervisor will be built against. Default is gnu"
158    echo ""
159    echo "    tests [--unit|--cargo|--all] [--libc musl|gnu] [-- [<cargo test args>]]"
160    echo "        Run the Cloud Hypervisor tests."
161    echo "        --unit               Run the unit tests."
162    echo "        --cargo              Run the cargo tests."
163    echo "        --integration        Run the integration tests."
164    echo "        --libc               Select the C library Cloud Hypervisor will be built against. Default is gnu"
165    echo "        --all                Run all tests."
166    echo ""
167    echo "    build-container [--type]"
168    echo "        Build the Cloud Hypervisor container."
169    echo "        --dev                Build dev container. This is the default."
170    echo ""
171    echo "    clean [<cargo args>]]"
172    echo "        Remove the Cloud Hypervisor artifacts."
173    echo ""
174    echo "    shell"
175    echo "        Run the development container into an interactive, privileged BASH shell."
176    echo ""
177    echo "    help"
178    echo "        Display this help message."
179    echo ""
180}
181
182cmd_build() {
183    build="debug"
184    libc="gnu"
185
186    while [ $# -gt 0 ]; do
187	case "$1" in
188            "-h"|"--help")  { cmd_help; exit 1;     } ;;
189            "--debug")      { build="debug";      } ;;
190            "--release")    { build="release";    } ;;
191            "--libc")
192                shift
193                [[ "$1" =~ ^(musl|gnu)$ ]] || \
194                    die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
195                libc="$1"
196                ;;
197            "--")           { shift; break;         } ;;
198            *)
199		die "Unknown build argument: $1. Please use --help for help."
200		;;
201	esac
202	shift
203    done
204
205    target="$(uname -m)-unknown-linux-${libc}"
206
207    cargo_args=("$@")
208    [ $build = "release" ] && cargo_args+=("--release")
209    cargo_args+=(--target "$target")
210    [ $(uname -m) = "aarch64" ] && cargo_args+=("--no-default-features")
211    [ $(uname -m) = "aarch64" ] && cargo_args+=(--features "mmio,kvm")
212
213    rustflags=""
214    if [ $(uname -m) = "aarch64" ] && [ $libc = "musl" ] ; then
215        rustflags="-C link-arg=-lgcc -C link_arg=-specs -C link_arg=/usr/lib/aarch64-linux-musl/musl-gcc.specs"
216    fi
217
218    # A workaround on Arm64 to avoid build errors in kvm-bindings
219    if [ $(uname -m) = "aarch64" ]; then
220        sed -i 's/"with-serde",\ //g' "$CLH_ROOT_DIR"/hypervisor/Cargo.toml
221    fi
222
223    $DOCKER_RUNTIME run \
224	   --user "$(id -u):$(id -g)" \
225	   --workdir "$CTR_CLH_ROOT_DIR" \
226	   --rm \
227	   --volume /dev:/dev \
228	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
229	   --env RUSTFLAGS="$rustflags" \
230	   "$CTR_IMAGE" \
231	   cargo build --all \
232	         --target-dir "$CTR_CLH_CARGO_TARGET" \
233	         "${cargo_args[@]}" && say "Binaries placed under $CLH_CARGO_TARGET/$target/$build"
234}
235
236cmd_clean() {
237    cargo_args=("$@")
238
239    $DOCKER_RUNTIME run \
240	   --user "$(id -u):$(id -g)" \
241	   --workdir "$CTR_CLH_ROOT_DIR" \
242	   --rm \
243	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
244	   "$CTR_IMAGE" \
245	   cargo clean \
246	         --target-dir "$CTR_CLH_CARGO_TARGET" \
247	         "${cargo_args[@]}"
248    }
249
250cmd_tests() {
251    unit=false
252    cargo=false
253    integration=false
254    libc="gnu"
255
256    while [ $# -gt 0 ]; do
257	case "$1" in
258            "-h"|"--help")           { cmd_help; exit 1;     } ;;
259            "--unit")                { unit=true;      } ;;
260            "--cargo")               { cargo=true;    } ;;
261            "--integration")         { integration=true;    } ;;
262            "--libc")
263                shift
264                [[ "$1" =~ ^(musl|gnu)$ ]] || \
265                    die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
266                libc="$1"
267                ;;
268	    "--all")                 { cargo=true; unit=true; integration=true;  } ;;
269            "--")                    { shift; break;         } ;;
270            *)
271		die "Unknown tests argument: $1. Please use --help for help."
272		;;
273	esac
274	shift
275    done
276
277    target="$(uname -m)-unknown-linux-${libc}"
278    cflags=""
279    target_cc=""
280    if [[ "$target" == "x86_64-unknown-linux-musl" ]]; then
281	target_cc="musl-gcc"
282	cflags="-I /usr/include/x86_64-linux-musl/ -idirafter /usr/include/"
283    fi
284
285    if [ "$unit" = true ] ;  then
286	say "Running unit tests for $target..."
287	$DOCKER_RUNTIME run \
288	       --workdir "$CTR_CLH_ROOT_DIR" \
289	       --rm \
290	       --device /dev/kvm \
291	       --device /dev/net/tun \
292	       --cap-add net_admin \
293	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
294	       --env BUILD_TARGET="$target" \
295	       --env CFLAGS="$cflags" \
296	       --env TARGET_CC="$target_cc" \
297	       "$CTR_IMAGE" \
298	       ./scripts/run_unit_tests.sh "$@" || fix_dir_perms $? || exit $?
299    fi
300
301    if [ "$cargo" = true ] ;  then
302	say "Running cargo tests..."
303	$DOCKER_RUNTIME run \
304	       --workdir "$CTR_CLH_ROOT_DIR" \
305	       --rm \
306	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
307	       "$CTR_IMAGE" \
308	       ./scripts/run_cargo_tests.sh || fix_dir_perms $? || exit $?
309    fi
310
311    if [ "$integration" = true ] ;  then
312	say "Running integration tests for $target..."
313	$DOCKER_RUNTIME run \
314	       --workdir "$CTR_CLH_ROOT_DIR" \
315	       --rm \
316	       --privileged \
317	       --security-opt seccomp=unconfined \
318	       --ipc=host \
319	       --net="$CTR_CLH_NET" \
320	       --mount type=tmpfs,destination=/tmp \
321	       --volume /dev:/dev \
322	       --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
323	       --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
324	       --env USER="root" \
325	       --env CH_LIBC="${libc}" \
326	       "$CTR_IMAGE" \
327	       ./scripts/run_integration_tests_$(uname -m).sh "$@" || fix_dir_perms $? || exit $?
328    fi
329
330    fix_dir_perms $?
331}
332
333cmd_build-container() {
334    container_type="dev"
335
336    while [ $# -gt 0 ]; do
337	case "$1" in
338            "-h"|"--help")  { cmd_help; exit 1;     } ;;
339            "--dev")        { container_type="dev"; } ;;
340            "--")           { shift; break;         } ;;
341            *)
342		die "Unknown build-container argument: $1. Please use --help for help."
343		;;
344	esac
345	shift
346    done
347
348    BUILD_DIR=/tmp/cloud-hypervisor/container/
349
350    mkdir -p $BUILD_DIR
351    cp $CLH_DOCKERFILE $BUILD_DIR
352
353    $DOCKER_RUNTIME build \
354	   --target $container_type \
355	   -t $CTR_IMAGE \
356	   -f $BUILD_DIR/Dockerfile \
357	   --build-arg TARGETARCH="$(uname -m)" \
358	   $BUILD_DIR
359}
360
361cmd_shell() {
362    say_warn "Starting a privileged shell prompt as root ..."
363    say_warn "WARNING: Your $CLH_ROOT_DIR folder will be bind-mounted in the container under $CTR_CLH_ROOT_DIR"
364    $DOCKER_RUNTIME run \
365	   -ti \
366	   --workdir "$CTR_CLH_ROOT_DIR" \
367	   --rm \
368	   --privileged \
369	   --security-opt seccomp=unconfined \
370	   --ipc=host \
371	   --net="$CTR_CLH_NET" \
372	   --tmpfs /tmp:exec \
373	   --volume /dev:/dev \
374	   --volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
375	   --volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
376	   --env USER="root" \
377	   --env CH_LIBC="${libc}" \
378	   --entrypoint bash \
379	   "$CTR_IMAGE"
380
381    fix_dir_perms $?
382}
383
384# Parse main command line args.
385#
386while [ $# -gt 0 ]; do
387    case "$1" in
388        -h|--help)              { cmd_help; exit 1;     } ;;
389        -y|--unattended)        { OPT_UNATTENDED=true;  } ;;
390        -*)
391            die "Unknown arg: $1. Please use \`$0 help\` for help."
392            ;;
393        *)
394            break
395            ;;
396    esac
397    shift
398done
399
400# $1 is now a command name. Check if it is a valid command and, if so,
401# run it.
402#
403declare -f "cmd_$1" > /dev/null
404ok_or_die "Unknown command: $1. Please use \`$0 help\` for help."
405
406cmd=cmd_$1
407shift
408
409ensure_build_dir
410if [ $(uname -m) = "x86_64" ]; then
411    ensure_latest_ctr
412fi
413
414# Before a public image for AArch64 ready, we build the container if needed.
415if [ $(uname -m) = "aarch64" ]; then
416    cmd_build-container
417fi
418
419$cmd "$@"
420