summaryrefslogtreecommitdiff
path: root/redis/selector.py
blob: 11837bc39c9d95bfc51ec2d23cb401f49a92937e (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import errno
import select
from redis.exceptions import RedisError


_DEFAULT_SELECTOR = None


class BaseSelector(object):
    """
    Base class for all Selectors
    """
    def __init__(self, sock):
        self.sock = sock

    def can_read(self, timeout=0):
        """
        Return True if data is ready to be read from the socket,
        otherwise False.

        This doesn't guarentee that the socket is still connected, just that
        there is data to read.

        Automatically retries EINTR errors based on PEP 475.
        """
        while True:
            try:
                return self.check_can_read(timeout)
            except (select.error, IOError) as ex:
                if self.errno_from_exception(ex) == errno.EINTR:
                    continue
                return False

    def is_ready_for_command(self, timeout=0):
        """
        Return True if the socket is ready to send a command,
        otherwise False.

        Automatically retries EINTR errors based on PEP 475.
        """
        while True:
            try:
                return self.check_is_ready_for_command(timeout)
            except (select.error, IOError) as ex:
                if self.errno_from_exception(ex) == errno.EINTR:
                    continue
                return False

    def check_can_read(self, timeout):
        """
        Perform the can_read check. Subclasses should implement this.
        """
        raise NotImplementedError

    def check_is_ready_for_command(self, timeout):
        """
        Perform the is_ready_for_command check. Subclasses should
        implement this.
        """
        raise NotImplementedError

    def close(self):
        """
        Close the selector.
        """
        self.sock = None

    def errno_from_exception(self, ex):
        """
        Get the error number from an exception
        """
        if hasattr(ex, 'errno'):
            return ex.errno
        elif ex.args:
            return ex.args[0]
        else:
            return None


if hasattr(select, 'select'):
    class SelectSelector(BaseSelector):
        """
        A select-based selector that should work on most platforms.

        This is the worst poll strategy and should only be used if no other
        option is available.
        """
        def check_can_read(self, timeout):
            """
            Return True if data is ready to be read from the socket,
            otherwise False.

            This doesn't guarentee that the socket is still connected, just
            that there is data to read.
            """
            return bool(select.select([self.sock], [], [], timeout)[0])

        def check_is_ready_for_command(self, timeout):
            """
            Return True if the socket is ready to send a command,
            otherwise False.
            """
            r, w, e = select.select([self.sock], [self.sock], [self.sock],
                                    timeout)
            return bool(w and not r and not e)


if hasattr(select, 'poll'):
    class PollSelector(BaseSelector):
        """
        A poll-based selector that should work on (almost?) all versions
        of Unix
        """
        _EVENT_MASK = (select.POLLIN | select.POLLPRI | select.POLLOUT |
                       select.POLLERR | select.POLLHUP)
        _READ_MASK = select.POLLIN | select.POLLPRI
        _WRITE_MASK = select.POLLOUT

        def __init__(self, sock):
            super(PollSelector, self).__init__(sock)
            self.poller = select.poll()
            self.poller.register(sock, self._EVENT_MASK)

        def close(self):
            """
            Close the selector.
            """
            try:
                self.poller.unregister(self.sock)
            except (KeyError, ValueError):
                # KeyError is raised if somehow the socket was not registered
                # ValueError is raised if the socket's file descriptor is
                #   negative.
                # In either case, we can't do anything better than to remove
                # the reference to the poller.
                pass
            self.poller = None
            self.sock = None

        def check_can_read(self, timeout=0):
            """
            Return True if data is ready to be read from the socket,
            otherwise False.

            This doesn't guarentee that the socket is still connected, just
            that there is data to read.
            """
            events = self.poller.poll(0)
            return bool(events and events[0][1] & self._READ_MASK)

        def check_is_ready_for_command(self, timeout=0):
            """
            Return True if the socket is ready to send a command,
            otherwise False
            """
            events = self.poller.poll(0)
            return bool(events and events[0][1] == self._WRITE_MASK)


def has_selector(selector):
    "Determine if the current platform has the selector available"
    try:
        if selector == 'poll':
            # the select module offers the poll selector even if the platform
            # doesn't support it. Attempt to poll for nothing to make sure
            # poll is available
            p = select.poll()
            p.poll(0)
        else:
            # the other selectors will fail when instantiated
            getattr(select, selector)().close()
        return True
    except (OSError, AttributeError):
        return False


def DefaultSelector(sock):
    "Return the best selector for the platform"
    global _DEFAULT_SELECTOR
    if _DEFAULT_SELECTOR is None:
        if has_selector('poll'):
            _DEFAULT_SELECTOR = PollSelector
        elif hasattr(select, 'select'):
            _DEFAULT_SELECTOR = SelectSelector
        else:
            raise RedisError('Platform does not support any selectors')
    return _DEFAULT_SELECTOR(sock)