Пример #1
0
 def _run(self, conf):
     cherrypy.server.using_wsgi = True
     cherrypy.server.using_apache = True
     cherrypy.server.httpserver = servers.FlupFCGIServer(
         application=cherrypy.tree, bindAddress=('127.0.0.1', 4000))
     cherrypy.server.httpserver.bind_addr = ('127.0.0.1', 4000)
     try:
         start_apache(self.host, self.port, conf_fcgid)
         return test.TestHarness._run(self, conf)
     finally:
         stop()
Пример #2
0
 def start(self, modulename):
     cherrypy.server.httpserver = servers.FlupFCGIServer(
         application=cherrypy.tree, bindAddress=('127.0.0.1', 4000))
     cherrypy.server.httpserver.bind_addr = ('127.0.0.1', 4000)
     self.start_apache()
     helper.LocalServer.start(self, modulename)
Пример #3
0
def serve(**kwargs):
    """
    Spawn a new running Cherrypy process

    usage: blubeberry serve [options]

    options:
      -h, --help                                 show this help message and exit
      -b BINDING, --bind BINDING                 the address and port to bind to.
                                                 [default: 127.0.0.1:8080]
      -e ENVIRONMENT, --environment ENVIRONMENT  apply the given config environment
      -C ENV_VAR_NAME, --env-var ENV_VAR_NAME    add the given config from environment variable name
                                                 [default: BLUEBERRYPY_CONFIG]
      -f                                         start a fastcgi server instead of the default HTTP
                                                 server
      -s                                         start a scgi server instead of the default HTTP
                                                 server
      -d, --daemonize                            run the server as a daemon. [default: False]
      -p, --drop-privilege                       drop privilege to separately specified umask, uid
                                                 and gid. [default: False]
      -P PIDFILE, --pidfile PIDFILE              store the process id in the given file
      -u UID, --uid UID                          setuid to uid [default: www]
      -g GID, --gid GID                          setgid to gid [default: www]
      -m UMASK, --umask UMASK                    set umask [default: 022]

    """

    config = BlueberryPyConfiguration(config_dir=kwargs.get('config_dir'),
                                      env_var_name=kwargs.get('env_var'))

    cpengine = cherrypy.engine

    cpenviron = kwargs.get("environment")
    if cpenviron:
        config = BlueberryPyConfiguration(config_dir=kwargs.get('config_dir'),
                                          env_var_name=kwargs.get('env_var'),
                                          environment=cpenviron)
        cherrypy.config.update({"environment": cpenviron})

    if config.use_email and config.email_config:
        from blueberrypy import email
        email.configure(config.email_config)

    if config.use_logging and config.logging_config:
        from blueberrypy.plugins import LoggingPlugin
        cpengine.logging = LoggingPlugin(cpengine, config=config.logging_config)

    if config.use_redis:
        from blueberrypy.session import RedisSession
        cherrypy.lib.sessions.RedisSession = RedisSession

    if config.use_sqlalchemy:
        from blueberrypy.plugins import SQLAlchemyPlugin
        cpengine.sqlalchemy = SQLAlchemyPlugin(cpengine,
                                               config=config.sqlalchemy_config)
        from blueberrypy.tools import SQLAlchemySessionTool
        cherrypy.tools.orm_session = SQLAlchemySessionTool()

    if config.use_jinja2:
        if config.webassets_env:
            configure_jinja2(assets_env=config.webassets_env,
                             **config.jinja2_config)
        else:
            configure_jinja2(**config.jinja2_config)

    # update global config first, so subsequent command line options can
    # override the settings in the config files
    cherrypy.config.update(config.app_config)

    if kwargs.get("bind"):
        address, port = kwargs.get("bind").strip().split(":")
        cherrypy.server.socket_host = address
        cherrypy.server.socket_port = int(port)

    if kwargs.get("daemonize"):
        cherrypy.config.update({'log.screen': False})
        Daemonizer(cpengine).subscribe()

    if kwargs.get("drop_privilege"):
        cherrypy.config.update({'engine.autoreload_on': False})
        DropPrivileges(cpengine, umask=int(kwargs.get("umask")),
                       uid=kwargs.get("uid") or "www",
                       gid=kwargs.get("gid") or "www").subscribe()

    if kwargs.get("pidfile"):
        PIDFile(cpengine, kwargs.get("pidfile")).subscribe()

    fastcgi, scgi = kwargs.get("fastcgi"), kwargs.get("scgi")
    if fastcgi and scgi:
        cherrypy.log.error("You may only specify one of the fastcgi and "
                           "scgi options.", 'ENGINE')
        sys.exit(1)
    elif fastcgi or scgi:
        # Turn off autoreload when using *cgi.
        cherrypy.config.update({'engine.autoreload_on': False})
        # Turn off the default HTTP server (which is subscribed by default).
        cherrypy.server.unsubscribe()

        addr = cherrypy.server.bind_addr
        if fastcgi:
            f = servers.FlupFCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        elif scgi:
            f = servers.FlupSCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        s = servers.ServerPlugin(cpengine, httpserver=f, bind_addr=addr)
        s.subscribe()

    if hasattr(cpengine, 'signal_handler'):
        cpengine.signal_handler.subscribe()

    # for win32 only
    if hasattr(cpengine, "console_control_handler"):
        cpengine.console_control_handler.subscribe()

    # mount the controllers
    for script_name, section in config.controllers_config.viewitems():
        section = section.copy()
        controller = section.pop("controller")
        if isinstance(controller, cherrypy.dispatch.RoutesDispatcher):
            routes_config = {'/': {"request.dispatch": controller}}
            for path in section.viewkeys():
                if path.strip() == '/':
                    routes_config['/'].update(section['/'])
                else:
                    routes_config[path] = section[path].copy()
            app_config = config.app_config.copy()
            app_config.pop("controllers")
            routes_config.update(app_config)
            cherrypy.tree.mount(None, script_name=script_name,
                                config=routes_config)
        else:
            app_config = config.app_config.copy()
            app_config.pop("controllers")
            controller_config = section.copy()
            controller_config.update(app_config)
            cherrypy.tree.mount(controller(), script_name=script_name,
                                config=controller_config)

    # Add the blueberrypy config files into CP's autoreload monitor
    # Jinja2 templates are monitored by Jinja2 itself and will autoreload if
    # needed
    if config.config_file_paths:
        for path in config.config_file_paths:
            cpengine.autoreload.files.add(path)

    try:
        cpengine.start()
    except:
        sys.exit(1)
    else:
        cpengine.block()
Пример #4
0
    try:
        maroon.Model.database = maroon.MongoDB(name=settings.mongo_database,
                                               host=settings.mongo_host)

        if settings.production:
            cherrypy.config.update("etc/crowdy_prod.conf")
            cherrypy.tree.mount(api, "/api/1", config="etc/api.conf")
            cherrypy.tree.mount(web, "/", config="etc/web.conf")

            # taken from the cherryd script
            engine = cherrypy.engine
            if hasattr(engine, "signal_handler"):
                engine.signal_handler.subscribe()
            if hasattr(engine, "console_control_handler"):
                engine.console_control_handler.subscribe()
            cherrypy.server.unsubscribe()
            addr = cherrypy.server.bind_addr
            f = servers.FlupFCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
            s = servers.ServerAdapter(engine, httpserver=f, bind_addr=addr)
            s.subscribe()

            engine.start()
            engine.block()
        else:
            cherrypy.config.update("etc/crowdy.conf")
            cherrypy.tree.mount(api, "/api/1", config="etc/api.conf")
            cherrypy.quickstart(web, "/", config="etc/web.conf")
    except:
        traceback.print_exc()
Пример #5
0
def start(configfiles=None,
          daemonize=False,
          environment=None,
          fastcgi=False,
          scgi=False,
          pidfile=None,
          imports=None,
          cgi=False):
    """Subscribe all engine plugins and start the engine."""
    sys.path = [''] + sys.path
    for i in imports or []:
        exec("import %s" % i)

    for c in configfiles or []:
        cherrypy.config.update(c)
        # If there's only one app mounted, merge config into it.
        if len(cherrypy.tree.apps) == 1:
            for app in cherrypy.tree.apps.values():
                if isinstance(app, Application):
                    app.merge(c)

    engine = cherrypy.engine

    if environment is not None:
        cherrypy.config.update({'environment': environment})

    # Only daemonize if asked to.
    if daemonize:
        # Don't print anything to stdout/sterr.
        cherrypy.config.update({'log.screen': False})
        plugins.Daemonizer(engine).subscribe()

    if pidfile:
        plugins.PIDFile(engine, pidfile).subscribe()

    if hasattr(engine, "signal_handler"):
        engine.signal_handler.subscribe()
    if hasattr(engine, "console_control_handler"):
        engine.console_control_handler.subscribe()

    if (fastcgi and (scgi or cgi)) or (scgi and cgi):
        cherrypy.log.error(
            "You may only specify one of the cgi, fastcgi, and "
            "scgi options.", 'ENGINE')
        sys.exit(1)
    elif fastcgi or scgi or cgi:
        # Turn off autoreload when using *cgi.
        cherrypy.config.update({'engine.autoreload_on': False})
        # Turn off the default HTTP server (which is subscribed by default).
        cherrypy.server.unsubscribe()

        addr = cherrypy.server.bind_addr
        if fastcgi:
            f = servers.FlupFCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        elif scgi:
            f = servers.FlupSCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        else:
            f = servers.FlupCGIServer(application=cherrypy.tree,
                                      bindAddress=addr)
        s = servers.ServerAdapter(engine, httpserver=f, bind_addr=addr)
        s.subscribe()

    # Always start the engine; this will start all other services
    try:
        engine.start()
    except:
        # Assume the error has been logged already via bus.log.
        sys.exit(1)
    else:
        engine.block()
Пример #6
0
def start(configfile=None,
          daemonize=False,
          environment=None,
          fastcgi=False,
          scgi=False,
          pidfile=None,
          cgi=False,
          debug=False,
          context_root='/'):
    """Subscribe all engine plugins and start the engine."""
    sys.path = [''] + sys.path

    # monkey patching cherrypy to disable config interpolation
    def new_as_dict(self, raw=True, vars=None):
        """Convert an INI file to a dictionary"""
        # Load INI file into a dict
        result = {}
        for section in self.sections():
            if section not in result:
                result[section] = {}
            for option in self.options(section):
                value = self.get(section, option, raw=raw, vars=vars)
                try:
                    value = cherrypy.lib.reprconf.unrepr(value)
                except Exception:
                    x = sys.exc_info()[1]
                    msg = ("Config error in section: %r, option: %r, "
                           "value: %r. Config values must be valid Python." %
                           (section, option, value))
                    raise ValueError(msg, x.__class__.__name__, x.args)
                result[section][option] = value
        return result

    cherrypy.lib.reprconf.Parser.as_dict = new_as_dict

    class Root(object):
        @cherrypy.expose
        def index(self):
            return 'Nothing here'

    instance = LdapCherry()
    if context_root != '/':
        root = cherrypy.tree.mount(Root())
    app = cherrypy.tree.mount(instance, context_root, configfile)
    cherrypy.config.update(configfile)
    instance.reload(app.config, debug)

    engine = cherrypy.engine

    # Turn off autoreload
    cherrypy.config.update({'engine.autoreload.on': False})

    if environment is not None:
        cherrypy.config.update({'environment': environment})

    # Only daemonize if asked to.
    if daemonize:
        # Don't print anything to stdout/sterr.
        cherrypy.config.update({'log.screen': False})
        plugins.Daemonizer(engine).subscribe()

    if pidfile:
        plugins.PIDFile(engine, pidfile).subscribe()

    if hasattr(engine, "signal_handler"):
        engine.signal_handler.subscribe()
    if hasattr(engine, "console_control_handler"):
        engine.console_control_handler.subscribe()

    if (fastcgi and (scgi or cgi)) or (scgi and cgi):
        cherrypy.log.error(
            "You may only specify one of the cgi, fastcgi, and "
            "scgi options.", 'ENGINE')
        sys.exit(1)
    elif fastcgi or scgi or cgi:
        # Turn off the default HTTP server (which is subscribed by default).
        cherrypy.server.unsubscribe()

        addr = cherrypy.server.bind_addr
        if fastcgi:
            f = servers.FlupFCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        elif scgi:
            f = servers.FlupSCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        else:
            f = servers.FlupCGIServer(application=cherrypy.tree,
                                      bindAddress=addr)
        s = servers.ServerAdapter(engine, httpserver=f, bind_addr=addr)
        s.subscribe()

    # Always start the engine; this will start all other services
    try:
        engine.start()
    except Exception as e:
        # Assume the error has been logged already via bus.log.
        sys.exit(1)
    else:
        engine.block()
Пример #7
0
def start(cgi=False,
          config=None,
          daemon=False,
          debug=False,
          environment=None,
          fastcgi=False,
          gid=None,
          imports=None,
          logs=None,
          path=None,
          pidfile=None,
          quiet=False,
          scgi=False,
          uid=None):
    """Subscribe all engine plugins and start the engine."""

    # Insert paths to the search path
    for p in path or []:
        sys.path.insert(0, p)

    # Import requested modules
    for i in imports or []:
        exec('import %s' % i)

    # SQLAlchemy plugin
    from bdosoa.cherrypy.plugin import SQLAlchemyPlugin
    SQLAlchemyPlugin(cherrypy.engine).subscribe()

    # SQLAlchemy tool
    from bdosoa.cherrypy.tool import SQLAlchemyTool
    cherrypy.tools.sqlalchemy = SQLAlchemyTool()

    # Root App
    from bdosoa.app import App
    root_app = cherrypy.tree.mount(App)

    # Merge configuration files
    for c in config or []:
        cherrypy.config.update(c)

        # If there's only one app mounted, merge config into it.
        if len(cherrypy.tree.apps) == 1:
            for app in cherrypy.tree.apps.values():
                if isinstance(app, cherrypy.Application):
                    app.merge(c)

        # Else merge to the root app
        else:
            root_app.merge(c)

    # Set CherryPy environment
    if environment is not None:
        cherrypy.config.update({'environment': environment})

    # Only daemonize if asked to.
    if daemon:
        # Don't print anything to stdout/sterr.
        cherrypy.config.update({'log.screen': False})
        plugins.Daemonizer(cherrypy.engine).subscribe()

    # Write PID file
    if pidfile:
        plugins.PIDFile(cherrypy.engine, pidfile).subscribe()

    # Drop privileges
    if gid or uid:

        try:
            gid = int(gid) if gid else None
        except ValueError:
            # Get the gid from the group name
            import grp
            gid = grp.getgrnam(gid).gr_gid

        try:
            uid = int(uid) if uid else None
        except ValueError:
            # Get the uid from the user name
            import pwd
            uid = pwd.getpwnam(uid).pw_uid

        plugins.DropPrivileges(cherrypy.engine, uid=uid, gid=gid).subscribe()

    # Handle OS signals
    cherrypy.engine.signals.subscribe()

    # Start a *cgi server instead of the default HTTP server
    if (fastcgi and (scgi or cgi)) or (scgi and cgi):
        cherrypy.log.error(
            'You may only specify one of the cgi, fastcgi, and scgi options.',
            'ENGINE')
        sys.exit(1)

    if fastcgi or scgi or cgi:
        # Turn off autoreload when using *cgi.
        cherrypy.config.update({'engine.autoreload.on': False})

        # Turn off the default HTTP server (which is subscribed by default).
        cherrypy.server.unsubscribe()

        if fastcgi:
            httpserver = servers.FlupFCGIServer(
                application=cherrypy.tree,
                bindAddress=cherrypy.server.bind_addr)
        elif scgi:
            httpserver = servers.FlupSCGIServer(
                application=cherrypy.tree,
                bindAddress=cherrypy.server.bind_addr)
        else:
            httpserver = servers.FlupCGIServer(application=cherrypy.tree)

        cherrypy.server = servers.ServerAdapter(cherrypy.engine, httpserver,
                                                cherrypy.server.bind_addr)
        cherrypy.server.subscribe()

    # Set logging level
    if debug and quiet:
        cherrypy.log.error(
            'You may only specify one of the debug, quiet options',
            'ENGINE',
            severity=50)
        sys.exit(1)

    if debug:
        cherrypy.log.error_log.setLevel(10)
    elif quiet:
        cherrypy.log.error_log.setLevel(30)

    # Setup logging for other modules
    for name in logs or []:

        # Get CherryPy builtin handlers
        cherrypy_log_handlers = [
            cherrypy.log._get_builtin_handler(cherrypy.log.error_log, h)
            for h in ['screen', 'file', 'wsgi']
        ]

        # Create logger for the module
        logger = getLogger(name)
        logger.setLevel(cherrypy.log.error_log.getEffectiveLevel())

        for handler in cherrypy_log_handlers:
            if handler is not None:
                logger.addHandler(handler)

    # Always start the engine; this will start all other services
    try:
        cherrypy.engine.start()
    except:
        # Assume the error has been logged already via bus.log.
        sys.exit(1)
    else:
        cherrypy.engine.block()