-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathruntime.py
More file actions
2405 lines (2191 loc) · 97.1 KB
/
runtime.py
File metadata and controls
2405 lines (2191 loc) · 97.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
"""
Local backend
Execute the flow with a native runtime
using local / remote processes
"""
from __future__ import print_function
import json
import os
import sys
import fcntl
import re
import tempfile
import time
import subprocess
from datetime import datetime
from enum import Enum
from io import BytesIO
from itertools import chain
from functools import partial
from concurrent import futures
from typing import Dict, Tuple
from metaflow.datastore.exceptions import DataException
from contextlib import contextmanager
from . import get_namespace
from .client.filecache import FileCache, FileBlobCache, TaskMetadataCache
from .metadata_provider import MetaDatum
from .metaflow_config import (
FEAT_ALWAYS_UPLOAD_CODE_PACKAGE,
MAX_ATTEMPTS,
UI_URL,
SPIN_ALLOWED_DECORATORS,
SPIN_DISALLOWED_DECORATORS,
)
from .metaflow_profile import from_start
from .plugins import DATASTORES
from .exception import (
MetaflowException,
MetaflowInternalError,
METAFLOW_EXIT_DISALLOW_RETRY,
)
from . import procpoll
from .datastore import FlowDataStore, TaskDataStoreSet
from .debug import debug
from .decorators import flow_decorators
from .flowspec import FlowStateItems
from .mflog import mflog, RUNTIME_LOG_SOURCE
from .util import to_unicode, compress_list, unicode_type, get_latest_task_pathspec
from .clone_util import clone_task_helper
from .unbounded_foreach import (
CONTROL_TASK_TAG,
UBF_CONTROL,
UBF_TASK,
)
from .user_configs.config_options import ConfigInput
from .user_configs.config_parameters import dump_config_values
import metaflow.tracing as tracing
MAX_WORKERS = 16
MAX_NUM_SPLITS = 100
MAX_LOG_SIZE = 1024 * 1024
POLL_TIMEOUT = 1000 # ms
PROGRESS_INTERVAL = 300 # s
# The following is a list of the (data) artifacts used by the runtime while
# executing a flow. These are prefetched during the resume operation by
# leveraging the TaskDataStoreSet.
PREFETCH_DATA_ARTIFACTS = [
"_foreach_stack",
"_iteration_stack",
"_task_ok",
"_transition",
"_control_mapper_tasks",
"_control_task_is_mapper_zero",
]
RESUME_POLL_SECONDS = 60
class LoopBehavior(Enum):
NONE = "none"
ENTERING = "entering"
EXITING = "exiting"
LOOPING = "looping"
# Runtime must use logsource=RUNTIME_LOG_SOURCE for all loglines that it
# formats according to mflog. See a comment in mflog.__init__
mflog_msg = partial(mflog.decorate, RUNTIME_LOG_SOURCE)
# TODO option: output dot graph periodically about execution
class SpinRuntime(object):
def __init__(
self,
flow,
graph,
flow_datastore,
metadata,
environment,
package,
logger,
entrypoint,
event_logger,
monitor,
step_func,
step_name,
spin_pathspec,
skip_decorators=False,
artifacts_module=None,
persist=True,
max_log_size=MAX_LOG_SIZE,
):
from metaflow import Task
self._flow = flow
self._graph = graph
self._flow_datastore = flow_datastore
self._metadata = metadata
self._environment = environment
self._package = package
self._logger = logger
self._entrypoint = entrypoint
self._event_logger = event_logger
self._monitor = monitor
self._step_func = step_func
# Determine if we have a complete pathspec or need to get the task
if spin_pathspec:
parts = spin_pathspec.split("/")
if len(parts) == 4:
# Complete pathspec: flow/run/step/task_id
try:
# If user provides whole pathspec, we do not need to check namespace
task = Task(spin_pathspec, _namespace_check=False)
except Exception:
raise MetaflowException(
f"Invalid pathspec: {spin_pathspec} for step: {step_name}"
)
elif len(parts) == 3:
# Partial pathspec: flow/run/step - need to get the task
_, run_id, _ = parts
task = get_latest_task_pathspec(flow.name, step_name, run_id=run_id)
logger(
f"To make spin even faster, provide complete pathspec with task_id: {task.pathspec}",
system_msg=True,
)
else:
raise MetaflowException(
f"Invalid pathspec format: {spin_pathspec}. Expected flow/run/step or flow/run/step/task_id"
)
else:
# No pathspec provided, get latest task for this step
task = get_latest_task_pathspec(flow.name, step_name)
logger(
f"To make spin even faster, provide complete pathspec {task.pathspec}",
system_msg=True,
)
from_start("SpinRuntime: after getting task")
# Get the original FlowDatastore so we can use it to access artifacts from the
# spun task
meta_dict = task.metadata_dict
ds_type = meta_dict["ds-type"]
ds_root = meta_dict["ds-root"]
orig_datastore_impl = [d for d in DATASTORES if d.TYPE == ds_type][0]
orig_datastore_impl.datastore_root = ds_root
spin_pathspec = task.pathspec
orig_flow_datastore = FlowDataStore(
flow.name,
environment=None,
storage_impl=orig_datastore_impl,
ds_root=ds_root,
)
self._filecache = FileCache()
orig_flow_datastore.set_metadata_cache(
TaskMetadataCache(self._filecache, ds_type, ds_root, flow.name)
)
orig_flow_datastore.ca_store.set_blob_cache(
FileBlobCache(
self._filecache, FileCache.flow_ds_id(ds_type, ds_root, flow.name)
)
)
self._orig_flow_datastore = orig_flow_datastore
self._spin_pathspec = spin_pathspec
self._persist = persist
self._spin_task = task
self._input_paths = None
self._split_index = None
self._whitelist_decorators = None
self._config_file_name = None
self._skip_decorators = skip_decorators
self._artifacts_module = artifacts_module
self._max_log_size = max_log_size
self._encoding = sys.stdout.encoding or "UTF-8"
# Create a new run_id for the spin task
self.run_id = self._metadata.new_run_id()
# Raise exception if we have a black listed decorator
for deco in self._step_func.decorators:
if deco.name in SPIN_DISALLOWED_DECORATORS:
raise MetaflowException(
f"Spinning steps with @{deco.name} decorator is not supported."
)
for deco in self.whitelist_decorators:
deco.runtime_init(flow, graph, package, self.run_id)
from_start("SpinRuntime: after init decorators")
@property
def split_index(self):
"""
Returns the split index, caching the result after the first access.
"""
if self._split_index is None:
self._split_index = getattr(self._spin_task, "index", None)
return self._split_index
@property
def input_paths(self):
def _format_input_paths(task_pathspec, attempt):
_, run_id, step_name, task_id = task_pathspec.split("/")
return f"{run_id}/{step_name}/{task_id}/{attempt}"
if self._input_paths:
return self._input_paths
if self._step_func.name == "start":
from metaflow import Step
flow_name, run_id, _, _ = self._spin_pathspec.split("/")
task = Step(
f"{flow_name}/{run_id}/_parameters", _namespace_check=False
).task
self._input_paths = [
_format_input_paths(task.pathspec, task.current_attempt)
]
else:
parent_tasks = self._spin_task.parent_tasks
self._input_paths = [
_format_input_paths(t.pathspec, t.current_attempt) for t in parent_tasks
]
return self._input_paths
@property
def whitelist_decorators(self):
if self._skip_decorators:
self._whitelist_decorators = []
return self._whitelist_decorators
if self._whitelist_decorators:
return self._whitelist_decorators
self._whitelist_decorators = [
deco
for deco in self._step_func.decorators
if any(deco.name.startswith(prefix) for prefix in SPIN_ALLOWED_DECORATORS)
]
return self._whitelist_decorators
def _new_task(self, step, input_paths=None, **kwargs):
return Task(
flow_datastore=self._flow_datastore,
flow=self._flow,
step=step,
run_id=self.run_id,
metadata=self._metadata,
environment=self._environment,
entrypoint=self._entrypoint,
event_logger=self._event_logger,
monitor=self._monitor,
input_paths=input_paths,
decos=self.whitelist_decorators,
logger=self._logger,
split_index=self.split_index,
**kwargs,
)
def execute(self):
exception = None
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as config_file:
config_value = dump_config_values(self._flow)
if config_value:
json.dump(config_value, config_file)
config_file.flush()
self._config_file_name = config_file.name
else:
self._config_file_name = None
from_start("SpinRuntime: config values processed")
self.task = self._new_task(self._step_func.name, self.input_paths)
try:
self._launch_and_monitor_task()
except Exception as ex:
self._logger("Task failed.", system_msg=True, bad=True)
exception = ex
raise
finally:
for deco in self.whitelist_decorators:
deco.runtime_finished(exception)
def _launch_and_monitor_task(self):
worker = Worker(
self.task,
self._max_log_size,
self._config_file_name,
orig_flow_datastore=self._orig_flow_datastore,
spin_pathspec=self._spin_pathspec,
artifacts_module=self._artifacts_module,
persist=self._persist,
skip_decorators=self._skip_decorators,
)
from_start("SpinRuntime: created worker")
poll = procpoll.make_poll()
fds = worker.fds()
for fd in fds:
poll.add(fd)
active_fds = set(fds)
while active_fds:
events = poll.poll(POLL_TIMEOUT)
for event in events:
if event.can_read:
worker.read_logline(event.fd)
if event.is_terminated:
poll.remove(event.fd)
active_fds.remove(event.fd)
from_start("SpinRuntime: read loglines")
returncode = worker.terminate()
from_start("SpinRuntime: worker terminated")
if returncode != 0:
raise TaskFailed(self.task, f"Task failed with return code {returncode}")
else:
self._logger("Task finished successfully.", system_msg=True)
class NativeRuntime(object):
def __init__(
self,
flow,
graph,
flow_datastore,
metadata,
environment,
package,
logger,
entrypoint,
event_logger,
monitor,
run_id=None,
clone_run_id=None,
clone_only=False,
reentrant=False,
steps_to_rerun=None,
max_workers=MAX_WORKERS,
max_num_splits=MAX_NUM_SPLITS,
max_log_size=MAX_LOG_SIZE,
resume_identifier=None,
skip_decorator_hooks=False,
):
if run_id is None:
self._run_id = metadata.new_run_id()
else:
self._run_id = run_id
metadata.register_run_id(run_id)
self._flow = flow
self._graph = graph
self._flow_datastore = flow_datastore
self._metadata = metadata
self._environment = environment
self._package = package
self._logger = logger
self._max_workers = max_workers
self._active_tasks = dict() # Key: step name;
# value: [number of running tasks, number of done tasks]
# Special key 0 is total number of running tasks
self._active_tasks[0] = 0
self._unprocessed_steps = set([n.name for n in self._graph])
self._max_num_splits = max_num_splits
self._max_log_size = max_log_size
self._params_task = None
self._entrypoint = entrypoint
self.event_logger = event_logger
self._monitor = monitor
self._resume_identifier = resume_identifier
self._clone_run_id = clone_run_id
self._clone_only = clone_only
self._cloned_tasks = []
self._ran_or_scheduled_task_index = set()
self._reentrant = reentrant
self._run_url = None
self._skip_decorator_hooks = skip_decorator_hooks
# If steps_to_rerun is specified, we will not clone them in resume mode.
self._steps_to_rerun = steps_to_rerun or {}
# sorted_nodes are in topological order already, so we only need to
# iterate through the nodes once to get a stable set of rerun steps.
for step_name in self._graph.sorted_nodes:
if step_name in self._steps_to_rerun:
out_funcs = self._graph[step_name].out_funcs or []
for next_step in out_funcs:
self._steps_to_rerun.add(next_step)
self._origin_ds_set = None
if clone_run_id:
# resume logic
# 0. If clone_run_id is specified, attempt to clone all the
# successful tasks from the flow with `clone_run_id`. And run the
# unsuccessful or not-run steps in the regular fashion.
# 1. With _find_origin_task, for every task in the current run, we
# find the equivalent task in `clone_run_id` using
# pathspec_index=run/step:[index] and verify if this task can be
# cloned.
# 2. If yes, we fire off a clone-only task which copies the
# metadata from the `clone_origin` to pathspec=run/step/task to
# mimmick that the resumed run looks like an actual run.
# 3. All steps that couldn't be cloned (either unsuccessful or not
# run) are run as regular tasks.
# Lastly, to improve the performance of the cloning process, we
# leverage the TaskDataStoreSet abstraction to prefetch the
# entire DAG of `clone_run_id` and relevant data artifacts
# (see PREFETCH_DATA_ARTIFACTS) so that the entire runtime can
# access the relevant data from cache (instead of going to the datastore
# after the first prefetch).
logger(
"Gathering required information to resume run (this may take a bit of time)..."
)
self._origin_ds_set = TaskDataStoreSet(
flow_datastore,
clone_run_id,
prefetch_data_artifacts=PREFETCH_DATA_ARTIFACTS,
)
self._run_queue = []
self._poll = procpoll.make_poll()
self._workers = {} # fd -> subprocess mapping
self._finished = {}
self._is_cloned = {}
# NOTE: In case of unbounded foreach, we need the following to schedule
# the (sibling) mapper tasks of the control task (in case of resume);
# and ensure that the join tasks runs only if all dependent tasks have
# finished.
self._control_num_splits = {} # control_task -> num_splits mapping
if not self._skip_decorator_hooks:
for step in flow:
for deco in step.decorators:
deco.runtime_init(flow, graph, package, self._run_id)
def _new_task(self, step, input_paths=None, **kwargs):
if input_paths is None:
may_clone = True
else:
may_clone = all(self._is_cloned[path] for path in input_paths)
if step in self._steps_to_rerun:
may_clone = False
if step == "_parameters" or self._skip_decorator_hooks:
decos = []
else:
decos = getattr(self._flow, step).decorators
return Task(
self._flow_datastore,
self._flow,
step,
self._run_id,
self._metadata,
self._environment,
self._entrypoint,
self.event_logger,
self._monitor,
input_paths=input_paths,
may_clone=may_clone,
clone_run_id=self._clone_run_id,
clone_only=self._clone_only,
reentrant=self._reentrant,
origin_ds_set=self._origin_ds_set,
decos=decos,
logger=self._logger,
resume_identifier=self._resume_identifier,
**kwargs,
)
@property
def run_id(self):
return self._run_id
def persist_constants(self, task_id=None):
self._params_task = self._new_task("_parameters", task_id=task_id)
if not self._params_task.is_cloned:
self._params_task.persist(self._flow)
self._is_cloned[self._params_task.path] = self._params_task.is_cloned
def should_skip_clone_only_execution(self):
(
should_skip_clone_only_execution,
skip_reason,
) = self._should_skip_clone_only_execution()
if should_skip_clone_only_execution:
self._logger(skip_reason, system_msg=True)
return True
return False
@contextmanager
def run_heartbeat(self):
self._metadata.start_run_heartbeat(self._flow.name, self._run_id)
yield
self._metadata.stop_heartbeat()
def print_workflow_info(self):
self._run_url = (
"%s/%s/%s" % (UI_URL.rstrip("/"), self._flow.name, self._run_id)
if UI_URL
else None
)
if self._run_url:
self._logger(
"Workflow starting (run-id %s), see it in the UI at %s"
% (
self._run_id,
self._run_url,
),
system_msg=True,
)
else:
self._logger(
"Workflow starting (run-id %s):" % self._run_id, system_msg=True
)
def _should_skip_clone_only_execution(self):
if self._clone_only and self._params_task:
if self._params_task.resume_done():
return True, "Resume already complete. Skip clone-only execution."
if not self._params_task.is_resume_leader():
return (
True,
"Not resume leader under resume execution. Skip clone-only execution.",
)
return False, None
def clone_task(
self,
step_name,
task_id,
pathspec_index,
cloned_task_pathspec_index,
finished_tuple,
iteration_tuple,
ubf_context,
generate_task_obj,
verbose=False,
):
try:
new_task_id = task_id
if generate_task_obj:
task = self._new_task(step_name, pathspec_index=pathspec_index)
if ubf_context:
task.ubf_context = ubf_context
new_task_id = task.task_id
self._cloned_tasks.append(task)
self._ran_or_scheduled_task_index.add(cloned_task_pathspec_index)
task_pathspec = "{}/{}/{}".format(self._run_id, step_name, new_task_id)
else:
task_pathspec = "{}/{}/{}".format(self._run_id, step_name, new_task_id)
Task.clone_pathspec_mapping[task_pathspec] = "{}/{}/{}".format(
self._clone_run_id, step_name, task_id
)
if verbose:
self._logger(
"Cloning task from {}/{}/{}/{} to {}/{}/{}/{}".format(
self._flow.name,
self._clone_run_id,
step_name,
task_id,
self._flow.name,
self._run_id,
step_name,
new_task_id,
),
system_msg=True,
)
clone_task_helper(
self._flow.name,
self._clone_run_id,
self._run_id,
step_name,
task_id, # origin_task_id
new_task_id,
self._flow_datastore,
self._metadata,
origin_ds_set=self._origin_ds_set,
)
self._finished[(step_name, finished_tuple, iteration_tuple)] = task_pathspec
self._is_cloned[task_pathspec] = True
except Exception as e:
self._logger(
"Cloning {}/{}/{}/{} failed with error: {}".format(
self._flow.name, self._clone_run_id, step_name, task_id, str(e)
)
)
def clone_original_run(self, generate_task_obj=False, verbose=True):
self._logger(
"Cloning {}/{}".format(self._flow.name, self._clone_run_id),
system_msg=True,
)
inputs = []
ubf_mapper_tasks_to_clone = set()
ubf_control_tasks = set()
# We only clone ubf mapper tasks if the control task is complete.
# Here we need to check which control tasks are complete, and then get the corresponding
# mapper tasks.
for task_ds in self._origin_ds_set:
_, step_name, task_id = task_ds.pathspec.split("/")
pathspec_index = task_ds.pathspec_index
if task_ds["_task_ok"] and step_name != "_parameters":
# Control task contains "_control_mapper_tasks" but, in the case of
# @parallel decorator, the control task is also a mapper task so we
# need to distinguish this using _control_task_is_mapper_zero
control_mapper_tasks = (
[]
if "_control_mapper_tasks" not in task_ds
else task_ds["_control_mapper_tasks"]
)
if control_mapper_tasks:
if task_ds.get("_control_task_is_mapper_zero", False):
# Strip out the control task of list of mapper tasks
ubf_control_tasks.add(control_mapper_tasks[0])
ubf_mapper_tasks_to_clone.update(control_mapper_tasks[1:])
else:
ubf_mapper_tasks_to_clone.update(control_mapper_tasks)
# Since we only add mapper tasks here, if we are not in the list
# we are a control task
if task_ds.pathspec not in ubf_mapper_tasks_to_clone:
ubf_control_tasks.add(task_ds.pathspec)
for task_ds in self._origin_ds_set:
_, step_name, task_id = task_ds.pathspec.split("/")
pathspec_index = task_ds.pathspec_index
if (
task_ds["_task_ok"]
and step_name != "_parameters"
and (step_name not in self._steps_to_rerun)
):
# "_unbounded_foreach" is a special flag to indicate that the transition
# is an unbounded foreach.
# Both parent and splitted children tasks will have this flag set.
# The splitted control/mapper tasks
# are not foreach types because UBF is always followed by a join step.
is_ubf_task = (
"_unbounded_foreach" in task_ds and task_ds["_unbounded_foreach"]
) and (self._graph[step_name].type != "foreach")
is_ubf_control_task = task_ds.pathspec in ubf_control_tasks
is_ubf_mapper_task = is_ubf_task and (not is_ubf_control_task)
if is_ubf_mapper_task and (
task_ds.pathspec not in ubf_mapper_tasks_to_clone
):
# Skip copying UBF mapper tasks if control task is incomplete.
continue
ubf_context = None
if is_ubf_task:
ubf_context = "ubf_test" if is_ubf_mapper_task else "ubf_control"
finished_tuple = tuple(
[s._replace(value=0) for s in task_ds.get("_foreach_stack", ())]
)
iteration_tuple = tuple(task_ds.get("_iteration_stack", ()))
cloned_task_pathspec_index = pathspec_index.split("/")[1]
if task_ds.get("_control_task_is_mapper_zero", False):
# Replace None with index 0 for control task as it is part of the
# UBF (as a mapper as well)
finished_tuple = finished_tuple[:-1] + (
finished_tuple[-1]._replace(index=0),
)
# We need this reverse override though because when we check
# if a task has been cloned in _queue_push, the index will be None
# because the _control_task_is_mapper_zero is set in the control
# task *itself* and *not* in the one that is launching the UBF nest.
# This means that _translate_index will use None.
cloned_task_pathspec_index = re.sub(
r"(\[(?:\d+, ?)*)0\]",
lambda m: (m.group(1) or "[") + "None]",
cloned_task_pathspec_index,
)
inputs.append(
(
step_name,
task_id,
pathspec_index,
cloned_task_pathspec_index,
finished_tuple,
iteration_tuple,
is_ubf_mapper_task,
ubf_context,
)
)
with futures.ThreadPoolExecutor(max_workers=self._max_workers) as executor:
all_tasks = [
executor.submit(
self.clone_task,
step_name,
task_id,
pathspec_index,
cloned_task_pathspec_index,
finished_tuple,
iteration_tuple,
ubf_context=ubf_context,
generate_task_obj=generate_task_obj and (not is_ubf_mapper_task),
verbose=verbose,
)
for (
step_name,
task_id,
pathspec_index,
cloned_task_pathspec_index,
finished_tuple,
iteration_tuple,
is_ubf_mapper_task,
ubf_context,
) in inputs
]
_, _ = futures.wait(all_tasks)
self._logger(
"{}/{} cloned!".format(self._flow.name, self._clone_run_id), system_msg=True
)
self._params_task.mark_resume_done()
def execute(self):
if len(self._cloned_tasks) > 0:
# mutable list storing the cloned tasks.
self._run_queue = []
self._active_tasks[0] = 0
else:
if self._params_task:
self._queue_push("start", {"input_paths": [self._params_task.path]})
else:
self._queue_push("start", {})
progress_tstamp = time.time()
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as config_file:
# Configurations are passed through a file to avoid overloading the
# command-line. We only need to create this file once and it can be reused
# for any task launch
config_value = dump_config_values(self._flow)
if config_value:
json.dump(config_value, config_file)
config_file.flush()
self._config_file_name = config_file.name
else:
self._config_file_name = None
try:
# main scheduling loop
exception = None
while (
self._run_queue or self._active_tasks[0] > 0 or self._cloned_tasks
):
# 1. are any of the current workers finished?
if self._cloned_tasks:
finished_tasks = []
# For loops (right now just recursive steps), we need to find
# the exact frontier because if we queue all "successors" to all
# the finished iterations, we would incorrectly launch multiple
# successors. We therefore have to strip out all non-last
# iterations *per* foreach branch.
idx_per_finished_id = (
{}
) # type: Dict[Tuple[str, Tuple[int, ...], Tuple[int, Tuple[int, ...]]]]
for task in self._cloned_tasks:
step_name, foreach_stack, iteration_stack = task.finished_id
existing_task_idx = idx_per_finished_id.get(
(step_name, foreach_stack), None
)
if existing_task_idx is not None:
len_diff = len(iteration_stack) - len(
existing_task_idx[1]
)
# In this case, we need to keep only the latest iteration
if (
len_diff == 0
and iteration_stack > existing_task_idx[1]
) or len_diff == -1:
# We remove the one we currently have and replace
# by this one. The second option means that we are
# adding the finished iteration marker.
existing_task = finished_tasks[existing_task_idx[0]]
# These are the first two lines of _queue_tasks
# We still consider the tasks finished so we need
# to update state to be clean.
self._finished[existing_task.finished_id] = (
existing_task.path
)
self._is_cloned[existing_task.path] = (
existing_task.is_cloned
)
finished_tasks[existing_task_idx[0]] = task
idx_per_finished_id[(step_name, foreach_stack)] = (
existing_task_idx[0],
iteration_stack,
)
elif (
len_diff == 0
and iteration_stack < existing_task_idx[1]
) or len_diff == 1:
# The second option is when we have already marked
# the end of the iteration in self._finished and
# are now seeing a previous iteration.
# We just mark the task as finished but we don't
# put it in the finished_tasks list to pass to
# the _queue_tasks function
self._finished[task.finished_id] = task.path
self._is_cloned[task.path] = task.is_cloned
else:
raise MetaflowInternalError(
"Unexpected recursive cloned tasks -- "
"this is a bug, please report it."
)
else:
# New entry
finished_tasks.append(task)
idx_per_finished_id[(step_name, foreach_stack)] = (
len(finished_tasks) - 1,
iteration_stack,
)
# reset the list of cloned tasks and let poll_workers handle
# the remaining transition
self._cloned_tasks = []
else:
finished_tasks = list(self._poll_workers())
# 2. push new tasks triggered by the finished tasks to the queue
self._queue_tasks(finished_tasks)
# 3. if there are available worker slots, pop and start tasks
# from the queue.
self._launch_workers()
if time.time() - progress_tstamp > PROGRESS_INTERVAL:
progress_tstamp = time.time()
tasks_print = ", ".join(
[
"%s (%d running; %d done)" % (k, v[0], v[1])
for k, v in self._active_tasks.items()
if k != 0 and v[0] > 0
]
)
if self._active_tasks[0] == 0:
msg = "No tasks are running."
else:
if self._active_tasks[0] == 1:
msg = "1 task is running: "
else:
msg = "%d tasks are running: " % self._active_tasks[0]
msg += "%s." % tasks_print
self._logger(msg, system_msg=True)
if len(self._run_queue) == 0:
msg = "No tasks are waiting in the queue."
else:
if len(self._run_queue) == 1:
msg = "1 task is waiting in the queue: "
else:
msg = "%d tasks are waiting in the queue." % len(
self._run_queue
)
self._logger(msg, system_msg=True)
if len(self._unprocessed_steps) > 0:
if len(self._unprocessed_steps) == 1:
msg = "%s step has not started" % (
next(iter(self._unprocessed_steps)),
)
else:
msg = "%d steps have not started: " % len(
self._unprocessed_steps
)
msg += "%s." % ", ".join(self._unprocessed_steps)
self._logger(msg, system_msg=True)
except KeyboardInterrupt as ex:
self._logger(
"Workflow interrupted. Please avoid pressing Ctrl+C again to let the workflow clean up process finish.",
system_msg=True,
bad=True,
)
self._killall()
exception = ex
raise
except Exception as ex:
self._logger("Workflow failed.", system_msg=True, bad=True)
self._killall()
exception = ex
raise
finally:
# on finish clean tasks
if not self._skip_decorator_hooks:
for step in self._flow:
for deco in step.decorators:
deco.runtime_finished(exception)
self._run_exit_hooks()
# assert that end was executed and it was successful
if ("end", (), ()) in self._finished:
if self._run_url:
self._logger(
"Done! See the run in the UI at %s" % self._run_url,
system_msg=True,
)
else:
self._logger("Done!", system_msg=True)
elif self._clone_only:
self._logger(
"Clone-only resume complete -- only previously successful steps were "
"cloned; no new tasks executed!",
system_msg=True,
)
self._params_task.mark_resume_done()
else:
raise MetaflowInternalError(
"The *end* step was not successful by the end of flow."
)
def _run_exit_hooks(self):
try:
flow_decos = self._flow._flow_state[FlowStateItems.FLOW_DECORATORS]
exit_hook_decos = flow_decos.get("exit_hook", [])
if not exit_hook_decos:
return
successful = ("end", (), ()) in self._finished or self._clone_only
pathspec = f"{self._graph.name}/{self._run_id}"
flow_file = self._environment.get_environment_info()["script"]
def _call(fn_name):
try:
result = (
subprocess.check_output(
args=[
sys.executable,
"-m",
"metaflow.plugins.exit_hook.exit_hook_script",
flow_file,
fn_name,
pathspec,
],
env=os.environ,
)
.decode()
.strip()
)
print(result)
except subprocess.CalledProcessError as e:
print(f"[exit_hook] Hook '{fn_name}' failed with error: {e}")
except Exception as e:
print(f"[exit_hook] Unexpected error in hook '{fn_name}': {e}")
# Call all exit hook functions regardless of individual failures
for fn_name in [
name
for deco in exit_hook_decos
for name in (deco.success_hooks if successful else deco.error_hooks)
]:
_call(fn_name)
except Exception as ex:
pass # do not fail due to exit hooks for whatever reason.
def _killall(self):
# If we are here, all children have received a signal and are shutting down.
# We want to give them an opportunity to do so and then kill
live_workers = set(self._workers.values())
now = int(time.time())
self._logger(
"Terminating %d active tasks..." % len(live_workers),
system_msg=True,
bad=True,
)
while live_workers and int(time.time()) - now < 5: