Skip to content

Instantly share code, notes, and snippets.

@josephglanville
Last active December 29, 2015 03:49
Show Gist options
  • Save josephglanville/7610288 to your computer and use it in GitHub Desktop.
Save josephglanville/7610288 to your computer and use it in GitHub Desktop.
Simple master election using RethinkDB and gevent
#!/usr/bin/env python
import rethinkdb as r
import gevent
import gevent.monkey
gevent.monkey.patch_all()
LOCK_TIMEOUT = 15
UPDATE_TIMEOUT = 5
r.connect().repl()
r.branch(r.table_list().contains('locks'),
r.expr({"created": 1}),
r.table_create('locks')).run()
class MasterElectionExample:
def __init__(self):
self.is_master = False
self.request_master_election()
while True:
if self.is_master:
print 'i am the master, updating lock'
self.update_lock('master')
else:
self.request_master_election()
gevent.sleep(UPDATE_TIMEOUT)
def aquire_lock(self, lock_name):
res = r.branch(r.table('locks').get(lock_name),
r.do(r.table('locks').get(lock_name),
lambda lock: r.branch(
lock['time'] > (r.now() - LOCK_TIMEOUT),
r.expr(
{"unchanged": 1, "replaced": 0, "inserted": 0}),
r.table('locks').replace(
{"id": lock_name, "time": r.now()})
)
),
r.table('locks').insert(
{"id": lock_name, "time": r.now()})
).run()
print res
return res['inserted'] == 1 or res['replaced'] == 1
def update_lock(self, lock_name):
r.table('locks').update({'id': lock_name, 'time': r.now()}).run()
def request_master_election(self):
if self.aquire_lock('master'):
self.is_master = True
print 'i am the master. :)'
else:
self.is_master = False
print 'i am not the master. :('
master = MasterElectionExample()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment