cyber_start.sh 17.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#!/usr/bin/env bash

###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
18
APOLLO_ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
19 20 21 22
source "${APOLLO_ROOT_DIR}/scripts/apollo.bashrc"

# CACHE_ROOT_DIR="${APOLLO_ROOT_DIR}/.cache"

23
VERSION_X86_64="cyber-x86_64-18.04-20200629_0512"
24
VERSION_AARCH64="cyber-aarch64-18.04-20200629_0524"
25 26
VERSION_LOCAL_CYBER="local_cyber_dev"
CYBER_CONTAINER="apollo_cyber_${USER}"
27
CYBER_INSIDE="in-cyber-docker"
28

29
DOCKER_REPO="apolloauto/apollo"
30 31 32 33 34 35
DOCKER_RUN_CMD="docker run"
DOCKER_PULL_CMD="docker pull"

SUPPORTED_ARCHS=" x86_64 aarch64 "
HOST_ARCH="$(uname -m)"
TARGET_ARCH=""
36 37

USE_GPU=0
38 39 40
USE_LOCAL_IMAGE=0
CUSTOM_VERSION=
GEOLOC=
41

42 43
# Check whether user has agreed license agreement
function check_agreement() {
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    local agreement_record="${HOME}/.apollo_agreement.txt"
    if [[ -e "${agreement_record}" ]]; then
        return 0
    fi
    local agreement_file
    agreement_file="$APOLLO_ROOT_DIR/scripts/AGREEMENT.txt"
    if [[ ! -f "${agreement_file}" ]]; then
        error "AGREEMENT ${agreement_file} does not exist."
        exit 1
    fi

    cat "${agreement_file}"
    local tip="Type 'y' or 'Y' to agree to the license agreement above, \
or type any other key to exit:"
    echo -n "${tip}"
    read -r -n 1 user_agreed
    echo
    if [[ "${user_agreed}" == "y" || "${user_agreed}" == "Y" ]]; then
        cp -f "${agreement_file}" "${agreement_record}"
        echo
        echo "${tip}" >> "${agreement_record}"
        echo "${user_agreed}" >> "${agreement_record}"
    else
        exit 1
    fi
69 70 71
}

function check_host_environment() {
72
    echo "Done checking host environment."
73 74
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
function _optarg_check_for_opt() {
    local opt="$1"
    local optarg="$2"

    if [[ -z "${optarg}" || "${optarg}" =~ ^-.* ]]; then
        error "Missing parameter for ${opt}. Exiting..."
        exit 2
    fi
}

function _target_arch_check() {
    local arch="$1"
    if [[ "${SUPPORTED_ARCHS}" != *" ${arch} "* ]]; then
        error "Unsupported target architecture: ${arch}. Allowed values:${SUPPORTED_ARCHS}"
        exit 1
    fi
}

93
function show_usage() {
94 95
cat <<EOF
Usage: $0 [options] ...
96
OPTIONS:
97
    -g <us|cn>             Pull docker image from mirror registry based on geolocation.
98 99 100
    -h, --help             Display this help and exit.
    -t, --tag <version>    Specify which version of a docker image to pull.
    -l, --local            Use local docker image.
101
    -m <arch>              Specify docker image for a different CPU arch.
S
storypku 已提交
102
    stop [-f|--force]      Stop all running Apollo containers. Use "-f" to force removal.
103 104 105
EOF
}

106
function stop_all_apollo_containers_for_user() {
S
storypku 已提交
107
    local force="$1"
108
    local running_containers
S
storypku 已提交
109
    running_containers="$(docker ps -a --format '{{.Names}}')"
110 111 112 113 114 115
    for container in ${running_containers[*]} ; do
        if [[ "${container}" =~ apollo_.*_${USER} ]] ; then
            #printf %-*s 70 "Now stop container: ${container} ..."
            #printf "\033[32m[DONE]\033[0m\n"
            #printf "\033[31m[FAILED]\033[0m\n"
            info "Now stop container ${container} ..."
S
storypku 已提交
116 117 118 119
            if docker stop "${container}" >/dev/null; then
                if [[ "${force}" == "-f" || "${force}" == "--force" ]]; then
                    docker rm -f "${container}" >/dev/null
                fi
120
                info "Done."
121
            else
122
                warning "Failed."
123 124 125
            fi
        fi
    done
S
storypku 已提交
126 127 128 129 130
    if [[ "${force}" == "-f" || "${force}" == "--force" ]]; then
        info "OK. Done stop and removal"
    else
        info "OK. Done stop."
    fi
131 132
}

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
function parse_arguments() {
    local use_local_image=0
    local custom_version=""
    local target_arch=""
    local geo=""

    while [[ $# -gt 0 ]] ; do
        local opt="$1"; shift
        case "${opt}" in
        -g|--geo)
            geo="$1"; shift
            _optarg_check_for_opt "${opt}" "${geo}"
            ;;
        -t|--tag)
            if [[ ! -z "${custom_version}" ]]; then
                warning "Multiple option ${opt} specified, only the last one will take effect."
            fi
            custom_version="$1"; shift
            _optarg_check_for_opt "${opt}" "${custom_version}"
            ;;
        -h|--help)
            show_usage
            exit 1
            ;;
        -l|--local)
            use_local_image=1
            ;;
        -m)
            target_arch="$1"; shift
            _optarg_check_for_opt "${opt}" "${target_arch}"
            _target_arch_check "${target_arch}"
            ;;
        stop)
S
storypku 已提交
166
            local force="$1"; shift
167
            info "Now, stop all apollo containers created by ${USER} ..."
S
storypku 已提交
168
            stop_all_apollo_containers_for_user "${force}"
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
            exit 0
            ;;
        *)
            warning "Unknown option: $1"
            exit 2
            ;;
        esac
    done # End while loop

    [[ ! -z "${geo}" ]] && GEOLOC="${geo}"
    USE_LOCAL_IMAGE="${use_local_image}"
    [[ ! -z "${target_arch}" ]] && TARGET_ARCH="${target_arch}"
    [[ ! -z "${custom_version}" ]] && CUSTOM_VERSION="${custom_version}"
}

184 185 186 187 188 189 190
# TODO(storypku): What does these do with apollo inside container
# if [ ! -e /apollo ]; then
#    sudo ln -sf "${APOLLO_ROOT_DIR}" /apollo
# fi
# if [ -e /proc/sys/kernel ]; then
#    echo "/apollo/data/core/core_%e.%p" | sudo tee /proc/sys/kernel/core_pattern > /dev/null
# fi
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
# <cyber|dev>-<arch>-<ubuntu-release>-<timestamp>
function guess_arch_from_tag() {
    local tag="$1"
    local __result="$2"

    local arch
    IFS='-' read -ra __arr <<< "${tag}"
    IFS=' ' # restore
    if [[ ${#__arr[@]} -lt 3 ]]; then
        warning "Unexpected image: ${tag}"
        arch=""
    else
        arch="${__arr[1]}"
    fi
    eval "${__result}='${arch}'"
}
207

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
function determine_target_version_and_arch() {
    local version="$1"
    # If no custom version specified
    if [[ -z "${version}" ]]; then
        if [[ ${USE_LOCAL_IMAGE} -eq 1 ]]; then
            version="${VERSION_LOCAL_CYBER}"
            if [[ -z "${TARGET_ARCH}" ]]; then
                TARGET_ARCH="${HOST_ARCH}"
            fi
            _target_arch_check "${TARGET_ARCH}"
        else # Neither CUSTOM_VERSION nor USE_LOCAL_IMAGE set
            # if target arch not set, assume it is equal to host arch.
            if [[ -z "${TARGET_ARCH}" ]]; then
                TARGET_ARCH="${HOST_ARCH}"
            fi
            _target_arch_check "${TARGET_ARCH}"
            if [[ "${TARGET_ARCH}" == "x86_64" ]]; then
                version="${VERSION_X86_64}"
            elif [[ "${TARGET_ARCH}" == "aarch64" ]]; then
                version="${VERSION_AARCH64}"
            else
                error "CAN'T REACH HERE"
                exit 1
            fi
        fi
    elif [[ "${version}" =~ local* ]]; then
        if [[ -z "${TARGET_ARCH}" ]]; then
            TARGET_ARCH="${HOST_ARCH}"
        fi
        _target_arch_check "${TARGET_ARCH}"
        info "Local image ${version} specified, indicating USE_LOCAL_IMAGE=1"
        USE_LOCAL_IMAGE=1
    else # CUSTOM_VERSION specified
        local supposed_arch
        guess_arch_from_tag "${version}" supposed_arch
        if [[ -z "${supposed_arch}" ]]; then
            error "Can't guess target arch from image tag: ${version}"
            error "  Expected format <target>-<arch>-<ubuntu_release>-<timestamp>"
            exit 1
        fi
        if [[ -z "${TARGET_ARCH}" ]]; then
            _target_arch_check "${supposed_arch}"
            TARGET_ARCH="${supposed_arch}"
        elif [[ "${TARGET_ARCH}" != "${supposed_arch}" ]]; then
            error "Target arch (${TARGET_ARCH}) doesn't match supposed arch"\
                  "(${supposed_arch}) from ${version}"
            exit 1
        fi
    fi
    CUSTOM_VERSION="${version}"
258 259
}

260 261 262 263 264 265 266 267 268 269 270
# Operate on DOCKER_REPO
function geo_specific_config() {
    local geo="$1"
    if [[ -z "${geo}" ]]; then
        return
    fi
    info "Setup geolocation specific configurations for ${geo}"
    if [[ "${geo}" == "cn" ]]; then
        info "TODO: CN mirrors"
    fi
}
271

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
function determine_gpu_use_aarch64() {
    local use_gpu=0
    if  lsmod | grep -q nvgpu ; then
        use_gpu=1
    fi
    if [[ "${use_gpu}" -eq 1 ]]; then
        local docker_version
        docker_version="$(docker version --format '{{.Server.Version}}')"
        if dpkg --compare-versions "${docker_version}" "ge" "19.03"; then
            DOCKER_RUN_CMD="docker run --gpus all"
        else
            warning "You must upgrade to docker-ce 19.03+ to access GPU from container!"
            use_gpu=0
        fi
    fi
    USE_GPU="${use_gpu}"
}

function determine_gpu_use_amd64() {
291 292 293 294 295 296
    # Check nvidia-driver and GPU device
    local nv_driver="nvidia-smi"
    if [ ! -x "$(command -v ${nv_driver} )" ]; then
        warning "No nvidia-driver found. CPU will be used"
    elif [ -z "$(eval ${nv_driver} )" ]; then
        warning "No GPU device found. CPU will be used."
297
    else
298 299 300 301 302 303 304
        USE_GPU=1
    fi

    # Try to use GPU inside container
    local nv_docker_doc="https://github.com/NVIDIA/nvidia-docker/blob/master/README.md"
    if [ ${USE_GPU} -eq 1 ]; then
        if [ ! -z "$(which nvidia-docker)" ]; then
305 306
            DOCKER_RUN_CMD="nvidia-docker run"
            warning "nvidia-docker is deprecated. Please install latest docker" \
307 308 309 310 311
                    "and nvidia-container-toolkit as described by:"
            warning "  ${nv_docker_doc}"
        elif [ ! -z "$(which nvidia-container-toolkit)" ]; then
            local docker_version
            docker_version="$(docker version --format '{{.Server.Version}}')"
312 313
            if dpkg --compare-versions "${docker_version}" "ge" "19.03"; then
                DOCKER_RUN_CMD="docker run --gpus all"
314 315 316 317 318 319
            else
                warning "You must upgrade to docker-ce 19.03+ to access GPU from container!"
                USE_GPU=0
            fi
        else
            USE_GPU=0
320
            warning "Cannot access GPU from within container. Please install latest docker" \
321 322 323
                    "and nvidia-container-toolkit as described by: "
            warning "  ${nv_docker_doc}"
        fi
324 325 326
    fi
}

327 328 329 330 331 332 333 334
function determine_gpu_use() {
    if [[ "${HOST_ARCH}" == "x86_64" ]]; then
        determine_gpu_use_amd64
    else
        determine_gpu_use_aarch64
    fi

}
335 336 337 338 339 340
function setup_devices_and_mount_volumes() {
    local __retval="$1"

    if [[ "${HOST_ARCH}" == "${TARGET_ARCH}" ]]; then
        source "${APOLLO_ROOT_DIR}/scripts/apollo_base.sh" CYBER_ONLY
        setup_device
341 342
    fi

343 344 345 346 347 348 349
    local volumes
    volumes="-v ${APOLLO_ROOT_DIR}:/apollo"

    local kernel="$(uname -s)"
    if [[ "${kernel}" != "Linux" ]]; then
        warning "Running Apollo cyber container on ${kernel} is UNTESTED, exiting..."
        exit 1
350 351
    fi

352 353 354 355 356 357 358 359 360
    local os_release="$(lsb_release -rs)"
    case "${os_release}" in
        14.04)
            warning "[Deprecated] Support for Ubuntu 14.04 will be removed" \
                    "in the near future. Please upgrade to ubuntu 18.04+."
            ;;
        16.04|18.04|20.04|*)
            ## Question(storypku): Any special considerations here ?
            if [[ "${HOST_ARCH}" == "${TARGET_ARCH}" ]]; then
S
storypku 已提交
361
                volumes="${volumes} -v /dev:/dev"
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
            fi
            ;;
    esac

    volumes="${volumes} -v /etc/localtime:/etc/localtime:ro"
    # volumes="${volumes} -v /usr/src:/usr/src"
    if [[ "${HOST_ARCH}" == "${TARGET_ARCH}" ]]; then
        volumes="${volumes} -v /dev/null:/dev/raw1394 \
                            -v /media:/media \
                            -v /tmp/.X11-unix:/tmp/.X11-unix:rw \
                            -v /lib/modules:/lib/modules \
                    "

    fi
    volumes="$(tr -s " " <<< "${volumes}")"
    eval "${__retval}='${volumes}'"
}

function determine_display() {
    local display
    # read from env
    if [[ -z "${DISPLAY}" ]]; then
384 385 386 387
        display=":0"
    else
        display="${DISPLAY}"
    fi
388 389 390 391 392
    echo "${display}"
}

function remove_existing_cyber_container() {
    if docker ps -a --format '{{.Names}}' | grep -q "${CYBER_CONTAINER}"; then
S
storypku 已提交
393 394 395
        info "Removing existing cyber container ${CYBER_CONTAINER}"
        docker stop "${CYBER_CONTAINER}" >/dev/null
        docker rm -v -f "${CYBER_CONTAINER}" >/dev/null
396 397
    fi
}
398

399 400 401 402 403 404 405 406 407 408 409 410 411
function docker_pull_if_needed() {
    local image="$1"
    local use_local_image="$2"
    if [[ ${use_local_image} -eq 1 ]]; then
        info "Start cyber container based on local image: ${image}"
    elif docker images -a --format '{{.Repository}}:{{.Tag}}' \
        | grep -q "${image}"; then
        info "Image ${image} found locally, will be used."
        use_local_image=1
    fi
    if [[ ${use_local_image} -eq 1 ]]; then
        return
    fi
412

413 414 415 416 417 418 419 420
    # Note(storypku): use may-be-modified ${DOCKER_REPO}
    image="${DOCKER_REPO}:${image##*:}"
    echo "Start pulling docker image: ${image}"
    if ! ${DOCKER_PULL_CMD} "${image}"; then
        error "Failed to pull docker image: ${image}"
        exit 1
    fi
}
421

422 423 424 425 426 427
function check_multi_arch_support() {
    if [[ "${TARGET_ARCH}" == "${HOST_ARCH}" ]]; then
        return
    fi
    info "Cyber ${TARGET_ARCH} container running on ${HOST_ARCH} host."

428 429 430 431
    # Note(storypku):
    # ubuntu 18.04: apt-get -y install qemu-user-static
    # with sudo-no-suid problem

432 433
    local qemu="multiarch/qemu-user-static"
    local refer="https://github.com/multiarch/qemu-user-static"
S
storypku 已提交
434
    local qemu_cmd="docker run --rm --privileged ${qemu} --reset -p yes"
435
    if docker images --format "{{.Repository}}" |grep -q "${qemu}" ; then
S
storypku 已提交
436 437 438
        info "Run: ${qemu_cmd}"
        ## docker run --rm --privileged "${qemu}" --reset -p yes >/dev/null
        eval "${qemu_cmd}" >/dev/null
439 440 441
        info "Multiarch support has been enabled. Ref: ${refer}"
    else
        warning "Multiarch support hasn't been enabled. Please make sure the"
S
storypku 已提交
442 443
        warning "following command has been executed before continuing:"
        warning "  ${qemu_cmd}"
444 445 446 447 448 449 450
        warning "Refer to ${refer} for more."
        exit 1
    fi
}

function start_cyber_container() {
    local image="$1"
451 452 453
    # if [ ! -d "${CACHE_ROOT_DIR}" ]; then
    #    mkdir "${CACHE_ROOT_DIR}"
    # fi
454
    info "Starting docker container \"${CYBER_CONTAINER}\" ..."
455

456 457
    local user="${USER}"
    local uid="$(id -u)"
458

459 460 461 462 463 464
    local group=$(id -g -n)
    local gid=$(id -g)
    local local_host="$(hostname)"

    local local_volumes
    setup_devices_and_mount_volumes local_volumes
465

466
    local display="$(determine_display)"
L
Liu Jiaming 已提交
467

468
    set -x
S
storypku 已提交
469 470
    ${DOCKER_RUN_CMD} -it \
        -d \
471
        --privileged \
472 473 474 475 476 477 478 479 480
        --name "${CYBER_CONTAINER}" \
        -e DISPLAY="${display}" \
        -e DOCKER_USER="${user}" \
        -e USER="${user}" \
        -e DOCKER_USER_ID="${uid}" \
        -e DOCKER_GRP="${group}" \
        -e DOCKER_GRP_ID="${gid}" \
        -e DOCKER_IMG="${image}" \
        -e USE_GPU="${USE_GPU}" \
L
Liu Jiaming 已提交
481 482
        -e NVIDIA_VISIBLE_DEVICES=all \
        -e NVIDIA_DRIVER_CAPABILITIES=compute,video,graphics,utility \
483
        -e OMP_NUM_THREADS=1 \
484
        ${local_volumes} \
485 486
        --net host \
        -w /apollo \
487 488 489
        --add-host "${CYBER_INSIDE}:172.0.0.1" \
        --add-host "${local_host}:127.0.0.1" \
        --hostname "${CYBER_INSIDE}" \
490 491
        --shm-size 2G \
        --pid=host \
492
        "${image}" \
493 494 495
        /bin/bash

    if [ $? -ne 0 ];then
496
        error "Failed to start docker container \"${CYBER_CONTAINER}\" based on image: ${image}"
497 498
        exit 1
    fi
499 500
    set +x
}
501

502
function after_run_setup() {
503 504 505 506
    if [[ "${USER}" != "root" ]]; then
        docker exec -u root "${CYBER_CONTAINER}" \
            bash -c '/apollo/scripts/docker_start_user.sh'
    fi
507 508 509 510 511
    # if [[ "${TARGET_ARCH}" == "aarch64" ]]; then
    #    warning "!!! Due to problem with 'docker exec' on Drive PX2 platform," \
    #            "please run '/apollo/scripts/docker_start_user.sh' the first" \
    #            "time you login into cyber docker !!!"
    # fi
512
}
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
function main() {
    check_agreement
    check_host_environment

    parse_arguments "$@"
    determine_target_version_and_arch "${CUSTOM_VERSION}"

    check_multi_arch_support

    local image="${DOCKER_REPO}:${CUSTOM_VERSION}"

    geo_specific_config "${GEOLOC}"
    docker_pull_if_needed "${image}" "${USE_LOCAL_IMAGE}"

    image="${DOCKER_REPO}:${CUSTOM_VERSION}"

    remove_existing_cyber_container

    determine_gpu_use
    info "DOCKER_RUN_CMD evaluated to: ${DOCKER_RUN_CMD}"

    start_cyber_container "${image}"

    after_run_setup

    ok "Congrats, you have successfully finished setting up Apollo cyber docker environment." \
       "To login into cyber container, please run the following command:"
    ok "  bash docker/scripts/cyber_into.sh"
542 543 544
    ok "Enjoy!"
}

545
main "$@"
546