# Copyright (c) 2001-2006 Twisted Matrix Laboratories.
# See LICENSE for details.

"""
An epoll() based implementation of the twisted main loop.

To install the event loop (and you should do this before any connections,
listeners or connectors are added)::

    from twisted.internet import epollreactor
    epollreactor.install()

API Stability: stable

Maintainer: U{Jp Calderone <mailto:exarkun@twistedmatrix.com>}
"""

# System imports
import sys, errno

# Twisted imports
from twisted.python import _epoll
from twisted.python import log
from twisted.internet import main, posixbase, error

# globals. They're often passed as default arguments for performance purpose.
reads = {}
writes = {}
selectables = {}

# Create the poller we're going to use (we should really do this in __init__
# of the reactor - but hey, poorly thought out globals like this are
# practically a design pattern in Twisted reactors.  The 1024 here is just a
# hint to the kernel, it is not a hard maximum.
poller = _epoll.epoll(1024)

class EPollReactor(posixbase.PosixReactorBase):
    """
    A reactor that uses epoll(4).
    """

    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).
        """
        fd = xer.fileno()
        if fd not in primary:
            cmd = _epoll.CTL_ADD
            flags = event
            if fd in other:
                flags |= antievent
                cmd = _epoll.CTL_MOD
            primary[fd] = 1
            selectables[fd] = xer
            # 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.
            poller._control(cmd, fd, flags)

    def addReader(self, reader, reads=reads, writes=writes,
                  selectables=selectables):
        """
        Add a FileDescriptor for notification of data available to read.
        """
        self._add(reader, reads, writes, selectables, _epoll.IN, _epoll.OUT)

    def addWriter(self, writer, writes=writes, reads=reads,
                  selectables=selectables):
        """
        Add a FileDescriptor for notification of data available to write.
        """
        self._add(writer, writes, reads, selectables, _epoll.OUT, _epoll.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.
        """
        fd = xer.fileno()
        if fd == -1:
            for fd, fdes in selectables.items():
                if xer is fdes:
                    break
            else:
                return
        if fd in primary:
            cmd = _epoll.CTL_DEL
            flags = event
            if fd in other:
                flags = antievent
                cmd = _epoll.CTL_MOD
            else:
                del selectables[fd]
            del primary[fd]
            # See comment above _control call in _add.
            poller._control(cmd, fd, flags)

    def removeReader(self, reader, reads=reads, writes=writes,
                     selectables=selectables):
        """
        Remove a Selectable for notification of data available to read.
        """
        self._remove(reader, reads, writes, selectables, _epoll.IN, _epoll.OUT)

    def removeWriter(self, writer, writes=writes, reads=reads,
                     selectables=selectables):
        """
        Remove a Selectable for notification of data available to write.
        """
        self._remove(writer, writes, reads, selectables, _epoll.OUT, _epoll.IN)

    def removeAll(self, reads=reads, writes=writes, selectables=selectables):
        """
        Remove all selectables, and return a list of them.
        """
        if self.waker is not None:
            fd = self.waker.fileno()
            if fd in reads:
                del reads[fd]
                del selectables[fd]
        result = selectables.values()
        fds = selectables.keys()
        reads.clear()
        writes.clear()
        selectables.clear()
        for fd in fds:
            try:
                # Actually, we'll ignore all errors from this, since it's
                # just last-chance cleanup.
                poller._control(_epoll.CTL_DEL, fd, 0)
            except IOError:
                pass
        if self.waker is not None:
            fd = self.waker.fileno()
            reads[fd] = 1
            selectables[fd] = self.waker
        return result

    def doPoll(self, timeout,
               reads=reads,
               writes=writes,
               selectables=selectables,
               wait=poller.wait,
               log=log):
        """
        Poll the poller for new events.
        """
        if timeout is None:
            timeout = 1
        timeout = int(timeout * 1000) # convert seconds to milliseconds

        try:
            # Limit the number of events to the number of io objects we're
            # currently tracking (because that's maybe a good heuristic) and
            # the amount of time we block to the value specified by our
            # caller.
            l = wait(len(selectables), timeout)
        except IOError, err:
            if err.errno == errno.EINTR:
                return
            # See epoll_wait(2) for documentation on the other conditions
            # under which this can fail.  They can only be due to a serious
            # programming error on our part, so let's just announce them
            # loudly.
            raise

        _drdw = self._doReadOrWrite
        for fd, event in l:
            try:
                selectable = selectables[fd]
            except KeyError:
                pass
            else:
                log.callWithLogger(selectable, _drdw, selectable, fd, event)

    doIteration = doPoll

    def _doReadOrWrite(self, selectable, fd, event):
        """
        fd is available for read or write, make the work and raise errors
        if necessary.
        """
        why = None
        inRead = False
        if event in (_epoll.HUP, _epoll.ERR):
            why = main.CONNECTION_LOST
        else:
            try:
                if event & _epoll.IN:
                    why = selectable.doRead()
                    inRead = True
                if not why and event & _epoll.OUT:
                    why = selectable.doWrite()
                    inRead = False
                if selectable.fileno() != fd:
                    why = error.ConnectionFdescWentAway(
                          'Filedescriptor went away')
                    inRead = False
            except:
                log.err()
                why = sys.exc_info()[1]
        if why:
            self._disconnectSelectable(selectable, why, inRead)

def install():
    """
    Install the epoll() reactor.
    """
    p = EPollReactor()
    main.installReactor(p)


__all__ = ["EPollReactor", "install"]

