#!/bin/bash set -ef -o pipefail # shellcheck source=jenkins-helpers.sh . "$(dirname $0)"/jenkins-helpers.sh convert_args_to_variables "$@" shift "$SHIFT_CONVERTED_ARGS" obligatory_variables container image declare container image keep_existing="${keep_existing-true}" verbose="${verbose-true}" set -u if $verbose; then set -x; fi docker pull "$image" rm_cnt="" if docker stats --no-stream "$container" >/dev/null 2>&1; then running=$(docker container inspect -f "{{.State.Running}}" "$container") case "$running:$keep_existing" in true:true) exit 0 ;; true:keep_if_same_image) old_image=$(docker container inspect -f "{{.Image}}" "$container") new_image=$(docker image inspect -f "{{.Id}}" "$image") if [ x"$old_image" = x"$new_image" ]; then exit 0 fi ;; esac # Rename the current container to free-up the name for "docker run" below. # Use rename name starting with a number (seconds since epoch) so that # it'll be cleaned up even if something goes wrong here. rm_cnt="$(date +%Y-%m-%d)-$container.bak" docker rename "$container" "$rm_cnt" & res=0 && wait $! || res=$? if [ x"$res" != x"0" ]; then # Failure to rename a container is usually caused by container # restarting loop. This restarting container can't be the current # one, so just delete it. docker rm -vf "$container" rm_cnt="" fi fi qemu_mount="" qemu_bin=$(mktemp -p $HOME) case "$(uname -m):$image" in x86_64:*-arm64-tcwg-llvmbot-*) # See dockerfiles.git/tcwg-base/tcwg-llvmbot/start.sh for details # on how this works. cp "$(which qemu-aarch64-static)" "$qemu_bin" chmod +x "$qemu_bin" qemu_mount="-v $qemu_bin:/bin/qemu-aarch64-static" ;; esac start_sh=$(mktemp) docker run --rm $qemu_mount $image start.sh > "$start_sh" bash "$start_sh" "$@" rm "$start_sh" "$qemu_bin" if [ x"$rm_cnt" != x"" ]; then # With the new container started delete the old one. # Note that if both old and new containers need an exclusive resource # (e.g., tcp port or connection to jenkins), then the new container might # need to restart a couple of times to wait for removal of the old one. docker rm -vf "$rm_cnt" fi