Skip to content

Instantly share code, notes, and snippets.

@bencord0
Created March 5, 2016 00:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bencord0/0c1812b0a39fa52950a7 to your computer and use it in GitHub Desktop.
Save bencord0/0c1812b0a39fa52950a7 to your computer and use it in GitHub Desktop.
etcd leader election in python
from os import urandom
from etcd import Client, EtcdKeyNotFound
from time import sleep
from uuid import uuid4
# Usually, read this from the local node's configuration
me = uuid4().hex
client = Client()
def find_the_leader(service, ttl=10):
service = str(service)
try:
client.test_and_set(service + '/leader', me, me, ttl=ttl)
print('I am still the leader')
except EtcdKeyNotFound:
client.write(service + '/leader', me, ttl=ttl, prevExist=False)
print('I am the leader')
except ValueError as ve:
leader = ve.message.split()[-1][:-1]
print('The leader is: {}'.format(leader))
def main():
while True:
find_the_leader('/service')
# simulate flaky conditions
sleep(ord(urandom(1)) % 15)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
try:
client.delete('/service/leader', prevValue=me)
except ValueError:
# I wasn't the leader anyway
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment