-
Notifications
You must be signed in to change notification settings - Fork 19
/
rdams_client.py
executable file
·576 lines (463 loc) · 15.1 KB
/
rdams_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/env python
"""List dataset metadata, subset data subset requests,
check on request status.
Usage:
```
rdams-client.py -get_summary <dsnnn.n>
rdams-client.py -get_metadata <dsnnn.n> <-f>
rdams-client.py -get_param_summary <dsnnn.n> <-f>
rdams-client.py -submit [control_file_name]
rdams-client.py -get_status <RequestIndex> <-proc_status>
rdams-client.py -download [RequestIndex]
rdams-client.py -globus_download [RequestIndex]
rdams-client.py -get_control_file_template <dsnnn.n>
rdams-client.py -help
```
"""
__version__ = '3.0.0'
__author__ = 'Doug Schuster (schuster@ucar.edu), Riley Conroy (rpconroy@ucar.edu)'
import sys
import os
import requests
import getpass
import json
import argparse
import codecs
import pdb
BASE_URL = 'https://rda.ucar.edu/api/'
DEFAULT_AUTH_FILE = './rdams_token.txt'
# Python 2 compatibility
try:
input = raw_input
except NameError:
pass
def query(args=None):
"""Perform a query based on command line like arguments.
Args:
args (list): argument list of querying commands.
Returns:
(dict): Output of json decoded API query.
Example:
```
>>> query(['-get_status', '123456'])
>>> query(['-get_metadata', 'ds083.2'])
```
"""
parser = get_parser()
if args is None or len(args) == 0:
parser.parse_args(['-h'])
args = parser.parse_args(args)
args_dict = args.__dict__
func,params = get_selected_function(args_dict)
if args_dict['outdir'] and func==download:
out_dir = args_dict['outdir']
return func(params, out_dir)
result = func(params)
if not args.noprint:
print(json.dumps(result, indent=3))
return result
def add_ds_str(ds_num):
"""Adds 'ds' to ds_num if needed.
Throws error if ds number isn't valid.
"""
ds_num = ds_num.strip()
if ds_num[0:2] != 'ds':
ds_num = 'ds' + ds_num
if len(ds_num) != 7:
print("'" + ds_num + "' is not valid.")
sys.exit()
return ds_num
def get_userinfo():
"""Get token from command line."""
print('Please visit https://rda.ucar.edu/accounts/profile/ to access token.')
token = input("Paste that token here: ")
write_token_file(token)
return token
def write_token_file(token, token_file=DEFAULT_AUTH_FILE):
"""Write token to a file."""
with open(token_file, "w") as fo:
fo.write(token)
def read_token_file(token_file):
"""Read user information from token file.
Args:
token_file (str): location of token file.
Returns:
(str): token
"""
with open(token_file, 'r') as f:
token = f.read()
return token.strip()
def read_control_file(control_file):
"""Reads control file, and return python dict.
Args:
control_file (str): Location of control file to parse.
Or control file string.
Returns:
(dict) python dict representing control file.
"""
control_params = {}
if os.path.exists(control_file):
myfile = open(control_file, 'r')
else:
myfile = control_file.split('\n')
for line in myfile:
line = line.strip()
if line.startswith('#') or line == "":
continue
li = line.rstrip()
(key, value) = li.split('=', 2)
control_params[key] = value
# Handle empty params
if 'param' in control_params and control_params['param'].strip() == '':
all_params = get_all_params(control_params['dataset'])
control_params['param'] = '/'.join(all_params)
try:
myfile.close()
except:
pass
return control_params
def get_parser():
"""Creates and returns parser object.
Returns:
(argparse.ArgumentParser): Parser object from which to parse arguments.
"""
description = "Queries NCAR RDA REST API."
parser = argparse.ArgumentParser(prog='rdams', description=description)
parser.add_argument('-noprint', '-np',
action='store_true',
required=False,
help="Do not print result of queries.")
parser.add_argument('-outdir', '-od',
nargs='?',
required=False,
help="Change the output directory of downloaded files")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-get_summary', '-gsum',
type=str,
metavar='<dsid>',
required=False,
help="Get a summary of the given dataset.")
group.add_argument('-get_metadata', '-gm',
type=str,
metavar='<dsid>',
required=False,
help="Get metadata for a given dataset.")
group.add_argument('-get_param_summary', '-gpm',
type=str,
metavar='<dsid>',
required=False,
help="Get only parameters for a given dataset.")
group.add_argument('-submit', '-s',
type=str,
metavar='<control file>',
required=False,
help="Submit a request using a control file.")
group.add_argument('-get_status', '-gs',
type=str,
nargs='?',
const='ALL',
metavar='<Request Index>',
required=False,
help="Get a summary of the given dataset.")
group.add_argument('-download', '-d',
type=str,
required=False,
metavar='<Request Index>',
help="Download data given a request id.")
group.add_argument('-get_filelist', '-gf',
type=str,
required=False,
metavar='<Request Index>',
help="Query the filelist for a completed request.")
group.add_argument('-globus_download', '-gd',
type=str,
required=False,
metavar='<Request Index>',
help="Start a globus transfer for a give request index.")
group.add_argument('-get_control_file_template', '-gt',
type=str,
metavar='<dsid>',
required=False,
help="Get a template control file used for subsetting.")
group.add_argument('-purge', # Sorry no -p
type=str,
metavar='<Request Index>',
required=False,
help="Purge a request.")
return parser
def check_status(ret, token_file=DEFAULT_AUTH_FILE):
"""Checks that status of return object.
Exits if a 401 status code.
Args:
ret (response.Response): Response of a request.
token_file (str) : password file. Will remove if auth incorrect
Returns:
None
"""
if ret.status_code == 401: # Not Authorized
print(ret.content)
exit(1)
def check_file_status(filepath, filesize):
"""Prints file download status as percent of file complete.
Args:
filepath (str): File being downloaded.
filesize (int): Expected total size of file in bytes.
Returns:
None
"""
sys.stdout.write('\r')
sys.stdout.flush()
size = int(os.stat(filepath).st_size)
percent_complete = (size/filesize)*100
sys.stdout.write('%.3f %s' % (percent_complete, '% Completed'))
sys.stdout.flush()
def download_files(filelist, out_dir='./', cookie_file=None):
"""Download files in a list.
Args:
filelist (list): List of web files to download.
out_dir (str): directory to put downloaded files
Returns:
None
"""
for _file in filelist:
file_base = os.path.basename(_file)
out_file = out_dir + file_base
print('Downloading',file_base)
header = requests.head(_file, allow_redirects=True, stream=True)
filesize = int(header.headers['Content-Length'])
req = requests.get(_file, allow_redirects=True, stream=True)
with open(out_file, 'wb') as outfile:
chunk_size=1048576
for chunk in req.iter_content(chunk_size=chunk_size):
outfile.write(chunk)
if chunk_size < filesize:
check_file_status(out_file, filesize)
check_file_status(out_file, filesize)
print()
def encode_url(url, token):
return url + '?token=' + token
def get_authentication(token_file=DEFAULT_AUTH_FILE):
"""Attempts to get authentication.
Args:
token_file (str): location of password file.
Returns:
(tuple): token
"""
if os.path.isfile(token_file) and os.path.getsize(token_file) > 0:
return read_token_file(token_file)
else:
return get_userinfo()
def get_summary(ds):
"""Returns summary of dataset.
Args:
ds (str): Datset id. e.g. 'ds083.2'
Returns:
dict: JSON decoded result of the query.
"""
url = BASE_URL + 'summary/'
url += ds
token = get_authentication()
ret = requests.get(encode_url(url,token))
check_status(ret)
return ret.json()
def get_metadata(ds):
"""Return metadata of dataset.
Args:
ds (str): Datset id. e.g. 'ds083.2'
Returns:
dict: JSON decoded result of the query.
"""
url = BASE_URL + 'metadata/'
url += ds
token = get_authentication()
ret = requests.get(encode_url(url,token))
check_status(ret)
return ret.json()
def get_all_params(ds):
"""Return set of parameters for a dataset.
Args:
ds (str): Datset id. e.g. 'ds083.2'
Returns:
set: All unique params in dataset.
"""
res = get_param_summary(ds)
res_data = res['data']['data']
param_names = set()
for param in res_data:
param_names.add(param['param'])
return param_names
def get_param_summary(ds):
"""Return summary of parameters for a dataset.
Args:
ds (str): Datset id. e.g. 'ds083.2'
Returns:
dict: JSON decoded result of the query.
"""
url = BASE_URL + 'paramsummary/'
url += ds
token = get_authentication()
ret = requests.get(encode_url(url,token))
check_status(ret)
return ret.json()
def submit_json(json_file):
"""Submit a RDA subset or format conversion request using json file or dict.
Args:
json_file (str): json control file to submit.
OR
Python dict to submit.
Returns:
dict: JSON decoded result of the query.
"""
if type(json_file) is str:
assert os.path.isfile(json_file)
with open(json_file) as fh:
control_dict = json.load(fh)
else:
assert type(json_file) is dict
control_dict = json_file
url = BASE_URL + 'submit/'
token = get_authentication()
ret = requests.post(encode_url(url,token), json=control_dict)
check_status(ret)
return ret.json()
def submit(control_file_name):
"""Submit a RDA subset or format conversion request.
Calls submit json after reading control_file
Args:
control_file_name (str): control file to submit.
Returns:
dict: JSON decoded result of the query.
"""
_dict = read_control_file(control_file_name)
return submit_json(_dict)
def get_status(request_idx=None):
"""Get status of request.
If request_ix not provided, get all open requests
Args:
request_idx (str, Optional): Request Index, typcally a 6-digit integer.
Returns:
dict: JSON decoded result of the query.
"""
if request_idx is None:
request_idx = 'ALL'
url = BASE_URL + 'status/'
url += str(request_idx)
token = get_authentication()
ret = requests.get(encode_url(url,token))
check_status(ret)
return ret.json()
def get_filelist(request_idx):
"""Gets filelist for request
Args:
request_idx (str): Request Index, typically a 6-digit integer.
Returns:
dict: JSON decoded result of the query.
"""
url = BASE_URL + 'get_req_files/'
url += str(request_idx)
token = get_authentication()
ret = requests.get(encode_url(url,token))
check_status(ret)
return ret.json()
def download(request_idx, out_dir='./'):
"""Download files given request Index
Args:
request_idx (str): Request Index, typically a 6-digit integer.
Returns:
None
"""
ret = get_filelist(request_idx)
if len(ret['data']) == 0:
return ret
filelist = ret['data']['web_files']
token = get_authentication()
web_files = list(map(lambda x: x['web_path'], filelist))
# Only download unique files.
download_files(set(web_files), out_dir)
return ret
def globus_download(request_idx):
"""Begin a globus transfer.
Args:
request_ix (str): Request Index, typically a 6-digit integer.
Returns:
dict: JSON decoded result of the query.
"""
url = BASE_URL + 'request/'
url += request_idx
url += '-globus_download'
token = get_authentication()
ret = requests.get(encode_url(url,token))
check_status(ret)
return ret.json()
def get_control_file_template(ds):
"""Write a control file for use in subset requests.
Args:
ds (str): datset id. e.g. 'ds083.2'
Returns:
dict: JSON decoded result of the query.
"""
url = BASE_URL + 'control_file_template/'
url += ds
token = get_authentication()
ret = requests.get(encode_url(url,token))
check_status(ret)
return ret.json()
def write_control_file_template(ds, write_location='./'):
"""Write a control file for use in subset requests.
Args:
ds (str): datset id. e.g. 'ds083.2'
write_location (str, Optional): Directory in which to write.
Defaults to working directory
Returns:
dict: JSON decoded result of the query.
"""
_json = get_control_file_template(ds)
control_str = _json['data']['template']
template_filename = write_location + add_ds_str(ds) + '_control.ctl'
if os.path.exists(template_filename):
print(template_filename + " already exists.\nExiting")
exit(1)
with open(template_filename, 'w') as fh:
fh.write(control_str)
return _json
def purge_request(request_idx):
"""Write a control file for use in subset requests.
Args:
ds (str): datset id. e.g. 'ds083.2'
write_location (str, Optional): Directory in which to write.
Defaults to working directory
Returns:
None
"""
url = BASE_URL + 'purge/'
url += request_idx
token = get_authentication()
ret = requests.delete(encode_url(url,token))
check_status(ret)
return ret.json()
def get_selected_function(args_dict):
"""Returns correct function based on options.
Args:
options (dict) : Command with options.
Returns:
(function): function that the options specified
"""
# Maps an argument to function call
action_map = {
'get_summary' : get_summary,
'get_metadata' : get_metadata,
'get_param_summary' : get_param_summary,
'submit' : submit,
'get_status' : get_status,
'download' : download,
'get_filelist' : get_filelist,
'globus_download' : globus_download,
'get_control_file_template' : write_control_file_template,
'purge' : purge_request
}
for opt,value in args_dict.items():
if opt in action_map and value is not None:
return (action_map[opt], value)
if __name__ == "__main__":
"""Calls main method"""
query(sys.argv[1:])