def test_backdoor_port_range_all_inuse(self):
     self.config(backdoor_port="8800:8899")
     self.common_backdoor_port_setup()
     for i in range(8800, 8900):
         eventlet.listen(("localhost", i)).AndRaise(socket.error(errno.EADDRINUSE, ""))
     self.mox.ReplayAll()
     self.assertRaises(socket.error, eventlet_backdoor.initialize_if_enabled)
Exemplo n.º 2
0
def run(config):
    global CONFIG
    CONFIG = config
    
    registrar = Registrar()

    addr = (config['sfk_server']['host'], 
            int(config['sfk_server']['port']))
    LOGGER.info("Starting sfk-side server on %s:%d" %addr)
    eventlet.spawn_n(eventlet.serve, 
                     eventlet.listen(addr), 
                     registrar.register_sfk) 

    addr = (config['rengine_server']['host'],
            int(config['rengine_server']['port']))
    LOGGER.info("Starting rengine-side server on %s:%d" %addr)
    eventlet.spawn_n(eventlet.serve, 
                     eventlet.listen(addr), 
                     registrar.register_rengine) 

    LOGGER.info("Starting http server")

    run_httpserver(registrar, config,
                          host=config['http_server']['host'],
                          port=config['http_server']['port'],
                          debug=True, # TODO remove in production!!
                          quiet=True,
                          server='eventlet')
Exemplo n.º 3
0
 def start(self, start_listeners=True):
     self.log('Server', 'info', 'starting server')
     for name in self.config.components:
         self.components[name] = self.config.components.import_(name)(self,
             name)
     self._greenlet = eventlet.spawn(self._process)
     if start_listeners and 'backdoor_port' in self.config.server:
         # enable backdoor console
         bdport = self.config.getint(('server', 'backdoor_port'))
         self.log('Server', 'info', 'enabling backdoor on port %s'
             % bdport)
         eventlet.spawn(backdoor.backdoor_server,
             eventlet.listen(('127.0.0.1', bdport)),
             locals={'server': self,
                     'debug': debug,
                     'exit': safe_exit(),
                     'quit': safe_exit(),
                     'stats': lambda: pprint.pprint(self.stats()),
             })
     app = create_application(self)
     dirs = self.config.server.get('static_directories', None)
     if dirs is not None:
         app = StaticFileServer(dirs.split(','), app, self)
     self.wsgiapp = app
     if start_listeners:
         numsimulreq = self.config.get(('http', 'max_simultaneous_reqs'))
         host = self.config.http.address
         port = self.config.http.getint('port')
         sock = eventlet.listen((host, port))
         pool = self.server_pool = eventlet.GreenPool(10000)
         log = (self.options.nohttp or self.options.statdump) and \
             dummylog() or None
         wsgi.server(sock, app, custom_pool=pool, log=log)
Exemplo n.º 4
0
def main():
    from eventlet import wsgi,wrap_ssl,listen
    from ankisyncd.thread import shutdown

    config = SafeConfigParser()
    config.read("ankisyncd.conf")

    ankiserver = SyncApp(config)
    host = config.get("sync_app", "host")
    port = config.getint("sync_app", "port")

    if(config.getboolean("sync_app", "ssl")):
        certfile = config.get("sync_app", "certfile")
        keyfile = config.get("sync_app", "keyfile")
        socket = wrap_ssl(  listen((host, port)),
                            certfile=certfile,
                            keyfile=keyfile,
                            server_side=True )
    else:
        socket = listen((host, port))

    try:
        wsgi.server(socket, ankiserver)
    finally:
        shutdown()
Exemplo n.º 5
0
    def get_socket(self):
        """Create listener socket based on bottle server parameters."""
        import eventlet

        # Separate out socket.listen arguments
        socket_args = {}
        for arg in ('backlog', 'family'):
            try:
                socket_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        # Separate out wrap_ssl arguments
        ssl_args = {}
        for arg in ('keyfile', 'certfile', 'server_side', 'cert_reqs',
                    'ssl_version', 'ca_certs', 'do_handshake_on_connect',
                    'suppress_ragged_eofs', 'ciphers'):
            try:
                ssl_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        address = (self.host, self.port)
        try:
            sock = eventlet.listen(address, **socket_args)
        except TypeError:
            # Fallback, if we have old version of eventlet
            sock = eventlet.listen(address)
        if ssl_args:
            sock = eventlet.wrap_ssl(sock, **ssl_args)
        return sock
 def test_backdoor_port_inuse(self):
     self.config(backdoor_port=2345)
     self.common_backdoor_port_setup()
     eventlet.listen(('localhost', 2345)).AndRaise(
         socket.error(errno.EADDRINUSE, ''))
     self.mox.ReplayAll()
     self.assertRaises(socket.error,
                       eventlet_backdoor.initialize_if_enabled)
 def test_backdoor_port_range(self):
     self.config(backdoor_port="8800:8899")
     self.common_backdoor_port_setup()
     eventlet.listen(("localhost", 8800)).AndReturn(self.sock)
     self.sock.getsockname().AndReturn(("127.0.0.1", 8800))
     eventlet.spawn_n(eventlet.backdoor.backdoor_server, self.sock, locals=mox.IsA(dict))
     self.mox.ReplayAll()
     port = eventlet_backdoor.initialize_if_enabled()
     self.assertEqual(port, 8800)
Exemplo n.º 8
0
def setUp(self):
    global _servers, keystone0_lis, keystone1_lis, keystone0_srv, keystone1_srv, keystone0_spa, keystone1_spa
    nl = NullLogger()
    keystone0_lis = listen(('localhost', 5001))
    keystone1_lis = listen(('localhost', 15001))
    keystone0_srv = DummySrv('http://127.0.0.1:5001')
    keystone1_srv = DummySrv('http://127.0.0.1:15001')
    keystone0_spa = spawn(wsgi.server, keystone0_lis, keystone0_srv, nl)
    keystone1_spa = spawn(wsgi.server, keystone1_lis, keystone1_srv, nl)
    _servers = (keystone0_spa, keystone1_spa)
Exemplo n.º 9
0
def run():
    eventlet.debug.hub_prevent_multiple_readers(False)
    eventlet.monkey_patch(socket=True)

    logging.basicConfig(format="%(asctime)s %(levelname) 7s %(module)s: %(message)s", level=logging.DEBUG)

    parser = argparse.ArgumentParser(description="Localtunnel server daemon")
    parser.add_argument(
        "frontend",
        metavar="frontend_listener",
        type=str,
        help="hostname to run frontend on (default: vcap.me:8000)",
        default="vcap.me:8000",
    )
    parser.add_argument(
        "backend",
        metavar="backend_listener",
        type=str,
        help="port or address to run backend server on (default: 8001)",
        default="8001",
    )
    args = parser.parse_args()

    frontend_address, frontend_hostname = util.parse_address(args.frontend)
    backend_address, backend_hostname = util.parse_address(args.backend)

    logging.info("starting frontend on {0} for {1}...".format(frontend_address, frontend_hostname))
    logging.info("starting backend on {0}...".format(backend_address))

    Tunnel.backend_port = backend_address[1]
    if frontend_address[1] == 80:
        Tunnel.domain_suffix = frontend_hostname
    else:
        Tunnel.domain_suffix = ":".join([frontend_hostname, str(frontend_address[1])])

    stats_key = os.environ.get("STATHAT_EZKEY", None)
    if stats_key:
        metrics.run_reporter(stats_key)

    frontend_listener = eventlet.listen(frontend_address)
    backend_listener = eventlet.listen(backend_address)

    try:
        Tunnel.schedule_idle_scan()
        pool = eventlet.greenpool.GreenPool(size=2)
        pool.spawn_n(eventlet.serve, frontend_listener, frontend.connection_handler)
        pool.spawn_n(eventlet.serve, backend_listener, backend.connection_handler)
        pool.waitall()
    except KeyboardInterrupt:
        pass
Exemplo n.º 10
0
    def run(self, handler):
        from eventlet import wsgi, listen

        try:
            wsgi.server(listen((self.host, self.port)), handler,
                log_output=(not self.quiet))
        except TypeError:
            # Needed to ignore the log
            class NoopLog:
                def write(self, *args):
                    pass

            # Fallback, if we have old version of eventlet
            wsgi.server(listen((self.host, self.port)), handler, log=NoopLog())
Exemplo n.º 11
0
    def test_socket_reuse(self):
        lsock1 = eventlet.listen(('localhost', 0))
        port = lsock1.getsockname()[1]

        if hasattr(socket, 'SO_REUSEPORT'):
            lsock2 = eventlet.listen(('localhost', port))
        else:
            try:
                lsock2 = eventlet.listen(('localhost', port))
                assert lsock2
                lsock2.close()
            except socket.error:
                pass

        lsock1.close()
Exemplo n.º 12
0
def setUp(self):
    global _servers, proxy0_srv, proxy1_srv, webcache0_srv, proxy0_lis, \
        proxy1_lis, webcache0_lis
    nl = NullLogger()
    conf = get_config()
    proxy0_lis = listen(('localhost', 8080))
    proxy1_lis = listen(('localhost', 18080))
    webcache0_lis = listen(('localhost', 8888))
    proxy0_srv = DummySrv('http://127.0.0.1:8080')
    proxy1_srv = DummySrv('http://127.0.0.1:18080')
    webcache0_srv = DummySrv('http://127.0.0.1:8888')
    proxy0_spa = spawn(wsgi.server, proxy0_lis, proxy0_srv, nl)
    proxy1_spa = spawn(wsgi.server, proxy1_lis, proxy1_srv, nl)
    webcache0_spa = spawn(wsgi.server, webcache0_lis, webcache0_srv, nl)
    _servers = (proxy0_spa, proxy1_spa, webcache0_spa)
Exemplo n.º 13
0
def get_socket(conf, default_port=8080):
    """Bind socket to bind ip:port in conf

    :param conf: Configuration dict to read settings from
    :param default_port: port to use if not specified in conf

    :returns : a socket object as returned from socket.listen or
               ssl.wrap_socket if conf specifies cert_file
    """
    bind_addr = (conf.get("bind_ip", "0.0.0.0"), int(conf.get("bind_port", default_port)))
    address_family = [
        addr[0]
        for addr in socket.getaddrinfo(bind_addr[0], bind_addr[1], socket.AF_UNSPEC, socket.SOCK_STREAM)
        if addr[0] in (socket.AF_INET, socket.AF_INET6)
    ][0]
    sock = None
    retry_until = time.time() + 30
    while not sock and time.time() < retry_until:
        try:
            sock = listen(bind_addr, backlog=int(conf.get("backlog", 4096)), family=address_family)
            if "cert_file" in conf:
                sock = ssl.wrap_socket(sock, certfile=conf["cert_file"], keyfile=conf["key_file"])
        except socket.error, err:
            if err.args[0] != errno.EADDRINUSE:
                raise
            sleep(0.1)
Exemplo n.º 14
0
    def _get_socket(self, host, port, backlog):
        # TODO(dims): eventlet's green dns/socket module does not actually
        # support IPv6 in getaddrinfo(). We need to get around this in the
        # future or monitor upstream for a fix
        info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)[0]
        family = info[0]
        bind_addr = info[-1]

        sock = None
        retry_until = time.time() + 30
        while not sock and time.time() < retry_until:
            try:
                sock = eventlet.listen(bind_addr, backlog=backlog, family=family)
                if sslutils.is_enabled():
                    sock = sslutils.wrap(sock)

            except socket.error as err:
                if err.args[0] != errno.EADDRINUSE:
                    raise
                eventlet.sleep(0.1)
        if not sock:
            raise RuntimeError(
                _("Could not bind to %(host)s:%(port)s " "after trying for 30 seconds") % {"host": host, "port": port}
            )
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # sockets can hang around forever without keepalive
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        # This option isn't available in the OS X version of eventlet
        if hasattr(socket, "TCP_KEEPIDLE"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, CONF.tcp_keepidle)

        return sock
Exemplo n.º 15
0
def initialize_if_enabled():
    backdoor_locals = {
        'exit': _dont_use_this,      # So we don't exit the entire process
        'quit': _dont_use_this,      # So we don't exit the entire process
        'fo': _find_objects,
        'pgt': _print_greenthreads,
    }

    if CONF.backdoor_port is None:
        return None

    # NOTE(johannes): The standard sys.displayhook will print the value of
    # the last expression and set it to __builtin__._, which overwrites
    # the __builtin__._ that gettext sets. Let's switch to using pprint
    # since it won't interact poorly with gettext, and it's easier to
    # read the output too.
    def displayhook(val):
        if val is not None:
            pprint.pprint(val)
    sys.displayhook = displayhook

    sock = eventlet.listen(('localhost', CONF.backdoor_port))
    port = sock.getsockname()[1]
    eventlet.spawn_n(eventlet.backdoor.backdoor_server, sock,
                     locals=backdoor_locals)
    return port
Exemplo n.º 16
0
 def test_http_connect(self):
     bindsock = listen(('127.0.0.1', 0))
     def accept(expected_par):
         try:
             with Timeout(3):
                 sock, addr = bindsock.accept()
                 fp = sock.makefile()
                 fp.write('HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\n'
                          'RESPONSE')
                 fp.flush()
                 self.assertEquals(fp.readline(),
                     'PUT /dev/%s/path/..%%25/?omg&no=%%7f HTTP/1.1\r\n' %
                     expected_par)
                 headers = {}
                 line = fp.readline()
                 while line and line != '\r\n':
                     headers[line.split(':')[0].lower()] = \
                         line.split(':')[1].strip()
                     line = fp.readline()
                 self.assertEquals(headers['content-length'], '7')
                 self.assertEquals(headers['x-header'], 'value')
                 self.assertEquals(fp.readline(), 'REQUEST\r\n')
         except BaseException, err:
             return err
         return None
Exemplo n.º 17
0
 def start(self, host="0.0.0.0", key=None, backlog=128):
     """Run a WSGI server with the given application."""
     logging.debug("Starting %(arg0)s on %(host)s:%(port)s" % {"arg0": sys.argv[0], "host": host, "port": self.port})
     socket = eventlet.listen((host, self.port), backlog=backlog)
     self.pool.spawn_n(self._run, self.application, socket)
     if key:
         self.socket_info[key] = socket.getsockname()
Exemplo n.º 18
0
    def test_timeout_cancel(self):
        server = eventlet.listen(('0.0.0.0', 0))
        bound_port = server.getsockname()[1]

        done = [False]

        def client_closer(sock):
            while True:
                (conn, addr) = sock.accept()
                conn.close()

        def go():
            desc = eventlet.connect(('127.0.0.1', bound_port))
            try:
                api.trampoline(desc, read=True, timeout=0.1)
            except api.TimeoutError:
                assert False, "Timed out"

            server.close()
            desc.close()
            done[0] = True

        greenthread.spawn_after_local(0, go)

        server_coro = api.spawn(client_closer, server)
        while not done[0]:
            api.sleep(0)
        api.kill(server_coro)

        check_hub()
Exemplo n.º 19
0
 def run(self):
     upgrade()
     app.wsgi_app = WSGIErrorMiddleware(app.wsgi_app)
     if self.debug:
         app.run(host=self.host, port=self.port, debug=self.debug)
     else:
         wsgi.server(eventlet.listen((self.host, self.port)), app)
Exemplo n.º 20
0
 def start_tcp(self, listener, port, host='0.0.0.0', key=None, backlog=128):
     """Run a raw TCP server with the given application."""
     arg0 = sys.argv[0]
     LOG.info(_('Starting TCP server %(arg0)s on %(host)s:%(port)s')
              % locals())
     socket = eventlet.listen((host, port), backlog=backlog)
     self._tcp_server = self._pool.spawn_n(self._run_tcp, listener, socket)
Exemplo n.º 21
0
 def run(self):
     for (iface, port, ssl, certfile, keyfile), app in self._wsgi_apps.items():
         if ssl == 1:
             print "Orbited listening on https://%s:%s using cert: %s and key: %s" % (iface or "0.0.0.0", port, certfile, keyfile)
             eventlet.spawn(eventlet.wsgi.server, eventlet.wrap_ssl(eventlet.listen((iface, port)),
                                           certfile=certfile,
                                           keyfile=keyfile,
                                           server_side=True), app, log=EmptyLogShim())
         else:
             print "Orbited listening on http://%s:%s" % (iface or "0.0.0.0", port)
             eventlet.spawn(eventlet.wsgi.server, eventlet.listen((iface,port)), app, log=EmptyLogShim())
         
         
     ev = eventlet.event.Event()        
     eventlet.spawn(self._run, ev)
     return ev
Exemplo n.º 22
0
 def handle(self, *args, **options):
     if sio.async_mode == 'threading':
         super(Command, self).handle(*args, **options)
     elif sio.async_mode == 'eventlet':
         # deploy with eventlet
         import eventlet
         import eventlet.wsgi
         from django_example.wsgi import application
         eventlet.wsgi.server(eventlet.listen(('', 8000)), application)
     elif sio.async_mode == 'gevent':
         # deploy with gevent
         from gevent import pywsgi
         from django_example.wsgi import application
         try:
             from geventwebsocket.handler import WebSocketHandler
             websocket = True
         except ImportError:
             websocket = False
         if websocket:
             pywsgi.WSGIServer(
                 ('', 8000), application,
                 handler_class=WebSocketHandler).serve_forever()
         else:
             pywsgi.WSGIServer(('', 8000), application).serve_forever()
     elif sio.async_mode == 'gevent_uwsgi':
         print('Start the application through the uwsgi server. Example:')
         print('uwsgi --http :5000 --gevent 1000 --http-websockets '
               '--master --wsgi-file django_example/wsgi.py --callable '
               'application')
     else:
         print('Unknown async_mode: ' + sio.async_mode)
Exemplo n.º 23
0
    def _get_socket(host, port, backlog):
        info = socket.getaddrinfo(
            host, port, socket.AF_UNSPEC, socket.SOCK_STREAM
        )[0]
        family = info[0]
        bind_addr = info[-1]

        sock = None
        retry_until = time.time() + 30
        while not sock and time.time() < retry_until:
            try:
                sock = eventlet.listen(bind_addr, backlog=backlog,
                                       family=family)
                if sslutils.is_enabled(CONF):
                    sock = sslutils.wrap(CONF, sock)

            except socket.error as err:
                if err.args[0] != errno.EADDRINUSE:
                    raise
        if not sock:
            raise RuntimeError(_(
                "Could not bind to %(host)s:%(port)s "
                "after trying for 30 seconds") %
                {'host': host, 'port': port})
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # sockets can hang around forever without keepalive
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        # This option isn't available in the OS X version of eventlet
        if hasattr(socket, 'TCP_KEEPIDLE'):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
                            CONF.tcp_keepidle)

        return sock
Exemplo n.º 24
0
 def run(self):
     for (iface, port), app in self._wsgi_apps.items():
         print "Orbited listening on http://%s:%s" % (iface or "0.0.0.0", port)
         eventlet.spawn(eventlet.wsgi.server, eventlet.listen((iface,port)), app, log=EmptyLogShim())
     ev = eventlet.event.Event()        
     eventlet.spawn(self._run, ev)
     return ev
Exemplo n.º 25
0
def _run_server():
    host = cfg.CONF.auth.host
    port = cfg.CONF.auth.port
    use_ssl = cfg.CONF.auth.use_ssl

    cert_file_path = os.path.realpath(cfg.CONF.auth.cert)
    key_file_path = os.path.realpath(cfg.CONF.auth.key)

    if use_ssl and not os.path.isfile(cert_file_path):
        raise ValueError('Certificate file "%s" doesn\'t exist' % (cert_file_path))

    if use_ssl and not os.path.isfile(key_file_path):
        raise ValueError('Private key file "%s" doesn\'t exist' % (key_file_path))

    socket = eventlet.listen((host, port))

    if use_ssl:
        socket = eventlet.wrap_ssl(socket,
                                   certfile=cert_file_path,
                                   keyfile=key_file_path,
                                   server_side=True)

    LOG.info('ST2 Auth API running in "%s" auth mode', cfg.CONF.auth.mode)
    LOG.info('(PID=%s) ST2 Auth API is serving on %s://%s:%s.', os.getpid(),
             'https' if use_ssl else 'http', host, port)

    wsgi.server(socket, app.setup_app())
    return 0
Exemplo n.º 26
0
    def _get_socket(self, host, port, backlog):
        # TODO(dims): eventlet's green dns/socket module does not actually
        # support IPv6 in getaddrinfo(). We need to get around this in the
        # future or monitor upstream for a fix
        info = socket.getaddrinfo(host,
                                  port,
                                  socket.AF_UNSPEC,
                                  socket.SOCK_STREAM)[0]
        family = info[0]
        bind_addr = info[-1]

        sock = None
        retry_until = time.time() + 30
        while not sock and time.time() < retry_until:
            try:
                sock = eventlet.listen(bind_addr,
                                       backlog=backlog,
                                       family=family)
                if sslutils.is_enabled():
                    sock = sslutils.wrap(sock)

            except socket.error, err:
                if err.args[0] != errno.EADDRINUSE:
                    raise
                eventlet.sleep(0.1)
Exemplo n.º 27
0
    def test_hub_exceptions(self):
        debug.hub_exceptions(True)
        server = eventlet.listen(('0.0.0.0', 0))
        client = eventlet.connect(('127.0.0.1', server.getsockname()[1]))
        client_2, addr = server.accept()

        def hurl(s):
            s.recv(1)
            {}[1]  # keyerror

        fake = six.StringIO()
        orig = sys.stderr
        sys.stderr = fake
        try:
            gt = eventlet.spawn(hurl, client_2)
            eventlet.sleep(0)
            client.send(b' ')
            eventlet.sleep(0)
            # allow the "hurl" greenlet to trigger the KeyError
            # not sure why the extra context switch is needed
            eventlet.sleep(0)
        finally:
            sys.stderr = orig
            self.assertRaises(KeyError, gt.wait)
            debug.hub_exceptions(False)
        # look for the KeyError exception in the traceback
        assert 'KeyError: 1' in fake.getvalue(), "Traceback not in:\n" + fake.getvalue()
Exemplo n.º 28
0
    def listen(self, key=None, backlog=128):
        """Create and start listening on socket.

        Call before forking worker processes.

        Raises Exception if this has already been called.
        """

        # TODO(dims): eventlet's green dns/socket module does not actually
        # support IPv6 in getaddrinfo(). We need to get around this in the
        # future or monitor upstream for a fix.
        # Please refer below link
        # (https://bitbucket.org/eventlet/eventlet/
        # src/e0f578180d7d82d2ed3d8a96d520103503c524ec/eventlet/support/
        # greendns.py?at=0.12#cl-163)
        info = socket.getaddrinfo(self.host,
                                  self.port,
                                  socket.AF_UNSPEC,
                                  socket.SOCK_STREAM)[0]

        try:
            self.socket = eventlet.listen(info[-1], family=info[0],
                                          backlog=backlog)
        except EnvironmentError:
            LOG.error(_LE("Could not bind to %(host)s:%(port)s"),
                      {'host': self.host, 'port': self.port})
            raise

        LOG.info(_LI('Starting %(arg0)s on %(host)s:%(port)s'),
                 {'arg0': sys.argv[0],
                  'host': self.host,
                  'port': self.port})
Exemplo n.º 29
0
    def test_send_timeout(self):
        self.reset_timeout(2)
        listener = bufsized(eventlet.listen(('', 0)))

        evt = event.Event()

        def server():
            # accept the connection in another greenlet
            sock, addr = listener.accept()
            sock = bufsized(sock)
            evt.wait()

        gt = eventlet.spawn(server)

        addr = listener.getsockname()

        client = bufsized(greenio.GreenSocket(socket.socket()))
        client.connect(addr)
        try:
            client.settimeout(0.00001)
            msg = b"A" * 100000  # large enough number to overwhelm most buffers

            total_sent = 0
            # want to exceed the size of the OS buffer so it'll block in a
            # single send
            for x in range(10):
                total_sent += client.send(msg)
            self.fail("socket.timeout not raised")
        except socket.timeout as e:
            assert hasattr(e, 'args')
            self.assertEqual(e.args[0], 'timed out')

        evt.send()
        gt.wait()
Exemplo n.º 30
0
    def test_closure(self):
        def spam_to_me(address):
            sock = eventlet.connect(address)
            while True:
                try:
                    sock.sendall(b'hello world')
                except socket.error as e:
                    if get_errno(e) == errno.EPIPE:
                        return
                    raise

        server = eventlet.listen(('127.0.0.1', 0))
        sender = eventlet.spawn(spam_to_me, server.getsockname())
        client, address = server.accept()
        server.close()

        def reader():
            try:
                while True:
                    data = client.recv(1024)
                    assert data
            except socket.error as e:
                # we get an EBADF because client is closed in the same process
                # (but a different greenthread)
                if get_errno(e) != errno.EBADF:
                    raise

        def closer():
            client.close()

        reader = eventlet.spawn(reader)
        eventlet.spawn_n(closer)
        reader.wait()
        sender.wait()
Exemplo n.º 31
0
def wsgi_server():
    wsgi.server(eventlet.listen(('', 8080)), hello_world)
Exemplo n.º 32
0
    def __init__(self,
                 name,
                 app,
                 host=None,
                 port=None,
                 pool_size=None,
                 protocol=eventlet.wsgi.HttpProtocol,
                 backlog=128):
        """Initialize, but do not start, a WSGI server.

        :param name: Pretty name for logging.
        :param app: The WSGI application to serve.
        :param host: IP address to serve the application.
        :param port: Port number to server the application.
        :param pool_size: Maximum number of eventlets to spawn concurrently.
        :returns: None

        """
        # Allow operators to customize http requests max header line size.
        eventlet.wsgi.MAX_HEADER_LINE = CONF.max_header_line
        self.name = name
        self.app = app
        self._host = host or "0.0.0.0"
        self._port = port or 0
        self._server = None
        self._socket = None
        self._protocol = protocol
        self.pool_size = pool_size or self.default_pool_size
        self._pool = eventlet.GreenPool(self.pool_size)
        self._logger = logging.getLogger("eventlet.wsgi.server")
        self._wsgi_logger = logging.WritableLogger(self._logger)

        if backlog < 1:
            raise exception.InvalidInput(
                reason='The backlog must be more than 1')

        bind_addr = (host, port)
        # TODO(dims): eventlet's green dns/socket module does not actually
        # support IPv6 in getaddrinfo(). We need to get around this in the
        # future or monitor upstream for a fix
        try:
            info = socket.getaddrinfo(bind_addr[0], bind_addr[1],
                                      socket.AF_UNSPEC, socket.SOCK_STREAM)[0]
            family = info[0]
            bind_addr = info[-1]
        except Exception:
            family = socket.AF_INET

        cert_file = CONF.ssl_cert_file
        key_file = CONF.ssl_key_file
        ca_file = CONF.ssl_ca_file
        self._use_ssl = cert_file or key_file

        if cert_file and not os.path.exists(cert_file):
            raise RuntimeError(_("Unable to find cert_file : %s") % cert_file)

        if ca_file and not os.path.exists(ca_file):
            raise RuntimeError(_("Unable to find ca_file : %s") % ca_file)

        if key_file and not os.path.exists(key_file):
            raise RuntimeError(_("Unable to find key_file : %s") % key_file)

        if self._use_ssl and (not cert_file or not key_file):
            raise RuntimeError(
                _("When running server in SSL mode, you "
                  "must specify both a cert_file and "
                  "key_file option value in your "
                  "configuration file."))

        retry_until = time.time() + 30
        while not self._socket and time.time() < retry_until:
            try:
                self._socket = eventlet.listen(bind_addr,
                                               backlog=backlog,
                                               family=family)
            except socket.error as err:
                if err.args[0] != errno.EADDRINUSE:
                    raise
                eventlet.sleep(0.1)

        if not self._socket:
            raise RuntimeError(
                _("Could not bind to %(host)s:%(port)s "
                  "after trying for 30 seconds") % {
                      'host': host,
                      'port': port
                  })

        (self._host, self._port) = self._socket.getsockname()[0:2]
        LOG.info(
            _("%(name)s listening on %(_host)s:%(_port)s") % self.__dict__)
Exemplo n.º 33
0
    def __init__(self,
                 name,
                 app,
                 host='0.0.0.0',
                 port=0,
                 pool_size=None,
                 protocol=eventlet.wsgi.HttpProtocol,
                 backlog=128,
                 use_ssl=False,
                 max_url_len=None):
        """Initialize, but do not start, a WSGI server.

        :param name: Pretty name for logging.
        :param app: The WSGI application to serve.
        :param host: IP address to serve the application.
        :param port: Port number to server the application.
        :param pool_size: Maximum number of eventlets to spawn concurrently.
        :param backlog: Maximum number of queued connections.
        :param max_url_len: Maximum length of permitted URLs.
        :returns: None
        :raises: masakari.exception.InvalidInput
        """
        # Allow operators to customize http requests max header line size.
        eventlet.wsgi.MAX_HEADER_LINE = CONF.wsgi.max_header_line
        self.name = name
        self.app = app
        self._server = None
        self._protocol = protocol
        self.pool_size = pool_size or self.default_pool_size
        self._pool = eventlet.GreenPool(self.pool_size)
        self._logger = logging.getLogger("masakari.%s.wsgi.server" % self.name)
        self._use_ssl = use_ssl
        self._max_url_len = max_url_len

        self.client_socket_timeout = CONF.wsgi.client_socket_timeout or None

        if backlog < 1:
            raise exception.InvalidInput(
                reason=_('The backlog must be more than 0'))

        bind_addr = (host, port)
        try:
            info = socket.getaddrinfo(bind_addr[0], bind_addr[1],
                                      socket.AF_UNSPEC, socket.SOCK_STREAM)[0]
            family = info[0]
            bind_addr = info[-1]
        except Exception:
            family = socket.AF_INET

        try:
            self._socket = eventlet.listen(bind_addr, family, backlog=backlog)
        except EnvironmentError:
            LOG.error("Could not bind to %(host)s:%(port)d", {
                'host': host,
                'port': port
            })
            raise

        (self.host, self.port) = self._socket.getsockname()[0:2]
        LOG.info("%(name)s listening on %(host)s:%(port)d", {
            'name': self.name,
            'host': self.host,
            'port': self.port
        })
Exemplo n.º 34
0
import os
import eventlet
from eventlet import wsgi
from _source_code import app
port = int(os.environ.get("PORT", 5000))
wsgi.server(eventlet.listen(('0.0.0.0', port)), app)
Exemplo n.º 35
0
    print("nuevo  find producto")
    codigo = request.args.get('codigo')
    lista = findByProductoDB(codigo)
    print("busqueda producto desde bd")
    print(lista)
    if lista is None:
        print("Datos en local")
        lista = findByProducto(codigo)
    send(json.dumps(lista), namespace='/', broadcast=True)
    msg = '$' + str(lista['precioVenta']) + '  -- ' + lista['description']
    n = notify2.Notification(summary=msg, message="Tlapeleria", icon='')
    n.set_timeout(5)
    n.show()

    return lista


@app.route('/test', methods=['GET'])
def prueba():
    return "<h1> Hola mundo </h1>"


if __name__ == '__main__':
    eventlet.wsgi.server(
        eventlet.wrap_ssl(eventlet.listen(('192.168.100.9', 5000)),
                          certfile='server_cert.pem',
                          keyfile='server_key.pem',
                          server_side=True), app)
#   socketio.run(app,ssl_context='adhoc', host='192.168.100.9',port='5000',debug=True)
#   socketio.run(app,port='5000')
Exemplo n.º 36
0
parent_conn, child_conn = Pipe()
p = Process(target=effects.led_manager, args=(child_conn,))


@sio.on('connect')
def connect(sid, environ):
    print("connect ", sid)


@sio.on('change')
def message(sid, data):
    print("message ", data)
    parent_conn.send(data)


@sio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)


if __name__ == '__main__':
    try:
        host = os.environ.get('LEDSERVICE_HOST')
        port = os.environ.get('LEDSERVICE_PORT')
        p.start()
        app = socketio.Middleware(sio, app)
        eventlet.wsgi.server(eventlet.listen((host, int(port))), app)
    except KeyError as e:
        print('Failling start Service reason: {}'.format(e))
Exemplo n.º 37
0
sio = socketio.Server()
app = Flask(__name__)


@sio.on('connect')
def connect(sid, environ):
    print("connect ", sid)


@sio.on('submit')
def message(sid, data):
    # when a submit event is sent from client that means the user has solved a problem successfully
    # so all the users should update their leader board
    print("message ", data)
    # emit a changed event so clients can know that the leaderboard has been changed
    sio.emit('changed', {"data": "changed"})


@sio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)


if __name__ == '__main__':
    # wrap Flask application with engineio's middleware
    app = socketio.Middleware(sio, app)

    # deploy as an eventlet WSGI server
    eventlet.wsgi.server(eventlet.listen(('127.0.0.1', 8081)), app)
Exemplo n.º 38
0
 def run_server(self):
     wsgi.server(eventlet.listen(('', 8800)), self.wsgi_app, max_size=50)
Exemplo n.º 39
0
def test_reuse_random_port_warning():
    with warnings.catch_warnings(record=True) as w:
        eventlet.listen(('localhost', 0), reuse_port=True).close()
        assert len(w) == 1
        assert issubclass(w[0].category, convenience.ReuseRandomPortWarning)
Exemplo n.º 40
0
import eventlet
import json
from eventlet import wsgi


def serve(env, start_response):
    if env['PATH_INFO'] != '/':
        start_response('404 Not Found', [('Content-Type', 'text/plain')])
        return ['Not found']

    start_response('200 OK', [('Content-Type', 'application/json')])
    f = open()
    response = json.dumps({'tweets': 'hello world'})
    return [response]


if __name__ == '__main__':
    wsgi.server(eventlet.listen(('127.0.0.1', 8090)), serve)
Exemplo n.º 41
0
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Remote Driving')
    parser.add_argument(
        'image_folder',
        type=str,
        nargs='?',
        default='',
        help=
        'Path to image folder. This is where the images from the run will be saved.'
    )
    args = parser.parse_args()

    #os.system('rm -rf IMG_stream/*')
    if args.image_folder != '':
        print("Creating image folder at {}".format(args.image_folder))
        if not os.path.exists(args.image_folder):
            os.makedirs(args.image_folder)
        else:
            shutil.rmtree(args.image_folder)
            os.makedirs(args.image_folder)
        print("Recording this run ...")
    else:
        print("NOT recording this run ...")

    # wrap Flask application with socketio's middleware
    app = socketio.Middleware(sio, app)

    # deploy as an eventlet WSGI server
    eventlet.wsgi.server(eventlet.listen(('', 4567)), app)
Exemplo n.º 42
0
    if is_number(data["a"]) and is_number(data["b"]):
        a = float(data["a"])
        b = float(data["b"])
        if a + b == sphere.spin():
            did_split = the_spheres.split_child(sphere, a, b)
            reset_options()
            options["show_others"] = True
            sio.emit("collapsed", json.dumps({"message": "split!"}))


@sio.on("penrose")
def penrose(sid, data):
    global the_spheres
    global sphere
    sio.emit("angles", {"angles": the_spheres.pretty_penrose()})


@sio.on("iterated_majorana")
def iterated_majorana(sid, data):
    global options
    options["iterated_majorana"] = True if options[
        "iterated_majorana"] == False else False


##################################################################################################################

if __name__ == '__main__':
    app = socketio.Middleware(sio, app)
    port = int(sys.argv[1])
    eventlet.wsgi.server(eventlet.listen(('', port)), app)
Exemplo n.º 43
0
#!/usr/bin/env python
#-*- coding:utf-8 -*-

# http://wsfdl.com/openstack/2013/10/18/%E7%90%86%E8%A7%A3nova-api%E7%9A%84WSGI%E6%A1%86%E6%9E%B6.html

import eventlet
from eventlet import wsgi


class AnimalApplication(object):
    def __init__(self):
        pass

    def __call__(self, environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/plain')])
        return ['This is a animal application!\r\n']


if __name__ == '__main__':
    application = AnimalApplication()
    server = eventlet.spawn(
        wsgi.server,
        # eventlet.listen(('0.0.0.0', 8080)), application)
        eventlet.listen(('', 8080)),
        application)
    server.wait()
Exemplo n.º 44
0
    def start(self, application, file_socket, workers, backlog):
        self._socket = eventlet.listen(file_socket,
                                       family=socket.AF_UNIX,
                                       backlog=backlog)

        self._launch(application, workers=workers)
'''
Taken from the documentation:
http://eventlet.net/doc/modules/websocket.html
And from this example:
http://eventlet.net/doc/examples.html#websocket-server-example
'''

import eventlet
from eventlet import wsgi
from eventlet import websocket

SERVER_HOSTNAME = '127.0.0.1'
SERVER_PORT = 8090


@websocket.WebSocketWSGI
def application(ws):
    while True:
        # http://eventlet.net/doc/modules/websocket.html#eventlet.websocket.WebSocket.wait
        message = ws.wait()
        if message is None:
            break
        ws.send(message)


if __name__ == '__main__':
    listener = eventlet.listen((SERVER_HOSTNAME, SERVER_PORT))
    wsgi.server(listener, application)
Exemplo n.º 46
0
import eventlet


def handle(fd):
    # 单个协程的处理器
    print('clientd connected')
    while True:
        # pass through every non-eof line
        x = fd.readline()
        if not x:
            break
        fd.write(x)
        fd.flush()
        print("echoed", x, end=' ')
    print("client disconnected")


print("server socket listening on port 6000")
server = eventlet.listen(('0.0.0.0', 6000))
#监听 6000 端口
pool = eventlet.GreenPool()
# 构造协程池
while True:
    try:
        new_sock, address = server.accept()
        # accept 新的连接
        print("accepted", address)
        pool.spawn(handle, new_sock.makefile('rw'))
        # 将新的连接交由一个新的协程去处理
    except (SystemExit, KeyboardInterrupt):
        break
Exemplo n.º 47
0
def create_app(main_module: bool = False):
    app = Flask(__name__, static_url_path='/static', static_folder='static')
    
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = os.path.abspath(
        'limonero/i18n/locales')
    app.json_encoder = LimoneroJSONEncoder
    
    babel = Babel(app)
    
    logging.config.fileConfig('logging_config.ini')
    
    app.secret_key = 'l3m0n4d1'
    
    
    # Cryptography key
    app.download_key = Fernet.generate_key()
    app.fernet = Fernet(app.download_key)
    
    
    # Cache
    cache.init_app(app)
    
    # CORS
    CORS(app, resources={r"/*": {"origins": "*"}})
    api = Api(app)
    
    # Swagger
    swaggerui_blueprint = get_swaggerui_blueprint(
        '/api/docs',  
        '/static/swagger.yaml',
        config={  # Swagger UI config overrides
            'app_name': "Lemonade Caipirinha"
        },
        # oauth_config={  # OAuth config. See https://github.com/swagger-api/swagger-ui#oauth2-configuration .
        #    'clientId': "your-client-id",
        #    'clientSecret': "your-client-secret-if-required",
        #    'realm': "your-realms",
        #    'appName': "your-app-name",
        #    'scopeSeparator': " ",
        #    'additionalQueryStringParams': {'test': "hello"}
        # }
    )
    
    app.register_blueprint(swaggerui_blueprint)
    
    mappings = {
        '/datasources': DataSourceListApi,
        '/datasources/upload': DataSourceUploadApi,
        '/datasources/infer-schema/<int:data_source_id>': DataSourceInferSchemaApi,
        '/datasources/sample/<int:data_source_id>': DataSourceSampleApi,
        '/datasources/initialize/<status>/<int:data_source_id>': 
            DataSourceInitializationApi,
        '/datasources/<int:data_source_id>': DataSourceDetailApi,
        '/datasources/<int:data_source_id>/permission/<int:user_id>':
            DataSourcePermissionApi,
        '/datasources/<int:data_source_id>/privacy': DataSourcePrivacyApi,
        '/privacy': GlobalPrivacyListApi,
        '/privacy/attribute-groups': AttributePrivacyGroupListApi,
        '/models': ModelListApi,
        '/models/<int:model_id>': ModelDetailApi,
    
        '/storages': StorageListApi,
        '/storages/<int:storage_id>': StorageDetailApi,
        '/storages/metadata/<int:storage_id>': StorageMetadataApi,
    }
    grouped_mappings = itertools.groupby(sorted(mappings.items()),
                                         key=lambda path: path[1])
    for view, g in grouped_mappings:
        api.add_resource(view, *[x[0] for x in g], endpoint=view.__name__)
    
    app.add_url_rule('/datasources/public/<int:data_source_id>/download',
                     methods=['GET'], endpoint='DataSourceDownload',
                     view_func=DataSourceDownload.as_view('download'))

    app.add_url_rule('/models/<int:model_id>/download',
                     methods=['GET'], endpoint='ModelDownloadApi',
                     view_func=ModelDownloadApi.as_view('download_model'))
    migrate = Migrate(app, db)
    app.handle_exception

    @babel.localeselector
    def get_locale():
        user = getattr(flask_g, 'user', None)
        if user is not None and user.locale:
            return user.locale
        else:
            return request.args.get(
                'lang', request.accept_languages.best_match(['en', 'pt', 'es']))
    
    sqlalchemy_utils.i18n.get_locale = get_locale

    config_file = None
    signal.signal(signal.SIGINT, exit_gracefully)
    if main_module:
        parser = argparse.ArgumentParser()
        parser.add_argument("-c", "--config", type=str,
                            help="Config file", required=False)
        args = parser.parse_args()
        config_file = args.config

    if config_file is None:
        config_file = os.environ.get('LIMONERO_CONFIG')

    logger = logging.getLogger(__name__)
    if config_file:
        with open(config_file) as f:
            config = yaml.load(f, Loader=yaml.FullLoader)['limonero']

        app.config['LIMONERO_CONFIG'] = config
        app.config["RESTFUL_JSON"] = {"cls": app.json_encoder}

        server_config = config.get('servers', {})
        app.config['SQLALCHEMY_DATABASE_URI'] = server_config.get(
            'database_url')
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

        is_mysql = 'mysql://' in app.config['SQLALCHEMY_DATABASE_URI']
        if config.get('config') is not None and 'config' in config and is_mysql:
            app.config.update(config.get('config', {}))
            app.config['SQLALCHEMY_POOL_SIZE'] = 10
            app.config['SQLALCHEMY_POOL_RECYCLE'] = 240

        db.init_app(app)

        port = int(config.get('port', 5000))
        logger.debug(
            gettext('Running in %(mode)s mode', mode=config.get('environment')))

        init_jvm(app, logger)
        if main_module:
            # JVM, used to interact with HDFS.
            if config.get('environment', 'dev') == 'dev':
                app.run(debug=True, port=port, host='0.0.0.0')
            else:
                eventlet.wsgi.server(eventlet.listen(('', port)), app)
        else:
            return app    
    else:
        logger.error(
            gettext('Please, set LIMONERO_CONFIG environment variable'))
        exit(1)
    return app
Exemplo n.º 48
0
    def sendData(self):
        pi.set_servo_pulsewidth(14, self.throttle)
        pi.set_servo_pulsewidth(15, self.roll)
        pi.set_servo_pulsewidth(17, self.pitch)
        pi.set_servo_pulsewidth(18, self.yaw)

    def printData(self):
        print(self.throttle)
        print(self.roll)
        print(self.pitch)
        print(self.yaw)
        print("")


sio = socketio.Server(async_mode='eventlet')
pwm = PWMSoftware()


@sio.on('send data')
def message(sid, data):
    print(data)
    data1 = json.loads(data)
    pwm.convertData(data1['command'], data1['speed'], data1['angle'])


##    pwm.printData()

app = socketio.Middleware(sio)
eventlet.wsgi.server(eventlet.listen(('localhost', 8000)), app)
Exemplo n.º 49
0
if __name__ == '__main__':
    from eventlet import monkey_patch, wsgi
    import eventlet
    eventlet.sleep()
    monkey_patch()
    from wsgi_benchmark.handlers import app

    wsgi.server(eventlet.listen(('0.0.0.0', 8765)), app)
Exemplo n.º 50
0
def detect_face(imageStream):
    # image = Image.open(io.BytesIO(image_data))
    # with open(str(time.time())+'.jpg','wb+') as f:
    #  f.write(imageStream)
    image = face_recognition.load_image_file(io.BytesIO(imageStream))

    face_locations = face_recognition.face_locations(image)
    frames = []
    for face_location in face_locations:
        top, right, bottom, left = face_location
        # print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

        newFrame = {}
        newFrame['x'] = left
        newFrame['y'] = top
        newFrame['w'] = right - left
        newFrame['h'] = top - bottom
        newFrame['label'] = 'face'
        frames.append(newFrame)
    print('finish detection!')
    return frames


if __name__ == '__main__':

    # wrap Flask application with socketio's middleware
    app = socketio.Middleware(sio, app)

    # deploy as an eventlet WSGI server
    eventlet.wsgi.server(eventlet.listen(('', 8000)), app)
Exemplo n.º 51
0
def in_process_setup(the_object_server=object_server):
    _info('IN-PROCESS SERVERS IN USE FOR FUNCTIONAL TESTS')
    _info('Using object_server class: %s' % the_object_server.__name__)
    conf_src_dir = os.environ.get('SWIFT_TEST_IN_PROCESS_CONF_DIR')

    if conf_src_dir is not None:
        if not os.path.isdir(conf_src_dir):
            msg = 'Config source %s is not a dir' % conf_src_dir
            raise InProcessException(msg)
        _info('Using config source dir: %s' % conf_src_dir)

    # If SWIFT_TEST_IN_PROCESS_CONF specifies a config source dir then
    # prefer config files from there, otherwise read config from source tree
    # sample files. A mixture of files from the two sources is allowed.
    proxy_conf = _in_process_find_conf_file(conf_src_dir, 'proxy-server.conf')
    _info('Using proxy config from %s' % proxy_conf)
    swift_conf_src = _in_process_find_conf_file(conf_src_dir, 'swift.conf')
    _info('Using swift config from %s' % swift_conf_src)

    monkey_patch_mimetools()

    global _testdir
    _testdir = os.path.join(mkdtemp(), 'tmp_functional')
    utils.mkdirs(_testdir)
    rmtree(_testdir)
    utils.mkdirs(os.path.join(_testdir, 'sda1'))
    utils.mkdirs(os.path.join(_testdir, 'sda1', 'tmp'))
    utils.mkdirs(os.path.join(_testdir, 'sdb1'))
    utils.mkdirs(os.path.join(_testdir, 'sdb1', 'tmp'))

    swift_conf = _in_process_setup_swift_conf(swift_conf_src, _testdir)
    obj_sockets = _in_process_setup_ring(swift_conf, conf_src_dir, _testdir)

    global orig_swift_conf_name
    orig_swift_conf_name = utils.SWIFT_CONF_FILE
    utils.SWIFT_CONF_FILE = swift_conf
    constraints.reload_constraints()
    storage_policy.SWIFT_CONF_FILE = swift_conf
    storage_policy.reload_storage_policies()
    global config
    if constraints.SWIFT_CONSTRAINTS_LOADED:
        # Use the swift constraints that are loaded for the test framework
        # configuration
        _c = dict(
            (k, str(v)) for k, v in constraints.EFFECTIVE_CONSTRAINTS.items())
        config.update(_c)
    else:
        # In-process swift constraints were not loaded, somethings wrong
        raise SkipTest
    global orig_hash_path_suff_pref
    orig_hash_path_suff_pref = utils.HASH_PATH_PREFIX, utils.HASH_PATH_SUFFIX
    utils.validate_hash_conf()

    # We create the proxy server listening socket to get its port number so
    # that we can add it as the "auth_port" value for the functional test
    # clients.
    prolis = eventlet.listen(('localhost', 0))

    # The following set of configuration values is used both for the
    # functional test frame work and for the various proxy, account, container
    # and object servers.
    config.update({
        # Values needed by the various in-process swift servers
        'devices': _testdir,
        'swift_dir': _testdir,
        'mount_check': 'false',
        'client_timeout': '4',
        'allow_account_management': 'true',
        'account_autocreate': 'true',
        'allow_versions': 'True',
        # Below are values used by the functional test framework, as well as
        # by the various in-process swift servers
        'auth_host': '127.0.0.1',
        'auth_port': str(prolis.getsockname()[1]),
        'auth_ssl': 'no',
        'auth_prefix': '/auth/',
        # Primary functional test account (needs admin access to the
        # account)
        'account': 'test',
        'username': '******',
        'password': '******',
        # User on a second account (needs admin access to the account)
        'account2': 'test2',
        'username2': 'tester2',
        'password2': 'testing2',
        # User on same account as first, but without admin access
        'username3': 'tester3',
        'password3': 'testing3',
        # Service user and prefix (emulates glance, cinder, etc. user)
        'account5': 'test5',
        'username5': 'tester5',
        'password5': 'testing5',
        'service_prefix': 'SERVICE',
        # For tempauth middleware. Update reseller_prefix
        'reseller_prefix': 'AUTH, SERVICE',
        'SERVICE_require_group': 'service'
    })

    acc1lis = eventlet.listen(('localhost', 0))
    acc2lis = eventlet.listen(('localhost', 0))
    con1lis = eventlet.listen(('localhost', 0))
    con2lis = eventlet.listen(('localhost', 0))

    account_ring_path = os.path.join(_testdir, 'account.ring.gz')
    with closing(GzipFile(account_ring_path, 'wb')) as f:
        pickle.dump(
            ring.RingData([[0, 1, 0, 1], [1, 0, 1, 0]],
                          [{
                              'id': 0,
                              'zone': 0,
                              'device': 'sda1',
                              'ip': '127.0.0.1',
                              'port': acc1lis.getsockname()[1]
                          }, {
                              'id': 1,
                              'zone': 1,
                              'device': 'sdb1',
                              'ip': '127.0.0.1',
                              'port': acc2lis.getsockname()[1]
                          }], 30), f)
    container_ring_path = os.path.join(_testdir, 'container.ring.gz')
    with closing(GzipFile(container_ring_path, 'wb')) as f:
        pickle.dump(
            ring.RingData([[0, 1, 0, 1], [1, 0, 1, 0]],
                          [{
                              'id': 0,
                              'zone': 0,
                              'device': 'sda1',
                              'ip': '127.0.0.1',
                              'port': con1lis.getsockname()[1]
                          }, {
                              'id': 1,
                              'zone': 1,
                              'device': 'sdb1',
                              'ip': '127.0.0.1',
                              'port': con2lis.getsockname()[1]
                          }], 30), f)

    eventlet.wsgi.HttpProtocol.default_request_version = "HTTP/1.0"
    # Turn off logging requests by the underlying WSGI software.
    eventlet.wsgi.HttpProtocol.log_request = lambda *a: None
    logger = utils.get_logger(config, 'wsgi-server', log_route='wsgi')
    # Redirect logging other messages by the underlying WSGI software.
    eventlet.wsgi.HttpProtocol.log_message = \
        lambda s, f, *a: logger.error('ERROR WSGI: ' + f % a)
    # Default to only 4 seconds for in-process functional test runs
    eventlet.wsgi.WRITE_TIMEOUT = 4

    acc1srv = account_server.AccountController(config,
                                               logger=debug_logger('acct1'))
    acc2srv = account_server.AccountController(config,
                                               logger=debug_logger('acct2'))
    con1srv = container_server.ContainerController(
        config, logger=debug_logger('cont1'))
    con2srv = container_server.ContainerController(
        config, logger=debug_logger('cont2'))

    objsrvs = [(obj_sockets[index],
                the_object_server.ObjectController(config,
                                                   logger=debug_logger(
                                                       'obj%d' % (index + 1))))
               for index in range(len(obj_sockets))]

    logger = debug_logger('proxy')

    def get_logger(name, *args, **kwargs):
        return logger

    with mock.patch('swift.common.utils.get_logger', get_logger):
        with mock.patch('swift.common.middleware.memcache.MemcacheMiddleware',
                        FakeMemcacheMiddleware):
            try:
                app = loadapp(proxy_conf, global_conf=config)
            except Exception as e:
                raise InProcessException(e)

    nl = utils.NullLogger()
    prospa = eventlet.spawn(eventlet.wsgi.server, prolis, app, nl)
    acc1spa = eventlet.spawn(eventlet.wsgi.server, acc1lis, acc1srv, nl)
    acc2spa = eventlet.spawn(eventlet.wsgi.server, acc2lis, acc2srv, nl)
    con1spa = eventlet.spawn(eventlet.wsgi.server, con1lis, con1srv, nl)
    con2spa = eventlet.spawn(eventlet.wsgi.server, con2lis, con2srv, nl)

    objspa = [
        eventlet.spawn(eventlet.wsgi.server, objsrv[0], objsrv[1], nl)
        for objsrv in objsrvs
    ]

    global _test_coros
    _test_coros = \
        (prospa, acc1spa, acc2spa, con1spa, con2spa) + tuple(objspa)

    # Create accounts "test" and "test2"
    def create_account(act):
        ts = utils.normalize_timestamp(time())
        account_ring = Ring(_testdir, ring_name='account')
        partition, nodes = account_ring.get_nodes(act)
        for node in nodes:
            # Note: we are just using the http_connect method in the object
            # controller here to talk to the account server nodes.
            conn = swift.proxy.controllers.obj.http_connect(
                node['ip'], node['port'], node['device'], partition, 'PUT',
                '/' + act, {
                    'X-Timestamp': ts,
                    'x-trans-id': act
                })
            resp = conn.getresponse()
            assert (resp.status == 201)

    create_account('AUTH_test')
    create_account('AUTH_test2')
Exemplo n.º 52
0
import os
import sys
if os.environ.get('FLASK_ENV') == "production":
    import eventlet
    eventlet.monkey_patch()
    from eventlet import wsgi
from app import app, init
from db import init_db
from util import get_logger

logger = get_logger('user')
app.logger = logger

init(app)
init_db(app)

if __name__ == '__main__':
    app.logger.info("Starting server")
    if os.environ.get('FLASK_ENV') == "production":
        wsgi.server(eventlet.listen(('0.0.0.0', app.config['PORT'])), app, debug=False, log_output=False)
    else:
        app.run(port=app.config['PORT'])
Exemplo n.º 53
0
                return app

    def __call__(self,environ, start_response):
      
        path = environ.get('PATH_INFO','/')
        method = environ.get('REQUEST_METHOD')
        contenttype = environ.get('CONTENT_TYPE')
        environ['QUEUE_CHANNEL'] = self.channel

        #Restful web requests:
        app = RestfulMethod(method)
        if app:
            return app(environ, start_response)
        else:
            start_response("404 NOT FOUND",[('Content-type', 'text/plain')])
            return ["Page dose not exists!"]

app = Dispatcher()

# option 1
#from  wsgiref import make_server
#httpd = make_server('', 8910, app)
#print "Serving on port 8910..."
#httpd.serve_forever()


#option 2
wsgi.server(eventlet.listen(('127.0.0.1',8910)), app)


Exemplo n.º 54
0
def _in_process_setup_ring(swift_conf, conf_src_dir, testdir):
    """
    If SWIFT_TEST_POLICY is set:
    - look in swift.conf file for specified policy
    - move this to be policy-0 but preserving its options
    - copy its ring file to test dir, changing its devices to suit
      in process testing, and renaming it to suit policy-0
    Otherwise, create a default ring file.
    """
    conf = ConfigParser()
    conf.read(swift_conf)
    sp_prefix = 'storage-policy:'

    try:
        # policy index 0 will be created if no policy exists in conf
        policies = parse_storage_policies(conf)
    except PolicyError as e:
        raise InProcessException(e)

    # clear all policies from test swift.conf before adding test policy back
    for policy in policies:
        conf.remove_section(sp_prefix + str(policy.idx))

    policy_specified = os.environ.get('SWIFT_TEST_POLICY')
    if policy_specified:
        policy_to_test = policies.get_by_name(policy_specified)
        if policy_to_test is None:
            raise InProcessException('Failed to find policy name "%s"' %
                                     policy_specified)
        _info('Using specified policy %s' % policy_to_test.name)
    else:
        policy_to_test = policies.default
        _info('Defaulting to policy %s' % policy_to_test.name)

    # make policy_to_test be policy index 0 and default for the test config
    sp_zero_section = sp_prefix + '0'
    conf.add_section(sp_zero_section)
    for (k, v) in policy_to_test.get_options().items():
        conf.set(sp_zero_section, k, v)
    conf.set(sp_zero_section, 'default', True)

    with open(swift_conf, 'w') as fp:
        conf.write(fp)

    # look for a source ring file
    ring_file_src = ring_file_test = 'object.ring.gz'
    if policy_to_test.idx:
        ring_file_src = 'object-%s.ring.gz' % policy_to_test.idx
    try:
        ring_file_src = _in_process_find_conf_file(conf_src_dir,
                                                   ring_file_src,
                                                   use_sample=False)
    except InProcessException as e:
        if policy_specified:
            raise InProcessException('Failed to find ring file %s' %
                                     ring_file_src)
        ring_file_src = None

    ring_file_test = os.path.join(testdir, ring_file_test)
    if ring_file_src:
        # copy source ring file to a policy-0 test ring file, re-homing servers
        _info('Using source ring file %s' % ring_file_src)
        ring_data = ring.RingData.load(ring_file_src)
        obj_sockets = []
        for dev in ring_data.devs:
            device = 'sd%c1' % chr(len(obj_sockets) + ord('a'))
            utils.mkdirs(os.path.join(_testdir, 'sda1'))
            utils.mkdirs(os.path.join(_testdir, 'sda1', 'tmp'))
            obj_socket = eventlet.listen(('localhost', 0))
            obj_sockets.append(obj_socket)
            dev['port'] = obj_socket.getsockname()[1]
            dev['ip'] = '127.0.0.1'
            dev['device'] = device
            dev['replication_port'] = dev['port']
            dev['replication_ip'] = dev['ip']
        ring_data.save(ring_file_test)
    else:
        # make default test ring, 2 replicas, 4 partitions, 2 devices
        _info('No source object ring file, creating 2rep/4part/2dev ring')
        obj_sockets = [eventlet.listen(('localhost', 0)) for _ in (0, 1)]
        ring_data = ring.RingData([[0, 1, 0, 1], [1, 0, 1, 0]],
                                  [{
                                      'id': 0,
                                      'zone': 0,
                                      'device': 'sda1',
                                      'ip': '127.0.0.1',
                                      'port': obj_sockets[0].getsockname()[1]
                                  }, {
                                      'id': 1,
                                      'zone': 1,
                                      'device': 'sdb1',
                                      'ip': '127.0.0.1',
                                      'port': obj_sockets[1].getsockname()[1]
                                  }], 30)
        with closing(GzipFile(ring_file_test, 'wb')) as f:
            pickle.dump(ring_data, f)

    for dev in ring_data.devs:
        _debug('Ring file dev: %s' % dev)

    return obj_sockets
Exemplo n.º 55
0
        dbg.debug("req.body is %s",req.body)
        dbg.debug("headers is %s" , req.headers)
        dbg.debug("headers.type is %s", content_type)
        dbg.debug("headers.length is %s" ,content_length)
        dbg.debug("host is %s" , host)
        dbg.debug("params is %s" , params)
        dbg.debug("req.params is %s" , req.params)
        dbg.debug("params_1 is %s" , params_1)
        dbg.debug("params_sig is %s" , params_sig)
        dbg.debug("params_ts is %s" , params_ts)
        dbg.debug("params_nonce is %s" , params_nonce)
        dbg.debug("params_echostr is %s" , params_echostr)
        dbg.debug("method is %s" , method )
        dbg.debug("args.id is %s" , args['id'])
        dbg.debug("args is %s" , args)
        #return 'uploaded!')

        return params_echostr
'''

if __name__ == '__main__':
    dbg.debug("Weclome!")
    sock = eventlet.listen(('119.84.78.194', 80))
    #sock = eventlet.listen(('', 12345))
    map = routes.Mapper()
    map.connect('/v1.0/{action}/{id}', controller=API())
    eventlet.wsgi.server(
        sock,
        routes.middleware.RoutesMiddleware(
            ParsedRoutes(webob.exc.HTTPNotFound()), map))
Exemplo n.º 56
0
@sio.event
def ctrl(sid, data):
    print('ctrl ', data)
    carControl.ctrl(data)


@sio.event
def set(sid, data):
    print('set ', data)
    carControl.set(data)


@sio.event
def ping(sid, data):
    #print('ping', data)
    sio.emit('ping', data)


@sio.event
def exec(sid, data):
    print('exec ', data)
    functionControl.execute(data['cmd'])


if __name__ == '__main__':
    ip = get_ip.getIp()
    socket = eventlet.listen((ip, 12306))  #3 监听端口
    eventlet.wsgi.server(socket, app)  #4 启动服务器
    # eventlet是一个协程库, 其中提供了服务器代码, 而且该服务器支持websocket协议的
Exemplo n.º 57
0
        return [img_data]

    elif environ['PATH_INFO'] == '/WASM_Client.js':
        print('PATH_INFO == \'/WASM_Client.js\'')
        str_data = open(
            os.path.join(os.path.dirname(__file__),
                         'mysite/static/WASM_Client.js')).read()
        start_response('200 OK', [('content-type', 'application/javascript')])
        return [str_data]

    elif environ['PATH_INFO'] == '/WASM_Client.wasm':
        print('PATH_INFO == \'/WASM_Client.wasm\'')
        bin_data = open(
            os.path.join(os.path.dirname(__file__),
                         'mysite/static/WASM_Client.wasm'), 'rb').read()
        start_response('200 OK', [('content-type', 'application/wasm')])
        return [bin_data]

    else:
        path_info = environ['PATH_INFO']
        print('PATH_INFO = {}'.format(path_info))
        return None


if __name__ == '__main__':
    listener = eventlet.listen(('127.0.0.1', 7000))
    print(
        '\nVisit http://localhost:7000/ in your websocket-capable browser.\n')
    wsgi.server(listener, dispatch)
Exemplo n.º 58
0
    print a message in the console (for debug reasons).
    """
    global connected_users
    connected_users += 1
    print("[*] New device connected! (Total: {0})".format(connected_users))


@socketio.on('move_car', namespace='')
def move_car(received_data):
    movedir = received_data['direction']
    print(movedir)

    active_connection.send_data(movedir)


@socketio.on('disconnect', namespace='')
def test_disconnect():
    """
    In this method we keep track of the connected users. For
    any new devices disconnected to the application server, we
    decrement the global variable for the connected users and
    print a message in the console (for debug reasons).
    """
    global connected_users
    connected_users -= 1
    print("[*] Client disconnected! (Total: {0})".format(connected_users))


if __name__ == '__main__':
    wsgi.server(eventlet.listen((serverInfo.host, serverInfo.port)), app)
Exemplo n.º 59
0
 def start(self):
     """fire up the app"""
     wsgi.server(listen((self.wsgi_address, self.wsgi_port)),
                 self.handle_request,
                 log=self.request_logger)
 def start_server(self):
     eventlet.wsgi.server(eventlet.listen((self.url, self.port)), self.app)