Created
October 22, 2014 08:26
-
-
Save grooverdan/192d4bccf4d2725c68bf to your computer and use it in GitHub Desktop.
This file contains 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
#!/bin/bash | |
if [ $# -gt 1 ]; then | |
CLIENT=$1 | |
HOSTNAME=$2 | |
else | |
echo fail | |
exit 1 | |
fi | |
SCRIPT=' | |
local client = KEYS[1] | |
local host = ARGV[1] | |
-- Decrement the count, if back to 0 release the munin-update | |
if redis.call("DECR", client .. "_hostcount") == 0 then | |
redis.call("DEL", client) | |
return 1 | |
end | |
return 0 | |
' | |
ret=`redis-cli EVAL "${SCRIPT}" 1 $CLIENT $HOSTNAME` | |
if [ $ret -eq 1 ]; then | |
redis-cli "PUBLISH" "${CLIENT}hosts-finished" "munin-update go!" | |
fi | |
root@blackfish:/usr/local/bin# cat rsync_lock.sh | |
#!/bin/bash | |
if [ $# -gt 1 ]; then | |
CLIENT=$1 | |
HOSTNAME=$2 | |
else | |
echo fail | |
exit 1 | |
fi | |
SCRIPT=' | |
local client = KEYS[1] | |
local host = ARGV[1] | |
redis.call("SET", client .. "_hostcount", 0, "NX") | |
-- lock the client in the name of host if not exists, expires 120 seconds | |
if redis.call("SET", client, host, "EX", 120, "NX") == "OK" then | |
return redis.call("INCR", client .. "_hostcount") | |
else | |
if redis.call("get", client) ~= "munin-update" then | |
-- another host is also sync set timeout back to 120 for us | |
redis.call("EXPIRE", client, 120) | |
return redis.call("INCR", client .. "_hostcount") | |
end | |
-- need to wait | |
return -1 | |
end | |
return 0 | |
' | |
# ensure a value exists | |
redis-cli "SET" "${CLIENT}_hostcount" 0 "NX" | |
channel=${CLIENT}munin-update-finished | |
attempts=5 | |
while [ `redis-cli EVAL "${SCRIPT}" 1 $CLIENT $HOSTNAME` -eq -1 ]; do | |
if [ $attempts -eq 0 ]; then | |
echo "failed to set ${CLIENT} to ${HOST} after 5 attempts" | |
exit 2 | |
fi | |
attempts=$(( $attempts - 1 )) | |
if [ -z "${sub_PID}" ]; then | |
coproc sub { redis-cli --raw "SUBSCRIBE" "${channel}" ; } | |
# read 3 lines that say we where subscribed | |
read -ru ${sub[0]}; read -ru ${sub[0]};read -ru ${sub[0]}; | |
fi | |
read -ru ${sub[0]}; | |
if [ "$REPLY" != 'message' ]; then | |
kill $sub_PID | |
exit 3 | |
fi | |
read -ru ${sub[0]}; | |
if [ "$REPLY" != "${channel}" ]; then | |
kill $sub_PID | |
exit 4 | |
fi | |
read -ru ${sub[0]}; | |
#echo "channel ${channel} message $REPLY" | |
done | |
[ ! -z "${sub_PID}" ] && kill $sub_PID | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment