cyber_start.sh 15.6 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 23 24 25 26 27
source "${APOLLO_ROOT_DIR}/scripts/apollo.bashrc"

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

VERSION_X86_64="cyber-x86_64-18.04-20200525_0253"
VERSION_AARCH64="cyber-aarch64-18.04-20190621_1606"
VERSION_LOCAL_CYBER="local_cyber_dev"
CYBER_CONTAINER="apollo_cyber_${USER}"
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 44 45
ARCH=$(uname -m)

# Check whether user has agreed license agreement
function check_agreement() {
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    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
71 72 73
}

function check_host_environment() {
74
    echo "Done checking host environment."
75 76
}

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
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
}

95
function show_usage() {
96 97
cat <<EOF
Usage: $0 [options] ...
98
OPTIONS:
99
    -g <us|cn>             Pull docker image from mirror registry based on geolocation.
100 101 102
    -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.
103
    -m <arch>              Specify docker image for a different CPU arch.
104 105 106 107
    stop                   Stop all running Apollo containers.
EOF
}

108
function stop_all_apollo_containers_for_user() {
109
    local running_containers
110 111 112 113 114 115 116 117 118
    running_containers="$(docker ps --format '{{.Names}}')"
    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} ..."
            if docker stop "${container}"; then
                info "Done."
119
            else
120
                warning "Failed."
121 122 123
            fi
        fi
    done
124 125
}

126 127 128 129 130 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 166 167 168 169 170 171 172 173 174 175
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)
            info "Now, stop all apollo containers created by ${USER} ..."
            stop_all_apollo_containers_for_user
            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}"
}

176 177 178 179 180 181 182
# 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
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
# <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}'"
}
199

200 201 202 203 204 205 206 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
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}"
250 251
}

252 253 254 255 256 257 258 259 260 261 262
# 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
}
263 264

function determine_gpu_use() {
265 266 267 268 269 270
    # 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."
271
    else
272 273 274 275 276 277 278
        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
279 280
            DOCKER_RUN_CMD="nvidia-docker run"
            warning "nvidia-docker is deprecated. Please install latest docker" \
281 282 283 284 285
                    "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}}')"
286 287
            if dpkg --compare-versions "${docker_version}" "ge" "19.03"; then
                DOCKER_RUN_CMD="docker run --gpus all"
288 289 290 291 292 293
            else
                warning "You must upgrade to docker-ce 19.03+ to access GPU from container!"
                USE_GPU=0
            fi
        else
            USE_GPU=0
294
            warning "Cannot access GPU from within container. Please install latest docker" \
295 296 297
                    "and nvidia-container-toolkit as described by: "
            warning "  ${nv_docker_doc}"
        fi
298 299 300
    fi
}

301 302 303 304 305 306
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
307 308
    fi

309 310 311 312 313 314 315
    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
316 317
    fi

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    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
                volumes="${volumes} -v /dev:/dev "
            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
350 351 352 353
        display=":0"
    else
        display="${DISPLAY}"
    fi
354 355 356 357 358 359 360 361 362
    echo "${display}"
}

function remove_existing_cyber_container() {
    if docker ps -a --format '{{.Names}}' | grep -q "${CYBER_CONTAINER}"; then
        docker stop "${CYBER_CONTAINER}"
        docker rm -v -f "${CYBER_CONTAINER}"
    fi
}
363

364 365 366 367 368 369 370 371 372 373 374 375 376
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
377

378 379 380 381 382 383 384 385
    # 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
}
386

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
function check_multi_arch_support() {
    if [[ "${TARGET_ARCH}" == "${HOST_ARCH}" ]]; then
        return
    fi
    info "Cyber ${TARGET_ARCH} container running on ${HOST_ARCH} host."

    local qemu="multiarch/qemu-user-static"
    local refer="https://github.com/multiarch/qemu-user-static"
    if docker images --format "{{.Repository}}" |grep -q "${qemu}" ; then
        info "Multiarch support has been enabled. Ref: ${refer}"
    else
        warning "Multiarch support hasn't been enabled. Please make sure the"
        warning "following command has been executed ONCE before continuing:"
        warning "  docker run --rm --privileged multiarch/qemu-user-static --reset -p yes"
        warning "Refer to ${refer} for more."
        exit 1
    fi
}

function start_cyber_container() {
    local image="$1"
408 409 410
    # if [ ! -d "${CACHE_ROOT_DIR}" ]; then
    #    mkdir "${CACHE_ROOT_DIR}"
    # fi
411
    info "Starting docker container \"${CYBER_CONTAINER}\" ..."
412

413 414
    local user="${USER}"
    local uid="$(id -u)"
415

416 417 418 419 420 421
    local group=$(id -g -n)
    local gid=$(id -g)
    local local_host="$(hostname)"

    local local_volumes
    setup_devices_and_mount_volumes local_volumes
422

423
    local display="$(determine_display)"
L
Liu Jiaming 已提交
424

425 426
    set -x
    ${DOCKER_RUN_CMD} -itd \
427
        --privileged \
428 429 430 431 432 433 434 435 436
        --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 已提交
437 438
        -e NVIDIA_VISIBLE_DEVICES=all \
        -e NVIDIA_DRIVER_CAPABILITIES=compute,video,graphics,utility \
439
        -e OMP_NUM_THREADS=1 \
440
        ${local_volumes} \
441 442
        --net host \
        -w /apollo \
443 444 445
        --add-host "${CYBER_INSIDE}:172.0.0.1" \
        --add-host "${local_host}:127.0.0.1" \
        --hostname "${CYBER_INSIDE}" \
446 447
        --shm-size 2G \
        --pid=host \
448
        "${image}" \
449 450 451
        /bin/bash

    if [ $? -ne 0 ];then
452
        error "Failed to start docker container \"${CYBER_CONTAINER}\" based on image: ${image}"
453 454
        exit 1
    fi
455 456
    set +x
}
457

458 459
function after_run_setup() {
    if [[ "${TARGET_ARCH}" == "x86_64" ]]; then
460
        if [[ "${USER}" != "root" ]]; then
461 462
            docker exec -u root "${CYBER_CONTAINER}" \
                bash -c '/apollo/scripts/docker_start_user.sh'
463 464
        fi
    else
465 466 467
        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 !!!"
468
    fi
469
}
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
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"
499 500 501
    ok "Enjoy!"
}

502
main "$@"
503