-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathbase.py
More file actions
2123 lines (1799 loc) · 76.3 KB
/
base.py
File metadata and controls
2123 lines (1799 loc) · 76.3 KB
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
# base.py - the base classes etc. for a Python interface to bugzilla
#
# Copyright (C) 2007, 2008, 2009, 2010 Red Hat Inc.
# Author: Will Woods <[email protected]>
#
# This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import collections
import getpass
import locale
from logging import getLogger
import mimetypes
import os
import sys
import urllib.parse
from io import BytesIO
from ._authfiles import _BugzillaRCFile, _BugzillaTokenCache
from .apiversion import __version__
from ._backendrest import _BackendREST
from ._backendxmlrpc import _BackendXMLRPC
from .bug import Bug, Group, User
from .exceptions import BugzillaError
from ._rhconverters import _RHBugzillaConverters
from ._session import _BugzillaSession
from ._util import listify
log = getLogger(__name__)
def _nested_update(d, u):
# Helper for nested dict update()
for k, v in list(u.items()):
if isinstance(v, collections.abc.Mapping):
d[k] = _nested_update(d.get(k, {}), v)
else:
d[k] = v
return d
class _FieldAlias(object):
"""
Track API attribute names that differ from what we expose in users.
For example, originally 'short_desc' was the name of the property that
maps to 'summary' on modern bugzilla. We want pre-existing API users
to be able to continue to use Bug.short_desc, and
query({"short_desc": "foo"}). This class tracks that mapping.
@oldname: The old attribute name
@newname: The modern attribute name
@is_api: If True, use this mapping for values sent to the xmlrpc API
(like the query example)
@is_bug: If True, use this mapping for Bug attribute names.
"""
def __init__(self, newname, oldname, is_api=True, is_bug=True):
self.newname = newname
self.oldname = oldname
self.is_api = is_api
self.is_bug = is_bug
class _BugzillaAPICache(object):
"""
Helper class that holds cached API results for things like products,
components, etc.
"""
def __init__(self):
self.products = []
self.component_names = {}
self.bugfields = []
self.version_raw = None
self.version_parsed = (0, 0)
class Bugzilla(object):
"""
The main API object. Connects to a bugzilla instance over XMLRPC, and
provides wrapper functions to simplify dealing with API calls.
The most common invocation here will just be with just a URL:
bzapi = Bugzilla("http://bugzilla.example.com")
If you have previously logged into that URL, and have cached login
tokens, you will automatically be logged in. Otherwise to
log in, you can either pass auth options to __init__, or call a login
helper like interactive_login().
If you are not logged in, you won't be able to access restricted data like
user email, or perform write actions like bug create/update. But simple
querys will work correctly.
If you are unsure if you are logged in, you can check the .logged_in
property.
Another way to specify auth credentials is via a 'bugzillarc' file.
See readconfig() documentation for details.
"""
@staticmethod
def url_to_query(url):
"""
Given a big huge bugzilla query URL, returns a query dict that can
be passed along to the Bugzilla.query() method.
"""
q = {}
# pylint: disable=unpacking-non-sequence
(ignore1, ignore2, path,
ignore, query, ignore3) = urllib.parse.urlparse(url)
base = os.path.basename(path)
if base not in ('buglist.cgi', 'query.cgi'):
return {}
for (k, v) in urllib.parse.parse_qsl(query):
if k not in q:
q[k] = v
elif isinstance(q[k], list):
q[k].append(v)
else:
oldv = q[k]
q[k] = [oldv, v]
# Handle saved searches
if base == "buglist.cgi" and "namedcmd" in q and "sharer_id" in q:
q = {
"sharer_id": q["sharer_id"],
"savedsearch": q["namedcmd"],
}
return q
@staticmethod
def fix_url(url, force_rest=False):
"""
Turn passed url into a bugzilla XMLRPC web url
:param force_rest: If True, generate a REST API url
"""
(scheme, netloc, path,
params, query, fragment) = urllib.parse.urlparse(url)
if not scheme:
scheme = 'https'
if path and not netloc:
netloc = path.split("/", 1)[0]
path = "/".join(path.split("/")[1:]) or None
if not path:
path = 'xmlrpc.cgi'
if force_rest:
path = "rest/"
if not path.startswith("/"):
path = "/" + path
newurl = urllib.parse.urlunparse(
(scheme, netloc, path, params, query, fragment))
return newurl
@staticmethod
def get_rcfile_default_url():
"""
Helper to check all the default bugzillarc file paths for
a [DEFAULT] url=X section, and if found, return it.
"""
configpaths = _BugzillaRCFile.get_default_configpaths()
rcfile = _BugzillaRCFile()
rcfile.set_configpaths(configpaths)
return rcfile.get_default_url()
def __init__(self, url=-1, user=None, password=None, cookiefile=-1,
sslverify=True, tokenfile=-1, use_creds=True, api_key=None,
cert=None, configpaths=-1,
force_rest=False, force_xmlrpc=False, requests_session=None):
"""
:param url: The bugzilla instance URL, which we will connect
to immediately. Most users will want to specify this at
__init__ time, but you can defer connecting by passing
url=None and calling connect(URL) manually
:param user: optional username to connect with
:param password: optional password for the connecting user
:param cert: optional certificate file for client side certificate
authentication
:param cookiefile: Deprecated, raises an error if not -1 or None
:param sslverify: Set this to False to skip SSL hostname and CA
validation checks, like out of date certificate
:param tokenfile: Location to cache the API login token so youi
don't have to keep specifying username/password.
If -1, use the default path. If None, don't use
or save any tokenfile.
:param use_creds: If False, this disables tokenfile
and configpaths by default. This is a convenience option to
unset those values at init time. If those values are later
changed, they may be used for future operations.
:param sslverify: Maps to 'requests' sslverify parameter. Set to
False to disable SSL verification, but it can also be a path
to file or directory for custom certs.
:param api_key: A bugzilla5+ API key
:param configpaths: A list of possible bugzillarc locations.
:param force_rest: Force use of the REST API
:param force_xmlrpc: Force use of the XMLRPC API. If neither force_X
parameter are specified, heuristics will be used to determine
which API to use, with XMLRPC preferred for back compatability.
:param requests_session: An optional requests.Session object the
API will use to contact the remote bugzilla instance. This
way the API user can set up whatever auth bits they may need.
"""
if url == -1:
raise TypeError("Specify a valid bugzilla url, or pass url=None")
# Settings the user might want to tweak
self.user = user or ''
self.password = password or ''
self.api_key = api_key
self.cert = cert or None
self.url = ''
self._backend = None
self._session = None
self._user_requests_session = requests_session
self._sslverify = sslverify
self._cache = _BugzillaAPICache()
self._bug_autorefresh = False
self._is_redhat_bugzilla = False
self._rcfile = _BugzillaRCFile()
self._tokencache = _BugzillaTokenCache()
self._force_rest = force_rest
self._force_xmlrpc = force_xmlrpc
if cookiefile not in [None, -1]:
raise TypeError("cookiefile is deprecated, don't pass any value.")
if not use_creds:
tokenfile = None
configpaths = []
if tokenfile == -1:
tokenfile = self._tokencache.get_default_path()
if configpaths == -1:
configpaths = _BugzillaRCFile.get_default_configpaths()
self._settokenfile(tokenfile)
self._setconfigpath(configpaths)
if url:
self.connect(url)
def _detect_is_redhat_bugzilla(self):
if self._is_redhat_bugzilla:
return True
match = ".redhat.com"
if match in self.url:
log.info("Using RHBugzilla for URL containing %s", match)
return True
return False
def _init_class_from_url(self):
"""
Detect if we should use RHBugzilla class, and if so, set it
"""
from .oldclasses import RHBugzilla # pylint: disable=cyclic-import
if not self._detect_is_redhat_bugzilla():
return
self._is_redhat_bugzilla = True
if self.__class__ == Bugzilla:
# Overriding the class doesn't have any functional effect,
# but we continue to do it for API back compat incase anyone
# is doing any class comparison. We should drop this in the future
self.__class__ = RHBugzilla
def _get_field_aliases(self):
# List of field aliases. Maps old style RHBZ parameter
# names to actual upstream values. Used for createbug() and
# query include_fields at least.
ret = []
def _add(*args, **kwargs):
ret.append(_FieldAlias(*args, **kwargs))
def _add_both(newname, origname):
_add(newname, origname, is_api=False)
_add(origname, newname, is_bug=False)
_add('summary', 'short_desc')
_add('description', 'comment')
_add('platform', 'rep_platform')
_add('severity', 'bug_severity')
_add('status', 'bug_status')
_add('id', 'bug_id')
_add('blocks', 'blockedby')
_add('blocks', 'blocked')
_add('depends_on', 'dependson')
_add('creator', 'reporter')
_add('url', 'bug_file_loc')
_add('dupe_of', 'dupe_id')
_add('dupe_of', 'dup_id')
_add('comments', 'longdescs')
_add('creation_time', 'opendate')
_add('creation_time', 'creation_ts')
_add('whiteboard', 'status_whiteboard')
_add('last_change_time', 'delta_ts')
if self._is_redhat_bugzilla:
_add_both('fixed_in', 'cf_fixed_in')
_add_both('qa_whiteboard', 'cf_qa_whiteboard')
_add_both('devel_whiteboard', 'cf_devel_whiteboard')
_add_both('internal_whiteboard', 'cf_internal_whiteboard')
_add('component', 'components', is_bug=False)
_add('version', 'versions', is_bug=False)
# Yes, sub_components is the field name the API expects
_add('sub_components', 'sub_component', is_bug=False)
# flags format isn't exactly the same but it's the closest approx
_add('flags', 'flag_types')
return ret
def _get_user_agent(self):
return 'python-bugzilla/%s' % __version__
user_agent = property(_get_user_agent)
@property
def bz_ver_major(self):
return self._cache.version_parsed[0]
@property
def bz_ver_minor(self):
return self._cache.version_parsed[1]
###################
# Private helpers #
###################
def _get_version(self):
"""
Return version number as a float
"""
return float("%d.%d" % (self.bz_ver_major, self.bz_ver_minor))
def _get_bug_aliases(self):
return [(f.newname, f.oldname)
for f in self._get_field_aliases() if f.is_bug]
def _get_api_aliases(self):
return [(f.newname, f.oldname)
for f in self._get_field_aliases() if f.is_api]
#################
# Auth handling #
#################
def _getcookiefile(self):
return None
cookiefile = property(_getcookiefile)
def _gettokenfile(self):
return self._tokencache.get_filename()
def _settokenfile(self, filename):
self._tokencache.set_filename(filename)
def _deltokenfile(self):
self._settokenfile(None)
tokenfile = property(_gettokenfile, _settokenfile, _deltokenfile)
def _getconfigpath(self):
return self._rcfile.get_configpaths()
def _setconfigpath(self, configpaths):
return self._rcfile.set_configpaths(configpaths)
def _delconfigpath(self):
return self._rcfile.set_configpaths(None)
configpath = property(_getconfigpath, _setconfigpath, _delconfigpath)
#############################
# Login/connection handling #
#############################
def readconfig(self, configpath=None, overwrite=True):
"""
:param configpath: Optional bugzillarc path to read, instead of
the default list.
This function is called automatically from Bugzilla connect(), which
is called at __init__ if a URL is passed. Calling it manually is
just for passing in a non-standard configpath.
The locations for the bugzillarc file are preferred in this order:
~/.config/python-bugzilla/bugzillarc
~/.bugzillarc
/etc/bugzillarc
It has content like:
[bugzilla.yoursite.com]
user = username
password = password
Or
[bugzilla.yoursite.com]
api_key = key
The file can have multiple sections for different bugzilla instances.
A 'url' field in the [DEFAULT] section can be used to set a default
URL for the bugzilla command line tool.
Be sure to set appropriate permissions on bugzillarc if you choose to
store your password in it!
:param overwrite: If True, bugzillarc will clobber any already
set self.user/password/api_key/cert value.
"""
if configpath:
self._setconfigpath(configpath)
data = self._rcfile.parse(self.url)
for key, val in data.items():
if key == "api_key" and (overwrite or not self.api_key):
log.debug("bugzillarc: setting api_key")
self.api_key = val
elif key == "user" and (overwrite or not self.user):
log.debug("bugzillarc: setting user=%s", val)
self.user = val
elif key == "password" and (overwrite or not self.password):
log.debug("bugzillarc: setting password")
self.password = val
elif key == "cert" and (overwrite or not self.cert):
log.debug("bugzillarc: setting cert")
self.cert = val
else:
log.debug("bugzillarc: unknown key=%s", key)
def _set_bz_version(self, version):
self._cache.version_raw = version
try:
major, minor = [int(i) for i in version.split(".")[0:2]]
except Exception:
log.debug("version doesn't match expected format X.Y.Z, "
"assuming 5.0", exc_info=True)
major = 5
minor = 0
self._cache.version_parsed = (major, minor)
def _get_backend_class(self, url): # pragma: no cover
# This is a hook for the test suite to do some mock hackery
if self._force_rest and self._force_xmlrpc:
raise BugzillaError(
"Cannot specify both force_rest and force_xmlrpc")
xmlurl = self.fix_url(url)
if self._force_xmlrpc:
return _BackendXMLRPC, xmlurl
resturl = self.fix_url(url, force_rest=self._force_rest)
if self._force_rest:
return _BackendREST, resturl
# Simple heuristic if the original url has a path in it
if "/xmlrpc" in url:
return _BackendXMLRPC, xmlurl
if "/rest" in url:
return _BackendREST, resturl
# We were passed something like bugzilla.example.com but we
# aren't sure which method to use, try probing
if _BackendXMLRPC.probe(xmlurl):
return _BackendXMLRPC, xmlurl
if _BackendREST.probe(resturl):
return _BackendREST, resturl
# Otherwise fallback to XMLRPC default and let it fail
return _BackendXMLRPC, xmlurl
def connect(self, url=None):
"""
Connect to the bugzilla instance with the given url. This is
called by __init__ if a URL is passed. Or it can be called manually
at any time with a passed URL.
This will also read any available config files (see readconfig()),
which may set 'user' and 'password', and others.
If 'user' and 'password' are both set, we'll run login(). Otherwise
you'll have to login() yourself before some methods will work.
"""
if self._session:
self.disconnect()
url = url or self.url
backendclass, newurl = self._get_backend_class(url)
if url != newurl:
log.debug("Converted url=%s to fixed url=%s", url, newurl)
self.url = newurl
log.debug("Connecting with URL %s", self.url)
# we've changed URLs - reload config
self.readconfig(overwrite=False)
# Detect if connecting to redhat bugzilla
self._init_class_from_url()
self._session = _BugzillaSession(self.url, self.user_agent,
sslverify=self._sslverify,
cert=self.cert,
tokencache=self._tokencache,
api_key=self.api_key,
is_redhat_bugzilla=self._is_redhat_bugzilla,
requests_session=self._user_requests_session)
self._backend = backendclass(self.url, self._session)
if (self.user and self.password):
log.info("user and password present - doing login()")
self.login()
if self.api_key:
log.debug("using API key")
version = self._backend.bugzilla_version()["version"]
log.debug("Bugzilla version string: %s", version)
self._set_bz_version(version)
@property
def _proxy(self):
"""
Return an xmlrpc ServerProxy instance that will work seamlessly
with bugzilla
Some apps have historically accessed _proxy directly, like
fedora infrastrucutre pieces. So we consider it part of the API
"""
return self._backend.get_xmlrpc_proxy()
def is_xmlrpc(self):
"""
:returns: True if using the XMLRPC API
"""
return self._backend.is_xmlrpc()
def is_rest(self):
"""
:returns: True if using the REST API
"""
return self._backend.is_rest()
def get_requests_session(self):
"""
Give API users access to the Requests.session object we use for
talking to the remote bugzilla instance.
:returns: The Requests.session object backing the open connection.
"""
return self._session.get_requests_session()
def disconnect(self):
"""
Disconnect from the given bugzilla instance.
"""
self._backend = None
self._session = None
self._cache = _BugzillaAPICache()
def login(self, user=None, password=None, restrict_login=None):
"""
Attempt to log in using the given username and password. Subsequent
method calls will use this username and password. Returns False if
login fails, otherwise returns some kind of login info - typically
either a numeric userid, or a dict of user info.
If user is not set, the value of Bugzilla.user will be used. If *that*
is not set, ValueError will be raised. If login fails, BugzillaError
will be raised.
The login session can be restricted to current user IP address
with restrict_login argument. (Bugzilla 4.4+)
This method will be called implicitly at the end of connect() if user
and password are both set. So under most circumstances you won't need
to call this yourself.
"""
if self.api_key:
raise ValueError("cannot login when using an API key")
if user:
self.user = user
if password:
self.password = password
if not self.user:
raise ValueError("missing username")
if not self.password:
raise ValueError("missing password")
payload = {"login": self.user}
if restrict_login:
payload['restrict_login'] = True
log.debug("logging in with options %s", str(payload))
payload['password'] = self.password
try:
ret = self._backend.user_login(payload)
self.password = ''
log.info("login succeeded for user=%s", self.user)
if "token" in ret:
self._tokencache.set_value(self.url, ret["token"])
return ret
except Exception as e:
log.debug("Login exception: %s", str(e), exc_info=True)
raise BugzillaError("Login failed: %s" %
BugzillaError.get_bugzilla_error_string(e)) from None
def interactive_save_api_key(self):
"""
Helper method to interactively ask for an API key, verify it
is valid, and save it to a bugzillarc file referenced via
self.configpaths
"""
sys.stdout.write('API Key: ')
sys.stdout.flush()
api_key = sys.stdin.readline().strip()
self.disconnect()
self.api_key = api_key
log.info('Checking API key... ')
self.connect()
if not self.logged_in: # pragma: no cover
raise BugzillaError("Login with API_KEY failed")
log.info('API Key accepted')
wrote_filename = self._rcfile.save_api_key(self.url, self.api_key)
log.info("API key written to filename=%s", wrote_filename)
msg = "Login successful."
if wrote_filename:
msg += " API key written to %s" % wrote_filename
print(msg)
def interactive_login(self, user=None, password=None, force=False,
restrict_login=None):
"""
Helper method to handle login for this bugzilla instance.
:param user: bugzilla username. If not specified, prompt for it.
:param password: bugzilla password. If not specified, prompt for it.
:param force: Unused
:param restrict_login: restricts session to IP address
"""
ignore = force
log.debug('Calling interactive_login')
if not user:
sys.stdout.write('Bugzilla Username: ')
sys.stdout.flush()
user = sys.stdin.readline().strip()
if not password:
password = getpass.getpass('Bugzilla Password: ')
log.info('Logging in... ')
out = self.login(user, password, restrict_login)
msg = "Login successful."
if "token" not in out:
msg += " However no token was returned."
else:
if not self.tokenfile:
msg += " Token not saved to disk."
else:
msg += " Token cache saved to %s" % self.tokenfile
if self._get_version() >= 5.0:
msg += "\nToken usage is deprecated. "
msg += "Consider using bugzilla API keys instead. "
msg += "See `man bugzilla` for more details."
print(msg)
def logout(self):
"""
Log out of bugzilla. Drops server connection and user info, and
destroys authentication cache
"""
self._backend.user_logout()
self.disconnect()
self.user = ''
self.password = ''
@property
def logged_in(self):
"""
This is True if this instance is logged in else False.
We test if this session is authenticated by calling the User.get()
XMLRPC method with ids set. Logged-out users cannot pass the 'ids'
parameter and will result in a 505 error. If we tried to login with a
token, but the token was incorrect or expired, the server returns a
32000 error.
For Bugzilla 5 and later, a new method, User.valid_login is available
to test the validity of the token. However, this will require that the
username be cached along with the token in order to work effectively in
all scenarios and is not currently used. For more information, refer to
the following url.
http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login
"""
try:
self._backend.user_get({"ids": [1]})
return True
except Exception as e:
code = BugzillaError.get_bugzilla_error_code(e)
if code in [505, 32000]:
return False
raise e
######################
# Bugfields querying #
######################
def getbugfields(self, force_refresh=False, names=None):
"""
Calls getBugFields, which returns a list of fields in each bug
for this bugzilla instance. This can be used to set the list of attrs
on the Bug object.
:param force_refresh: If True, overwrite the bugfield cache
with these newly checked values.
:param names: Only check for the passed bug field names
"""
def _fieldnames():
data = {"include_fields": ["name"]}
if names:
data["names"] = names
r = self._backend.bug_fields(data)
return [f['name'] for f in r['fields']]
if force_refresh or not self._cache.bugfields:
log.debug("Refreshing bugfields")
self._cache.bugfields = _fieldnames()
self._cache.bugfields.sort()
log.debug("bugfields = %s", self._cache.bugfields)
return self._cache.bugfields
bugfields = property(fget=lambda self: self.getbugfields(),
fdel=lambda self: setattr(self, '_bugfields', None))
####################
# Product querying #
####################
def product_get(self, ids=None, names=None,
include_fields=None, exclude_fields=None,
ptype=None):
"""
Raw wrapper around Product.get
https://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#get-product
This does not perform any caching like other product API calls.
If ids, names, or ptype is not specified, we default to
ptype=accessible for historical reasons
@ids: List of product IDs to lookup
@names: List of product names to lookup
@ptype: Either 'accessible', 'selectable', or 'enterable'. If
specified, we return data for all those
@include_fields: Only include these fields in the output
@exclude_fields: Do not include these fields in the output
"""
if ids is None and names is None and ptype is None:
ptype = "accessible"
if ptype:
raw = None
if ptype == "accessible":
raw = self._backend.product_get_accessible()
elif ptype == "enterable":
raw = self._backend.product_get_enterable()
elif ptype == "selectable":
raw = self._backend.product_get_selectable()
if raw is None:
raise RuntimeError("Unknown ptype=%s" % ptype)
ids = raw['ids']
log.debug("For ptype=%s found ids=%s", ptype, ids)
kwargs = {}
if ids:
kwargs["ids"] = listify(ids)
if names:
kwargs["names"] = listify(names)
if include_fields:
kwargs["include_fields"] = include_fields
if exclude_fields:
kwargs["exclude_fields"] = exclude_fields
ret = self._backend.product_get(kwargs)
return ret['products']
def refresh_products(self, **kwargs):
"""
Refresh a product's cached info. Basically calls product_get
with the passed arguments, and tries to intelligently update
our product cache.
For example, if we already have cached info for product=foo,
and you pass in names=["bar", "baz"], the new cache will have
info for products foo, bar, baz. Individual product fields are
also updated.
"""
for product in self.product_get(**kwargs):
updated = False
for current in self._cache.products[:]:
if (current.get("id", -1) != product.get("id", -2) and
current.get("name", -1) != product.get("name", -2)):
continue
_nested_update(current, product)
updated = True
break
if not updated:
self._cache.products.append(product)
def getproducts(self, force_refresh=False, **kwargs):
"""
Query all products and return the raw dict info. Takes all the
same arguments as product_get.
On first invocation this will contact bugzilla and internally
cache the results. Subsequent getproducts calls or accesses to
self.products will return this cached data only.
:param force_refresh: force refreshing via refresh_products()
"""
if force_refresh or not self._cache.products:
self.refresh_products(**kwargs)
return self._cache.products
products = property(
fget=lambda self: self.getproducts(),
fdel=lambda self: setattr(self, '_products', None),
doc="Helper for accessing the products cache. If nothing "
"has been cached yet, this calls getproducts()")
#######################
# components querying #
#######################
def _lookup_product_in_cache(self, productname):
prodstr = isinstance(productname, str) and productname or None
prodint = isinstance(productname, int) and productname or None
for proddict in self._cache.products:
if prodstr == proddict.get("name", -1):
return proddict
if prodint == proddict.get("id", "nope"):
return proddict
return {}
def getcomponentsdetails(self, product, force_refresh=False):
"""
Wrapper around Product.get(include_fields=["components"]),
returning only the "components" data for the requested product,
slightly reworked to a dict mapping of components.name: components,
for historical reasons.
This uses the product cache, but will update it if the product
isn't found or "components" isn't cached for the product.
In cases like bugzilla.redhat.com where there are tons of
components for some products, this API will time out. You
should use product_get instead.
"""
proddict = self._lookup_product_in_cache(product)
if (force_refresh or not proddict or "components" not in proddict):
self.refresh_products(names=[product],
include_fields=["name", "id", "components"])
proddict = self._lookup_product_in_cache(product)
ret = {}
for compdict in proddict["components"]:
ret[compdict["name"]] = compdict
return ret
def getcomponentdetails(self, product, component, force_refresh=False):
"""
Helper for accessing a single component's info. This is a wrapper
around getcomponentsdetails, see that for explanation
"""
d = self.getcomponentsdetails(product, force_refresh)
return d[component]
def getcomponents(self, product, force_refresh=False):
"""
Return a list of component names for the passed product.
On first invocation the value is cached, and subsequent calls
will return the cached data.
:param force_refresh: Force refreshing the cache, and return
the new data
"""
proddict = self._lookup_product_in_cache(product)
product_id = proddict.get("id", None)
if (force_refresh or product_id is None or
"components" not in proddict):
self.refresh_products(
names=[product],
include_fields=["name", "id", "components.name"])
proddict = self._lookup_product_in_cache(product)
if "id" not in proddict:
raise BugzillaError("Product '%s' not found" % product)
product_id = proddict["id"]
if product_id not in self._cache.component_names:
names = []
for comp in proddict.get("components", []):
name = comp.get("name")
if name:
names.append(name)
self._cache.component_names[product_id] = names
return self._cache.component_names[product_id]
############################
# component adding/editing #
############################
def _component_data_convert(self, data, update=False):
# Back compat for the old RH interface
convert_fields = [
("initialowner", "default_assignee"),
("initialqacontact", "default_qa_contact"),
("initialcclist", "default_cc"),
]
for old, new in convert_fields:
if old in data:
data[new] = data.pop(old)
if update:
names = {"product": data.pop("product"),
"component": data.pop("component")}
updates = {}
for k in list(data.keys()):
updates[k] = data.pop(k)
data["names"] = [names]
data["updates"] = updates
def addcomponent(self, data):
"""
A method to create a component in Bugzilla. Takes a dict, with the
following elements:
product: The product to create the component in
component: The name of the component to create
description: A one sentence summary of the component
default_assignee: The bugzilla login (email address) of the initial
owner of the component
default_qa_contact (optional): The bugzilla login of the
initial QA contact
default_cc: (optional) The initial list of users to be CC'ed on
new bugs for the component.
is_active: (optional) If False, the component is hidden from
the component list when filing new bugs.
"""
data = data.copy()
self._component_data_convert(data)
return self._backend.component_create(data)
def editcomponent(self, data):
"""
A method to edit a component in Bugzilla. Takes a dict, with
mandatory elements of product. component, and initialowner.
All other elements are optional and use the same names as the
addcomponent() method.
"""
data = data.copy()
self._component_data_convert(data, update=True)
return self._backend.component_update(data)
###################
# getbug* methods #
###################