Skip to content

Instantly share code, notes, and snippets.

@ueokande
Last active January 25, 2018 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ueokande/01ec5cdd6fa31f9bd481dc05e7d42c50 to your computer and use it in GitHub Desktop.
Save ueokande/01ec5cdd6fa31f9bd481dc05e7d42c50 to your computer and use it in GitHub Desktop.
Leader election with etcd
#!/bin/sh
ID=$(uuidgen)
LEADER_KEY="localhost:2379/v2/keys/master"
TTL=5
INTERVAL=1
i_am_leader() {
echo "I am leader";
while true; do
body=$(curl -sSL -XPUT "${LEADER_KEY}?prevValue=${ID}&ttl=${TTL}&value=${ID}")
[ $? != 0 ] && return
errorCode=$(echo $body | jq -r .errorCode)
if [ $errorCode != 'null' ]; then
echo "something fail"
exit 1
fi
sleep $INTERVAL
done
}
try_to_be_leader() {
echo "wait for leader dying"
while true; do
body=$(curl -sSL -XPUT "${LEADER_KEY}?prevExist=false&ttl=${TTL}&value=${ID}")
[ $? != 0 ] && return
errorCode=$(echo $body | jq -r .errorCode)
if [ $errorCode = 'null' ]; then
i_am_leader
fi
sleep $INTERVAL
done
}
try_to_be_leader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment