Beispiel #1
0
class TCPServer:

    def __init__(self):
        self.ioloop = IOLoop()
        self.port = None

        self.server_sock = socket.socket()
        self.server_sock.setsockopt(socket.SOL_SOCKET,
                                    socket.SO_REUSEADDR, 1)

    def bind(self, port):
        self.port = port
        self.server_sock.bind(('', port))

    def listen(self, backlog=10):
        self.server_sock.listen(backlog)

    def start(self):
        self.ioloop.add_handler(self.server_sock,
                                selectors.EVENT_READ,
                                self.accept)
        print('Server running on port', self.port)
        self.ioloop.start()

    def accept(self):
        client, addr = self.server_sock.accept()
        stream = Stream(client)
        print(stream, 'incoming connection')
        handle_client(stream)
Beispiel #2
0
    def establish(self, term="xterm"):
        self._shell = self.ssh.invoke_shell(term)
        self._shell.setblocking(0)

        self._id = self._shell.fileno()
        IOLoop.instance().register(self)
        IOLoop.instance().add_future(self.trans_back())
Beispiel #3
0
def main():
    init_config()
    options.parse_config_file("/var/www/app/webssh.conf")

    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    IOLoop.instance().start()
    tornado.ioloop.IOLoop.instance().start()
Beispiel #4
0
    def establish(self, term="xterm"):
        self.shell = self.ssh.invoke_shell(term)
        self.shell.setblocking(0)

        fileno = self.shell.fileno()
        connection = self.shell
        websocket = self.websocket
        IOLoop.instance().register(fileno, connection, websocket)
Beispiel #5
0
 def _loop(self,handler): #"""Serve handler's IO loop in a separate thread or process."""
     ioloop=IOLoop()
     try:
         handler.ioloop=ioloop
         try: handler.add_channel()
         except EnvironmentError:
         	err=sys.exc_info()[1]
         	if err.errno==errno.EBADF: return # we might get here in case the other end quickly disconnected (see test_quick_connect())
         	else: raise
         # Here we localize variable access to minimize overhead.
         poll=ioloop.poll; sched_poll=ioloop.sched.poll; poll_timeout=getattr(self,'poll_timeout',None); soonest_timeout=poll_timeout
         while (ioloop.socket_map or ioloop.sched._tasks) and not self._exit.is_set():
             if (self.IsServerOn()==False): 
             	#try: ioloop.close()
             	#except: print "ioloop.close() in servers.py ioloop while statement failed."; pass
             	#try: handler.del_channel()
             	#except: pass
             	#try: self.close_all()
             	#except: pass
             	#sys.exit()
             	try: self.socket.close(); 
             	except: pass
             	self._exit.set()
             	return
             try:
             	if ioloop.socket_map: poll(timeout=soonest_timeout)
             	if ioloop.sched._tasks:
             		soonest_timeout=sched_poll()
             		# Handle the case where socket_map is emty but some cancelled scheduled calls are still around causing
             		# this while loop to hog CPU resources. In theory this should never happen as all the sched
             		# functions are supposed to be cancel()ed on close() but by using threads we can incur into
             		# synchronization issues such as this one.  https://code.google.com/p/pyftpdlib/issues/detail?id=245
             		if not ioloop.socket_map:
             			ioloop.sched.reheapify() # get rid of cancel()led calls
             			soonest_timeout=sched_poll()
             			if soonest_timeout: time.sleep(min(soonest_timeout,1))
             	else: soonest_timeout=None
             except (KeyboardInterrupt,SystemExit): self._exit.set(); sys.exit();   # note: these two exceptions are raised in all sub processes
             except select.error: 
             	err=sys.exc_info()[1] # on Windows we can get WSAENOTSOCK if the client rapidly connect and disconnects
             	if os.name=='nt' and err.args[0]==10038:
             		for fd in list(ioloop.socket_map.keys()):
             			try: select.select([fd],[],[],0)
             			except select.error:
             				try: logger.info("discarding broken socket %r",ioloop.socket_map[fd]); del ioloop.socket_map[fd]
             				except KeyError: pass # dict changed during iteration
             	else: raise
             else:
             	if poll_timeout:
             		if soonest_timeout is None or soonest_timeout > poll_timeout: soonest_timeout=poll_timeout
     finally: ioloop.close()
Beispiel #6
0
def sleep(duration):
    """Return a `.Future` that resolves after the given number of seconds.

    When used with ``yield`` in a coroutine, this is a non-blocking
    analogue to `time.sleep` (which should not be used in coroutines
    because it is blocking)::

        yield gen.sleep(0.5)

    Note that calling this function on its own does nothing; you must
    wait on the `.Future` it returns (usually by yielding it).
    """
    f = Future()
    IOLoop.current().call_later(duration, lambda: f.set_result(None))
    return f
Beispiel #7
0
    def add_sockets(self, sockets):
        if self._io_loop is None:
            self._io_loop = IOLoop.current()

        for sock in sockets:
            self._sockets[sock.fileno()] = sock
            add_accept_handler(sock, self._handle_connection, io_loop=self._io_loop)
Beispiel #8
0
    def __init__(self):
        self.ioloop = IOLoop()
        self.port = None

        self.server_sock = socket.socket()
        self.server_sock.setsockopt(socket.SOL_SOCKET,
                                    socket.SO_REUSEADDR, 1)
Beispiel #9
0
 def __init__(self, gen, result_future):
     self.gen = gen
     # future returned by the async function
     self.result_future = result_future
     self.ioloop = IOLoop()
     self.next = None
     # And now we start to drive the generator
     self.run()
Beispiel #10
0
def add_accept_handler(sock, call_back, io_loop=None):
    if io_loop is None:
        io_loop = IOLoop.instance()

    def accept_handler(fd, events):
        while True:
            try:
                connection, address = sock.accept()
            except Exception as e:
                break
            call_back(connection, address)

    io_loop.add_handler(sock.fileno(), accept_handler, ioloop._EPOLLIN)
Beispiel #11
0
def with_timeout(abstimeout, future, io_loop=None, quiet_exceptions=()):
    """Wraps a `.Future` in a timeout.

    Raises `TimeoutError` if the input future does not complete before
    ``timeout``, which may be specified in any form allowed by
    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
    relative to `.IOLoop.time`)

    If the wrapped `.Future` fails after it has timed out, the exception
    will be logged unless it is of a type contained in ``quiet_exceptions``
    (which may be an exception type or a sequence of types).

    Currently only supports Futures, not other `YieldPoint` classes.
    """
    result = Future()
    chain_future(future, result)
    if io_loop is None:
        io_loop = IOLoop.current()

    def error_callback(future):
        try:
            future.result()
        except Exception as e:
            if not isinstance(e, quiet_exceptions):
                logging.error("Exception in Future %r after timeout",
                              future,
                              exc_info=True)

    def timeout_callback():
        result.set_exception(TimeoutError("Timeout"))
        # In case the wrapped future goes on to fail, log it.
        future.add_done_callback(error_callback)

    timeout_handle = io_loop.call_at(abstimeout, timeout_callback)
    if isinstance(future, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future
        future.add_done_callback(
            lambda future: io_loop.remove_timeout(timeout_handle))
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.

        def cancel_on_ioloop(fut):
            IOLoop.current().call_next_tick(
                lambda fut: IOLoop.current().remove_timeout(timeout_handle))

        future.add_done_callback(cancel_on_ioloop)

    return result
Beispiel #12
0
    def _receive(self, connect, event):
        if event & IOLoop.ERROR:
            self._close(connect)

        fd = connect.fileno()
        connection = self.conn_pool[fd]
        fragment = connect.recv(1024)
        connection.request_buffer.append(fragment)

        last_fragment = ''.join(connection.request_buffer[:2])
        if EOL2 in last_fragment:
            ioloop = IOLoop.instance()
            ioloop.update_handler(fd, IOLoop.WRITE)
            ioloop.replace_handler(fd, self._send)
Beispiel #13
0
    def __init__(self, socket, *args, **kwargs):
        self.io_loop = IOLoop.instance()
        self.socket = socket
        self.socket.setblocking(0)

        self._read_callback = None
        self.max_buffer_size = 104857600
        self.read_chunk_size = 4096
        self._read_buffer_size = 0
        self._read_buffer = []
        self._write_buffer = []

        self._state = None
        self._closed = False
Beispiel #14
0
class Runner:

    def __init__(self, gen, result_future):
        self.gen = gen
        # future returned by the async function
        self.result_future = result_future
        self.ioloop = IOLoop()
        self.next = None
        # And now we start to drive the generator
        self.run()

    def run(self):
        try:
            future = self.gen.send(self.next)
        except StopIteration as e:
            self.result_future.set_result(e.value)
            return

        def callback(f):
            self.next = f.result
            self.run()

        self.ioloop.add_future(future, callback)
Beispiel #15
0
def with_timeout(abstimeout, future, io_loop=None, quiet_exceptions=()):
    """Wraps a `.Future` in a timeout.

    Raises `TimeoutError` if the input future does not complete before
    ``timeout``, which may be specified in any form allowed by
    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
    relative to `.IOLoop.time`)

    If the wrapped `.Future` fails after it has timed out, the exception
    will be logged unless it is of a type contained in ``quiet_exceptions``
    (which may be an exception type or a sequence of types).

    Currently only supports Futures, not other `YieldPoint` classes.
    """
    result = Future()
    chain_future(future, result)
    if io_loop is None:
        io_loop = IOLoop.current()

    def error_callback(future):
        try:
            future.result()
        except Exception as e:
            if not isinstance(e, quiet_exceptions):
                logging.error("Exception in Future %r after timeout",
                              future, exc_info=True)

    def timeout_callback():
        result.set_exception(TimeoutError("Timeout"))
        # In case the wrapped future goes on to fail, log it.
        future.add_done_callback(error_callback)

    timeout_handle = io_loop.call_at(abstimeout, timeout_callback)
    if isinstance(future, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future 
        future.add_done_callback(
            lambda future: io_loop.remove_timeout(timeout_handle))
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.

        def cancel_on_ioloop(fut):
            IOLoop.current().call_next_tick(lambda fut : IOLoop.current().remove_timeout(timeout_handle))

        future.add_done_callback(cancel_on_ioloop)

    return result
Beispiel #16
0
def add_accept_handler(sock, callback, io_loop=None):
    if io_loop is None:
        io_loop = IOLoop.current()

    def accept_handler(fd, events):
        while True:
            try:
                connection, address = sock.accept()
            except socket.error as e:
                if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN):
                    return
                if e.args[0] == errno.ECONNABORTED:
                    continue
                raise
            callback(connection, address)
    io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ)
Beispiel #17
0
 def __init__(self, gen, result_future, first_yielded):
     self.gen = gen
     self.result_future = result_future
     self.future = _null_future
     self.running = False
     self.finished = False # is coroutine over?
     self.had_exception = False
     self.io_loop = IOLoop.current()
     # For efficiency, we do not create a stack context until we
     # reach a YieldPoint (stack contexts are required for the historical
     # semantics of YieldPoints, but not for Futures).  When we have
     # done so, this field will be set and must be called at the end
     # of the coroutine.
     if self.handle_yield(first_yielded):
         self.run()
     else:
         pass # future is not ready
Beispiel #18
0
 def __init__(self, gen, result_future, first_yielded):
     self.gen = gen
     self.result_future = result_future
     self.future = _null_future
     self.running = False
     self.finished = False  # is coroutine over?
     self.had_exception = False
     self.io_loop = IOLoop.current()
     # For efficiency, we do not create a stack context until we
     # reach a YieldPoint (stack contexts are required for the historical
     # semantics of YieldPoints, but not for Futures).  When we have
     # done so, this field will be set and must be called at the end
     # of the coroutine.
     if self.handle_yield(first_yielded):
         self.run()
     else:
         pass  # future is not ready
Beispiel #19
0
class Stream:
    '''
    A wrapper around a client socket.
    '''

    def __init__(self, sock):
        self.sock = sock
        self.ioloop = IOLoop()

    def __getattr__(self, attrname):
        return getattr(self.sock, attrname)

    def __repr__(self):
        return '%s %s' % self.getpeername()

    def recv(self):
        future = Future()

        def handler():
            future.set_result(self.sock.recv(65536))
            # Every time a remove handler to add it back again
            self.ioloop.remove_handler(self.sock)

        self.ioloop.add_handler(self.sock, selectors.EVENT_READ, handler)
        return future

    def send(self, data):
        future = Future()

        def handler():
            self.sock.send(data)
            future.set_result(None)
            self.ioloop.remove_handler(self.sock)

        self.ioloop.add_handler(self.sock, selectors.EVENT_WRITE, handler)
        return future
Beispiel #20
0
            print('on header exception.')
            raise
        print(method, uri, version, self._address)
        remote_ip = self._address[0]

        self._request = HTTPRequest(connection=self,
                                    method=method,
                                    uri=uri,
                                    version=version,
                                    headers=headers,
                                    remote_ip=remote_ip)
        content_length = headers.get('Content-Length')
        if content_length:
            content_length = int(content_length)
            if content_length > self._stream.max_buffer_size():
                print('Content-Length too long')
                raise
            self._stream.read_bytes(content_length, self._on_request_body)

    def _on_request_body(self, data):
        print('request body: %s' % data)
        self._request.body = data
        if self._request_callback:
            self._request_callback(self._request)


if __name__ == '__main__':
    server = HTTPServer(None, io_loop=IOLoop.current())
    server.listen(9999)
    IOLoop.instance().start()
Beispiel #21
0
# -*- coding: utf-8 -*-

import tornado.ioloop
from urls import urls
from settings import settings
from ioloop import IOLoop

if __name__ == '__main__':
    app = tornado.web.Application(urls, **settings)
    app.listen(8080)
    IOLoop.instance().start()
    tornado.ioloop.IOLoop.instance().start()

Beispiel #22
0
 def wrapper(*args, **kwargs):
     future = func(*args, **kwargs)
     IOLoop.instance().add_future(future)
Beispiel #23
0
 def __init__(self, address, port):
     self.io_loop = IOLoop.instance()
     self._socket = self.bind_socket(address, port)
     self.io_loop.add_handler(self._socket.fileno(), self.accept_handler, select.EPOLLIN)
Beispiel #24
0
            if not version.startswith('HTTP/'):
                print('error http version')
        except:
            print('on header exception.')
            raise
        print(method, uri, version, self._address)
        remote_ip = self._address[0]

        self._request = HTTPRequest(
            connection=self, method=method, uri=uri,
            version=version, headers=headers, remote_ip=remote_ip)
        content_length = headers.get('Content-Length')
        if content_length:
            content_length = int(content_length)
            if content_length > self._stream.max_buffer_size():
                print('Content-Length too long')
                raise
            self._stream.read_bytes(content_length, self._on_request_body)

    def _on_request_body(self, data):
        print('request body: %s' % data)
        self._request.body = data
        if self._request_callback:
            self._request_callback(self._request)


if __name__ == '__main__':
    server = HTTPServer(None, io_loop=IOLoop.current())
    server.listen(9999)
    IOLoop.instance().start()
Beispiel #25
0
            #print("recv " + str(mv))
            conn.send("*1\r\n$4\r\npong\r\n")
            return MessageCallback.__call__(self, conn, mv)

    class ConnectHandler(OnConnectCallback):
        def __call__(self, conn):
            OnConnectCallback.__call__(self, conn)
            #print("on connect, send ping")
            #conn.send("*3\r\n$3\r\nset\r\n$3\r\nage\r\n$3\r\n711\r\n")

    class NewConnHandler(NewConnectionCallback):
        def __call__(self, conn):
            NewConnectionCallback.__call__(self, conn)
            conn.setMsgCallback(MsgHandler())
            conn.setOnConnectCallback(ConnectHandler())

    def print_time(a='default'):
        import time
        print("From print_time", time.time(), a)

    loop = IOLoop()
    loop._sched.enter(delay=0.4, count=10, action=print_time)
    acceptor = Acceptor(port=6379, loop=loop)
    acceptor.setNewConnCallback(NewConnHandler())
    #connector = Connector(loop = loop)
    #connector.setNewConnCallback(NewConnHandler())
    #connector.connect(port = 6379)
    print("start")

    loop.start()
Beispiel #26
0
 def __init__(self, *args, **kwargs):
     _depwarn("CallLater is deprecated; use "
         "ioloop.IOLoop.instance().call_later() instead")
     from ioloop import IOLoop
     IOLoop.instance().call_later(*args, **kwargs)
Beispiel #27
0
 def callback_on_ioloop(fut):
     IOLoop.current().call_next_tick(lambda fut : callback(fut.result()))
Beispiel #28
0
class UDPEchoServer(UDPServer):

    def handle_receive(self):
        msg, addr = self.socket.recvfrom(8192)
        self.socket.sendto(msg, addr)


def fib(n):
    if n < 2:
        return 1
    else:
        return fib(n-1) + fib(n-2)


class UDPFibServer(UDPServer):

    def handle_receive(self):
        msg, addr = self.socket.recvfrom(128)
        n = int(msg)
        pool.run(fib, (n,), callback=lambda r: self.respond(r, addr))

    def respond(self, result, addr):
        self.socket.sendto(str(result).encode('ascii'), addr)


if __name__ == '__main__':
    # IOLoop((UDPTimeServer(('', 14000)), UDPEchoServer(('', 15000)))).run()
    pool = ThreadPoolHandler(4)
    IOLoop((pool, UDPFibServer(('', 16000)))).run()
Beispiel #29
0
 def call_on_ioloop(fut):
     IOLoop.current().call_next_tick(lambda: self.run())
Beispiel #30
0
def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    IOLoop.instance().start()
    tornado.ioloop.IOLoop.instance().start()
Beispiel #31
0
 def wrapper(*args, **kwargs):
     future = func(*args, **kwargs)
     IOLoop.instance().add_future(future)
Beispiel #32
0
 def __init__(self, *args, **kwargs):
     _depwarn("CallEvery is deprecated; use "
         "pyftpdlib.ioloop.IOLoop.instance().call_every() instead")
     from ioloop import IOLoop
     IOLoop.instance().call_every(*args, **kwargs)
Beispiel #33
0
def sleep(seconds):
    future = Future()
    loop = IOLoop()
    time_ = loop.time() + seconds
    loop.add_timeout(Timeout(time_, lambda: future.set_result(None)))
    yield from future
Beispiel #34
0
 def __init__(self, port=9999):
     self.__port = port
     self.__instance = IOLoop.instance()
     self.init()
Beispiel #35
0
#!/usr/bin/env python
# encoding: utf-8

import socket
from ioloop import IOLoop, READ, ERROR, WRITE

main_sock_fd = None
loop = IOLoop()


socks = {}
buff = ''

def handle_read(fd, events):
    global buff
    sock = socks[int(fd)]
    data = sock.recv(10)
    print 'Recv:%s' %  data
    sock.send('pikachu\n')
    buff += data

def handle_write(fd, events):
    global buff
    sock = socks[int(fd)]
    sock.send(buff)
    buff = ''

def handle_events(fd, events):

    if fd == main_sock_fd:
        # new connection
Beispiel #36
0
        self._io_loop = io_loop
        self._sockets = {}

    def listen(self, port, address=""):
        sockets = bind_sockets(port, address=address)
        self.add_sockets(sockets)

    def add_sockets(self, sockets):
        if self._io_loop is None:
            self._io_loop = IOLoop.current()

        for sock in sockets:
            self._sockets[sock.fileno()] = sock
            add_accept_handler(sock, self._handle_connection, io_loop=self._io_loop)

    def add_socket(self, socket):
        self.add_sockets([socket])

    def handle_stream(self, stream, address):
        raise NotImplementedError()

    def _handle_connection(self, connection, address):
        stream = IOStream(connection, self._io_loop)
        self.handle_stream(stream, address)


if __name__ == "__main__":
    server = TCPServer()
    server.listen(9999)
    IOLoop.instance().start()
Beispiel #37
0
 def __init__(self, sock):
     self.sock = sock
     self.ioloop = IOLoop()
Beispiel #38
0
 def cancel_on_ioloop(fut):
     IOLoop.current().call_next_tick(lambda fut : IOLoop.current().remove_timeout(timeout_handle))
Beispiel #39
0
def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(settings['port'])
    IOLoop.instance().start()
    tornado.ioloop.IOLoop.instance().start()
Beispiel #40
0
async def sleep_await(seconds):
    future = Future()
    loop = IOLoop()
    time_ = loop.time() + seconds
    loop.add_timeout(Timeout(time_, lambda: future.set_result(None)))
    await future
Beispiel #41
0
 def establish(self, term="xterm"):
     self._shell = self.ssh.invoke_shell(term)
     self._shell.setblocking(0)
     self._id = self._shell.fileno()
     IOLoop.instance().register(self)
     IOLoop.instance().add_future(self.trans_back())
Beispiel #42
0
 def callback_on_ioloop(fut):
     IOLoop.current().call_next_tick(
         lambda fut: callback(fut.result()))
Beispiel #43
0
 def call_on_ioloop(fut): 
     IOLoop.current().call_next_tick(lambda : self.run())
Beispiel #44
0
 def cancel_on_ioloop(fut):
     IOLoop.current().call_next_tick(
         lambda fut: IOLoop.current().remove_timeout(timeout_handle))