Esempio n. 1
0
 def serve_forever(self):
     engine = cherrypy.engine
     if hasattr(engine, "signal_handler"):
         engine.signal_handler.subscribe()
     if hasattr(engine, "console_control_handler"):
         engine.console_control_handler.subscribe()
     app = self._bootstrap_app()
     try:
         if self.use_gevent:
             # Turn off autoreload when using *cgi.
             #cherrypy.config.update({'engine.autoreload_on': False})
             addr = cherrypy.server.bind_addr
             cherrypy.server.unsubscribe()
             f = GeventWSGIServer(addr, app, log=None)
             s = servers.ServerAdapter(engine, httpserver=f, bind_addr=addr)
             s.subscribe()
             engine.start()
         else:
             cherrypy.quickstart(app)
     except KeyboardInterrupt:
         self.stop()
     else:
         engine.block()
Esempio n. 2
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
        cls = (servers.FlupFCGIServer if fastcgi else
               servers.FlupSCGIServer if scgi else servers.FlupCGIServer)
        f = cls(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:
        # Assume the error has been logged already via bus.log.
        sys.exit(1)
    else:
        engine.block()
Esempio n. 3
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()
Esempio n. 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()
Esempio n. 5
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()