Created
March 5, 2016 00:35
-
-
Save bencord0/0c1812b0a39fa52950a7 to your computer and use it in GitHub Desktop.
etcd leader election in python
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
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