Exemplo n.º 1
0
def make_middleware(app):
    from repoze.profile.profiler import AccumulatingProfileMiddleware
    return AccumulatingProfileMiddleware(app,
                                         log_filename='/tmp/profile.log',
                                         discard_first_request=True,
                                         flush_at_shutdown=True,
                                         path='/__profile__')
    def make_app(global_conf, **app_conf):
        """Returns a Sync Server Application."""
        global_conf.update(app_conf)
        params = convert_config(global_conf)
        app = klass(urls, controllers, params, auth_class)

        if params.get('debug', False):
            app = TransLogger(app, logger_name='syncserver',
                              setup_console_handler=True)

        if params.get('profile', False):
            from repoze.profile.profiler import AccumulatingProfileMiddleware
            app = AccumulatingProfileMiddleware(app,
                                          log_filename='profile.log',
                                          cachegrind_filename='cachegrind.out',
                                          discard_first_request=True,
                                          flush_at_shutdown=True,
                                          path='/__profile__')

        if params.get('client_debug', False):
            # errors are displayed in the user client
            app = ErrorMiddleware(app, debug=True,
                                  show_exceptions_in_wsgi_errors=True)
        else:
            # errors are logged and a 500 is returned with an empty body
            # to avoid any security whole
            app = CatchErrorMiddleware(app, logger_name='syncserver')

        if wrapper is not None:
            app = wrapper(app)
        return app
Exemplo n.º 3
0
def make_app(global_conf, full_stack=True, **app_conf):
    from moksha.middleware import make_moksha_middleware
    app = make_base_app(global_conf, wrap_app=make_moksha_middleware,
                        full_stack=True, **app_conf)

    if base_config.squeeze:
        from repoze.squeeze.processor import ResourceSqueezingMiddleware
        app = ResourceSqueezingMiddleware(
                app,
                cache_dir='public/cache',
                url_prefix='/cache/',
                )

    if base_config.profile:
        from repoze.profile.profiler import AccumulatingProfileMiddleware
        app = AccumulatingProfileMiddleware(
                app,
                log_filename='profile.log',
                discard_first_request=True,
                flush_at_shutdown=True,
                path='/__profile__',
                cachegrind_filename='moksha.cachegrind',
                )

    return app
Exemplo n.º 4
0
 def rocket_with_repoze_profiler(app, address, **options):
     from rocket import HttpServer
     from repoze.profile.profiler import AccumulatingProfileMiddleware
     wrapped = AccumulatingProfileMiddleware(app,
                                             log_filename='wsgi.prof',
                                             discard_first_request=True,
                                             flush_at_shutdown=True,
                                             path='/__profile__')
     server = HttpServer(wrapped, ip=address[0], port=address[1])
     server.start()
Exemplo n.º 5
0
 def rocket_with_repoze_profiler(app, address, **options):
     from gluon.rocket import CherryPyWSGIServer
     from repoze.profile.profiler import AccumulatingProfileMiddleware
     from gluon.settings import global_settings
     global_settings.web2py_crontype = 'none'
     wrapped = AccumulatingProfileMiddleware(app,
                                             log_filename='wsgi.prof',
                                             discard_first_request=True,
                                             flush_at_shutdown=True,
                                             path='/__profile__')
     server = CherryPyWSGIServer(address, wrapped)
     server.start()
Exemplo n.º 6
0
def run_command(rule_filename, debug=False, interactive_debugger=False, 
                debug_headers=False, profile=False, memory_profile=False,
                garbage_collect=False):
    """Actually runs the command from the parsed arguments"""
    settings = ProxySettings.parse_file(rule_filename)
    app = ReloadingApp(rule_filename, settings)
    if profile:
        try:
            from repoze.profile.profiler import AccumulatingProfileMiddleware
        except ImportError:
            print('Error: you must manually install repoze.profiler to use --profile')
            sys.exit(1)
        app = AccumulatingProfileMiddleware(
            app,
            log_filename='/tmp/deliverance-proxy-profiling.log',
            discard_first_request=True,
            flush_at_shutdown=True,
            path='/.deliverance/profile')
    if memory_profile:
        try:
            from dozer import Dozer
        except ImportError:
            print('Error: you must manually install Dozer to use --memory-profile')
            sys.exit(1)
        app = Dozer(app)
    if interactive_debugger:
        from weberror.evalexception import EvalException
        app = EvalException(app, debug=True)
    else:
        from weberror.errormiddleware import ErrorMiddleware
        app = ErrorMiddleware(app, debug=debug)
    if debug_headers:
        from wsgifilter.proxyapp import DebugHeaders
        app = DebugHeaders(app, show_body=debug_headers > 1)
    if garbage_collect:
        from deliverance.garbagecollect import GarbageCollectingMiddleware
        app = GarbageCollectingMiddleware(app)

    print('To see logging, visit %s/.deliverance/login' % settings.base_url)
    print('    after login go to %s/?deliv_log' % settings.base_url)
    if profile:
        print('To see profiling information visit %s/.deliverance/profile' % settings.base_url)
    serve(app, host=settings.host, port=settings.port)
Exemplo n.º 7
0
def make_app(global_conf, full_stack=True, **app_conf):
    from moksha.wsgi.middleware import make_moksha_middleware
    from fedoracommunity.connectors.api.mw import FCommConnectorMiddleware

    def make_middleware(app):
        if tg_version_tuple < (2, 1):
            app = base_config.add_tosca2_middleware(app)

        app = FCommConnectorMiddleware(app)
        app = make_moksha_middleware(app, tg.config)
        return app

    if tg_version_tuple >= (2, 1):
        app_conf['custom_tw2_config'] = {
            'script_name': global_conf.get('fedoracommunity.script_name', '/')
        }

    app = make_base_app(global_conf,
                        wrap_app=make_middleware,
                        full_stack=full_stack,
                        **app_conf)

    if base_config.squeeze:
        from repoze.squeeze.processor import ResourceSqueezingMiddleware
        app = ResourceSqueezingMiddleware(
            app,
            cache_dir='public/cache',
            url_prefix='/cache/',
        )

    if base_config.profile:
        from repoze.profile.profiler import AccumulatingProfileMiddleware
        app = AccumulatingProfileMiddleware(
            app,
            log_filename='profile.log',
            discard_first_request=True,
            cachegrind_filename='./cachegrind.out',
            flush_at_shutdown=True,
            path='/__profile__')

    return app
Exemplo n.º 8
0
def make_app(global_conf, **app_conf):
    global app, log

    logging.config.fileConfig(global_conf['__file__'])
    log = logging.getLogger('solder')

    import solder.logger

    app = wrap = Solder(global_conf, **app_conf)

    from beaker.middleware import SessionMiddleware
    wrap = SessionMiddleware(wrap, app.config)

    from beaker.middleware import CacheMiddleware
    wrap = CacheMiddleware(wrap, app.config)

    from routes.middleware import RoutesMiddleware
    wrap = RoutesMiddleware(wrap, app)

    if False and app.debug:
        from repoze.profile.profiler import AccumulatingProfileMiddleware
        wrap = AccumulatingProfileMiddleware(wrap,
                                             log_filename='./logs/profile.log',
                                             discard_first_request=True,
                                             flush_at_shutdown=True,
                                             path='/_profile_')

    from weberror.evalexception import make_general_exception
    wrap = make_general_exception(wrap, global_conf,
                                  asbool(app.config['interactive']))

    from paste.fileapp import DirectoryApp
    public = DirectoryApp('./solder/public')

    from paste.cascade import Cascade
    wrap = Cascade([public, wrap], [403, 404])

    return wrap
Exemplo n.º 9
0
 def _makeOne(self, *arg, **kw):
     from repoze.profile.profiler import AccumulatingProfileMiddleware
     return AccumulatingProfileMiddleware(*arg, **kw)
Exemplo n.º 10
0
import sys
from wsgiref.simple_server import make_server

from repoze.profile.profiler import AccumulatingProfileMiddleware
import trac.web.main

if len(sys.argv) < 2:
    logfile_name = 'profiling.log'
else:
    logfile_name = sys.argv[1]

if len(sys.argv) < 3:
    trac_env_dir = os.environ['TRAC_ENV']
else:
    trac_env_dir = sys.argv[2]
assert os.path.isdir(
    trac_env_dir
), 'Please point TRAC_ENV to the environment you want to profile'
os.environ['TRAC_ENV'] = trac_env_dir

app = trac.web.main.dispatch_request
middleware = AccumulatingProfileMiddleware(app,
                                           log_filename=logfile_name,
                                           discard_first_request=False,
                                           flush_at_shutdown=False,
                                           path='/profile')

httpd = make_server('', 8011, middleware)
print "Serving on port 8011..."
httpd.serve_forever()
Exemplo n.º 11
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """
    Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()

    # Profiling Middleware
    if profile_load:
        if asbool(config['profile']):
            app = AccumulatingProfileMiddleware(
                app,
                log_filename='/var/log/linotp/profiling.log',
                cachegrind_filename='/var/log/linotp/cachegrind.out',
                discard_first_request=True,
                flush_at_shutdown=True,
                path='/__profile__')

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])

    # repoze.who
    if repoze_load:
        if 'who.generate_random_secret' in app_conf and not app_conf[
                'who.generate_random_secret']:
            app = make_who_with_config(app, global_conf,
                                       app_conf['who.config_file'],
                                       app_conf['who.log_file'],
                                       app_conf['who.log_level'])
        else:
            # Read the current configuration file and replace "secret" keys in every line
            who_config_lines = []
            secret = binascii.hexlify(os.urandom(16))
            if len(secret) != 32:
                raise RuntimeError(
                    'Could not generate random repoze.who secret, no os.urandom support?'
                )

            with open(app_conf['who.config_file']) as f:
                for line in f.readlines():
                    who_config_lines.append(
                        re.sub(r'^(secret)\s*=\s*.*$', r'\1 = %s' % secret,
                               line))
            with tempinput(''.join(who_config_lines)) as who_config_file:
                app = make_who_with_config(app, global_conf, who_config_file,
                                           app_conf['who.log_file'],
                                           app_conf['who.log_level'])

    # this is a compatibility hack for pylons > 1.0!!!
    conf = PyConf(config)

    conf['global_conf'] = global_conf
    conf['app_conf'] = app_conf
    conf['__file__'] = global_conf['__file__']
    conf['FILE'] = global_conf['__file__']
    conf['routes.map'] = config['routes.map']

    if not hasattr(conf, 'init_app'):
        setattr(conf, 'init_app', config.init_app)
    app.config = conf

    return app
Exemplo n.º 12
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """
    Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()

    # Profiling Middleware
    if profile_load:
        if asbool(config['profile']):
            app = AccumulatingProfileMiddleware(
                app,
                log_filename='/var/log/linotp/profiling.log',
                cachegrind_filename='/var/log/linotp/cachegrind.out',
                discard_first_request=True,
                flush_at_shutdown=True,
                path='/__profile__'
            )

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])

    # repoze.who
    if repoze_load:
        app = make_who_with_config(app, global_conf, app_conf['who.config_file'], app_conf['who.log_file'], app_conf['who.log_level'])

    return app
Exemplo n.º 13
0
from groundhog import Groundhog
from repoze.profile.profiler import AccumulatingProfileMiddleware
from paste.httpserver import serve

# application

app = Groundhog(__name__, 'seekrit')

@app.route('/')
def root():
    return 'hello'

if __name__ == '__main__':
    wsgiapp = app.get_wsgiapp()
    wrapped = AccumulatingProfileMiddleware(wsgiapp)
    serve(wrapped)