Created
March 15, 2018 07:30
-
-
Save yrong/fc62dbaabeb9971966f135aa331e5113 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
session_id=$(curl -s -XPUT "${consul_address}/v1/session/create" -d "{\"Name\": \"${task_name}\"}" | jq -r '.ID') | |
acquire_lock() { | |
session_id=${1} | |
echo "Trying to acquire the lock..." | |
result=$(curl -s -XPUT "${consul_address}/v1/kv/locks/${task_name}/.lock?acquire=${session_id}") | |
[ "${result}" == "true" ] && echo "Lock acquired" | |
} | |
release_lock() { | |
session_id=${1} | |
echo "Releasing the lock..." | |
result=$(curl -s -XPUT "${consul_address}/v1/kv/locks/${task_name}/.lock?release=${session_id}") | |
[ "${result}" == "true" ] && echo "Lock released" | |
} | |
destroy_session () { | |
session_id=${1} | |
echo "Destroying the session..." | |
result=$(curl -s -XPUT "${consul_address}/v1/session/destroy/${session_id}") | |
[ "${result}" == "true" ] && echo "Session destroyed" | |
} | |
if ! acquire_lock "${session_id}"; then | |
destroy_session "${session_id}" | |
echo "Unable to acquire the lock." | |
echo "The job is probably already running on an other server." | |
exit 0 | |
fi | |
do_stuff | |
release_lock "${session_id}" | |
destroy_session "${session_id}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment