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 12set -ex 13 14cd $(dirname $0)/.. 15git_root=$(pwd) 16cd - 17 18# Use image name based on Dockerfile location checksum 19DOCKER_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. 22docker build -t $DOCKER_IMAGE_NAME $DOCKERFILE_DIR 23 24# Ensure existence of ccache directory 25CCACHE_DIR=/tmp/protobuf-ccache 26mkdir -p $CCACHE_DIR 27 28# Choose random name for docker container 29CONTAINER_NAME="build_and_run_docker_$(uuidgen)" 30 31# Run command inside docker 32docker 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 45if [ "$OUTPUT_DIR" != "" ] 46then 47 docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "$git_root" || FAILED="true" 48fi 49 50# remove the container, possibly killing it first 51docker rm -f $CONTAINER_NAME || true 52 53if [ "$FAILED" != "" ] 54then 55 exit 1 56fi 57