-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathrestapi.py
More file actions
1780 lines (1555 loc) · 85 KB
/
restapi.py
File metadata and controls
1780 lines (1555 loc) · 85 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
###################################################################################################
#
# pyral.restapi - Python Rally REST API module
# round 20 support Python 3.12, 2.13 and 3.14
# notable dependency:
# requests v2.32.x or better
#
###################################################################################################
__version__ = (1, 7, 0)
import sys, os
import re
import json
import string
import base64
from operator import itemgetter
from urllib.parse import quote
from urllib.parse import unquote
import requests
# intra-package imports
from .config import PROTOCOL, SERVER, WS_API_VERSION, WEB_SERVICE, SCHEMA_SERVICE, AUTH_ENDPOINT
from .config import RALLY_REST_HEADERS
from .config import DEFAULT_SESSION_TIMEOUT
from .config import USER_NAME, PASSWORD
from .config import START_INDEX, KILO_PAGESIZE, MAX_PAGESIZE, MAX_ITEMS
from .config import timestamp
from .proj_utils import projectAncestors, projectDescendants, projeny, flatten
from .multiop import createMultiple as multiop_createMultiple
from .multiop import updateMultiple as multiop_updateMultiple
###################################################################################################
#
# define a module global that should be set up/known before a few more module imports
#
_rallyCache = {} # keyed by a context tuple (server, user, password, workspace, project)
# value is a dict with at least:
# a key of 'rally' whose value there is a Rally instance and
# a key of 'hydrator' whose value there is an EntityHydrator instance
def warning(message):
sys.stderr.write("WARNING: %s\n" % message)
SERVICE_REQUEST_TIMEOUT = 120
HTTP_REQUEST_SUCCESS_CODE = 200
PAGE_NOT_FOUND_CODE = 404
PROJECT_PATH_ELEMENT_SEPARATOR = ' // '
INTEGRATION_HEADER_PREFIX = 'X-RallyIntegration'
###################################################################################################
class RallyRESTAPIError(Exception): pass
class RallyAttributeNameError(Exception): pass
#
# define a couple of entry point functions for use by other pkg modules and import the modules
#
def hydrateAnInstance(context, item, existingInstance=None):
global _rallyCache
rallyContext = _rallyCache.get(context, None)
if not rallyContext:
# throwing an Exception is probably the correct thing to do
return None
hydrator = rallyContext.get('hydrator', None)
if not hydrator:
hydrator = EntityHydrator(context, hydration="full")
rallyContext['hydrator'] = hydrator
return hydrator.hydrateInstance(item, existingInstance=existingInstance)
def getResourceByOID(context, entity, oid, **kwargs):
"""
Retrieves a reference in _rallyCache to a Rally instance and uses that to
call its internal _getResourceByOID method
Returns a RallyRESTResponse instance
that has status_code, headers and content attributes.
"""
##
## print("getResourceByOID called:")
## print(" context: %s" % context)
## print(" entity: %s" % entity)
## print(" oid: %s" % oid)
## print(" kwargs: %s" % kwargs)
## sys.stdout.flush()
##
## if entity == 'context':
## raise Exception("getResourceByOID called to get resource for entity of 'context'")
##
global _rallyCache
rallyContext = _rallyCache.get(context, None)
if not rallyContext:
# raising an Exception is the only thing we can do, don't see any prospect of recovery...
raise RallyRESTAPIError('Unable to find Rally instance for context: %s' % context)
##
## print("_rallyCache.keys:")
## for key in _rallyCache.keys():
## print(" -->%s<--" % key)
## print("")
## print(" apparently no key to match: -->%s<--" % context)
## print(" context is a %s" % type(context))
##
rally = rallyContext.get('rally')
resp = rally._getResourceByOID(context, entity, oid, **kwargs)
if 'unwrap' not in kwargs or not kwargs.get('unwrap', False):
return resp
response = RallyRESTResponse(rally.session, context, f"{entity}.x", resp, "full", 1)
return response
def getCollection(context, collection_url, **kwargs):
"""
Retrieves a reference in _rallyCache to a Rally instance and uses that to
call its getCollection method.
Returns a RallyRESTResponse instance that has status_code, headers and content attributes.
"""
global _rallyCache
rallyContext = _rallyCache.get(context, None)
if not rallyContext:
ck_matches = [rck for rck in list(_rallyCache.keys()) if rck.identity() == context.identity()]
if ck_matches:
rck = ck_matches.pop()
rallyContext = _rallyCache[rck]
else:
# raising an Exception is the only thing we can do, don't see any prospect of recovery...
raise RallyRESTAPIError(f'Unable to find Rally instance for context: {context}')
rally = rallyContext.get('rally')
response = rally.getCollection(collection_url, **kwargs)
return response
# these imports have to take place after the prior class and function defs
from .rallyresp import RallyRESTResponse, RallyResponseError, ErrorResponse
from .hydrate import EntityHydrator
from .context import RallyContext, RallyContextHelper
from .entity import validRallyType, DomainObject
from .query_builder import RallyUrlBuilder
__all__ = ["Rally", "getResourceByOID", "getCollection", "hydrateAnInstance", "RallyUrlBuilder"]
def _createShellInstance(context, entity_name, item_name, item_ref):
oid = item_ref.split('/').pop()
item = {
'ObjectID' : oid,
'Name' : item_name,
'_type' : entity_name,
'_ref' : item_ref,
'ref' : f'{entity_name.lower()}/{oid}'
}
hydrator = EntityHydrator(context, hydration="shell")
return hydrator.hydrateInstance(item)
##################################################################################################
class Rally:
"""
An instance of this class provides the instance holder the ability to
interact with Rally via the Rally REST WSAPI.
The holder can create, query (read), update and delete Rally entities
(but only selected appropriate entities).
In addition, there are several convenience methods (for users, workspaces and projects)
that allow the holder to quickly get a picture of their Rally operating environment.
"""
ARTIFACT_TYPE = { 'S' : 'Story',
'US' : 'Story',
'DE' : 'Defect',
'DS' : 'DefectSuite',
'TA' : 'Task',
'TC' : 'TestCase',
'TS' : 'TestSet',
'PI' : 'PortfolioItem'
}
FORMATTED_ID_PATTERN = re.compile(r'^[A-Z]{1,2}\d+$') #S|US|DE|DS|TA|TC|TS|PI
MAX_ATTACHMENT_SIZE = 50000000 # approx 50 MB
def __init__(self, server=SERVER, user=None, password=None, apikey=None,
version=WS_API_VERSION, warn=True, server_ping=None,
isolated_workspace=False, **kwargs):
self.server = server
self.user = user or USER_NAME
self.password = password or PASSWORD
self.apikey = apikey
self.version = WS_API_VERSION # we only support v2.0 now
self._inflated = False
self.service_url = f'{PROTOCOL}://{self.server}/{WEB_SERVICE}/{self.version}'
self.schema_url = f'{PROTOCOL}://{self.server}/{SCHEMA_SERVICE}/{self.version}'
self.hydration = "full"
self._sec_token = None
self._log = False
self._logDest = None
self._logAttrGet = False
self._warn = warn
self.isolated_workspace = isolated_workspace
config = {}
if kwargs and 'debug' in kwargs and kwargs.get('debug', False):
config['verbose'] = sys.stdout
proxy_dict = {}
https_proxy = os.environ.get('HTTPS_PROXY', None) or os.environ.get('https_proxy', None)
if https_proxy and https_proxy not in ["", None]:
if not https_proxy.startswith('http'):
https_proxy = f"http://{https_proxy}" # prepend the standard http scheme on the front-end
os.environ['https_proxy'] = https_proxy
os.environ['HTTPS_PROXY'] = https_proxy
proxy_dict['https'] = https_proxy
verify_ssl_cert = True
if kwargs and 'verify_ssl_cert' in kwargs:
vsc = kwargs.get('verify_ssl_cert')
if vsc in [False, True]:
verify_ssl_cert = vsc
self.session = requests.Session()
self.session.headers = RALLY_REST_HEADERS.copy()
if 'headers' in kwargs:
for header_name, header_value in kwargs['headers'].items():
matching_header = [key for key in self.session.headers
if key.replace(INTEGRATION_HEADER_PREFIX, '').lower() == header_name.lower()]
if matching_header:
self.session.headers[matching_header[0]] = header_value
if self.apikey:
self.session.headers['ZSESSIONID'] = self.apikey
self.user = None
self.password = None
else:
self.session.auth = requests.auth.HTTPBasicAuth(self.user, self.password)
self.session.timeout = DEFAULT_SESSION_TIMEOUT
self.session.proxies = proxy_dict
self.session.verify = verify_ssl_cert
self.session.config = config
global _rallyCache
self.contextHelper = RallyContextHelper(self, self.server, self.user, self.password or self.apikey)
_rallyCache[self.contextHelper.context] = {'rally' : self }
wksp = None
proj = None
if 'workspace' in kwargs and kwargs['workspace'] and kwargs['workspace']!= 'default':
wksp = kwargs['workspace']
if 'project' in kwargs and kwargs['project'] and kwargs['project']!= 'default':
proj = kwargs['project']
self.contextHelper.check(self.server, wksp, proj, self.isolated_workspace)
if self.contextHelper.currentContext() not in _rallyCache:
_rallyCache[self.contextHelper.currentContext()] = {'rally' : self}
if self.contextHelper.defaultContext not in _rallyCache:
_rallyCache[self.contextHelper.defaultContext] = {'rally' : self}
__adjust_cache = False
if 'workspace' in kwargs and kwargs['workspace'] != self.contextHelper.currentContext().workspace \
and kwargs['workspace'] != 'default':
if self.contextHelper.isAccessibleWorkspaceName(kwargs['workspace']):
self.contextHelper.setWorkspace(kwargs['workspace'])
__adjust_cache = True
else:
warning("Unable to use your workspace specification, that value is not listed in your subscription")
if 'project' in kwargs and kwargs['project'] != self.contextHelper.currentContext().project \
and kwargs['project'] != 'default':
mep_proj = None
accessibleProjects = [name for name, ref in self.contextHelper.getAccessibleProjects(workspace='current')]
if PROJECT_PATH_ELEMENT_SEPARATOR in kwargs['project']: # is ' // ' in kwargs['project']?
mep_proj = self.contextHelper._findMultiElementPathToProject(kwargs['project'])
if mep_proj:
accessibleProjects.append(kwargs['project'])
if kwargs['project'] in accessibleProjects:
if not mep_proj:
self.contextHelper.setProject(kwargs['project'])
else:
self.contextHelper.setProject(mep_proj.ref, name=kwargs['project'])
__adjust_cache = True
else:
issue = ("Unable to use your project specification of '%s', "
"that value is not associated with current workspace setting of: '%s'" )
raise Exception(issue % (kwargs['project'], self.contextHelper.currentContext().workspace))
if 'project' not in kwargs:
#
# It's possible that the invoker has specified a workspace but no project
# and the default project isn't in the workspace that was specified.
# In that case reset the current and default project to first project in
# the list of projects for the current workspace.
#
cdp = self.contextHelper.getProject() # cdp alias for current_default_project
ndp = self.contextHelper.resetDefaultProject() # ndp alias for new_default_project
if ndp != cdp: # have to test both the name and ref values!!
__adjust_cache = True
cdp_name, cdp_ref = cdp
ndp_name, ndp_ref = ndp
# but we'll only issue a warning if the project names are different
if self.warningsEnabled() and ndp_name != cdp_name:
short_proj_ref = "/".join(ndp_ref.split('/')[-2:])
wksp_name, wksp_ref = self.contextHelper.getWorkspace()
prob = "Default project changed to '%s' (%s).\n" + \
" Your normal default project: '%s' is not valid for\n" +\
" the current workspace setting of: '%s'"
warning(prob % (ndp_name, short_proj_ref, cdp_name, wksp_name))
if __adjust_cache:
_rallyCache[self.contextHelper.currentContext()] = {'rally' : self}
def _wpCacheStatus(self):
"""
intended to be only for unit testing...
values could be None, True, False, 'minimal', 'narrow', 'wide'
"""
return self.contextHelper._inflated
def serviceURL(self):
"""
Crutch to allow the RallyContextHelper to pass this along in the initialization
of a RallyContext instance.
"""
return self.service_url
def obtainSecurityToken(self):
if self.apikey:
return None
if not self._sec_token:
security_service_url = f'{self.service_url}/{AUTH_ENDPOINT}'
response = self.session.get(security_service_url)
doc = response.json()
self._sec_token = str(doc['OperationResult']['SecurityToken'])
return self._sec_token
def enableLogging(self, dest=sys.stdout, attrget=False, append=False):
"""
Use this to enable logging. dest can set to the name of a file or an open file/stream (writable).
If attrget is set to true, all Rally REST requests that are executed to obtain attribute information
will also be logged. Be careful with that as the volume can get quite large.
The append parm controls whether any existing file will be appended to or overwritten.
"""
self._log = True
if hasattr(dest, 'write'):
self._logDest = dest
elif isinstance(dest, (str,bytes)):
try:
mode = 'w'
if append:
mode = 'a'
self._logDest = open(dest, mode)
except IOError as ex:
self._log = False
self._logDest = None
else:
self._log = False
# emit a warning that logging is disabled due to a faulty dest arg
warning('Logging dest arg cannot be written to, proceeding with logging disabled.')
if self._log:
log_entry = (f"{timestamp()} Following entries record Rally REST API "
f"interaction via {self.service_url} for user {self.user}\n")
self._logDest.write(log_entry)
self._logDest.flush()
if attrget:
self._logAttrGet = True
def disableLogging(self):
"""
Disable logging.
"""
if self._log:
self._log = False
self._logAttrGet = False
if self._logDest and self._logDest not in (sys.stdout, sys.stderr):
try:
self._logDest.flush()
self._logDest.close()
except IOError as ex:
# emit a warning that the logging destination was unable to be closed
pass
self._logDest = None
def enableWarnings(self):
self._warn = True
def disableWarnings(self):
self._warn = False
def warningsEnabled(self):
return self._warn == True
def subscriptionName(self):
"""
Returns the name of the subscription in the currently active context.
"""
return self.contextHelper.currentContext().subscription()
def setWorkspace(self, workspaceName):
"""
Given a workspaceName, set that as the currentWorkspace and use the ref for
that workspace in subsequent interactions with Rally.
However, if the instance was realized using the keyword arg isolated_workspace = True
then do not permit the workspace switch to take place, raise an Exception.
"""
if self.isolated_workspace and workspaceName != self.getWorkspace().Name:
problem = "No reset of of the Workspace is permitted when the isolated_workspace option is specified"
raise RallyRESTAPIError(problem)
if not self.contextHelper.isAccessibleWorkspaceName(workspaceName):
raise Exception('Specified workspace not valid for your credentials or is in a Closed state')
self.contextHelper.setWorkspace(workspaceName)
def getWorkspace(self):
"""
Returns a minimally hydrated Workspace instance with the Name and ref
of the workspace in the currently active context.
"""
context = self.contextHelper.currentContext()
wksp_name, wksp_ref = self.contextHelper.getWorkspace()
return _createShellInstance(context, 'Workspace', wksp_name, wksp_ref)
def getWorkspaces(self):
"""
Return a list of minimally hydrated Workspace instances
that are available to the registered user in the currently active context.
Return a list of (workspace.Name, workspace._ref) tuples
that are available to the registered user in the currently active context.
"""
context = self.contextHelper.currentContext()
wkspcs = self.contextHelper.getAccessibleWorkspaces()
workspaces = [_createShellInstance(context, 'Workspace', wksp_name, wksp_ref)
for wksp_name, wksp_ref in sorted(wkspcs)
]
return workspaces
def setProject(self, projectName):
"""
Given a projectName, set that as the current project and use the ref for
that project in subsequent interractions with Rally unless overridden.
If the projectName contains the ' // ' path element separator token string and there are
two or more path elements in the deconstructed string, the verify that the project path
given is valid and use that project and ref are used in subsequent interactions with Rally
unless overridden.
"""
context = self.contextHelper.currentContext()
if PROJECT_PATH_ELEMENT_SEPARATOR not in projectName: # is ' // ' in projectName?
eligible_projects = [proj for proj,ref in self.contextHelper.getAccessibleProjects(workspace='current')]
if projectName not in eligible_projects:
raise Exception('Specified project not valid for your current workspace or credentials')
self.contextHelper.setProject(projectName)
else: # projectName name like baseProject // nextLevelProject // targetProject
proj = self.contextHelper._findMultiElementPathToProject(projectName)
if not proj:
raise Exception('Specified projectName not found or not valid for your current workspace or credentials')
#proj = _createShellInstance(context, 'Project', projectName, proj._ref)
self.contextHelper.setProject(proj.ref, name=projectName)
def getProject(self, name=None):
"""
Returns a minimally hydrated Project instance with the Name and ref
of the project in the currently active context if the name keyword arg
is not supplied or the Name and ref of the project identified by the name
as long as the name identifies a valid project in the currently selected workspace.
If the name keyword arg has the form of fully qualified path using the ' // ' path
element separator token, then specialized pyral machinery will attempt to "chase"
the elements until either an invalid path element is detected or all path elements
are valid and the name and ref of the ending Project path element is returned.
Returns None if a name parameter is supplied that does not identify a valid project
in the currently selected workspace.
"""
context = self.contextHelper.currentContext()
if not name:
proj_name, proj_ref = self.contextHelper.getProject()
return _createShellInstance(context, 'Project', proj_name, proj_ref)
if name and PROJECT_PATH_ELEMENT_SEPARATOR in name:
proj = self.contextHelper._findMultiElementPathToProject(name)
if proj:
return _createShellInstance(context, 'Project', name, proj._ref)
projs = self.contextHelper.getAccessibleProjects(workspace='current')
hits = [(proj,ref) for proj,ref in projs if str(proj) == str(name)]
if not hits:
return None
tp = hits[0]
tp_ref = tp[1]
return _createShellInstance(context, 'Project', name, tp_ref)
def getProjects(self, workspace=None):
"""
Return a list of minimally hydrated Project instances
that are available to the registered user in the currently active context.
"""
wksp_target = workspace or 'current'
projs = self.contextHelper.getAccessibleProjects(workspace=wksp_target)
context = self.contextHelper.currentContext()
projects = [_createShellInstance(context, 'Project', proj_name, proj_ref)
for proj_name, proj_ref in sorted(projs)
]
return projects
def getUserInfo(self, oid=None, username=None, name=None):
"""
A convenience method to collect specific user related information.
Caller must provide at least one keyword arg and non-None / non-empty value
to identify the user target on which to obtain information.
The name keyword arg is associated with the User.DisplayName attribute
The username keyword arg is associated with the User.UserName attribute
If provided, the oid keyword argument is used, even if other keyword args are
provided. Similarly, if the username keyword arg is provided it is used
even if the name keyword argument is provided.
User
DisplayName
UserName
Disabled
EmailAddress
FirstName
MiddleName
LastName
OnpremLdapUsername
ShortDisplayName
Role
TeamMemberships (from projects)
LastPasswordUpdateDate
UserPermissions - from UserPermission items associated with this User
UserProfile
DefaultWorkspace
DefaultProject
TimeZone
DateFormat
DateTimeFormat
EmailNotificationEnabled
SessionTimeoutSeconds
SessionTimeoutWarning
UserPermission
Name - name of the User Permission
Role
Returns either a single User instance or a list of User instances
"""
#context = self.contextHelper.currentContext()
item, response = None, None
if oid:
item = self._itemQuery('User', oid)
elif username:
response = self.get('User', fetch=True, query=f'UserName = "{username}"')
elif name:
response = self.get('User', fetch=True, query=f'DisplayName = "{name}"')
else:
raise RallyRESTAPIError("No specification provided to obtain User information")
if item:
return item
if response:
return [user for user in response]
return None
def getAllUsers(self, workspace=None):
"""
Given that actually getting full information about all users in the workspace
via the Rally WSAPI is somewhat opaque, this method offers a one-stop convenient
means of obtaining usable information about users in the named workspace.
If no workspace is specified, then the current context's workspace is used.
Return a list of User instances (fully hydrated for scalar attributes)
whose ref and collection attributes will be resolved upon initial access.
"""
saved_workspace_name, saved_workspace_ref = self.contextHelper.getWorkspace()
if not workspace:
workspace = saved_workspace_name
self.setWorkspace(workspace)
context, augments = self.contextHelper.identifyContext(workspace=workspace)
workspace_ref = self.contextHelper.currentWorkspaceRef()
# Somewhere post 1.3x in Rally WSAPI, the ability to list the User attrs along with the TimeZone
# attr of UserProfile and have that all returned in 1 query was no longer supported.
# And somewhere north of v 1.42 and into v2, only a user who is a SubscriptionAdmin
# can actually get information about another user's UserProfile so the next statement
# is limited to a Rally instance whose credentials represent a SubscriptionAdmin capable user.
# So we do a full bucket query on User and UserProfile separately and "join" them via our
# own brute force method so that the caller can access any UserProfile attribute
# for a User.
user_attrs = ["UserName", "DisplayName",
"FirstName", "LastName", "MiddleName",
"ShortDisplayName", "OnpremLdapUsername",
"CreationDate", "EmailAddress",
"LastPasswordUpdateDate", "Disabled",
"Subscription", "SubscriptionAdmin",
"Role", "UserPermissions", "TeamMemberships",
"UserProfile",
"TimeZone", # a UserProfile attribute
# and other UserProfile attributes
]
user_inclusion = "((Disabled = true) OR (Disabled = false))"
user_attrs_string = ",".join(user_attrs)
users_resource = (f'users?fetch={user_attrs_string}&query={user_inclusion}'
f'&pagesize={KILO_PAGESIZE}&start=1&workspace={workspace_ref}')
full_resource_url = f'{self.service_url}/{users_resource}'
response = self.session.get(full_resource_url, timeout=SERVICE_REQUEST_TIMEOUT*5)
if response.status_code != HTTP_REQUEST_SUCCESS_CODE:
return []
response = RallyRESTResponse(self.session, context, full_resource_url, response, "full", 0)
users = [user for user in response]
# find the operator of this instance of Rally and short-circuit now if they *aren't* a SubscriptionAdmin
operator = [user for user in users if user.UserName == self.user]
if not operator or len(operator) == 0 or not operator[0].SubscriptionAdmin:
self.setWorkspace(saved_workspace_name)
return users
user_profile_resource = f'userprofile?fetch=true&query=&pagesize={KILO_PAGESIZE}&start=1&workspace={workspace_ref}'
response = self.session.get(f'{self.service_url}/{user_profile_resource}', timeout=SERVICE_REQUEST_TIMEOUT*5)
if response.status_code != HTTP_REQUEST_SUCCESS_CODE:
warning("Unable to retrieve UserProfile information for users")
profiles = []
else:
response = RallyRESTResponse(self.session, context, user_profile_resource, response, "full", 0)
profiles = [profile for profile in response]
# do our own brute force "join" operation on User to UserProfile info
for user in users:
# get any matching user profiles (aka mups), there really should only be 1 matching...
mups = [prof for prof in profiles
if hasattr(user, 'UserProfile') and prof._ref == user.UserProfile._ref]
if not mups:
up = user.UserProfile if hasattr(user, 'UserProfile') else "Unknown"
problem = (f'unable to find a matching UserProfile record for '
f'User: {user.UserName} UserProfile: {up}')
continue
else:
if len(mups) > 1:
anomaly = f'Found {len(mups)} UserProfile items associated with username: {user.UserName}'
warning(anomaly)
# now attach the first matching UserProfile to the User
user.UserProfile = mups[0]
self.setWorkspace(saved_workspace_name)
return users
def _officialRallyEntityName(self, supplied_name):
if supplied_name in ['Story', 'UserStory', 'User Story']:
supplied_name = 'HierarchicalRequirement'
# here's where we'd make an inquiry into entity to see if the supplied_name
# is a Rally entity on which CRUD ops are permissible.
# An Exception is raised if not.
# If supplied_name resolves in some way to a valid Rally entity,
# this returns either a simple name or a TypePath string (like PortfolioItem/Feature)
official_name = validRallyType(supplied_name)
return official_name
def _getResourceByOID(self, context, entity, oid, **kwargs):
"""
The _ref URL (containing the entity name and OID) can be used unchanged but the format
of the response is slightly different from that returned when the resource URL is
constructed per spec (by this class's get method). The _ref URL response can be
termed "un-wrapped" in that there's no boilerplate involved, just the JSON object.
Returns a raw response instance (with status_code, headers and content attributes).
"""
##
## print("in _getResourceByOID, OID specific resource ...", entity, oid)
## sys.stdout.flush()
##
resource = f'{entity}/{oid}'
if '_disableAugments' not in kwargs:
contextDict = context.asDict()
##
## print("_getResourceByOID, current contextDict: %s" % repr(contextDict))
## sys.stdout.flush()
##
context, augments = self.contextHelper.identifyContext(**contextDict)
if augments:
resource += ("?" + "&".join(augments))
##
## print("_getResourceByOID, modified contextDict: %s" % repr(context.asDict()))
## sys.stdout.flush()
##
full_resource_url = f'{self.service_url}/{resource}'
if self._logAttrGet:
log_entry = f"{timestamp()} GET {resource}\n"
self._logDest.write(log_entry)
self._logDest.flush()
##
## print(f'issuing GET for resource: {full_resource_url}')
## sys.stdout.flush()
##
try:
raw_response = self.session.get(full_resource_url)
except Exception as ex:
exctype, value, tb = sys.exc_info()
warning(f"{exctype}: {value}")
return None
##
## print(f'_getResourceByOID({entity}, {oid}) raw_response: {raw_response}')
## sys.stdout.flush()
##
return raw_response
def _itemQuery(self, entityName, oid, workspace=None, project=None):
"""
Internal method to retrieve a specific instance of an entity identified by the OID.
"""
##
## print(f'Rally._itemQuery("{entityName}", {oid}, workspace={workspace}, project={project})')
##
resource = f'{entityName}/{oid}'
context, augments = self.contextHelper.identifyContext(workspace=workspace, project=project)
if augments:
resource += ("?" + "&".join(augments))
if self._log:
self._logDest.write(f"{timestamp()} GET {resource}\n")
self._logDest.flush()
response = self._getResourceByOID(context, entityName, oid)
if self._log:
self._logDest.write(f"{timestamp()} {response.status_code} {resource}\n")
self._logDest.flush()
if not response or response.status_code != HTTP_REQUEST_SUCCESS_CODE:
problem = f"Unreferenceable {entityName} OID: {oid}"
raise RallyRESTAPIError(f'{response.status_code} {problem}')
response = RallyRESTResponse(self.session, context, f'{entityName}.x', response, "full", 1)
item = response.next()
return item # return back an instance representing the item
def _greased(self, item_data):
"""
Given a dict instance with keys that are attribute names for some
Rally entity associated with values that are to be created for
or updated in a target Rally entity, identify which attributes are
likely COLLECTION types and perform any transformation necessary to
ensure that the prospective attribute values are refs that are placed
in a dict and thence put in a list of values for the attribute.
As an initial implementation to forego yet another round trip query
to Rally for all the Attributes on an entity name, we employ
the following rough heuristic to determine what attributes
are COLLECTIONS and thus _may_ need greasing:
Attribute name of Children or an attribute that ends in 's'.
So, we'll look at the keys in item_data that match our heuristic
(case-insensitive) and then we also check to see if the value
associated with the attribute name key is a list.
If there are no hits for those criteria, return the item_data untouched.
Otherwise, roll thru the attribute name hits whose value is a list
and determine if each element in the list is a string that has the
pattern of "someentityname/324324", (where the digits are an OID value)
and if so, replace the element value with a dict with a key of "_ref"
whose value is the original list element.
Return the item_dict with any updates to COLLECTIONS attributes that
needed "greasing".
"""
collection_attributes = [attr_name for attr_name in list(item_data.keys())
if attr_name.lower == 'children'
or attr_name[-1] == 's'
]
if not collection_attributes:
return item_data
for attr_name in collection_attributes:
if type(item_data[attr_name]) != list:
continue
obj_list = []
for value in item_data[attr_name]:
# is value like "someentityname/34223214" ?
if (type(value) == str or type(value) == bytes) and '/' in value \
and re.match(r'^\d+$', value.split('/')[-1]):
obj_list.append({"_ref" : value}) # transform to a dict instance
elif issubclass(value.__class__, DomainObject):
obj_list.append({"_ref" : value.ref}) # put the ref in a dict instance
else:
obj_list.append(value) # value is untouched
item_data[attr_name] = obj_list
return item_data
def _buildRequest(self, entity, fetch, query, order, kwargs):
pagesize = KILO_PAGESIZE
startIndex = START_INDEX
limit = MAX_ITEMS
if kwargs and 'pagesize' in kwargs:
pagesize = kwargs['pagesize']
if kwargs and 'start' in kwargs:
try:
usi = int(kwargs['start']) # usi - user supplied start index
if 0 < usi < MAX_ITEMS: # start index must be greater than 0 and less than max
startIndex = usi
else:
raise ValueError('Provided start index is greater than pyral MAX_ITEMS configured value.')
except ValueError as ex:
pass
if kwargs and 'limit' in kwargs:
try:
ulimit = int(kwargs['limit']) # in case someone specifies something like limit=gazillionish
limit = min(ulimit, MAX_ITEMS)
except:
pass
if fetch in ['true', 'True', True]:
fetch = 'true'
self.hydration = "full"
elif fetch in ['false', 'False', False, None]:
fetch = 'false'
self.hydration = "shell"
elif (type(fetch) == bytes or type(fetch) == str) and fetch.lower() != 'false':
self.hydration = "full"
elif type(fetch) == tuple and len(fetch) == 1 and fetch[0].count(',') > 0:
fetch = fetch[0]
elif type(fetch) in [list, tuple]:
field_dict = dict([(attr_name, True) for attr_name in fetch])
attr_info = self.validateAttributeNames(entity, field_dict)
fetch = ",".join(k for k in list(attr_info.keys()))
self.hydration = "full"
entity = self._officialRallyEntityName(entity)
resource = RallyUrlBuilder(entity)
resource.qualify(fetch, query, order, pagesize, startIndex)
if '_disableAugments' in kwargs:
context = RallyContext(self.server, self.user, self.password or self.apikey, self.service_url)
else:
context, augments = self.contextHelper.identifyContext(**kwargs)
workspace_ref = self.contextHelper.currentWorkspaceRef()
project_ref = self.contextHelper.currentProjectRef()
if workspace_ref: # TODO: would we ever _not_ have a workspace_ref?
if 'workspace' not in kwargs or ('workspace' in kwargs and kwargs['workspace'] is not None):
resource.augmentWorkspace(augments, workspace_ref)
if project_ref:
if 'project' not in kwargs or ('project' in kwargs and kwargs['project'] is not None):
resource.augmentProject(augments, project_ref)
resource.augmentScoping(augments)
resource = resource.build() # can also use resource = resource.build(pretty=True)
full_resource_url = f'{self.service_url}/{resource}'
return context, resource, full_resource_url, limit
def _getRequestResponse(self, context, request_url, limit, **kwargs):
response = None # in case an exception gets raised in the session.get call ...
try:
# a response has status_code, content and data attributes
# the data attribute is a dict that has a single entry for the key 'QueryResult'
# or 'OperationResult' whose value is in turn a dict with values of
# 'Errors', 'Warnings', 'Results'
response = self.session.get(request_url, timeout=SERVICE_REQUEST_TIMEOUT)
except Exception as ex:
if response:
##
## print("Exception detected for session.get requests, response status code: %s" % response.status_code)
##
ret_code, content = response.status_code, response.content
else:
ret_code, content = PAGE_NOT_FOUND_CODE, str(ex.args[0])
if self._log:
self._logDest.write(f"{timestamp()} {ret_code}\n")
self._logDest.flush()
errorResponse = ErrorResponse(ret_code, content)
response = RallyRESTResponse(self.session, context, request_url, errorResponse, self.hydration, 0)
return response
##
## print(f'response.status_code is {response.status_code}')
##
if response.status_code != HTTP_REQUEST_SUCCESS_CODE:
if self._log:
code, verbiage = response.status_code, response.content[:56]
log_entry = f"{timestamp()} {code} {verbiage} ...\n"
self._logDest.write(log_entry)
self._logDest.flush()
##
## print(response)
##
#if response.status_code == PAGE_NOT_FOUND_CODE:
# problem = (f'{response.status_code} Service unavailable from {self.service_url}, '
# f'check for proper hostname')
# raise Exception(problem)
errorResponse = ErrorResponse(response.status_code, response.content)
response = RallyRESTResponse(self.session, context, request_url, errorResponse, self.hydration, 0)
return response
response = RallyRESTResponse(self.session, context, request_url, response,
self.hydration, limit, **kwargs)
if self._log:
if response.status_code == HTTP_REQUEST_SUCCESS_CODE:
slm_ws_ver = f'/{WEB_SERVICE}/{WS_API_VERSION}/'
req_target, oid = request_url.split(slm_ws_ver)[-1].rsplit('/', 1)
desc = f'{req_target} TotalResultCount {response.resultCount}'
else:
desc = response.errors[0]
log_entry = f"{timestamp()} {response.status_code} {desc}\n"
self._logDest.write(log_entry)
self._logDest.flush()
return response
def get(self, entity, fetch=False, query=None, order=None, **kwargs) -> object:
"""
A REST approach has the world seen as resources with the big 4 ops available on them
(GET, PUT, POST, DELETE). There are other ops, but we don't care about them here.
Each resource _should_ have a unique URI that is used to identify the resource.
The GET operation is used to specify that we want a representation of that resource.
For Rally, in order to construct a URI, we need the name of the entity, the attributes
of the entity (and attributes on any child/parent entity related to the named entity),
the query (selection criteria) and the order in which the results should be returned.
The fetch argument (boolean or a comma separated list of attributes) indicates whether
we get complete representations of objects back or whether we get "shell" objects with
refs to be able to retrieve the full info at some later time.
An optional instance=True keyword argument will result in returning an instantiated
Rally Entity if and only if the resultCount of the get is exactly equal to 1.
Otherwise, a RallyRESTResponse instance is returned.
All optional keyword args:
fetch=True/False or "List,Of,Attributes,We,Are,Interested,In"
query='FieldName = "some value"' or ['fld1 = 19', 'fld27 != "Shamu"', etc.]
order="fieldName ASC|DESC"
instance=False/True
pagesize=n
start=n
limit=n
projectScopeUp=True/False
projectScopeDown=True/False
"""
context, resource, full_resource_url, limit = self._buildRequest(entity, fetch, query, order, kwargs)
if self._log:
# unquote the resource for enhanced readability
self._logDest.write(f"{timestamp()} GET {unquote(resource)}\n")
self._logDest.flush()
threads = 0
if 'threads' in kwargs:
if kwargs['threads'] in [1,2,3,4,5,6,7,8]:
threads = kwargs['threads']
else:
threads = 2
response = self._getRequestResponse(context, full_resource_url, limit, threads=threads)
if kwargs and 'instance' in kwargs and kwargs['instance'] == True and response.resultCount == 1:
return response.next()
return response
find = get # some folks are happier with this alias...
def put(self, entityName, itemData, workspace='current', project='current', **kwargs):
"""
Given a Rally entityName, a dict with data that the newly created entity should contain,
issue the REST call and return the newly created target entity item.
"""
auth_token = self.obtainSecurityToken()
# raises a RallyAttributeNameError if any attribute names in itemData are invalid
# see if we need to transform workspace / project values of 'current' to actual
if workspace == 'current':
workspace = self.getWorkspace().Name # just need the Name here
if project == 'current':
project = self.getProject().Name # just need the Name here
entityName = self._officialRallyEntityName(entityName)
if entityName.lower() == 'recyclebinentry':
raise RallyRESTAPIError("create operation unsupported for RecycleBinEntry")
resource = f'{entityName.lower()}/create?key={auth_token}'
context, augments = self.contextHelper.identifyContext(workspace=workspace, project=project)
if augments:
resource += ("&" + "&".join(augments))
full_resource_url = f"{self.service_url}/{resource}"
itemData = self.validateAttributeNames(entityName, itemData)
item = {entityName: self._greased(itemData)} # where _greased is a convenience
# method that will transform
# any ref lists for COLLECTION attributes
# into a list of one-key dicts {'_ref' : ref}
payload = json.dumps(item)
if self._log:
log_entry = f"{timestamp()} PUT {resource}\n{' ':>27} {payload}\n"
self._logDest.write(log_entry)
self._logDest.flush()
response = self.session.put(full_resource_url, data=payload)