图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.2 KiB

  1. """ZooKeeper Leader Elections
  2. :Maintainer: None
  3. :Status: Unknown
  4. """
  5. from kazoo.exceptions import CancelledError
  6. class Election(object):
  7. """Kazoo Basic Leader Election
  8. Example usage with a :class:`~kazoo.client.KazooClient` instance::
  9. zk = KazooClient()
  10. zk.start()
  11. election = zk.Election("/electionpath", "my-identifier")
  12. # blocks until the election is won, then calls
  13. # my_leader_function()
  14. election.run(my_leader_function)
  15. """
  16. def __init__(self, client, path, identifier=None):
  17. """Create a Kazoo Leader Election
  18. :param client: A :class:`~kazoo.client.KazooClient` instance.
  19. :param path: The election path to use.
  20. :param identifier: Name to use for this lock contender. This
  21. can be useful for querying to see who the
  22. current lock contenders are.
  23. """
  24. self.lock = client.Lock(path, identifier)
  25. def run(self, func, *args, **kwargs):
  26. """Contend for the leadership
  27. This call will block until either this contender is cancelled
  28. or this contender wins the election and the provided leadership
  29. function subsequently returns or fails.
  30. :param func: A function to be called if/when the election is
  31. won.
  32. :param args: Arguments to leadership function.
  33. :param kwargs: Keyword arguments to leadership function.
  34. """
  35. if not callable(func):
  36. raise ValueError("leader function is not callable")
  37. try:
  38. with self.lock:
  39. func(*args, **kwargs)
  40. except CancelledError:
  41. pass
  42. def cancel(self):
  43. """Cancel participation in the election
  44. .. note::
  45. If this contender has already been elected leader, this
  46. method will not interrupt the leadership function.
  47. """
  48. self.lock.cancel()
  49. def contenders(self):
  50. """Return an ordered list of the current contenders in the
  51. election
  52. .. note::
  53. If the contenders did not set an identifier, it will appear
  54. as a blank string.
  55. """
  56. return self.lock.contenders()