/
models.py
3002 lines (2513 loc) · 116 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright © 2011-2017 Red Hat, Inc. and others.
#
# This file is part of Bodhi.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from collections import defaultdict
from datetime import datetime
from textwrap import wrap
import copy
import hashlib
import json
import os
import re
import rpm
import time
import uuid
from pkgdb2client import PkgDB
from simplemediawiki import MediaWiki
from six.moves.urllib.parse import quote
from sqlalchemy import (and_, Boolean, Column, DateTime, ForeignKey, Integer, or_, Table, Unicode,
UnicodeText, UniqueConstraint)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import class_mapper, relationship, backref, validates
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.properties import RelationshipProperty
from sqlalchemy.sql import text
from sqlalchemy.types import SchemaType, TypeDecorator, Enum
from bodhi.server import bugs, buildsys, log, mail, notifications, Session
from bodhi.server.config import config
from bodhi.server.exceptions import BodhiException, LockedUpdateException
from bodhi.server.util import (
avatar as get_avatar, build_evr, flash_log, get_critpath_components,
get_nvr, get_rpm_header, header, packagename_from_nvr, tokenize, pagure_api_get)
import bodhi.server.util
# http://techspot.zzzeek.org/2011/01/14/the-enum-recipe
class EnumSymbol(object):
"""Define a fixed symbol tied to a parent class."""
def __init__(self, cls_, name, value, description):
self.cls_ = cls_
self.name = name
self.value = value
self.description = description
def __reduce__(self):
"""Allow unpickling to return the symbol
linked to the DeclEnum class."""
return getattr, (self.cls_, self.name)
def __iter__(self):
return iter([self.value, self.description])
def __repr__(self):
return "<%s>" % self.name
def __unicode__(self):
return unicode(self.value)
def __json__(self, request=None):
return self.value
class EnumMeta(type):
"""Generate new DeclEnum classes."""
def __init__(cls, classname, bases, dict_):
cls._reg = reg = cls._reg.copy()
for k, v in dict_.items():
if isinstance(v, tuple):
sym = reg[v[0]] = EnumSymbol(cls, k, *v)
setattr(cls, k, sym)
return type.__init__(cls, classname, bases, dict_)
def __iter__(cls):
return iter(cls._reg.values())
class DeclEnum(object):
"""Declarative enumeration."""
__metaclass__ = EnumMeta
_reg = {}
@classmethod
def from_string(cls, value):
try:
return cls._reg[value]
except KeyError:
raise ValueError("Invalid value for %r: %r" % (cls.__name__, value))
@classmethod
def values(cls):
return cls._reg.keys()
@classmethod
def db_type(cls):
return DeclEnumType(cls)
class DeclEnumType(SchemaType, TypeDecorator):
def __init__(self, enum):
self.enum = enum
self.impl = Enum(
*enum.values(),
name="ck%s" % re.sub('([A-Z])', lambda m: "_" + m.group(1).lower(), enum.__name__))
def _set_table(self, table, column):
self.impl._set_table(table, column)
def copy(self):
return DeclEnumType(self.enum)
def process_bind_param(self, value, dialect):
"""
:type value: bodhi.server.models.enum.EnumSymbol
:type dialect: sqlalchemy.engine.default.DefaultDialect
"""
if value is None:
return None
return value.value
def process_result_value(self, value, dialect):
if value is None:
return None
return self.enum.from_string(value.strip())
def create(self, bind=None, checkfirst=False):
"""Issue CREATE ddl for this type, if applicable."""
super(DeclEnumType, self).create(bind, checkfirst)
t = self.dialect_impl(bind.dialect)
if t.impl.__class__ is not self.__class__ and isinstance(t, SchemaType):
t.impl.create(bind=bind, checkfirst=checkfirst)
def drop(self, bind=None, checkfirst=False):
"""Issue DROP ddl for this type, if applicable."""
super(DeclEnumType, self).drop(bind, checkfirst)
t = self.dialect_impl(bind.dialect)
if t.impl.__class__ is not self.__class__ and isinstance(t, SchemaType):
t.impl.drop(bind=bind, checkfirst=checkfirst)
class BodhiBase(object):
"""
Base class for the SQLAlchemy model base class.
Attributes:
__exclude_columns__ (tuple): A list of columns to exclude from JSON
__include_extras__ (tuple): A list of methods or attrs to include in JSON
__get_by__ (tuple): A list of columns that :meth:`.get` will query.
id (int): An integer id that serves as the default primary key.
query (sqlalchemy.orm.query.Query): a class property which produces a
Query object against the class and the current Session when called.
"""
__exclude_columns__ = ('id',)
__include_extras__ = tuple()
__get_by__ = ()
id = Column(Integer, primary_key=True)
query = Session.query_property()
@classmethod
def get(cls, id, db):
return db.query(cls).filter(or_(
getattr(cls, col) == id for col in cls.__get_by__
)).first()
def __getitem__(self, key):
return getattr(self, key)
def __repr__(self):
return '<{0} {1}>'.format(self.__class__.__name__, self.__json__())
def __json__(self, request=None, anonymize=False):
return self._to_json(self, request=request, anonymize=anonymize)
@classmethod
def _to_json(cls, obj, seen=None, request=None, anonymize=False):
if not seen:
seen = []
if not obj:
return
exclude = getattr(obj, '__exclude_columns__', [])
properties = list(class_mapper(type(obj)).iterate_properties)
rels = [p.key for p in properties if type(p) is RelationshipProperty]
attrs = [p.key for p in properties if p.key not in rels]
d = dict([(attr, getattr(obj, attr)) for attr in attrs
if attr not in exclude and not attr.startswith('_')])
extras = getattr(obj, '__include_extras__', [])
for name in extras:
attribute = getattr(obj, name)
if callable(attribute):
attribute = attribute(request)
d[name] = attribute
for attr in rels:
if attr in exclude:
continue
target = getattr(type(obj), attr).property.mapper.class_
if target in seen:
continue
d[attr] = cls._expand(obj, getattr(obj, attr), seen, request)
for key, value in d.iteritems():
if isinstance(value, datetime):
d[key] = value.strftime('%Y-%m-%d %H:%M:%S')
if isinstance(value, EnumSymbol):
d[key] = unicode(value)
# If explicitly asked to, we will overwrite some fields if the
# corresponding condition of each evaluates to True.
# This is primarily for anonymous Comments. We want to serialize
# authenticated FAS usernames in the 'author' field, but we want to
# scrub out anonymous users' email addresses.
if anonymize:
for key1, key2 in getattr(obj, '__anonymity_map__', {}).items():
if getattr(obj, key2):
d[key1] = 'anonymous'
return d
@classmethod
def _expand(cls, obj, relation, seen, req):
""" Return the to_json or id of a sqlalchemy relationship. """
if hasattr(relation, 'all'):
relation = relation.all()
if hasattr(relation, '__iter__'):
return [cls._expand(obj, item, seen, req) for item in relation]
if type(relation) not in seen:
return cls._to_json(relation, seen + [type(obj)], req)
else:
return relation.id
@classmethod
def grid_columns(cls):
columns = []
exclude = getattr(cls, '__exclude_columns__', [])
for col in cls.__table__.columns:
if col.name in exclude:
continue
columns.append(col.name)
return columns
@classmethod
def find_polymorphic_child(cls, identity):
""" Find a child of a polymorphic base class.
For example, given the base Package class and the 'rpm' identity, this
class method should return the RpmPackage class.
This is accomplished by iterating over all classes in scope.
Limiting that to only those which are an extension of the given base
class. Among those, return the one whose polymorphic_identity matches
the value given. If none are found, then raise a NameError.
Arguments:
identity -- An instance of EnumSymbol used to identify the child.
"""
if not isinstance(identity, EnumSymbol):
raise TypeError("%r is not an instance of EnumSymbol" % identity)
if 'polymorphic_on' not in getattr(cls, '__mapper_args__', {}):
raise KeyError("%r is not a polymorphic model." % cls)
classes = (c for c in globals().values() if isinstance(c, type))
children = (c for c in classes if issubclass(c, cls))
for child in children:
candidate = child.__mapper_args__.get('polymorphic_identity')
if candidate is identity:
return child
error = "Found no child of %r with identity %r"
raise NameError(error % (cls, identity))
def update_relationship(self, name, model, data, db):
"""Add items to or remove items from a many-to-many relationship
:name: The name of the relationship column on self, as well as
the key in `data`
:model: The model class of the relationship that we're updating
:data: A dict containing the key `name` with a list of values
Returns a three-tuple of lists, `new`, `same`, and `removed` indicating
which items have been added and removed, and which remain unchanged.
"""
rel = getattr(self, name)
items = data.get(name)
new, same, removed = [], copy.copy(items), []
if items:
for item in items:
obj = model.get(item, db)
if not obj:
obj = model(name=item)
db.add(obj)
if obj not in rel:
rel.append(obj)
new.append(item)
same.remove(item)
for item in rel:
if item.name not in items:
log.info('Removing %r from %r', item, self)
rel.remove(item)
removed.append(item.name)
return new, same, removed
Base = declarative_base(cls=BodhiBase)
metadata = Base.metadata
##
# Enumerated type declarations
##
class ContentType(DeclEnum):
base = 'base', 'Base'
rpm = 'rpm', 'RPM'
module = 'module', 'Module'
@classmethod
def infer_content_class(cls, base, build):
""" Given a base class and a build from koji, identify and return the child
class associated with the appropriate ContentType.
For example, given the Package base class and a normal koji build, return
the RpmPackage model class. Or, given the Build base class and a container
build, return the ContainerBuild model class.
Arguments:
base -- A base model class.
build -- A dict of information from the build system (koji).
"""
# Default value. Overridden below if we find markers in the build info
identity = cls.rpm
extra = build.get('extra') or {}
if 'module' in extra.get('typeinfo', {}):
identity = cls.module
elif 'container_koji_task_id' in extra:
# TODO - implement containers as yet another content type someday.
raise NotImplementedError("Inferred type 'container' is unhandled.")
return base.find_polymorphic_child(identity)
class UpdateStatus(DeclEnum):
pending = 'pending', 'pending'
testing = 'testing', 'testing'
stable = 'stable', 'stable'
unpushed = 'unpushed', 'unpushed'
obsolete = 'obsolete', 'obsolete'
processing = 'processing', 'processing'
class TestGatingStatus(DeclEnum):
""" This class lists the different status the test_gating_status flag can have. """
# None: Updates created while bodhi has not enabled Greenwave integration
# waiting: Updates created while bodhi has enabled Greenwave integration
waiting = 'waiting', 'Waiting'
# ignored: a decision from Greenwave said that this update does not require any tests
ignored = 'ignored', 'Ignored'
# queued: a decision from Greenwave said that the required tests for this update have been
# queued
queued = 'queued', 'Queued'
# running: a decision from Greenwave said that the required tests for this update are running
running = 'running', 'Running'
# passed: a decision from Greenwave said that the required tests for this update have passed
passed = 'passed', 'Passed'
# failed: a decision from the Greenwave said that the required tests for this update have
# been failed
failed = 'failed', 'Failed'
class UpdateType(DeclEnum):
bugfix = 'bugfix', 'bugfix'
security = 'security', 'security'
newpackage = 'newpackage', 'newpackage'
enhancement = 'enhancement', 'enhancement'
class UpdateRequest(DeclEnum):
testing = 'testing', 'testing'
batched = 'batched', 'batched'
obsolete = 'obsolete', 'obsolete'
unpush = 'unpush', 'unpush'
revoke = 'revoke', 'revoke'
stable = 'stable', 'stable'
class UpdateSeverity(DeclEnum):
unspecified = 'unspecified', 'unspecified'
urgent = 'urgent', 'urgent'
high = 'high', 'high'
medium = 'medium', 'medium'
low = 'low', 'low'
class UpdateSuggestion(DeclEnum):
unspecified = 'unspecified', 'unspecified'
reboot = 'reboot', 'reboot'
logout = 'logout', 'logout'
class ReleaseState(DeclEnum):
disabled = 'disabled', 'disabled'
pending = 'pending', 'pending'
current = 'current', 'current'
archived = 'archived', 'archived'
##
# Association tables
##
update_bug_table = Table(
'update_bug_table', metadata,
Column('update_id', Integer, ForeignKey('updates.id')),
Column('bug_id', Integer, ForeignKey('bugs.id')))
update_cve_table = Table(
'update_cve_table', metadata,
Column('update_id', Integer, ForeignKey('updates.id')),
Column('cve_id', Integer, ForeignKey('cves.id')))
bug_cve_table = Table(
'bug_cve_table', metadata,
Column('bug_id', Integer, ForeignKey('bugs.id')),
Column('cve_id', Integer, ForeignKey('cves.id')))
user_package_table = Table(
'user_package_table', metadata,
Column('user_id', Integer, ForeignKey('users.id')),
Column('package_id', Integer, ForeignKey('packages.id')))
class Release(Base):
__tablename__ = 'releases'
__exclude_columns__ = ('id', 'builds')
__get_by__ = ('name', 'long_name', 'dist_tag')
name = Column(Unicode(10), unique=True, nullable=False)
long_name = Column(Unicode(25), unique=True, nullable=False)
version = Column(Unicode(5), nullable=False)
id_prefix = Column(Unicode(25), nullable=False)
branch = Column(Unicode(10), unique=True, nullable=False)
dist_tag = Column(Unicode(20), nullable=False)
stable_tag = Column(UnicodeText, nullable=False)
testing_tag = Column(UnicodeText, nullable=False)
candidate_tag = Column(UnicodeText, nullable=False)
pending_signing_tag = Column(UnicodeText, nullable=False)
pending_testing_tag = Column(UnicodeText, nullable=False)
pending_stable_tag = Column(UnicodeText, nullable=False)
override_tag = Column(UnicodeText, nullable=False)
state = Column(ReleaseState.db_type(), default=ReleaseState.disabled, nullable=False)
@property
def version_int(self):
regex = re.compile('\D+(\d+)$')
return int(regex.match(self.name).groups()[0])
@property
def mandatory_days_in_testing(self):
name = self.name.lower().replace('-', '')
status = config.get('%s.status' % name, None)
if status:
days = int(config.get(
'%s.%s.mandatory_days_in_testing' % (name, status)))
if days:
return days
days = int(config.get('%s.mandatory_days_in_testing' %
self.id_prefix.lower().replace('-', '_')))
if not days:
log.warn('No mandatory days in testing defined for %s' % self.name)
return days
@property
def collection_name(self):
""" Return the collection name of this release. (eg: Fedora EPEL) """
return ' '.join(self.long_name.split()[:-1])
@classmethod
def all_releases(cls, session):
if cls._all_releases:
return cls._all_releases
releases = defaultdict(list)
for release in session.query(cls).order_by(cls.name.desc()).all():
releases[release.state.value].append(release.__json__())
cls._all_releases = releases
return cls._all_releases
_all_releases = None
@classmethod
def get_tags(cls, session):
if cls._tag_cache:
return cls._tag_cache
data = {'candidate': [], 'testing': [], 'stable': [], 'override': [],
'pending_testing': [], 'pending_stable': []}
tags = {} # tag -> release lookup
for release in session.query(cls).all():
for key in data:
tag = getattr(release, '%s_tag' % key)
data[key].append(tag)
tags[tag] = release.name
cls._tag_cache = (data, tags)
return cls._tag_cache
_tag_cache = None
@classmethod
def from_tags(cls, tags, session):
tag_types, tag_rels = cls.get_tags(session)
for tag in tags:
release = session.query(cls).filter_by(name=tag_rels[tag]).first()
if release:
return release
class TestCase(Base):
"""Test cases from the wiki"""
__tablename__ = 'testcases'
__get_by__ = ('name',)
name = Column(UnicodeText, nullable=False)
package_id = Column(Integer, ForeignKey('packages.id'))
# package backref
class Package(Base):
"""
This model represents a package.
This model uses single-table inheritance to allow for different package types.
Attributes:
name (unicode): A unicode string that uniquely identifies the package.
requirements (unicode): A unicode string that lists space-separated taskotron test
results that must pass for this package
type (int): The polymorphic identity column. This is used to identify what Python
class to create when loading rows from the database.
builds (sqlalchemy.orm.collections.InstrumentedList): A list of :class:`Build` objects.
test_cases (sqlalchemy.orm.collections.InstrumentedList): A list of :class:`TestCase`
objects.
committers (sqlalchemy.orm.collections.InstrumentedList): A list of :class:`User` objects
who are committers.
stack_id (int): A foreign key to the :class:`Stack`
"""
__tablename__ = 'packages'
__get_by__ = ('name',)
__exclude_columns__ = ('id', 'committers', 'test_cases', 'builds',)
name = Column(UnicodeText, nullable=False)
requirements = Column(UnicodeText)
type = Column(ContentType.db_type(), nullable=False)
builds = relationship('Build', backref=backref('package', lazy='joined'))
test_cases = relationship('TestCase', backref='package', order_by="TestCase.id")
committers = relationship('User', secondary=user_package_table,
backref='packages')
stack_id = Column(Integer, ForeignKey('stacks.id'))
__mapper_args__ = {
'polymorphic_on': type,
'polymorphic_identity': ContentType.base,
}
__table_args__ = (
UniqueConstraint('name', 'type', name='packages_name_and_type_key'),
)
def get_pkg_pushers(self, branch, settings):
""" Pull users who can commit and are watching a package.
Return two two-tuples of lists:
* The first tuple is for usernames. The second tuple is for groups.
* The first list of the tuple is for committers. The second is for
watchers.
"""
watchers = []
committers = []
watchergroups = []
committergroups = []
pkgdb = PkgDB(settings.get('pkgdb_url'))
acls = pkgdb.get_package(self.name, branches=branch)
for package in acls['packages']:
for acl in package.get('acls', []):
if acl['status'] == 'Approved':
if acl['acl'] == 'watchcommits':
name = acl['fas_name']
if name.startswith('group::'):
watchergroups.append(name.split('::')[1])
else:
watchers.append(name)
elif acl['acl'] == 'commit':
name = acl['fas_name']
if name.startswith('group::'):
committergroups.append(name.split('::')[1])
else:
committers.append(name)
return (committers, watchers), (committergroups, watchergroups)
def get_pkg_committers_from_pagure(self):
"""
Pull users and groups who can commit on a package in Pagure.
Returns a tuple with two lists:
* The first list contains usernames that have commit access.
* The second list contains FAS group names that have commit access.
"""
pagure_url = config.get('pagure_url')
# Pagure uses plural names for its namespaces such as "rpms" except for
# container
if self.type.name == 'container':
namespace = self.type.name
else:
namespace = self.type.name + 's'
package_pagure_url = '{0}/api/0/{1}/{2}'.format(
pagure_url.rstrip('/'), namespace, self.name)
package_json = pagure_api_get(package_pagure_url)
committers = set()
for access_type in ['owner', 'admin', 'commit']:
committers = committers | set(
package_json['access_users'][access_type])
groups = set()
for access_type in ['admin', 'commit']:
for group_name in package_json['access_groups'][access_type]:
groups.add(group_name)
# The first list contains usernames with commit access. The second list
# contains FAS group names with commit access.
return list(committers), list(groups)
def fetch_test_cases(self, db):
""" Get a list of test cases from the wiki """
if not config.get('query_wiki_test_cases'):
return
start = datetime.utcnow()
log.debug('Querying the wiki for test cases')
wiki = MediaWiki(config.get('wiki_url'))
cat_page = 'Category:Package %s test cases' % self.name
def list_categorymembers(wiki, cat_page, limit=500):
# Build query arguments and call wiki
query = dict(action='query', list='categorymembers',
cmtitle=cat_page, cmlimit=limit)
response = wiki.call(query)
members = [entry['title'] for entry in
response.get('query', {}).get('categorymembers', {})
if 'title' in entry]
# Determine whether we need to recurse
idx = 0
while True:
if idx >= len(members) or limit <= 0:
break
# Recurse?
if members[idx].startswith('Category:') and limit > 0:
members.extend(list_categorymembers(wiki, members[idx], limit - 1))
members.remove(members[idx]) # remove Category from list
else:
idx += 1
log.debug('Found the following unit tests: %s', members)
return members
for test in set(list_categorymembers(wiki, cat_page)):
case = db.query(TestCase).filter_by(name=test).first()
if not case:
case = TestCase(name=test, package=self)
db.add(case)
db.flush()
log.debug('Finished querying for test cases in %s', datetime.utcnow() - start)
@validates('builds')
def validate_builds(self, key, build):
"""
Validates builds being appended to ensure they are all the same type as the Package.
This method checks to make sure that all the builds on self.builds have their type attribute
equal to self.type. The goal is to make sure that Builds of a specific type are only ever
associated with Packages of the same type and vice-versa. For example, RpmBuilds should only
ever associate with RpmPackages and never with ModulePackages.
Args:
key (str): The field's key, which is un-used in this validator.
build (Build): The build object which was appended to the list
of builds.
Raises:
ValueError: If the build being appended is not the same type as the package.
"""
if build.type != self.type:
raise ValueError(
(u"A {} Build cannot be associated with a {} Package. A Package's builds must be "
u"the same type as the package.").format(
build.type.description, self.type.description))
return build
def __str__(self):
x = header(self.name)
states = {'pending': [], 'testing': [], 'stable': []}
if len(self.builds):
for build in self.builds:
if build.update and build.update.status.description in states:
states[build.update.status.description].append(
build.update)
for state in states.keys():
if len(states[state]):
x += "\n %s Updates (%d)\n" % (state.title(),
len(states[state]))
for update in states[state]:
x += " o %s\n" % update.get_title()
del states
return x
class ModulePackage(Package):
"""Represents a Module package."""
__mapper_args__ = {
'polymorphic_identity': ContentType.module,
}
class RpmPackage(Package):
"""Represents a RPM package."""
__mapper_args__ = {
'polymorphic_identity': ContentType.rpm,
}
class Build(Base):
"""
This model represents a specific build of a package.
This model uses single-table inheritance to allow for different build types.
Attributes:
inherited (bool): The purpose of this column is unknown, and it appears to be unused. At the
time of this writing, there are 112,234 records with inherited set to False and 0 with
it set to True in the Fedora Bodhi deployment.
nvr (unicode): The nvr field is really a mapping to the Koji build_target.name field, and is
used to reference builds in Koji. It is named nvr in reference to the dash-separated
name-version-release Koji name for RPMs, but it is used by other types as well. At the
time of this writing, it was not practical to rename nvr since it is used in the REST
API to reference builds. Thus, it should be thought of as a Koji build identifier rather
than strictly as an RPM's name, version, and release.
package_id (int): A foreign key to the Package that this Build is part of.
release_id (int): A foreign key to the Release that this Build is part of.
signed (bool): If True, this package has been signed by robosignatory. If False, it has not
been signed yet.
update_id (int): A foreign key to the Update that this Build is part of.
release (sqlalchemy.orm.relationship): A relationship to the Release that this build is part
of.
type (int): The polymorphic identify of the row. This is used by sqlalchemy to identify
which subclass of Build to use.
"""
__tablename__ = 'builds'
__exclude_columns__ = ('id', 'package', 'package_id', 'release',
'release_id', 'update_id', 'update', 'override')
__get_by__ = ('nvr',)
nvr = Column(Unicode(100), unique=True, nullable=False)
package_id = Column(Integer, ForeignKey('packages.id'))
release_id = Column(Integer, ForeignKey('releases.id'))
signed = Column(Boolean, default=False, nullable=False)
update_id = Column(Integer, ForeignKey('updates.id'))
ci_url = Column(UnicodeText, default=None, nullable=True)
release = relationship('Release', backref='builds', lazy=False)
type = Column(ContentType.db_type(), nullable=False)
__mapper_args__ = {
'polymorphic_on': type,
'polymorphic_identity': ContentType.base,
}
def get_url(self):
"""
Return a the url to details about this build.
This method appears to be unused and incorrect.
Return:
str: A URL for this build.
"""
return '/' + self.nvr
def get_tags(self, koji=None):
"""
Return a list of koji tags for this build.
Args:
koji (bodhi.server.buildsys.Buildsysem or koji.ClientSession): A koji client. Defaults
to calling bodhi.server.buildsys.get_session().
Return:
list: A list of strings of the Koji tags on this Build.
"""
if not koji:
koji = buildsys.get_session()
return [tag['name'] for tag in koji.listTags(self.nvr)]
def untag(self, koji, db):
"""
Remove all known tags from this build.
Args:
koji (bodhi.server.buildsys.Buildsysem or koji.ClientSession): A koji client.
db (sqlalchemy.orm.session.Session): A database Session.
"""
tag_types, tag_rels = Release.get_tags(db)
for tag in self.get_tags():
if tag in tag_rels:
log.info('Removing %s tag from %s' % (tag, self.nvr))
koji.untagBuild(tag, self.nvr)
def unpush(self, koji):
"""
Move this build back to the candidate tag and remove any pending tags.
Args:
koji (bodhi.server.buildsys.Buildsysem or koji.ClientSession): A koji client.
"""
log.info('Unpushing %s' % self.nvr)
release = self.update.release
for tag in self.get_tags(koji):
if tag == release.pending_signing_tag:
log.info('Removing %s tag from %s' % (tag, self.nvr))
koji.untagBuild(tag, self.nvr)
if tag == release.pending_testing_tag:
log.info('Removing %s tag from %s' % (tag, self.nvr))
koji.untagBuild(tag, self.nvr)
if tag == release.pending_stable_tag:
log.info('Removing %s tag from %s' % (tag, self.nvr))
koji.untagBuild(tag, self.nvr)
elif tag == release.testing_tag:
log.info(
'Moving %s from %s to %s' % (
self.nvr, tag, release.candidate_tag))
koji.moveBuild(tag, release.candidate_tag, self.nvr)
class ModuleBuild(Build):
"""
Represents a Module build.
Note that this model uses single-table inheritance with its Build superclass.
Attributes:
nvr (unicode): A unique Koji identifier for the module build.
"""
__mapper_args__ = {
'polymorphic_identity': ContentType.module,
}
class RpmBuild(Build):
"""
Represents an RPM build.
Note that this model uses single-table inheritance with its Build superclass.
Attributes:
nvr (unicode): A dash (-) separated string of an RPM's name, version, and release (e.g.
u'bodhi-2.5.0-1.fc26')
epoch (int): The RPM's epoch.
"""
epoch = Column(Integer, default=0)
__mapper_args__ = {
'polymorphic_identity': ContentType.rpm,
}
@property
def evr(self):
"""
The RpmBuild's epoch, version, release, all basestrings in a 3-tuple.
Return:
tuple: (epoch, version, release)
"""
if self.epoch:
name, version, release = get_nvr(self.nvr)
return (str(self.epoch), version, release)
else:
koji_session = buildsys.get_session()
build = koji_session.getBuild(self.nvr)
evr = build_evr(build)
self.epoch = int(evr[0])
return evr
def get_latest(self):
"""
Return the nvr string of the most recent evr that is less than this RpmBuild's nvr. If there
is no other Build, this returns None.
Return:
basestring or None: An nvr string, formatted like RpmBuild.nvr. If there is no other
Build, returns None.
"""
koji_session = buildsys.get_session()
# Grab a list of builds tagged with ``Release.stable_tag`` release
# tags, and find the most recent update for this package, other than
# this one. If nothing is tagged for -updates, then grab the first
# thing in ``Release.dist_tag``. We aren't checking
# ``Release.candidate_tag`` first, because there could potentially be
# packages that never make their way over stable, so we don't want to
# generate ChangeLogs against those.
latest = None
evr = self.evr
for tag in [self.update.release.stable_tag, self.update.release.dist_tag]:
builds = koji_session.getLatestBuilds(
tag, package=self.package.name)
# Find the first build that is older than us
for build in builds:
new_evr = build_evr(build)
if rpm.labelCompare(evr, new_evr) < 0:
latest = build['nvr']
break
if latest:
break
return latest
def get_changelog(self, timelimit=0):
"""
Retrieve the RPM changelog of this package since it's last update, or since timelimit.
Args:
timelimit (int): Timestamp, specified as the number of seconds since 1970-01-01 00:00:00
UTC.
Return:
str: The RpmBuild's changelog.
"""
rpm_header = get_rpm_header(self.nvr)
descrip = rpm_header['changelogtext']
if not descrip:
return ""
who = rpm_header['changelogname']
when = rpm_header['changelogtime']
num = len(descrip)
if num == 1:
when = [when]
str = ""
i = 0
while (i < num) and (when[i] > timelimit):
str += '* %s %s\n%s\n' % (time.strftime("%a %b %e %Y",
time.localtime(when[i])), who[i],
descrip[i])
i += 1
return str
class Update(Base):
"""
This model represents an update.
Attributes:
title (unicode): The update's title which uniquely identifies the update.
This is generally an ordered list of the build NVRs contained in the
update.