Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env bash
CONSUL_ADDR="${CONSUL_ADDR:-http://127.0.0.1:8500}"
function create_session(){
local session_id=$(curl -s -XPUT "${CONSUL_ADDR}/v1/session/create" \
-d "{\"Name\": \"backup\"}" | jq -r '.ID' )
echo ${session_id}
}
function acquire_lock(){
local session_id=${1}
echo -n "Trying to acquire a lock for session ${session_id}..."
res=$(curl -s -f -XPUT "${CONSUL_ADDR}/v1/kv/locks/backup/.lock?acquire=${session_id}")
if [[ ${res} != "true" ]]; then
echo "Couldn't acquire lock - exiting now!"
exit 1
fi
echo ${res}
}
function release_lock(){
echo -n "Releasing lock..."
local session_id=${1}
curl -XPUT \
"${CONSUL_ADDR}/v1/kv/locks/backup/.lock?release=${session_id}"
}
function perform_backup(){
echo -n "Copying some stuff on S3.."
echo "Done!"
}
session_id=$(create_session)
acquire_lock ${session_id}
perform_backup
release_lock ${session_id}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment