build_and_run_docker.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. set -ex
  11. cd $(dirname $0)/..
  12. git_root=$(pwd)
  13. cd -
  14. # Use image name based on Dockerfile location checksum
  15. DOCKER_IMAGE_NAME=$(basename $DOCKERFILE_DIR)_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ )
  16. # Make sure docker image has been built. Should be instantaneous if so.
  17. docker build -t $DOCKER_IMAGE_NAME $DOCKERFILE_DIR
  18. # Ensure existence of ccache directory
  19. CCACHE_DIR=/tmp/protobuf-ccache
  20. mkdir -p $CCACHE_DIR
  21. # Choose random name for docker container
  22. CONTAINER_NAME="build_and_run_docker_$(uuidgen)"
  23. # Run command inside docker
  24. docker run \
  25. "$@" \
  26. -e CCACHE_DIR=$CCACHE_DIR \
  27. -e EXTERNAL_GIT_ROOT="/var/local/jenkins/protobuf" \
  28. -e TEST_SET="$TEST_SET" \
  29. -e THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \
  30. -v "$git_root:/var/local/jenkins/protobuf:ro" \
  31. -v $CCACHE_DIR:$CCACHE_DIR \
  32. -w /var/local/git/protobuf \
  33. --name=$CONTAINER_NAME \
  34. $DOCKER_IMAGE_NAME \
  35. bash -l "/var/local/jenkins/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true"
  36. # Copy output artifacts
  37. if [ "$OUTPUT_DIR" != "" ]
  38. then
  39. docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "$git_root" || FAILED="true"
  40. fi
  41. # remove the container, possibly killing it first
  42. docker rm -f $CONTAINER_NAME || true
  43. if [ "$FAILED" != "" ]
  44. then
  45. exit 1
  46. fi