示例#1
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)
示例#2
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()
示例#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
文件: 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()
示例#5
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()
示例#6
0
def run_server(app):
    http_config = app.config['rest_api']['http']
    https_config = app.config['rest_api']['https']

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

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

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

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

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

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

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

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

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

    try:
        cherrypy.engine.start()
        cherrypy.engine.block()
    except KeyboardInterrupt:
        cherrypy.engine.stop()
示例#7
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()
示例#8
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()
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()
示例#10
0
        check_file('CA_CERTIFICATE_FILE', CA_CERTIFICATE_FILE)
        check_file('PARTNER_CERTIFICATE', PARTNER_CERTIFICATE)
        check_file('PARTNER_PRIVATE_KEY', PARTNER_PRIVATE_KEY)
        check_string('HFPP_PARTNER_ID', HFPP_PARTNER_ID)
        check_port('PARTNER_CLIENT_HTTP_SERVICE_PORT',
                   PARTNER_CLIENT_HTTP_SERVICE_PORT)
        check_bool('PARTNER_IMMEDIATE_FULLFIL', PARTNER_IMMEDIATE_FULLFIL)
        check_string('DECISION_MODULE_URL', DECISION_MODULE_URL)
        check_file('STUDY_REPORT_DIRECTORY', STUDY_REPORT_DIRECTORY)
        #badly formed hexadecimal UUID string will throw if not uuid string
        partner_id = uuid.UUID(HFPP_PARTNER_ID)
        logging.debug('hfpp partner id:%s', partner_id)
    except (TypeError, ValueError) as e:
        method_error(signature, e)
        sys.exit(-1)
    conf = {'global': {'request.error_response': handle_error}}
    #configure cherrypy
    cherrypy.config.update(conf)

    wsgi_app = cherrypy.Application(PartnerHTTPServices(), '/callbacks')
    dispatcher = WSGIPathInfoDispatcher({'/': wsgi_app})
    server = CherryPyWSGIServer(('0.0.0.0', PARTNER_CLIENT_HTTP_SERVICE_PORT),
                                dispatcher)
    sslAdapter = BuiltinSSLAdapter(PARTNER_CERTIFICATE, PARTNER_PRIVATE_KEY)
    server.ssl_adapter = sslAdapter
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
    method_exit(signature)
        check_file('PARTNER_PRIVATE_KEY', PARTNER_PRIVATE_KEY)
        check_string('HFPP_PARTNER_ID',HFPP_PARTNER_ID)
        check_port('PARTNER_CLIENT_HTTP_SERVICE_PORT',PARTNER_CLIENT_HTTP_SERVICE_PORT)
        check_bool('PARTNER_IMMEDIATE_FULLFIL', PARTNER_IMMEDIATE_FULLFIL)
        check_string('DECISION_MODULE_URL', DECISION_MODULE_URL)
        check_file('STUDY_REPORT_DIRECTORY', STUDY_REPORT_DIRECTORY)
        #badly formed hexadecimal UUID string will throw if not uuid string
        partner_id = uuid.UUID(HFPP_PARTNER_ID)
        logging.debug('hfpp partner id:%s',partner_id)
    except (TypeError,ValueError) as e:
        method_error(signature, e)
        sys.exit(-1)
    conf = {'global': {
            'request.error_response' : handle_error
        }
    }
    #configure cherrypy
    cherrypy.config.update(conf)
    
    wsgi_app = cherrypy.Application(PartnerHTTPServices(), '/callbacks')
    dispatcher = WSGIPathInfoDispatcher({'/': wsgi_app})
    server = CherryPyWSGIServer(('0.0.0.0', PARTNER_CLIENT_HTTP_SERVICE_PORT), dispatcher)
    sslAdapter = BuiltinSSLAdapter(PARTNER_CERTIFICATE, PARTNER_PRIVATE_KEY)
    server.ssl_adapter = sslAdapter
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
    method_exit(signature)

示例#12
0
    def start_server_servestatic(self, options):
        """
        Start CherryPy server AND serve default static files

        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

        """
        # debug?
        # print "options:"
        from django.conf import settings
        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'

        self.stdout.write("Validating models..")
        self.validate(display_num_errors=True)
        self.stdout.write((
            "%(started_at)s\n"
            "Django version %(version)s, using settings %(settings)r\n"
            "cherrypy django_wsgiserver is running at http://%(addr)s:%(port)s/\n"
            "Quit the server with %(quit_command)s.\n"
        ) % {
            "started_at": datetime.now().strftime('%B %d, %Y - %X'),
            "version": self.get_version(),
            "settings": settings.SETTINGS_MODULE,
            "addr": options['host'],  # self._raw_ipv6 and '[%s]' % self.addr or self.addr,
            "port": options['port'],
            "quit_command": quit_command,
        })

        #logger.info("launching wsgiserver with the following options")
        # logger.info(pformat(options))
        if int(options['verbose']) >= 2:
            self.stdout.write("launching with the following options:\n")
            self.stdout.write(pformat(options))

        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, WSGIPathInfoDispatcher
        #from cherrypy.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher

        from django.core.handlers.wsgi import WSGIHandler
        from django.conf import settings
        app = WSGIHandler()  # serve the django content
        path = {'/': app}  # well will build up the serving url routing path below

        # Now work on serving the static content
        # note as of django 1.4, ADMIN_MEDIA_PREFIX is depreciated and instead uses django.contrib.staticfiles
        # so it is not an error for ADMIN_MEDIA_PREFIX to not be defined, I will test to see if exists
        # and print a warning that adminserve is activated but it's not defined.
        # so for django 1.4 (or 1.5 ?) staticserve=True => adminserve=True
        # so the choices
        # There are basically two ways for statics to be served
        # 1. in development, one often wants each application's static files to be served from within its file structure
        #    this is what the django runserver dose
        # 2. in production usually, all the static files are collected into a common storage region (files, S3, CDN) and a good webserver
        #    serve them from there

        # deprecated
        # if options['adminserve']: # serve the admin media too
        # AdminMediaHandler is middleware for local use
        # import django.core.servers.basehttp
        # adminapp = django.core.servers.basehttp.AdminMediaHandler(app)
        # another way to serve the admin media three application
        #     if settings.__dict__.has_key('ADMIN_MEDIA_PREFIX'):
        #         import django.contrib.admin

        #         path[settings.ADMIN_MEDIA_PREFIX] = django_wsgiserver.mediahandler.StaticFileWSGIApplication(
        #             os.path.join( django.contrib.admin.__path__[0], 'media'))
        #     else:
        #         print "Warning adminserve was selected BUT ADMIN_MEDIA_PREFIX was not defined"

        if options['staticserve']:
            try:
                if not settings.STATIC_URL or not settings.STATIC_ROOT:
                    # could use misconfigured exception (what is this in django)  instead of AttributeError
                    fmtargs = (settings.STATIC_URL, settings.STATIC_ROOT)
                    errmsg = ((
                        "settings.STATIC_URL = {!r},"
                        "settings.STATIC_ROOT={!r}").format(*fmtargs))

                    raise AttributeError(errmsg)
            except AttributeError as msg:
                logger.error(msg)
                logger.error("****")
                logger.error("STATIC_URL and STATIC_ROOT  must be set in settings file for staticserve option to work in django_wsgiserver")
                logger.error("****")
                raise

            if options['staticserve'] != 'collectstatic':
                if settings.STATICFILES_FINDERS:  # find the apps' static files and add them to the path
                    logger.debug("see settings.STATICFILES_FINDERS")
                    logger.debug(pformat(settings.STATICFILES_FINDERS))
                    from django.contrib.staticfiles.finders import AppDirectoriesFinder
                    app_static_finder = AppDirectoriesFinder(settings.INSTALLED_APPS)
                    logger.debug("app_static_finder.storages:")
                    logger.debug(pformat(app_static_finder.storages))
                    for key, val in app_static_finder.storages.items():
                        logger.debug(key, " static location:", val.location)
                    # need to decide what to do with this in terms of the fusion of the app static directories
                        app_url = key.split('.')[-1] + r'/'  # I'm not sure if it needs the end '/'
                        full_static_url = os.path.join(settings.STATIC_URL, app_url)
                        full_dir_location = os.path.join(val.location, app_url)
                        logger.debug(full_static_url, full_dir_location)
                        path[full_static_url] = django_wsgiserver.wsgiutil.StaticFileWSGIApplication(full_dir_location)

            if options['servestaticdirs'] and hasattr(settings, 'STATICFILES_DIRS'):
                staticlocations = process_staticfiles_dirs(settings.STATICFILES_DIRS)
                # debug !!!
                logger.debug("staticlocations::")
                logger.debug(pformat(staticlocations))
                for urlprefix, root in staticlocations:
                    path[os.path.join(settings.STATIC_URL, urlprefix)] = django_wsgiserver.wsgiutil.StaticFileWSGIApplication(root)

            # One important thing is that there are two different ways to serve the static files
            # 1. convenient: serve each app's static files (assuming they follow convention)
            # 2. do a collectstatic and serve from that node -- likely this would be done more in a "production" scenario

            if options['staticserve'] == 'collectstatic':
                # and serve the root of the STATIC_URL ? hmm !!!
                path[settings.STATIC_URL] = django_wsgiserver.wsgiutil.StaticFileWSGIApplication(settings.STATIC_ROOT)
                logger.warning("serving all static files from %s. *** Make sure you have done a fresh collectstatic operation ***" % settings.STATIC_ROOT)

        # debug
        logger.debug("path:", pformat(path))
        dispatcher = WSGIPathInfoDispatcher(path)
        logger.debug("apps:", pformat(dispatcher.apps))

        if options['verbose'] == '1':
            from django_wsgiserver.wsgiutil import WSGIRequestLoggerMiddleware
            dispatcher = WSGIRequestLoggerMiddleware(dispatcher)
            logger.setLevel(10)

        if int(options['verbose']) >= 2:
            from django_wsgiserver.wsgiutil import WSGIRequestLoggerMiddleware
            dispatcher = WSGIRequestLoggerMiddleware(dispatcher)
            logger.setLevel(logging.INFO)

        server = CherryPyWSGIServer(
            (options['host'], int(options['port'])),
            dispatcher,
            int(options['threads']),
            options['server_name']
        )
        if options['ssl_certificate'] and options['ssl_private_key']:
            Adapter = wsgiserver.get_ssl_adapter_class()
            try:
                server.ssl_adapter = Adapter(certificate=options['ssl_certificate'],
                                             private_key=options['ssl_private_key'])
            except ImportError:
                pass  # because we can try again
            try:
                Adapter = wsgiserver.get_ssl_adapter_class('builtin')
                server.ssl_adapter = Adapter(certificate=options['ssl_certificate'],
                                             private_key=options['ssl_private_key'])
            except ImportError:
                Adapter = None
                raise
        try:
            server.start()
        except KeyboardInterrupt:
            server.stop()
示例#13
0
    sock.settimeout(1)
    try:
        sock.connect(('127.0.0.1', PORT))
        return True
    except Exception, err:
        return False
    finally:
        sock.close()


if __name__ == '__main__':
    if is_server_started():
        print('Git server is already started')
        sys.exit(0)

    certfile = keyfile = None
    if len(sys.argv) > 1:
        certfile = sys.argv[1]
    if len(sys.argv) > 2:
        keyfile = sys.argv[2]

    app = assemble_WSGI_git_app(content_path=GIT_DIR, uri_marker=URI_MARKER)
    httpd = CherryPyWSGIServer(('0.0.0.0', PORT), app)

    if certfile:
        httpd.ssl_adapter = SSLAdapter(certfile, keyfile)

    signal.signal(signal.SIGINT, stop)
    httpd.start()