Package coprs :: Module models
[hide private]
[frames] | no frames]

Source Code for Module coprs.models

   1  import copy 
   2  import datetime 
   3  import os 
   4  import json 
   5  import base64 
   6  import uuid 
   7  from fnmatch import fnmatch 
   8   
   9  from sqlalchemy.ext.associationproxy import association_proxy 
  10  from six.moves.urllib.parse import urljoin 
  11  from libravatar import libravatar_url 
  12  import zlib 
  13   
  14  from copr_common.enums import ActionTypeEnum, BackendResultEnum, FailTypeEnum, ModuleStatusEnum, StatusEnum 
  15  from coprs import constants 
  16  from coprs import db 
  17  from coprs import helpers 
  18  from coprs import app 
  19   
  20  import itertools 
  21  import operator 
  22  from coprs.helpers import JSONEncodedDict 
  23   
  24  import gi 
  25  gi.require_version('Modulemd', '1.0') 
  26  from gi.repository import Modulemd 
27 28 29 -class CoprSearchRelatedData(object):
32
33 34 -class User(db.Model, helpers.Serializer):
35 """ 36 Represents user of the copr frontend 37 """ 38 39 id = db.Column(db.Integer, primary_key=True) 40 41 # unique username 42 username = db.Column(db.String(100), nullable=False, unique=True) 43 44 # email 45 mail = db.Column(db.String(150), nullable=False) 46 47 # optional timezone 48 timezone = db.Column(db.String(50), nullable=True) 49 50 # is this user proven? proven users can modify builder memory and 51 # timeout for single builds 52 proven = db.Column(db.Boolean, default=False) 53 54 # is this user admin of the system? 55 admin = db.Column(db.Boolean, default=False) 56 57 # can this user behave as someone else? 58 proxy = db.Column(db.Boolean, default=False) 59 60 # stuff for the cli interface 61 api_login = db.Column(db.String(40), nullable=False, default="abc") 62 api_token = db.Column(db.String(40), nullable=False, default="abc") 63 api_token_expiration = db.Column( 64 db.Date, nullable=False, default=datetime.date(2000, 1, 1)) 65 66 # list of groups as retrieved from openid 67 openid_groups = db.Column(JSONEncodedDict) 68 69 @property
70 - def name(self):
71 """ 72 Return the short username of the user, e.g. bkabrda 73 """ 74 75 return self.username
76
77 - def permissions_for_copr(self, copr):
78 """ 79 Get permissions of this user for the given copr. 80 Caches the permission during one request, 81 so use this if you access them multiple times 82 """ 83 84 if not hasattr(self, "_permissions_for_copr"): 85 self._permissions_for_copr = {} 86 if copr.name not in self._permissions_for_copr: 87 self._permissions_for_copr[copr.name] = ( 88 CoprPermission.query 89 .filter_by(user=self) 90 .filter_by(copr=copr) 91 .first() 92 ) 93 return self._permissions_for_copr[copr.name]
94
95 - def can_build_in(self, copr):
96 """ 97 Determine if this user can build in the given copr. 98 """ 99 can_build = False 100 if copr.user_id == self.id: 101 can_build = True 102 if (self.permissions_for_copr(copr) and 103 self.permissions_for_copr(copr).copr_builder == 104 helpers.PermissionEnum("approved")): 105 106 can_build = True 107 108 # a bit dirty code, here we access flask.session object 109 if copr.group is not None and \ 110 copr.group.fas_name in self.user_teams: 111 return True 112 113 return can_build
114 115 @property
116 - def user_teams(self):
117 if self.openid_groups and 'fas_groups' in self.openid_groups: 118 return self.openid_groups['fas_groups'] 119 else: 120 return []
121 122 @property
123 - def user_groups(self):
124 return Group.query.filter(Group.fas_name.in_(self.user_teams)).all()
125
126 - def can_build_in_group(self, group):
127 """ 128 :type group: Group 129 """ 130 if group.fas_name in self.user_teams: 131 return True 132 else: 133 return False
134
135 - def can_edit(self, copr):
136 """ 137 Determine if this user can edit the given copr. 138 """ 139 140 if copr.user == self or self.admin: 141 return True 142 if (self.permissions_for_copr(copr) and 143 self.permissions_for_copr(copr).copr_admin == 144 helpers.PermissionEnum("approved")): 145 146 return True 147 148 if copr.group is not None and \ 149 copr.group.fas_name in self.user_teams: 150 return True 151 152 return False
153 154 @property
155 - def serializable_attributes(self):
156 # enumerate here to prevent exposing credentials 157 return ["id", "name"]
158 159 @property
160 - def coprs_count(self):
161 """ 162 Get number of coprs for this user. 163 """ 164 165 return (Copr.query.filter_by(user=self). 166 filter_by(deleted=False). 167 filter_by(group_id=None). 168 count())
169 170 @property
171 - def gravatar_url(self):
172 """ 173 Return url to libravatar image. 174 """ 175 176 try: 177 return libravatar_url(email=self.mail, https=True) 178 except IOError: 179 return ""
180
181 182 -class Copr(db.Model, helpers.Serializer, CoprSearchRelatedData):
183 """ 184 Represents a single copr (private repo with builds, mock chroots, etc.). 185 """ 186 187 __table_args__ = ( 188 db.Index('copr_webhook_secret', 'webhook_secret'), 189 db.Index('copr_name_group_id_idx', 'name', 'group_id'), 190 ) 191 192 id = db.Column(db.Integer, primary_key=True) 193 # name of the copr, no fancy chars (checked by forms) 194 name = db.Column(db.String(100), nullable=False) 195 homepage = db.Column(db.Text) 196 contact = db.Column(db.Text) 197 # string containing urls of additional repos (separated by space) 198 # that this copr will pull dependencies from 199 repos = db.Column(db.Text) 200 # time of creation as returned by int(time.time()) 201 created_on = db.Column(db.Integer) 202 # description and instructions given by copr owner 203 description = db.Column(db.Text) 204 instructions = db.Column(db.Text) 205 deleted = db.Column(db.Boolean, default=False) 206 playground = db.Column(db.Boolean, default=False) 207 208 # should copr run `createrepo` each time when build packages are changed 209 auto_createrepo = db.Column(db.Boolean, default=True) 210 211 # relations 212 user_id = db.Column(db.Integer, db.ForeignKey("user.id"), index=True) 213 user = db.relationship("User", backref=db.backref("coprs")) 214 group_id = db.Column(db.Integer, db.ForeignKey("group.id")) 215 group = db.relationship("Group", backref=db.backref("groups")) 216 mock_chroots = association_proxy("copr_chroots", "mock_chroot") 217 forked_from_id = db.Column(db.Integer, db.ForeignKey("copr.id")) 218 forked_from = db.relationship("Copr", remote_side=id, backref=db.backref("forks")) 219 220 # a secret to be used for webhooks authentication 221 webhook_secret = db.Column(db.String(100)) 222 223 # enable networking for the builds by default 224 build_enable_net = db.Column(db.Boolean, default=True, 225 server_default="1", nullable=False) 226 227 unlisted_on_hp = db.Column(db.Boolean, default=False, nullable=False) 228 229 # information for search index updating 230 latest_indexed_data_update = db.Column(db.Integer) 231 232 # builds and the project are immune against deletion 233 persistent = db.Column(db.Boolean, default=False, nullable=False, server_default="0") 234 235 # if backend deletion script should be run for the project's builds 236 auto_prune = db.Column(db.Boolean, default=True, nullable=False, server_default="1") 237 238 # use mock's bootstrap container feature 239 use_bootstrap_container = db.Column(db.Boolean, default=False, nullable=False, server_default="0") 240 241 # if chroots for the new branch should be auto-enabled and populated from rawhide ones 242 follow_fedora_branching = db.Column(db.Boolean, default=True, nullable=False, server_default="1") 243 244 # scm integration properties 245 scm_repo_url = db.Column(db.Text) 246 scm_api_type = db.Column(db.Text) 247 scm_api_auth_json = db.Column(db.Text) 248 249 __mapper_args__ = { 250 "order_by": created_on.desc() 251 } 252 253 @property
254 - def main_dir(self):
255 """ 256 Return main copr dir for a Copr 257 """ 258 return CoprDir.query.filter(CoprDir.copr_id==self.id).filter(CoprDir.main==True).one()
259 260 @property
261 - def scm_api_auth(self):
262 if not self.scm_api_auth_json: 263 return {} 264 return json.loads(self.scm_api_auth_json)
265 266 @property
267 - def is_a_group_project(self):
268 """ 269 Return True if copr belongs to a group 270 """ 271 return self.group is not None
272 273 @property
274 - def owner(self):
275 """ 276 Return owner (user or group) of this copr 277 """ 278 return self.group if self.is_a_group_project else self.user
279 280 @property
281 - def owner_name(self):
282 """ 283 Return @group.name for a copr owned by a group and user.name otherwise 284 """ 285 return self.group.at_name if self.is_a_group_project else self.user.name
286 287 @property
288 - def repos_list(self):
289 """ 290 Return repos of this copr as a list of strings 291 """ 292 return self.repos.split()
293 294 @property
295 - def active_chroots(self):
296 """ 297 Return list of active mock_chroots of this copr 298 """ 299 return filter(lambda x: x.is_active, self.mock_chroots)
300 301 @property
302 - def active_copr_chroots(self):
303 """ 304 :rtype: list of CoprChroot 305 """ 306 return [c for c in self.copr_chroots if c.is_active]
307 308 @property
309 - def active_chroots_sorted(self):
310 """ 311 Return list of active mock_chroots of this copr 312 """ 313 return sorted(self.active_chroots, key=lambda ch: ch.name)
314 315 @property
316 - def outdated_chroots(self):
317 return [chroot for chroot in self.copr_chroots if chroot.delete_after]
318 319 @property
320 - def active_chroots_grouped(self):
321 """ 322 Return list of active mock_chroots of this copr 323 """ 324 chroots = [("{} {}".format(c.os_release, c.os_version), c.arch) for c in self.active_chroots_sorted] 325 output = [] 326 for os, chs in itertools.groupby(chroots, operator.itemgetter(0)): 327 output.append((os, [ch[1] for ch in chs])) 328 329 return output
330 331 @property
332 - def build_count(self):
333 """ 334 Return number of builds in this copr 335 """ 336 return len(self.builds)
337 338 @property
339 - def disable_createrepo(self):
340 return not self.auto_createrepo
341 342 @disable_createrepo.setter
343 - def disable_createrepo(self, value):
344 self.auto_createrepo = not bool(value)
345 346 @property
347 - def devel_mode(self):
348 return self.disable_createrepo
349 350 @property
351 - def modified_chroots(self):
352 """ 353 Return list of chroots which has been modified 354 """ 355 modified_chroots = [] 356 for chroot in self.copr_chroots: 357 if ((chroot.buildroot_pkgs or chroot.repos 358 or chroot.with_opts or chroot.without_opts) 359 and chroot.is_active): 360 modified_chroots.append(chroot) 361 return modified_chroots
362
363 - def is_release_arch_modified(self, name_release, arch):
364 if "{}-{}".format(name_release, arch) in \ 365 [chroot.name for chroot in self.modified_chroots]: 366 return True 367 return False
368 369 @property
370 - def full_name(self):
371 return "{}/{}".format(self.owner_name, self.name)
372 373 @property
374 - def repo_name(self):
375 return "{}-{}".format(self.owner_name, self.main_dir.name)
376 377 @property
378 - def repo_url(self):
379 return "/".join([app.config["BACKEND_BASE_URL"], 380 u"results", 381 self.main_dir.full_name])
382 383 @property
384 - def repo_id(self):
385 return "-".join([self.owner_name.replace("@", "group_"), self.name])
386 387 @property
388 - def modules_url(self):
389 return "/".join([self.repo_url, "modules"])
390
391 - def to_dict(self, private=False, show_builds=True, show_chroots=True):
392 result = {} 393 for key in ["id", "name", "description", "instructions"]: 394 result[key] = str(copy.copy(getattr(self, key))) 395 result["owner"] = self.owner_name 396 return result
397 398 @property
399 - def still_forking(self):
400 return bool(Action.query.filter(Action.result == BackendResultEnum("waiting")) 401 .filter(Action.action_type == ActionTypeEnum("fork")) 402 .filter(Action.new_value == self.full_name).all())
403 406 407 @property
408 - def enable_net(self):
409 return self.build_enable_net
410 411 @enable_net.setter
412 - def enable_net(self, value):
413 self.build_enable_net = value
414
415 - def new_webhook_secret(self):
416 self.webhook_secret = str(uuid.uuid4())
417
418 419 -class CoprPermission(db.Model, helpers.Serializer):
420 """ 421 Association class for Copr<->Permission relation 422 """ 423 424 # see helpers.PermissionEnum for possible values of the fields below 425 # can this user build in the copr? 426 copr_builder = db.Column(db.SmallInteger, default=0) 427 # can this user serve as an admin? (-> edit and approve permissions) 428 copr_admin = db.Column(db.SmallInteger, default=0) 429 430 # relations 431 user_id = db.Column(db.Integer, db.ForeignKey("user.id"), primary_key=True) 432 user = db.relationship("User", backref=db.backref("copr_permissions")) 433 copr_id = db.Column(db.Integer, db.ForeignKey("copr.id"), primary_key=True) 434 copr = db.relationship("Copr", backref=db.backref("copr_permissions"))
435
436 437 -class CoprDir(db.Model):
438 """ 439 Represents one of data directories for a copr. 440 """ 441 id = db.Column(db.Integer, primary_key=True) 442 443 name = db.Column(db.Text, index=True) 444 main = db.Column(db.Boolean, default=False, server_default="0", nullable=False) 445 446 ownername = db.Column(db.Text, index=True, nullable=False) 447 448 copr_id = db.Column(db.Integer, db.ForeignKey("copr.id"), index=True, nullable=False) 449 copr = db.relationship("Copr", backref=db.backref("dirs")) 450 451 __table_args__ = ( 452 db.Index('only_one_main_copr_dir', copr_id, main, 453 unique=True, postgresql_where=(main==True)), 454 455 db.UniqueConstraint('ownername', 'name', 456 name='ownername_copr_dir_uniq'), 457 ) 458
459 - def __init__(self, *args, **kwargs):
460 if kwargs.get('copr') and not kwargs.get('ownername'): 461 kwargs['ownername'] = kwargs.get('copr').owner_name 462 super(CoprDir, self).__init__(*args, **kwargs)
463 464 @property
465 - def full_name(self):
466 return "{}/{}".format(self.copr.owner_name, self.name)
467 468 @property
469 - def repo_name(self):
470 return "{}-{}".format(self.copr.owner_name, self.name)
471 472 @property
473 - def repo_url(self):
474 return "/".join([app.config["BACKEND_BASE_URL"], 475 u"results", self.full_name])
476 477 @property
478 - def repo_id(self):
479 if self.copr.is_a_group_project: 480 return "group_{}-{}".format(self.copr.group.name, self.name) 481 else: 482 return "{}-{}".format(self.copr.user.name, self.name)
483
484 485 -class Package(db.Model, helpers.Serializer, CoprSearchRelatedData):
486 """ 487 Represents a single package in a project_dir. 488 """ 489 490 __table_args__ = ( 491 db.UniqueConstraint('copr_dir_id', 'name', name='packages_copr_dir_pkgname'), 492 db.Index('package_webhook_sourcetype', 'webhook_rebuild', 'source_type'), 493 ) 494
495 - def __init__(self, *args, **kwargs):
496 if kwargs.get('copr') and not kwargs.get('copr_dir'): 497 kwargs['copr_dir'] = kwargs.get('copr').main_dir 498 super(Package, self).__init__(*args, **kwargs)
499 500 id = db.Column(db.Integer, primary_key=True) 501 name = db.Column(db.String(100), nullable=False) 502 # Source of the build: type identifier 503 source_type = db.Column(db.Integer, default=helpers.BuildSourceEnum("unset")) 504 # Source of the build: description in json, example: git link, srpm url, etc. 505 source_json = db.Column(db.Text) 506 # True if the package is built automatically via webhooks 507 webhook_rebuild = db.Column(db.Boolean, default=False) 508 # enable networking during a build process 509 enable_net = db.Column(db.Boolean, default=False, server_default="0", nullable=False) 510 511 # @TODO Remove me few weeks after Copr migration 512 # Contain status of the Package before migration 513 # Normally the `status` is not stored in `Package`. It is computed from `status` variable of `BuildChroot`, 514 # but `old_status` has to be stored here, because we migrate whole `package` table, but only succeeded builds. 515 # Therefore if `old_status` was in `BuildChroot` we wouldn't be able to know old state of non-succeeded packages 516 # even though it would be known before migration. 517 old_status = db.Column(db.Integer) 518 519 builds = db.relationship("Build", order_by="Build.id") 520 521 # relations 522 copr_id = db.Column(db.Integer, db.ForeignKey("copr.id"), index=True) 523 copr = db.relationship("Copr", backref=db.backref("packages")) 524 525 copr_dir_id = db.Column(db.Integer, db.ForeignKey("copr_dir.id"), index=True) 526 copr_dir = db.relationship("CoprDir", backref=db.backref("packages")) 527 528 # comma-separated list of wildcards of chroot names that this package should 529 # not be built against, e.g. "fedora-*, epel-*-i386" 530 chroot_blacklist_raw = db.Column(db.Text) 531 532 @property
533 - def dist_git_repo(self):
534 return "{}/{}".format(self.copr_dir.full_name, self.name)
535 536 @property
537 - def source_json_dict(self):
538 if not self.source_json: 539 return {} 540 return json.loads(self.source_json)
541 542 @property
543 - def source_type_text(self):
545 546 @property
547 - def has_source_type_set(self):
548 """ 549 Package's source type (and source_json) is being derived from its first build, which works except 550 for "link" and "upload" cases. Consider these being equivalent to source_type being unset. 551 """ 552 return self.source_type and self.source_type_text != "link" and self.source_type_text != "upload"
553 554 @property
555 - def dist_git_url(self):
556 if "DIST_GIT_URL" in app.config: 557 return "{}/{}.git".format(app.config["DIST_GIT_URL"], self.dist_git_repo) 558 return None
559 560 @property
561 - def dist_git_clone_url(self):
562 if "DIST_GIT_CLONE_URL" in app.config: 563 return "{}/{}.git".format(app.config["DIST_GIT_CLONE_URL"], self.dist_git_repo) 564 else: 565 return self.dist_git_url
566
567 - def last_build(self, successful=False):
568 for build in reversed(self.builds): 569 if not successful or build.state == "succeeded": 570 return build 571 return None
572
573 - def to_dict(self, with_latest_build=False, with_latest_succeeded_build=False, with_all_builds=False):
574 package_dict = super(Package, self).to_dict() 575 package_dict['source_type'] = helpers.BuildSourceEnum(package_dict['source_type']) 576 577 if with_latest_build: 578 build = self.last_build(successful=False) 579 package_dict['latest_build'] = build.to_dict(with_chroot_states=True) if build else None 580 if with_latest_succeeded_build: 581 build = self.last_build(successful=True) 582 package_dict['latest_succeeded_build'] = build.to_dict(with_chroot_states=True) if build else None 583 if with_all_builds: 584 package_dict['builds'] = [build.to_dict(with_chroot_states=True) for build in reversed(self.builds)] 585 586 return package_dict
587 590 591 592 @property
593 - def chroot_blacklist(self):
594 if not self.chroot_blacklist_raw: 595 return [] 596 597 blacklisted = [] 598 for pattern in self.chroot_blacklist_raw.split(','): 599 pattern = pattern.strip() 600 if not pattern: 601 continue 602 blacklisted.append(pattern) 603 604 return blacklisted
605 606 607 @staticmethod
608 - def matched_chroot(chroot, patterns):
609 for pattern in patterns: 610 if fnmatch(chroot.name, pattern): 611 return True 612 return False
613 614 615 @property
616 - def main_pkg(self):
617 if self.copr_dir.main: 618 return self 619 620 main_pkg = Package.query.filter_by( 621 name=self.name, 622 copr_dir_id=self.copr.main_dir.id 623 ).first() 624 return main_pkg
625 626 627 @property
628 - def chroots(self):
629 chroots = list(self.copr.active_chroots) 630 if not self.chroot_blacklist_raw: 631 # no specific blacklist 632 if self.copr_dir.main: 633 return chroots 634 return self.main_pkg.chroots 635 636 filtered = [c for c in chroots if not self.matched_chroot(c, self.chroot_blacklist)] 637 # We never want to filter everything, this is a misconfiguration. 638 return filtered if filtered else chroots
639
640 641 -class Build(db.Model, helpers.Serializer):
642 """ 643 Representation of one build in one copr 644 """ 645 646 SCM_COMMIT = 'commit' 647 SCM_PULL_REQUEST = 'pull-request' 648 649 __table_args__ = (db.Index('build_canceled', "canceled"), 650 db.Index('build_order', "is_background", "id"), 651 db.Index('build_filter', "source_type", "canceled"), 652 db.Index('build_canceled_is_background_source_status_id_idx', 'canceled', "is_background", "source_status", "id"), 653 ) 654
655 - def __init__(self, *args, **kwargs):
656 if kwargs.get('source_type') == helpers.BuildSourceEnum("custom"): 657 source_dict = json.loads(kwargs['source_json']) 658 if 'fedora-latest' in source_dict['chroot']: 659 arch = source_dict['chroot'].rsplit('-', 2)[2] 660 source_dict['chroot'] = \ 661 MockChroot.latest_fedora_branched_chroot(arch=arch).name 662 kwargs['source_json'] = json.dumps(source_dict) 663 664 if kwargs.get('copr') and not kwargs.get('copr_dir'): 665 kwargs['copr_dir'] = kwargs.get('copr').main_dir 666 667 super(Build, self).__init__(*args, **kwargs)
668 669 id = db.Column(db.Integer, primary_key=True) 670 # single url to the source rpm, should not contain " ", "\n", "\t" 671 pkgs = db.Column(db.Text) 672 # built packages 673 built_packages = db.Column(db.Text) 674 # version of the srpm package got by rpm 675 pkg_version = db.Column(db.Text) 676 # was this build canceled by user? 677 canceled = db.Column(db.Boolean, default=False) 678 # list of space separated additional repos 679 repos = db.Column(db.Text) 680 # the three below represent time of important events for this build 681 # as returned by int(time.time()) 682 submitted_on = db.Column(db.Integer, nullable=False) 683 # directory name on backend with the srpm build results 684 result_dir = db.Column(db.Text, default='', server_default='', nullable=False) 685 # memory requirements for backend builder 686 memory_reqs = db.Column(db.Integer, default=constants.DEFAULT_BUILD_MEMORY) 687 # maximum allowed time of build, build will fail if exceeded 688 timeout = db.Column(db.Integer, default=constants.DEFAULT_BUILD_TIMEOUT) 689 # enable networking during a build process 690 enable_net = db.Column(db.Boolean, default=False, 691 server_default="0", nullable=False) 692 # Source of the build: type identifier 693 source_type = db.Column(db.Integer, default=helpers.BuildSourceEnum("unset")) 694 # Source of the build: description in json, example: git link, srpm url, etc. 695 source_json = db.Column(db.Text) 696 # Type of failure: type identifier 697 fail_type = db.Column(db.Integer, default=FailTypeEnum("unset")) 698 # background builds has lesser priority than regular builds. 699 is_background = db.Column(db.Boolean, default=False, server_default="0", nullable=False) 700 701 source_status = db.Column(db.Integer, default=StatusEnum("waiting")) 702 srpm_url = db.Column(db.Text) 703 704 # relations 705 user_id = db.Column(db.Integer, db.ForeignKey("user.id"), index=True) 706 user = db.relationship("User", backref=db.backref("builds")) 707 copr_id = db.Column(db.Integer, db.ForeignKey("copr.id"), index=True) 708 copr = db.relationship("Copr", backref=db.backref("builds")) 709 package_id = db.Column(db.Integer, db.ForeignKey("package.id"), index=True) 710 package = db.relationship("Package") 711 712 chroots = association_proxy("build_chroots", "mock_chroot") 713 714 batch_id = db.Column(db.Integer, db.ForeignKey("batch.id")) 715 batch = db.relationship("Batch", backref=db.backref("builds")) 716 717 module_id = db.Column(db.Integer, db.ForeignKey("module.id"), index=True) 718 module = db.relationship("Module", backref=db.backref("builds")) 719 720 copr_dir_id = db.Column(db.Integer, db.ForeignKey("copr_dir.id"), index=True) 721 copr_dir = db.relationship("CoprDir", backref=db.backref("builds")) 722 723 # scm integration properties 724 scm_object_id = db.Column(db.Text) 725 scm_object_type = db.Column(db.Text) 726 scm_object_url = db.Column(db.Text) 727 728 # method to call on build state change 729 update_callback = db.Column(db.Text) 730 731 @property
732 - def user_name(self):
733 return self.user.name
734 735 @property
736 - def group_name(self):
737 return self.copr.group.name
738 739 @property
740 - def copr_name(self):
741 return self.copr.name
742 743 @property
744 - def copr_dirname(self):
745 return self.copr_dir.name
746 747 @property
748 - def copr_full_dirname(self):
749 return self.copr_dir.full_name
750 751 @property
752 - def fail_type_text(self):
753 return FailTypeEnum(self.fail_type)
754 755 @property
756 - def repos_list(self):
757 if self.repos is None: 758 return list() 759 else: 760 return self.repos.split()
761 762 @property
763 - def task_id(self):
764 return str(self.id)
765 766 @property
767 - def id_fixed_width(self):
768 return "{:08d}".format(self.id)
769 770 @property
771 - def import_log_urls(self):
772 backend_log = self.import_log_url_backend 773 types = [helpers.BuildSourceEnum("upload"), helpers.BuildSourceEnum("link")] 774 return filter(None, [backend_log, self.import_log_url_distgit])
775 776 @property
777 - def import_log_url_distgit(self):
778 if app.config["COPR_DIST_GIT_LOGS_URL"]: 779 return "{}/{}.log".format(app.config["COPR_DIST_GIT_LOGS_URL"], 780 self.task_id.replace('/', '_')) 781 return None
782 783 @property
784 - def import_log_url_backend(self):
785 parts = ["results", self.copr.owner_name, self.copr_dirname, 786 "srpm-builds", self.id_fixed_width, "builder-live.log"] 787 path = os.path.normpath(os.path.join(*parts)) 788 return urljoin(app.config["BACKEND_BASE_URL"], path)
789 790 @property
791 - def source_json_dict(self):
792 if not self.source_json: 793 return {} 794 return json.loads(self.source_json)
795 796 @property
797 - def started_on(self):
798 return self.min_started_on
799 800 @property
801 - def min_started_on(self):
802 mb_list = [chroot.started_on for chroot in 803 self.build_chroots if chroot.started_on] 804 if len(mb_list) > 0: 805 return min(mb_list) 806 else: 807 return None
808 809 @property
810 - def ended_on(self):
811 return self.max_ended_on
812 813 @property
814 - def max_ended_on(self):
815 if not self.build_chroots: 816 return None 817 if any(chroot.ended_on is None for chroot in self.build_chroots): 818 return None 819 return max(chroot.ended_on for chroot in self.build_chroots)
820 821 @property
822 - def chroots_started_on(self):
823 return {chroot.name: chroot.started_on for chroot in self.build_chroots}
824 825 @property
826 - def chroots_ended_on(self):
827 return {chroot.name: chroot.ended_on for chroot in self.build_chroots}
828 829 @property
830 - def source_type_text(self):
832 833 @property
834 - def source_metadata(self):
835 if self.source_json is None: 836 return None 837 838 try: 839 return json.loads(self.source_json) 840 except (TypeError, ValueError): 841 return None
842 843 @property
844 - def chroot_states(self):
845 return map(lambda chroot: chroot.status, self.build_chroots)
846
847 - def get_chroots_by_status(self, statuses=None):
848 """ 849 Get build chroots with states which present in `states` list 850 If states == None, function returns build_chroots 851 """ 852 chroot_states_map = dict(zip(self.build_chroots, self.chroot_states)) 853 if statuses is not None: 854 statuses = set(statuses) 855 else: 856 return self.build_chroots 857 858 return [ 859 chroot for chroot, status in chroot_states_map.items() 860 if status in statuses 861 ]
862 863 @property
864 - def chroots_dict_by_name(self):
865 return {b.name: b for b in self.build_chroots}
866 867 @property
868 - def status(self):
869 """ 870 Return build status. 871 """ 872 if self.canceled: 873 return StatusEnum("canceled") 874 875 use_src_statuses = ["starting", "pending", "running"] 876 if self.source_status in [StatusEnum(s) for s in use_src_statuses]: 877 return self.source_status 878 879 for state in ["running", "starting", "pending", "failed", "succeeded", "skipped", "forked", "waiting"]: 880 if StatusEnum(state) in self.chroot_states: 881 if state == "waiting": 882 return self.source_status 883 else: 884 return StatusEnum(state) 885 886 return None
887 888 @property
889 - def state(self):
890 """ 891 Return text representation of status of this build. 892 """ 893 if self.status != None: 894 return StatusEnum(self.status) 895 return "unknown"
896 897 @property
898 - def cancelable(self):
899 """ 900 Find out if this build is cancelable. 901 """ 902 return not self.finished and self.status != StatusEnum("starting")
903 904 @property
905 - def repeatable(self):
906 """ 907 Find out if this build is repeatable. 908 909 Build is repeatable only if sources has been imported. 910 """ 911 return self.source_status == StatusEnum("succeeded")
912 913 @property
914 - def finished(self):
915 """ 916 Find out if this build is in finished state. 917 918 Build is finished only if all its build_chroots are in finished state or 919 the build was canceled. 920 """ 921 return self.canceled or all([chroot.finished for chroot in self.build_chroots])
922 923 @property
924 - def persistent(self):
925 """ 926 Find out if this build is persistent. 927 928 This property is inherited from the project. 929 """ 930 return self.copr.persistent
931 932 @property
933 - def package_name(self):
934 try: 935 return self.package.name 936 except: 937 return None
938
939 - def to_dict(self, options=None, with_chroot_states=False):
940 result = super(Build, self).to_dict(options) 941 result["src_pkg"] = result["pkgs"] 942 del result["pkgs"] 943 del result["copr_id"] 944 945 result['source_type'] = helpers.BuildSourceEnum(result['source_type']) 946 result["state"] = self.state 947 948 if with_chroot_states: 949 result["chroots"] = {b.name: b.state for b in self.build_chroots} 950 951 return result
952
953 954 -class DistGitBranch(db.Model, helpers.Serializer):
955 """ 956 1:N mapping: branch -> chroots 957 """ 958 959 # Name of the branch used on dist-git machine. 960 name = db.Column(db.String(50), primary_key=True)
961
962 963 -class MockChroot(db.Model, helpers.Serializer):
964 """ 965 Representation of mock chroot 966 """ 967 968 __table_args__ = ( 969 db.UniqueConstraint('os_release', 'os_version', 'arch', name='mock_chroot_uniq'), 970 ) 971 972 id = db.Column(db.Integer, primary_key=True) 973 # fedora/epel/..., mandatory 974 os_release = db.Column(db.String(50), nullable=False) 975 # 18/rawhide/..., optional (mock chroot doesn"t need to have this) 976 os_version = db.Column(db.String(50), nullable=False) 977 # x86_64/i686/..., mandatory 978 arch = db.Column(db.String(50), nullable=False) 979 is_active = db.Column(db.Boolean, default=True) 980 981 # Reference branch name 982 distgit_branch_name = db.Column(db.String(50), 983 db.ForeignKey("dist_git_branch.name"), 984 nullable=False) 985 986 distgit_branch = db.relationship("DistGitBranch", 987 backref=db.backref("chroots")) 988 989 @classmethod
990 - def latest_fedora_branched_chroot(cls, arch='x86_64'):
991 return (cls.query 992 .filter(cls.is_active == True) 993 .filter(cls.os_release == 'fedora') 994 .filter(cls.os_version != 'rawhide') 995 .filter(cls.arch == arch) 996 .order_by(cls.os_version.desc()) 997 .first())
998 999 @property
1000 - def name(self):
1001 """ 1002 Textual representation of name of this chroot 1003 """ 1004 return "{}-{}-{}".format(self.os_release, self.os_version, self.arch)
1005 1006 @property
1007 - def name_release(self):
1008 """ 1009 Textual representation of name of this or release 1010 """ 1011 return "{}-{}".format(self.os_release, self.os_version)
1012 1013 @property
1014 - def os(self):
1015 """ 1016 Textual representation of the operating system name 1017 """ 1018 return "{0} {1}".format(self.os_release, self.os_version)
1019 1020 @property
1021 - def serializable_attributes(self):
1022 attr_list = super(MockChroot, self).serializable_attributes 1023 attr_list.extend(["name", "os"]) 1024 return attr_list
1025
1026 1027 -class CoprChroot(db.Model, helpers.Serializer):
1028 """ 1029 Representation of Copr<->MockChroot relation 1030 """ 1031 1032 buildroot_pkgs = db.Column(db.Text) 1033 repos = db.Column(db.Text, default="", server_default="", nullable=False) 1034 mock_chroot_id = db.Column( 1035 db.Integer, db.ForeignKey("mock_chroot.id"), primary_key=True) 1036 mock_chroot = db.relationship( 1037 "MockChroot", backref=db.backref("copr_chroots")) 1038 copr_id = db.Column(db.Integer, db.ForeignKey("copr.id"), primary_key=True) 1039 copr = db.relationship("Copr", 1040 backref=db.backref( 1041 "copr_chroots", 1042 single_parent=True, 1043 cascade="all,delete,delete-orphan")) 1044 1045 comps_zlib = db.Column(db.LargeBinary(), nullable=True) 1046 comps_name = db.Column(db.String(127), nullable=True) 1047 1048 module_md_zlib = db.Column(db.LargeBinary(), nullable=True) 1049 module_md_name = db.Column(db.String(127), nullable=True) 1050 1051 with_opts = db.Column(db.Text, default="", server_default="", nullable=False) 1052 without_opts = db.Column(db.Text, default="", server_default="", nullable=False) 1053 1054 # Once mock_chroot gets EOL, copr_chroots are going to be deleted 1055 # if their owner doesn't extend their time span 1056 delete_after = db.Column(db.DateTime, index=True) 1057 delete_notify = db.Column(db.DateTime, index=True) 1058
1059 - def update_comps(self, comps_xml):
1060 if isinstance(comps_xml, str): 1061 data = comps_xml.encode("utf-8") 1062 else: 1063 data = comps_xml 1064 self.comps_zlib = zlib.compress(data)
1065
1066 - def update_module_md(self, module_md_yaml):
1067 if isinstance(module_md_yaml, str): 1068 data = module_md_yaml.encode("utf-8") 1069 else: 1070 data = module_md_yaml 1071 self.module_md_zlib = zlib.compress(data)
1072 1073 @property
1074 - def buildroot_pkgs_list(self):
1075 return (self.buildroot_pkgs or "").split()
1076 1077 @property
1078 - def repos_list(self):
1079 return (self.repos or "").split()
1080 1081 @property
1082 - def comps(self):
1083 if self.comps_zlib: 1084 return zlib.decompress(self.comps_zlib).decode("utf-8")
1085 1086 @property
1087 - def module_md(self):
1088 if self.module_md_zlib: 1089 return zlib.decompress(self.module_md_zlib).decode("utf-8")
1090 1091 @property
1092 - def comps_len(self):
1093 if self.comps_zlib: 1094 return len(zlib.decompress(self.comps_zlib)) 1095 else: 1096 return 0
1097 1098 @property
1099 - def module_md_len(self):
1100 if self.module_md_zlib: 1101 return len(zlib.decompress(self.module_md_zlib)) 1102 else: 1103 return 0
1104 1105 @property
1106 - def name(self):
1107 return self.mock_chroot.name
1108 1109 @property
1110 - def is_active(self):
1111 return self.mock_chroot.is_active
1112 1113 @property
1114 - def delete_after_days(self):
1115 if not self.delete_after: 1116 return None 1117 now = datetime.datetime.now() 1118 return (self.delete_after - now).days
1119
1120 - def to_dict(self):
1121 options = {"__columns_only__": [ 1122 "buildroot_pkgs", "repos", "comps_name", "copr_id", "with_opts", "without_opts" 1123 ]} 1124 d = super(CoprChroot, self).to_dict(options=options) 1125 d["mock_chroot"] = self.mock_chroot.name 1126 return d
1127
1128 1129 -class BuildChroot(db.Model, helpers.Serializer):
1130 """ 1131 Representation of Build<->MockChroot relation 1132 """ 1133 1134 __table_args__ = (db.Index('build_chroot_status_started_on_idx', "status", "started_on"),) 1135 1136 mock_chroot_id = db.Column(db.Integer, db.ForeignKey("mock_chroot.id"), 1137 primary_key=True) 1138 mock_chroot = db.relationship("MockChroot", backref=db.backref("builds")) 1139 build_id = db.Column(db.Integer, db.ForeignKey("build.id"), 1140 primary_key=True) 1141 build = db.relationship("Build", backref=db.backref("build_chroots")) 1142 git_hash = db.Column(db.String(40)) 1143 status = db.Column(db.Integer, default=StatusEnum("waiting")) 1144 1145 started_on = db.Column(db.Integer, index=True) 1146 ended_on = db.Column(db.Integer, index=True) 1147 1148 # directory name on backend with build results 1149 result_dir = db.Column(db.Text, default='', server_default='', nullable=False) 1150 1151 build_requires = db.Column(db.Text) 1152 1153 @property
1154 - def name(self):
1155 """ 1156 Textual representation of name of this chroot 1157 """ 1158 return self.mock_chroot.name
1159 1160 @property
1161 - def state(self):
1162 """ 1163 Return text representation of status of this build chroot 1164 """ 1165 if self.status is not None: 1166 return StatusEnum(self.status) 1167 return "unknown"
1168 1169 @property
1170 - def finished(self):
1171 return (self.state in ["succeeded", "forked", "canceled", "skipped", "failed"])
1172 1173 @property
1174 - def task_id(self):
1175 return "{}-{}".format(self.build_id, self.name)
1176 1177 @property
1178 - def dist_git_url(self):
1179 if app.config["DIST_GIT_URL"]: 1180 if self.state == "forked": 1181 copr_dirname = self.build.copr.forked_from.main_dir.full_name 1182 else: 1183 copr_dirname = self.build.copr_dir.full_name 1184 return "{}/{}/{}.git/commit/?id={}".format(app.config["DIST_GIT_URL"], 1185 copr_dirname, 1186 self.build.package.name, 1187 self.git_hash) 1188 return None
1189 1190 @property
1191 - def result_dir_url(self):
1192 return urljoin(app.config["BACKEND_BASE_URL"], os.path.join( 1193 "results", self.build.copr_dir.full_name, self.name, self.result_dir, ""))
1194
1195 1196 -class LegalFlag(db.Model, helpers.Serializer):
1197 id = db.Column(db.Integer, primary_key=True) 1198 # message from user who raised the flag (what he thinks is wrong) 1199 raise_message = db.Column(db.Text) 1200 # time of raising the flag as returned by int(time.time()) 1201 raised_on = db.Column(db.Integer) 1202 # time of resolving the flag by admin as returned by int(time.time()) 1203 resolved_on = db.Column(db.Integer) 1204 1205 # relations 1206 copr_id = db.Column(db.Integer, db.ForeignKey("copr.id"), nullable=True) 1207 # cascade="all" means that we want to keep these even if copr is deleted 1208 copr = db.relationship( 1209 "Copr", backref=db.backref("legal_flags", cascade="all")) 1210 # user who reported the problem 1211 reporter_id = db.Column(db.Integer, db.ForeignKey("user.id")) 1212 reporter = db.relationship("User", 1213 backref=db.backref("legal_flags_raised"), 1214 foreign_keys=[reporter_id], 1215 primaryjoin="LegalFlag.reporter_id==User.id") 1216 # admin who resolved the problem 1217 resolver_id = db.Column( 1218 db.Integer, db.ForeignKey("user.id"), nullable=True) 1219 resolver = db.relationship("User", 1220 backref=db.backref("legal_flags_resolved"), 1221 foreign_keys=[resolver_id], 1222 primaryjoin="LegalFlag.resolver_id==User.id")
1223
1224 1225 -class Action(db.Model, helpers.Serializer):
1226 """ 1227 Representation of a custom action that needs 1228 backends cooperation/admin attention/... 1229 """ 1230 1231 id = db.Column(db.Integer, primary_key=True) 1232 # see ActionTypeEnum 1233 action_type = db.Column(db.Integer, nullable=False) 1234 # copr, ...; downcase name of class of modified object 1235 object_type = db.Column(db.String(20)) 1236 # id of the modified object 1237 object_id = db.Column(db.Integer) 1238 # old and new values of the changed property 1239 old_value = db.Column(db.String(255)) 1240 new_value = db.Column(db.String(255)) 1241 # additional data 1242 data = db.Column(db.Text) 1243 # result of the action, see BackendResultEnum 1244 result = db.Column( 1245 db.Integer, default=BackendResultEnum("waiting")) 1246 # optional message from the backend/whatever 1247 message = db.Column(db.Text) 1248 # time created as returned by int(time.time()) 1249 created_on = db.Column(db.Integer) 1250 # time ended as returned by int(time.time()) 1251 ended_on = db.Column(db.Integer) 1252
1253 - def __str__(self):
1254 return self.__unicode__()
1255
1256 - def __unicode__(self):
1257 if self.action_type == ActionTypeEnum("delete"): 1258 return "Deleting {0} {1}".format(self.object_type, self.old_value) 1259 elif self.action_type == ActionTypeEnum("legal-flag"): 1260 return "Legal flag on copr {0}.".format(self.old_value) 1261 1262 return "Action {0} on {1}, old value: {2}, new value: {3}.".format( 1263 self.action_type, self.object_type, self.old_value, self.new_value)
1264
1265 - def to_dict(self, **kwargs):
1266 d = super(Action, self).to_dict() 1267 if d.get("object_type") == "module": 1268 module = Module.query.filter(Module.id == d["object_id"]).first() 1269 data = json.loads(d["data"]) 1270 data.update({ 1271 "projectname": module.copr.name, 1272 "ownername": module.copr.owner_name, 1273 "modulemd_b64": module.yaml_b64, 1274 }) 1275 d["data"] = json.dumps(data) 1276 return d
1277
1278 1279 -class Krb5Login(db.Model, helpers.Serializer):
1280 """ 1281 Represents additional user information for kerberos authentication. 1282 """ 1283 1284 __tablename__ = "krb5_login" 1285 1286 # FK to User table 1287 user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False) 1288 1289 # 'string' from 'copr.conf' from KRB5_LOGIN[string] 1290 config_name = db.Column(db.String(30), nullable=False, primary_key=True) 1291 1292 # krb's primary, i.e. 'username' from 'username@EXAMPLE.COM' 1293 primary = db.Column(db.String(80), nullable=False, primary_key=True) 1294 1295 user = db.relationship("User", backref=db.backref("krb5_logins"))
1296
1297 1298 -class CounterStat(db.Model, helpers.Serializer):
1299 """ 1300 Generic store for simple statistics. 1301 """ 1302 1303 name = db.Column(db.String(127), primary_key=True) 1304 counter_type = db.Column(db.String(30)) 1305 1306 counter = db.Column(db.Integer, default=0, server_default="0")
1307
1308 1309 -class Group(db.Model, helpers.Serializer):
1310 1311 """ 1312 Represents FAS groups and their aliases in Copr 1313 """ 1314 1315 id = db.Column(db.Integer, primary_key=True) 1316 name = db.Column(db.String(127)) 1317 1318 # TODO: add unique=True 1319 fas_name = db.Column(db.String(127)) 1320 1321 @property
1322 - def at_name(self):
1323 return u"@{}".format(self.name)
1324
1325 - def __str__(self):
1326 return self.__unicode__()
1327
1328 - def __unicode__(self):
1329 return "{} (fas: {})".format(self.name, self.fas_name)
1330
1331 1332 -class Batch(db.Model):
1333 id = db.Column(db.Integer, primary_key=True)
1334
1335 1336 -class Module(db.Model, helpers.Serializer):
1337 id = db.Column(db.Integer, primary_key=True) 1338 name = db.Column(db.String(100), nullable=False) 1339 stream = db.Column(db.String(100), nullable=False) 1340 version = db.Column(db.BigInteger, nullable=False) 1341 summary = db.Column(db.String(100), nullable=False) 1342 description = db.Column(db.Text) 1343 created_on = db.Column(db.Integer, nullable=True) 1344 1345 # When someone submits YAML (not generate one on the copr modules page), we might want to use that exact file. 1346 # Yaml produced by deconstructing into pieces and constructed back can look differently, 1347 # which is not desirable (Imo) 1348 # 1349 # Also if there are fields which are not covered by this model, we will be able to add them in the future 1350 # and fill them with data from this blob 1351 yaml_b64 = db.Column(db.Text) 1352 1353 # relations 1354 copr_id = db.Column(db.Integer, db.ForeignKey("copr.id")) 1355 copr = db.relationship("Copr", backref=db.backref("modules")) 1356 1357 __table_args__ = ( 1358 db.UniqueConstraint("copr_id", "name", "stream", "version", name="copr_name_stream_version_uniq"), 1359 ) 1360 1361 @property
1362 - def yaml(self):
1363 return base64.b64decode(self.yaml_b64)
1364 1365 @property
1366 - def modulemd(self):
1367 mmd = Modulemd.ModuleStream() 1368 mmd.import_from_string(self.yaml.decode("utf-8")) 1369 return mmd
1370 1371 @property
1372 - def nsv(self):
1373 return "-".join([self.name, self.stream, str(self.version)])
1374 1375 @property
1376 - def full_name(self):
1377 return "{}/{}".format(self.copr.full_name, self.nsv)
1378 1379 @property
1380 - def action(self):
1381 return Action.query.filter(Action.object_type == "module").filter(Action.object_id == self.id).first()
1382 1383 @property
1384 - def status(self):
1385 """ 1386 Return numeric representation of status of this build 1387 """ 1388 if any(b for b in self.builds if b.status == StatusEnum("failed")): 1389 return ModuleStatusEnum("failed") 1390 return self.action.result if self.action else ModuleStatusEnum("pending")
1391 1392 @property
1393 - def state(self):
1394 """ 1395 Return text representation of status of this build 1396 """ 1397 return ModuleStatusEnum(self.status)
1398 1399 @property
1400 - def rpm_filter(self):
1401 return self.modulemd.get_rpm_filter().get()
1402 1403 @property
1404 - def rpm_api(self):
1405 return self.modulemd.get_rpm_api().get()
1406 1407 @property
1408 - def profiles(self):
1409 return {k: v.get_rpms().get() for k, v in self.modulemd.get_profiles().items()}
1410
1411 1412 -class BuildsStatistics(db.Model):
1413 time = db.Column(db.Integer, primary_key=True) 1414 stat_type = db.Column(db.Text, primary_key=True) 1415 running = db.Column(db.Integer) 1416 pending = db.Column(db.Integer)
1417