-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.py
798 lines (688 loc) · 19.6 KB
/
server.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
""""Controllers for TRS endpoints."""
import logging
from typing import (Optional, Dict, List, Tuple)
from urllib.parse import unquote
from flask import (request, current_app)
from foca.utils.logging import log_traffic
from trs_filer.errors.exceptions import (
BadRequest,
InternalServerError,
NotFound,
)
from trs_filer.ga4gh.trs.endpoints.register_objects import (
RegisterTool,
RegisterToolVersion,
)
from trs_filer.ga4gh.trs.endpoints.register_tool_classes import (
RegisterToolClass
)
from trs_filer.ga4gh.trs.endpoints.service_info import (
RegisterServiceInfo,
)
logger = logging.getLogger(__name__)
@log_traffic
def toolsIdGet(
id: str
) -> Dict:
"""List one specific tool, acts as an anchor for self references.
Args:
id: Tool identifier.
Returns:
Tool object dict corresponding given tool id.
Raise:
NotFound if no object mapping with given id present.
"""
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
obj = db_coll_tools.find_one({"id": id})
if obj is None:
raise NotFound
del obj["_id"]
if "versions" in obj:
for _version in obj["versions"]:
if "files" in _version:
del _version["files"]
return obj
@log_traffic
def toolsIdVersionsGet(
id: str
) -> List[Dict]:
"""List versions of a tool.
Args:
id: Tool identifier.
Returns:
List of version dicts corresponding given tool id.
"""
obj = toolsIdGet.__wrapped__(id)
return obj["versions"]
@log_traffic
def toolsIdVersionsVersionIdGet(
id: str,
version_id: str,
) -> Dict:
"""
List one specific tool version, acts as an anchor for self references.
Args:
id: Tool identifier.
version_id: Tool version identifier.
Returns:
Specific version dict of the given tool.
Raises:
NotFound if no tool object present for give id mapping. Also, if
version with given id not found.
"""
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
proj = {
'_id': False,
'versions': {
'$elemMatch': {
'id': version_id,
},
},
}
data = db_coll_tools.find_one(
filter={'id': id},
projection=proj,
)
try:
version = data['versions'][0]
if version and 'files' in version:
del version['files']
return version
except (KeyError, TypeError):
raise NotFound
@log_traffic
def toolsGet(
id: Optional[str] = None,
alias: Optional[str] = None,
toolClass: Optional[str] = None,
descriptorType: Optional[str] = None,
registry: Optional[str] = None,
organization: Optional[str] = None,
name: Optional[str] = None,
toolname: Optional[str] = None,
description: Optional[str] = None,
author: Optional[str] = None,
checker: Optional[bool] = None,
limit: Optional[int] = 1000, # default as per specs
offset: Optional[str] = None,
) -> Tuple[List, str, Dict]:
"""List all tools.
Filter parameters to subset the tools list can be specified. Filter
parameters are additive.
Args:
id: Return only entries with the given identifier.
alias: Return only entries with the given alias.
toolClass: Return only entries with the given subclass name.
descriptorType: Return only entries with the given descriptor type.
registry: Return only entries from the given registry.
organization: Return only entries from the given organization.
name: Return only entries with the given image name.
toolname: Return only entries with the given tool name.
description: Return only entries with the given description.
author: Return only entries from the given author.
checker: Return only checker workflows.
limit: Number of records when paginating results.
offset: Start index when paginating results.
Returns:
List of all tools consistent with all filters, if specified.
"""
# set filters
filt = {}
if id is not None:
filt['id'] = id
if alias is not None:
filt['aliases'] = {
'$in': [alias],
}
if toolClass is not None:
filt['toolclass.name'] = toolClass
if descriptorType:
filt['versions'] = {
'$elemMatch': {
'descriptor_type': {
'$in': [descriptorType],
},
},
}
if registry is not None:
filt['versions'] = {
'$elemMatch': {
'images': {
'$elemMatch': {
'registry_host': registry,
},
},
},
}
if organization is not None:
filt['organization'] = organization
if name is not None:
filt['versions'] = {
'$elemMatch': {
'images': {
'$elemMatch': {
'image_name': name,
},
},
},
}
if toolname is not None:
filt['name'] = toolname
if description is not None:
filt['description'] = description
if author:
filt['versions'] = {
'$elemMatch': {
'author': {
'$in': [author],
},
},
}
if checker is not None:
filt['has_checker'] = checker
logger.info(f"offset {offset} limit {limit} ")
# offset validation
if(offset is None):
offset_int = 0
elif (offset is not None and int(offset) < 0):
return [], '422', {}
else:
offset_int = int(offset)
# limit validation
if(limit is not None and int(limit) < 0):
return [], '422', {}
# fetch data
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
records = db_coll_tools.find(
filter=filt,
projection={"_id": False},
).sort(
# Sort results by descending object ID (+/- oldest to newest)
'_id', 1
).skip(
# Skip number of records by given offset
offset_int
).limit(
# Implement page size limit
limit
)
records = list(records)
for record in records:
if 'versions' in record:
for _version in record['versions']:
if 'files' in _version:
del _version['files']
previous_page_url = (
f"{request.base_url}?offset={max(offset_int - limit, 0)}"
f"&limit={limit}"
)
next_page_url = (
f"{request.base_url}?offset={offset_int + limit}&limit={limit}"
)
headers = {}
headers['next_page'] = next_page_url
headers['last_page'] = previous_page_url
headers['self_link'] = f"{request.url}"
headers['current_offset'] = str(offset_int)
headers['current_limit'] = limit
return records, '200', headers
@log_traffic
def toolsIdVersionsVersionIdTypeDescriptorGet(
type: str,
id: str,
version_id: str,
) -> Dict:
"""Get the tool descriptor for the specified tool.
Args:
type: The output type of the descriptor. Allowable values include
"CWL", "WDL", "NFL", "GALAXY".
id: Tool identifier.
version_id: Identifier to the tool version of the given tool `id`.
Returns:
The tool descriptor. Plain types return the bare descriptor while the
"non-plain" types return a descriptor wrapped with metadata.
"""
validate_descriptor_type(type=type)
ret = {}
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
proj = {
'_id': False,
'versions': {
'$elemMatch': {
'id': version_id,
},
},
}
data = db_coll_tools.find(
filter={'id': id},
projection=proj,
)
try:
version_files_data = data[0]['versions'][0]['files']
for _d in version_files_data:
if (
_d['tool_file']['file_type'] == 'PRIMARY_DESCRIPTOR' and
_d['type'] == type
):
ret = _d['file_wrapper']
except (IndexError, KeyError, TypeError):
raise NotFound
if not ret:
raise NotFound
return ret
@log_traffic
def toolsIdVersionsVersionIdTypeDescriptorRelativePathGet(
type: str,
id: str,
version_id: str,
relative_path: str,
) -> Dict:
"""Get additional tool descriptor files relative to the main file.
Args:
type: The output type of the descriptor. Examples of allowable
values are "CWL", "WDL", "NFL", "GALAXY".
id: Tool identifier.
version_id: Tool version identifier.
relative_path: A relative path to the additional file (same directory
or subdirectories), for example 'foo.cwl' would return a 'foo.cwl'
from the same directory as the main descriptor. Needs to be percent/url
encoded/quoted.
Returns:
Additional files associated with a given descriptor type of a given
tool version.
"""
logger.debug(f"Encoded relative path: '{relative_path}'")
relative_path = unquote(relative_path)
logger.debug(f"Decoded relative path: '{relative_path}'")
ret = {}
validate_descriptor_type(type=type)
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
proj = {
'_id': False,
'versions': {
'$elemMatch': {
'id': version_id,
},
},
}
data = db_coll_tools.find(
filter={'id': id},
projection=proj,
)
file_types = [
'OTHER',
'TEST_FILE',
'PRIMARY_DESCRIPTOR',
'SECONDARY_DESCRIPTOR',
]
try:
version_data = data[0]['versions'][0]['files']
for _d in version_data:
if (
_d['tool_file']['path'] == relative_path and
_d['tool_file']['file_type'] in file_types and
_d['type'] == type
):
ret = _d['file_wrapper']
except (IndexError, KeyError, TypeError):
raise NotFound
if not ret:
raise NotFound
return ret
@log_traffic
def toolsIdVersionsVersionIdTypeTestsGet(
type: str,
id: str,
version_id: str,
) -> List:
"""Get a list of test JSONs.
Args:
type: The output type of the descriptor. Examples of allowable
values are "CWL", "WDL", "NFL", "GALAXY".
id: Tool identifier.
version_id: Tool version identifier.
Returns:
List of JSONs associated with a given descriptor type of a given
tool version.
"""
validate_descriptor_type(type=type)
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
proj = {
'_id': False,
'versions': {
'$elemMatch': {
'id': version_id,
'files': {
'$elemMatch': {
'type': type,
'tool_file.file_type': 'TEST_FILE',
},
},
},
},
}
data = db_coll_tools.find(
filter={'id': id},
projection=proj,
)
try:
ret_array = []
version_data = data[0]['versions'][0]['files']
for _d in version_data:
if (
_d['tool_file']['file_type'] == 'TEST_FILE' and
_d['type'] == type
):
ret_array.append(_d['file_wrapper'])
except (IndexError, KeyError, TypeError):
raise NotFound
return ret_array
@log_traffic
def toolsIdVersionsVersionIdTypeFilesGet(
type: str,
id: str,
version_id: str,
format: Optional[str] = None,
) -> List:
"""Get the tool_file specification(s) for the specified tool version.
Args:
type: The output type of the descriptor. Examples of allowable
values are "CWL", "WDL", "NFL", "GALAXY".
id: Tool identifier.
version_id: Tool version identifier.
Returns:
List of file JSON responses.
"""
validate_descriptor_type(type=type)
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
proj = {
'_id': False,
'versions': {'$elemMatch': {'id': version_id}},
}
data = db_coll_tools.find_one(
filter={'id': id},
projection=proj,
)
file_types = [
'OTHER',
'TEST_FILE',
'PRIMARY_DESCRIPTOR',
'SECONDARY_DESCRIPTOR',
]
try:
data = data['versions'][0]
ret = [
d['tool_file'] for d in data['files']
if d['type'] == type and d['tool_file']['file_type'] in file_types
]
except (IndexError, KeyError, TypeError):
raise NotFound
return ret
@log_traffic
def toolsIdVersionsVersionIdContainerfileGet(
id: str,
version_id: str,
) -> List[Dict]:
"""Get the container specification(s) for the specified tool version.
Args:
id: Tool identifier.
version_id: Tool version identifier.
Returns:
List of wrapped containerfile objects.
"""
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
proj = {
'_id': False,
'versions': {'$elemMatch': {'id': version_id}},
}
data = db_coll_tools.find_one(
filter={'id': id},
projection=proj,
)
try:
data = data['versions'][0]
ret = [
d['file_wrapper'] for d in data['files']
if d['tool_file']['file_type'] == 'CONTAINERFILE'
]
except (IndexError, KeyError, TypeError):
raise NotFound
if not ret:
raise NotFound
return ret
@log_traffic
def toolClassesGet(
) -> List:
"""List all tool classes.
Returns:
List of tool class objects.
"""
db_collection_class = (
current_app.config.foca.db.dbs['trsStore']
.collections['toolclasses'].client
)
records = db_collection_class.find(
filter={},
projection={"_id": False},
)
return list(records)
@log_traffic
def getServiceInfo() -> Dict:
"""Show information about this service.
Returns:
An empty 201 response with headers.
"""
service_info = RegisterServiceInfo()
return service_info.get_service_info()
@log_traffic
def postServiceInfo() -> Tuple[None, str, Dict]:
"""Show information about this service.
Returns:
An empty 201 response with headers.
"""
service_info = RegisterServiceInfo()
headers = service_info.set_service_info_from_app_context(data=request.json)
return None, '201', headers
@log_traffic
def postTool() -> str:
"""Add tool with an auto-generated ID.
Returns:
Identifier of created tool.
"""
tool = RegisterTool(data=request.json)
tool.register_metadata()
return tool.data['id']
@log_traffic
def putTool(
id: str,
) -> str:
"""Add/replace tool with a user-supplied ID.
Args:
id: Identifier of tool to be created/updated.
Returns:
Identifier of created/updated tool.
"""
tool = RegisterTool(
data=request.json,
id=id,
)
tool.register_metadata()
return tool.data['id']
@log_traffic
def deleteTool(
id: str,
) -> str:
"""Delete tool.
Args:
id: Identifier of tool to be deleted.
Returns:
Previous identifier of deleted tool.
"""
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
del_obj_tools = db_coll_tools.delete_one({'id': id})
if del_obj_tools.deleted_count:
return id
else:
raise NotFound
@log_traffic
def postToolVersion(
id: str,
) -> str:
"""Add tool version with an auto-generated ID.
Args:
id: Identifier of tool to be modified.
Returns:
Identifier of created tool version.
"""
version = RegisterToolVersion(
id=id,
data=request.json,
)
version.register_metadata()
return version.data['id']
@log_traffic
def putToolVersion(
id: str,
version_id: str,
) -> str:
"""Add/replace tool version with a user-supplied ID.
Args:
id: Identifier of tool to be modified.
id: Identifier of tool to be created/updated.
Returns:
Identifier of created tool version.
"""
version = RegisterToolVersion(
id=id,
version_id=version_id,
data=request.json,
)
version.register_metadata()
return version.data['id']
@log_traffic
def deleteToolVersion(
id: str,
version_id: str,
) -> str:
"""Delete tool version.
Args:
id: Identifier of tool to be modified.
version_id: Identifier of tool version to be deleted.
Returns:
Previous identifier of deleted tool version. Note that a
`BadRequest/400` error response is returned if attempting to delete
the only remaining tool version.
"""
db_coll_tools = (
current_app.config.foca.db.dbs['trsStore']
.collections['tools'].client
)
filt = {
'id': id,
'versions.id': version_id,
}
update = {
'$pull': {
'versions': {'id': version_id},
},
}
del_ver_tools = db_coll_tools.update_one(
filter=filt,
update=update,
)
if not del_ver_tools.matched_count:
raise NotFound
elif not del_ver_tools.modified_count:
raise InternalServerError
else:
return version_id
@log_traffic
def postToolClass() -> str:
"""Add tool class with an auto-generated ID.
Returns:
Identifier of created tool class.
"""
tool_class = RegisterToolClass(data=request.json)
tool_class.register_metadata()
return tool_class.data['id']
@log_traffic
def putToolClass(
id: str,
) -> str:
"""Add tool class with a user-supplied ID.
Args:
id: Identifier of tool class to be created/updated.
Returns:
Identifier of created/updated tool class.
"""
tool_class = RegisterToolClass(
data=request.json,
id=id,
)
tool_class.register_metadata()
print(tool_class.data['id'])
return tool_class.data['id']
@log_traffic
def deleteToolClass(
id: str,
) -> str:
"""Delete tool class.
Args:
id: Identifier of tool class to be deleted.
Returns:
Previous identifier of deleted tool class. Note that a `BadRequest/400`
error response is returned if attempting to delete a tool class that
is associated with any tool.
"""
db_coll_classes = (
current_app.config.foca.db.dbs['trsStore']
.collections['toolclasses'].client
)
# do not allow deleting tool class associated with tool
if id in [t['toolclass']['id'] for t in toolsGet.__wrapped__()[0]]:
raise BadRequest
if db_coll_classes.delete_one({'id': id}).deleted_count:
return id
else:
raise NotFound
def validate_descriptor_type(type: str) -> None:
"""Validate tool descriptor type.
Args:
type: Descriptor type, e.g., NFL".
Raises:
BadRequest: Provided descriptor type is invalid.
"""
valid_types = [f"PLAIN_{t}" for t in RegisterToolVersion.descriptor_types]
valid_types += RegisterToolVersion.descriptor_types
if type not in valid_types:
logger.error(
f"Specified type '{type}' not among valid types: {valid_types}'"
)
raise BadRequest