68 lines
1.2 KiB
Bash
68 lines
1.2 KiB
Bash
MUTEX=mutex
|
|
MUTEX_OWNER=$HOSTNAME
|
|
MUTEX_TIMEOUT=600
|
|
|
|
release_lock() {
|
|
local S3LOCK=$1
|
|
|
|
rm -f $MUTEX
|
|
aws s3 rm $S3LOCK
|
|
}
|
|
|
|
# Lock not timed out and we own it: 0
|
|
# Lock not timed out and someone else owns it: 1
|
|
# Lock timed out: 2
|
|
verify_lock() {
|
|
local S3LOCK=$1
|
|
|
|
aws s3 cp $S3LOCK $MUTEX
|
|
_host=$(grep "MUTEX_OWNER=" $MUTEX | sed -e 's/MUTEX_OWNER=//')
|
|
_time=$(grep "MUTEX_TIME=" $MUTEX | sed -e 's/MUTEX_TIME=//')
|
|
|
|
# Check for timestamp and timeout
|
|
let timepassed=$(date -u +%s)-$_time
|
|
[ $timepassed -gt $MUTEX_TIMEOUT ] && return 2
|
|
|
|
[ "$_host" == "$MUTEX_OWNER" ] && return 0
|
|
return 1
|
|
}
|
|
|
|
aquire_lock() {
|
|
local S3LOCK=$1
|
|
|
|
echo "MUTEX_OWNER=${MUTEX_OWNER}" > $MUTEX
|
|
echo "MUTEX_TIME=$(date -u +%s)" >> $MUTEX
|
|
aws s3 cp $MUTEX $S3LOCK
|
|
|
|
# verify we actually got the lock
|
|
sleep 2
|
|
verify_lock $S3LOCK
|
|
}
|
|
|
|
check_lock() {
|
|
local S3LOCK=$1
|
|
|
|
aws s3 ls $S3LOCK && rc=$? || rc=$?
|
|
|
|
# No LOCK ? -> get it !
|
|
if [ $rc -ne 0 ]; then
|
|
aquire_lock $S3LOCK
|
|
|
|
else
|
|
verify_lock $S3LOCK && rc=$? || rc=$?
|
|
|
|
# Lock timeout -> we get it
|
|
if [ $rc -eq 2 ]; then
|
|
aquire_lock $S3LOCK
|
|
|
|
# we already own it
|
|
elif [ $rc -eq 0 ]; then
|
|
return 0
|
|
|
|
# someone else has a valid lock
|
|
else
|
|
return 1
|
|
fi
|
|
fi
|
|
}
|