summaryrefslogtreecommitdiff
path: root/src/etcd/election.py
blob: 25ea403df92270443e832f4262a283d1f2c20b08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import etcd
import platform


class LeaderElection(object):

    """
    Leader Election class using the etcd module
    """

    def __init__(self, client):
        """
        Initialize a leader election object.

        Args:
            client (etcd.Client): etcd client to use for the connection
        """
        self.client = client

    def get_path(self, key):
        if key.startswith('/'):
            return '/mod/v2/leader{}'.format(key)
        return '/mod/v2/leader/{}'.format(key)

    def set(self, key, name=None, ttl=0, timeout=None):
        """
        Initialize a leader election object.

        Args:
            key (string): name of the leader key,

            ttl (int): ttl (in seconds) for the lock to live.

            name (string): the name to store as the leader name. Defaults to the
                           client's hostname

        """

        name = name or platform.node()
        params = {'ttl': ttl, 'name': name}
        path = self.get_path(key)

        res = self.client.api_execute(
            path, self.client._MPUT, params=params, timeout=timeout)
        return res.data.decode('utf-8')

    def get(self, key):
        """
        Get the name of a leader object.

        Args:
            key (string): name of the leader key,

        Raises:
            etcd.EtcdException

        """
        res = self.client.api_execute(self.get_path(key), self.client._MGET)
        if not res.data:
            raise etcd.EtcdException('Leader path {} not found'.format(key))
        return res.data.decode('utf-8')

    def delete(self, key, name=None):
        """
        Delete a leader object.

        Args:
            key (string): the leader key,

            name (string): name of the elected leader

        Raises:
            etcd.EtcdException

        """
        path = self.get_path(key)
        name = name or platform.node()
        res = self.client.api_execute(path, self.client._MDELETE, {'name': name})
        return res.data.decode('utf-8') == ''