Esempio n. 1
0
class CherryPyLiveServerPlugin(AbstractLiveServerPlugin):
    name = 'cherrypyliveserver'
    activation_parameter = '--with-cherrypyliveserver'

    def start_server(self, address='0.0.0.0', port=8000):
        _application = AdminMediaHandler(WSGIHandler())

        def application(environ, start_response):
            environ[
                'PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']
            return _application(environ, start_response)

        from cherrypy.wsgiserver import CherryPyWSGIServer
        from threading import Thread
        self.httpd = CherryPyWSGIServer((address, port),
                                        application,
                                        server_name='django-test-http')
        self.httpd_thread = Thread(target=self.httpd.start)
        self.httpd_thread.start()
        #FIXME: This could be avoided by passing self to thread class starting django
        # and waiting for Event lock
        sleep(.5)

    def stop_test_server(self):
        if self.server_started:
            self.httpd.stop()
            self.server_started = False
Esempio n. 2
0
class CherryPyLiveServerPlugin(AbstractLiveServerPlugin):
    """Live server plugin using cherrypy instead of the django server,
    that got its issues. Original code by Mikeal Rogers, released under
    Apache License.
    """

    name = 'cherrypyliveserver'
    activation_parameter = '--with-cherrypyliveserver'

    def start_server(self, address='0.0.0.0', port=8000, serve_static=True):
        from cherrypy.wsgiserver import CherryPyWSGIServer
        from threading import Thread

        _application = AdminMediaHandler(WSGIHandler())
        if serve_static:
            _application = StaticFilesHandler(_application)

        def application(environ, start_response):
            environ['PATH_INFO'] = environ['SCRIPT_NAME'] + \
                    environ['PATH_INFO']

            return _application(environ, start_response)

        self.httpd = CherryPyWSGIServer((address, port),
                                        application,
                                        server_name='django-test-http')
        self.httpd_thread = Thread(target=self.httpd.start)
        self.httpd_thread.start()
        # FIXME: This could be avoided by passing self to thread class starting
        # django and waiting for Event lock
        time.sleep(.5)

    def stop_server(self):
        self.httpd.stop()
Esempio n. 3
0
File: app.py Progetto: jab/radarpost
    def __call__(self, address=None):
        """
        start development web server
        address - where to serve, [interface:]port
        """
        if address is not None:
            interface = '127.0.0.1'
            port = address
            if ':' in port:
                interface, port = port.split(':')
            try:
                port = int(port)
            except: 
                raise InvalidArguments('Unable to parse port "%s"' % address)
        else:
            interface = '127.0.0.1'
            port = DEFAULT_RADAR_PORT

        from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer

        app = RequestLogger(make_app(self.config))
        cherry_opts = config_section('cherrypy', self.config) 
        server = WSGIServer((interface, port), app, **cherry_opts)
        
        print "* serving on %s:%d" % (interface, port)
        try:
            server.start()
        except KeyboardInterrupt:
            server.stop()        
Esempio n. 4
0
def main():
    root_path = gettempdir()
    provider = FilesystemProvider(root_path)

    config = {
        "provider_mapping": {"/": provider},
        "http_authenticator": {
            "domain_controller": None  # None: dc.simple_dc.SimpleDomainController(user_mapping)
        },
        "simple_dc": {"user_mapping": {"*": True}},  # anonymous access
        "verbose": 1,
        "enable_loggers": [],
        "property_manager": True,  # True: use property_manager.PropertyManager
        "lock_manager": True,  # True: use lock_manager.LockManager
    }
    app = WsgiDAVApp(config)

    # For an example, use CherryPy
    from cherrypy.wsgiserver import CherryPyWSGIServer

    server = CherryPyWSGIServer(
        bind_addr=(config["host"], config["port"]),
        wsgi_app=app,
        server_name="WsgiDAV/{} {}".format(__version__, CherryPyWSGIServer.version),
    )

    try:
        server.start()
    except KeyboardInterrupt:
        print("Caught Ctrl-C, shutting down...")
    finally:
        server.stop()
class CherryPyLiveServerPlugin(AbstractLiveServerPlugin):
    """Live server plugin using cherrypy instead of the django server,
    that got its issues. Original code by Mikeal Rogers, released under
    Apache License.
    """

    name = 'cherrypyliveserver'
    activation_parameter = '--with-cherrypyliveserver'

    def start_server(self, address='0.0.0.0', port=8000, serve_static=True):
        from cherrypy.wsgiserver import CherryPyWSGIServer
        from threading import Thread

        _application = AdminMediaHandler(WSGIHandler())
        if serve_static:
            _application = StaticFilesHandler(_application)

        def application(environ, start_response):
            environ['PATH_INFO'] = environ['SCRIPT_NAME'] + \
                    environ['PATH_INFO']

            return _application(environ, start_response)

        self.httpd = CherryPyWSGIServer((address, port), application,
                                        server_name='django-test-http')
        self.httpd_thread = Thread(target=self.httpd.start)
        self.httpd_thread.start()
        # FIXME: This could be avoided by passing self to thread class starting
        # django and waiting for Event lock
        time.sleep(.5)

    def stop_server(self):
        self.httpd.stop()
Esempio n. 6
0
 def inner_run():
     from django.conf import settings
     print "Validating models..."
     self.validate(display_num_errors=True)
     print "\nDjango version %s, using settings %r" % (
         django.get_version(), settings.SETTINGS_MODULE)
     print "CherryPy server is running at http://%s:%s/" % (addr, port)
     print "Quit the server with %s." % quit_command
     try:
         path = admin_media_path or django.__path__[
             0] + '/contrib/admin/media'
         handler = AdminMediaHandler(WSGIHandler(), path)
         handler = TransLogger(handler)
         server = Server((addr, int(port)), handler, server_name=addr)
         server.start()
     except WSGIServerException, e:
         # Use helpful error messages instead of ugly tracebacks.
         ERRORS = {
             13: "You don't have permission to access that port.",
             98: "That port is already in use.",
             99: "That IP address can't be assigned-to.",
         }
         try:
             error_text = ERRORS[e.args[0].args[0]]
         except (AttributeError, KeyError):
             error_text = str(e)
         sys.stderr.write(
             self.style.ERROR("Error: %s" % error_text) + '\n')
         # Need to use an OS exit because sys.exit doesn't work in a thread
         os._exit(1)
Esempio n. 7
0
        def inner_run():
            from django.conf import settings

            print "Validating models..."
            self.validate(display_num_errors=True)
            print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
            print "CherryPy server is running at http://%s:%s/" % (addr, port)
            print "Quit the server with %s." % quit_command
            try:
                path = admin_media_path or django.__path__[0] + "/contrib/admin/media"
                handler = AdminMediaHandler(WSGIHandler(), path)
                handler = TransLogger(handler)
                server = Server((addr, int(port)), handler, server_name=addr)
                server.start()
            except WSGIServerException, e:
                # Use helpful error messages instead of ugly tracebacks.
                ERRORS = {
                    13: "You don't have permission to access that port.",
                    98: "That port is already in use.",
                    99: "That IP address can't be assigned-to.",
                }
                try:
                    error_text = ERRORS[e.args[0].args[0]]
                except (AttributeError, KeyError):
                    error_text = str(e)
                sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + "\n")
                # Need to use an OS exit because sys.exit doesn't work in a thread
                os._exit(1)
Esempio n. 8
0
 def run(self):
     try:
         self.server = CherryPyWSGIServer((address, port),
                                          StaticFilesHandler(WSGIHandler()))
         self.server.start()
     except Exception as e:
         log("Server error: %s" % e)
Esempio n. 9
0
class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option("-h", "--host", dest="host", default=DEFAULT_HOST),
        make_option("-p", "--port", dest="port", default=DEFAULT_PORT),
        make_option("-d", "--daemon", dest="daemonize", action="store_true"),
    )
    requires_model_validation = False

    def handle(self, *args, **options):
        self.options = options
        self.server = CherryPyWSGIServer((options["host"], options["port"]),
                                         WSGIHandler())
        self.pidfile = os.path.join(settings.PROJECT_ROOT, "logs/wsgi.pid")
        try:
            action = args[0]
        except IndexError:
            print "You must provide an action. Possible actions are start, stop and restart."
            raise SystemExit
        if action == "start":
            print "Running %s:%d" % (options["host"], options["port"])
            self.daemonize()
            self.start()
        elif action == "stop":
            pid = open(self.pidfile, "r").read()
            self.stop(pid)
        elif action == "restart":
            pid = open(self.pidfile, "r").read()
            self.restart(pid)

    def daemonize(self):
        if self.options["daemonize"]:
            daemonize()

    def start(self):
        writepid(self.pidfile)
        try:
            self.server.start()
        except KeyboardInterrupt:
            # likely not a daemon so make sure to shutdown properly.
            self.server.stop()

    def stop(self, pid):
        os.kill(int(pid), signal.SIGHUP)

    def restart(self, pid):
        self.stop(pid)
        self.daemonize()
        self.start()

    def create_parser(self, prog_name, subcommand):
        """
        Create and return the ``OptionParser`` which will be used to
        parse the arguments to this command.
        """
        return OptionParser(prog=prog_name,
                            usage=self.usage(subcommand),
                            version=self.get_version(),
                            option_list=self.option_list,
                            conflict_handler="resolve")
Esempio n. 10
0
 def _cherrypy():
     from cherrypy.wsgiserver import CherryPyWSGIServer
     server = CherryPyWSGIServer(
         (hostname, port),
         app,
         server_name=ctx.cfg['base_domain_name'],
         request_queue_size=500)
     server.start()
Esempio n. 11
0
  def handle(self, **options):
    # Determine the port number
    if 'port' in options:
      port = int(options['port'] or settings.PORT)
    else:
      port = settings.PORT

    # Determine the number of threads
    if 'threads' in options:
      threads = int(options['threads'] or 25)
      if threads < 1:
        raise Exception("Invalid number of threads: %s" % threads)
    else:
      threads = 25

    # Determine the IP-address to listen on:
    # - either as command line argument
    # - either 0.0.0.0 by default, which means all active IPv4 interfaces
    address = 'address' in options and options['address'] or '0.0.0.0'

    # Validate the address and port number
    try:
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.bind( (address, port) )
      s.close()
    except socket.error as e:
      raise Exception("Invalid address '%s' and/or port '%s': %s" % (address, port, e))

    # Print a header message
    hostname = socket.getfqdn()
    print('Starting frePPLe %s web server\n' % VERSION)
    print('To access the server, point your browser to either of the following URLS:')
    if address == '0.0.0.0':
      print('    http://%s:%s/' % (hostname, port))
      for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
        print('    http://%s:%s/' % (ip, port))
    else:
      print('    http://%s:%s/' % (address, port))
    print('\nThree users are created by default: "admin", "frepple" and "guest" (the default password is equal to the user name)\n')
    print('Quit the server with CTRL-C.\n')

    # Start a separate thread that will check for updates
    # We don't wait for it to finish
    CheckUpdates().start()

    # Run the WSGI server
    server = CherryPyWSGIServer(
      (address, port),
      StaticFilesHandler(WSGIHandler()),
      numthreads=threads
      )
    # Want SSL support? Just set these attributes apparently, but I haven't tested or verified this
    #  server.ssl_certificate = <filename>
    #  server.ssl_private_key = <filename>
    try:
      server.start()
    except KeyboardInterrupt:
      server.stop()
Esempio n. 12
0
    def __init__(self, host, port, http_interface, use_ssl, ca_cert,
                 ssl_key, ssl_cert, server_dh, daemon_thread_pool_size):
        # pylint: disable=too-many-arguments
        """
        Initialize HTTP daemon

        :param host: host address
        :param port: listening port
        :param http_interface:
        :param use_ssl:
        :param ca_cert:
        :param ssl_key:
        :param ssl_cert:
        :param daemon_thread_pool_size:
        """
        # Port = 0 means "I don't want HTTP server"
        if port == 0:
            return

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((host, port))
        if result == 0:
            msg = "Error: Sorry, the port %s/%d is not free" % (host, port)
            raise PortNotFree(msg)

        self.port = port
        self.host = host

        self.use_ssl = use_ssl

        protocol = 'http'
        if use_ssl:
            protocol = 'https'
        self.uri = '%s://%s:%s' % (protocol, self.host, self.port)
        logger.info("Opening HTTP socket at %s", self.uri)

        # This config overrides default processors so we put them back in case we need them
        config = {
            '/': {
                'request.body.processors': {'application/x-www-form-urlencoded': process_urlencoded,
                                            'multipart/form-data': process_multipart_form_data,
                                            'multipart': process_multipart,
                                            'application/zlib': zlib_processor},
                'tools.gzip.on': True,
                'tools.gzip.mime_types': ['text/*', 'application/json'],
            }
        }
        # disable console logging of cherrypy when not in DEBUG
        if getattr(logger, 'level') != logging.DEBUG:
            cherrypy.log.screen = False

        if use_ssl:
            CherryPyWSGIServer.ssl_adapter = Pyopenssl(ssl_cert, ssl_key, ca_cert, server_dh)

        self.srv = CherryPyWSGIServer((host, port),
                                      cherrypy.Application(http_interface, "/", config),
                                      numthreads=daemon_thread_pool_size, shutdown_timeout=1,
                                      request_queue_size=30)
Esempio n. 13
0
    def __init__(self, host, port, http_interface, use_ssl, ca_cert,
                 ssl_key, ssl_cert, daemon_thread_pool_size):
        self.port = port
        self.host = host
        self.srv = None
        # Port = 0 means "I don't want HTTP server"
        if self.port == 0:
            return

        self.use_ssl = use_ssl

        self.srv = None

        protocol = 'http'
        if use_ssl:
            protocol = 'https'
        self.uri = '%s://%s:%s' % (protocol, self.host, self.port)
        logger.info("Opening HTTP socket at %s", self.uri)

        # This config override default processors so we put them back in case we need them
        config = {
            '/': {
                'request.body.processors': {'application/x-www-form-urlencoded': process_urlencoded,
                                            'multipart/form-data': process_multipart_form_data,
                                            'multipart': process_multipart,
                                            'application/zlib': zlib_processor},
                'tools.gzip.on': True,
                'tools.gzip.mime_types': ['text/*', 'application/json']
            }
        }
        # disable console logging of cherrypy when not in DEBUG
        if getattr(logger, 'level') != logging.DEBUG:
            cherrypy.log.screen = False

        self.srv = CherryPyWSGIServer((host, port),
                                      cherrypy.Application(http_interface, "/", config),
                                      numthreads=daemon_thread_pool_size, shutdown_timeout=1)
        if SSL and pyOpenSSLAdapter and use_ssl:
            adapter = pyOpenSSLAdapter(ssl_cert, ssl_key, ca_cert)
            context = adapter.get_context()
            # SSLV2 is deprecated since 2011 by RFC 6176
            # SSLV3, TLSV1 and TLSV1.1 have POODLE weakness (harder to exploit on TLS)
            # So for now (until a new TLS version) we only have TLSv1.2 left

            # WE also remove compression because of BREACH weakness
            context.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3 |
                                SSL.OP_NO_TLSv1 | SSL.OP_NO_TLSv1_1 |
                                SSL.OP_NO_COMPRESSION)

            # All excluded algorithm beyond are known to be weak.
            context.set_cipher_list('DEFAULT:!DSS:!PSK:!SRP:!3DES:!RC4:!DES:!IDEA:!RC2:!NULL')

            adapter.context = context
            self.srv.ssl_adapter = adapter
        if use_ssl:
            self.srv.ssl_certificate = ssl_cert
            self.srv.ssl_private_key = ssl_key
Esempio n. 14
0
class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option("-h", "--host", dest="host", default=DEFAULT_HOST),
        make_option("-p", "--port", dest="port", default=DEFAULT_PORT),
        make_option("-d", "--daemon", dest="daemonize", action="store_true"),
    )
    requires_model_validation = False
    
    def handle(self, *args, **options):
        self.options = options
        self.server = CherryPyWSGIServer((options["host"], options["port"]), WSGIHandler())
        self.pidfile = os.path.join(settings.PROJECT_ROOT, "logs/wsgi.pid")
        try:
            action = args[0]
        except IndexError:
            print "You must provide an action. Possible actions are start, stop and restart."
            raise SystemExit
        if action == "start":
            print "Running %s:%d" % (options["host"], options["port"])
            self.daemonize()
            self.start()
        elif action == "stop":
            pid = open(self.pidfile, "r").read()
            self.stop(pid)
        elif action == "restart":
            pid = open(self.pidfile, "r").read()
            self.restart(pid)
    
    def daemonize(self):
        if self.options["daemonize"]:
            daemonize()
    
    def start(self):
        writepid(self.pidfile)
        try:
            self.server.start()
        except KeyboardInterrupt:
            # likely not a daemon so make sure to shutdown properly.
            self.server.stop()
    
    def stop(self, pid):
        os.kill(int(pid), signal.SIGHUP)
    
    def restart(self, pid):
        self.stop(pid)
        self.daemonize()
        self.start()
    
    def create_parser(self, prog_name, subcommand):
        """
        Create and return the ``OptionParser`` which will be used to
        parse the arguments to this command.
        """
        return OptionParser(prog=prog_name, usage=self.usage(subcommand),
            version = self.get_version(),
            option_list = self.option_list,
            conflict_handler = "resolve")
Esempio n. 15
0
    def run(self):
        from cherrypy.wsgiserver import CherryPyWSGIServer
    #    Not possible to use 127.0.0.1 as this does not link to an
    #    externally accessible interface

        global server
        server = CherryPyWSGIServer((localIp(), portNo), BiFa())

        print "Started serving:"
        server.start()
Esempio n. 16
0
class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option("-h", "--host", dest="host", default=DEFAULT_HOST),
        make_option("-p", "--port", dest="port", default=DEFAULT_PORT, type="int"),
        make_option("-d", "--daemon", dest="daemonize", action="store_true"),
    )
    requires_model_validation = False

    def handle(self, *args, **options):
        self.server = CherryPyWSGIServer((options["host"], options["port"]), WSGIHandler())
        self.pidfile = settings.APP_DIR.joinpath("wsgi.pid")
        try:
            action = args[0]
        except IndexError:
            action = "start"
        if options["daemonize"]:
            daemonize()
        if action == "start":
            self.start(create_pid_file=options["daemonize"])
        elif action == "stop":
            pid = open(self.pidfile, "r").read()
            self.stop(pid)
        elif action == "restart":
            pid = open(self.pidfile, "r").read()
            self.restart(pid)

    def start(self, create_pid_file=False):
        if create_pid_file:
            writepid(self.pidfile)
        try:
            self.server.start()
        except KeyboardInterrupt:
            # likely not a daemon so make sure to shutdown properly.
            self.server.stop()

    def stop(self, pid):
        os.kill(int(pid), signal.SIGHUP)

    def restart(self, pid):
        self.stop(pid)
        self.start()

    def create_parser(self, prog_name, subcommand):
        """
        Create and return the ``OptionParser`` which will be used to
        parse the arguments to this command.
        """
        return OptionParser(
            prog=prog_name,
            usage=self.usage(subcommand),
            version=self.get_version(),
            option_list=self.option_list,
            conflict_handler="resolve",
        )
Esempio n. 17
0
def WSGIServer(port, application):
    from weberror.evalexception import EvalException
    application = EvalException(application, )
    application = timeit_middleware(application)
    logging.info('\nGAME BEGIN\n\n')
    
    server = CherryPyWSGIServer(('0.0.0.0', port), application, numthreads=10)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 18
0
class CherryPyLiveServerPlugin(Plugin):
    name = 'cherrypyliveserver'

    def __init__(self):
        Plugin.__init__(self)
        self.server_started = False
        self.server_thread = None

    def options(self, parser, env=os.environ):
        Plugin.options(self, parser, env)

    def configure(self, options, config):
        Plugin.configure(self, options, config)

    def startTest(self, test):
        from django.conf import settings

        if not self.server_started and \
           getattr(test, 'start_live_server', False):

            self.start_server(address=getattr(settings, "LIVE_SERVER_ADDRESS",
                                              DEFAULT_LIVE_SERVER_ADDRESS),
                              port=int(
                                  getattr(settings, "LIVE_SERVER_PORT",
                                          DEFAULT_LIVE_SERVER_PORT)))
            self.server_started = True

    def finalize(self, result):
        self.stop_test_server()

    def start_server(self, address='0.0.0.0', port=8000):
        _application = AdminMediaHandler(WSGIHandler())

        def application(environ, start_response):
            environ[
                'PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']
            return _application(environ, start_response)

        from cherrypy.wsgiserver import CherryPyWSGIServer
        from threading import Thread
        self.httpd = CherryPyWSGIServer((address, port),
                                        application,
                                        server_name='django-test-http')
        self.httpd_thread = Thread(target=self.httpd.start)
        self.httpd_thread.start()
        #FIXME: This could be avoided by passing self to thread class starting django
        # and waiting for Event lock
        sleep(.5)

    def stop_test_server(self):
        if self.server_started:
            self.httpd.stop()
            self.server_started = False
Esempio n. 19
0
class RunWSGIServer(Thread):
    def __init__(self, address, port):
        self.address = address
        self.port = port
        super(RunWSGIServer, self).__init__()

    def run(self):
        try:
            self.server = CherryPyWSGIServer((address, port),
                                             StaticFilesHandler(WSGIHandler()))
            self.server.start()
        except Exception as e:
            log("Server error: %s" % e)
Esempio n. 20
0
 def start(self):
     from cherrypy.wsgiserver import CherryPyWSGIServer
     hostname = self.config['server_host']['host']
     port = int(self.config['server_host']['port'])
     scheme = self.config['server_host']['scheme']
     server = CherryPyWSGIServer((hostname, port), self.server)
     try:
         logging.debug('starting CherryPy at %s://%s:%s',
                 scheme, hostname, port)
         print "Starting CherryPy at %s://%s:%s" % (scheme, hostname, port)
         server.start()
     except KeyboardInterrupt:
         server.stop()
Esempio n. 21
0
class CherryPyLiveServerPlugin(Plugin):
    name = 'cherrypyliveserver'
    activation_parameter = '--with-cherrypyliveserver'
    nosedjango = True

    def __init__(self):
        Plugin.__init__(self)
        self.server_started = False
        self.server_thread = None

    def options(self, parser, env=os.environ):
        Plugin.options(self, parser, env)

    def configure(self, options, config):
        Plugin.configure(self, options, config)

    def startTest(self, test):
        from django.conf import settings

        if not self.server_started and \
           getattr(test, 'start_live_server', False):

            self.start_server(
                address=getattr(settings, "LIVE_SERVER_ADDRESS", DEFAULT_LIVE_SERVER_ADDRESS),
                port=int(getattr(settings, "LIVE_SERVER_PORT", DEFAULT_LIVE_SERVER_PORT))
            )
            self.server_started = True

    def finalize(self, result):
        self.stop_test_server()

    def start_server(self, address='0.0.0.0', port=8000):
        _application = AdminMediaHandler(WSGIHandler())

        def application(environ, start_response):
            environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']
            return _application(environ, start_response)

        from cherrypy.wsgiserver import CherryPyWSGIServer
        from threading import Thread
        self.httpd = CherryPyWSGIServer((address, port), application, server_name='django-test-http')
        self.httpd_thread = Thread(target=self.httpd.start)
        self.httpd_thread.start()
        #FIXME: This could be avoided by passing self to thread class starting django
        # and waiting for Event lock
        time.sleep(.5)

    def stop_test_server(self):
        if self.server_started:
            self.httpd.stop()
            self.server_started = False
Esempio n. 22
0
def serve(application, host='127.0.0.1', port=8080):
	"""CherryPy-based WSGI-HTTP server."""
	
	# Instantiate the server with our configuration and application.
	server = CherryPyWSGIServer((host, int(port)), application, server_name=host)
	
	# Try to be handy as many terminals allow clicking links.
	print("serving on http://{0}:{1}".format(host, port))
	
	# Bind and launch the server; this is a blocking operation.
	try:
		server.start()
	except KeyboardInterrupt:
		server.stop()  # CherryPy has some of its own shutdown work to do.
Esempio n. 23
0
def wsgi_worker_function(options, args):
    if len(args) > 0:
        appfile = args[0]
        try:
            application = extract_application(appfile)
        except AttributeError:
            sys.exit("Could not find application in %s" % filename)

        server = CherryPyWSGIServer((options.host, int(options.port)), application, request_queue_size=500)
        print >>sys.stderr, "Serving on %s:%s\n" % (options.host, options.port)
        server.start()

    else:
        sys.exit("Is necesary application file.")
Esempio n. 24
0
def start_server(config):
    """
    Make a server and start it up as a daemon.
    """
    port = int(config['port'])
    local_host = config['local_host']

    server = CherryPyWSGIServer((local_host, port), create_app(config))

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
        sys.exit(0)
Esempio n. 25
0
def run_server(app):
    http_config = app.config['rest_api']['http']
    https_config = app.config['rest_api']['https']

    signal.signal(signal.SIGTERM, signal_handler)
    if app.config['profile']:
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
                                          profile_dir=app.config['profile'])

    wsgi_app = wsgiserver.WSGIPathInfoDispatcher({'/': app})

    cherrypy.server.unsubscribe()
    cherrypy.config.update({'environment': 'production'})

    if not (http_config['enabled'] or https_config['enabled']):
        logger.critical('No HTTP/HTTPS server enabled')
        exit()

    if https_config['enabled']:
        try:
            bind_addr_https = (https_config['listen'], https_config['port'])
            server_https = CherryPyWSGIServer(bind_addr=bind_addr_https,
                                              wsgi_app=wsgi_app)
            server_https.ssl_adapter = http_helpers.ssl_adapter(https_config['certificate'],
                                                                https_config['private_key'],
                                                                https_config['ciphers'])
            ServerAdapter(cherrypy.engine, server_https).subscribe()

            logger.debug('HTTPS server starting on %s:%s', *bind_addr_https)

        except IOError as e:
            logger.warning("HTTPS server won't start: %s", e)
    else:
        logger.debug('HTTPS server is disabled')

    if http_config['enabled']:
        bind_addr_http = (http_config['listen'], http_config['port'])
        server_http = CherryPyWSGIServer(bind_addr=bind_addr_http,
                                         wsgi_app=wsgi_app)
        ServerAdapter(cherrypy.engine, server_http).subscribe()

        logger.debug('HTTP server starting on %s:%s', *bind_addr_http)
    else:
        logger.debug('HTTP server is disabled')

    try:
        cherrypy.engine.start()
        cherrypy.engine.block()
    except KeyboardInterrupt:
        cherrypy.engine.stop()
Esempio n. 26
0
  def handle(self, **options):
    from cherrypy.wsgiserver import CherryPyWSGIServer

    # Determine the port number
    port = options['port']

    # Determine the number of threads
    threads = options['threads']
    if threads < 1:
      raise Exception("Invalid number of threads: %s" % threads)

    # Determine the IP-address to listen on:
    # - either as command line argument
    # - either 0.0.0.0 by default, which means all active IPv4 interfaces
    address = options['address'] or '0.0.0.0'

    # Validate the address and port number
    try:
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.bind( (address, port) )
      s.close()
    except socket.error as e:
      raise Exception("Invalid address '%s' and/or port '%s': %s" % (address, port, e))

    # Print a header message
    hostname = socket.getfqdn()
    print('Starting frePPLe %s web server\n' % VERSION)
    print('To access the server, point your browser to either of the following URLS:')
    if address == '0.0.0.0':
      print('    http://%s:%s/' % (hostname, port))
      for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
        print('    http://%s:%s/' % (ip, port))
    else:
      print('    http://%s:%s/' % (address, port))
    print('Quit the server with CTRL-C.\n')

    # Run the WSGI server
    server = CherryPyWSGIServer(
      (address, port),
      StaticFilesHandler(WSGIHandler()),
      numthreads=threads
      )
    # Want SSL support? Just set these attributes apparently, but I haven't tested or verified this
    #  server.ssl_certificate = <filename>
    #  server.ssl_private_key = <filename>
    try:
      server.start()
    except KeyboardInterrupt:
      server.stop()
Esempio n. 27
0
class RunWSGIServer(Thread):

  def __init__(self, address, port):
    self.address = address
    self.port = port
    super(RunWSGIServer,self).__init__()

  def run(self):
    try:
      self.server = CherryPyWSGIServer((address, port),
        StaticFilesHandler(WSGIHandler())
        )
      self.server.start()
    except Exception as e:
      log("Server error: %s" % e)
Esempio n. 28
0
    def start_server(self, address='0.0.0.0', port=8000):
        _application = AdminMediaHandler(WSGIHandler())

        def application(environ, start_response):
            environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']
            return _application(environ, start_response)

        from cherrypy.wsgiserver import CherryPyWSGIServer
        from threading import Thread
        self.httpd = CherryPyWSGIServer((address, port), application, server_name='django-test-http')
        self.httpd_thread = Thread(target=self.httpd.start)
        self.httpd_thread.start()
        #FIXME: This could be avoided by passing self to thread class starting django
        # and waiting for Event lock
        time.sleep(.5)
Esempio n. 29
0
 def run(self):
     """Launch CherryPy Django web server."""
     server = CherryPyWSGIServer(
         (self.options['host'], int(self.options['port'])),
         WSGIPathInfoDispatcher({
             '/': WSGIHandler(),
             settings.ADMIN_MEDIA_PREFIX: MediaHandler(
                 os.path.join(admin.__path__[0], 'media'))
         }),
         int(self.options['threads']), self.options['host'],
         request_queue_size=int(self.options['request_queue_size']))
     try:
         server.start()
     except KeyboardInterrupt:
         server.stop()
Esempio n. 30
0
    def setup_kws_server(self):
        """
        sets up the KWS server to run on a separate port
        """
        # based on http://docs.cherrypy.org/stable/refman/process/servers.html

        if not self.config['keyword_search']['kws_service_on']:
            return

        # load KWSWebService here since it will be loaded after self.configure
        # which brings secmodv2 into cherrypy.tools
        from DAS.web.kws_web_srv import KWSWebService
        kws_service = KWSWebService(self.config)
        kws_wsgi_app = _cptree.Tree()
        kws_wsgi_app.mount(kws_service, '/das')

        config = self.config['web_server']
        port = int(config.get("kws_port", 8214))
        host = config.get("kws_host", '0.0.0.0')

        if CherryPyWSGIServer:
            kws_server = CherryPyWSGIServer(
                bind_addr=(host, port),
                wsgi_app=kws_wsgi_app,
                numthreads=int(config.get("thread_pool_kws", 10)),
                request_queue_size=cpconfig["server.socket_queue_size"],
                # below are cherrypy default settings...
                # max=-1,
                # timeout=10,
                # shutdown_timeout=5
            )
            srv_adapter = ServerAdapter(engine, kws_server)
            srv_adapter.subscribe()
Esempio n. 31
0
def serve(db_path, state_machine, host, port, cherrypy=True, ssl_cert=None, ssl_key=None):
    '''
    The main part of this configuration is the definition of routes.
    Routes have three components:
    1) a regular expression which the url is matched against (not including an query string). The regular expression is matched against the end of the url.
    2) a controller class that will handle the route. As a convienience module_base can be set to a common package prefix. Note that back references can be used here from 1). Also note that the class name will be automatically capitalized.
    3) an action; i.e. a method of the class specified in 2). This method must take one argument. This can also contain backreferences from 1)
    4) (optional) extra arguments that are passed to the action. This can contain backreferences from 1)
    '''

    router = Router()
    router.module_base = 'pysmsd.http.controllers'
    #                 Pattern                                                   Controller           Action    Extra args
    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    router.add_route('/static/(.+)',                                           'static.Static',      'index',   {'path': r'\1', 'auth': 'no'})
    router.add_route('/messages/in.json',                                      'messages.Messages',  'in_messages', {'auth': 'yes'})
    router.add_route('/messages/in/(\d+).json',                                'messages.Messages',  'in_message', {'id': r'\1', 'auth': 'yes'})
    router.add_route('/messages/out.json',                                     'messages.Messages',  'out_messages', {'auth': 'yes'})
    router.add_route('/messages/out/(\d+).json',                               'messages.Messages',  'out_message', {'id': r'\1', 'auth': 'yes'})
    router.add_route('/',                                                      'index.Index',        'index', {'auth': 'no'})

    #authmw = AuthMiddleware(router)
    dbmw = DBMiddleware(db_path, router)
    smmw = StateMachineMiddleware(state_machine, dbmw)

    if cherrypy:
        if host == 'localhost':
            host = '127.0.0.1' # Force IPv4 to avoid problems with Firefox 2 on Mac OS X.
        if ssl_cert and ssl_key:
            CherryPyWSGIServer.ssl_certificate = ssl_cert
            CherryPyWSGIServer.ssl_private_key = ssl_key

        server = CherryPyWSGIServer((host, port), smmw, numthreads=10, timeout=30)
        router.server = server
        try:
            logging.info('starting cherrypy httpd daemon on port %s...', port)
            server.start()
        except KeyboardInterrupt:
            server.stop()

    else:
        httpd = make_server(host, port, dbmw, handler_class=PysmsdWSGIRequestHandler)
        try:
            logging.info('starting httpd daemon on port %s...', port)
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass
Esempio n. 32
0
 def run(self):
   try:
     self.server = CherryPyWSGIServer((address, port),
       StaticFilesHandler(WSGIHandler())
       )
     self.server.start()
   except Exception as e:
     log("Server error: %s" % e)
Esempio n. 33
0
def main():
    params = sys.argv[1:]
    if params:
        host, port = params
        if host == "0":
            host = "0.0.0.0"
        port = int(port)
    else:
        host, port = "127.0.0.1", 8000
    httpd = CherryPyWSGIServer((host, port), WSGIHandler(),
        server_name="localhost")
    daemonize()
    write_pid()
    try:
        httpd.start()
    except KeyboardInterrupt:
        httpd.stop()
Esempio n. 34
0
def start_server(options):
    """
    Start CherryPy server
    """

    if options['daemonize'] and options['server_user'] and options['server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])

    try:
        from cherrypy.wsgiserver import CherryPyWSGIServer as Server
    except ImportError:
        try:
            from wsgiserver import CherryPyWSGIServer as Server
        except ImportError:
            from cpserver.wsgiserver import CherryPyWSGIServer as Server
    from django.core.handlers.wsgi import WSGIHandler
    server = Server(
        (options['host'], int(options['port'])),
        WSGIHandler(),
        int(options['threads']),
        options['server_name'],
        request_queue_size=int(options['request_queue_size'])
    )
    if options['ssl_certificate'] and options['ssl_private_key']:
        server.ssl_certificate = options['ssl_certificate']
        server.ssl_private_key = options['ssl_private_key']
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 35
0
    def run(self, handler):
        self.options['bind_addr'] = (self.host, self.port)
        self.options['wsgi_app'] = handler

        certfile = self.options.get('certfile')
        if certfile or 'certfile' in self.options:
            del self.options['certfile']
        keyfile = self.options.get('keyfile')
        if keyfile or 'keyfile' in self.options:
            del self.options['keyfile']

        server = CherryPyWSGIServer(**self.options)
        if keyfile and certfile:
            LOGGER.info("Start using HTTPS")
            server.ssl_adapter = pyOpenSSLAdapter(certfile, keyfile, None)
            context = ssl.Context(ssl.SSLv23_METHOD)
            context.set_cipher_list('HIGH')
            context.use_privatekey_file(keyfile)
            context.use_certificate_file(certfile)
            server.ssl_adapter.context = context
        else:
            LOGGER.info("Start using HTTP")

        try:
            server.start()
        finally:
            server.stop()
Esempio n. 36
0
def start_server(options, settings):
    """
    Start CherryPy server
    """

    if options['daemonize'] and options['server_user'] and options['server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])

    from cherrypy.wsgiserver import CherryPyWSGIServer as Server
    from django.core.handlers.wsgi import WSGIHandler
    from django.core.servers.basehttp import AdminMediaHandler
    app = AdminMediaHandler(WSGIHandler())
    server = Server(
        (options['host'], int(options['port'])),
        app,
        int(options['threads']),
        options['server_name']
    )
    if options['ssl_certificate'] and options['ssl_private_key']:
        server.ssl_certificate = options['ssl_certificate']
        server.ssl_private_key = options['ssl_private_key']
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 37
0
        def inner_run():
            if ssl_private_key and ssl_certificate:
                print "MSS server is running at https://%s:%s/" % (addr, port)
            else:
                print "MSS server is running at http://%s:%s/" % (addr, port)
            if settings.DEBUG:
                print "Devel mode is ON"
                print "Quit the server with %s." % quit_command

            app = WSGIHandler()
            path = {}
            if show_log:
                logged_app = TransLogger(app)
                path['/'] = logged_app
            else:
                path['/'] = app
            path[settings.MEDIA_URL] = MediaHandler(settings.MEDIA_ROOT)
            dispatcher = WSGIPathInfoDispatcher(path)
            server = CherryPyWSGIServer((addr, int(port)), dispatcher, threads)

            if ssl_private_key and ssl_certificate:
                from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter
                server.ssl_adapter = pyOpenSSLAdapter(ssl_certificate, ssl_private_key, None)

            try:
                server.start()
            except KeyboardInterrupt:
                server.stop()
                sys.exit(0)
Esempio n. 38
0
def start_server(options):
    """
    Start CherryPy server
    """

    if options['daemonize'] and options['server_user'] and options[
            'server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])

    try:
        from cherrypy.wsgiserver import CherryPyWSGIServer as Server
    except ImportError:
        try:
            from wsgiserver import CherryPyWSGIServer as Server
        except ImportError:
            from cpserver.wsgiserver import CherryPyWSGIServer as Server
    from django.core.handlers.wsgi import WSGIHandler
    server = Server((options['host'], int(options['port'])),
                    WSGIHandler(),
                    int(options['threads']),
                    options['server_name'],
                    request_queue_size=int(options['request_queue_size']))
    if options['ssl_certificate'] and options['ssl_private_key']:
        server.ssl_certificate = options['ssl_certificate']
        server.ssl_private_key = options['ssl_private_key']
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 39
0
def start_server(options):
    """
    Start CherryPy server. DEPRICATED>>>>
    Saving this function for future readers to use. 
    """
    
    if options['daemonize'] and options['server_user'] and options['server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])
    
    from cherrypy.wsgiserver import CherryPyWSGIServer as Server
    
    from django.core.handlers.wsgi import WSGIHandler
    server = Server(
        (options['host'], int(options['port'])),
        WSGIHandler(), 
        int(options['threads']), 
        options['server_name']
    )
    if options['ssl_certificate'] and options['ssl_private_key']:
        server.ssl_certificate = options['ssl_certificate']
        server.ssl_private_key = options['ssl_private_key']  
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 40
0
 def run(self, handler):
     server = CherryPyWSGIServer((self.host, self.port), handler)
     server.ssl_adapter = pyOpenSSLAdapter(CONSTANTS['certificate'], CONSTANTS['key'])
     try:
         server.start()
     finally:
         server.stop()
Esempio n. 41
0
def start_server(options):
    """
    Start CherryPy server
    """

    if options['daemonize'] and options['server_user'] and options[
            'server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])

    from cherrypy.wsgiserver import CherryPyWSGIServer as Server
    from django.core.handlers.wsgi import WSGIHandler
    app = WSGIHandler()
    server = Server((options['host'], int(options['port'])),
                    app,
                    int(options['threads']),
                    options['server_name'],
                    timeout=2,
                    shutdown_timeout=2)
    if options['ssl_certificate'] and options['ssl_private_key']:
        server.ssl_certificate = options['ssl_certificate']
        server.ssl_private_key = options['ssl_private_key']
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 42
0
def start_cherrypy(config):
    """
    Start a CherryPy webserver to run our app.
    """
    from cherrypy.wsgiserver import CherryPyWSGIServer
    hostname = config['server_host']['host']
    port = int(config['server_host']['port'])
    scheme = config['server_host']['scheme']
    app = load_app()
    server = CherryPyWSGIServer((hostname, port), app)
    try:
        LOGGER.debug('starting CherryPy at %s://%s:%s',
                scheme, hostname, port)
        std_error_message("Starting CherryPy at %s://%s:%s"
                % (scheme, hostname, port))
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 43
0
    def _runCherryPy(self, app, config):
        version = "WsgiDAV/%s %s Python/%s" % (
            __version__, wsgiserver.CherryPyWSGIServer.version, PYTHON_VERSION)

        wsgiserver.CherryPyWSGIServer.version = version

        protocol = "http"

        if config["verbose"] >= 1:
            print("Running %s" % version)
            print("Listening on %s://%s:%s ..." %
                  (protocol, config["host"], config["port"]))
        self._server = CherryPyWSGIServer(
            (config["host"], config["port"]),
            app,
            server_name=version,
        )

        self._server.start()
Esempio n. 44
0
 def handle(self, *args, **options):
     self.server = CherryPyWSGIServer((options["host"], options["port"]),
                                      WSGIHandler())
     self.pidfile = os.path.join(settings.PROJECT_ROOT, "logs/wsgi.pid")
     try:
         action = args[0]
     except IndexError:
         print "You must provide an action. Possible actions are start, stop and restart."
         raise SystemExit
     if options["daemonize"]:
         daemonize()
     if action == "start":
         self.start()
     elif action == "stop":
         pid = open(self.pidfile, "r").read()
         self.stop(pid)
     elif action == "restart":
         pid = open(self.pidfile, "r").read()
         self.restart(pid)
Esempio n. 45
0
def django_worker_function(options, args):
    from django.core.handlers.wsgi import WSGIHandler
    from django.conf import settings
    from django.utils import translation
    translation.activate(settings.LANGUAGE_CODE)

    if len(args) > 0:
        appfile = args[0]
        try:
            application = extract_application(appfile)
        except AttributeError:
            sys.exit("Could not find application in %s" % filename)
    
    else:
        application = WSGIHandler()
        
    server = CherryPyWSGIServer((options.host, int(options.port)), application, request_queue_size=500)
    print >>sys.stderr, "Serving on %s:%s\n" % (options.host, options.port)
    server.start()
Esempio n. 46
0
def start_server(options):
    """
    Start Django server and serve static files
    """
    
    if options['daemonize'] and options['server_user'] and options['server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])
    
    from cherrypy.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher
    #from cherrypy.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher
    from django.core.handlers.wsgi import WSGIHandler
    from django.conf import settings
    app = WSGIHandler()
    
    if options['adminserve']: # serve the admin media too
        # AdminMediaHandler is middleware for local use
        import django.core.servers.basehttp
        app = django.core.servers.basehttp.AdminMediaHandler(app)

    # route the requests appropriately
    path = {
        '/': app,
        settings.MEDIA_URL: mediahandler.MediaHandler(settings.MEDIA_ROOT),
         # settings.MEDIA_URL: mediahandler.MediaHandler(settings.MEDIA_ROOT),
         # settings.STATIC_URL + "admin/": mediahandler.MediaHandler(
         #     os.path.join(django.contrib.admin.__path__[0], 'static/admin')
         #     )
         }
    
    dispatcher = WSGIPathInfoDispatcher(path)
        
    server = CherryPyWSGIServer(
        (options['host'], int(options['port'])),
        dispatcher,
        int(options['threads']), 
        options['server_name']
    )

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 47
0
 def run(self, handler):
     server = CherryPyWSGIServer((self.host, self.port), handler)
     server.ssl_adapter = \
             pyOpenSSLAdapter(RestConfig.get('ssl', 'certificate'),
                              RestConfig.get('ssl', 'key'))
     try:
         server.start()
     finally:
         server.stop()
class Engine(ThreadedEngine):

    cp_server = None # a CherryPyWSGIServer instance

    def bind(self):
        self.cp_server = CherryPyWSGIServer( self.website.network_address
                                           , self.website
                                            )

        # Work around a Jython bug.
        # =========================
        # http://bugs.jython.org/issue1848
        # http://stackoverflow.com/questions/1103487/
        try:                        # >= 2.6
            import platform
            if platform.python_implementation() == 'Jython':
                self.cp_server.nodelay = False
        except AttributeError:      # < 2.6
            import sys
            if sys.platform.startswith('java'):
                self.cp_server.nodelay = False

    def start(self):
        self.cp_server.start()

    def stop(self):
        self.cp_server.stop()

    def start_checking(self, check_all):

        def loop():
            while True:
                try:
                    check_all()
                except SystemExit:
                    self.cp_server.interrupt = SystemExit
                time.sleep(0.5)

        checker = threading.Thread(target=loop)
        checker.daemon = True
        checker.start()
Esempio n. 49
0
def main():
    rootpath = gettempdir()
    provider = FilesystemProvider(rootpath)

    config = DEFAULT_CONFIG.copy()
    config.update({
        "provider_mapping": {
            "/": provider
        },
        "user_mapping": {},
        "verbose": 1,
        "enable_loggers": [],
        "propsmanager": True,  # True: use property_manager.PropertyManager
        "locksmanager": True,  # True: use lock_manager.LockManager
        "domaincontroller":
        None,  # None: domain_controller.WsgiDAVDomainController(user_mapping)
    })
    app = WsgiDAVApp(config)

    # For an example, use CherryPy
    from cherrypy.wsgiserver import CherryPyWSGIServer

    server = CherryPyWSGIServer(
        bind_addr=(config["host"], config["port"]),
        wsgi_app=app,
        server_name="WsgiDAV/%s %s" %
        (__version__, CherryPyWSGIServer.version),
    )

    try:
        server.start()
    except KeyboardInterrupt:
        print("Caught Ctrl-C, shutting down...")
    finally:
        server.stop()
Esempio n. 50
0
def main():
    root_path = gettempdir()
    provider = FilesystemProvider(root_path)

    config = {
        "provider_mapping": {"/": provider},
        "http_authenticator": {
            "domain_controller": None  # None: dc.simple_dc.SimpleDomainController(user_mapping)
        },
        "simple_dc": {"user_mapping": {"*": True}},  # anonymous access
        "verbose": 1,
        "enable_loggers": [],
        "property_manager": True,  # True: use property_manager.PropertyManager
        "lock_manager": True,  # True: use lock_manager.LockManager
    }
    app = WsgiDAVApp(config)

    # For an example, use CherryPy
    from cherrypy.wsgiserver import CherryPyWSGIServer

    server = CherryPyWSGIServer(
        bind_addr=(config["host"], config["port"]),
        wsgi_app=app,
        server_name="WsgiDAV/{} {}".format(__version__, CherryPyWSGIServer.version),
    )

    try:
        server.start()
    except KeyboardInterrupt:
        print("Caught Ctrl-C, shutting down...")
    finally:
        server.stop()
Esempio n. 51
0
def main():
    cherrypy.config.update({'error_page.404': err_pages.err_404})
    # = Daemonizer(cherrypy.engine)
    #d.subscribe()
    AppDispatcher = WSGIPathInfoDispatcher({
        '/':
        cherrypy.tree.mount(Main(), '/', config=config),
        #'/login': LoginApp,
        '/file':
        FileApp
    })
    server = CherryPyWSGIServer((settings['ip'], settings['port']),
                                AppDispatcher,
                                server_name=render('__server_info__'),
                                numthreads=100,
                                request_queue_size=70)

    serverSSL = None

    if settings.has_key('ssl_certificate') and settings.has_key(
            'ssl_private_key'):
        if os.path.exists(settings['ssl_certificate']) and os.path.exists(
                settings['ssl_private_key']):
            serverSSL = CherryPyWSGIServer(
                (settings['ip'], settings['sslport']),
                AppDispatcher,
                server_name=render('__server_info__'),
                numthreads=100,
                request_queue_size=70)
            serverSSL.ssl_certificate = settings['ssl_certificate']
            serverSSL.ssl_private_key = settings['ssl_private_key']
            s2 = ServerAdapter(cherrypy.engine, serverSSL)
            s2.subscribe()
    s1 = ServerAdapter(cherrypy.engine, server)
    s1.subscribe()
    check_create_db(settings['db_name'], settings['db_name'])
    cherrypy.engine.timeout_monitor.unsubscribe()
    cherrypy.engine.start()
    cherrypy.engine.block()
Esempio n. 52
0
def start_server(options):
    """
    Start CherryPy server
    """

    if options['daemonize'] and options['server_user'] and options[
            'server_group']:
        #ensure the that the daemon runs as specified user
        change_uid_gid(options['server_user'], options['server_group'])

    from cherrypy.wsgiserver import CherryPyWSGIServer as Server
    from django.core.handlers.wsgi import WSGIHandler
    server = Server((options['host'], int(options['port'])),
                    WSGIHandler(),
                    int(options['threads']),
                    options['server_name'],
                    timeout=int(options['timeout']))

    if cherrypy.__version__ >= '3.2.0':
        #3.2 and beyond usage of ssl_adapter
        try:
            #use the openssl adapter if available
            from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter as sslAdapter
        except ImportError:
            from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter as sslAdapter
        if options['ssl_certificate'] and options['ssl_private_key']:
            if options['ssl_certificate_chain']:
                chain = options['ssl_certificate_chain']
            else:
                chain = None
            server.ssl_adapter = sslAdapter(options['ssl_certificate'],
                                            options['ssl_private_key'],
                                            certificate_chain=chain)
    else:
        #legacy older ssl setup method
        server.ssl_certificate = options['ssl_certificate']
        server.ssl_private_key = options['ssl_private_key']
        if options['ssl_certificate_chain']:
            server.ssl_certificate_chain = options['ssl_certificate_chain']

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 53
0
    def handle(self, **options):
        # Determine the port number
        if 'port' in options:
            port = int(options['port'] or settings.PORT)
        else:
            port = settings.PORT

        # Determine the number of threads
        if 'threads' in options:
            threads = int(options['threads'] or 25)
            if threads < 1:
                raise Exception("Invalid number of threads: %s" % threads)
        else:
            threads = 25

        # Determine the IP-address to listen on:
        # - either as command line argument
        # - either 0.0.0.0 by default, which means all active IPv4 interfaces
        address = 'address' in options and options['address'] or '0.0.0.0'

        # Validate the address and port number
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((address, port))
            s.close()
        except socket.error as e:
            raise Exception("Invalid address '%s' and/or port '%s': %s" %
                            (address, port, e))

        # Print a header message
        hostname = socket.getfqdn()
        print('Starting frePPLe %s web server\n' % VERSION)
        print(
            'To access the server, point your browser to either of the following URLS:'
        )
        if address == '0.0.0.0':
            print('    http://%s:%s/' % (hostname, port))
            for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
                print('    http://%s:%s/' % (ip, port))
        else:
            print('    http://%s:%s/' % (address, port))
        print('Quit the server with CTRL-C.\n')

        # Start a separate thread that will check for updates
        # We don't wait for it to finish
        CheckUpdates().start()

        # Run the WSGI server
        server = CherryPyWSGIServer((address, port),
                                    StaticFilesHandler(WSGIHandler()),
                                    numthreads=threads)
        # Want SSL support? Just set these attributes apparently, but I haven't tested or verified this
        #  server.ssl_certificate = <filename>
        #  server.ssl_private_key = <filename>
        try:
            server.start()
        except KeyboardInterrupt:
            server.stop()
Esempio n. 54
0
File: serve.py Progetto: amitu/zums
def main():
    parser = argparse.ArgumentParser(
        description='zmq based session and user manager for web applications.')
    parser.add_argument("-i",
                        "--ip",
                        default="0.0.0.0",
                        help="listen on this ip (default: 0.0.0.0)")
    parser.add_argument("-p",
                        "--port",
                        default=8088,
                        type=int,
                        help="listen on this port (default: 8088)")
    parser.add_argument(
        "-s",
        "--settings",
        default="zums.zumsd_users.settings",
        help="settings module to use (default: zums.zumsd_users.settings)")
    parser.add_argument(
        "-t",
        "--templates",
        default="./ROOT/templates",
        help="location of templates (default: ./ROOT/templates)")
    parser.add_argument("-d",
                        "--debug",
                        default=False,
                        action="store_true",
                        help="run in debug mode, default is in settings file")
    parser.add_argument("--init",
                        default=False,
                        action="store_true",
                        help="create user database")
    args = parser.parse_args()

    os.environ["DJANGO_SETTINGS_MODULE"] = args.settings

    from django.core.management import call_command
    from django.core.handlers.wsgi import WSGIHandler
    from django.conf import settings

    if args.init:
        call_command('syncdb', interactive=True)
        return

    if args.templates:
        settings.TEMPLATE_DIRS = (args.templates, )
    if args.debug:
        settings.DEBUG = True

    server = CherryPyWSGIServer((args.ip, args.port), WSGIHandler())
    print "Started http server on %s:%s." % (args.ip, args.port)
    print "Hit ^C to exit."

    try:
        server.start()
    except KeyboardInterrupt:
        print "Shutting down gracefully."
        server.stop()
Esempio n. 55
0
 def _start_httpd(self, host_port):
     host_port = to_ip(host_port)
     if not self.running_tests:
         if host_port not in self.servs:
             host, _, port = host_port.partition(':')
             serv = CherryPyWSGIServer((host, int(port)),
                                       self.dispatcher,
                                       request_queue_size=128,
                                       numthreads=4)
             start_new_thread(start_serv, (serv, ))
             #while not serv.ready:
             #    time.sleep(.1)
             self.servs[host_port] = serv
             while not self.servs[host_port].ready:
                 time.sleep(.001)
Esempio n. 56
0
def launch_server_cherrypy(host, port, app):
    """use cherrypy's wsgiserver, a multithreaded scallable server"""
    from cherrypy.wsgiserver import  CherryPyWSGIServer

    server = CherryPyWSGIServer((host, port), app)
    logging.info("Starting CherryPy server, listening on port %s", port)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Esempio n. 57
0
def _start_server():
    from cherrypy.wsgiserver import CherryPyWSGIServer
    from wsgiref.simple_server import demo_app
    from threading import Thread
    import time

    global _httpd
    _httpd = CherryPyWSGIServer(('127.0.0.1', 57909), demo_app,
                                server_name='osmpoint-test-http')
    Thread(target=_httpd.start).start()

    for t in xrange(100):
        if _httpd.ready:
            break
        time.sleep(.01)
    else:
        raise ValueError("CherryPy server has not started")