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