build_and_run_docker.sh 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 sha1
  15. DOCKERHUB_ORGANIZATION=grpctesting/protobuf
  16. DOCKER_IMAGE_NAME=${DOCKERHUB_ORGANIZATION}_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ )
  17. # Pull dockerimage from Dockerhub
  18. docker pull $DOCKER_IMAGE_NAME
  19. # Ensure existence of ccache directory
  20. CCACHE_DIR=/tmp/protobuf-ccache
  21. mkdir -p $CCACHE_DIR
  22. # Choose random name for docker container
  23. CONTAINER_NAME="build_and_run_docker_$(uuidgen)"
  24. echo $git_root
  25. # Run command inside docker
  26. docker run \
  27. "$@" \
  28. -e CCACHE_DIR=$CCACHE_DIR \
  29. -e KOKORO_BUILD_NUMBER=$KOKORO_BUILD_NUMBER \
  30. -e KOKORO_BUILD_ID=$KOKORO_BUILD_ID \
  31. -e EXTERNAL_GIT_ROOT="/var/local/kokoro/protobuf" \
  32. -e TEST_SET="$TEST_SET" \
  33. -e THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \
  34. -v "$git_root:/var/local/kokoro/protobuf:ro" \
  35. -v $CCACHE_DIR:$CCACHE_DIR \
  36. -w /var/local/git/protobuf \
  37. --name=$CONTAINER_NAME \
  38. $DOCKER_IMAGE_NAME \
  39. bash -l "/var/local/kokoro/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true"
  40. # Copy output artifacts
  41. if [ "$OUTPUT_DIR" != "" ]
  42. then
  43. docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "${git_root}/kokoro" || FAILED="true"
  44. fi
  45. # remove the container, possibly killing it first
  46. docker rm -f $CONTAINER_NAME || true
  47. if [ "$FAILED" != "" ]
  48. then
  49. exit 1
  50. fi