Files
fm-orchestrator/module_build_service/resolver/base.py
Chenxiong Qi 3878affa41 Separate use of database sessions
This patch separates the use of database session in different MBS components
and do not mix them together.

In general, MBS components could be separated as the REST API (implemented
based on Flask) and non-REST API including the backend build workflow
(implemented as a fedmsg consumer on top of fedmsg-hub and running
independently) and library shared by them. As a result, there are two kind of
database session used in MBS, one is created and managed by Flask-SQLAlchemy,
and another one is created from SQLAclhemy Session API directly. The goal of
this patch is to make ensure session object is used properly in the right
place.

All the changes follow these rules:

* REST API related code uses the session object db.session created and
  managed by Flask-SQLAlchemy.
* Non-REST API related code uses the session object created with SQLAlchemy
  Session API. Function make_db_session does that.
* Shared code does not created a new session object as much as possible.
  Instead, it accepts an argument db_session.

The first two rules are applicable to tests as well.

Major changes:

* Switch tests back to run with a file-based SQLite database.
* make_session is renamed to make_db_session and SQLAlchemy connection pool
  options are applied for PostgreSQL backend.
* Frontend Flask related code uses db.session
* Shared code by REST API and backend build workflow accepts SQLAlchemy session
  object as an argument. For example, resolver class is constructed with a
  database session, and some functions accepts an argument for database session.
* Build workflow related code use session object returned from make_db_session
  and ensure db.session is not used.
* Only tests for views use db.session, and other tests use db_session fixture
  to access database.
* All argument name session, that is for database access, are renamed to
  db_session.
* Functions model_tests_init_data, reuse_component_init_data and
  reuse_shared_userspace_init_data, which creates fixture data for
  tests, are converted into pytest fixtures from original function
  called inside setup_method or a test method. The reason of this
  conversion is to use fixture ``db_session`` rather than create a
  new one. That would also benefit the whole test suite to reduce the
  number of SQLAlchemy session objects.

Signed-off-by: Chenxiong Qi <cqi@redhat.com>
2019-07-18 21:26:50 +08:00

150 lines
5.2 KiB
Python

# -*- coding: utf-8 -*-
# Copyright (c) 2018 Red Hat, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Written by Filip Valder <fvalder@redhat.com>
"""Generic resolver functions."""
import six
from abc import ABCMeta, abstractmethod
import module_build_service.config as cfg
from module_build_service import conf
class GenericResolver(six.with_metaclass(ABCMeta)):
"""
External Api for resolvers
"""
_resolvers = cfg.SUPPORTED_RESOLVERS
# Resolver name. Each subclass of GenericResolver must set its own name.
backend = "generic"
# Supported resolver backends registry. Generally, resolver backend is
# registered by calling :meth:`GenericResolver.register_backend_class`.
# This is a mapping from resolver name to backend class object
# For example, {'mbs': MBSResolver}
backends = {}
@classmethod
def register_backend_class(cls, backend_class):
GenericResolver.backends[backend_class.backend] = backend_class
@classmethod
def create(cls, db_session, config, backend=None, **extra):
"""Factory method to create a resolver object
:param config: MBS config object.
:type config: :class:`Config`
:kwarg str backend: resolver backend name, e.g. 'db'. If omitted,
system configuration ``resolver`` is used.
:kwarg extra: any additional arguments are optional extras which can
be passed along and are implementation-dependent.
:return: resolver backend object.
:rtype: corresponding registered resolver class.
:raises ValueError: if specified resolver backend name is not
registered.
"""
# get the appropriate resolver backend via configuration
if not backend:
backend = conf.resolver
if backend in GenericResolver.backends:
return GenericResolver.backends[backend](db_session, config, **extra)
else:
raise ValueError("Resolver backend='%s' not recognized" % backend)
@classmethod
def supported_builders(cls):
if cls is GenericResolver:
return {k: v["builders"] for k, v in cls._resolvers.items()}
else:
try:
return cls._resolvers[cls.backend]["builders"]
except KeyError:
raise RuntimeError(
"No configuration of builder backends found for resolver {}".format(cls))
@classmethod
def is_builder_compatible(cls, builder):
"""
:param backend: a string representing builder e.g. 'koji'
Get supported builder backend(s) via configuration
"""
if cls is not GenericResolver:
return builder in cls.supported_builders()
return False
@abstractmethod
def get_module(self, name, stream, version, context, state="ready", strict=False):
raise NotImplementedError()
@abstractmethod
def get_module_count(self, **kwargs):
raise NotImplementedError()
@abstractmethod
def get_latest_with_virtual_stream(self, name, virtual_stream):
raise NotImplementedError()
@abstractmethod
def get_module_modulemds(self, name, stream, version=None, context=None, strict=False):
raise NotImplementedError()
@abstractmethod
def get_compatible_base_module_modulemds(
self, name, stream, stream_version_lte, virtual_streams, states
):
raise NotImplementedError()
@abstractmethod
def get_buildrequired_modulemds(self, name, stream, base_module_nsvc, strict=False):
raise NotImplementedError()
@abstractmethod
def resolve_profiles(self, mmd, keys):
raise NotImplementedError()
@abstractmethod
def get_module_build_dependencies(
self, name=None, stream=None, version=None, mmd=None, context=None, strict=False
):
raise NotImplementedError()
@abstractmethod
def resolve_requires(self, requires):
raise NotImplementedError()
@abstractmethod
def get_modulemd_by_koji_tag(self, tag):
"""Get module metadata by module's koji_tag
:param str tag: name of module's koji_tag.
:return: module metadata
:rtype: Modulemd.Module
"""
raise NotImplementedError()