forked from sassoftware/pyviyatools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsharedfunctions.py
executable file
·608 lines (418 loc) · 18.2 KB
/
sharedfunctions.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# sharedfunctions.py
# December 2017
#
# A set of shared functions used by the piviyatool which makes REST calls to supplement the VIYA CLI
#
# callrestapi is the core function it will accept a method endpoint and optionally a python dictionary as input
# getfolderid returns a folder id if it is passed the path to the viya folder
# getebaseuri returns the base url for the service from the default profile
# getauthtoken returns the authentication token created by the CLI call sas-admin auth login
# getinputjson converts the input json to a python dictionary
#
# Change History
#
# 27JAN2018 Comments added
# 29JAN2018 Added simpleresults function
# 31JAN2018 Added the ability to pass contenttype to call_rest_api (now callrestapi)
# 31JAN2018 Improved error handling of call_rest_api (now callrestapi)
# 31JAN2018 Deal with situation where json is not returned
# 31JAN2018 Fix a bug when neither json or text is returned
# 02FEB2018 Fix a bug when text is returned
# 12MAR2018 Made simple result print generic
# 20MAR2018 Added some comments
# 20MAR2018 Handle errors when profile and authentication token do not exist
# 20May2018 Fixed bug in authentication check
# 01jun2018 Deal with empty profile error
# 23oct2018 Added print result function
# 23oct2018 Added print csv
# 28oct2018 Added stop on error to be able to override stopping processing when an error occurs
# 20nov2018 Updated so that multiple profiles can be used
# 20dec2018 Fixed standard csv output
# 14JAN2019 Added getpath
#
# Copyright © 2018, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
# Import Python modules
from __future__ import print_function
import requests
import sys
import json
import pprint
import os
import collections
pp = pprint.PrettyPrinter(indent=4)
# validate rest api is not used at this time
# not used
def validaterestapi(baseurl, reqval, reqtype, data={}):
global result
print("The request is a "+reqtype+" request: ",baseurl+reqval)
json_data=json.dumps(data, ensure_ascii=False)
print("Data for Request:")
print(json_data)
if (reqtype !="get" or reqtype !="post" or reqtype!="delete" or reqtype!="put"):
print("NOTE: Invalid method")
return;
# callrestapi
# this is the main function called many other programs and by the callrestapi program to make the REST calls
# change history
# 01dec2017 initial development
# 28oct2018 Added stop on error to be able to override stopping processing when an error occurs
def callrestapi(reqval, reqtype, acceptType='application/json', contentType='application/json',data={},stoponerror=1):
# get the url from the default profile
baseurl=getbaseurl()
# get the auth token
oaval=getauthtoken(baseurl)
# build the authorization header
head= {'Content-type':contentType,'Accept':acceptType}
head.update({"Authorization" : oaval})
# maybe this can be removed
global result
# sereliaze the data string for the request to json format
json_data=json.dumps(data, ensure_ascii=False)
# call the rest api using the parameters passed in and the requests python library
if reqtype=="get":
ret = requests.get(baseurl+reqval,headers=head,data=json_data)
elif reqtype=="post":
ret = requests.post(baseurl+reqval,headers=head,data=json_data)
elif reqtype=="delete":
ret = requests.delete(baseurl+reqval,headers=head,data=json_data)
elif reqtype=="put":
ret = requests.put(baseurl+reqval,headers=head,data=json_data)
else:
result=None
print("NOTE: Invalid method")
sys.exit()
# response error if status code between these numbers
if (400 <= ret.status_code <=599):
print(ret.text)
result=None
if stoponerror: sys.exit()
# return the result
else:
# is it json
try:
result=ret.json()
except:
# is it text
try:
result=ret.text
except:
result=None
print("NOTE: No result to print")
return result;
# getfolderid
# when a Viya content path is passed in return the id, path and uri
# change history
# 01dec2017 initial development
def getfolderid(path):
# build the request parameters
reqval="/folders/folders/@item?path="+path
reqtype='get'
callrestapi(reqval,reqtype)
if result==None:
print("NOTE: Folder'"+path+"' not found.")
targetid=None
targetname=None
targeturi=None
else:
targetid=result['id']
targetname=result['name']
targeturi="/folders/folders/"+targetid
return [targetid,targeturi,targetname]
# getbaseurl
# from the default profile return the baseurl of the Viya server
# change history
# 01dec2017 initial development
# 01jun2018 Deal with empty profile error
# 20nov2018 Use the SAS_CLI_PROFILE env variable
def getbaseurl():
# check that profile file is available and can be read
# note the path to the profile is hard-coded right now
endpointfile=os.path.join(os.path.expanduser('~'),'.sas','config.json')
access_file=file_accessible(endpointfile,'r')
#profile does not exist
if access_file==False:
print("ERROR: Cannot read CLI profile at:",endpointfile,". Recreate profile with sas-admin profile init.")
sys.exit()
#profile is empty file
if os.stat(endpointfile).st_size==0:
print("ERROR: Cannot read CLI profile empty file at:",endpointfile,". Recreate profile with sas-admin profile init.")
sys.exit()
# get json from profile
with open(endpointfile) as json_file:
data = json.load(json_file)
# get the profile environment variable to use it
# if it is not set default to the default profile
cur_profile=os.environ.get("SAS_CLI_PROFILE","Default")
#print("URL: ",cur_profile )
# check that information is in profile
if cur_profile in data:
baseurl=data[cur_profile]['sas-endpoint']
else:
baseurl=None
print("ERROR: profile "+cur_profile+" does not exist. Recreate profile with sas-admin profile init.")
sys.exit()
return baseurl
# getauthtoken
# from the stored auth file get the authentication token for the request header
# change history
# 01dec2017 initial development
# return oaval=None when no authtoken retrieved
# 20nov2018 Use the SAS_CLI_PROFILE env variable
def getauthtoken(baseurl):
#get authentication information for the header
credential_file=os.path.join(os.path.expanduser('~'),'.sas','credentials.json')
# check that credential file is available and can be read
access_file=file_accessible(credential_file,'r')
if access_file==False:
oaval=None
print("ERROR: Cannot read authentication credentials at: ", credential_file)
print("ERROR: Try refreshing your token with sas-admin auth login")
sys.exit()
with open(credential_file) as json_file:
data = json.load(json_file)
type(data)
# the sas-admin profile init creates an empty credential file
# check that credential is in file, if it is add it to the header, if not exit
# get the profile environment variable to use it
# if it is not set default to the default profile
cur_profile=os.environ.get("SAS_CLI_PROFILE","Default")
#print("LOGON: ", cur_profile )
if cur_profile in data:
oauthToken=data[cur_profile]['access-token']
oauthTokenType="bearer"
oaval=oauthTokenType + ' ' + oauthToken
head= {'Content-type':'application/json','Accept':'application/json' }
head.update({"Authorization" : oaval})
# test a connection to rest api if it fails exit
r = requests.get(baseurl,headers=head)
if (400 <= r.status_code <=599):
oaval=None
print(r.text)
print("ERROR: cannot connect to "+baseurl+" is your token expired?")
print("ERROR: Try refreshing your token with sas-admin auth login")
sys.exit()
else:
oaval=None
print("ERROR: access token not in file: ", credential_file)
print("ERROR: Try refreshing your token with sas-admin auth login")
sys.exit()
return oaval
# getinputjson
# load the returned json to a python dictionary
# change history
# 01dec2017 initial development
def getinputjson(input_file):
with open(input_file) as json_file:
inputdata = json.load(json_file)
return inputdata
# simpleresults
# take the complex json and create a simple print of the results
# change history
# 01dec2017 initial development
# 20dec2018 simple output now alphibetical order by key
def simpleresults(resultdata):
# print a simplification of the json results
# list of items returned by rest call
if 'items' in resultdata:
total_items=resultdata['count']
returned_items=len(resultdata['items'])
if total_items == 0: print("Note: No items returned.")
for i in range(0,returned_items):
print ("=====Item ",i,"=======")
origpairs=resultdata['items'][i]
test=origpairs.get('description')
if test==None: origpairs['description']='None'
pairs=collections.OrderedDict(sorted(origpairs.items()))
for key,val in pairs.items():
if key != 'links':
print(key,end="")
print(" = ", val)
print("Result Summary: Total items available: ",total_items ,"Total items returned: ", returned_items)
elif 'id' in resultdata: #one item returned by rest call
for key,val in resultdata.items():
if key != 'links':
print(key,end="")
print(" = ", val)
else:
print("NOTE: No JSON Results Found")
# tableresults
# take the complex json and create a simple table of the results
# change history
# 01aug2018 initial development
# 19dece2018 print csv in column orderwith only common columns
def csvresults(resultdata,columns=[]):
if 'items' in resultdata:
total_items=resultdata['count']
returned_items=len(resultdata['items'])
if total_items == 0: print("Note: No items returned.")
for i in range(0,returned_items):
origpairs=resultdata['items'][i]
# create an ordered dictionary
pairs=collections.OrderedDict()
# loop thru the column list and insert to a new dictionary in that order
# this ensures that colums appear in this order in the csv
for keylabel in columns:
# get the value for the current column
curval=origpairs.get(keylabel)
if curval != None:
pairs[keylabel] = curval
else:
pairs[keylabel] = 'None'
numvals=len(columns)
z=0
# print header row of column names
for key,val in pairs.items():
z=z+1
# seperate with comma except last item
if z==numvals: sep=''
else: sep=','
if i==0 and key in columns: print(key,sep,end="")
print("\n",end="")
z=0
# print rows
for key,val in pairs.items():
# seperate with comma except last item
z=z+1
if z==numvals: sep=''
else: sep=','
if key != 'links' and key in columns: print('"'+str(val)+'"'+sep, end="")
print("\n",end="")
elif 'id' in resultdata: #one item returned by rest call
numvals=len(resultdata.items())
z=0
for key,val in resultdata.items():
# seperate with comma except last item
z=z+1
if z==numvals: sep=''
else: sep=','
if key != 'links': print(key,sep,end="")
print("\n",end="")
z=0
for key,val in resultdata.items():
# seperate with comma except last item
z=z+1
if z==numvals: sep=''
else: sep=','
if key != 'links': print('"'+str(val)+'"'+sep,end="")
print("\n",end="")
else:
print("NOTE: No JSON Results Found")
# file_accessible
# Check if a file exists and is accessible.
# change history
# 01dec2017 initial development
def file_accessible(filepath, mode):
try:
f = open(filepath, mode)
f.close()
except IOError as e:
return False
return True
# printresult
# prints the results in the style requested
# change history
# 28oct2018 initial development
# 22dec2018 add csv columns only relevent for csv output, defaults provided but can be overriden when called
def printresult(result,output_style,colsforcsv=["id","name","type","description","creationTimeStamp","modifiedTimeStamp"]):
# print rest call results
if type(result) is dict:
if output_style=='simple':
simpleresults(result)
elif output_style=='csv':
csvresults(result,columns=colsforcsv)
else:
print(json.dumps(result,indent=2))
else: print(result)
# getprofileinfo
# prints the token expiration, endpoint and current user
# change history
# 20nov2018 initial development
def getprofileinfo(myprofile):
#get authentication information for the header
credential_file=os.path.join(os.path.expanduser('~'),'.sas','credentials.json')
# check that credential file is available and can be read
access_file=file_accessible(credential_file,'r')
if access_file==False:
print("ERROR: Cannot read authentication credentials at: ", credential_file)
print("ERROR: Try refreshing your token with sas-admin auth login")
sys.exit()
with open(credential_file) as json_file:
data = json.load(json_file)
type(data)
# the sas-admin profile init creates an empty credential file
# check that credential is in file, if it is add it to the header, if not exit
# get the profile environment variable to use it
# if it is not set default to the default profile
if myprofile in data:
expiry=data[myprofile]['expiry']
print("Note your authentication token expires at: "+expiry)
else:
print("ERROR: access token not in file: ", credential_file)
print("ERROR: Try refreshing your token with sas-admin auth login")
sys.exit()
# note the path to the profile is hard-coded right now
endpointfile=os.path.join(os.path.expanduser('~'),'.sas','config.json')
access_file=file_accessible(endpointfile,'r')
#profile does not exist
if access_file==False:
print("ERROR: Cannot read CLI profile at:",endpointfile,". Recreate profile with sas-admin profile init.")
sys.exit()
#profile is empty file
if os.stat(endpointfile).st_size==0:
print("ERROR: Cannot read CLI profile empty file at:",endpointfile,". Recreate profile with sas-admin profile init.")
sys.exit()
# get json from profile
with open(endpointfile) as json_file:
data = json.load(json_file)
# check that information is in profile
if myprofile in data:
baseurl=data[myprofile]['sas-endpoint']
print("Endpoint is: "+baseurl)
else:
print("ERROR: profile "+myprofile+" does not exist. Recreate profile with sas-admin profile init.")
# build the request parameters
reqval="/identities/users/@currentUser"
reqtype='get'
result=callrestapi(reqval,reqtype)
if result==None:
print("NOTE: Not logged in.")
else:
print("Logged on as id: "+ result['id'])
print("Logged on as name: "+result['name'])
# getpath
# when a Viya objectURI is passed in return the path
# change history
# 14JAN2019 initial development
def getpath(objecturi):
# build the request parameters
reqval='/folders/ancestors?childUri='+objecturi
reqtype='get'
accept='application/vnd.sas.content.folder.ancestor+json'
ancestors_result_json=callrestapi(reqval,reqtype,accept)
#print(ancestors_result_json)
if not 'ancestors' in ancestors_result_json:
print("NOTE: Could not get ancestor folders of ObjectURI '"+objecturi+"'.")
path=None
else:
ancestors = ancestors_result_json['ancestors']
path=''
#For each principle's section in the explanations section of the data returned from the REST API call...
for ancestor in ancestors:
path=ancestor['name']+'/'+path
path='/'+path
return path