Josh Haberman | 67c727c | 2016-03-04 14:21:18 -0800 | [diff] [blame] | 1 | #!/bin/bash |
| 2 | # |
| 3 | # Builds docker image and runs a command under it. |
| 4 | # This is a generic script that is configured with the following variables: |
| 5 | # |
| 6 | # DOCKERFILE_DIR - Directory in which Dockerfile file is located. |
| 7 | # DOCKER_RUN_SCRIPT - Script to run under docker (relative to protobuf repo root) |
| 8 | # OUTPUT_DIR - Directory that will be copied from inside docker after finishing. |
| 9 | # $@ - Extra args to pass to docker run |
| 10 | |
| 11 | |
| 12 | set -ex |
| 13 | |
| 14 | cd $(dirname $0)/.. |
| 15 | git_root=$(pwd) |
| 16 | cd - |
| 17 | |
| 18 | # Use image name based on Dockerfile location checksum |
| 19 | DOCKER_IMAGE_NAME=$(basename $DOCKERFILE_DIR)_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ ) |
| 20 | |
| 21 | # Make sure docker image has been built. Should be instantaneous if so. |
| 22 | docker build -t $DOCKER_IMAGE_NAME $DOCKERFILE_DIR |
| 23 | |
| 24 | # Ensure existence of ccache directory |
| 25 | CCACHE_DIR=/tmp/protobuf-ccache |
| 26 | mkdir -p $CCACHE_DIR |
| 27 | |
| 28 | # Choose random name for docker container |
| 29 | CONTAINER_NAME="build_and_run_docker_$(uuidgen)" |
| 30 | |
| 31 | # Run command inside docker |
| 32 | docker run \ |
| 33 | "$@" \ |
| 34 | -e CCACHE_DIR=$CCACHE_DIR \ |
| 35 | -e EXTERNAL_GIT_ROOT="/var/local/jenkins/protobuf" \ |
| 36 | -e THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \ |
| 37 | -v "$git_root:/var/local/jenkins/protobuf:ro" \ |
| 38 | -v $CCACHE_DIR:$CCACHE_DIR \ |
| 39 | -w /var/local/git/protobuf \ |
| 40 | --name=$CONTAINER_NAME \ |
| 41 | $DOCKER_IMAGE_NAME \ |
| 42 | bash -l "/var/local/jenkins/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true" |
| 43 | |
| 44 | # Copy output artifacts |
| 45 | if [ "$OUTPUT_DIR" != "" ] |
| 46 | then |
| 47 | docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "$git_root" || FAILED="true" |
| 48 | fi |
| 49 | |
| 50 | # remove the container, possibly killing it first |
| 51 | docker rm -f $CONTAINER_NAME || true |
| 52 | |
| 53 | if [ "$FAILED" != "" ] |
| 54 | then |
| 55 | exit 1 |
| 56 | fi |