build_and_run_docker.sh 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. # DOCKERHUB_ORGANIZATION - The organization on docker hub storing the
  7. # Dockerfile.
  8. # DOCKERFILE_DIR - Directory in which Dockerfile file is located.
  9. # DOCKER_RUN_SCRIPT - Script to run under docker (relative to protobuf repo root)
  10. # OUTPUT_DIR - Directory that will be copied from inside docker after finishing.
  11. # $@ - Extra args to pass to docker run
  12. set -ex
  13. cd $(dirname $0)/../..
  14. git_root=$(pwd)
  15. cd -
  16. # Use image name based on Dockerfile sha1
  17. if [ -z "$DOCKERHUB_ORGANIZATION" ]
  18. then
  19. DOCKERHUB_ORGANIZATION=grpctesting/protobuf
  20. DOCKER_IMAGE_NAME=${DOCKERHUB_ORGANIZATION}_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ )
  21. else
  22. # TODO(teboring): Remove this when all tests have been migrated to separate
  23. # docker images.
  24. DOCKERFILE_PREFIX=$(basename $DOCKERFILE_DIR)
  25. DOCKER_IMAGE_NAME=${DOCKERHUB_ORGANIZATION}/${DOCKERFILE_PREFIX}_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ )
  26. fi
  27. # Pull dockerimage from Dockerhub. This sometimes fails intermittently, so we
  28. # keep trying until we succeed.
  29. until docker pull $DOCKER_IMAGE_NAME; do sleep 10; done
  30. # Ensure existence of ccache directory
  31. CCACHE_DIR=/tmp/protobuf-ccache
  32. mkdir -p $CCACHE_DIR
  33. # Choose random name for docker container
  34. CONTAINER_NAME="build_and_run_docker_$(uuidgen)"
  35. echo $git_root
  36. # Run command inside docker
  37. docker run \
  38. "$@" \
  39. -e CCACHE_DIR=$CCACHE_DIR \
  40. -e KOKORO_BUILD_NUMBER=$KOKORO_BUILD_NUMBER \
  41. -e KOKORO_BUILD_ID=$KOKORO_BUILD_ID \
  42. -e EXTERNAL_GIT_ROOT="/var/local/kokoro/protobuf" \
  43. -e TEST_SET="$TEST_SET" \
  44. -v "$git_root:/var/local/kokoro/protobuf:ro" \
  45. -v $CCACHE_DIR:$CCACHE_DIR \
  46. -w /var/local/git/protobuf \
  47. --name=$CONTAINER_NAME \
  48. $DOCKER_IMAGE_NAME \
  49. bash -l "/var/local/kokoro/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true"
  50. # remove the container, possibly killing it first
  51. docker rm -f $CONTAINER_NAME || true
  52. [ -z "$FAILED" ] || {
  53. exit 1
  54. }