summaryrefslogtreecommitdiff
path: root/tcwg-start-container.sh
blob: cc9b040b6ae845cd45a2dc035ecf3f17f3f654e5 (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
75
76
77
#!/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

# See start-container-docker.sh for background on image stamp files.
# Note that there is no need to track pull requests, since these happen
# once a day anyway.
stamp_dir=/home/shared/docker
if ! [ -d "$stamp_dir" ]; then
    sudo mkdir -p "$stamp_dir" || mkdir -p "$stamp_dir"
    sudo chmod 0777 "$stamp_dir" || chmod 0777 "$stamp_dir"
fi
image_stamp="$stamp_dir/$(echo "$image" | tr "/:" "_")"

docker pull "$image"

rm -f "$image_stamp.pull"
touch "$image_stamp.pull"

rm_cnt=""
if docker stats --no-stream "$container" >/dev/null 2>&1; then
    case "$keep_existing" in
	true) exit 0 ;;
	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

start_sh=$(mktemp)
docker run --rm $image start.sh > "$start_sh"

bash "$start_sh" "$@"
rm "$start_sh"

rm -f "$image_stamp.use"
touch "$image_stamp.use"

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