1. Martin Gergov
  2. udt4twisted

Source

udt4twisted / udt4twisted / udtepollreactor.py

  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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"""
An UDT::epoll() implementation.
For use with the UDT protocol.
"""
from __future__ import division, absolute_import
import errno
import sys
from zope.interface import implementer
from zope.interface import Interface, Attribute
from twisted.internet.interfaces import IReactorFDSet
from twisted.python import log
from twisted.internet import posixbase, base
from twisted.internet.epollreactor import EPollReactor, _ContinuousPolling
from twisted.internet import threads
import udt4
from udt4 import pyudt, accept, sendmsg, recvmsg, UDT_RCVDATE, UDTException
from udt4.pyudt import UdtSocket
from udt4twisted import udt
from udt4 import EASYNCRCV, ECONNLOST
import socket as s
import gc

class IReactorUDT(Interface):
    """
    UDT transport interface.
    """
    def listenUDT(port,
                  protocol,
                  interface='',
                  maxPacketSize=8192,
                  backlog=50):
        """
        Connects a given DatagramProtocol to the given numeric UDT port.

        @return: object which provides L{IListeningPort}.
        """

    def connectUDT(host,
                   port,
                   factory,
                   timeout,
                   bindAddress):
        """
        Connects a given ClientFactory to a remote host.

        @return: object which provides L{IListeningPort}.
        """

@implementer(IReactorFDSet)
class _UDTContinuousPolling(_ContinuousPolling):
    _POLL_DISCONNECTED = (udt4.ECONNLOST | udt4.UDT_EPOLL_ERR)
    _POLL_IN = udt4.UDT_EPOLL_IN
    _POLL_OUT = udt4.UDT_EPOLL_OUT


@implementer(IReactorFDSet, IReactorUDT)
class UDTEPollReactor(EPollReactor):
    _POLL_DISCONNECTED = (udt4.ECONNLOST | udt4.UDT_EPOLL_ERR)
    _POLL_IN = udt4.UDT_EPOLL_IN
    _POLL_OUT = udt4.UDT_EPOLL_OUT

    def __init__(self):
        """
        Initialize epoll object, udt library
        and adds event trigger to clean the latter after shutdown.
        """
        udt4.startup()
        self._poller = udt4.UDTepoll()
        self._reads = {}
        self._writes = {}
        self._selectables = {}
        self._udtsockets = {}
        self._continuousPolling = _UDTContinuousPolling(self)
        posixbase.PosixReactorBase.__init__(self)
        self.addSystemEventTrigger("after", "shutdown", udt4.cleanup)

    def _isUDT(self, xer):
        """
        Private method that, based on selectable instance, decides
        if something is an udt socket
        """
        if isinstance(xer, udt.Port) or isinstance(xer, udt.Connection):
            return True
        else:
            return False

    def _add(self, xer, primary, other, selectables, event, antievent):
        """
        Private method for adding a descriptor from the event loop.

        It takes care of adding it if  new or modifying it if already added
        for another state (read -> read/write for example).
        """
        if isinstance(xer, udt.Port):
            fd = xer.socket.UDTSOCKET.UDTSOCKET
        else:
            fd = xer.fileno()
        if fd not in primary:
            flags = event
            # epoll_ctl can raise all kinds of IOErrors, and every one
            # indicates a bug either in the reactor or application-code.
            # Let them all through so someone sees a traceback and fixes
            # something.  We'll do the same thing for every other call to
            # this method in this file.
            if fd in other:
                flags |= antievent
                #FIXME for now remove and add again
                if self._isUDT(xer):
                    self._poller.remove_usock(fd)
                    self._poller.add_usock(fd, flags)
                else:
                    self._poller.remove_ssock(fd)
                    self._poller.add_ssock(fd, flags)
                #self._poller.modify(fd, flags)
                log.msg("MODIFY:{0} with flags:{1}".format(fd, flags))
            else:
                if self._isUDT(xer):
                    self._poller.add_usock(fd, flags)
                else:
                    self._poller.add_ssock(fd, flags)
                log.msg("ADDING:{0} with flags:{1}".format(fd, flags))

            # Update our own tracking state *only* after the epoll call has
            # succeeded.  Otherwise we may get out of sync.
            selectables[fd] = xer
            primary[fd] = 1

    def addReader(self, reader):
        """
        Add a FileDescriptor for notification of data available to read.
        """
        try:
            self._add(reader, self._reads, self._writes, self._selectables,
                      self._POLL_IN, self._POLL_OUT)
        except IOError as e:
            if e.errno == errno.EPERM:
                # epoll(7) doesn't support certain file descriptors,
                # e.g. filesystem files, so for those we just poll
                # continuously:
                self._continuousPolling.addReader(reader)
            else:
                raise


    def addWriter(self, writer):
        """
        Add a FileDescriptor for notification of data available to write.
        """
        try:
            self._add(writer, self._writes, self._reads, self._selectables,
                      self._POLL_OUT, self._POLL_IN)
        except IOError as e:
            if e.errno == errno.EPERM:
                # epoll(7) doesn't support certain file descriptors,
                # e.g. filesystem files, so for those we just poll
                # continuously:
                self._continuousPolling.addWriter(writer)
            else:
                raise

    def removeReader(self, reader):
        """
        Remove a Selectable for notification of data available to read.
        """
        if self._continuousPolling.isReading(reader):
            self._continuousPolling.removeReader(reader)
            return
        self._remove(reader, self._reads, self._writes, self._selectables,
                     self._POLL_IN, self._POLL_OUT)


    def removeWriter(self, writer):
        """
        Remove a Selectable for notification of data available to write.
        """
        if self._continuousPolling.isWriting(writer):
            self._continuousPolling.removeWriter(writer)
            return
        self._remove(writer, self._writes, self._reads, self._selectables,
                      self._POLL_OUT, self._POLL_IN)

    def _remove(self, xer, primary, other, selectables, event, antievent):
        """
        Private method for removing a descriptor from the event loop.

        It does the inverse job of _add, and also add a check in case of the fd
        has gone away.
        """
        if isinstance(xer, udt.Port):
            fd = xer.socket.UDTSOCKET.UDTSOCKET
        else:
            fd = xer.fileno()
        if fd == -1:
            for fd, fdes in selectables.items():
                if xer is fdes:
                    break
            else:
                return
        if fd in primary:
            if fd in other:
                #FIXME for now remove and add again
                flags = antievent
                # See comment above modify call in _add.
                if self._isUDT(xer):
                    self._poller.remove_usock(fd)
                    self._poller.add_usock(fd, flags)
                else:
                    self._poller.remove_ssock(fd)
                    self._poller.add_ssock(fd, flags)
                #self._poller.modify(fd, flags)
                log.msg("MODIFY:{0} with flags:{1}".format(fd, flags))
            else:
                flags = event
                if self._isUDT(xer):
                    del selectables[fd]
                else:
                    del selectables[fd]
                # See comment above _control call in _add.
                if self._isUDT(xer):
                    self._poller.remove_usock(fd, flags)
                else:
                    #FIXME Apparently flags are not parsed in this method
                    self._poller.remove_ssock(fd)
                log.msg("REMOVING:{0} with flags:{1}".format(fd, flags))
            del primary[fd]

    def _handleSystemSocketSet(self, set, event):
        _drdw = self._doReadOrWrite
        for fd in set:
            try:
                selectable = self._selectables[fd]
            except KeyError:
                pass
            else:
                log.callWithLogger(selectable, _drdw, selectable, fd,
                                   event)
    def _handleUDTReadSocketSet(self, set, event):
        _drdw = self._doReadOrWrite
        for fd in set:
            try:
                selectable = self._selectables[fd.UDTSOCKET]
                # socket, addr = accept(fd)
                # log.msg("ACCEPT FD:{0}SELECT:{1}".format(fd, selectable))
                # selectable.addresses[socket.UDTSOCKET] = (socket, addr)
                # self._udtsockets[socket.UDTSOCKET] = selectable
                # socket = UdtSocket(_sock=socket)
                # socket.setblocking(False)
                # self._poller.add_usock(socket.UDTSOCKET,
                #                        self._POLL_IN | self._POLL_DISCONNECTED)
            except KeyError:
                pass
            #     if self._udtsockets.has_key(fd.UDTSOCKET):
            #         selectable = self._udtsockets[fd.UDTSOCKET]
            #         log.callWithLogger(selectable,
            #                            _drdw,
            #                            selectable,
            #                            fd,
            #                            event)
            # except UDTException as ue:
            #     if ue[0] == 5006:
            #         log.callWithLogger(selectable,
            #                            _drdw,
            #                            selectable,
            #                            fd,
            #                            event)
            else:
                log.callWithLogger(selectable, _drdw, selectable, fd,
                                   event)

    def _handleUDTWriteSocketSet(self, set, event):
        """
        Has no job for now.
        """
        pass

    tests = True
    sock = None

    def doPoll(self, timeout):
        """
        Poll the poller for new events.
        """

        if timeout is None:
            timeout = -1  # Wait indefinitely.

        try:
            #doesn't work with floats :/
            l = self._poller.wait(True, True, int(timeout*1000), True, True)
        except IOError as err:
            if err.errno == errno.EINTR:
                return
            raise
        #handle system sockets
        sread, swrite = l[2:]
        self._handleSystemSocketSet(sread, self._POLL_IN)
        self._handleSystemSocketSet(swrite, self._POLL_OUT)

        #handle UDT sockets
        uread, uwrite = l[:2]
        #print uread, uwrite, timeout
        self._handleUDTReadSocketSet(uread, self._POLL_IN)
        self._handleUDTWriteSocketSet(uwrite, self._POLL_OUT)

    def _doReadOrWrite(self, selectable, fd, event):
        """
        fd is available for read or write, do the work and raise errors if
        necessary.
        """
        why = None
        inRead = False
        if event & self._POLL_DISCONNECTED and not (event & self._POLL_IN):
            if fd in self._reads:
                inRead = True
                why = CONNECTION_DONE
            else:
                why = CONNECTION_LOST
        else:
            try:
                if selectable.fileno() == -1:
                    why = _NO_FILEDESC
                else:
                    if event & self._POLL_IN:
                        # Handle a read event.
                        if isinstance(fd, udt4.UDTSOCKET):
                            why = selectable.doRead()
                        else:
                            why = selectable.doRead()
                        inRead = True
                    if not why and event & self._POLL_OUT:
                        # Handle a write event, as long as doRead didn't
                        # disconnect us.
                        why = selectable.doWrite()
                        inRead = False
            except:
                # Any exception from application code gets logged and will
                # cause us to disconnect the selectable.
                why = sys.exc_info()[1]
                log.err()
        if why:
            if isinstance(fd, udt4.UDTSOCKET):
                self._poller.remove_usock(fd, self._POLL_IN)
                if why[0] == EASYNCRCV:
                    #Reset monitoring if no data is available
                    self._poller.add_usock(fd, self._POLL_IN)
                if why[0] == ECONNLOST:
                    del self._udtsockets[fd]
                gc.collect()
                return
            self._disconnectSelectable(selectable, why, inRead)



    def listenUDT(self,
                  port,
                  protocol,
                  interface='',
                  maxPacketSize=8192,
                  backlog=50):

        p = udt.Port(port, protocol, interface,
                     maxPacketSize, self, backlog)
        p.startListening()
        return p

    def tlistenUDT(self,
                   port,
                   factory,
                   interface='',
                   maxPacketSize=8192,
                   backlog=50):
        p = udt.Port(port, factory, interface,
                      maxPacketSize, self, backlog)
        p.startListening()
        return p

    def connectUDT(self,
                   host,
                   port,
                   protocol,
                   bindAddress = (0, "127.0.0.1"),
                   maxPacketSize=8192):

        c = udt.Connector(bindAddress[0], protocol, bindAddress[1],
                     maxPacketSize, self, 0)
        c.connect(host, port)
        return c



    doIteration = doPoll



def install():
    """
    Install the epoll() reactor.
    """
    p = UDTEPollReactor()
    from twisted.internet.main import installReactor
    installReactor(p)


__all__ = ["UDTEPollReactor", "install"]