Last active
January 25, 2018 13:13
-
-
Save ueokande/01ec5cdd6fa31f9bd481dc05e7d42c50 to your computer and use it in GitHub Desktop.
Leader election with etcd
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/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