build_and_run_docker.sh 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \
  29. -v "$git_root:/var/local/jenkins/protobuf:ro" \
  30. -v $CCACHE_DIR:$CCACHE_DIR \
  31. -w /var/local/git/protobuf \
  32. --name=$CONTAINER_NAME \
  33. $DOCKER_IMAGE_NAME \
  34. bash -l "/var/local/jenkins/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true"
  35. # Copy output artifacts
  36. if [ "$OUTPUT_DIR" != "" ]
  37. then
  38. docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "$git_root" || FAILED="true"
  39. fi
  40. # remove the container, possibly killing it first
  41. docker rm -f $CONTAINER_NAME || true
  42. if [ "$FAILED" != "" ]
  43. then
  44. exit 1
  45. fi