Skip to content

Commit

Permalink
Guard docker network operations with lock
Browse files Browse the repository at this point in the history
  • Loading branch information
Helcaraxan committed Mar 26, 2021
1 parent ffb8dfe commit 38db4cb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
14 changes: 11 additions & 3 deletions hooks/pre-command
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# shellcheck shell=bash

set -e -u -o pipefail
[[ -n "${DEBUG:-}" ]] && set -x

if [[ -z "${BUILDKITE_PLUGIN_DOCKER_SERVICE_CONTAINER:-}" ]]; then
Expand All @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion plugin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 38db4cb

Please sign in to comment.