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
188
189
190
191
192
193
194
195
196
197
198
199
200
|
# -*- test-case-name: twisted.test.test_internet -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Select reactor
"""
from __future__ import division, absolute_import
from time import sleep
import sys, select, socket
from errno import EINTR, EBADF
from zope.interface import implementer
from twisted.internet.interfaces import IReactorFDSet
from twisted.internet import posixbase
from twisted.python import log
from twisted.python.runtime import platformType
def win32select(r, w, e, timeout=None):
"""Win32 select wrapper."""
if not (r or w):
# windows select() exits immediately when no sockets
if timeout is None:
timeout = 0.01
else:
timeout = min(timeout, 0.001)
sleep(timeout)
return [], [], []
# windows doesn't process 'signals' inside select(), so we set a max
# time or ctrl-c will never be recognized
if timeout is None or timeout > 0.5:
timeout = 0.5
r, w, e = select.select(r, w, w, timeout)
return r, w + e, []
if platformType == "win32":
_select = win32select
else:
_select = select.select
try:
from twisted.internet.win32eventreactor import _ThreadedWin32EventsMixin
except ImportError:
_extraBase = object
else:
_extraBase = _ThreadedWin32EventsMixin
@implementer(IReactorFDSet)
class SelectReactor(posixbase.PosixReactorBase, _extraBase):
"""
A select() based reactor - runs on all POSIX platforms and on Win32.
@ivar _reads: A set containing L{FileDescriptor} instances which will be
checked for read events.
@ivar _writes: A set containing L{FileDescriptor} instances which will be
checked for writability.
"""
def __init__(self):
"""
Initialize file descriptor tracking dictionaries and the base class.
"""
self._reads = set()
self._writes = set()
posixbase.PosixReactorBase.__init__(self)
def _preenDescriptors(self):
log.msg("Malformed file descriptor found. Preening lists.")
readers = list(self._reads)
writers = list(self._writes)
self._reads.clear()
self._writes.clear()
for selSet, selList in ((self._reads, readers),
(self._writes, writers)):
for selectable in selList:
try:
select.select([selectable], [selectable], [selectable], 0)
except Exception as e:
log.msg("bad descriptor %s" % selectable)
self._disconnectSelectable(selectable, e, False)
else:
selSet.add(selectable)
def doSelect(self, timeout):
"""
Run one iteration of the I/O monitor loop.
This will run all selectables who had input or output readiness
waiting for them.
"""
try:
r, w, ignored = _select(self._reads,
self._writes,
[], timeout)
except ValueError:
# Possibly a file descriptor has gone negative?
self._preenDescriptors()
return
except TypeError:
# Something *totally* invalid (object w/o fileno, non-integral
# result) was passed
log.err()
self._preenDescriptors()
return
except (select.error, socket.error, IOError) as se:
# select(2) encountered an error, perhaps while calling the fileno()
# method of a socket. (Python 2.6 socket.error is an IOError
# subclass, but on Python 2.5 and earlier it is not.)
if se.args[0] in (0, 2):
# windows does this if it got an empty list
if (not self._reads) and (not self._writes):
return
else:
raise
elif se.args[0] == EINTR:
return
elif se.args[0] == EBADF:
self._preenDescriptors()
return
else:
# OK, I really don't know what's going on. Blow up.
raise
_drdw = self._doReadOrWrite
_logrun = log.callWithLogger
for selectables, method, fdset in ((r, "doRead", self._reads),
(w,"doWrite", self._writes)):
for selectable in selectables:
# if this was disconnected in another thread, kill it.
# ^^^^ --- what the !@#*? serious! -exarkun
if selectable not in fdset:
continue
# This for pausing input when we're not ready for more.
_logrun(selectable, _drdw, selectable, method)
doIteration = doSelect
def _doReadOrWrite(self, selectable, method):
try:
why = getattr(selectable, method)()
except:
why = sys.exc_info()[1]
log.err()
if why:
self._disconnectSelectable(selectable, why, method=="doRead")
def addReader(self, reader):
"""
Add a FileDescriptor for notification of data available to read.
"""
self._reads.add(reader)
def addWriter(self, writer):
"""
Add a FileDescriptor for notification of data available to write.
"""
self._writes.add(writer)
def removeReader(self, reader):
"""
Remove a Selectable for notification of data available to read.
"""
self._reads.discard(reader)
def removeWriter(self, writer):
"""
Remove a Selectable for notification of data available to write.
"""
self._writes.discard(writer)
def removeAll(self):
return self._removeAll(self._reads, self._writes)
def getReaders(self):
return list(self._reads)
def getWriters(self):
return list(self._writes)
def install():
"""Configure the twisted mainloop to be run using the select() reactor.
"""
reactor = SelectReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
__all__ = ['install']
|