Skip to content

Instantly share code, notes, and snippets.

@nevmerzhitsky
Created July 4, 2020 18:42
Show Gist options
  • Save nevmerzhitsky/d98a0041cd76e43a056199c1f8040500 to your computer and use it in GitHub Desktop.
Save nevmerzhitsky/d98a0041cd76e43a056199c1f8040500 to your computer and use it in GitHub Desktop.
Run a Docker Swarm service one-off
#!/usr/bin/env bash
set -e
config_file="$1"
stack_name="$2"
service_name="$3"
timeout="${4:-60}"
if [[ -z ${config_file} ]] || [[ -z ${stack_name} ]] || [[ -z ${service_name} ]]; then
exit 1
fi
service_full_name="${stack_name}_${service_name}"
function gracefully_exit() {
docker service rm $1
if [[ $2 > 0 ]]; then
kill -SIGTERM $2 || true
fi
exit $3
}
echo "Running one-off service ${service_full_name} from config ${config_file} with timeout ${timeout}"
docker service scale ${service_full_name}=0 || true
env $(cat .env | grep ^[A-Z] | xargs) docker stack deploy -c docker-compose.yml \
-c ${config_file} ${stack_name}
task_id=$(docker service ps ${service_full_name} -f "desired-state=running" -q | head -1)
echo "Running task ID: ${task_id}"
if [[ "${task_id}" == "" ]]; then
echo "Cannot find task ID with desired state is running"
gracefully_exit ${service_full_name} 0 1
fi
bash -c "docker service logs --raw -f ${task_id}" &
process_id=$!
end_seconds=$((SECONDS + ${timeout}))
while [[ $SECONDS -lt ${end_seconds} ]]; do
if [[ "$(docker inspect --format "{{.Status.State}}" ${task_id})" == "complete" ]]; then
echo "Finished by complete state"
gracefully_exit ${service_full_name} ${process_id} 0
fi
sleep 5
done
echo "Stopped by timeout"
gracefully_exit ${service_full_name} ${process_id} 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment