Merge branch 'Database-Migration-Support-and-Cleanup'

This commit is contained in:
Ralph Bean
2016-08-10 13:48:45 -04:00
28 changed files with 574 additions and 385 deletions

View File

@@ -40,5 +40,27 @@ for a number of tasks:
- Emitting bus messages about all state changes so that other
infrastructure services can pick up the work.
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import sys
import rida.logger
from logging import getLogger
from rida.database import BUILD_STATES
app = Flask(__name__)
app.config.from_envvar("RIDA_SETTINGS", silent=True)
here = sys.path[0]
if here not in ('/usr/bin', '/bin', '/usr/local/bin'):
app.config.from_object('config.DevConfiguration')
else:
app.config.from_object('config.ProdConfiguration')
db = SQLAlchemy(app)
import rida.config
conf = rida.config.from_app_config()
rida.logger.init_logging(conf)
log = getLogger(__name__)
from rida import views

View File

@@ -45,10 +45,10 @@ import kobo.rpmlib
import munch
from OpenSSL.SSL import SysCallError
from rida import log
import rida.utils
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
# TODO: read defaults from rida's config
KOJI_DEFAULT_GROUPS = {

View File

@@ -25,9 +25,6 @@
"""Configuration handler functions."""
import os.path
import json
try:
import configparser # py3
except ImportError:
@@ -35,6 +32,7 @@ except ImportError:
import six
from rida import app
from rida import logger
def asbool(value):
@@ -44,54 +42,15 @@ def asbool(value):
]
def from_file(filename=None):
"""Create the configuration instance from a file.
The file name is optional and defaults to /etc/rida/rida.conf.
:param str filename: The configuration file to load, optional.
def from_app_config():
""" Create the configuration instance from the values in app.config
"""
if filename is None:
filename = "/etc/rida/rida.conf"
if not isinstance(filename, str):
raise TypeError("The configuration filename must be a string.")
if not os.path.isfile(filename):
raise IOError("The configuration file '%s' doesn't exist." % filename)
cp = configparser.ConfigParser(allow_no_value=True)
cp.read(filename)
default = cp.defaults()
conf = Config()
conf.db = default.get("db")
conf.system = default.get("system")
conf.messaging = default.get("messaging")
conf.polling_interval = int(default.get("polling_interval"))
conf.pdc_url = default.get("pdc_url")
conf.pdc_insecure = default.get("pdc_insecure")
conf.pdc_develop = default.get("pdc_develop")
conf.koji_config = default.get("koji_config")
conf.koji_profile = default.get("koji_profile")
conf.koji_arches = json.loads(default.get("koji_arches"))
conf.scmurls = json.loads(default.get("scmurls"))
conf.rpms_default_repository = default.get("rpms_default_repository")
conf.rpms_allow_repository = asbool(default.get("rpms_allow_repository"))
conf.rpms_default_cache = default.get("rpms_default_cache")
conf.rpms_allow_cache = asbool(default.get("rpms_allow_cache"))
conf.port = default.get("port")
conf.host = default.get("host")
conf.ssl_enabled = asbool(default.get("ssl_enabled"))
conf.ssl_certificate_file = default.get("ssl_certificate_file")
conf.ssl_certificate_key_file = default.get("ssl_certificate_key_file")
conf.ssl_ca_certificate_file = default.get("ssl_ca_certificate_file")
conf.pkgdb_api_url = default.get("pkgdb_api_url")
conf.log_backend = default.get("log_backend")
conf.log_file = default.get("log_file")
conf.log_level = default.get("log_level")
for key, value in app.config.items():
setattr(conf, key.lower(), value)
return conf
class Config(object):
"""Class representing the orchestrator configuration."""
@@ -201,7 +160,6 @@ class Config(object):
def koji_config(self, s):
self._koji_config = str(s)
@property
def koji_profile(self):
"""Koji URL."""

View File

@@ -21,30 +21,18 @@
#
# Written by Petr Šabata <contyk@redhat.com>
# Ralph Bean <rbean@redhat.com>
# Matt Prahl <mprahl@redhat.com>
"""Database handler functions."""
""" SQLAlchemy Database models for the Flask app
"""
from sqlalchemy import (
Column,
Integer,
String,
ForeignKey,
create_engine,
)
from sqlalchemy.orm import (
sessionmaker,
relationship,
validates,
)
from sqlalchemy.ext.declarative import declarative_base
from rida import db, log
from sqlalchemy.orm import validates
import modulemd as _modulemd
import rida.messaging
import logging
log = logging.getLogger(__name__)
# Just like koji.BUILD_STATES, except our own codes for modules.
BUILD_STATES = {
@@ -75,75 +63,33 @@ BUILD_STATES = {
INVERSE_BUILD_STATES = {v: k for k, v in BUILD_STATES.items()}
class RidaBase(object):
# TODO -- we can implement functionality here common to all our model
# classes.
pass
class RidaBase(db.Model):
# TODO -- we can implement functionality here common to all our model classes
__abstract__ = True
Base = declarative_base(cls=RidaBase)
class Database(object):
"""Class for handling database connections."""
def __init__(self, config, debug=False):
"""Initialize the database object."""
self.engine = create_engine(config.db, echo=debug)
self._session = None # Lazilly created..
def __enter__(self):
return self.session
def __exit__(self, *args, **kwargs):
self._session.close()
self._session = None
@property
def session(self):
"""Database session object."""
if not self._session:
Session = sessionmaker(bind=self.engine)
self._session = Session()
return self._session
@classmethod
def create_tables(cls, config, debug=False):
""" Creates our tables in the database.
:arg config, config object with a 'db' URL attached to it.
ie: <engine>://<user>:<password>@<host>/<dbname>
:kwarg debug, a boolean specifying wether we should have the verbose
output of sqlalchemy or not.
:return a Database connection that can be used to query to db.
"""
engine = create_engine(config.db, echo=debug)
Base.metadata.create_all(engine)
return cls(config, debug=debug)
class Module(Base):
class Module(RidaBase):
__tablename__ = "modules"
name = Column(String, primary_key=True)
name = db.Column(db.String, primary_key=True)
class ModuleBuild(Base):
class ModuleBuild(RidaBase):
__tablename__ = "module_builds"
id = Column(Integer, primary_key=True)
name = Column(String, ForeignKey('modules.name'), nullable=False)
version = Column(String, nullable=False)
release = Column(String, nullable=False)
state = Column(Integer, nullable=False)
modulemd = Column(String, nullable=False)
koji_tag = Column(String) # This gets set after 'wait'
scmurl = Column(String)
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, db.ForeignKey('modules.name'), nullable=False)
version = db.Column(db.String, nullable=False)
release = db.Column(db.String, nullable=False)
state = db.Column(db.Integer, nullable=False)
modulemd = db.Column(db.String, nullable=False)
koji_tag = db.Column(db.String) # This gets set after 'wait'
scmurl = db.Column(db.String)
# A monotonically increasing integer that represents which batch or
# iteration this module is currently on for successive rebuilds of its
# components. Think like 'mockchain --recurse'
batch = Column(Integer, default=0)
batch = db.Column(db.Integer, default=0)
module = relationship('Module', backref='module_builds', lazy=False)
module = db.relationship('Module', backref='module_builds', lazy=False)
def current_batch(self):
""" Returns all components of this module in the current batch. """
@@ -212,8 +158,7 @@ class ModuleBuild(Base):
@classmethod
def by_state(cls, session, state):
return session.query(rida.database.ModuleBuild)\
.filter_by(state=BUILD_STATES[state]).all()
return session.query(ModuleBuild).filter_by(state=BUILD_STATES[state]).all()
@classmethod
def from_repo_done_event(cls, session, event):
@@ -253,27 +198,27 @@ class ModuleBuild(Base):
INVERSE_BUILD_STATES[self.state], self.batch)
class ComponentBuild(Base):
class ComponentBuild(RidaBase):
__tablename__ = "component_builds"
id = Column(Integer, primary_key=True)
package = Column(String, nullable=False)
scmurl = Column(String, nullable=False)
id = db.Column(db.Integer, primary_key=True)
package = db.Column(db.String, nullable=False)
scmurl = db.Column(db.String, nullable=False)
# XXX: Consider making this a proper ENUM
format = Column(String, nullable=False)
task_id = Column(Integer) # This is the id of the build in koji
format = db.Column(db.String, nullable=False)
task_id = db.Column(db.Integer) # This is the id of the build in koji
# XXX: Consider making this a proper ENUM (or an int)
state = Column(Integer)
state = db.Column(db.Integer)
# This stays as None until the build completes.
nvr = Column(String)
nvr = db.Column(db.String)
# A monotonically increasing integer that represents which batch or
# iteration this *component* is currently in. This relates to the owning
# module's batch. This one defaults to None, which means that this
# component is not currently part of a batch.
batch = Column(Integer, default=0)
batch = db.Column(db.Integer, default=0)
module_id = Column(Integer, ForeignKey('module_builds.id'), nullable=False)
module_build = relationship('ModuleBuild', backref='component_builds', lazy=False)
module_id = db.Column(db.Integer, db.ForeignKey('module_builds.id'), nullable=False)
module_build = db.relationship('ModuleBuild', backref='component_builds', lazy=False)
@classmethod
def from_component_event(cls, session, event):
@@ -301,8 +246,6 @@ class ComponentBuild(Base):
return retval
def __repr__(self):
return "<ComponentBuild %s, %r, state: %r, task_id: %r, batch: %r>" % (
self.package, self.module_id, self.state, self.task_id, self.batch)

View File

@@ -26,20 +26,20 @@
import logging
import rida.builder
import rida.database
import rida.pdc
import koji
from rida import models, log
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def _finalize(config, session, msg, state):
""" Called whenever a koji build completes or fails. """
# First, find our ModuleBuild associated with this repo, if any.
component_build = rida.database.ComponentBuild.from_component_event(session, msg)
component_build = models.ComponentBuild.from_component_event(session, msg)
nvr = "{name}-{version}-{release}".format(**msg['msg'])
if not component_build:
log.debug("We have no record of %s" % nvr)
@@ -55,7 +55,7 @@ def _finalize(config, session, msg, state):
if component_build.package == 'module-build-macros':
if state != koji.BUILD_STATES['COMPLETE']:
# If the macro build failed, then the module is doomed.
parent.transition(config, state=rida.BUILD_STATES['failed'])
parent.transition(config, state=models.BUILD_STATES['failed'])
session.commit()
return
@@ -80,7 +80,7 @@ def _finalize(config, session, msg, state):
# to a next batch. This module build is doomed.
if all([c.state != koji.BUILD_STATES['COMPLETE'] for c in current_batch]):
# They didn't all succeed.. so mark this module build as a failure.
parent.transition(config, rida.BUILD_STATES['failed'])
parent.transition(config, models.BUILD_STATES['failed'])
session.commit()
return

View File

@@ -23,8 +23,8 @@
""" Handlers for module change events on the message bus. """
from rida import models, db, log
import rida.builder
import rida.database
import rida.pdc
import rida.utils
@@ -34,15 +34,16 @@ import logging
import os
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def get_rpm_release_from_tag(tag):
return tag.replace("-", "_")
def get_artifact_from_srpm(srpm_path):
return os.path.basename(srpm_path).replace(".src.rpm", "")
def wait(config, session, msg):
""" Called whenever a module enters the 'wait' state.
@@ -52,7 +53,7 @@ def wait(config, session, msg):
The kicking off of individual component builds is handled elsewhere,
in rida.schedulers.handlers.repos.
"""
build = rida.database.ModuleBuild.from_module_event(session, msg)
build = models.ModuleBuild.from_module_event(db.session, msg)
log.info("Found build=%r from message" % build)
module_info = build.json()
@@ -111,7 +112,7 @@ def wait(config, session, msg):
artifact_name = "module-build-macros"
task_id = builder.build(artifact_name=artifact_name, source=srpm)
component_build = rida.database.ComponentBuild(
component_build = models.ComponentBuild(
module_id=build.id,
package=artifact_name,
format="rpms",

View File

@@ -24,13 +24,12 @@
""" Handlers for repo change events on the message bus. """
import rida.builder
import rida.database
import rida.pdc
import logging
import koji
from rida import models, log
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def done(config, session, msg):
@@ -38,7 +37,7 @@ def done(config, session, msg):
# First, find our ModuleBuild associated with this repo, if any.
tag = msg['msg']['tag'].strip('-build')
module_build = rida.database.ModuleBuild.from_repo_done_event(session, msg)
module_build = models.ModuleBuild.from_repo_done_event(session, msg)
if not module_build:
log.info("No module build found associated with koji tag %r" % tag)
return
@@ -46,7 +45,7 @@ def done(config, session, msg):
# It is possible that we have already failed.. but our repo is just being
# routinely regenerated. Just ignore that. If rida says the module is
# dead, then the module is dead.
if module_build.state == rida.BUILD_STATES['failed']:
if module_build.state == models.BUILD_STATES['failed']:
log.info("Ignoring repo regen for already failed %r" % module_build)
return
@@ -71,7 +70,7 @@ def done(config, session, msg):
# first before we ever get here. This is here as a race condition safety
# valve.
if not good:
module_build.transition(config, rida.BUILD_STATES['failed'])
module_build.transition(config, models.BUILD_STATES['failed'])
session.commit()
log.warn("Odd! All components in batch failed for %r." % module_build)
return
@@ -103,7 +102,7 @@ def done(config, session, msg):
rida.utils.start_next_build_batch(
module_build, session, builder, components=leftover_components)
else:
module_build.transition(config, state=rida.BUILD_STATES['done'])
module_build.transition(config, state=models.BUILD_STATES['done'])
session.commit()
# And that's it. :)

View File

@@ -31,7 +31,6 @@ proper scheduling component builds in the supported build systems.
import inspect
import logging
import operator
import os
import pprint
@@ -47,26 +46,14 @@ except ImportError:
import rida.config
import rida.logger
import rida.messaging
import rida.scheduler.handlers.components
import rida.scheduler.handlers.modules
import rida.scheduler.handlers.repos
import sys
import koji
log = logging.getLogger(__name__)
# Load config from git checkout or the default location
config = None
here = sys.path[0]
if here not in ('/usr/bin', '/bin', '/usr/local/bin'):
# git checkout
config = rida.config.from_file("rida.conf")
else:
# production
config = rida.config.from_file()
from rida import conf, db, models, log
class STOP_WORK(object):
@@ -77,7 +64,7 @@ class STOP_WORK(object):
def module_build_state_from_msg(msg):
state = int(msg['msg']['state'])
# TODO better handling
assert state in rida.BUILD_STATES.values(), "state=%s(%s) is not in %s" % (state, type(state), rida.BUILD_STATES.values())
assert state in models.BUILD_STATES.values(), "state=%s(%s) is not in %s" % (state, type(state), models.BUILD_STATES.values())
return state
@@ -88,7 +75,7 @@ class MessageIngest(threading.Thread):
def run(self):
for msg in rida.messaging.listen(backend=config.messaging):
for msg in rida.messaging.listen(backend=conf.messaging):
self.outgoing_work_queue.put(msg)
@@ -109,12 +96,12 @@ class MessageWorker(threading.Thread):
koji.BUILD_STATES["DELETED"]: NO_OP,
}
self.on_module_change = {
rida.BUILD_STATES["init"]: NO_OP,
rida.BUILD_STATES["wait"]: rida.scheduler.handlers.modules.wait,
rida.BUILD_STATES["build"]: NO_OP,
rida.BUILD_STATES["failed"]: NO_OP,
rida.BUILD_STATES["done"]: NO_OP,
rida.BUILD_STATES["ready"]: NO_OP,
models.BUILD_STATES["init"]: NO_OP,
models.BUILD_STATES["wait"]: rida.scheduler.handlers.modules.wait,
models.BUILD_STATES["build"]: NO_OP,
models.BUILD_STATES["failed"]: NO_OP,
models.BUILD_STATES["done"]: NO_OP,
models.BUILD_STATES["ready"]: NO_OP,
}
# Only one kind of repo change event, though...
self.on_repo_change = rida.scheduler.handlers.repos.done
@@ -122,8 +109,8 @@ class MessageWorker(threading.Thread):
def sanity_check(self):
""" On startup, make sure our implementation is sane. """
# Ensure we have every state covered
for state in rida.BUILD_STATES:
if rida.BUILD_STATES[state] not in self.on_module_change:
for state in models.BUILD_STATES:
if models.BUILD_STATES[state] not in self.on_module_change:
raise KeyError("Module build states %r not handled." % state)
for state in koji.BUILD_STATES:
if koji.BUILD_STATES[state] not in self.on_build_change:
@@ -176,10 +163,9 @@ class MessageWorker(threading.Thread):
if handler is self.NO_OP:
log.debug("Handler is NO_OP: %s" % idx)
else:
with rida.database.Database(config) as session:
log.info("Calling %s" % idx)
handler(config, session, msg)
log.info("Done with %s" % idx)
log.info("Calling %s" % idx)
handler(conf, db.session, msg)
log.info("Done with %s" % idx)
class Poller(threading.Thread):
@@ -189,20 +175,15 @@ class Poller(threading.Thread):
def run(self):
while True:
with rida.database.Database(config) as session:
self.log_summary(session)
self.log_summary(db.session)
# XXX: detect whether it's really stucked first
#with rida.database.Database(config) as session:
# self.process_waiting_module_builds(session)
with rida.database.Database(config) as session:
self.process_open_component_builds(session)
with rida.database.Database(config) as session:
self.process_lingering_module_builds(session)
with rida.database.Database(config) as session:
self.fail_lost_builds(session)
# self.process_waiting_module_builds(db.session)
self.process_open_component_builds(db.session)
self.process_lingering_module_builds(db.session)
self.fail_lost_builds(db.session)
log.info("Polling thread sleeping, %rs" % config.polling_interval)
time.sleep(config.polling_interval)
log.info("Polling thread sleeping, %rs" % conf.polling_interval)
time.sleep(conf.polling_interval)
def fail_lost_builds(self, session):
# This function is supposed to be handling only
@@ -211,12 +192,11 @@ class Poller(threading.Thread):
# TODO re-use
if config.system == "koji":
koji_session, _ = rida.builder.KojiModuleBuilder.get_session_from_config(config)
if conf.system == "koji":
koji_session, _ = rida.builder.KojiModuleBuilder.get_session_from_config(conf)
state = koji.BUILD_STATES['BUILDING'] # Check tasks that we track as BUILDING
log.info("Querying tasks for statuses:")
query = session.query(rida.database.ComponentBuild)
res = query.filter(state==koji.BUILD_STATES['BUILDING']).all()
res = models.ComponentBuild.query.filter_by(state=koji.BUILD_STATES['BUILDING']).all()
log.info("Checking status for %d tasks." % len(res))
for component_build in res:
@@ -245,16 +225,16 @@ class Poller(threading.Thread):
})
else:
raise NotImplementedError("Buildsystem %r is not supported." % config.system)
raise NotImplementedError("Buildsystem %r is not supported." % conf.system)
def log_summary(self, session):
log.info("Current status:")
backlog = self.outgoing_work_queue.qsize()
log.info(" * internal queue backlog is %i." % backlog)
states = sorted(rida.BUILD_STATES.items(), key=operator.itemgetter(1))
states = sorted(models.BUILD_STATES.items(), key=operator.itemgetter(1))
for name, code in states:
query = session.query(rida.database.ModuleBuild)
count = query.filter_by(state=code).count()
query = models.ModuleBuild.query.filter_by(state=code)
count = query.count()
if count:
log.info(" * %i module builds in the %s state." % (count, name))
if name == 'build':
@@ -263,10 +243,9 @@ class Poller(threading.Thread):
for component_build in module_build.component_builds:
log.info(" * %r" % component_build)
def process_waiting_module_builds(self, session):
log.info("Looking for module builds stuck in the wait state.")
builds = rida.database.ModuleBuild.by_state(session, "wait")
builds = models.ModuleBuild.by_state(session, "wait")
# TODO -- do throttling calculation here...
log.info(" %r module builds in the wait state..." % len(builds))
for build in builds:
@@ -275,7 +254,7 @@ class Poller(threading.Thread):
'topic': '.module.build.state.change',
'msg': build.json(),
}
rida.scheduler.handlers.modules.wait(config, session, msg)
rida.scheduler.handlers.modules.wait(conf, session, msg)
def process_open_component_builds(self, session):
log.warning("process_open_component_builds is not yet implemented...")
@@ -285,7 +264,6 @@ class Poller(threading.Thread):
def main():
rida.logger.init_logging(config)
log.info("Starting ridad.")
try:
work_queue = queue.Queue()

View File

@@ -34,9 +34,7 @@ import subprocess as sp
import re
import tempfile
import logging
log = logging.getLogger(__name__)
from rida import log
import rida.utils

View File

@@ -22,10 +22,8 @@
""" Utility functions for rida. """
import functools
import logging
import time
log = logging.getLogger(__name__)
from rida import log
def retry(timeout=120, interval=30, wait_on=Exception):

165
rida/views.py Normal file
View File

@@ -0,0 +1,165 @@
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 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 Petr Šabata <contyk@redhat.com>
""" The module build orchestrator for Modularity, API.
This is the implementation of the orchestrator's public RESTful API.
"""
from flask import request, jsonify
import json
import logging
import modulemd
import os
import rida.auth
import rida.logger
import rida.scm
import shutil
import tempfile
from rida import app, conf, db, log
from rida import models
@app.route("/rida/module-builds/", methods=["POST"])
def submit_build():
"""Handles new module build submissions."""
username = rida.auth.is_packager(conf.pkgdb_api_url)
if not username:
return ("You must use your Fedora certificate when submitting"
" new build", 403)
try:
r = json.loads(request.get_data().decode("utf-8"))
except:
return "Invalid JSON submitted", 400
if "scmurl" not in r:
return "Missing scmurl", 400
url = r["scmurl"]
urlallowed = False
for prefix in conf.scmurls:
if url.startswith(prefix):
urlallowed = True
break
if not urlallowed:
return "The submitted scmurl isn't allowed", 403
yaml = str()
try:
td = tempfile.mkdtemp()
scm = rida.scm.SCM(url, conf.scmurls)
cod = scm.checkout(td)
cofn = os.path.join(cod, (scm.name + ".yaml"))
with open(cofn, "r") as mmdfile:
yaml = mmdfile.read()
except Exception as e:
if "is not in the list of allowed SCMs" in str(e):
rc = 403
elif "Invalid SCM URL" in str(e):
rc = 400
else:
rc = 500
return str(e), rc
finally:
shutil.rmtree(td)
mmd = modulemd.ModuleMetadata()
try:
mmd.loads(yaml)
except:
return "Invalid modulemd", 422
if models.ModuleBuild.query.filter_by(name=mmd.name, version=mmd.version, release=mmd.release).first():
return "Module already exists", 409
module = models.ModuleBuild.create(
db.session,
conf,
name=mmd.name,
version=mmd.version,
release=mmd.release,
modulemd=yaml,
scmurl=url,
)
def failure(message, code):
# TODO, we should make some note of why it failed in the db..
log.exception(message)
module.transition(conf, models.BUILD_STATES["failed"])
db.session.add(module)
db.session.commit()
return message, code
for pkgname, pkg in mmd.components.rpms.packages.items():
if pkg.get("repository") and not conf.rpms_allow_repository:
return failure("Custom component repositories aren't allowed", 403)
if pkg.get("cache") and not conf.rpms_allow_cache:
return failure("Custom component caches aren't allowed", 403)
if not pkg.get("repository"):
pkg["repository"] = conf.rpms_default_repository + pkgname
if not pkg.get("cache"):
pkg["cache"] = conf.rpms_default_cache + pkgname
if not pkg.get("commit"):
try:
pkg["commit"] = rida.scm.SCM(pkg["repository"]).get_latest()
except Exception as e:
return failure("Failed to get the latest commit: %s" % pkgname, 422)
full_url = pkg["repository"] + "?#" + pkg["commit"]
if not rida.scm.SCM(full_url).is_available():
return failure("Cannot checkout %s" % pkgname, 422)
build = models.ComponentBuild(
module_id=module.id,
package=pkgname,
format="rpms",
scmurl=full_url,
)
db.session.add(build)
module.modulemd = mmd.dumps()
module.transition(conf, models.BUILD_STATES["wait"])
db.session.add(module)
db.session.commit()
logging.info("%s submitted build of %s-%s-%s", username, mmd.name,
mmd.version, mmd.release)
return jsonify(module.json()), 201
@app.route("/rida/module-builds/", methods=["GET"])
def query_builds():
"""Lists all tracked module builds."""
return jsonify([{"id": x.id, "state": x.state}
for x in models.ModuleBuild.query.all()]), 200
@app.route("/rida/module-builds/<int:id>", methods=["GET"])
def query_build(id):
"""Lists details for the specified module builds."""
module = models.ModuleBuild.query.filter_by(id=id).first()
if module:
tasks = dict()
if module.state != "init":
for build in models.ComponentBuild.query.filter_by(module_id=id).all():
tasks[build.format + "/" + build.package] = \
str(build.task_id) + "/" + build.state
return jsonify({
"id": module.id,
"state": module.state,
"tasks": tasks
}), 200
else:
return "No such module found.", 404