Exemplo n.º 1
0
def start(port=35729):
    global PORT
    PORT = port
    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()
    app = Application(handlers=handlers)
    app.listen(port)
    print("Start service at  127.0.0.1:%s" % port)
    ioloop.IOLoop.instance().start()
Exemplo n.º 2
0
def start(port):
    global PORT
    PORT = port
    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()
    app = Application(handlers=handlers)
    app.listen(port)
    print('Start service at  127.0.0.1:%s' % port)
    ioloop.IOLoop.instance().start()
Exemplo n.º 3
0
Arquivo: backend.py Projeto: smvv/trs
def start_server(app, port):
    from tornado.ioloop import IOLoop
    from tornado.options import enable_pretty_logging

    enable_pretty_logging()

    try:
        app.listen(port)
        IOLoop.instance().start()
    except KeyboardInterrupt:
        pass
Exemplo n.º 4
0
Arquivo: backend.py Projeto: smvv/trs
def start_server(app, port):
    from tornado.ioloop import IOLoop
    from tornado.options import enable_pretty_logging

    enable_pretty_logging()

    try:
        app.listen(port)
        IOLoop.instance().start()
    except KeyboardInterrupt:
        pass
Exemplo n.º 5
0
def start(port=35729, root='.'):
    global PORT
    PORT = port
    global ROOT
    if root is None:
        root = '.'
    ROOT = root
    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()
    app = Application(handlers=handlers)
    app.listen(port)
    print('Serving path %s on 127.0.0.1:%s' % (root, port))
    webbrowser.open('http://localhost:%s' % port, new=2, autoraise=True)
    ioloop.IOLoop.instance().start()
Exemplo n.º 6
0
def start(port=35729, root=".", autoraise=False):
    global PORT
    PORT = port
    global ROOT
    if root is None:
        root = "."
    ROOT = root
    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()
    app = Application(handlers=handlers)
    app.listen(port)
    print("Serving path %s on 127.0.0.1:%s" % (root, port))

    if autoraise:
        webbrowser.open("http://127.0.0.1:%s" % port, new=2, autoraise=True)
    ioloop.IOLoop.instance().start()
Exemplo n.º 7
0
def start(port=35729, root='.', autoraise=False):
    global PORT
    PORT = port
    global ROOT
    if root is None:
        root = '.'
    ROOT = root
    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()
    app = Application(handlers=handlers)
    app.listen(port)
    print('Serving path %s on 127.0.0.1:%s' % (root, port))

    if autoraise:
        webbrowser.open('http://127.0.0.1:%s' % port, new=2, autoraise=True)
    ioloop.IOLoop.instance().start()
Exemplo n.º 8
0
def main ():
    
    """
    Main Method

    Will load the logging and other related classes then
    parse our given command and route to the proper responders.

    Note
    """
    
    #   Turn on Pretty Logging
    enable_pretty_logging()
    parse_command_line()
    
    #   Now lets route this to the appropriate command
    route()
Exemplo n.º 9
0
def tornadorun(webpy_app, port=8080):
    """Run web.py application using tornado."""
    from tornado.options import enable_pretty_logging
    import logging

    patch_webpy()

    # enable pretty logging
    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()

    application = Application([
        (r"/static/(.*)", StaticFileHandler, {'path': 'static'}),
        (r"/.*", WebpyHandler, {'webpy_app': webpy_app}),
    ])
    server = tornado.httpserver.HTTPServer(application)
    server.listen(int(port))
    print "http://0.0.0.0:%d" % port
    IOLoop.instance().start()
Exemplo n.º 10
0
def setup_logging(config, debug=False):
    """
    Setup the logging module to respect our configuration values.
    Expects a dictionary called config with the following parameters

    * directory:   Optional log file output directory
    * filename:    Optional filename, not needed for syslog
    * format:      Format for non-debug mode
    * level:       One of debug, error, warning, info
    * handler:     Optional handler
    * syslog:      If handler == syslog, parameters for syslog
      * address:   Syslog address
      * facility:  Syslog facility

    Passing in debug=True will disable any log output to anything but stdout
    and will set the log level to debug regardless of the config.
    """
    # Set logging levels dictionary
    logging_levels = {
        "debug": logging.DEBUG,
        "info": logging.INFO,
        "warning": logging.WARNING,
        "error": logging.ERROR,
        "critical": logging.CRITICAL,
    }

    # Get the logging value from the dictionary
    logging_level = config["level"]

    if debug:

        # Override the logging level to use debug mode
        config["level"] = logging.DEBUG

        # If we have specified a file, remove it so logging info goes to stdout
        if "filename" in config:
            del config["filename"]

    else:

        # Use the configuration option for logging
        config["level"] = logging_levels.get(config["level"], logging.NOTSET)

    # Pass in our logging config
    logging.basicConfig(**config)
    logging.info("Log level set to %s" % logging_level)

    # Get the default logger
    default_logging = logging.getLogger()

    # Remove the default stream handler
    stream_handler = None
    for handler in default_logging.handlers:
        if isinstance(handler, logging.StreamHandler):
            stream_handler = handler
            break

    # Use colorized output
    if config["level"] == logging.DEBUG:
        enable_pretty_logging()

    # If we have supported handler
    elif "handler" in config:

        # If we want to syslog
        if config["handler"] == "syslog":

            facility = config["syslog"]["facility"]
            import logging.handlers as handlers

            # If we didn't type in the facility name
            if facility in handlers.SysLogHandler.facility_names:

                # Create the syslog handler
                address = config["syslog"]["address"]
                facility = handlers.SysLogHandler.facility_names[facility]
                syslog = handlers.SysLogHandler(address=address, facility=facility)
                # Add the handler
                default_logging.addHandler(syslog)

                # Remove the StreamHandler
                if stream_handler:
                    default_logging.removeHandler(stream_handler)
            else:
                logging.error("%s:Invalid facility, syslog logging aborted", application_name())
    parser = argparse.ArgumentParser(description='Start Apertium APY Gateway')
    parser.add_argument('serverlist', help='path to file with list of servers and ports available')
    parser.add_argument('-t', '--tests', help='perform tests on server pool', action='store_true', default=False)
    parser.add_argument('-p', '--port', help='port to run gateway on (default = 2738)', type=int, default=2738)
    parser.add_argument('-c', '--ssl-cert', help='path to SSL Certificate', default=None)
    parser.add_argument('-k', '--ssl-key', help='path to SSL Key File', default=None)
    parser.add_argument('-d', '--debug', help='debug mode (do not verify SSL certs)', action='store_false', default=True)
    parser.add_argument('-j', '--num-processes', help='number of processes to run (default = number of cores)', type=int, default=0)
    parser.add_argument('-i', '--test-interval', help='interval to perform tests in ms (default = 3600000)', type=int, default=3600000)
    args = parser.parse_args()

    global verify_ssl_cert
    verify_ssl_cert = args.debug

    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()

    # read the serverlist file
    try:
        with open(args.serverlist) as serverlist:
            server_port_list = []
            for server_port_pair in serverlist:
                if server_port_pair[0] != '#':  # filter out the commented lines
                    srv, port = server_port_pair.rsplit(':', 1)
                    server_port_list.append((srv, int(port)))
    except IOError:
        logging.critical('Could not open serverlist: %s', args.serverlist)
        sys.exit(-1)

    if len(server_port_list) == 0:
        logging.critical('Serverlist must not be empty')
Exemplo n.º 12
0
        help='number of processes to run (default = number of cores)',
        type=int,
        default=0)
    parser.add_argument(
        '-i',
        '--test-interval',
        help='interval to perform tests in ms (default = 3600000)',
        type=int,
        default=3600000)
    args = parser.parse_args()

    global verify_ssl_cert
    verify_ssl_cert = args.debug

    logging.getLogger().setLevel(logging.INFO)
    enable_pretty_logging()

    # read the serverlist file
    try:
        with open(args.serverlist) as serverlist:
            server_port_list = []
            for server_port_pair in serverlist:
                if server_port_pair[0] != '#':  # filter out the commented lines
                    srv, port = server_port_pair.rsplit(':', 1)
                    server_port_list.append((srv, int(port)))
    except IOError:
        logging.critical('Could not open serverlist: %s', args.serverlist)
        sys.exit(-1)

    if len(server_port_list) == 0:
        logging.critical('Serverlist must not be empty')
Exemplo n.º 13
0
    def run(self, *args, **options):
        from django.conf import settings
        
        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'

        conf = defaults.copy()
        conf.update(getattr(settings, 'PUSH_SERVER', {}))

        if self.port:
            conf['port'] = self.port
        if self.address:
            conf['address'] = self.address

        if not conf['port']:
            conf['port'] = ALL_REQUESTS_DEFAULT_PORT if self.allrequests else DEFAULT_PORT
        if not conf['address']:
            conf['address'] = DEFAULT_IPV6_ADDRESS if self.use_ipv6 else DEFAULT_IPV4_ADDRESS

        if self._raw_ipv6 or (re.search(r'^[a-fA-F0-9:]+$', conf['address']) is not None and ':' in conf['address']):
            # Raw IPv6 address
            address = '[%s]' % conf['address']
        else:
            address = conf['address']

        self.stdout.write((
            "Django version %(version)s, using settings %(settings)r\n"
            "Push server version %(push_version)s on Tornado version %(tornado_version)s\n"
            "Development push server is running at http://%(address)s:%(port)s/\n"
            "Quit the server with %(quit_command)s.\n"
        ) % {
            "version": self.get_version(),
            "push_version": hbpush.__version__,
            "tornado_version": tornado.version,
            "settings": settings.SETTINGS_MODULE,
            "address": address,
            "port": conf['port'],
            "quit_command": quit_command,
        })

        updates.current_host = '%s:%s' % (address, conf['port'])

        conf['store'] = make_stores(conf['store'])
        conf['locations'] = map(functools.partial(make_location, stores=conf['store'], servername=conf['servername']), conf['locations'])

        if self.allrequests:
            class SetServenameMiddleware(object):
                def __init__(self, application):
                    self.application = application

                def __call__(self, environ, start_response):
                    def servername_start_response(status, response_headers, exc_info=None):
                        if conf.get('servername', None):
                            header_set = set(k.lower() for (k, v) in response_headers)
                            if 'server' not in header_set:
                                response_headers.append(('Server', conf.get('servername', None)))
                        return start_response(status, response_headers, exc_info)

                    return self.application(environ, servername_start_response)

            wsgi_app = tornado_wsgi.WSGIContainer(SetServenameMiddleware(django_wsgi.get_wsgi_application()))
            conf['locations'] += (
                ('.*', web.FallbackHandler, {'fallback': wsgi_app}),
            )

        import logging
        logging.getLogger().setLevel('INFO')
        tornado_options.enable_pretty_logging()

        if self.forcehost:
            class RedirectHandler(web.RequestHandler):
                def initialize(self, forcehost):
                    self._forcehost = forcehost

                def prepare(self):
                    url = self.request.protocol + '://' + self._forcehost + self.request.uri
                    self.redirect(url, permanent=True)

                def set_default_headers(self):
                    if conf.get('servername', None):
                        self.set_header('Server', conf.get('servername', None))

            application = web.Application()
            application.add_handlers('^%s$' % re.escape(self.forcehost.lower().split(':')[0]), conf['locations'])
            application.add_handlers('.*$', (('.*', RedirectHandler, {'forcehost': self.forcehost}),))
        else:
            application = web.Application(conf['locations'])

        httpserver.HTTPServer(application).listen(conf['port'], conf['address'])

        try:
            ioloop.IOLoop.instance().start()
        except KeyboardInterrupt:
            pass
Exemplo n.º 14
0
def setup_logging(config, debug=False):
    """
    Setup the logging module to respect our configuration values.
    Expects a dictionary called config with the following parameters

    * directory:   Optional log file output directory
    * filename:    Optional filename, not needed for syslog
    * format:      Format for non-debug mode
    * level:       One of debug, error, warning, info
    * handler:     Optional handler
    * syslog:      If handler == syslog, parameters for syslog
      * address:   Syslog address
      * facility:  Syslog facility

    Passing in debug=True will disable any log output to anything but stdout
    and will set the log level to debug regardless of the config.
    """
    # Set logging levels dictionary
    logging_levels = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    # Get the logging value from the dictionary
    logging_level = config['level']

    if debug:

        # Override the logging level to use debug mode
        config['level'] = logging.DEBUG

        # If we have specified a file, remove it so logging info goes to stdout
        if 'filename' in config:
            del config['filename']

    else:

        # Use the configuration option for logging
        config['level'] = logging_levels.get(config['level'], logging.NOTSET)

    # Pass in our logging config
    logging.basicConfig(**config)
    logging.info('Log level set to %s' % logging_level)

    # Get the default logger
    default_logging = logging.getLogger()

    # Remove the default stream handler
    stream_handler = None
    for handler in default_logging.handlers:
        if isinstance(handler, logging.StreamHandler):
            stream_handler = handler
            break

    # Use colorized output
    if config['level'] == logging.DEBUG:
        enable_pretty_logging()

    # If we have supported handler
    elif 'handler' in config:

        # If we want to syslog
        if config['handler'] == 'syslog':

            facility = config['syslog']['facility']
            import logging.handlers as handlers

            # If we didn't type in the facility name
            if facility in handlers.SysLogHandler.facility_names:

                # Create the syslog handler
                address = config['syslog']['address']
                facility = handlers.SysLogHandler.facility_names[facility]
                syslog = handlers.SysLogHandler(address=address,
                                                facility=facility)
                # Add the handler
                default_logging.addHandler(syslog)

                # Remove the StreamHandler
                if stream_handler:
                    default_logging.removeHandler(stream_handler)
            else:
                logging.error('%s:Invalid facility, syslog logging aborted',
                              application_name())