/
api.py
800 lines (699 loc) · 34.1 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
import cgi
import copy
import importlib
import io
import logging
import mimetypes
import os
import warnings
from http import HTTPStatus
from urllib.parse import quote, unquote, urlencode, urlparse
import requests
from airavata.model.data.replica.ttypes import (
DataProductModel,
DataProductType,
DataReplicaLocationModel,
ReplicaLocationCategory,
ReplicaPersistentType
)
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from airavata_django_portal_sdk.user_storage.backends.base import (
ProvidesDownloadUrl
)
from ..util import convert_iso8601_to_datetime
logger = logging.getLogger(__name__)
TMP_INPUT_FILE_UPLOAD_DIR = "tmp"
def get_user_storage_provider(request, owner_username=None, storage_resource_id=None):
# TODO: default the module_class_name to MFT provider
module_class_name = None
options = {}
if storage_resource_id is None:
if not hasattr(settings, 'USER_STORAGES'):
# make this backward compatible with the older settings
module_class_name = 'airavata_django_portal_sdk.user_storage.backends.DjangoFileSystemProvider'
storage_resource_id = settings.GATEWAY_DATA_STORE_RESOURCE_ID
options = dict(directory=settings.GATEWAY_DATA_STORE_DIR)
logger.warning("Please add the USER_STORAGES setting. Using legacy GATEWAY_DATA_STORE_RESOURCE_ID and GATEWAY_DATA_STORE_DIR settings.")
else:
conf = settings.USER_STORAGES["default"]
module_class_name = conf['BACKEND']
storage_resource_id = conf['STORAGE_RESOURCE_ID']
options = conf.get('OPTIONS', {})
else:
if not hasattr(settings, 'USER_STORAGES'):
# make this backward compatible with the older settings
module_class_name = 'airavata_django_portal_sdk.user_storage.backends.DjangoFileSystemProvider'
storage_resource_id = settings.GATEWAY_DATA_STORE_RESOURCE_ID
options = dict(directory=settings.GATEWAY_DATA_STORE_DIR)
logger.warning("Please add the USER_STORAGES setting. Using legacy GATEWAY_DATA_STORE_RESOURCE_ID and GATEWAY_DATA_STORE_DIR settings.")
else:
for key in settings.USER_STORAGES:
conf = settings.USER_STORAGES[key]
if conf['STORAGE_RESOURCE_ID'] == storage_resource_id:
module_class_name = conf['BACKEND']
options = conf.get('OPTIONS', {})
break
module_name, class_name = module_class_name.rsplit(".", 1)
module = importlib.import_module(module_name)
BackendClass = getattr(module, class_name)
authz_token = request.authz_token
context = {
'request': request,
'owner_username': owner_username,
}
instance = BackendClass(authz_token, storage_resource_id, context=context, **options)
return instance
def save(request, path, file, name=None, content_type=None, storage_resource_id=None):
"Save file in path in the user's storage and return DataProduct."
if _is_remote_api():
if name is None and hasattr(file, 'name'):
name = os.path.basename(file.name)
files = {'file': (name, file, content_type)
if content_type is not None else file, }
resp = _call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
method="post",
files=files)
data = resp.json()
product_uri = data['uploaded']['productUri']
data_product = request.airavata_client.getDataProduct(
request.authz_token, product_uri)
return data_product
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
storage_resource_id, resource_path = backend.save(path, file, name=name, content_type=content_type)
data_product = _save_data_product(
request, resource_path, storage_resource_id, name=name, content_type=content_type, backend=backend
)
return data_product
def save_input_file(request, file, name=None, content_type=None, storage_resource_id=None):
"""Save input file in staging area for input files."""
if _is_remote_api():
if name is None and hasattr(file, 'name'):
name = os.path.basename(file.name)
files = {'file': (name, file, content_type)
if content_type is not None else file, }
resp = _call_remote_api(request,
"/upload",
method="post",
files=files)
data = resp.json()
product_uri = data['data-product']['productUri']
data_product = request.airavata_client.getDataProduct(
request.authz_token, product_uri)
return data_product
else:
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
file_name = name if name is not None else os.path.basename(file.name)
storage_resource_id, resource_path = backend.save(
TMP_INPUT_FILE_UPLOAD_DIR, file, name=file_name)
data_product = _save_data_product(
request, resource_path, storage_resource_id, name=name, content_type=content_type, backend=backend
)
return data_product
def copy_input_file(request, data_product=None, data_product_uri=None, storage_resource_id=None):
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
source_storage_resource_id, source_resource_path = _get_replica_resource_id_and_filepath(data_product)
source_backend = get_user_storage_provider(request,
owner_username=data_product.ownerName,
storage_resource_id=source_storage_resource_id)
file = source_backend.open(source_resource_path)
name = data_product.productName
target_backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
storage_resource_id, full_path = target_backend.save(TMP_INPUT_FILE_UPLOAD_DIR, file, name=name)
return _save_copy_of_data_product(request, full_path, data_product, storage_resource_id)
def is_input_file(request, data_product=None, data_product_uri=None):
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
if _is_remote_api():
resp = _call_remote_api(
request,
"/data-products/",
params={'product-uri': data_product.productUri})
data = resp.json()
return data['isInputFileUpload']
# Check if file is one of user's files and in TMP_INPUT_FILE_UPLOAD_DIR
storage_resource_id, path = _get_replica_resource_id_and_filepath(data_product)
backend = get_user_storage_provider(request,
owner_username=data_product.ownerName,
storage_resource_id=storage_resource_id)
if backend.exists(path):
directories, files = backend.get_metadata(path)
rel_path = files[0]['path']
return os.path.dirname(rel_path) == TMP_INPUT_FILE_UPLOAD_DIR
else:
return False
def move(request, data_product=None, path=None, data_product_uri=None, storage_resource_id=None):
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
source_storage_resource_id, source_path = _get_replica_resource_id_and_filepath(data_product)
source_backend = get_user_storage_provider(request,
owner_username=data_product.ownerName,
storage_resource_id=source_storage_resource_id)
file = source_backend.open(source_path)
file_name = data_product.productName
target_backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
storage_resource_id, full_path = target_backend.save(path, file, name=file_name)
data_product_copy = _save_copy_of_data_product(request, full_path, data_product, storage_resource_id)
# Remove the source file and data product metadata
source_backend.delete(source_path)
_delete_data_product(data_product.ownerName, source_path)
return data_product_copy
def move_input_file(request, data_product=None, path=None, data_product_uri=None, storage_resource_id=None):
warnings.warn("Use 'move' instead.", DeprecationWarning)
return move(request, data_product=data_product, path=path, data_product_uri=data_product_uri, storage_resource_id=storage_resource_id)
def get_download_url(request, data_product=None, data_product_uri=None):
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
storage_resource_id, path = _get_replica_resource_id_and_filepath(data_product)
backend = get_user_storage_provider(request,
owner_username=data_product.ownerName,
storage_resource_id=storage_resource_id)
if isinstance(backend, ProvidesDownloadUrl):
return backend.get_download_url(path)
else:
# if backend doesn't provide a download url, then use default one
# that uses backend to read the file
return (reverse("airavata_django_portal_sdk:download_file") + "?" +
urlencode({"data-product-uri": data_product.productUri}))
def get_lazy_download_url(request, data_product=None, data_product_uri=None):
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
# /download will call get_download_url and redirect to it
return (reverse("airavata_django_portal_sdk:download") + "?" +
urlencode({"data-product-uri": data_product.productUri}))
def open_file(request, data_product=None, data_product_uri=None):
"""
Return file object for replica if it exists in user storage. One of
`data_product` or `data_product_uri` is required.
"""
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
if _is_remote_api():
resp = _call_remote_api(
request,
"/download",
params={'data-product-uri': data_product.productUri})
file = io.BytesIO(resp.content)
disposition = resp.headers['Content-Disposition']
disp_value, disp_params = cgi.parse_header(disposition)
# Give the file object a name just like a real opened file object
file.name = disp_params['filename']
return file
else:
storage_resource_id, path = _get_replica_resource_id_and_filepath(data_product)
backend = get_user_storage_provider(request,
owner_username=data_product.ownerName,
storage_resource_id=storage_resource_id)
return backend.open(path)
def exists(request, data_product=None, data_product_uri=None):
"""
Return True if replica for data_product exists in user storage. One of
`data_product` or `data_product_uri` is required.
"""
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
if _is_remote_api():
resp = _call_remote_api(
request,
"/data-products/",
params={'product-uri': data_product.productUri})
data = resp.json()
return data['downloadURL'] is not None
else:
storage_resource_id, path = _get_replica_resource_id_and_filepath(data_product)
backend = get_user_storage_provider(request,
owner_username=data_product.ownerName,
storage_resource_id=storage_resource_id)
return backend.exists(path)
def dir_exists(request, path, storage_resource_id=None):
"Return True if path exists in user's data store."
if _is_remote_api():
resp = _call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
raise_for_status=False)
if resp.status_code == HTTPStatus.NOT_FOUND:
return False
resp.raise_for_status()
return resp.json()['isDir']
else:
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
return backend.is_dir(path)
def user_file_exists(request, path, storage_resource_id=None):
"""If file exists, return data product URI, else None."""
if _is_remote_api():
resp = _call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
raise_for_status=False)
if resp.status_code == HTTPStatus.NOT_FOUND or resp.json()['isDir']:
return None
resp.raise_for_status()
return resp.json()['files'][0]['dataProductURI']
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
if backend.is_file(path):
_, files = backend.get_metadata(path)
full_path = files[0]['resource_path']
data_product_uri = _get_data_product_uri(request, full_path, backend.resource_id)
return data_product_uri
else:
return None
def delete_dir(request, path, storage_resource_id=None):
"""Delete path in user's data store, if it exists."""
if _is_remote_api():
resp = _call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
method="delete",
raise_for_status=False)
_raise_404(resp, f"File path does not exist {path}")
resp.raise_for_status()
return
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
backend.delete(path)
def delete_user_file(request, path, storage_resource_id=None):
"""Delete file in user's data store, if it exists."""
if _is_remote_api():
resp = _call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
method="delete",
raise_for_status=False)
_raise_404(resp, f"File path does not exist {path}")
resp.raise_for_status()
return
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
backend.delete(path)
def update_file_content(request, path, fileContentText, storage_resource_id=None):
if _is_remote_api():
_call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
method="put",
data={"fileContentText": fileContentText}
)
return
else:
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
file = io.StringIO(fileContentText)
backend.update(path, file)
def update_data_product_content(request, data_product=None, fileContentText="", data_product_uri=None):
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
if _is_remote_api():
_call_remote_api(request,
"/data-products/",
params={'product-uri': data_product.productUri},
method="put",
data={"fileContentText": fileContentText},
)
return
storage_resource_id, path = _get_replica_resource_id_and_filepath(data_product)
update_file_content(request, path, fileContentText, storage_resource_id=storage_resource_id)
def get_file_metadata(request, path, storage_resource_id=None):
if _is_remote_api():
resp = _call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
raise_for_status=False
)
_raise_404(resp, "User storage file path does not exist")
data = resp.json()
if data["isDir"]:
raise Exception("User storage path is a directory, not a file")
file = data['files'][0]
file['created_time'] = convert_iso8601_to_datetime(file['createdTime'])
file['mime_type'] = file['mimeType']
file['data-product-uri'] = file['dataProductURI']
return file
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
if backend.is_file(path):
_, files = backend.get_metadata(path)
file = files[0]
data_product_uri = _get_data_product_uri(request, file['resource_path'],
storage_resource_id=backend.resource_id)
data_product = request.airavata_client.getDataProduct(
request.authz_token, data_product_uri)
mime_type = None
if 'mime-type' in data_product.productMetadata:
mime_type = data_product.productMetadata['mime-type']
file['data-product-uri'] = data_product_uri
file['mime_type'] = mime_type
return file
else:
raise ObjectDoesNotExist("File does not exist at that path.")
def get_file(request, path, storage_resource_id=None):
warnings.warn("Use 'get_file_metadata' instead.", DeprecationWarning)
return get_file_metadata(request, path, storage_resource_id)
def delete(request, data_product=None, data_product_uri=None):
"""
Delete replica for data product in this data store. One of `data_product`
or `data_product_uri` is required.
"""
if data_product is None:
data_product = _get_data_product(request, data_product_uri)
if _is_remote_api():
_call_remote_api(
request,
"/delete-file",
params={'data-product-uri': data_product.productUri},
method="delete")
return
else:
storage_resource_id, path = _get_replica_resource_id_and_filepath(data_product)
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
try:
backend.delete(path)
_delete_data_product(data_product.ownerName, path)
except Exception:
logger.exception(
"Unable to delete file {} for data product uri {}".format(
path, data_product.productUri
)
)
raise
def listdir(request, path, storage_resource_id=None):
"""Return a tuple of two lists, one for directories, the second for files."""
if _is_remote_api():
resp = _call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
)
data = resp.json()
for directory in data['directories']:
# Convert JSON ISO8601 timestamp to datetime instance
directory['created_time'] = convert_iso8601_to_datetime(
directory['createdTime'])
for file in data['files']:
# Convert JSON ISO8601 timestamp to datetime instance
file['created_time'] = convert_iso8601_to_datetime(
file['createdTime'])
file['mime_type'] = file['mimeType']
file['data-product-uri'] = file['dataProductURI']
return data['directories'], data['files']
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
directories, files = backend.get_metadata(path)
# Mark the TMP_INPUT_FILE_UPLOAD_DIR directory as hidden in the UI
for directory in directories:
directory['hidden'] = directory['path'] == TMP_INPUT_FILE_UPLOAD_DIR
# for each file, lookup or register a data product and enrich the file
# metadata with data-product-uri and mime-type
for file in files:
data_product_uri = _get_data_product_uri(request, file['resource_path'],
storage_resource_id=backend.resource_id,
backend=backend)
data_product = request.airavata_client.getDataProduct(
request.authz_token, data_product_uri)
mime_type = None
if 'mime-type' in data_product.productMetadata:
mime_type = data_product.productMetadata['mime-type']
file['data-product-uri'] = data_product_uri
file['mime_type'] = mime_type
# TODO: remove this, there's no need for hidden files
file['hidden'] = False
return directories, files
def list_experiment_dir(request, experiment_id, path="", storage_resource_id=None):
"""
List files, directories in experiment data directory. Returns a tuple,
see `listdir`.
"""
if _is_remote_api():
resp = _call_remote_api(request,
"/experiment-storage/{experiment_id}/{path}",
path_params={"path": path,
"experiment_id": experiment_id},
)
data = resp.json()
for directory in data['directories']:
# Convert JSON ISO8601 timestamp to datetime instance
directory['created_time'] = convert_iso8601_to_datetime(
directory['createdTime'])
for file in data['files']:
# Convert JSON ISO8601 timestamp to datetime instance
file['created_time'] = convert_iso8601_to_datetime(
file['createdTime'])
file['mime_type'] = file['mimeType']
file['data-product-uri'] = file['dataProductURI']
return data['directories'], data['files']
experiment = request.airavata_client.getExperiment(
request.authz_token, experiment_id)
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
exp_data_path = experiment.userConfigurationData.experimentDataDir
exp_data_path = os.path.join(exp_data_path, path)
# Implement username override with exp_owner
# exp_owner = experiment.userName
if backend.exists(exp_data_path):
directories, files = backend.get_metadata(exp_data_path)
# for each file, lookup or register a data product and enrich the file
# metadata with data-product-uri and mime-type
for file in files:
data_product_uri = _get_data_product_uri(request, file['resource_path'],
storage_resource_id=backend.resource_id,
backend=backend)
data_product = request.airavata_client.getDataProduct(
request.authz_token, data_product_uri)
mime_type = None
if 'mime-type' in data_product.productMetadata:
mime_type = data_product.productMetadata['mime-type']
file['data-product-uri'] = data_product_uri
file['mime_type'] = mime_type
# TODO: remove this, there's no need for hidden files
file['hidden'] = False
return directories, files
else:
raise ObjectDoesNotExist("Experiment data directory does not exist")
def experiment_dir_exists(request, experiment_id, path="", storage_resource_id=None):
if _is_remote_api():
resp = _call_remote_api(request,
"/experiment-storage/{experiment_id}/{path}",
path_params={"path": path,
"experiment_id": experiment_id},
raise_for_status=False)
if resp.status_code == HTTPStatus.NOT_FOUND:
return False
resp.raise_for_status()
return resp.json()['isDir']
experiment = request.airavata_client.getExperiment(
request.authz_token, experiment_id)
exp_data_path = experiment.userConfigurationData.experimentDataDir
if exp_data_path is None:
return False
# Implement username overide with exp_owner
# exp_owner = experiment.userName
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
return backend.exists(exp_data_path)
def get_experiment_dir(request, project_name=None, experiment_name=None, path=None, storage_resource_id=None):
warnings.warn("Use 'create_user_dir' instead.", DeprecationWarning)
storage_resource_id, resource_path = create_user_dir(request,
dir_names=[project_name, experiment_name],
create_unique=True,
storage_resource_id=storage_resource_id)
return resource_path
def create_user_dir(request, path="", dir_names=(), create_unique=False, storage_resource_id=None):
if _is_remote_api():
logger.debug(f"path={path}")
_call_remote_api(request,
"/user-storage/~/{path}",
path_params={"path": path},
method="post")
return
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
# For backwards compatibility, manufacture the dir_names array as needed
if len(dir_names) == 0:
dir_names = []
while not backend.exists(path):
path, dir_name = os.path.split(path)
if dir_name == '':
raise Exception("Could not find a base directory in which to create directories.")
dir_names.insert(0, dir_name)
storage_resource_id, resource_path = backend.create_dirs(path, dir_names=dir_names, create_unique=create_unique)
return storage_resource_id, resource_path
def get_rel_experiment_dir(request, experiment_id, storage_resource_id=None):
"""Return experiment data dir path relative to user's directory."""
warnings.warn("Use 'list_experiment_dir' instead.", DeprecationWarning)
if _is_remote_api():
resp = _call_remote_api(request,
"/experiments/{experimentId}/",
path_params={"experimentId": experiment_id})
resp.raise_for_status()
return resp.json()['relativeExperimentDataDir']
experiment = request.airavata_client.getExperiment(
request.authz_token, experiment_id)
if (experiment.userConfigurationData and
experiment.userConfigurationData.experimentDataDir):
backend = get_user_storage_provider(request, storage_resource_id=storage_resource_id)
data_dir = experiment.userConfigurationData.experimentDataDir
if backend.exists(data_dir):
directories, _ = backend.get_metadata(os.path.dirname(data_dir))
for directory in directories:
if directory['name'] == os.path.basename(data_dir):
return directory['path']
raise Exception(f"Could not find relative path to experiment data dir {data_dir}")
else:
return None
else:
return None
def _get_data_product_uri(request, full_path, storage_resource_id, owner=None, backend=None):
from airavata_django_portal_sdk import models
if owner is None:
owner = request.user.username
user_file = models.UserFiles.objects.filter(
username=owner, file_path=full_path)
if user_file.exists():
product_uri = user_file[0].file_dpu
else:
data_product = _save_data_product(request, full_path, storage_resource_id, owner=owner, backend=backend)
product_uri = data_product.productUri
return product_uri
def _get_data_product(request, data_product_uri):
return request.airavata_client.getDataProduct(
request.authz_token, data_product_uri)
def _save_data_product(request, full_path, storage_resource_id, name=None, content_type=None, owner=None, backend=None):
"Create, register and record in DB a data product for full_path."
if owner is None:
owner = request.user.username
data_product = _create_data_product(
owner, full_path, storage_resource_id, name=name, content_type=content_type, backend=backend
)
product_uri = _register_data_product(request, full_path, data_product, owner=owner)
data_product.productUri = product_uri
return data_product
def _register_data_product(request, full_path, data_product, owner=None):
if owner is None:
owner = request.user.username
product_uri = request.airavata_client.registerDataProduct(
request.authz_token, data_product
)
from airavata_django_portal_sdk import models
user_file_instance = models.UserFiles(
username=owner,
file_path=full_path,
file_dpu=product_uri)
user_file_instance.save()
return product_uri
def _save_copy_of_data_product(request, full_path, data_product, storage_resource_id):
"""Save copy of a data product with a different path."""
data_product_copy = _copy_data_product(request, data_product, full_path, storage_resource_id)
product_uri = _register_data_product(request, full_path, data_product_copy)
data_product_copy.productUri = product_uri
return data_product_copy
def _copy_data_product(request, data_product, full_path, storage_resource_id):
"""Create an unsaved copy of a data product with different path."""
data_product_copy = copy.copy(data_product)
data_product_copy.productUri = None
data_product_copy.ownerName = request.user.username
data_replica_location = _create_replica_location(
full_path, data_product_copy.productName, storage_resource_id
)
data_product_copy.replicaLocations = [data_replica_location]
return data_product_copy
def _delete_data_product(username, full_path):
# TODO: call API to delete data product from replica catalog when it is
# available (not currently implemented)
from airavata_django_portal_sdk import models
user_file = models.UserFiles.objects.filter(
username=username, file_path=full_path)
if user_file.exists():
user_file.delete()
def _create_data_product(username, full_path, storage_resource_id, name=None, content_type=None, backend=None):
data_product = DataProductModel()
data_product.gatewayId = settings.GATEWAY_ID
data_product.ownerName = username
if name is not None:
file_name = name
else:
file_name = os.path.basename(full_path)
data_product.productName = file_name
data_product.dataProductType = DataProductType.FILE
final_content_type = _determine_content_type(full_path, content_type, backend=backend)
if final_content_type is not None:
data_product.productMetadata = {"mime-type": final_content_type}
data_replica_location = _create_replica_location(full_path, file_name, storage_resource_id)
data_product.replicaLocations = [data_replica_location]
return data_product
def _determine_content_type(full_path, content_type=None, backend=None):
result = content_type
if result is None:
# Try to guess the content-type from file extension
guessed_type, encoding = mimetypes.guess_type(full_path)
result = guessed_type
if result is None or result == "application/octet-stream":
# Check if file is Unicode text by trying to read some of it
try:
if backend is not None:
file = backend.open(full_path)
# Try to decode the first kb as UTF8
file.read(1024).decode('utf-8')
result = "text/plain"
except UnicodeDecodeError:
logger.debug(f"Failed to read as Unicode text: {full_path}")
return result
def _create_replica_location(full_path, file_name, storage_resource_id):
data_replica_location = DataReplicaLocationModel()
data_replica_location.storageResourceId = storage_resource_id
data_replica_location.replicaName = "{} gateway data store copy".format(
file_name)
data_replica_location.replicaLocationCategory = (
ReplicaLocationCategory.GATEWAY_DATA_STORE
)
data_replica_location.replicaPersistentType = ReplicaPersistentType.TRANSIENT
data_replica_location.filePath = quote(full_path)
return data_replica_location
def _get_replica_filepath(data_product):
replica_filepaths = [
rep.filePath
for rep in data_product.replicaLocations
if rep.replicaLocationCategory == ReplicaLocationCategory.GATEWAY_DATA_STORE
]
replica_filepath = replica_filepaths[0] if len(
replica_filepaths) > 0 else None
if replica_filepath:
return unquote(urlparse(replica_filepath).path)
return None
def _get_replica_location(data_product, category=ReplicaLocationCategory.GATEWAY_DATA_STORE):
replica_locations = [
rep
for rep in data_product.replicaLocations
if rep.replicaLocationCategory == ReplicaLocationCategory.GATEWAY_DATA_STORE
]
return replica_locations[0] if len(replica_locations) > 0 else None
def _get_replica_resource_id_and_filepath(data_product):
replica_location = _get_replica_location(data_product)
if replica_location is not None:
return (replica_location.storageResourceId,
unquote(urlparse(replica_location.filePath).path))
else:
return None
def _is_remote_api():
return getattr(settings, 'GATEWAY_DATA_STORE_REMOTE_API', None) is not None
def _call_remote_api(
request,
path,
path_params=None,
method="get",
raise_for_status=True,
**kwargs):
headers = {
'Authorization': f'Bearer {request.authz_token.accessToken}'}
encoded_path_params = {}
if path_params is not None:
for pk, pv in path_params.items():
encoded_path_params[pk] = quote(pv)
encoded_path = path.format(**encoded_path_params)
logger.debug(f"encoded_path={encoded_path}")
r = requests.request(
method,
f'{settings.GATEWAY_DATA_STORE_REMOTE_API}{encoded_path}',
headers=headers,
**kwargs,
)
if raise_for_status:
r.raise_for_status()
return r
def _raise_404(response, msg, exception_class=ObjectDoesNotExist):
if response.status_code == 404:
raise exception_class(msg)