forked from pycontribs/jira
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
4903 lines (4093 loc) · 180 KB
/
client.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
"""
This module implements a friendly (well, friendlier) interface between the raw JSON
responses from Jira and the Resource/dict abstractions provided by this library. Users
will construct a JIRA object as described below. Full API documentation can be found
at: https://jira.readthedocs.io/en/latest/
"""
import calendar
import copy
import datetime
import hashlib
import imghdr
import json
import logging as _logging
import mimetypes
import os
import re
import sys
import time
import urllib
import warnings
from collections import OrderedDict
from collections.abc import Iterable
from functools import lru_cache, wraps
from io import BufferedReader
from numbers import Number
from typing import (
Any,
Callable,
Dict,
Generic,
Iterator,
List,
Literal,
Optional,
Tuple,
Type,
TypeVar,
Union,
no_type_check,
overload,
)
from urllib.parse import parse_qs, quote, urlparse
import requests
from packaging.version import parse as parse_version
from requests import Response
from requests.auth import AuthBase
from requests.structures import CaseInsensitiveDict
from requests.utils import get_netrc_auth
from requests_toolbelt import MultipartEncoder
from jira import __version__
from jira.exceptions import JIRAError
from jira.resilientsession import PrepareRequestForRetry, ResilientSession
from jira.resources import (
AgileResource,
Attachment,
Board,
Comment,
Component,
Customer,
CustomFieldOption,
Dashboard,
Filter,
Group,
Issue,
IssueLink,
IssueLinkType,
IssueSecurityLevelScheme,
IssueType,
IssueTypeScheme,
NotificationScheme,
PermissionScheme,
Priority,
PriorityScheme,
Project,
RemoteLink,
RequestType,
Resolution,
Resource,
Role,
SecurityLevel,
ServiceDesk,
Sprint,
Status,
StatusCategory,
User,
Version,
Votes,
Watchers,
WorkflowScheme,
Worklog,
)
from jira.utils import json_loads, threaded_requests
try:
from requests_jwt import JWTAuth
except ImportError:
pass
try:
from typing import SupportsIndex # type:ignore[attr-defined] # Py38+
except ImportError:
from typing_extensions import SupportsIndex
LOG = _logging.getLogger("jira")
LOG.addHandler(_logging.NullHandler())
def translate_resource_args(func: Callable):
"""Decorator that converts Issue and Project resources to their keys when used as arguments."""
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
arg_list = []
for arg in args:
if isinstance(arg, (Issue, Project)):
arg_list.append(arg.key)
else:
arg_list.append(arg)
result = func(*arg_list, **kwargs)
return result
return wrapper
def _field_worker(
fields: Dict[str, Any] = None, **fieldargs: Any
) -> Union[Dict[str, Dict[str, Any]], Dict[str, Dict[str, str]]]:
if fields is not None:
return {"fields": fields}
return {"fields": fieldargs}
ResourceType = TypeVar("ResourceType", contravariant=True, bound=Resource)
class ResultList(list, Generic[ResourceType]):
def __init__(
self,
iterable: Iterable = None,
_startAt: int = 0,
_maxResults: int = 0,
_total: Optional[int] = None,
_isLast: Optional[bool] = None,
) -> None:
"""
Args:
iterable (Iterable): [description]. Defaults to None.
_startAt (int): Start page. Defaults to 0.
_maxResults (int): Max results per page. Defaults to 0.
_total (Optional[int]): Total results from query. Defaults to 0.
_isLast (Optional[bool]): Last Page? Defaults to None.
"""
if iterable is not None:
list.__init__(self, iterable)
else:
list.__init__(self)
self.startAt = _startAt
self.maxResults = _maxResults
# Optional parameters:
self.isLast = _isLast
self.total = _total if _total is not None else len(self)
self.iterable: List[ResourceType] = list(iterable) if iterable else []
self.current = self.startAt
def __next__(self) -> ResourceType: # type:ignore[misc]
self.current += 1
if self.current > self.total:
raise StopIteration
else:
return self.iterable[self.current - 1]
def __iter__(self) -> Iterator[ResourceType]:
return super().__iter__()
# fmt: off
# The mypy error we ignore is about returning a contravariant type.
# As this class is a List of a generic 'Resource' class
# this is the right way to specify that the output is the same as which
# the class was initialized with.
@overload
def __getitem__(self, i: SupportsIndex) -> ResourceType: ... # type:ignore[misc] # noqa: E704
@overload
def __getitem__(self, s: slice) -> List[ResourceType]: ... # type:ignore[misc] # noqa: E704
def __getitem__(self, slice_or_index): # noqa: E301,E261
return list.__getitem__(self, slice_or_index)
# fmt: on
class QshGenerator:
def __init__(self, context_path):
self.context_path = context_path
def __call__(self, req):
qsh = self._generate_qsh(req)
return hashlib.sha256(qsh.encode("utf-8")).hexdigest()
def _generate_qsh(self, req):
parse_result = urlparse(req.url)
path = (
parse_result.path[len(self.context_path) :]
if len(self.context_path) > 1
else parse_result.path
)
# create canonical query string according to docs at:
# https://developer.atlassian.com/cloud/jira/platform/understanding-jwt-for-connect-apps/#qsh
params = parse_qs(parse_result.query, keep_blank_values=True)
joined = {
key: ",".join(self._sort_and_quote_values(params[key])) for key in params
}
query = "&".join(f"{key}={joined[key]}" for key in sorted(joined.keys()))
qsh = f"{req.method.upper()}&{path}&{query}"
return qsh
def _sort_and_quote_values(self, values):
ordered_values = sorted(values)
return [quote(value, safe="~") for value in ordered_values]
class JiraCookieAuth(AuthBase):
"""Jira Cookie Authentication
Allows using cookie authentication as described by
https://developer.atlassian.com/server/jira/platform/cookie-based-authentication/
"""
def __init__(
self, session: ResilientSession, session_api_url: str, auth: Tuple[str, str]
):
"""Cookie Based Authentication
Args:
session (ResilientSession): The Session object to communicate with the API.
session_api_url (str): The session api url to use.
auth (Tuple[str, str]): The username, password tuple.
"""
self._session = session
self._session_api_url = session_api_url # e.g ."/rest/auth/1/session"
self.__auth = auth
self._retry_counter_401 = 0
self._max_allowed_401_retries = 1 # 401 aren't recoverable with retries really
@property
def cookies(self):
return self._session.cookies
def _increment_401_retry_counter(self):
self._retry_counter_401 += 1
def _reset_401_retry_counter(self):
self._retry_counter_401 = 0
def __call__(self, request: requests.PreparedRequest):
request.register_hook("response", self.handle_401)
return request
def init_session(self):
"""Initialise the Session object's cookies, so we can use the session cookie."""
username, password = self.__auth
authentication_data = {"username": username, "password": password}
r = self._session.post( # this also goes through the handle_401() hook
self._session_api_url, data=json.dumps(authentication_data)
)
r.raise_for_status()
def handle_401(self, response: requests.Response, **kwargs):
"""Refresh cookies if the session cookie has expired. Then retry the request."""
if (
response.status_code == 401
and self._retry_counter_401 < self._max_allowed_401_retries
):
LOG.info("Trying to refresh the cookie auth session...")
self._increment_401_retry_counter()
self.init_session()
response = self.process_original_request(response.request.copy())
self._reset_401_retry_counter()
return response
def process_original_request(self, original_request: requests.PreparedRequest):
self.update_cookies(original_request)
return self.send_request(original_request)
def update_cookies(self, original_request: requests.PreparedRequest):
# Cookie header needs first to be deleted for the header to be updated using
# the prepare_cookies method. See request.PrepareRequest.prepare_cookies
if "Cookie" in original_request.headers:
del original_request.headers["Cookie"]
original_request.prepare_cookies(self.cookies)
def send_request(self, request: requests.PreparedRequest):
return self._session.send(request)
class TokenAuth(AuthBase):
"""Bearer Token Authentication"""
def __init__(self, token: str):
# setup any auth-related data here
self._token = token
def __call__(self, r: requests.PreparedRequest):
# modify and return the request
r.headers["authorization"] = f"Bearer {self._token}"
return r
class JIRA:
"""User interface to Jira.
Clients interact with Jira by constructing an instance of this object and calling its methods. For addressable
resources in Jira -- those with "self" links -- an appropriate subclass of :py:class:`jira.resources.Resource` will be returned
with customized ``update()`` and ``delete()`` methods, along with attribute access to fields. This means that calls
of the form ``issue.fields.summary`` will be resolved into the proper lookups to return the JSON value at that
mapping. Methods that do not return resources will return a dict constructed from the JSON response or a scalar
value; see each method's documentation for details on what that method returns.
Without any arguments, this client will connect anonymously to the Jira instance
started by the Atlassian Plugin SDK from one of the 'atlas-run', ``atlas-debug``,
or ``atlas-run-standalone`` commands. By default, this instance runs at
``http://localhost:2990/jira``. The ``options`` argument can be used to set the Jira instance to use.
Authentication is handled with the ``basic_auth`` argument. If authentication is supplied (and is
accepted by Jira), the client will remember it for subsequent requests.
For quick command line access to a server, see the ``jirashell`` script included with this distribution.
The easiest way to instantiate is using ``j = JIRA("https://jira.atlassian.com")``
"""
DEFAULT_OPTIONS = {
"server": "http://localhost:2990/jira",
"auth_url": "/rest/auth/1/session",
"context_path": "/",
"rest_path": "api",
"rest_api_version": "2",
"agile_rest_path": AgileResource.AGILE_BASE_REST_PATH,
"agile_rest_api_version": "1.0",
"verify": True,
"resilient": True,
"async": False,
"async_workers": 5,
"client_cert": None,
"check_update": False,
# amount of seconds to wait for loading a resource after updating it
# used to avoid server side caching issues, used to be 4 seconds.
"delay_reload": 0,
"headers": {
"Cache-Control": "no-cache",
# 'Accept': 'application/json;charset=UTF-8', # default for REST
"Content-Type": "application/json", # ;charset=UTF-8',
# 'Accept': 'application/json', # default for REST
# 'Pragma': 'no-cache',
# 'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT'
"X-Atlassian-Token": "no-check",
},
"default_batch_size": {
Resource: 100,
},
}
checked_version = False
# TODO(ssbarnea): remove these two variables and use the ones defined in resources
JIRA_BASE_URL = Resource.JIRA_BASE_URL
AGILE_BASE_URL = AgileResource.AGILE_BASE_URL
def __init__(
self,
server: str = None,
options: Dict[str, Union[str, bool, Any]] = None,
basic_auth: Optional[Tuple[str, str]] = None,
token_auth: Optional[str] = None,
oauth: Dict[str, Any] = None,
jwt: Dict[str, Any] = None,
kerberos=False,
kerberos_options: Dict[str, Any] = None,
validate=False,
get_server_info: bool = True,
async_: bool = False,
async_workers: int = 5,
logging: bool = True,
max_retries: int = 3,
proxies: Any = None,
timeout: Optional[Union[Union[float, int], Tuple[float, float]]] = None,
auth: Tuple[str, str] = None,
default_batch_sizes: Optional[Dict[Type[Resource], Optional[int]]] = None,
):
"""Construct a Jira client instance.
Without any arguments, this client will connect anonymously to the Jira instance
started by the Atlassian Plugin SDK from one of the 'atlas-run', ``atlas-debug``,
or ``atlas-run-standalone`` commands. By default, this instance runs at
``http://localhost:2990/jira``. The ``options`` argument can be used to set the Jira instance to use.
Authentication is handled with the ``basic_auth`` or ``token_auth`` argument.
If authentication is supplied (and is accepted by Jira), the client will remember it for subsequent requests.
For quick command line access to a server, see the ``jirashell`` script included with this distribution.
The easiest way to instantiate is using ``j = JIRA("https://jira.atlasian.com")``
Args:
server (Optional[str]): The server address and context path to use. Defaults to ``http://localhost:2990/jira``.
options (Optional[Dict[str, Any]]): Specify the server and properties this client will use.
Use a dict with any of the following properties:
* server -- the server address and context path to use. Defaults to ``http://localhost:2990/jira``.
* rest_path -- the root REST path to use. Defaults to ``api``, where the Jira REST resources live.
* rest_api_version -- the version of the REST resources under rest_path to use. Defaults to ``2``.
* agile_rest_path - the REST path to use for Jira Agile requests. Defaults to ``agile``.
* verify (Union[bool, str]) -- Verify SSL certs. Defaults to ``True``.
Or path to to a CA_BUNDLE file or directory with certificates of trusted CAs,
for the `requests` library to use.
* client_cert (Union[str, Tuple[str,str]]) -- Path to file with both cert and key or
a tuple of (cert,key), for the `requests` library to use for client side SSL.
* check_update -- Check whether using the newest python-jira library version.
* headers -- a dict to update the default headers the session uses for all API requests.
basic_auth (Optional[Tuple[str, str]]): A tuple of username and password to use when
establishing a session via HTTP BASIC authentication.
token_auth (Optional[str]): A string containing the token necessary for (PAT) bearer token authorization.
oauth (Optional[Any]): A dict of properties for OAuth authentication. The following properties are required:
* access_token -- OAuth access token for the user
* access_token_secret -- OAuth access token secret to sign with the key
* consumer_key -- key of the OAuth application link defined in Jira
* key_cert -- private key file to sign requests with (should be the pair of the public key supplied to
Jira in the OAuth application link)
kerberos (bool): If true it will enable Kerberos authentication.
kerberos_options (Optional[Dict[str,str]]): A dict of properties for Kerberos authentication.
The following properties are possible:
* mutual_authentication -- string DISABLED or OPTIONAL.
Example kerberos_options structure: ``{'mutual_authentication': 'DISABLED'}``
jwt (Optional[Any]): A dict of properties for JWT authentication supported by Atlassian Connect.
The following properties are required:
* secret -- shared secret as delivered during 'installed' lifecycle event
(see https://developer.atlassian.com/static/connect/docs/latest/modules/lifecycle.html for details)
* payload -- dict of fields to be inserted in the JWT payload, e.g. 'iss'
Example jwt structure: ``{'secret': SHARED_SECRET, 'payload': {'iss': PLUGIN_KEY}}``
validate (bool): If true it will validate your credentials first. Remember that if you are accessing Jira
as anonymous it will fail to instantiate.
get_server_info (bool): If true it will fetch server version info first to determine if some API calls
are available.
async_ (bool): To enable async requests for those actions where we implemented it, like issue update() or delete().
async_workers (int): Set the number of worker threads for async operations.
timeout (Optional[Union[Union[float, int], Tuple[float, float]]]): Set a read/connect timeout for the underlying
calls to Jira (default: None).
Obviously this means that you cannot rely on the return code when this is enabled.
max_retries (int): Sets the amount Retries for the HTTP sessions initiated by the client. (Default: 3)
proxies (Optional[Any]): Sets the proxies for the HTTP session.
auth (Optional[Tuple[str,str]]): Set a cookie auth token if this is required.
logging (bool): Determine whether or not logging should be enabled. (Default: True)
default_batch_sizes (Optional[Dict[Type[Resource], Optional[int]]]): Manually specify the batch-sizes for
the paginated retrieval of different item types. `Resource` is used as a fallback for every item type not
specified. If an item type is mapped to `None` no fallback occurs, instead the JIRA-backend will use its
default batch-size. By default all Resources will be queried in batches of 100. E.g., setting this to
``{Issue: 500, Resource: None}`` will make :py:meth:`search_issues` query Issues in batches of 500, while
every other item type's batch-size will be controlled by the backend. (Default: None)
"""
# force a copy of the tuple to be used in __del__() because
# sys.version_info could have already been deleted in __del__()
self.sys_version_info = tuple(sys.version_info)
if options is None:
options = {}
if server and isinstance(server, dict):
warnings.warn(
"Old API usage, use JIRA(url) or JIRA(options={'server': url}, when using dictionary always use named parameters.",
DeprecationWarning,
)
options = server
server = ""
if server:
options["server"] = server
if async_:
options["async"] = async_
options["async_workers"] = async_workers
LOG.setLevel(_logging.INFO if logging else _logging.CRITICAL)
self.log = LOG
self._options: Dict[str, Any] = copy.deepcopy(JIRA.DEFAULT_OPTIONS)
if default_batch_sizes:
self._options["default_batch_size"].update(default_batch_sizes)
if "headers" in options:
headers = copy.copy(options["headers"])
del options["headers"]
else:
headers = {}
self._options.update(options)
self._options["headers"].update(headers)
self._rank = None
# Rip off trailing slash since all urls depend on that
assert isinstance(self._options["server"], str) # to help mypy
if self._options["server"].endswith("/"):
self._options["server"] = self._options["server"][:-1]
context_path = urlparse(self.server_url).path
if len(context_path) > 0:
self._options["context_path"] = context_path
self._try_magic()
assert isinstance(self._options["headers"], dict) # for mypy benefit
self._session: ResilientSession # for mypy benefit
if oauth:
self._create_oauth_session(oauth, timeout)
elif basic_auth:
self._create_http_basic_session(*basic_auth, timeout=timeout)
elif jwt:
self._create_jwt_session(jwt, timeout)
elif token_auth:
self._create_token_session(token_auth, timeout)
elif kerberos:
self._create_kerberos_session(timeout, kerberos_options=kerberos_options)
elif auth:
self._create_cookie_auth(auth, timeout)
# always log in for cookie based auth, as we need a first request to be logged in
validate = True
else:
self._session = ResilientSession(timeout=timeout)
# Add the client authentication certificate to the request if configured
self._add_client_cert_to_session()
# Add the SSL Cert to the request if configured
self._add_ssl_cert_verif_strategy_to_session()
self._session.headers.update(self._options["headers"])
if "cookies" in self._options:
self._session.cookies.update(self._options["cookies"])
self._session.max_retries = max_retries
if proxies:
self._session.proxies = proxies
self.auth = auth
if validate:
# This will raise an Exception if you are not allowed to login.
# It's better to fail faster than later.
user = self.session()
if user.raw is None:
auth_method = (
oauth or basic_auth or jwt or kerberos or auth or "anonymous"
)
raise JIRAError(f"Can not log in with {auth_method}")
self.deploymentType = None
if get_server_info:
# We need version in order to know what API calls are available or not
si = self.server_info()
try:
self._version = tuple(si["versionNumbers"])
except Exception as e:
self.log.error("invalid server_info: %s", si)
raise e
self.deploymentType = si.get("deploymentType")
else:
self._version = (0, 0, 0)
if self._options["check_update"] and not JIRA.checked_version:
self._check_update_()
JIRA.checked_version = True
self._fields_cache_value: Dict[str, str] = {} # access via self._fields_cache
@property
def _fields_cache(self) -> Dict[str, str]:
"""Cached dictionary of {Field Name: Field ID}. Lazy loaded."""
if not self._fields_cache_value:
self._update_fields_cache()
return self._fields_cache_value
def _update_fields_cache(self):
"""Update the cache used for `self._fields_cache`."""
self._fields_cache_value = {}
for f in self.fields():
if "clauseNames" in f:
for name in f["clauseNames"]:
self._fields_cache_value[name] = f["id"]
@property
def server_url(self) -> str:
"""Return the server url"""
return str(self._options["server"])
@property
def _is_cloud(self) -> bool:
"""Return whether we are on a Cloud based Jira instance."""
return self.deploymentType in ("Cloud",)
def _create_cookie_auth(
self,
auth: Tuple[str, str],
timeout: Optional[Union[Union[float, int], Tuple[float, float]]],
):
warnings.warn(
"Use OAuth or Token based authentication "
+ "instead of Cookie based Authentication.",
DeprecationWarning,
)
self._session = ResilientSession(timeout=timeout)
self._session.auth = JiraCookieAuth(
session=self._session,
session_api_url="{server}{auth_url}".format(**self._options),
auth=auth,
)
def _check_update_(self):
"""Check if the current version of the library is outdated."""
try:
data = requests.get(
"https://pypi.python.org/pypi/jira/json", timeout=2.001
).json()
released_version = data["info"]["version"]
if parse_version(released_version) > parse_version(__version__):
warnings.warn(
"You are running an outdated version of Jira Python %s. Current version is %s. Do not file any bugs against older versions."
% (__version__, released_version)
)
except requests.RequestException:
pass
except Exception as e:
self.log.warning(e)
def __del__(self):
"""Destructor for JIRA instance."""
self.close()
def close(self):
session = getattr(self, "_session", None)
if session is not None:
try:
session.close()
except TypeError:
# TypeError: "'NoneType' object is not callable"
# Could still happen here because other references are also
# in the process to be torn down, see warning section in
# https://docs.python.org/2/reference/datamodel.html#object.__del__
pass
self._session = None
def _check_for_html_error(self, content: str):
# Jira has the bad habit of returning errors in pages with 200 and
# embedding the error in a huge webpage.
if "<!-- SecurityTokenMissing -->" in content:
self.log.warning("Got SecurityTokenMissing")
raise JIRAError(f"SecurityTokenMissing: {content}")
return True
def _get_sprint_field_id(self):
sprint_field_name = "Sprint"
sprint_field_id = [
f["schema"]["customId"]
for f in self.fields()
if f["name"] == sprint_field_name
][0]
return sprint_field_id
def _fetch_pages(
self,
item_type: Type[ResourceType],
items_key: Optional[str],
request_path: str,
startAt: int = 0,
maxResults: int = 50,
params: Dict[str, Any] = None,
base: str = JIRA_BASE_URL,
) -> ResultList[ResourceType]:
"""Fetch from a paginated end point.
Args:
item_type (Type[Resource]): Type of single item. ResultList of such items will be returned.
items_key (Optional[str]): Path to the items in JSON returned from server.
Set it to None, if response is an array, and not a JSON object.
request_path (str): path in request URL
startAt (int): index of the first record to be fetched. (Default: 0)
maxResults (int): Maximum number of items to return.
If maxResults evaluates as False, it will try to get all items in batches. (Default:50)
params (Dict[str, Any]): Params to be used in all requests. Should not contain startAt and maxResults,
as they will be added for each request created from this function.
base (str): base URL to use for the requests.
Returns:
ResultList
"""
async_workers = None
async_class = None
if self._options["async"]:
try:
from requests_futures.sessions import FuturesSession
async_class = FuturesSession
except ImportError:
pass
async_workers = self._options.get("async_workers")
page_params = params.copy() if params else {}
if startAt:
page_params["startAt"] = startAt
if maxResults:
page_params["maxResults"] = maxResults
elif batch_size := self._get_batch_size(item_type):
page_params["maxResults"] = batch_size
resource = self._get_json(request_path, params=page_params, base=base)
next_items_page = self._get_items_from_page(item_type, items_key, resource)
items = next_items_page
if True: # isinstance(resource, dict):
if isinstance(resource, dict):
total = resource.get("total")
total = int(total) if total is not None else total
# 'isLast' is the optional key added to responses in Jira Agile 6.7.6. So far not used in basic Jira API.
is_last = resource.get("isLast", False)
start_at_from_response = resource.get("startAt", 0)
max_results_from_response = resource.get("maxResults", 1)
else:
# if is a list
total = 1
is_last = True
start_at_from_response = 0
max_results_from_response = 1
# If maxResults evaluates as False, get all items in batches
if not maxResults:
page_size = max_results_from_response or len(items)
if batch_size is not None and page_size < batch_size:
self.log.warning(
"'batch_size' set to %s, but only received %s items in batch. Falling back to %s.",
batch_size,
page_size,
page_size,
)
page_start = (startAt or start_at_from_response or 0) + page_size
if (
async_class is not None
and not is_last
and (total is not None and len(items) < total)
):
async_fetches = []
future_session = async_class(
session=self._session, max_workers=async_workers
)
for start_index in range(page_start, total, page_size):
page_params = params.copy() if params else {}
page_params["startAt"] = start_index
page_params["maxResults"] = page_size
url = self._get_url(request_path)
r = future_session.get(url, params=page_params)
async_fetches.append(r)
for future in async_fetches:
response = future.result()
resource = json_loads(response)
if resource:
next_items_page = self._get_items_from_page(
item_type, items_key, resource
)
items.extend(next_items_page)
while (
async_class is None
and not is_last
and (total is None or page_start < total)
and len(next_items_page) == page_size
):
page_params = (
params.copy() if params else {}
) # Hack necessary for mock-calls to not change
page_params["startAt"] = page_start
page_params["maxResults"] = page_size
resource = self._get_json(
request_path, params=page_params, base=base
)
if resource:
next_items_page = self._get_items_from_page(
item_type, items_key, resource
)
items.extend(next_items_page)
page_start += page_size
else:
# if resource is an empty dictionary we assume no-results
break
return ResultList(
items, start_at_from_response, max_results_from_response, total, is_last
)
else: # TODO: unreachable
# it seems that search_users can return a list() containing a single user!
return ResultList(
[item_type(self._options, self._session, resource)], 0, 1, 1, True
)
def _get_items_from_page(
self,
item_type: Type[ResourceType],
items_key: Optional[str],
resource: Dict[str, Any],
) -> List[ResourceType]:
try:
return [
# We need to ignore the type here, as 'Resource' is an option
item_type(self._options, self._session, raw_issue_json) # type: ignore
for raw_issue_json in (resource[items_key] if items_key else resource)
]
except KeyError as e:
# improving the error text so we know why it happened
raise KeyError(str(e) + " : " + json.dumps(resource))
def _get_batch_size(self, item_type: Type[ResourceType]) -> Optional[int]:
"""
Return the batch size for the given resource type from the options.
Check if specified item-type has a mapped batch-size, else try to fallback to batch-size assigned to `Resource`, else fallback to Backend-determined batch-size.
Returns:
Optional[int]: The batch size to use. When the configured batch size is None, the batch size should be determined by the JIRA-Backend.
"""
batch_sizes: Dict[Type[Resource], Optional[int]] = self._options[
"default_batch_size"
]
try:
item_type_batch_size = batch_sizes[item_type]
except KeyError:
# Cannot find Resource-key -> Fallback to letting JIRA-Backend determine batch-size (=None)
item_type_batch_size = batch_sizes.get(Resource, None)
return item_type_batch_size
# Information about this client
def client_info(self) -> str:
"""Get the server this client is connected to."""
return self.server_url
# Universal resource loading
def find(
self, resource_format: str, ids: Union[Tuple[str, str], int, str] = ""
) -> Resource:
"""Find Resource object for any addressable resource on the server.
This method is a universal resource locator for any REST-ful resource in Jira. The
argument ``resource_format`` is a string of the form ``resource``, ``resource/{0}``,
``resource/{0}/sub``, ``resource/{0}/sub/{1}``, etc. The format placeholders will be
populated from the ``ids`` argument if present. The existing authentication session
will be used.
The return value is an untyped Resource object, which will not support specialized
:py:meth:`.Resource.update` or :py:meth:`.Resource.delete` behavior. Moreover, it will
not know to return an issue Resource if the client uses the resource issue path. For this
reason, it is intended to support resources that are not included in the standard
Atlassian REST API.
Args:
resource_format (str): the subpath to the resource string
ids (Optional[Tuple]): values to substitute in the ``resource_format`` string
Returns:
Resource
"""
resource = Resource(resource_format, self._options, self._session)
resource.find(ids)
return resource
@no_type_check # FIXME: This function fails type checking, probably a bug or two
def async_do(self, size: int = 10):
"""Execute all asynchronous jobs and wait for them to finish. By default it will run on 10 threads.
Args:
size (int): number of threads to run on.
"""
if hasattr(self._session, "_async_jobs"):
self.log.info(
"Executing asynchronous %s jobs found in queue by using %s threads..."
% (len(self._session._async_jobs), size)
)
threaded_requests.map(self._session._async_jobs, size=size)
# Application properties
# non-resource
def application_properties(
self, key: str = None
) -> Union[Dict[str, str], List[Dict[str, str]]]:
"""Return the mutable server application properties.
Args:
key (Optional[str]): the single property to return a value for
Returns:
Union[Dict[str, str], List[Dict[str, str]]]
"""
params = {}
if key is not None:
params["key"] = key
return self._get_json("application-properties", params=params)
def set_application_property(self, key: str, value: str):
"""Set the application property.
Args:
key (str): key of the property to set
value (str): value to assign to the property
"""
url = self._get_latest_url("application-properties/" + key)
payload = {"id": key, "value": value}
return self._session.put(url, data=json.dumps(payload))
def applicationlinks(self, cached: bool = True) -> List:
"""List of application links.
Returns:
List[Dict]: json, or empty list
"""
self._applicationlinks: List[Dict] # for mypy benefit
# if cached, return the last result
if cached and hasattr(self, "_applicationlinks"):
return self._applicationlinks
# url = self._options['server'] + '/rest/applinks/latest/applicationlink'
url = self.server_url + "/rest/applinks/latest/listApplicationlinks"
r = self._session.get(url)
o = json_loads(r)
if "list" in o and isinstance(o, dict):
self._applicationlinks = o["list"]
else:
self._applicationlinks = []
return self._applicationlinks
# Attachments
def attachment(self, id: str) -> Attachment:
"""Get an attachment Resource from the server for the specified ID.
Args:
id (str): The Attachment ID
Returns:
Attachment
"""
return self._find_for_resource(Attachment, id)
# non-resource
def attachment_meta(self) -> Dict[str, int]:
"""Get the attachment metadata.
Return:
Dict[str, int]
"""
return self._get_json("attachment/meta")
@translate_resource_args
def add_attachment(
self, issue: str, attachment: Union[str, BufferedReader], filename: str = None
) -> Attachment:
"""Attach an attachment to an issue and returns a Resource for it.
The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready
for its use. The user is still responsible for tidying up (e.g., closing the file, killing the socket, etc.)
Args:
issue (str): the issue to attach the attachment to
attachment (Union[str,BufferedReader]): file-like object to attach to the issue, also works if it is a string with the filename.
filename (str): optional name for the attached file. If omitted, the file object's ``name`` attribute
is used. If you acquired the file-like object by any other method than ``open()``, make sure
that a name is specified in one way or the other.
Returns:
Attachment
"""
close_attachment = False
if isinstance(attachment, str):
attachment_io = open(attachment, "rb") # type: ignore
close_attachment = True
else:
attachment_io = attachment