Ejemplo n.º 1
0
def _trigger_task(config_uri: str, task_name: str, task_kwargs=None):
    """Trigger a task after initializing the configuration."""
    logging.basicConfig(level=logging.INFO)
    if config_uri:
        settings = get_appsettings(config_uri)
    else:
        settings = None
    config.load_config(settings)
    task_kwargs = task_kwargs or {}

    # Import here or the config will be loaded too early.
    import bodhi.server.tasks
    task = getattr(bodhi.server.tasks, task_name)

    result = task.delay(**task_kwargs)

    if bodhi.server.tasks.app.conf.result_backend is None:
        click.echo(
            "No result backend have been configured in Celery, "
            "I cannot wait for the task to complete."
        )
        return
    try:
        result.get(propagate=True)
    except Exception as e:
        click.echo(str(e))
        sys.exit(1)
Ejemplo n.º 2
0
def main(global_config, testing=None, session=None, **settings):
    """
    Return a WSGI application.

    Args:
        global_config (dict): A dictionary with two keys: __file__, a path to the ini file, and
            here, the path to the code.
        testing (str or None): If this app is contructed by the unit tests, they should set this to
            a username.
        session (sqlalchemy.orm.session.Session or None): If given, the session will be used instead
            of building a new one.
        settings (dictionary): Unused.
    Returns:
        pyramid.router.Router: A WSGI app.
    """
    if settings:
        bodhi_config.load_config(settings)

    # Setup our bugtracker and buildsystem
    bugs.set_bugtracker()
    setup_buildsys()

    # Sessions & Caching
    from pyramid.session import SignedCookieSessionFactory
    session_factory = SignedCookieSessionFactory(
        bodhi_config['session.secret'])

    # Construct a list of all groups we're interested in
    default = []
    for key in ('important_groups', 'admin_packager_groups',
                'mandatory_packager_groups', 'admin_groups'):
        default.extend(bodhi_config.get(key))
    # pyramid_fas_openid looks for this setting
    bodhi_config['openid.groups'] = bodhi_config.get('openid.groups', default)

    config = Configurator(settings=bodhi_config,
                          session_factory=session_factory)

    # Plugins
    config.include('pyramid_mako')
    config.include('cornice')

    # Initialize the database scoped session
    initialize_db(bodhi_config)

    # Lazy-loaded memoized request properties
    if session:
        config.registry.sessionmaker = lambda: session
    else:
        config.registry.sessionmaker = Session

    config.add_request_method(lambda x: Session, 'db', reify=True)

    config.add_request_method(get_user, 'user', reify=True)
    config.add_request_method(get_koji, 'koji', reify=True)
    config.add_request_method(get_cacheregion, 'cache', reify=True)
    config.add_request_method(get_buildinfo, 'buildinfo', reify=True)
    config.add_request_method(get_from_tag_inherited,
                              'from_tag_inherited',
                              reify=True)
    config.add_request_method(get_releases, 'releases', reify=True)

    # Templating
    config.add_mako_renderer('.html', settings_prefix='mako.')
    config.add_static_view(
        f'static/v{pkg_resources.get_distribution("bodhi").version}',
        'bodhi:server/static')

    from bodhi.server.renderers import rss
    config.add_renderer('rss', rss)
    config.add_renderer('jsonp', JSONP(param_name='callback'))

    # i18n
    config.add_translation_dirs('bodhi:server/locale/')

    # Authentication & Authorization
    if testing:
        # use a permissive security policy while running unit tests
        config.testing_securitypolicy(userid=testing, permissive=True)
    else:
        timeout = bodhi_config.get('authtkt.timeout')
        config.set_authentication_policy(
            AuthTktAuthenticationPolicy(bodhi_config['authtkt.secret'],
                                        callback=groupfinder,
                                        secure=bodhi_config['authtkt.secure'],
                                        hashalg='sha512',
                                        timeout=timeout,
                                        max_age=timeout))
        config.set_authorization_policy(ACLAuthorizationPolicy())

    # Frontpage
    config.add_route('home', '/')

    # Views for creating new objects
    config.add_route('new_update', '/updates/new')
    config.add_route('new_override', '/overrides/new')

    # Metrics
    config.add_route('metrics', '/metrics')

    # Auto-completion search
    config.add_route('latest_candidates', '/latest_candidates')
    config.add_route('latest_builds', '/latest_builds')
    config.add_route('get_sidetags', '/get_sidetags')
    config.add_route('latest_builds_in_tag', '/latest_builds_in_tag')

    # pyramid.openid
    config.add_route('login', '/login')
    config.add_view('bodhi.server.security.login', route_name='login')
    config.add_route('logout', '/logout')
    config.add_view('bodhi.server.security.logout', route_name='logout')
    config.add_route('verify_openid', pattern='/dologin.html')
    config.add_view('pyramid_fas_openid.verify_openid',
                    route_name='verify_openid')

    config.add_route('api_version', '/api_version')

    config.scan('bodhi.server.views')
    config.scan('bodhi.server.services')
    config.scan('bodhi.server.webapp')

    # Though importing in the middle of this function is the darkest of evils, we cannot do it any
    # other way without a backwards-incompatible change. See
    # https://github.com/fedora-infra/bodhi/issues/2294
    from bodhi.server import models
    from bodhi.server.views import generic

    # Let's put a cache on the home page stats, but only if it isn't already cached. The cache adds
    # an invalidate attribute to the method, so that's how we can tell. The server would not
    # encounter this function already having a cache in normal operation, but the unit tests do run
    # this function many times so we don't want them to cause it to cache a cache of the cache of
    # the cache…
    if not hasattr(generic._generate_home_page_stats, 'invalidate'):
        generic._generate_home_page_stats = get_cacheregion(
            None).cache_on_arguments()(generic._generate_home_page_stats)

    if bodhi_config['warm_cache_on_start']:
        log.info('Warming up caches…')

        # Let's warm up the Releases._all_releases cache. We can just call the function - we don't
        # need to capture the return value.
        models.Release.all_releases()

        # Let's warm up the home page cache by calling _generate_home_page_stats(). We can ignore
        # the return value.
        generic._generate_home_page_stats()

    # Let's close out the db session we used to warm the caches.
    Session.remove()

    log.info('Bodhi ready and at your service!')
    return config.make_wsgi_app()
Ejemplo n.º 3
0
def main(global_config, testing=None, session=None, **settings):
    """
    Return a WSGI application.

    Args:
        global_config (dict): A dictionary with two keys: __file__, a path to the ini file, and
            here, the path to the code.
        testing (bool or None): Whether or not we are in testing mode.
        session (sqlalchemy.orm.session.Session or None): If given, the session will be used instead
            of building a new one.
        settings (dictionary): Unused.
    Returns:
        pyramid.router.Router: A WSGI app.
    """
    if settings:
        bodhi_config.load_config(settings)

    # Setup our bugtracker and buildsystem
    bugs.set_bugtracker()
    buildsys.setup_buildsystem(bodhi_config)

    # Sessions & Caching
    from pyramid.session import SignedCookieSessionFactory
    session_factory = SignedCookieSessionFactory(
        bodhi_config['session.secret'])

    # Construct a list of all groups we're interested in
    default = []
    for key in ('important_groups', 'admin_packager_groups',
                'mandatory_packager_groups', 'admin_groups'):
        default.extend(bodhi_config.get(key))
    # pyramid_fas_openid looks for this setting
    bodhi_config['openid.groups'] = bodhi_config.get('openid.groups', default)

    config = Configurator(settings=bodhi_config,
                          session_factory=session_factory)

    # Plugins
    config.include('pyramid_mako')
    config.include('cornice')

    # Initialize the database scoped session
    initialize_db(bodhi_config)

    # Lazy-loaded memoized request properties
    if session:
        config.registry.sessionmaker = lambda: session
    else:
        config.registry.sessionmaker = Session

    config.add_request_method(get_db_session_for_request, 'db', reify=True)

    config.add_request_method(get_user, 'user', reify=True)
    config.add_request_method(get_koji, 'koji', reify=True)
    config.add_request_method(get_cacheregion, 'cache', reify=True)
    config.add_request_method(get_buildinfo, 'buildinfo', reify=True)
    config.add_request_method(get_releases, 'releases', reify=True)

    # Templating
    config.add_mako_renderer('.html', settings_prefix='mako.')
    config.add_static_view('static', 'bodhi:server/static')

    from bodhi.server.renderers import rss, jpeg
    config.add_renderer('rss', rss)
    config.add_renderer('jpeg', jpeg)
    config.add_renderer('jsonp', JSONP(param_name='callback'))

    # i18n
    config.add_translation_dirs('bodhi:server/locale/')

    # Authentication & Authorization
    if testing:
        # use a permissive security policy while running unit tests
        config.testing_securitypolicy(userid=testing, permissive=True)
    else:
        timeout = bodhi_config.get('authtkt.timeout')
        config.set_authentication_policy(
            AuthTktAuthenticationPolicy(bodhi_config['authtkt.secret'],
                                        callback=groupfinder,
                                        secure=bodhi_config['authtkt.secure'],
                                        hashalg='sha512',
                                        timeout=timeout,
                                        max_age=timeout))
        config.set_authorization_policy(ACLAuthorizationPolicy())

    # Frontpage
    config.add_route('home', '/')

    # Views for creating new objects
    config.add_route('new_update', '/updates/new')
    config.add_route('new_override', '/overrides/new')
    config.add_route('new_stack', '/stacks/new')

    # Metrics
    config.add_route('metrics', '/metrics')
    config.add_route('masher_status', '/masher/')

    # Auto-completion search
    config.add_route('search_packages', '/search/packages')
    config.add_route('latest_candidates', '/latest_candidates')
    config.add_route('latest_builds', '/latest_builds')

    config.add_route('captcha_image', '/captcha/{cipherkey}/')

    # pyramid.openid
    config.add_route('login', '/login')
    config.add_view('bodhi.server.security.login', route_name='login')
    config.add_view('bodhi.server.security.login', context=HTTPForbidden)
    config.add_route('logout', '/logout')
    config.add_view('bodhi.server.security.logout', route_name='logout')
    config.add_route('verify_openid', pattern='/dologin.html')
    config.add_view('pyramid_fas_openid.verify_openid',
                    route_name='verify_openid')

    config.add_route('api_version', '/api_version')

    # The only user preference we have.
    config.add_route('popup_toggle', '/popup_toggle')

    config.scan('bodhi.server.views')
    config.scan('bodhi.server.services')
    config.scan('bodhi.server.captcha')

    return config.make_wsgi_app()
Ejemplo n.º 4
0
def _do_init():
    config.load_config()
    initialize_db(config)
    buildsys.setup_buildsystem(config)
    bugs.set_bugtracker()