Example #1
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()
Example #2
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()
Example #3
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()
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
Example #5
0
File: app.py Project: 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()        
Example #6
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)
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()
Example #8
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()
Example #9
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()
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()
Example #11
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()
Example #12
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()
Example #13
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()
Example #14
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()
Example #15
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()
Example #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),
        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")
Example #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()
Example #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()
Example #19
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()
Example #20
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()
Example #21
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")
Example #22
0
File: serve.py Project: 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()
Example #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()
Example #24
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",
        )
Example #25
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
Example #26
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()
Example #27
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()
Example #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()
Example #29
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()
Example #30
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
Example #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()
Example #32
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)
Example #33
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.
Example #34
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()
Example #35
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()
Example #36
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.
Example #37
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
Example #38
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()
Example #39
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()
Example #40
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()
Example #41
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()
Example #42
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()
def start_server(options):
    """
    Start CherryPy server

    Want SSL support?
    a. The new (3.1 or 3.2) way: Just set server.ssl_adapter to an SSLAdapter instance.
    b. The old way (deprecated way) is to set these attributes:

       server.ssl_certificate = <filename>
       server.ssl_private_key = <filename>

       But this is the only way from the management command line
       in the future I may need to adapt this to use a server.ssl_adapter

    """

    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 django_wsgiserver.wsgiserver import CherryPyWSGIServer
    from cherrypy.wsgiserver import CherryPyWSGIServer
    from django.core.handlers.wsgi import WSGIHandler
    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)

    server = CherryPyWSGIServer(
        (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:
        logging.debug('starting server with options:\n%s' % pformat(options))
        server.start()
    except KeyboardInterrupt:
        server.stop()
Example #44
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()
Example #45
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()
Example #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()
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()
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()
Example #49
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()
Example #50
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'])
    )
    
  SERVER2 = Server(
      (options['host'], int(options['eport'])),
      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:
    if options['ssl_certificate'].lower() == 'none' or options['ssl_private_key'].lower() == 'none':
      SERVER.start()
      
    else:
      from multiprocessing import Process
      p = Process(target=SERVER.start)
      p.start()
      
      SERVER2.start()
      
  except KeyboardInterrupt:
    SERVER.stop()
    if options['ssl_certificate'].lower() == 'none' or options['ssl_private_key'].lower() == 'none':
      pass
      
    else:
      SERVER2.stop()
Example #51
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()
Example #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
    
    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()
Example #53
0
class test(unittest.TestCase):

    def setUp(self):
        self.server = CherryPyWSGIServer(('127.0.0.1',9191),TestService())
        t = Thread(target=self.server.start)
        t.start()
        time.sleep(3)

    def tearDown(self):
        self.server.stop()
        time.sleep(3)

    def test_simple(self):
        inMessage = Message('a',[('s',String),('i',Integer)])
        outMessage = Message('aResponse',[('retval',DateTime)])
        
        desc = MethodDescriptor('a','a',inMessage,outMessage,'')

        client = SimpleSoapClient('127.0.0.1:9191','/',desc)
        results = client('abc',54)
        self.assertEquals(results,datetime.datetime(1901,12,15))    

    def test_nested(self):
        inMessage = Message('b',[('p',Person),('s',String),('a',Integer)])
        outMessage = Message('bResponse',[('retval',Address)])
        
        desc = MethodDescriptor('b','b',inMessage,outMessage,'')

        client = SimpleSoapClient('127.0.0.1:9191','/',desc)
        p = Person()
        p.name = 'wilson'
        p.addresses = []
        for i in range(0,123):
            a = Address()
            a.zip = i
            p.addresses.append(a)
        res = client(p,'abc',123)
        self.assertEquals(res.longitude,None)
        self.assertEquals(res.zip,4444)
        self.assertEquals(res.street,'wsgi way')

    def test_async(self):
        inMessage = Message('d',[('person',Person)])
        outMessage = Message('dResponse',[])

        desc = MethodDescriptor('d','d',inMessage,outMessage,'')
        
        client = SimpleSoapClient('127.0.0.1:9191','/',desc)
        p = Person()
        p.name = 'wilson'
        r = client(p)
        self.assertEquals(r,None)
        
    def test_fault(self):
        inMessage = Message('fault',[])
        outMessage = Message('faultResponse',[])
        desc = MethodDescriptor('fault','fault',inMessage,outMessage,'')
        
        client = SimpleSoapClient('127.0.0.1:9191','/',desc)
        try:
            client()
        except Fault, f:
            self.assertEquals(f.faultcode,'faultFault')
            self.assertEquals(f.faultstring,'Testing faults')
            #self.assertTrue(f.detail.find('client_test.py') > -1)
        else:
Example #54
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
Example #55
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()