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

keep_existing="${keep_existing-true}"
verbose="${verbose-true}"

set -u

if $verbose; then set -x; fi

# shellcheck disable=SC2154
docker pull "$image"

rm_cnt=""
# shellcheck disable=SC2154
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.
    rm_cnt="$container.bak"
    docker rename "$container" "$rm_cnt"
fi

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

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

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