Skip to content

Commit

Permalink
review comments fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
mco-gh committed Aug 6, 2016
1 parent e2e6d1f commit ba95ccf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,10 @@ You can also use this technique via the command line using the gsutil
command, which enables serialization of shell scripts running anywhere.
The `gcslock.sh` file defines two functions, which give the ability to
globally lock shell script logic like this:
```
```sh
source gcslock.sh
lock
echo protected logic
echo "protected logic"
unlock
```

Expand Down
35 changes: 24 additions & 11 deletions gcslock.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,42 +18,55 @@
# via the gsutil command in a shell script. It depends on installation
# of the Google Cloud SDK (https://cloud.google.com/sdk/), which
# includes the gsutil command.

#
# Usage example:
#
# source gcslock.sh
# lock mybucket
# echo "lock acquired"
# unlock mybucket

# The lock function expects the first (and only) argument to be
# the name of a bucket writable by the user running this script.
# It creates the lock object in the passed bucket with a special
# header to obtain mutual exclusion.
# header to obtain mutual exclusion. If the lock object creation
# fails, it retries indefinitely with expontential backoff.

lock() {
if [ "$1" = "" ]
then
echo missing bucket argument
echo "lock: missing bucket argument"
exit 1
fi
LOCK="gs://$1/lock"
sleep_time=1
while ! echo "lock" | gsutil -q -h "x-goog-if-generation-match:0" cp - $LOCK
do
echo "failed to obtain lock, retrying in $sleep_time seconds"
echo "lock: failed to obtain lock, retrying in $sleep_time seconds"
sleep $sleep_time
sleep_time=$(expr $sleep_time '*' 2)
done
}

# The unlock function expects the first (and only) argument to be
# the name of a bucket writable by the user running this script.
# It relinquishes the lock by removing the lock object.
# It relinquishes the lock by removing the lock object. If the
# lock object removal fails, it retries indefinitely with
# expontential backoff.

unlock() {
if [ "$1" = "" ]
then
echo missing bucket argument
echo "unlock: missing bucket argument"
exit 1
fi
LOCK="gs://$1/lock"
gsutil -q rm $LOCK
sleep_time=1
while ! gsutil -q rm $LOCK
do
echo "unlock: failed to relinquish lock, retrying in $sleep_time seconds"
sleep $sleep_time
sleep_time=$(expr $sleep_time '*' 2)
done
}

# Usage example...
# lock mybucket
# echo "lock acquired"
# unlock mybucket

0 comments on commit ba95ccf

Please sign in to comment.