summaryrefslogtreecommitdiff
path: root/tcwg-start-container.sh
blob: e33a4bb76f975d27d783022ac2ee2612a8044c2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
69
70
71
72
73
74
#!/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