Package coprs :: Package logic :: Module modules_logic
[hide private]
[frames] | no frames]

Source Code for Module coprs.logic.modules_logic

  1  import os 
  2  import time 
  3  import base64 
  4  import requests 
  5  from collections import defaultdict 
  6  from sqlalchemy import and_ 
  7  from datetime import datetime 
  8  from coprs import models 
  9  from coprs import db 
 10  from coprs import exceptions 
 11  from coprs.logic import builds_logic 
 12  from wtforms import ValidationError 
 13   
 14  import gi 
 15  gi.require_version('Modulemd', '1.0') 
 16  from gi.repository import Modulemd 
17 18 19 -class ModulesLogic(object):
20 @classmethod
21 - def get(cls, module_id):
22 """ 23 Return single module identified by `module_id` 24 """ 25 return models.Module.query.filter(models.Module.id == module_id)
26 27 @classmethod
28 - def get_by_nsv(cls, copr, name, stream, version):
34 35 @classmethod
36 - def get_by_nsv_str(cls, copr, nsv):
37 name, stream, version = nsv.split("-") 38 return cls.get_by_nsv(copr, name, stream, version)
39 40 @classmethod
41 - def get_multiple(cls):
42 return models.Module.query.order_by(models.Module.id.desc())
43 44 @classmethod
45 - def get_multiple_by_copr(cls, copr):
47 48 @classmethod
49 - def yaml2modulemd(cls, yaml):
50 mmd = Modulemd.ModuleStream() 51 mmd.import_from_string(yaml) 52 return mmd
53 54 @classmethod
55 - def from_modulemd(cls, mmd):
56 yaml_b64 = base64.b64encode(mmd.dumps().encode("utf-8")).decode("utf-8") 57 return models.Module(name=mmd.get_name(), stream=mmd.get_stream(), version=mmd.get_version(), 58 summary=mmd.get_summary(), description=mmd.get_description(), yaml_b64=yaml_b64)
59 60 @classmethod
61 - def validate(cls, mmd):
62 if not all([mmd.get_name(), mmd.get_stream(), mmd.get_version()]): 63 raise ValidationError("Module should contain name, stream and version")
64 65 @classmethod
66 - def add(cls, user, copr, module):
67 if not user.can_build_in(copr): 68 raise exceptions.InsufficientRightsException("You don't have permissions to build in this copr.") 69 70 module.copr_id = copr.id 71 module.copr = copr 72 module.created_on = time.time() 73 74 db.session.add(module) 75 return module
76 77 @classmethod
78 - def set_defaults_for_optional_params(cls, mmd, filename=None):
79 mmd.set_name(mmd.get_name() or str(os.path.splitext(filename)[0])) 80 mmd.set_stream(mmd.get_stream() or "master") 81 mmd.set_version(mmd.get_version() or int(datetime.now().strftime("%Y%m%d%H%M%S")))
82
83 84 -class ModuleBuildFacade(object):
85 - def __init__(self, user, copr, yaml, filename=None):
86 self.user = user 87 self.copr = copr 88 self.yaml = yaml 89 self.filename = filename 90 91 self.modulemd = ModulesLogic.yaml2modulemd(yaml) 92 ModulesLogic.set_defaults_for_optional_params(self.modulemd, filename=filename) 93 ModulesLogic.validate(self.modulemd)
94
95 - def submit_build(self):
96 module = ModulesLogic.add(self.user, self.copr, ModulesLogic.from_modulemd(self.modulemd)) 97 if not self.platform_chroots: 98 raise ValidationError("Module platform is {} which doesn't match to any chroots enabled in {} project" 99 .format(self.platform, self.copr.full_name)) 100 self.add_builds(self.modulemd.get_rpm_components(), module) 101 return module
102 103 @classmethod
104 - def get_build_batches(cls, rpms):
105 """ 106 Determines Which component should be built in which batch. Returns an ordered list of grouped components, 107 first group of components should be built as a first batch, second as second and so on. 108 Particular components groups are represented by dicts and can by built in a random order within the batch. 109 :return: list of lists 110 """ 111 batches = defaultdict(dict) 112 for pkgname, rpm in rpms.items(): 113 batches[rpm.get_buildorder()][pkgname] = rpm 114 return [batches[number] for number in sorted(batches.keys())]
115 116 @property
117 - def platform(self):
118 platform = self.modulemd.get_buildrequires().get("platform", []) 119 return platform if isinstance(platform, list) else [platform]
120 121 @property
122 - def platform_chroots(self):
123 """ 124 Return a list of chroot names based on buildrequired platform and enabled chroots for the project. 125 Example: Copr chroots are ["fedora-22-x86-64", "fedora-23-x86_64"] and modulemd specifies "f23" as a platform, 126 then `platform_chroots` are ["fedora-23-x86_64"] 127 Alternatively, the result will be same for "-f22" platform 128 :return: list of strings 129 """ 130 131 # Just to be sure, that all chroot abbreviations from platform are in expected format, e.g. f28 or -f30 132 for abbrev in self.platform: 133 if not (abbrev.startswith(("f", "-f")) and abbrev.lstrip("-f").isnumeric()): 134 raise ValidationError("Unexpected platform '{}', it should be e.g. f28 or -f30".format(abbrev)) 135 136 chroot_archs = {} 137 for chroot in self.copr.active_chroots: 138 chroot_archs.setdefault(chroot.name_release, []).append(chroot.arch) 139 140 def abbrev2chroots(abbrev): 141 name_release = abbrev.replace("-", "").replace("f", "fedora-") 142 return ["{}-{}".format(name_release, arch) for arch in chroot_archs.get(name_release, [])]
143 144 exclude_chroots = set() 145 select_chroots = set() 146 for abbrev in self.platform: 147 abbrev_chroots = abbrev2chroots(abbrev) 148 if not abbrev_chroots: 149 raise ValidationError("Module platform stream {} doesn't match to any enabled chroots in the {} project" 150 .format(abbrev, self.copr.full_name)) 151 (exclude_chroots if abbrev.startswith("-") else select_chroots).update(abbrev_chroots) 152 153 chroots = {chroot.name for chroot in self.copr.active_chroots} 154 chroots -= exclude_chroots 155 if select_chroots: 156 chroots &= select_chroots 157 return chroots
158 159
160 - def add_builds(self, rpms, module):
161 blocked_by_id = None 162 for group in self.get_build_batches(rpms): 163 batch = models.Batch() 164 batch.blocked_by_id = blocked_by_id 165 db.session.add(batch) 166 for pkgname, rpm in group.items(): 167 clone_url = self.get_clone_url(pkgname, rpm) 168 build = builds_logic.BuildsLogic.create_new_from_scm(self.user, self.copr, scm_type="git", 169 clone_url=clone_url, committish=rpm.peek_ref(), 170 chroot_names=self.platform_chroots) 171 build.batch = batch 172 build.batch_id = batch.id 173 build.module_id = module.id 174 db.session.add(build) 175 176 # Every batch needs to by blocked by the previous one 177 blocked_by_id = batch.id
178
179 - def get_clone_url(self, pkgname, rpm):
180 if rpm.peek_repository(): 181 return rpm.peek_repository() 182 return self.default_distgit.format(pkgname=pkgname)
183 184 @property
185 - def default_distgit(self):
186 # @TODO move to better place 187 return "https://src.fedoraproject.org/rpms/{pkgname}"
188
189 190 -class ModulemdGenerator(object):
191 - def __init__(self, name="", stream="", version=0, summary="", config=None):
192 self.config = config 193 licenses = Modulemd.SimpleSet() 194 licenses.add("unknown") 195 self.mmd = Modulemd.ModuleStream(mdversion=1, name=name, stream=stream, version=version, summary=summary, 196 description="", content_licenses=licenses, module_licenses=licenses)
197 198 @property
199 - def nsv(self):
200 return "{}-{}-{}".format(self.mmd.get_name(), self.mmd.get_stream(), self.mmd.get_version())
201
202 - def add_api(self, packages):
203 mmd_set = Modulemd.SimpleSet() 204 for package in packages: 205 mmd_set.add(str(package)) 206 self.mmd.set_rpm_api(mmd_set)
207
208 - def add_filter(self, packages):
209 mmd_set = Modulemd.SimpleSet() 210 for package in packages: 211 mmd_set.add(str(package)) 212 self.mmd.set_rpm_filter(mmd_set)
213
214 - def add_profiles(self, profiles):
215 for i, values in profiles: 216 name, packages = values 217 profile = Modulemd.Profile(name=name) 218 for package in packages: 219 profile.add_rpm(str(package)) 220 self.mmd.add_profile(profile)
221
222 - def add_components(self, packages, filter_packages, builds):
223 build_ids = sorted(list(set([int(id) for p, id in zip(packages, builds) 224 if p in filter_packages]))) 225 for package in filter_packages: 226 build_id = builds[packages.index(package)] 227 build = builds_logic.BuildsLogic.get_by_id(build_id).first() 228 build_chroot = self._build_chroot(build) 229 buildorder = build_ids.index(int(build.id)) 230 rationale = "User selected the package as a part of the module" 231 self.add_component(package, build, build_chroot, rationale, buildorder)
232
233 - def _build_chroot(self, build):
234 chroot = None 235 for chroot in build.build_chroots: 236 if chroot.name == "custom-1-x86_64": 237 break 238 return chroot
239
240 - def add_component(self, package_name, build, chroot, rationale, buildorder=1):
241 ref = str(chroot.git_hash) if chroot else "" 242 distgit_url = self.config["DIST_GIT_URL"].replace("/cgit", "/git") 243 url = os.path.join(distgit_url, build.copr.full_name, "{}.git".format(build.package.name)) 244 component = Modulemd.ComponentRpm(name=str(package_name), rationale=rationale, 245 repository=url, ref=ref, buildorder=1) 246 self.mmd.add_rpm_component(component)
247
248 - def generate(self):
249 return self.mmd.dumps()
250
251 252 -class ModuleProvider(object):
253 - def __init__(self, filename, yaml):
254 self.filename = filename 255 self.yaml = yaml
256 257 @classmethod
258 - def from_input(cls, obj):
259 if hasattr(obj, "read"): 260 return cls.from_file(obj) 261 return cls.from_url(obj)
262 263 @classmethod
264 - def from_file(cls, ref):
265 return cls(ref.filename, ref.read().decode("utf-8"))
266 267 @classmethod
268 - def from_url(cls, url):
269 if not url.endswith(".yaml"): 270 raise ValidationError("This URL doesn't point to a .yaml file") 271 272 request = requests.get(url) 273 if request.status_code != 200: 274 raise requests.RequestException("This URL seems to be wrong") 275 return cls(os.path.basename(url), request.text)
276