-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWSGroupMigration.py
More file actions
1419 lines (1294 loc) · 67.4 KB
/
Copy pathWSGroupMigration.py
File metadata and controls
1419 lines (1294 loc) · 67.4 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
from os import getgrouplist
import requests
import json, math
from pyspark.sql.functions import lit,col,column
from functools import reduce
from pyspark.sql import DataFrame, session
import concurrent.futures
import time
class GroupMigration:
def __init__(self, groupL : list, cloud : str, account_id : str, workspace_url : str, pat : str, spark : session.SparkSession, userName : str, checkTableACL : False,
numThreads : int = 32, autoGenerateList : bool = False, verbose : bool = False):
self.groupL=groupL
self.cloud=cloud
self.workspace_url = workspace_url.rstrip("/")
self.account_id=account_id
self.token=pat
self.headers={'Authorization': 'Bearer %s' % self.token}
self.groupIdDict={} #map: group id => group name
self.groupNameDict={} #map: group name => group id
self.accountGroups_lower={}
self.groupMembers={} #map: group id => list[tuple[member name, memberid]]
self.groupEntitlements={}
self.groupWSGIdDict={} #map : temp group id => temp group name
self.groupWSGNameDict={} #map : temp group name => temp group id
self.groupRoles={}
self.passwordPerm={}
self.clusterPerm={}
self.clusterPolicyPerm={}
self.warehousePerm={}
self.dashboardPerm={}
self.queryPerm={}
self.alertPerm={}
self.instancePoolPerm={}
self.jobPerm={}
self.expPerm={}
self.modelPerm={}
self.dltPerm={}
self.folderPerm={}
self.notebookPerm={}
self.repoPerm={}
self.tokenPerm={}
self.secretScopePerm={}
self.dataObjectsPerm=[]
self.folderList={}
self.notebookList={}
self.spark=spark
self.userName=userName
self.checkTableACL=checkTableACL
self.verbose = verbose
self.numThreads = numThreads
self.lastInventoryRun = None
#Check if we should automatically generate list, and do it immediately.
#Implementers Note: Could change this section to a lazy calculation by setting groupL to nil or some sentinel value and adding checks before use.
if(autoGenerateList) :
print("autoGenerateList parameter is set to TRUE. Ignoring groupL parameter and instead will automatically generate list of migraiton groups.")
self.groupL = self.findMigrationEligibleGroups()
#Finish setting some params that depend on groupL
if(len(self.groupL) == 0):
raise Exception("Migration group list (groupL) is empty!")
self.TempGroupNames=["db-temp-"+g for g in self.groupL]
self.WorkspaceGroupNames=self.groupL
print(f"Successfully initialized GroupMigration class with {len(self.groupL)} workspace-local groups to migrate. Groups to migrate:")
for i, group in enumerate(self.groupL, start=1):
print(f"{i}. {group}")
print(f"Done listing {len(self.groupL)} groups to migrate.")
def findMigrationEligibleGroups(self):
print("Begin automatic generation of all migration eligible groups.")
#Get all workspace-local groups
try:
print("Executing request to list workspace groups")
res=requests.get(f"{self.workspace_url}/api/2.0/preview/scim/v2/Groups", headers=self.headers)
if res.status_code != 200:
raise Exception(f'Bad status code. Expected: 200. Got: {res.status_code}')
resJson=res.json()
allWsLocalGroups = [o["displayName"] for o in resJson["Resources"] if o['meta']['resourceType'] == "WorkspaceGroup" ]
#Prune special groups.
prune_groups = ["admins", "users"]
allWsLocalGroups = [g for g in allWsLocalGroups if g not in prune_groups]
allWsLocalGroups_lower = [x.casefold() for x in allWsLocalGroups]
allWsLocalGroups.sort()
print(f"\nFound {len(allWsLocalGroups)} workspace local groups. Listing (alphabetical order): \n" + "\n".join(f"{i+1}. {name}" for i, name in enumerate(allWsLocalGroups)))
except Exception as e:
print(f'ERROR in retrieving workspace group list: {e}')
raise
#Now match against account groups.
try:
print("\nExecuting request to list account groups")
res=requests.get(f"{self.workspace_url}/api/2.0/account/scim/v2/Groups", headers=self.headers)
if res.status_code != 200:
raise Exception(f'Bad status code. Expected: 200. Got: {res.status_code}')
resJson2=res.json()
allAccountGroups_lower = [r['displayName'].casefold() for r in resJson2['Resources']]
allAccountGroups_lower.sort()
# Get set intersection of both lists
migration_eligible_lower = list(set(allWsLocalGroups_lower) & set(allAccountGroups_lower))
migration_eligible = [wsl for wsl in allWsLocalGroups if wsl.casefold() in migration_eligible_lower]
migration_eligible.sort()
# Get list of items in allWsLocalGroups that are not in allAccountGroups
not_in_account_groups = [group for group in allWsLocalGroups if group.casefold() not in allAccountGroups_lower]
not_in_account_groups.sort()
# Print count and membership of not_in_account_groups
print(f"Unable to match {len(not_in_account_groups)} current workspace-local groups. No matching account level group with the same name found. These groups WILL NOT MIGRATE:")
for i, group in enumerate(not_in_account_groups, start=1):
print(f"{i}. {group} (WON'T MIGRATE)")
if(len(migration_eligible) > 0):
# Print count and membership of intersection
print(f"\nFound {len(migration_eligible)} current workspace-local groups to account level groups. These groups WILL BE MIGRATED.")
for i, group in enumerate(migration_eligible, start=1):
print(f"{i}. {group} (WILL MIGRATE)")
print('')
return migration_eligible
else:
print("There are no migration eligible groups. All existing workspace-local groups do not exist at the account level.\nNO MIGRATION WILL BE PERFORMED.")
return []
except Exception as e:
print(f'ERROR in retrieving account group list : {e}')
raise
def validateWSGroup(self)->list:
try:
res=requests.get(f"{self.workspace_url}/api/2.0/preview/scim/v2/Groups", headers=self.headers)
resJson=res.json()
for e in resJson['Resources']:
if e['meta']['resourceType']=="Group" and e['displayName'] in self.groupL:
print(f"{e['displayName']} is a Account level group, please provide workspace group" )
return 0
return 1
except Exception as e:
print(f'error in retrieving group objects : {e}')
def getGroupObjects(self, groupFilterKeeplist)->list:
try:
groupIdDict={}
groupMembers={}
groupEntitlements={}
groupRoles={}
res=requests.get(f"{self.workspace_url}/api/2.0/preview/scim/v2/Groups", headers=self.headers)
resJson=res.json()
#print(groupList)
#normalize case
groupFilterKeeplist = [x.casefold() for x in groupFilterKeeplist]
#Iterate over workspace groups, extracting useful info to vars above
for e in resJson['Resources']:
if not e['displayName'].casefold() in groupFilterKeeplist:
continue
groupIdDict[e['id']]=e['displayName']
#Get Group Members
members=[]
try:
for mem in e['members']:
members.append(list([mem['display'],mem['value']]))
except KeyError:
pass
groupMembers[e['id']]=members
#Get entitlements
entms=[]
try:
for ent in e['entitlements']:
entms.append(ent['value'])
except:
pass
groupEntitlements[e['id']]=entms
#Get Roles (AWS only)
if self.cloud=='AWS':
entms=[]
try:
for ent in e['roles']:
entms.append(ent['value'])
except:
continue
if len(entms)==0:
continue
groupRoles[e['id']]=entms
#Finally assign to self (Now that exception hasn't been thrown)
self.groupIdDict = groupIdDict
self.groupMembers = groupMembers
self.groupEntitlements = groupEntitlements
self.groupRoles = groupRoles
#Create reverse of groupIdDict
self.groupNameDict = {}
for k,v in self.groupIdDict.items():
self.groupNameDict[v]=k
except Exception as e:
print(f'error in retrieving group objects : {e}')
#getACL[n] family of functions extract the ACL from the converted json response into a standard format, filtering by groupL
def getACL(self, acls:dict)->list:
aclList=[]
for acl in acls:
try:
if acl['all_permissions'][0]['inherited']==True:continue
aclList.append(list([acl['group_name'],acl['all_permissions'][0]['permission_level']]))
except KeyError:
continue
aclList=[acl for acl in aclList if acl[0] in self.groupL]
return aclList
def getACL3(self, acls:dict)->list:
aclList=[]
for acl in acls:
try:
aclList.append(list([acl['group_name'],acl['all_permissions'][0]['permission_level']]))
except KeyError:
continue
aclList=[acl for acl in aclList if acl[0] in self.groupL]
return aclList
def getACL2(self, acls:dict)->list:
aclList=[]
for acl in acls:
try:
l=[]
for k,v in acl.items():
l.append(v)
aclList.append(l)
except KeyError:
continue
for acl in aclList:
if acl[0] in self.groupL:
return aclList
return {}
def getSingleClusterACL(self, clusterId):
if self.verbose:
print(f'[Verbose] Getting cluster permissions for cluster {clusterId}')
resCPerm=requests.get(f"{self.workspace_url}/api/2.0/preview/permissions/clusters/{clusterId}", headers=self.headers)
if resCPerm.status_code==404:
print(f'Error: cluster ACL not enabled for the cluster: {clusterId}')
return None
resCPermJson=resCPerm.json()
aclList=self.getACL(resCPermJson['access_control_list'])
if len(aclList)==0:
return None
return (clusterId, aclList)
def getAllClustersACL(self)-> dict:
print('Performing cluster inventory...')
try:
resC=requests.get(f"{self.workspace_url}/api/2.0/clusters/list", headers=self.headers)
resCJson=resC.json()
clusterPerm={}
if(len(resCJson)==0):return {}
print(f"Scanning permissions of {len(resCJson['clusters'])} clusters.")
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
future_to_cluster = [executor.submit(self.getSingleClusterACL, c['cluster_id']) for c in resCJson['clusters']]
for future in concurrent.futures.as_completed(future_to_cluster):
result = future.result()
if result is not None:
clusterPerm[result[0]] = result[1]
return clusterPerm
except Exception as e:
print(f'error in retrieving cluster permission: {e}')
def getSingleClusterPolicyACL(self, policyId):
if self.verbose:
print(f'[Verbose] Getting policy permissions for {policyId}')
resCPPerm=requests.get(f"{self.workspace_url}/api/2.0/preview/permissions/cluster-policies/{policyId}", headers=self.headers)
if resCPPerm.status_code==404:
print(f'Error: cluster policy feature is not enabled for policy: {policyId}')
return None
resCPPermJson=resCPPerm.json()
aclList=self.getACL(resCPPermJson['access_control_list'])
if len(aclList)==0:
return None
return (policyId, aclList)
def getAllClusterPolicyACL(self)-> dict:
print('Performing cluster policy inventory...')
try:
resCP=requests.get(f"{self.workspace_url}/api/2.0/policies/clusters/list", headers=self.headers)
resCPJson=resCP.json()
if resCPJson['total_count']==0:
print('No cluster policies defined.')
return {}
print(f"Scanning permissions of {len(resCPJson['policies'])} cluster policies.")
clusterPolicyPerm={}
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
future_to_cluster = [executor.submit(self.getSingleClusterPolicyACL, c['policy_id']) for c in resCPJson['policies']]
for future in concurrent.futures.as_completed(future_to_cluster):
result = future.result()
if result is not None:
clusterPolicyPerm[result[0]] = result[1]
return clusterPolicyPerm
except Exception as e:
print(f'Error in retrieving cluster policy permission: {e}')
def getSingleWarehouseACL(self, warehouseId):
if self.verbose:
print(f'[Verbose] Getting warehouse permissions for warehouse {warehouseId}')
resWPerm=requests.get(f"{self.workspace_url}/api/2.0/preview/permissions/sql/warehouses/{warehouseId}", headers=self.headers)
if resWPerm.status_code==404:
print(f'Error: warehouse ACL not enabled for the warehouse: {warehouseId}')
return None
resWPermJson=resWPerm.json()
aclList=self.getACL(resWPermJson['access_control_list'])
if len(aclList)==0:
return None
return (warehouseId, aclList)
def getAllWarehouseACL(self)-> dict:
print('Performing warehouse inventory ...')
try:
resW=requests.get(f"{self.workspace_url}/api/2.0/sql/warehouses", headers=self.headers)
resWJson=resW.json()
warehousePerm={}
if(len(resWJson)==0):return {}
print(f"Scanning permissions of {len(resWJson['warehouses'])} warehouses.")
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
future_to_warehouse = [executor.submit(self.getSingleWarehouseACL, w['id']) for w in resWJson['warehouses']]
for future in concurrent.futures.as_completed(future_to_warehouse):
result = future.result()
if result is not None:
warehousePerm[result[0]] = result[1]
return warehousePerm
except Exception as e:
print(f'error in retrieving warehouse permission: {e}')
def getAllDashboardACL(self, verbose=False) -> dict:
print('Performing dashboard inventory ...')
try:
resD = requests.get(f"{self.workspace_url}/api/2.0/preview/sql/dashboards", headers=self.headers)
resDJson = resD.json()
pages = math.ceil(resDJson['count'] / resDJson['page_size'])
dashboardPerm = {}
for pg in range(1, pages + 1):
if self.verbose:
print(f"[Verbose] Requesting dashboard page {pg}...")
resD = requests.get(f"{self.workspace_url}/api/2.0/preview/sql/dashboards?page={str(pg)}", headers=self.headers)
resDJson = resD.json()
results = resDJson['results']
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
future_dashboard_perms = {executor.submit(self.getSingleDashboardACL, dashboard['id']): dashboard['id'] for dashboard in results}
for future in concurrent.futures.as_completed(future_dashboard_perms):
dashboard_id = future_dashboard_perms[future]
try:
result = future.result()
if len(result) > 0:
dashboardPerm[dashboard_id] = result
except Exception as e:
print(f'Error in retrieving dashboard permission for dashboard {dashboard_id}: {e}')
return dashboardPerm
except Exception as e:
print(f'Error in retrieving dashboard permission: {e}')
raise e
#this request sometimes fails so we wrap in retry loop
def getSingleDashboardACL(self, dashboardId) -> list:
RETRY_LIMIT = 3
RETRY_DELAY = 500 / 1000 #500 ms
retry_count = 0
while retry_count < RETRY_LIMIT:
if retry_count > 0:
time.sleep(RETRY_DELAY)
if self.verbose:
print(f"[Verbose] Requesting dashboard id {dashboardId}. retry_count={retry_count}")
resDPerm = requests.get(f"{self.workspace_url}/api/2.0/preview/sql/permissions/dashboards/{dashboardId}", headers=self.headers)
if resDPerm.status_code != 200:
retry_count += 1
continue
try:
resDPermJson = resDPerm.json()
aclList = resDPermJson['access_control_list']
dashboard_acl = []
if len(aclList) > 0:
for acl in aclList:
try:
if acl['group_name'] in self.groupL:
dashboard_acl = aclList
break
except KeyError:
continue
return dashboard_acl
except KeyError:
retry_count += 1
continue
print(f"ERROR: Retry limit of {RETRY_LIMIT} exceeded requesting dashboard id {dashboardId}")
return [] # if retry limit exceeded, return empty list
def getAllQueriesACL(self, verbose=False) -> dict:
print('Performing query inventory ...')
try:
resQ = requests.get(f"{self.workspace_url}/api/2.0/preview/sql/queries", headers=self.headers)
resQJson = resQ.json()
pages = math.ceil(resQJson['count'] / resQJson['page_size'])
queryPerm = {}
for pg in range(1, pages + 1):
if self.verbose:
print(f"[Verbose] Requesting query page {pg}...")
resQ = requests.get(f"{self.workspace_url}/api/2.0/preview/sql/queries?page={str(pg)}", headers=self.headers)
resQJson = resQ.json()
results = resQJson['results']
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
future_query_perms = {executor.submit(self.getSingleQueryACL, query['id']): query['id'] for query in results}
for future in concurrent.futures.as_completed(future_query_perms):
query_id = future_query_perms[future]
try:
result = future.result()
if len(result) > 0:
queryPerm[query_id] = result
except Exception as e:
print(f'Error in retrieving query permission for query {query_id}: {e}')
return queryPerm
except Exception as e:
print(f'Error in retrieving query permission: {e}')
raise e
# this request sometimes fails so we wrap in retry loop
def getSingleQueryACL(self, queryId) -> list:
RETRY_LIMIT = 3
RETRY_DELAY = 500 / 1000 #500 ms
retry_count = 0
while retry_count < RETRY_LIMIT:
if retry_count > 0:
time.sleep(RETRY_DELAY)
if self.verbose:
print(f"[Verbose] Requesting query id {queryId}. retry_count={retry_count}")
resQPerm = requests.get(f"{self.workspace_url}/api/2.0/preview/sql/permissions/queries/{queryId}", headers=self.headers)
if resQPerm.status_code != 200:
retry_count += 1
continue
try:
resQPermJson = resQPerm.json()
aclList = resQPermJson['access_control_list']
query_acl = []
if len(aclList) > 0:
for acl in aclList:
try:
if acl['group_name'] in self.groupL:
query_acl = aclList
break
except KeyError:
continue
return query_acl
except KeyError:
retry_count += 1
continue
print(f"ERROR: Retry limit of {RETRY_LIMIT} exceeded requesting query id {queryId}")
return [] # if retry limit exceeded, return empty list
def getAlertsACL(self)-> dict:
try:
resA=requests.get(f"{self.workspace_url}/api/2.0/preview/sql/alerts", headers=self.headers)
resAJson=resA.json()
alertPerm={}
for c in resAJson:
alertId=c['id']
resAPerm=requests.get(f"{self.workspace_url}/api/2.0/preview/sql/permissions/alerts/{alertId}", headers=self.headers)
if resAPerm.status_code==404:
print(f'feature not enabled for this tier')
continue
resAPermJson=resAPerm.json()
aclList=resAPermJson['access_control_list']
if len(aclList)==0:continue
for acl in aclList:
try:
if acl['group_name'] in self.groupL:
alertPerm[alertId]=aclList
break
except KeyError:
continue
return alertPerm
except Exception as e:
print(f'error in retrieving alerts permission: {e}')
def getPasswordACL(self)-> dict:
try:
if self.cloud!='AWS':
return
resP=requests.get(f"{self.workspace_url}/api/2.0/preview/permissions/authorization/passwords", headers=self.headers)
resPJson=resP.json()
if len(resPJson)<3:
print('No password acls defined.')
return {}
passwordPerm={}
passwordPerm['passwords']=self.getACL(resPJson['access_control_list'])
return passwordPerm
except Exception as e:
print(f'error in retrieving password permission: {e}')
def getPoolACL(self)-> dict:
try:
resIP=requests.get(f"{self.workspace_url}/api/2.0/instance-pools/list", headers=self.headers)
resIPJson=resIP.json()
if len(resIPJson)==0:
print('No Instance Pools defined.')
return {}
instancePoolPerm={}
for c in resIPJson['instance_pools']:
instancePID=c['instance_pool_id']
resIPPerm=requests.get(f"{self.workspace_url}/api/2.0/preview/permissions/instance-pools/{instancePID}", headers=self.headers)
if resIPPerm.status_code==404:
print(f'feature not enabled for this tier')
continue
resIPPermJson=resIPPerm.json()
aclList=self.getACL(resIPPermJson['access_control_list'])
if len(aclList)==0:continue
instancePoolPerm[instancePID]=aclList
return instancePoolPerm
except Exception as e:
print(f'error in retrieving Instance Pool permission: {e}')
def getAllJobACL(self) -> dict:
print("Running job ACL inventory ...")
try:
jobPerm = {}
offset = 0
limit = 25 #25 is the max before the api complains
while True:
#Query next page
if self.verbose:
print(f'[Verbose] Retrieving jobs page offset={offset}, limit={limit}')
resJob=requests.get(f"{self.workspace_url}/api/2.1/jobs/list?limit={str(limit)}&offset={str(offset)}", headers=self.headers)
resJobJson = resJob.json()
if resJobJson['has_more'] == False and len(resJobJson) == 1:
print('Finished listing jobs')
break
#Grab job IDs and parallel map over them to get all ACLs
jobIDs = [c['job_id'] for c in resJobJson['jobs']]
with concurrent.futures.ThreadPoolExecutor() as executor:
results = executor.map(self.getSingleJobACL, jobIDs)
for result in results:
if result is not None:
jobPerm[result[0]] = result[1]
#Check for finish?
if not resJobJson['has_more']:
break
offset += limit
return jobPerm
except Exception as e:
print(f'error in retrieving job permissions: {e}')
def getSingleJobACL(self, jobID):
try:
resJobPerm = requests.get(f"{self.workspace_url}/api/2.0/permissions/jobs/{jobID}", headers=self.headers)
if resJobPerm.status_code == 404:
print(f'feature not enabled for this tier')
return None
resJobPermJson = resJobPerm.json()
aclList = self.getACL(resJobPermJson['access_control_list'])
if len(aclList) == 0:
return None
return (jobID, aclList)
except Exception as e:
print(f'error in retrieving permission for job {jobID}: {e}')
return None
def getExperimentACL(self)-> dict:
try:
nextPageToken=''
expPerm={}
while True:
data={}
data={'max_results':100}
if nextPageToken!="":
data={'page_token':nextPageToken, 'max_results':'100'}
resExp=requests.get(f"{self.workspace_url}/api/2.0/mlflow/experiments/list", headers=self.headers,data=json.dumps(data))
resExpJson=resExp.json()
if len(resExpJson)==0:
print('No experiments available')
return {}
for c in resExpJson['experiments']:
expID=c['experiment_id']
#print(c)
for k in c['tags']:
if k['key']=='mlflow.experimentType':
if k['value']=='NOTEBOOK':
#print('notebook')
resExpPerm=requests.get(f"{self.workspace_url}/api/2.0/permissions/notebooks/{expID}", headers=self.headers)
else:
#print('experiment')
resExpPerm=requests.get(f"{self.workspace_url}/api/2.0/permissions/experiments/{expID}", headers=self.headers)
#resExpPerm=requests.get(f"{self.workspace_url}/api/2.0/permissions/experiments/{expID}", headers=self.headers)
if resExpPerm.status_code==404:
print(f'feature not enabled for this tier')
continue
resExpPermJson=resExpPerm.json()
if resExpPerm.status_code!=200:
print(f'unable to get permission for experiment {expID}')
continue
aclList=self.getACL(resExpPermJson['access_control_list'])
if len(aclList)==0:continue
expPerm[expID]=aclList
try:
nextPageToken=resExpJson['next_page_token']
#break
except KeyError:
break
return expPerm
except Exception as e:
print(f'error in retrieving experiment permission: {e}')
def getModelACL(self)-> dict:
try:
nextPageToken=''
expPerm={}
while True:
data={}
data={'max_results':20}
if nextPageToken!="":
data={'page_token':nextPageToken}
resModel=requests.get(f"{self.workspace_url}/api/2.0/mlflow/registered-models/list", headers=self.headers,data=json.dumps(data))
resModelJson=resModel.json()
if len(resModelJson)==0:
print('No models available')
return {}
modelPerm={}
for c in resModelJson['registered_models']:
modelName=c['name']
param={'name':modelName}
modIDRes=requests.get(f"{self.workspace_url}/api/2.0/mlflow/databricks/registered-models/get", headers=self.headers, data=json.dumps(param))
modelID=modIDRes.json()['registered_model_databricks']['id']
resModelPerm=requests.get(f"{self.workspace_url}/api/2.0/permissions/registered-models/{modelID}", headers=self.headers)
if resModelPerm.status_code==404:
print(f'feature not enabled for this tier')
continue
resModelPermJson=resModelPerm.json()
aclList=self.getACL(resModelPermJson['access_control_list'])
if len(aclList)==0:continue
modelPerm[modelID]=aclList
try:
nextPageToken=resModelJson['next_page_token']
#break
except KeyError:
break
return modelPerm
except Exception as e:
print(f'error in retrieving model permission: {e}')
def getDLTACL(self)-> dict:
try:
nextPageToken=''
dltPerm={}
while True:
data={}
data={'max_results':20}
if nextPageToken!="":
data={'page_token':nextPageToken}
resDlt=requests.get(f"{self.workspace_url}/api/2.0/pipelines", headers=self.headers,data=json.dumps(data))
resDltJson=resDlt.json()
if len(resDltJson)==0:
print('No dlt pipelines available')
return {}
for c in resDltJson['statuses']:
dltID=c['pipeline_id']
resDltPerm=requests.get(f"{self.workspace_url}/api/2.0/permissions/pipelines/{dltID}", headers=self.headers)
if resDltPerm.status_code==404:
print(f'feature not enabled for this tier')
continue
resDltPermJson=resDltPerm.json()
aclList=self.getACL(resDltPermJson['access_control_list'])
if len(aclList)==0:continue
dltPerm[dltID]=aclList
try:
nextPageToken=resDltJson['next_page_token']
#break
except KeyError:
break
return dltPerm
except Exception as e:
print(f'error in retrieving dlt pipelines permission: {e}')
def getRecursiveFolderList(self, path:str) -> dict:
print(f'Getting directory structure starting with root path: {path} ...')
self.folderList.clear()
self.notebookList.clear()
remaining_dirs = [path]
depth=0
while remaining_dirs:
if self.verbose:
print(f"[Verbose] Requesting file list for Depth {depth} Path: {path}")
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
futuresMap = {executor.submit(self.getSingleFolderList, dir_path, depth) : dir_path for dir_path in remaining_dirs}
for future in concurrent.futures.as_completed(futuresMap):
dir_path = futuresMap[future]
res = future.result()
if res:
dir_path2, folders, notebooks = res
if dir_path2 != dir_path:
print(f"ERROR: got WRONG RESULT from future: sent: {dir_path} recieved: {dir_path2}")
remaining_dirs.remove(dir_path2)
#todo: what??
else:
self.folderList.update(folders)
self.notebookList.update(notebooks)
remaining_dirs.extend(dir_path for dir_path in folders.values())
else:
print(f"ERROR: one of the futurue results was None: {dir_path}")
remaining_dirs.remove(dir_path)
depth = depth + 1
return (self.folderList, self.notebookList)
def getSingleFolderList(self, path:str, depth:int) -> dict:
MAX_RETRY = 5
RETRY_DELAY = 500 / 1000
retry_count = 0
lastError = ''
while retry_count < MAX_RETRY:
#Give some time for the server to recover
if retry_count > 0:
time.sleep(RETRY_DELAY)
if self.verbose:
print(f"[Verbose] Requesting file list for Depth {depth} Retry {retry_count} Path: {path}")
retry_count = retry_count + 1
try:
data={'path':path}
resFolder=requests.get(f"{self.workspace_url}/api/2.0/workspace/list", headers=self.headers, data=json.dumps(data))
resFolderJson=resFolder.json()
if resFolder.status_code == 403:
print(f'[ERROR] status code 403 permission denied to read folder {path}.')
return (path, {}, {})
if resFolder.status_code != 200:
print(f'[ERROR] bad status code for folder {path}. code: {resFolder.status_code}')
continue
subFolders = {}
notebooks = {}
if len(resFolderJson)==0:
return (path, subFolders, notebooks)
for c in resFolderJson['objects']:
if c['object_type']=="DIRECTORY" and c['path'].startswith('/Repos') == False and c['path'].startswith('/Shared') == False and c['path'].endswith('/Trash') == False:
subFolders[c['object_id']] = c['path']
elif c['object_type']=="NOTEBOOK" and c['path'].startswith('/Repos') == False and c['path'].startswith('/Shared') == False:
notebooks[c['object_id']] = c['path']
return (path, subFolders, notebooks)
except Exception as e:
# print(f'error in retriving path {path}. error: {e}.')
lastError = e
continue
print(f'[ERROR] retry limit ({MAX_RETRY}) limit exceeded while retriving path {path}. last err: {lastError}.')
return (path, {}, {})
def getFoldersNotebookACL(self, rootPath = '/') -> list:
print('Performing folders and notebook inventory ...')
try:
# Get folder list
self.getRecursiveFolderList(rootPath)
# Collect folder IDs, ignoring suffix /Trash to avoid useless errors. /Repos and /Shared are ignored at the folder list level
folder_ids = [folder_id for folder_id in self.folderList.keys() if not self.folderList[folder_id].endswith('/Trash')]
# Get folder permissions in parallel
folder_results = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
folder_futures = {executor.submit(requests.get, f"{self.workspace_url}/api/2.0/permissions/directories/{folder_id}", headers=self.headers): folder_id for folder_id in folder_ids}
print(f"Awaiting parallel permission requests for {len(folder_futures)} folders ...")
for future in concurrent.futures.as_completed(folder_futures):
folder_id = folder_futures[future]
try:
resFolderPerm = future.result()
if resFolderPerm.status_code == 404:
print(f'feature not enabled for this tier')
continue
if resFolderPerm.status_code == 403:
print('Error retrieving permission for ' + self.folderList[folder_id] + ' ' + resFolderPerm.json()['message'])
continue
resFolderPermJson = resFolderPerm.json()
try:
aclList=self.getACL(resFolderPermJson['access_control_list'])
except Exception as e:
print(f'error in retriving folder details: {e}')
if len(aclList) == 0:
continue
folder_results[folder_id] = aclList
except Exception as e:
print(f'error in retrieving folder permission: {e}')
# Get notebook permissions in parallel
notebook_results = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=self.numThreads) as executor:
notebook_futures = {executor.submit(requests.get, f"{self.workspace_url}/api/2.0/permissions/notebooks/{notebook_id}", headers=self.headers): notebook_id for notebook_id in self.notebookList.keys()}
print(f"Awaiting parallel permission requests for {len(notebook_futures)} notebooks ...")
for future in concurrent.futures.as_completed(notebook_futures):
notebook_id = notebook_futures[future]
try:
resNotebookPerm = future.result()
if resNotebookPerm.status_code == 404:
print(f'feature not enabled for this tier')
continue
if resNotebookPerm.status_code == 403:
print('Error retrieving permission for ' + self.notebookList[notebook_id] + ' ' + resNotebookPerm.json()['message'])
continue
resNotebookPermJson = resNotebookPerm.json()
try:
aclList=self.getACL(resNotebookPermJson['access_control_list'])
except Exception as e:
print(f'error in retriving notebook details: {e}')
if len(aclList) == 0:
continue
notebook_results[notebook_id] = aclList
except Exception as e:
print(f'error in retrieving notebook permission: {e}')
return folder_results, notebook_results
except Exception as e:
print(f'error in retrieving folder and notebook permissions: {e}')
def getRepoACL(self)-> dict:
try:
nextPageToken=''
repoPerm={}
while True:
data={}
data={'max_results':20}
if nextPageToken!="":
data={'next_page_token':nextPageToken}
resRepo=requests.get(f"{self.workspace_url}/api/2.0/repos", headers=self.headers,data=json.dumps(data))
resRepoJson=resRepo.json()
if len(resRepoJson)==0:
print('No repos available')
return {}
for c in resRepoJson['repos']:
repoID=c['id']
resRepoPerm=requests.get(f"{self.workspace_url}/api/2.0/permissions/repos/{repoID}", headers=self.headers)
if resRepoPerm.status_code==404:
print(f'feature not enabled for this tier')
continue
resRepoPermJson=resRepoPerm.json()
aclList=self.getACL3(resRepoPermJson['access_control_list'])
if len(aclList)==0:continue
repoPerm[repoID]=aclList
try:
nextPageToken=resRepoJson['next_page_token']
except KeyError:
break
return repoPerm
except Exception as e:
print(f'error in retrieving repos permission: {e}')
def getTokenACL(self)-> dict:
try:
tokenPerm = {}
resTokenPerm=requests.get(f"{self.workspace_url}/api/2.0/preview/permissions/authorization/tokens", headers=self.headers)
if resTokenPerm.status_code==404:
print(f'feature not enabled for this tier')
return {}
resTokenPermJson=resTokenPerm.json()
aclList=[]
for acl in resTokenPermJson['access_control_list']:
try:
if acl['all_permissions'][0]['inherited']==True:continue
aclList.append(list([acl['group_name'],acl['all_permissions'][0]['permission_level']]))
except KeyError:
continue
aclList=[acl for acl in aclList if acl[0] in self.groupL]
tokenPerm['tokens']=aclList
return tokenPerm
except Exception as e:
print(f'error in retrieving Token permission: {e}')
return {}
def getSecretScoppeACL(self)-> dict:
try:
resSScope=requests.get(f"{self.workspace_url}/api/2.0/secrets/scopes/list", headers=self.headers)
resSScopeJson=resSScope.json()
if len(resSScopeJson)==0:
raise Exception('No secret scopes defined.')
secretScopePerm={}
for c in resSScopeJson['scopes']:
scopeName=c['name']
data={'scope':scopeName}
resSSPerm=requests.get(f"{self.workspace_url}/api/2.0/secrets/acls/list/", headers=self.headers, data=json.dumps(data))
if resSSPerm.status_code==404:
print(f'feature not enabled for this tier')
continue
if resSSPerm.status_code!=200:
print(f'Error retrieving ACL for Secret Scope: {scopeName}. HTTP Status Code {resSSPerm.status_code}')
continue
resSSPermJson=resSSPerm.json()
if not 'items' in resSSPermJson:
#print(f'ACL for Secret Scope {scopeName} missing "items" key. Contents:\n{resSSPermJson}\nSkipping...')
#This seems to be expected behaviour if there are no ACLs, silently ignore
continue
aclList=[]
for acl in resSSPermJson['items']:
try:
if acl['principal'] in self.groupL:
aclList.append(list([acl['principal'],acl['permission']]))
except KeyError:
continue
if len(aclList)==0:continue
secretScopePerm[scopeName]=aclList
return secretScopePerm
except Exception as e:
print(f'error in retriving Secret Scope permission: {e}')
def updateGroupEntitlements(self, groupEntitlements:dict, level:str):
try:
for group_id, etl in groupEntitlements.items():
entitlementList=[]
if level=="Workspace":
groupId=self.groupWSGNameDict["db-temp-"+self.groupIdDict[group_id]]
else: #Account, aka temp group, must discard db-temp- (8 chars)
groupId=self.accountGroups_lower[self.groupIdDict[group_id][8:].casefold()]
#print(groupId)
for e in etl:
entitlementList.append({"value":e})
entitlements = {
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"Operations": [{"op": "add",
"path": "entitlements",
"value": entitlementList}]
}
resPatch=requests.patch(f'{self.workspace_url}/api/2.0/preview/scim/v2/Groups/{groupId}', headers=self.headers, data=json.dumps(entitlements))
except Exception as e:
print(f'error applying entitiement for group id: {group_id}.')
def updateGroupRoles(self, level:str):
try:
for group_id, roles in self.groupRoles.items():
roleList=[]
if level=="Workspace":
groupId=self.groupWSGNameDict["db-temp-"+self.groupIdDict[group_id]]
else: #Account, aka temp group, must discard db-temp- (8 chars)
groupId=self.accountGroups_lower[self.groupIdDict[group_id][8:].casefold()]
for e in roles:
roleList.append({"value":e})
instanceProfileRoles = {
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"Operations": [{"op": "add",
"path": "roles",
"value": roleList}]
}
resPatch=requests.patch(f'{self.workspace_url}/api/2.0/preview/scim/v2/Groups/{groupId}', headers=self.headers, data=json.dumps(instanceProfileRoles))
except Exception as e:
print(f'error applying role for group id: {group_id}.')
def updateGroupPermission(self, object:str, groupPermission : dict, level:str):
try:
suffix=""
for object_id,aclList in groupPermission.items():
dataAcl=[]
for acl in aclList:
if level=="Workspace":
gName="db-temp-"+acl[0]
elif level=="Account":
gName=acl[0][8:]
dataAcl.append({"group_name":gName,"permission_level":acl[1]})
data={"access_control_list":dataAcl}
resAppPerm=requests.patch(f"{self.workspace_url}/api/2.0/preview/permissions/{object}/{object_id}", headers=self.headers, data=json.dumps(data))
except Exception as e:
print(f'Error setting permission for {object} {object_id}. {e} ')
def updateGroup2Permission(self, object:str, groupPermission : dict, level:str):
try:
for object_id,aclList in groupPermission.items():
dataAcl=[]
for acl in aclList:
try: