forked from virtual-imaging-platform/VIP-python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVipLauncher.py
More file actions
1888 lines (1758 loc) · 81.1 KB
/
VipLauncher.py
File metadata and controls
1888 lines (1758 loc) · 81.1 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 __future__ import annotations
import json
import os
import re
import textwrap
import time
from contextlib import contextmanager, nullcontext
from pathlib import *
from vip_client.utils import vip
class VipLauncher():
"""
Python class to run VIP pipelines on datasets located on VIP servers.
A single instance allows to run 1 pipeline with 1 parameter set (any number of runs).
Pipeline runs need at least three inputs:
- `pipeline_id` (str) Name of the pipeline.
- `input_settings` (dict) All parameters needed to run the pipeline.
- `output_dir` (str | os.PathLike) Path to the VIP directory where pipeline outputs will be stored.
N.B.: all instance methods require that `VipLauncher.init()` has been called with a valid API key.
See GitHub documentation to get your own VIP API key.
"""
##################
################ Class Attributes ##################
##################
# Class name
__name__ = "VipLauncher"
# Properties to save / display for this class
_PROPERTIES = [
"session_name",
"pipeline_id",
"vip_output_dir",
"input_settings",
"workflows"
]
# Default verbose state
_VERBOSE = True
# Default backup location
# (set to None to avoid saving and loading backup files)
_BACKUP_LOCATION = None
# Default location for VIP inputs/outputs (can be different for subclasses)
_SERVER_NAME = "vip"
# Prefix that defines a path from VIP
_SERVER_PATH_PREFIX = "/vip"
# Default file name to save session properties
_SAVE_FILE = "session_data.json"
# Vip portal
_VIP_PORTAL = "https://vip.creatis.insa-lyon.fr/"
# Mail address for support
_VIP_SUPPORT = "vip-support@creatis.insa-lyon.fr"
# Regular expression for invalid characters (i.e. all except valid characters)
_INVALID_CHARS_FOR_VIP = re.compile(r"[^0-9\.,A-Za-z\-+@/_(): \[\]?&=]")
# List of pipelines available to the user (will evolve after init())
_AVAILABLE_PIPELINES = []
#####################
################ Instance Properties ##################
#####################
# Session Name
@property
def session_name(self) -> str:
"""A name to identify the current Session"""
# Return None if the private attribute is unset
return self._session_name if self._is_defined("_session_name") else None
@session_name.setter
def session_name(self, name: str) -> None:
# Call deleter if agument is None
if name is None:
del self.session_name
return
# Check type
if not isinstance(name, str):
raise TypeError("`session_name` should be a string")
# Check the name for invalid characters
if re.search(r"[^0-9A-Za-z\-_]+", name):
raise ValueError("Session name must contain only alphanumeric characters and hyphens '-', '_'")
# Check conflict with private attribute
if self._is_defined("_session_name"):
self._check_value("_session_name", name)
# Assign
self._session_name = name
@session_name.deleter
def session_name(self) -> None:
# Delete only if the private attribute is defined
if self._is_defined("_session_name"):
del self._session_name
# ------------------------------------------------
# Pipeline identifier
@property
def pipeline_id(self) -> str:
"""Pipeline identifier for VIP"""
# Return None if the private attribute is unset
return self._pipeline_id if self._is_defined("_pipeline_id") else None
@pipeline_id.setter
def pipeline_id(self, pId: str) -> None:
# Display
self._print("Pipeline ID: '%s'" %pId, end="", flush=True)
# Call deleter if agument is None
if pId is None:
del self.pipeline_id
return
# Check type
if not isinstance(pId, str):
raise TypeError("`pipeline_id` should be a string")
# Check the ID (if possible)
if self._check_pipeline_id(pId):
self._print(" --> checked")
else: self._print(" --> unchecked")
# Check for conflict with private attribute
self._check_value("_pipeline_id", pId)
# Set
self._pipeline_id = pId
@pipeline_id.deleter
def pipeline_id(self) -> None:
# Delete only if the private attribute is defined
if self._is_defined("_pipeline_id"):
del self._pipeline_id
# ------------------------------------------------
# Input settings
@property
def input_settings(self) -> dict:
"""All parameters needed to run the pipeline
Run show_pipeline() for more information"""
# Return None if the private attribute is unset
return self._get_input_settings() if self._is_defined("_input_settings") else None
@input_settings.setter
def input_settings(self, input_settings: dict):
# Call deleter if agument is None
if input_settings is None:
del self.input_settings
return
# Display
self._print("Input Settings --> ", end="", flush=True)
# Check type
if not isinstance(input_settings, dict):
raise TypeError("`input_settings` should be a dictionary")
# Check if each input can be converted to a string with valid characters and no empty strings
self._check_invalid_input(input_settings)
# Parse the input settings
new_settings = self._parse_input_settings(input_settings)
self._print("parsed")
# Check conflicts with private attribute
self._check_value("_input_settings", new_settings)
# Update
self._input_settings = new_settings
@input_settings.deleter
def input_settings(self) -> None:
# Delete only if the private attribute is defined
if self._is_defined("_input_settings"):
del self._input_settings
# ------------------------------------------------
# Output directory
@property
def vip_output_dir(self) -> str:
"""Path to the VIP directory where pipeline outputs will be stored"""
# Return None if the private attribute is unset
return str(self._vip_output_dir) if self._is_defined("_vip_output_dir") else None
@vip_output_dir.setter
def vip_output_dir(self, new_dir) -> None:
# Call deleter if agument is None
if new_dir is None:
del self.vip_output_dir
return
# Check type
if not isinstance(new_dir, (str, os.PathLike)):
raise TypeError("`vip_output_dir` should be a string or os.PathLike object")
# Path-ify
new_path = PurePosixPath(new_dir)
# Check if the path contains invalid characters for VIP
invalid = self._invalid_chars_for_vip(new_path)
if invalid:
raise ValueError(
f"VIP output directory contains some invalid character(s): {', '.join(invalid)}"
)
# Check conflict with private attribute
self._check_value("_vip_output_dir", new_path)
# Assign
self._vip_output_dir = new_path
@vip_output_dir.deleter
def vip_output_dir(self) -> None:
# Delete only if the private attribute is defined
if self._is_defined("_vip_output_dir"):
del self._vip_output_dir
# ------------------------------------------------
# Interface for the output directory
@property
def output_dir(self) -> str:
"""
Safe interface for `vip_output_dir`.
Setting `output_dir` will automatically load backup data if any.
"""
return self.vip_output_dir
@output_dir.setter
def output_dir(self, new_dir: str) -> None:
# Call deleter if agument is None
if new_dir is None:
del self.vip_output_dir
return
# Display
self._print("Output directory: '%s'" %new_dir)
# Set the VIP output directory
self.vip_output_dir = new_dir
# Load backup data from the new output directory
self._load()
@output_dir.deleter
def output_dir(self) -> None:
# Delete only if the private attribute is defined
if self._is_defined("vip_output_dir"):
del self.vip_output_dir
# ------------------------------------------------
# Workflows
@property
def workflows(self) -> dict:
"""Workflows inventory"""
# Return empty dict if the private attribute is unset
return self._workflows if self._is_defined("_workflows") else {}
@workflows.setter
def workflows(self, workflows: dict) -> None:
# Check type
if not isinstance(workflows, dict):
raise TypeError("`workflows` should be a dictionary")
# Check conflicts with instance value
self._check_value("_workflows", workflows)
# Assign
self._workflows = workflows
@workflows.deleter
def workflows(self) -> None:
# Delete only if the private attribute is defined
if self._is_defined("_workflows"):
del self._workflows
# ------------------------------------------------
# Verbose state (not deletable)
@property
def verbose(self) -> bool:
"""
This session will displays logs if `verbose` is True.
"""
return self._verbose if self._is_defined("_verbose") else self._VERBOSE
@verbose.setter
def verbose(self, verbose: bool) -> None:
self._verbose = verbose
# -----------------------------------------------
# Lock Properties to avoid accidental confusion between VIP executions
@property
def _locked(self) -> bool:
"""
Boolean for locking session properties.
If True, a property must be deleted before reassignment.
Default value: True
"""
return self._locked_ if self._is_defined("_locked_") else True
@_locked.setter
def _locked(self, new_lock: bool) -> None:
# Set
self._locked_ = new_lock
# -----------------------------------------------
# Pipeline definition (read_only)
@property
def _pipeline_def(self) -> dict:
"""
Gets the full definition of `pipeline_id` from VIP.
Raises TypeError if `pipeline_id` unset.
"""
# Check if the pipeline identifier is set
if not self._is_defined("_pipeline_id"):
raise TypeError("Pipeline identifier is unset")
# Check if the pipeline definition is set
if not self._is_defined("_pipeline_def_"):
self._pipeline_def_ = self._get_pipeline_def(self._pipeline_id)
# Return the attribute
return self._pipeline_def_
# ------------------------------------------------
#############
################ Constructor ##################
#############
def __init__(
self, output_dir=None, pipeline_id: str=None,
input_settings: dict=None, session_name: str=None, verbose: bool=None
) -> None:
"""
Create a VipLauncher instance and sets properties from keyword arguments.
## Parameters
- `output_dir` (str | os.PathLike object) Path to the VIP directory where pipeline outputs will be stored
(does not need to exist).
- `pipeline_id` (str) Name of your pipeline in VIP.
- Usually in format : *application_name*/*version*.
- Run VipLauncher.show_pipeline() to display available pipelines.
- `input_settings` (dict) All parameters needed to run the pipeline.
- Run VipLauncher.show_pipeline(`pipeline_id`) to display these parameters.
- The dictionary can contain any object that can be converted to strings, or lists of such objects.
- Lists of parameters launch parallel workflows on VIP.
- `session_name` [Recommended] (str) A name to identify this session.
Default value: 'VipLauncher-[date]-[time]-[id]'
- `verbose` [Optional] (bool) Verbose mode for this instance.
- If True, instance methods will display logs;
- If False, instance methods will run silently.
`session_name` is only set at instantiation; other properties can be set later in function calls.
If `output_dir` leads to data from a previous session, properties will be loaded from the backup file on VIP.
"""
# Set the verbose mode
self.verbose = verbose if verbose is not None else self._VERBOSE
# Default value for session name
self.session_name = session_name if session_name else self._new_session_name()
# Display the session name only if arguments are given
if any([session_name, output_dir, pipeline_id, input_settings]):
self._print(f"\n=== SESSION '{self._session_name}' ===\n", max_space=2)
# Set the output directory (/!\ this will load the corresponding backup data if any /!\)
if output_dir :
self.output_dir = output_dir
# Unlock session properties
with self._unlocked_properties():
# Set Pipeline identifier
if pipeline_id:
self.pipeline_id = pipeline_id
# Set Input settings
if input_settings:
self.input_settings = input_settings
# Set Workflows inventory
if not self.workflows:
self.workflows = {}
# End display if we're in this class
if any([session_name, output_dir, pipeline_id, input_settings]) and self.__name__ == "VipLauncher":
self._print()
# ------------------------------------------------
################
################ Public Methods ##################
################
#################################################
# ($A) Manage a session from start to finish
#################################################
# ($A.1) Login to VIP
@classmethod
def init(cls, api_key="VIP_API_KEY", verbose=True, vip_portal_url=None,
**kwargs) -> VipLauncher:
"""
Handshakes with VIP using your own API key.
Returns a class instance which properties can be provided as keyword arguments.
## Parameters
- `api_key` (str): VIP API key. This can be either:
A. [unsafe] A **string litteral** containing your API key,
B. [safer] A **path to some local file** containing your API key,
C. [safer] The **name of some environment variable** containing your API key (default: "VIP_API_KEY").
In cases B or C, the API key will be loaded from the local file or the environment variable.
- `verbose` (bool): default verbose mode for all instances.
- If True, all instances will display logs by default;
- If False, all instance methods will run silently by default.
- `kwargs` [Optional] (dict): keyword arguments or dictionnary setting properties of the returned instance.
"""
# Set the default verbose mode for all sessions
cls._VERBOSE = verbose
# Set the VIP portal URL
cls._VIP_PORTAL = vip_portal_url if vip_portal_url else cls._VIP_PORTAL
# Check if `api_key` is in a local file or environment variable
true_key = cls._get_api_key(api_key)
# Set User API key
try:
# setApiKey() may return False
vip.set_vip_url(cls._VIP_PORTAL)
assert vip.setApiKey(true_key), \
f"(!) Unable to set the VIP API key: {true_key}.\nPlease check the key or retry later."
except RuntimeError as vip_error:
# setApiKey() may throw RuntimeError in case of bad key
cls._printc(f"(!) Unable to set the VIP API key: {true_key}.\n Original error message:")
raise vip_error
except(json.decoder.JSONDecodeError) as json_error:
# setApiKey() may throw JSONDecodeError in special cases
cls._printc(f"(!) Unable to set the VIP API key: {true_key}.\n Original error message:")
raise json_error
# Update the list of available pipelines
try:
cls._get_available_pipelines() # RunTimeError is handled downstream
except(json.decoder.JSONDecodeError) as json_error:
# The user still cannot communicate with VIP
cls._printc(f"(!) Unable to communicate with VIP.")
cls._printc(f" Original error messsage:")
raise json_error
cls._printc()
cls._printc("----------------------------------")
cls._printc("| You are communicating with VIP |")
cls._printc("----------------------------------")
cls._printc()
# Double check user can access pipelines
if not cls._AVAILABLE_PIPELINES:
cls._printc("(!) Your API key does not allow you to execute pipelines on VIP.")
cls._printc(f" Please join some research group(s) on the Web portal: {cls._VIP_PORTAL}")
# Return a VipLauncher instance for method cascading
return cls(verbose=(verbose and kwargs), **kwargs)
# ------------------------------------------------
# Launch executions on VIP
def launch_pipeline(
self, pipeline_id: str=None, input_settings: dict=None, output_dir=None, nb_runs=1,
) -> VipLauncher:
"""
Launches pipeline executions on VIP.
Input parameters :
- `pipeline_id` (str) Name of your pipeline in VIP.
Usually in format : *application_name*/*version*.
- `input_settings` (dict) All parameters needed to run the pipeline.
- Run VipSession.show_pipeline(`pipeline_id`) to display these parameters.
- The dictionary can contain any object that can be converted to strings, or lists of such objects.
- Lists of parameters launch parallel workflows on VIP.
- `output_dir` (str) Path to the VIP folder where execution results will be stored.
(Does not need to exist)
- `nb_runs` (int) Number of parallel workflows to launch with the same `pipeline_id`/`input_settings`.
Error profile:
- Raises TypeError:
- if some argmuent could not be checked;
- if some argument is missing;
- if some parameter is missing in `input_settings`.
- Raises ValueError:
- if some argument conflicts with session properties;
- if some parameter in `input_settings` does not the fit the pipeline definition.
- Raises FilenotFoundError if an input file is missing on VIP servers.
- Raises RuntimeError in case of failure from the VIP API.
"""
# First display
self._print("\n=== LAUNCH PIPELINE ===\n")
# Update the parameters
if pipeline_id:
self.pipeline_id = pipeline_id
if output_dir:
self.vip_output_dir = output_dir
if input_settings:
self.input_settings = input_settings
# Start parameter checks
self._print(min_space=1, max_space=1)
self._print("Parameter checks")
self._print("----------------")
# Check the pipeline identifier
self._print("Pipeline identifier: ", end="", flush=True)
if not self._check_pipeline_id():
raise TypeError(f"(!) Pipeline identifier could not be checked. Please call {self.__name__}.init()")
self._print("OK")
# Check the result directory
if not self._is_defined("_vip_output_dir"):
raise TypeError("Please provide an output directory for Session: %s" %self._session_name)
else: self._print("Output directory: ", end="", flush=True)
# Ensure the directory exists
if self._mkdirs(path=self._vip_output_dir, location=self._SERVER_NAME):
self._print(f"Created on {self._SERVER_NAME.upper()}")
else:
self._print("OK")
# Check the input parameters
self._print("Input settings: ", end="", flush=True)
# Check content
self._check_input_settings(location=self._SERVER_NAME)
self._print("OK")
# End parameters checks
self._print("----------------\n")
# Start pipeline launch
self._print("Launching %d new execution(s) on VIP" % nb_runs)
self._print("-------------------------------------")
self._print("Execution Name:", self._session_name)
self._print("Started Workflows:", end="\n\t")
# Launch all executions in parallel
for nEx in range(nb_runs):
# Initiate execution
try:
workflow_id = self._init_exec()
# This part may fail for a number of reasons
except Exception as e:
self._print("\n-------------------------------------")
self._print(f"(!) Stopped after {nEx} execution(s).\n")
self._save()
raise e from None
# Display
self._print(workflow_id, end=", ")
# Get workflow informations
try:
exec_infos = self._get_exec_infos(workflow_id)
except Exception as e:
self._save()
raise e from None
# Create or update workflow entry (depends on init_exec())
if workflow_id in self._workflows:
self._workflows[workflow_id].update(exec_infos)
else:
self._workflows[workflow_id] = exec_infos
# End the application launch
self._print("\n-------------------------------------")
self._print("Done.")
# Save the session
self._save()
# Return
return self
# ------------------------------------------------
# Monitor worflow executions on VIP
def monitor_workflows(self, refresh_time=30) -> VipLauncher:
"""
Updates and displays status for each execution launched in the current session.
- If an execution is still running, updates status every `refresh_time` (seconds) until all runs are done.
- Displays a full report when all executions are done.
Error profile:
- Raises RuntimeError if the client fails to communicate with VIP.
"""
self._print("\n=== MONITOR WORKFLOWS ===\n")
# Check if current session has existing workflows
if not self._workflows:
self._print("This session has not launched any execution.")
self._print("Run launch_pipeline() to launch workflows on VIP.")
return self
# Update existing workflows
self._print("Updating worflow inventory ... ", end="", flush=True)
self._update_workflows()
self._print("Done.")
# Check if workflows are still running
if self._still_running():
# First execution report
self._execution_report()
# Display standby
self._print("\n-------------------------------------------------------------")
self._print("The current proccess will wait until all executions are over.")
self._print("Their progress can be monitored on VIP portal:")
self._print(f"\t{self._VIP_PORTAL}")
self._print("-------------------------------------------------------------")
# Standby until all executions are over
time.sleep(refresh_time)
while self._still_running():
# Keep track of time
start = time.time()
# Update the workflow status & discard connection errors
try:
self._update_workflows()
except Exception as e:
# Print warning message
self._print("(!) Connection with VIP was interrupted following an unexpected error (see below).")
self._print(" This does not affect your executions on VIP servers.")
self._print(" Relaunch monitor_workflows() or visit the VIP portal to see their current status.\n")
# Save the session
self._save()
# Raise the error
raise e
# Sleep until next itertation
elapsed_time = time.time() - start
time.sleep(max(refresh_time - elapsed_time, 0))
# Display the end of executions
self._print("All executions are over.")
# Last execution report
self._execution_report()
# Save the session
self._save()
# Return
return self
# ------------------------------------------------
# Run a full VipLauncher session
def run_session( self, nb_runs=1, refresh_time=30) -> VipLauncher:
"""
Runs a full session from data on VIP servers:
1. Launches pipeline executions on VIP;
2. Monitors pipeline executions until they are all over.
|!| This function assumes that all session properties are already set.
Optional arguments can be provided:
- Increase `nb_runs` to run more than 1 execution at once;
- Set `refresh_time` to modify the default refresh time;
"""
# Run the pipeline
return (
# 1. Launch `nb_runs` pipeline executions on VIP
self.launch_pipeline(nb_runs=nb_runs)
# 2. Monitor pipeline executions until they are over
.monitor_workflows(refresh_time=refresh_time)
)
# ------------------------------------------------
# Clean session data on VIP
def finish(self, timeout=300) -> VipLauncher:
"""
Removes session's output data from VIP servers.
Detailed behaviour:
- This process checks folder deletion on VIP servers until `timeout` (seconds) is reached.
- Workflows status are set to "Removed" when the corresponding outputs have been removed.
"""
# Initial display
self._print("\n=== FINISH ===\n")
self._print("Ending Session:", self._session_name)
# Check if workflows are still running (without call to VIP)
if self._still_running():
# Update the workflow inventory
self._print("Updating worflow inventory ... ", end="", flush=True)
self._update_workflows()
self._print("Done.")
# Return is workflows are still running
if self._still_running():
self._print("\n(!) This session cannot be finished since the pipeline might still generate data.\n")
self._execution_report()
return self
# Enter removal phase
self._print("Removing session data")
self._print("---------------------")
# Browse paths to delete
success = True
for path, location in self._path_to_delete().items():
# Display progression
self._print(f"[{location}] {path} ... ", end="", flush=True)
# Check data existence
if not self._exists(path, location):
# Session may be already over
self._print("Already removed.")
else:
# Erase the path
done = self._delete_and_check(
path=path, location=location, timeout=timeout
)
# Display
if done:
self._print("Done.")
else:
self._print(f"\n\t(!) Timeout reached ({timeout} seconds).")
# Update success
success = success and done
# End of loop
self._print("---------------------\n")
self._print("Updating workflows status")
self._print("-------------------------")
# Set the workflow status to "removed" to avoid dead links in future downloads
if not self._workflows:
self._print(f"No registered workflow")
removed_outputs = success
else:
removed_outputs = True
for wid in self._workflows:
self._print(f"{wid}: ", end="", flush=True)
if (
# The output list is empty
not self._workflows[wid]["outputs"]
# Workflow's output directory does not exist anymore
or not self._exists(PurePosixPath(self._workflows[wid]["outputs"][0]["path"]).parent, location="vip")
):
# Set the workflow status to "Removed"
self._workflows[wid]["status"] = "Removed"
self._print("Removed")
else:
# Workflow's outputs still exist on VIP
removed_outputs = False
self._print("Still on VIP")
# Last display
self._print("-------------------------")
if removed_outputs:
self._print("All output data have been removed from VIP.")
if success:
self._print(f"Session '{self._session_name}' is now over.")
else:
self._print("(!) There may still be temporary data on VIP.")
self._print(f"Please run finish() again or check the following path(s) on the VIP portal ({self._VIP_PORTAL}):")
self._print('\n\t'.join([str(path) for path in self._path_to_delete()]))
# Finish display
self._print()
# Return
return self
# ------------------------------------------------
###########################################
# Additional Features
###########################################
@classmethod
def show_pipeline(cls, pipeline_id: str=None) -> None:
"""
Displays useful informations about VIP pipelines.
This method can be used to browse among available pipelines,
or as a brief guide to build valid `input_settings` for a given pipeline.
Detailed behaviour:
- If `pipeline_id` is None, shows the list of all available pipelines.
- If `pipeline_id` is not exact, shows a list of pipelines with a *partial*, *case-insensitive* match.
- If `pipeline_id` is exact, shows the list of parameters required to run `pipeline_id`.
"""
# Return if _VERBOSE is False
if not cls._VERBOSE: return
# Check init() was called first
if not cls._AVAILABLE_PIPELINES:
raise TypeError(
f"No pipeline found. Run {cls.__name__}.init() to access pipeline descriptions."
)
# Find all case-insensitive partial matches between `pipeline_id` and cls._AVAILABLE_PIPELINES
if pipeline_id:
pipelines = [
pipe for pipe in cls._AVAILABLE_PIPELINES
if pipeline_id.lower() in pipe.lower()
]
else: # In case no argument is given
pipelines = cls._AVAILABLE_PIPELINES
# Display depending on the number of pipelines found
if not pipelines: # Case no match
cls._printc(f"(!) No pipeline found for pattern '{pipeline_id}'.")
cls._printc(f" You may need to register with the correct group.")
elif len(pipelines) > 1: # Case multiple matches
# Print the list of matching pipelines
cls._printc()
cls._printc("Available pipelines")
cls._printc("-------------------")
cls._printc("\n".join(pipelines))
cls._printc("-------------------")
else: # Case single match
pipeline_id = pipelines[0]
# Display pipeline ID
cls._printc('='*len(pipeline_id))
cls._printc(pipeline_id)
cls._printc('='*len(pipeline_id), end="")
# Get pipeline_definition
pipeline_def = cls._get_pipeline_def(pipeline_id)
# Get header
pipe_header = f"NAME: {pipeline_def['name']} | VERSION: {pipeline_def['version']}"
# Define text width & wrapper
text_width = max(70, len(pipe_header))
wrapper = textwrap.TextWrapper(
width = text_width,
initial_indent = ' ',
subsequent_indent = ' ',
max_lines = 10,
drop_whitespace=False,
replace_whitespace = False,
break_on_hyphens = False,
break_long_words = False
)
# Display header
cls._printc('='*(text_width-len(pipeline_id)))
cls._printc(pipe_header)
cls._printc('-'*text_width)
# Display pipeline description
pipe_description = cls._clean_html(pipeline_def['description'])
cls._printc(f"DESCRIPTION:")
cls._printc(pipe_description, wrapper=wrapper)
cls._printc('-'*text_width)
# Print a description for each pipeline parameter
cls._printc("INPUT_SETTINGS:")
# Function to display one paramter
def display_parameter(param: dict) -> None:
"""Prints name, type & description"""
cls._printc(f"- {param['name']}")
cls._printc(f"[{param['type'].upper()}]", cls._clean_html(param['description']),
wrapper=wrapper)
# Non-Optional parameters sorted by name
cls._printc("REQUIRED" + "." * (text_width-len("REQUIRED")))
for param in sorted(
[param for param in pipeline_def['parameters'] if not param["isOptional"]],
key = lambda param: param["name"]
): display_parameter(param)
# Optional parameters sorted by name
cls._printc("OPTIONAL" + "." * (text_width-len("OPTIONAL")))
for param in sorted(
[param for param in pipeline_def['parameters'] if param["isOptional"]],
key = lambda param: param["name"]
): display_parameter(param)
# End the display
cls._printc('='*text_width)
cls._printc()
# ------------------------------------------------
# Display current session state
def display(self) -> VipLauncher:
"""
Displays useful properties in JSON format.
- `session_name` : current session name
- `pipeline_id`: pipeline identifier
- `output_dir` : path to the pipeline outputs
- `input_settings` : input parameters sent to VIP
- `workflows`: workflow inventory, identifying all pipeline runs in this session.
"""
# Get properties
session_data = self._data_to_save()
# Print session name
name_str = f'Session: "{session_data["session_name"]}"'
self._print("-"*len(name_str))
self._print(name_str)
self._print("-"*len(name_str))
del session_data["session_name"]
# Print the rest
for prop in session_data:
self._print(f"{prop}: {json.dumps(session_data[prop], indent=3)}")
self._print("-"*len(name_str))
# End the display
self._print()
# Return for method cascading
return self
# ------------------------------------------------
#################
################ Private Methods ################
#################
###################################################################
# Methods that must be overwritten to adapt VipLauncher methods to
# new locations
###################################################################
# Path to delete during session finish
def _path_to_delete(self) -> dict:
"""Returns the folders to delete during session finish, with appropriate location."""
return {
self._vip_output_dir: "vip"
}
# ------------------------------------------------
# Method to check existence of a distant resource.
@classmethod
def _exists(cls, path, location="vip") -> bool:
"""
Checks existence of a distant resource (`location`="vip").
`path` can be a string or Pathlib object.
"""
# Check `location`
if location != "vip":
raise NotImplementedError(f"Unknown location: {location}")
# Check path existence
try:
return vip.exists(str(path))
except RuntimeError as vip_error:
# Connection error with VIP
cls._handle_vip_error(vip_error)
except json.decoder.JSONDecodeError:
raise ValueError(
f"The following path generated an error on VIP:\n\t{path}\n"
+ "Please check this path or retry later."
)
# ------------------------------------------------
# Method to create a distant directory
@classmethod
def _create_dir(cls, path: PurePath, location="vip") -> None:
"""
Creates a directory at `path`, on VIP servers if `location` is "vip".
`path`can be a string or PathLib object.
Returns the VIP path of the newly created folder.
"""
# Check `location`
if location != "vip":
raise NotImplementedError(f"Unknown location: {location}")
# Create directory
try:
if not vip.create_dir(str(path)):
msg = f"The following directoy could not be created on VIP:\n\t{path}\n"
msg += f"Please retry later. Contact VIP support ({cls._VIP_SUPPORT}) if this cannot be fixed."
raise AssertionError(msg)
except RuntimeError as vip_error:
cls._handle_vip_error(vip_error)
except json.decoder.JSONDecodeError as json_error:
raise ValueError(
f"The following path generated an error on VIP:\n\t{path}\n"
+ "Please check this path is valid and/or consistent with your other inputs."
)
# ------------------------------------------------
# Function to delete a path
@classmethod
def _delete_path(cls, path: PurePath, location="vip") -> None:
"""
Deletes `path` on `location`. Raises an error if the file exists and could not be removed.
"""
# Check `location`
if location != "vip":
raise NotImplementedError(f"Unknown location: {location}")
# Try path deletion
done = vip.delete_path(str(path))
# VIP Errors are handled by returning False in `vip.delete_path()`.
if not done and vip.exists(str(path)):
# Raise a generic error if deletion did not work
msg = f"\n'{path}' could not be removed from VIP servers.\n"
msg += "Check your connection with VIP and path existence on the VIP portal.\n"
raise RuntimeError(msg)
# ------------------------------------------------
# Function to delete a path on VIP with warning
@classmethod
def _delete_and_check(cls, path: PurePath, location="vip", timeout=300) -> bool:
"""
Deletes `path` on `location` and waits until `path` is actually removed.
After `timeout` (seconds), displays a warning if `path` still exist.
"""
# Delete the path
cls._delete_path(path, location)
# Standby until path is indeed removed (give up after some time)
start = time.time()
t = time.time() - start
while (t < timeout) and cls._exists(path, location):
time.sleep(2)
t = time.time() - start
# Check if the data have indeed been removed
return (t < timeout)
# ------------------------------------------------
##########################################################
# Generic private methods than should work in any subclass
##########################################################
# Method to create a directory leaf on the top of any path, at any location
@classmethod
def _mkdirs(cls, path: PurePath, location: str, **kwargs) -> str:
"""
Creates each non-existent directory in `path` (like os.mkdirs()),
in the file system pointed by `location`.
- Directories are created using: cls._create_dir(`path`, `location`, **`kwargs`)
- Existence is checked using: cls._exists(`path`, `location`).
Returns the newly created part of `path` (empty string if `path` already exists).
"""
# Case : the current path exists
if cls._exists(path=path, location=location) :
return ""
# Find the 1rst non-existent node in the arborescence
first_node = path
while not cls._exists(first_node.parent, location=location):
first_node = first_node.parent
# Create the first node
cls._create_dir(path=first_node, location=location, **kwargs)
# Make the other nodes one by one
dir_to_make = first_node
while dir_to_make != path:
# Find the next directory to make
dir_to_make /= path.relative_to(dir_to_make).parts[0]
# Make the directory
cls._create_dir(path=dir_to_make, location=location, **kwargs)
# Return the created nodes
return str(path.relative_to(first_node.parent))
# ------------------------------------------------
# Generic method to get session properties
def _get(self, *args):
"""
Get multiple session properties such as: "session_name", "pipeline_id", "input_settings".
- If a single property is provided, returns its value.
- If this property is undefined, returns None.
- If multiple properties are provided, returns a dictionary with (property, value) as items.
"""
# Case: no argument
if not args: return None
# Case: single argument
elif len(args) == 1:
return getattr(self, args[0])
# Case: multiple arguments
else:
return {prop: self._get(prop) for prop in args}
# ------------------------------------------------
# Generic method to set session properties
def _set(self, **kwargs) -> None:
"""
Sets multiple session properties based on keywords arguments or mapping object `kwargs`.
Deletes property when value is None.
"""
# Browse keyword arguments
for property, value in kwargs.items():
# Set attribute
setattr(self, property, value)
# ------------------------------------------------