def run(self, lease_name, lease_time): zk = KazooClient(hosts=self.hosts) zk.start() path = "%s/%s" % (self.root, lease_name) # unique id ensures only one action execution if multiple executions on the same host identifier = '%s: %s' % (gethostname(), uuid4()) duration = timedelta(seconds=lease_time) lease = zk.NonBlockingLease(path, duration, identifier=identifier) if not lease: sys.exit(1)
import gevent from gevent.wsgi import WSGIServer from flask import Flask, jsonify from kazoo.client import KazooClient, EventType from kazoo.exceptions import NodeExistsException, NoNodeException logging.basicConfig() zoo_hosts = os.getenv('ZK_HOSTS') zk = KazooClient(hosts=zoo_hosts) zk.start() identity = uuid.uuid4().hex lease = zk.NonBlockingLease("/welcome", datetime.timedelta(minutes=1), identifier=identity) if lease: print(f"Welcome") class LeaderElection(object): def __init__(self): self.identity = bytes(uuid.uuid4().hex, encoding='utf') self.leader = None self.election = None @property def is_leader(self): return self.leader == self.identity