From 38db4cb9477bd66d7a390b913a8a46442b17ffd5 Mon Sep 17 00:00:00 2001 From: Duco van Amstel Date: Fri, 26 Mar 2021 13:47:52 +0000 Subject: [PATCH] Guard docker network operations with lock --- hooks/pre-command | 14 +++++++++++--- plugin.yml | 2 +- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/hooks/pre-command b/hooks/pre-command index e5fce68..9b8b619 100755 --- a/hooks/pre-command +++ b/hooks/pre-command @@ -1,5 +1,6 @@ # shellcheck shell=bash +set -e -u -o pipefail [[ -n "${DEBUG:-}" ]] && set -x if [[ -z "${BUILDKITE_PLUGIN_DOCKER_SERVICE_CONTAINER:-}" ]]; then @@ -10,10 +11,17 @@ fi docker_cmd="docker run --rm --detach" if [[ "${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK:-host}" != "host" ]]; then - if [[ "$(docker network ls --filter="name=${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK}" --format="{{.Name}}")" != "${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK}" ]]; then - docker network create --driver=bridge "${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK}" - fi + # We guard the network creation via a POSIX file-descriptor lock as we might otherwise end up with + # two identically named networks if this plugin is invoked on the same host multiple time + # simultaneously. + ( + flock --exclusive --timeout=5 9 + if [[ "$(docker network ls --filter="name=${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK}" --format="{{.Name}}")" != "${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK}" ]]; then + docker network create --driver=bridge "${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK}" + fi + ) 9>/var/lock/docker-service-buildkite-plugin.lock fi + docker_cmd="${docker_cmd} --network=${BUILDKITE_PLUGIN_DOCKER_SERVICE_NETWORK:-host}" function parse_flags() { diff --git a/plugin.yml b/plugin.yml index 182ac61..30a5c1d 100644 --- a/plugin.yml +++ b/plugin.yml @@ -3,8 +3,8 @@ name: Docker Service description: Run docker containers that can be used by your build steps as services author: https://github.com/improbable-eng requirements: - - bash - docker + - flock configuration: additionalProperties: false properties: