Python select.EPOLLERR Examples

The following are 20 code examples of select.EPOLLERR(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module select , or try the search function .
Example #1
Source File: conn.py    From CUP with Apache License 2.0 6 votes vote down vote up
def _handle_new_conn(self, newsock, peer):
        self._set_sock_params(newsock)
        self._set_sock_nonblocking(newsock)
        context = sockcontext.CConnContext()
        context.set_sock(newsock)
        context.set_conn_man(self)
        context.set_peerinfo(peer)
        self._epoll.register(
            newsock.fileno(), select.EPOLLIN | select.EPOLLET | select.EPOLLERR
        )
        self._rwlock.acquire_writelock()
        self._fileno2context[newsock.fileno()] = context
        self._peer2context[peer] = context
        self._context2fileno_peer[context] = (newsock.fileno(), peer)
        self._rwlock.release_writelock()
        log.info('a new connection: {0}'.format(peer)) 
Example #2
Source File: conn.py    From CUP with Apache License 2.0 6 votes vote down vote up
def bind(self):
        """
        bind the ip:port
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._set_sock_params(sock)
        sock.bind((self._bind_ip, self._bind_port))
        self._set_sock_nonblocking(sock)
        log.info(
            'bind port info:(ip:%s, port:%s)' % (
                self._bind_ip, self._bind_port
            )
        )
        self._epoll.register(
            sock.fileno(),
            select.EPOLLIN | select.EPOLLET | select.EPOLLOUT | select.EPOLLERR
        )
        self._bind_sock = sock 
Example #3
Source File: ioloop.py    From greendns with MIT License 6 votes vote down vote up
def register(self, sock, events, callback, *args, **kwargs):
        ev = select.EPOLLERR | select.EPOLLHUP
        need_modify = False
        if sock.fileno() in self.fd2socks:
            need_modify = True
        if events & EV_READ:
            ev |= select.EPOLLIN
        if events & EV_WRITE:
            ev |= select.EPOLLOUT
        if need_modify:
            self.epoll.modify(sock.fileno(), ev)
        else:
            try:
                self.epoll.register(sock.fileno(), ev)
            except (IOError, OSError):
                return False
            else:
                self.fd2socks[sock.fileno()] = sock
        return super(Epoll, self).register(sock, events, callback, *args, **kwargs) 
Example #4
Source File: link.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def handle_fd_mask(self, fd, mask):
        if fd == self._poll_bell.r:
            assert mask & select.EPOLLIN
            self._poll_bell.read(BELL_READ)  # flush the pipe
        else:
            # socket might have been already discarded by the Link
            # so this pass might be skipped
            if fd not in self._sock_by_fd:
                return
            sock = self._sock_by_fd[fd]

            if mask & (select.EPOLLERR | select.EPOLLHUP):
                self.handle_sock_err(sock)
            else:
                if sock in self._in_ssl_handshake:
                    if self.ssl_handshake(sock) == SSL_HANDSHAKE_DONE:
                        # connection is ready for user IO
                        self.on_connect(sock.conn_id)
                else:
                    self.handle_sock_io(fd, sock, mask)

    ########################################################## 
Example #5
Source File: poll.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def poll(self, timeout):
        """
        @param timeout: seconds
        """
        if len(self.fds) == 0:
            time.sleep(timeout)
            return []

        rlist = []
        wlist = []
        xlist = []
        for fd, mask in self.fds.items():
            fd = self._socket_to_fd(fd)
            if mask & select.EPOLLIN:
                rlist.append(fd)
            if mask & select.EPOLLOUT:
                wlist.append(fd)
            xlist.append(fd)

        rlist, wlist, xlist = select.select(rlist, wlist, xlist, timeout)

        res = {}
        for fd in rlist:
            res[fd] = res.get(fd, 0) | select.EPOLLIN
        for fd in wlist:
            res[fd] = res.get(fd, 0) | select.EPOLLOUT
        for fd in xlist:
            res[fd] = res.get(fd, 0) | select.EPOLLERR

        return res.items()

######################################################################### 
Example #6
Source File: websocket.py    From Thespian with MIT License 5 votes vote down vote up
def receiveMsg_Start_Websocket(self, m, sender):
        if self.started: # already started
            return
        self.config = m
        self.started = True
        self.running = True

        # open the connection
        websocket.enableTrace(False)
        self.ws = websocket.create_connection(m.ws_addr)
        log.info("Websocket Connected")

        # set up the socket monitoring
        self.epoll = select.epoll()
        mask = select.EPOLLIN | select.EPOLLHUP | select.EPOLLERR
        self.epoll.register(self.ws.sock.fileno(), mask)

        # subscribe to the feed
        self.ws.send(m.start_msg)

        # start checking for data
        self.send(self.myAddress, WakeupMessage(None)) 
Example #7
Source File: conn.py    From CUP with Apache License 2.0 5 votes vote down vote up
def _epoll_read_params(cls):
        return (select.EPOLLET | select.EPOLLIN | select.EPOLLERR) 
Example #8
Source File: conn.py    From CUP with Apache License 2.0 5 votes vote down vote up
def _epoll_write_params(cls):
        return (select.EPOLLET | select.EPOLLOUT | select.EPOLLERR) 
Example #9
Source File: ioloop.py    From greendns with MIT License 5 votes vote down vote up
def run(self):
        while self.running:
            self.check_timer()
            events = self.epoll.poll(self.MIN_INTERVAL)
            for fd, event in events:
                sock = self.fd2socks.get(fd)
                if not sock:
                    continue
                if event & select.EPOLLERR or event & select.EPOLLHUP:
                    if self.err_callback:
                        self.err_callback[0](sock, *self.err_callback[1],
                                             **self.err_callback[2])
                if event & select.EPOLLIN:
                    result = self.rd_socks.get(sock)
                    if not result:
                        continue
                    callback, args, kwargs = result
                    if callback:
                        callback(sock, *args, **kwargs)
                if event & select.EPOLLOUT:
                    result = self.wr_socks.get(sock)
                    if not result:
                        continue
                    callback, args, kwargs = result
                    if callback:
                        callback(sock, *args, **kwargs) 
Example #10
Source File: ioloop.py    From greendns with MIT License 5 votes vote down vote up
def unregister(self, sock, events=EV_READ | EV_WRITE):
        if not super(Epoll, self).unregister(sock, events):
            return False
        ev = select.EPOLLERR | select.EPOLLHUP | \
            select.EPOLLIN | select.EPOLLOUT
        if events & EV_READ:
            ev ^= select.EPOLLIN
        if events & EV_WRITE:
            ev ^= select.EPOLLOUT
        self.epoll.modify(sock.fileno(), ev)
        return True 
Example #11
Source File: baseServer.py    From DDDProxy with Apache License 2.0 5 votes vote down vote up
def start(self):
		while True:
			eventList = self.epollor.poll(1, 1000)
			for fd, event in eventList:
				if select.EPOLLIN & event:
					self.onSocketEvent(fd, sockConnect.socketEventCanRecv)
				elif select.EPOLLOUT & event:
					self.onSocketEvent(fd, sockConnect.socketEventCanSend)
				elif select.EPOLLERR & event or select.EPOLLHUP & event:
					self.onSocketEvent(fd, sockConnect.socketEventExcept)
				else:
					log.log(3, "unknow event", event) 

			self._handlerCallback() 
Example #12
Source File: baseServer.py    From DDDProxy with Apache License 2.0 5 votes vote down vote up
def onIOEventFlagsChanged(self, connect):
		if connect._ioEventFlags != sockConnect.socketIOEventFlagsNone:
			eventmask = select.EPOLLERR | select.EPOLLHUP
			if connect._ioEventFlags & sockConnect.socketIOEventFlagsRead:
				eventmask |= select.EPOLLIN
			if connect._ioEventFlags & sockConnect.socketIOEventFlagsWrite:
				eventmask |= select.EPOLLOUT
			if not connect.registerEpoll:
				self.epollor.register(connect._sock.fileno(), eventmask)
				connect.registerEpoll = True
			else:
				self.epollor.modify(connect._sock.fileno(), eventmask)
		else:
			self.epollor.unregister(connect._sock.fileno())
			connect.registerEpoll = False 
Example #13
Source File: _system_commands.py    From colabtools with Apache License 2.0 5 votes vote down vote up
def _run_command(cmd, clear_streamed_output):
  """Calls the shell command, forwarding input received on the stdin_socket."""
  locale_encoding = locale.getpreferredencoding()
  if locale_encoding != _ENCODING:
    raise NotImplementedError(
        'A UTF-8 locale is required. Got {}'.format(locale_encoding))

  parent_pty, child_pty = pty.openpty()
  _configure_term_settings(child_pty)

  epoll = select.epoll()
  epoll.register(
      parent_pty,
      (select.EPOLLIN | select.EPOLLOUT | select.EPOLLHUP | select.EPOLLERR))

  try:
    temporary_clearer = _tags.temporary if clear_streamed_output else _no_op

    with temporary_clearer(), _display_stdin_widget(
        delay_millis=500) as update_stdin_widget:
      # TODO(b/115531839): Ensure that subprocesses are terminated upon
      # interrupt.
      p = subprocess.Popen(
          cmd,
          shell=True,
          executable='/bin/bash',
          stdout=child_pty,
          stdin=child_pty,
          stderr=child_pty,
          close_fds=True)
      # The child PTY is only needed by the spawned process.
      os.close(child_pty)

      return _monitor_process(parent_pty, epoll, p, cmd, update_stdin_widget)
  finally:
    epoll.close()
    os.close(parent_pty) 
Example #14
Source File: poll.py    From vanilla with MIT License 5 votes vote down vote up
def poll(self, timeout=-1):
            events = self.q.poll(timeout=timeout)
            ret = []
            for fd, event in events:
                for mask in self.to_:
                    if event & mask:
                        ret.append((fd, self.to_[mask]))
                if event & (select.EPOLLERR | select.EPOLLHUP):
                    ret.append((fd, POLLERR))
            return ret 
Example #15
Source File: poll.py    From vanilla with MIT License 5 votes vote down vote up
def register(self, fd, *masks):
            masks = [self.from_[x] for x in masks] + [
                select.EPOLLET, select.EPOLLERR, select.EPOLLHUP]
            self.q.register(fd, reduce(operator.or_, masks, 0)) 
Example #16
Source File: recipe-577662.py    From code with MIT License 5 votes vote down vote up
def doPoll(self, block):
    readyList = self.__poller.poll(-1 if block else 0)
    for (fd, eventMask) in readyList:
      readReady = ((eventMask & select.EPOLLIN) != 0)
      writeReady = ((eventMask & select.EPOLLOUT) != 0)
      errorReady = ((eventMask & 
                     (select.EPOLLERR | select.EPOLLHUP)) != 0)
      self.handleEventForFD(fd = fd,
                            readReady = readReady,
                            writeReady = writeReady,
                            errorReady = errorReady) 
Example #17
Source File: recipe-576759.py    From code with MIT License 5 votes vote down vote up
def __init__(self, pipe):
		if isinstance(pipe, int):
			fd = self._fd = pipe
			pipe = os.fromfd(pipe)
		else: fd = self._fd = pipe.fileno()
		self._poll_in, self._poll_out = epoll(), epoll()
		self._poll_in.register(fd, EPOLLIN | EPOLLERR | EPOLLHUP)
		self._poll_out.register(fd, EPOLLOUT | EPOLLERR | EPOLLHUP)
		self.close = pipe.close
		self.reads = pipe.read
		self.writes = pipe.write 
Example #18
Source File: polling.py    From vlcp with Apache License 2.0 4 votes vote down vote up
def pollEvents(self, wait):
            ret = []
            epwrite = select.EPOLLOUT|select.EPOLLWRNORM|select.EPOLLWRBAND
            epread = select.EPOLLIN|select.EPOLLRDNORM|select.EPOLLRDBAND|select.EPOLLPRI
            eperr = select.EPOLLERR
            ephup = select.EPOLLHUP
            if self.socketCounter <= 0 and wait is None:
                return ([], True)
            generateFree = False
            if wait is None or (self.maxwait is not None and wait > self.maxwait):
                generateFree = True
                wait = self.maxwait
            events = []
            try:
                interrupted = False
                self.shouldraise = True
                if wait is None:
                    events = self.epoll.poll()
                else:
                    events = self.epoll.poll(wait)
                self.shouldraise = False
            except InterruptedBySignalException:
                interrupted = True
            except IOError as exc:
                if exc.args[0] == errno.EINTR:
                    interrupted = True
                else:
                    raise
            finally:
                self.shouldraise = False                
            for fd, e in events:
                if e & epwrite:
                    ret.append(PollEvent(fd, PollEvent.WRITE_READY, e & epwrite))
                if e & epread:
                    ret.append(PollEvent(fd, PollEvent.READ_READY, e & epread))
                if e & eperr:
                    ret.append(PollEvent(fd, PollEvent.ERROR, e & eperr))
                if e & ephup:
                    ret.append(PollEvent(fd, PollEvent.HANGUP, e & ephup))
            if not ret and generateFree and not interrupted:
                ret.append(SystemControlLowPriorityEvent(SystemControlLowPriorityEvent.FREE))
            return (ret, False) 
Example #19
Source File: conn.py    From CUP with Apache License 2.0 4 votes vote down vote up
def poll(self):
        """
        start to poll
        """
        self._thdpool.start()
        self._executor.run()
        log.info('thdpool and executor start')
        misc.check_not_none(self._bind_sock)
        self._bind_sock.listen(10)
        self._executor.delay_exec(
            2,   # todo set the check_time to ?
            self.do_check_msg_ack_loop,
            urgency=executor.URGENCY_HIGH
        )
        while not self._stopsign:
            try:
                events = self._epoll.poll(1)
            except IOError as err:
                if err.errno == errno.EINTR:
                    return
                raise err
            # log.debug('start to poll')
            for fileno, event in events:
                # if it comes from the listen port, new conn
                if fileno == self._bind_sock.fileno():
                    newsock, addr = self._bind_sock.accept()
                    self._handle_new_conn(newsock, addr)
                elif event & select.EPOLLIN:
                    try:
                        self._handle_new_recv(self._fileno2context[fileno])
                    except KeyError:
                        log.info('socket already closed')
                elif event & select.EPOLLOUT:
                    try:
                        self._handle_new_send(self._fileno2context[fileno])
                    except KeyError:
                        log.info('socket already closed')
                elif (event & select.EPOLLHUP) or (event & select.EPOLLERR):
                    # FIXME: consider if we need to release net msg resources
                    if event & select.EPOLLHUP:
                        log.info('--EPOLLHUP--')
                    else:
                        log.info('--EPOLLERR--')
                    try:
                        self.cleanup_error_context(
                            self._fileno2context[fileno]
                        )
                    except KeyError:
                        log.info('socket already closed') 
Example #20
Source File: asyncio.py    From pycopia with Apache License 2.0 4 votes vote down vote up
def poll(self, timeout=-1.0):
        while 1:
            try:
                rl = self.pollster.poll(timeout)
            except IOError as why:
                if why.errno == EINTR:
                    self._run_idle()
                    continue
                else:
                    raise
            else:
                break
        for fd, flags in rl:
            try:
                hobj = self.smap[fd]
            except KeyError: # this should never happen, but let's be safe.
                continue
            if hobj is None: # signals simple callback
                self._fd_callbacks[fd]()
                continue
            try:
                if (flags & EPOLLERR):
                    hobj.error_handler()
                    continue
                if (flags & POLLNVAL):
                    self.unregister_fd(fd)
                    continue
                if (flags & EPOLLPRI):
                    hobj.pri_handler()
                if (flags & EPOLLIN):
                    hobj.read_handler()
                if (flags & EPOLLOUT):
                    hobj.write_handler()
                if (flags & EPOLLHUP):
                    hobj.hangup_handler()
            except UnregisterNow as unr:
                self.unregister(unr.obj)
            except UnregisterFDNow as unr:
                self.unregister_fd(unr.filedescriptor)
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                ex, val, tb = sys.exc_info()
                hobj.exception_handler(ex, val, tb)