示例#1
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()
示例#2
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()
示例#3
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()
示例#4
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()
示例#5
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()
示例#6
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()
示例#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)
示例#8
0
文件: runmss.py 项目: neoclust/mss
        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)
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()
示例#10
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()
示例#11
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)
示例#12
0
文件: app.py 项目: 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()        
示例#13
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()
示例#14
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()
示例#15
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")
示例#16
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()
示例#17
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()
示例#18
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()
示例#19
0
文件: serve.py 项目: 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()
示例#20
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")
示例#21
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()
示例#22
0
文件: rest.py 项目: HengWang/openbmc
 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()
示例#23
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()
示例#24
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()
示例#25
0
文件: runwsgi.py 项目: amitu/dutils
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",
        )
示例#26
0
 def run(self, handler):
     server = CherryPyWSGIServer((self.host, self.port),
                                 handler,
                                 server_name='localhost')
     try:
         server.start()
     except Exception as e:
         error = parse_exception(e)
         log_exception(error_log_path, error)
         print(error)
     finally:
         server.stop()
示例#27
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()
示例#28
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()
示例#29
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)
示例#30
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()
示例#31
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
    import cherrypy 

    from django.core.handlers.wsgi import WSGIHandler

    if options['static']: 
        # If we want a static directory, wrap the regular app
        # with cherrypy.tree.mount() to serve static dir. 

        app = WSGIHandler()
        cherrypy.config.update({'global': {'log.screen': True}})
        conf = {
            '/' : {
                'tools.wsgiapp.on': True, 
                'tools.wsgiapp.app': app
            }, 
            '/static' : {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': options['static']
            }
        }
    
        full_app = cherrypy.tree.mount(app, '/', config=conf) 
        
    else:

        full_app = WSGIHandler() 

    server = Server(
        (options['host'], int(options['port'])), 
        full_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()
示例#32
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.
示例#33
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.")
示例#34
0
文件: server.py 项目: cdent/tsapp
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)
示例#35
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()
示例#36
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()
示例#37
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)
示例#38
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.
示例#39
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
示例#40
0
文件: wsgi.py 项目: brosner/oebfare
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()
示例#41
0
def start_server (options):
  if options['daemonize']:
    if options['server_user'] and options['server_group']:
      change_uid_gid(options['server_user'], options['server_group'])
      
    if options['workdir']:
      become_daemon(our_home_dir=options['workdir'])
      
    else:
      become_daemon()
      
    fp = open(options['pidfile'], 'w')
    fp.write("%d\n" % os.getpid())
    fp.close()
    
  d = WSGIPathInfoDispatcher({'/static': static, '/': WSGIHandler()})
  SERVER = Server(
      (options['host'], int(options['port'])),
      d, 
      numthreads=int(options['threads']),
      max=int(options['threads']), 
      server_name=options['server_name'],
      shutdown_timeout = int(options['shutdown_timeout']),
      request_queue_size = int(options['request_queue_size'])
    )
    
  if options['ssl_certificate'].lower() == 'none' or options['ssl_private_key'].lower() == 'none':
    pass
    
  else:
    if not os.path.exists(options['ssl_certificate']) or not os.path.exists(options['ssl_private_key']):
      if options['ssl_certificate'] == settings.SERVER_CERT and options['ssl_private_key'] == settings.SERVER_KEY:
        generate_cert()
        
      else:
        raise Exception('Invalid Certificate or Key Path')
        
    SERVER.ssl_certificate = options['ssl_certificate']
    SERVER.ssl_private_key = options['ssl_private_key'] 
    
  try:
    SERVER.start()
    
  except KeyboardInterrupt:
    SERVER.stop()
示例#42
0
文件: serve.py 项目: tup/tiddlyweb
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()
示例#43
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()
示例#44
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()
示例#45
0
    def run(self, handler):
        server = CherryPyWSGIServer((self.host, self.port), handler, server_name='localhost')
        """
        openssl genrsa -out privkey.pem 1024
        openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095
        """
        crt = '/etc/coinbend/cacert.pem'
        key = '/etc/coinbend/privkey.pem'
        #ca  = '/etc/ssl/intermediate.crt'
        server.ssl_module  = "pyopenssl"
        server.ssl_adapter = PatchBuiltinSSLAdapter(crt, key)

        # f*****g p.o.s. cherry does NOT support prebuilt ssl contexts
        #server.ssl_adapter.context = sc

        try:
            server.start()
        finally:
            server.stop()
示例#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()
示例#47
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()
示例#48
0
def run_rack_manager_default(app,
                             ssl_enabled,
                             host='0.0.0.0',
                             port=8080,
                             number_threads=30,
                             config=None,
                             **kwargs):
    if config is not None:
        cpy.config.update(config)

    server = CherryPyWSGIServer((host, port),
                                app,
                                numthreads=number_threads,
                                **kwargs)

    if (ssl_enabled):
        server.ssl_adapter = pyOpenSSLAdapter(
            certificate="/usr/lib/sslcerts/certs.pem",
            private_key="/usr/lib/sslcerts/privkey.pem")

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
示例#49
0
class HTTPDaemon(object):
    """HTTP Server class. Mostly based on Cherrypy

    It uses CherryPyWSGIServer and daemon http_interface as Application
    """
    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)

    def run(self):
        """Wrapper to start http daemon server

        :return: None
        """
        try:
            self.srv.start()
        except socket.error, exp:  # pragma: no cover, not during tests
            msg = "Error: Sorry, the port %d is not free: %s" % (self.port, str(exp))
            raise PortNotFree(msg)
示例#50
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
    
    import cherrypy
    
    pth = os.path.join(os.path.abspath('..'), 'media')
    pth_ext = os.path.exists(pth)
    
    #MEDIA_ROOT = '/var/projects/%s:%s/media/' % (options['server_name'], int(options['port']) + 1)
    '''
    try:
        if pth_ext:
            MEDIA_ROOT = pth
        else:
            print "Media path is %s" % MEDIA_ROOT
    except: 
        print "Could not create dynamic MEDIA_ROOT path"
        print "%s is missing" % pth
    
    cherrypy.config['tools.staticdir.on']= True
    cherrypy.config['tools.staticdir.dir'] = pth
    '''
    
    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']  
        #'tools.staticdir.on': True,
        #'tools.staticdir.dir': os.path.join(os.path.abspath('..'), 'media'),
    try:
        
        p('Starting server')
        server.start()
        #media_server.start()
        #from cherrypy.process.servers import ServerAdapter
        
        
        #s1 = ServerAdapter(cherrypy.engine, server)
        #s2 = ServerAdapter(cherrypy.engine, media_server)
        
        #s1.subscribe()
        #s2.subscribe()
        
        #cherrypy.engine.start()
    except KeyboardInterrupt:
        p('Stopping server')
        server.stop()
示例#51
0
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import tornado.wsgi

from cherrypy.wsgiserver import CherryPyWSGIServer

from zephyr.app import ZephyrApp
from zephyr.config import ConfigFactory

if __name__ == "__main__":
    config = ConfigFactory.parseFile('$your_conf',
                                     pystyle=True)  # or use SelectConfig
    app = ZephyrApp(config)
    wsgi_app = tornado.wsgi.WSGIAdapter(app)
    server = CherryPyWSGIServer(
        (config.get('cherry.host', 'localhost'), config.get(
            'cherry.port', 8888)),
        wsgi_app,
        server_name='Zephyr',
        numthreads=30)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
示例#52
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
示例#53
0
class WsgiDavDaemon(Daemon):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.config = self._initConfig()
        self._server = None

    def _initConfig(self):
        """Setup configuration dictionary from default, command line and configuration file."""
        from tg import config as tg_config

        # Set config defaults
        config = DEFAULT_CONFIG.copy()
        temp_verbose = config["verbose"]

        # Configuration file overrides defaults
        default_config_file = os.path.abspath(DEFAULT_CONFIG_FILE)
        config_file = tg_config.get('wsgidav.config_path', default_config_file)
        fileConf = self._readConfigFile(config_file, temp_verbose)
        config.update(fileConf)

        if not useLxml and config["verbose"] >= 1:
            print(
                "WARNING: Could not import lxml: using xml instead (slower). Consider installing lxml from http://codespeak.net/lxml/."
            )
        from wsgidav.dir_browser import WsgiDavDirBrowser
        from tracim.lib.webdav.tracim_http_authenticator import TracimHTTPAuthenticator
        from wsgidav.error_printer import ErrorPrinter
        from tracim.lib.webdav.utils import TracimWsgiDavDebugFilter

        config['middleware_stack'] = [
            WsgiDavDirBrowser,
            TracimHTTPAuthenticator,
            ErrorPrinter,
            TracimWsgiDavDebugFilter,
        ]

        config['provider_mapping'] = {
            config['root_path']:
            Provider(
                # TODO: Test to Re enabme archived and deleted
                show_archived=False,  # config['show_archived'],
                show_deleted=False,  # config['show_deleted'],
                show_history=False,  # config['show_history'],
                manage_locks=config['manager_locks'])
        }

        config['domaincontroller'] = TracimDomainController(presetdomain=None,
                                                            presetserver=None)

        return config

    def _readConfigFile(self, config_file, verbose):
        """Read configuration file options into a dictionary."""

        if not os.path.exists(config_file):
            raise RuntimeError("Couldn't open configuration file '%s'." %
                               config_file)

        try:
            import imp
            conf = {}
            configmodule = imp.load_source("configuration_module", config_file)

            for k, v in vars(configmodule).items():
                if k.startswith("__"):
                    continue
                elif isfunction(v):
                    continue
                conf[k] = v
        except Exception as e:
            exceptioninfo = traceback.format_exception_only(
                sys.exc_type, sys.exc_value)  # @UndefinedVariable
            exceptiontext = ""
            for einfo in exceptioninfo:
                exceptiontext += einfo + "\n"

            print("Failed to read configuration file: " + config_file +
                  "\nDue to " + exceptiontext,
                  file=sys.stderr)
            raise

        return conf

    def run(self):
        app = WsgiDAVApp(self.config)

        # Try running WsgiDAV inside the following external servers:
        self._runCherryPy(app, self.config)

    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()

    def stop(self):
        self._server.stop()

    def append_thread_callback(self, callback: collections.Callable) -> None:
        """
        Place here the logic who permit to execute a callback in your daemon.
        To get an exemple of that, take a look at
        socketserver.BaseServer#service_actions  and how we use it in
        tracim.lib.daemons.TracimSocketServerMixin#service_actions .
        :param callback: callback to execute in your thread.
        """
        raise NotImplementedError()
示例#54
0
class ServiceHandler(object):
    def __init__(self):
        # Event flag to communicate between the Run and Stop methods
        self.stopEvent = threading.Event()
        self.server = None

    # Called when the service is starting
    def Initialize(self, configFileName):
        # Environment settings (which are used in the Django settings file and need
        # to be updated BEFORE importing the settings)
        os.environ['DJANGO_SETTINGS_MODULE'] = 'freppledb.settings'
        os.environ['FREPPLE_APP'] = os.path.join(sys.path[0], 'custom')
        os.environ['FREPPLE_HOME'] = os.path.abspath(
            os.path.dirname(sys.argv[0]))
        os.environ['PYTHONPATH'] = \
          os.path.join(sys.path[0], 'lib', 'library.zip') \
          + os.pathsep + \
          os.path.join(sys.path[0], 'lib')

        # Add the custom directory to the Python path.
        sys.path += [os.environ['FREPPLE_APP']]

    # Called when the service is starting immediately after Initialize()
    # use this to perform the work of the service; don't forget to set or check
    # for the stop event or the service GUI will not respond to requests to
    # stop the service
    def Run(self):
        # Import modules
        import cherrypy
        from cherrypy.wsgiserver import CherryPyWSGIServer
        from subprocess import call, DEVNULL
        from win32process import DETACHED_PROCESS, CREATE_NO_WINDOW

        # Initialize django
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', "freppledb.settings")
        os.environ.setdefault('FREPPLE_APP',
                              os.path.join(sys.path[0], 'custom'))
        import django
        django.setup()
        from django.conf import settings
        from django.core.handlers.wsgi import WSGIHandler
        from django.contrib.staticfiles.handlers import StaticFilesHandler

        # Override the debugging settings
        settings.DEBUG = False
        settings.TEMPLATE_DEBUG = False

        # Sys.path contains the zip file with all packages. We need to put the
        # application directory into the path as well.
        sys.path += [os.environ['FREPPLE_APP']]

        # Append all output to a unbuffered log stream
        with open(os.path.join(settings.FREPPLE_LOGDIR, 'service.log'),
                  'a') as logfile:
            sys.stderr = sys.stdout = logfile
            try:
                # Using the included postgres database
                # Check if the database is running. If not, start it.
                if os.path.exists(
                        os.path.join(settings.FREPPLE_HOME, '..', 'pgsql',
                                     'bin', 'pg_ctl.exe')):
                    status = call([
                        os.path.join(settings.FREPPLE_HOME, '..', 'pgsql',
                                     'bin', 'pg_ctl.exe'), "--pgdata",
                        os.path.join(settings.FREPPLE_LOGDIR, 'database'),
                        "--silent", "status"
                    ],
                                  stdin=DEVNULL,
                                  stdout=DEVNULL,
                                  stderr=DEVNULL,
                                  creationflags=CREATE_NO_WINDOW)
                    if status:
                        print("%s\tStarting the PostgreSQL database" %
                              datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                              flush=True)
                        call([
                            os.path.join(settings.FREPPLE_HOME, '..', 'pgsql',
                                         'bin', 'pg_ctl.exe'), "--pgdata",
                            os.path.join(settings.FREPPLE_LOGDIR, 'database'),
                            "--log",
                            os.path.join(settings.FREPPLE_LOGDIR, 'database',
                                         'server.log'), "start"
                        ],
                             stdin=DEVNULL,
                             stdout=DEVNULL,
                             stderr=DEVNULL,
                             creationflags=DETACHED_PROCESS)

                # Prepare web server
                cherrypy.config.update({
                    'global': {
                        'log.screen': False,
                        'tools.log_tracebacks.on': True,
                        'engine.autoreload.on': False,
                        'engine.SIGHUP': None,
                        'engine.SIGTERM': None
                    }
                })
                self.server = CherryPyWSGIServer(
                    (settings.ADDRESS, settings.PORT),
                    StaticFilesHandler(WSGIHandler()))

                # Synchronize the scenario table with the settings
                from freppledb.common.models import Scenario
                Scenario.syncWithSettings()

                # Infinite loop serving requests
                # The loop gets interrupted when the service gets ordered to shut down.
                print("%s\tfrePPLe web server listening on http://%s:%d" %
                      (datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                       settings.ADDRESS, settings.PORT),
                      flush=True)
                self.server.start()
                print("%s\tStopping service" %
                      datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                      flush=True)

                # Using the included postgres database?
                if os.path.exists(
                        os.path.join(settings.FREPPLE_HOME, '..', 'pgsql',
                                     'bin', 'pg_ctl.exe')):
                    # Check if the database is running. If so, stop it.
                    os.environ['PATH'] = os.path.join(
                        settings.FREPPLE_HOME, '..', 'pgsql',
                        'bin') + os.pathsep + os.environ['PATH']
                    status = call([
                        os.path.join(settings.FREPPLE_HOME, '..', 'pgsql',
                                     'bin', 'pg_ctl.exe'), "--pgdata",
                        os.path.join(settings.FREPPLE_LOGDIR, 'database'),
                        "--silent", "status"
                    ],
                                  stdin=DEVNULL,
                                  stdout=DEVNULL,
                                  stderr=DEVNULL,
                                  creationflags=CREATE_NO_WINDOW)
                    if not status:
                        print("%s\tShutting down the database" %
                              datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                              flush=True)
                        call(
                            [
                                os.path.join(settings.FREPPLE_HOME, '..',
                                             'pgsql', 'bin', 'pg_ctl.exe'),
                                "--pgdata",
                                os.path.join(settings.FREPPLE_LOGDIR,
                                             'database'),
                                "--log",
                                os.path.join(settings.FREPPLE_LOGDIR,
                                             'database', 'server.log'),
                                "-w",  # Wait till it's down
                                "stop"
                            ],
                            stdin=DEVNULL,
                            stdout=DEVNULL,
                            stderr=DEVNULL,
                            creationflags=CREATE_NO_WINDOW)

                # Notify the manager
                self.stopEvent.set()

            except Exception as e:
                print("%s\tfrePPLe web server failure: %s" %
                      (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), e),
                      flush=True)

    # Called when the service is being stopped by the service manager GUI
    def Stop(self):
        if not self.server:
            return

        # Stop the CherryPy server
        self.server.stop()

        # Wait till stopped
        self.stopEvent.wait()
示例#55
0
文件: daemon.py 项目: pwgen/alignak
class HTTPDaemon(object):
    """HTTP Server class. Mostly based on Cherrypy
    It uses CherryPyWSGIServer and daemon http_interface as Application
    """
    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

    def run(self):
        """Wrapper to start http daemon server

        :return: None
        """
        try:
            self.srv.start()
        except socket.error, exp:
            msg = "Error: Sorry, the port %d is not free: %s" % (self.port, str(exp))
            raise PortNotFree(msg)