forked from cylc/cylc-flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_pool.py
More file actions
1960 lines (1757 loc) · 75.2 KB
/
task_pool.py
File metadata and controls
1960 lines (1757 loc) · 75.2 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
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Wrangle task proxies to manage the workflow."""
from contextlib import suppress
from collections import Counter
import json
from time import time
from typing import Dict, Iterable, List, Optional, Set, TYPE_CHECKING, Tuple
import logging
import cylc.flow.flags
from cylc.flow import LOG
from cylc.flow.cycling.loader import get_point, standardise_point_string
from cylc.flow.exceptions import WorkflowConfigError, PointParsingError
from cylc.flow.id import Tokens, detokenise
from cylc.flow.id_cli import contains_fnmatch
from cylc.flow.id_match import filter_ids
from cylc.flow.workflow_status import StopMode
from cylc.flow.task_action_timer import TaskActionTimer, TimerFlags
from cylc.flow.task_events_mgr import (
CustomTaskEventHandlerContext, TaskEventMailContext,
TaskJobLogsRetrieveContext)
from cylc.flow.task_id import TaskID
from cylc.flow.task_proxy import TaskProxy
from cylc.flow.task_state import (
TASK_STATUSES_ACTIVE,
TASK_STATUSES_FINAL,
TASK_STATUS_WAITING,
TASK_STATUS_EXPIRED,
TASK_STATUS_PREPARING,
TASK_STATUS_SUBMITTED,
TASK_STATUS_RUNNING,
TASK_STATUS_SUCCEEDED,
TASK_STATUS_FAILED,
TASK_OUTPUT_EXPIRED,
TASK_OUTPUT_FAILED,
TASK_OUTPUT_SUCCEEDED,
)
from cylc.flow.util import (
serialise,
deserialise
)
from cylc.flow.wallclock import get_current_time_string
from cylc.flow.platforms import get_platform
from cylc.flow.task_queues.independent import IndepQueueManager
from cylc.flow.flow_mgr import FLOW_ALL, FLOW_NONE, FLOW_NEW
if TYPE_CHECKING:
from cylc.flow.config import WorkflowConfig
from cylc.flow.cycling import IntervalBase, PointBase
from cylc.flow.data_store_mgr import DataStoreMgr
from cylc.flow.taskdef import TaskDef
from cylc.flow.task_events_mgr import TaskEventsManager
from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
from cylc.flow.flow_mgr import FlowMgr, FlowNums
Pool = Dict['PointBase', Dict[str, TaskProxy]]
class TaskPool:
"""Task pool of a workflow."""
ERR_TMPL_NO_TASKID_MATCH = "No matching tasks found: {0}"
SUICIDE_MSG = "suicide"
def __init__(
self,
config: 'WorkflowConfig',
workflow_db_mgr: 'WorkflowDatabaseManager',
task_events_mgr: 'TaskEventsManager',
data_store_mgr: 'DataStoreMgr',
flow_mgr: 'FlowMgr'
) -> None:
self.config: 'WorkflowConfig' = config
self.stop_point = config.stop_point or config.final_point
self.workflow_db_mgr: 'WorkflowDatabaseManager' = workflow_db_mgr
self.task_events_mgr: 'TaskEventsManager' = task_events_mgr
# TODO this is ugly:
self.task_events_mgr.spawn_func = self.spawn_on_output
self.data_store_mgr: 'DataStoreMgr' = data_store_mgr
self.flow_mgr: 'FlowMgr' = flow_mgr
self.do_reload = False
self.max_future_offset: Optional['IntervalBase'] = None
self._prev_runahead_base_point: Optional['PointBase'] = None
self._prev_runahead_sequence_points: Optional[Set['PointBase']] = None
self.runahead_limit_point: Optional['PointBase'] = None
self.main_pool: Pool = {}
self.hidden_pool: Pool = {}
self.main_pool_list: List[TaskProxy] = []
self.hidden_pool_list: List[TaskProxy] = []
self.main_pool_changed = False
self.hidden_pool_changed = False
self.hold_point: Optional['PointBase'] = None
self.abs_outputs_done: Set[Tuple[str, str, str]] = set()
self.stop_task_id: Optional[str] = None
self.stop_task_finished = False
self.abort_task_failed = False
self.expected_failed_tasks = self.config.get_expected_failed_tasks()
self.orphans: List[str] = []
self.task_name_list = self.config.get_task_name_list()
self.task_queue_mgr = IndepQueueManager(
self.config.cfg['scheduling']['queues'],
self.config.get_task_name_list(),
self.config.runtime['descendants']
)
self.tasks_to_hold: Set[Tuple[str, 'PointBase']] = set()
def set_stop_task(self, task_id):
"""Set stop after a task."""
tokens = Tokens(task_id, relative=True)
name = tokens['task']
if name in self.config.get_task_name_list():
task_id = TaskID.get_standardised_taskid(task_id)
LOG.info("Setting stop task: " + task_id)
self.stop_task_id = task_id
self.stop_task_finished = False
self.workflow_db_mgr.put_workflow_stop_task(task_id)
else:
LOG.warning("Requested stop task name does not exist: %s" % name)
def stop_task_done(self):
"""Return True if stop task has succeeded."""
if self.stop_task_id is not None and self.stop_task_finished:
LOG.info("Stop task %s finished" % self.stop_task_id)
self.stop_task_id = None
self.stop_task_finished = False
self.workflow_db_mgr.delete_workflow_stop_task()
return True
else:
return False
def _swap_out(self, itask):
"""Swap old task for new, during reload."""
if itask.point in self.hidden_pool:
if itask.identity in self.hidden_pool[itask.point]:
self.hidden_pool[itask.point][itask.identity] = itask
self.hidden_pool_changed = True
elif (
itask.point in self.main_pool
and itask.identity in self.main_pool[itask.point]
):
self.main_pool[itask.point][itask.identity] = itask
self.main_pool_changed = True
def load_from_point(self):
"""Load the task pool for the workflow start point.
Add every parentless task out to the runahead limit.
"""
flow_num = self.flow_mgr.get_new_flow(
f"original flow from {self.config.start_point}")
self.compute_runahead()
for name in self.config.get_task_name_list():
tdef = self.config.get_taskdef(name)
point = tdef.first_point(self.config.start_point)
self.spawn_to_rh_limit(tdef, point, {flow_num})
def add_to_pool(self, itask, is_new: bool = True) -> None:
"""Add a task to the hidden (if not satisfied) or main task pool.
If the task already exists in the hidden pool and is satisfied, move it
to the main pool.
(is_new is False inidcates load from DB at restart).
"""
if itask.is_task_prereqs_not_done() and not itask.is_manual_submit:
# Add to hidden pool if not satisfied.
self.hidden_pool.setdefault(itask.point, {})
self.hidden_pool[itask.point][itask.identity] = itask
self.hidden_pool_changed = True
LOG.debug(f"[{itask}] added to hidden task pool")
else:
# Add to main pool.
# First remove from hidden pool if necessary.
try:
del self.hidden_pool[itask.point][itask.identity]
except KeyError:
pass
else:
self.hidden_pool_changed = True
if not self.hidden_pool[itask.point]:
del self.hidden_pool[itask.point]
self.main_pool.setdefault(itask.point, {})
self.main_pool[itask.point][itask.identity] = itask
self.main_pool_changed = True
LOG.debug(f"[{itask}] added to main task pool")
self.create_data_store_elements(itask)
if is_new:
# Add row to "task_states" table.
now = get_current_time_string()
self.workflow_db_mgr.put_insert_task_states(
itask,
{
"time_created": now,
"time_updated": now,
"status": itask.state.status,
"flow_nums": serialise(itask.flow_nums)
}
)
# Add row to "task_outputs" table:
self.workflow_db_mgr.put_insert_task_outputs(itask)
if itask.tdef.max_future_prereq_offset is not None:
# (Must do this once added to the pool).
self.set_max_future_offset()
def create_data_store_elements(self, itask):
"""Create the node window elements about given task proxy."""
# Register pool node reference
self.data_store_mgr.add_pool_node(itask.tdef.name, itask.point)
# Create new data-store n-distance graph window about this task
self.data_store_mgr.increment_graph_window(itask)
self.data_store_mgr.delta_task_state(itask)
self.data_store_mgr.delta_task_held(itask)
self.data_store_mgr.delta_task_queued(itask)
self.data_store_mgr.delta_task_runahead(itask)
def release_runahead_tasks(self):
"""Release tasks below the runahead limit.
Return True if any tasks are released, else False.
Call when RH limit changes.
"""
if not self.main_pool or not self.runahead_limit_point:
# (At start-up main pool might not exist yet)
return False
released = False
# An intermediate list is needed here: auto-spawning of parentless
# tasks can cause the task pool to change size during iteration.
release_me = [
itask
for point, itask_id_map in self.main_pool.items()
for itask in itask_id_map.values()
if point <= self.runahead_limit_point
if itask.state.is_runahead
]
for itask in release_me:
self.rh_release_and_queue(itask)
self.spawn_to_rh_limit(
itask.tdef,
itask.tdef.next_point(itask.point),
itask.flow_nums
)
released = True
return released
def compute_runahead(self, force=False) -> bool:
"""Compute the runahead limit; return True if it changed.
To be called if:
* The runahead base point might have changed:
- a task completed expected outputs, or expired
- (Cylc7 back compat: a task succeeded or failed)
* The max future offset might have changed.
* The runahead limit config or task pool might have changed (reload).
Start from earliest point with unfinished tasks. Partially satisfied
and incomplete tasks count too because they still need to run.
The limit itself is limited by workflow stop point, if there is one,
and adjusted upward on the fly if tasks with future offsets appear.
With force=True we recompute the limit even if the base point has not
changed (needed if max_future_offset changed, or on reload).
"""
points: List['PointBase'] = []
if not self.main_pool:
# Start at first point in each sequence, after the initial point.
points = list({
seq.get_first_point(self.config.start_point)
for seq in self.config.sequences
})
else:
# Find the earliest point with unfinished tasks.
for point, itasks in sorted(self.get_tasks_by_point().items()):
if (
points # got the limit already so this point too
or any(
not itask.state(
TASK_STATUS_FAILED,
TASK_STATUS_SUCCEEDED,
TASK_STATUS_EXPIRED
)
or (
# For Cylc 7 back-compat, ignore incomplete tasks.
# (Success is required in back-compat mode, so
# failedtasks end up as incomplete; and Cylc 7
# ignores failed tasks in computing the limit).
itask.state.outputs.is_incomplete()
and not cylc.flow.flags.cylc7_back_compat
)
for itask in itasks
)
):
points.append(point)
if not points:
return False
base_point = min(points)
if self._prev_runahead_base_point is None:
self._prev_runahead_base_point = base_point
if (
not force
and self.runahead_limit_point is not None
and (
base_point == self._prev_runahead_base_point
or self.runahead_limit_point == self.stop_point
)
):
# No need to recompute the list of points if the base point did not
# change or the runahead limit is already at stop point.
return False
try:
limit = int(self.config.runahead_limit) # type: ignore
except TypeError:
count_cycles = False
limit = self.config.runahead_limit
else:
count_cycles = True
# Get all cycle points possible after the runahead base point.
if (
not force
and self._prev_runahead_sequence_points
and base_point == self._prev_runahead_base_point
):
# Cache for speed.
sequence_points = self._prev_runahead_sequence_points
else:
# Recompute possible points.
sequence_points = set()
for sequence in self.config.sequences:
seq_point = sequence.get_next_point(base_point)
count = 1
while seq_point is not None:
if count_cycles:
# P0 allows only the base cycle point to run.
if count > 1 + limit:
break
else:
# PT0H allows only the base cycle point to run.
if seq_point > base_point + limit:
break
count += 1
sequence_points.add(seq_point)
seq_point = sequence.get_next_point(seq_point)
self._prev_runahead_sequence_points = sequence_points
self._prev_runahead_base_point = base_point
points = set(points).union(sequence_points)
if count_cycles:
# Some sequences may have different intervals.
limit_point = sorted(points)[:(limit + 1)][-1]
else:
# We already stopped at the runahead limit.
limit_point = sorted(points)[-1]
# Adjust for future offset and stop point, if necessary.
orig_limit = limit_point
if self.max_future_offset is not None:
limit_point += self.max_future_offset
LOG.debug(f"{orig_limit} -> {limit_point} (future offset)")
if self.stop_point and limit_point > self.stop_point:
limit_point = self.stop_point
LOG.debug(f"{orig_limit} -> {limit_point} (stop point)")
orig_limit = limit_point
if (
self.config.cfg["scheduling"]["isolate initial cycle point"]
and base_point <= self.config.initial_point
and limit_point > self.config.initial_point
):
limit_point = self.config.initial_point
LOG.debug(
f"{orig_limit} -> {limit_point} (isolate initial point)")
orig_limit = limit_point
if (
self.config.second_to_last_point is not None
and base_point <= self.config.second_to_last_point
and limit_point > self.config.second_to_last_point
):
limit_point = self.config.second_to_last_point
LOG.debug(f"{orig_limit} -> {limit_point} (isolate final point)")
LOG.info(f"Runahead limit: {limit_point}")
self.runahead_limit_point = limit_point
return True
def update_flow_mgr(self):
flow_nums_seen = set()
for itask in self.get_all_tasks():
flow_nums_seen.update(itask.flow_nums)
self.flow_mgr.load_from_db(flow_nums_seen)
def load_abs_outputs_for_restart(self, row_idx, row):
cycle, name, output = row
self.abs_outputs_done.add((cycle, name, output))
def load_db_task_pool_for_restart(self, row_idx, row):
"""Load tasks from DB task pool/states/jobs tables.
Output completion status is loaded from the DB, and tasks recorded
as submitted or running are polled to confirm their true status.
Tasks are added to queues again on release from runahead pool.
"""
if row_idx == 0:
LOG.info("LOADING task proxies")
# Create a task proxy corresponding to this DB entry.
(cycle, name, flow_nums, is_late, status, is_held, submit_num, _,
platform_name, time_submit, time_run, timeout, outputs_str) = row
try:
itask = TaskProxy(
self.config.get_taskdef(name),
get_point(cycle),
deserialise(flow_nums),
status=status,
is_held=is_held,
submit_num=submit_num,
is_late=bool(is_late)
)
except WorkflowConfigError:
LOG.exception(
f'ignoring task {name} from the workflow run database\n'
'(its task definition has probably been deleted).')
except Exception:
LOG.exception(f'could not load task {name}')
else:
if status in (
TASK_STATUS_SUBMITTED,
TASK_STATUS_RUNNING
):
# update the task proxy with platform
itask.platform = get_platform(platform_name)
if time_submit:
itask.set_summary_time('submitted', time_submit)
if time_run:
itask.set_summary_time('started', time_run)
if timeout is not None:
itask.timeout = timeout
elif status == TASK_STATUS_PREPARING:
# put back to be readied again.
status = TASK_STATUS_WAITING
# Re-prepare same submit.
itask.submit_num -= 1
# Running or finished task can have completed custom outputs.
if itask.state(
TASK_STATUS_RUNNING,
TASK_STATUS_FAILED,
TASK_STATUS_SUCCEEDED
):
for message in json.loads(outputs_str):
itask.state.outputs.set_completion(message, True)
self.data_store_mgr.delta_task_output(itask, message)
if platform_name and status != TASK_STATUS_WAITING:
itask.summary['platforms_used'][
int(submit_num)] = platform_name
LOG.info(
f"+ {cycle}/{name} {status}{' (held)' if is_held else ''}")
# Update prerequisite satisfaction status from DB
sat = {}
for prereq_name, prereq_cycle, prereq_output, satisfied in (
self.workflow_db_mgr.pri_dao.select_task_prerequisites(
cycle,
name,
flow_nums,
)
):
key = (prereq_cycle, prereq_name, prereq_output)
sat[key] = satisfied if satisfied != '0' else False
for itask_prereq in itask.state.prerequisites:
for key, _ in itask_prereq.satisfied.items():
itask_prereq.satisfied[key] = sat[key]
if itask.state_reset(status, is_runahead=True):
self.data_store_mgr.delta_task_runahead(itask)
self.add_to_pool(itask, is_new=False)
# All tasks load as runahead-limited, but finished and manually
# triggered tasks (incl. --start-task's) can be released now.
if (
itask.state(
TASK_STATUS_FAILED,
TASK_STATUS_SUCCEEDED,
TASK_STATUS_EXPIRED
)
or itask.is_manual_submit
):
self.rh_release_and_queue(itask)
self.compute_runahead()
self.release_runahead_tasks()
def load_db_task_action_timers(self, row_idx, row):
"""Load a task action timer, e.g. event handlers, retry states."""
if row_idx == 0:
LOG.info("LOADING task action timers")
(cycle, name, ctx_key_raw, ctx_raw, delays_raw, num, delay,
timeout) = row
id_ = Tokens(
cycle=cycle,
task=name,
).relative_id
try:
# Extract type namedtuple variables from JSON strings
ctx_key = json.loads(str(ctx_key_raw))
ctx_data = json.loads(str(ctx_raw))
for known_cls in [
CustomTaskEventHandlerContext,
TaskEventMailContext,
TaskJobLogsRetrieveContext]:
if ctx_data and ctx_data[0] == known_cls.__name__:
ctx = known_cls(*ctx_data[1])
break
else:
ctx = ctx_data
if ctx is not None:
ctx = tuple(ctx)
delays = json.loads(str(delays_raw))
except ValueError:
LOG.exception(
"%(id)s: skip action timer %(ctx_key)s" %
{"id": id_, "ctx_key": ctx_key_raw})
return
LOG.info("+ %s/%s %s" % (cycle, name, ctx_key))
if ctx_key == "poll_timer":
itask = self._get_main_task_by_id(id_)
if itask is None:
LOG.warning("%(id)s: task not found, skip" % {"id": id_})
return
itask.poll_timer = TaskActionTimer(
ctx, delays, num, delay, timeout)
elif ctx_key[0] == "try_timers":
itask = self._get_main_task_by_id(id_)
if itask is None:
LOG.warning("%(id)s: task not found, skip" % {"id": id_})
return
if 'retrying' in ctx_key[1]:
if 'submit' in ctx_key[1]:
submit = True
ctx_key[1] = TimerFlags.SUBMISSION_RETRY
else:
submit = False
ctx_key[1] = TimerFlags.EXECUTION_RETRY
if timeout:
LOG.info(
f' (upgrading retrying state for {itask.identity})')
self.task_events_mgr._retry_task(
itask,
float(timeout),
submit_retry=submit
)
itask.try_timers[ctx_key[1]] = TaskActionTimer(
ctx, delays, num, delay, timeout)
elif ctx:
key1, submit_num = ctx_key
# Convert key1 to type tuple - JSON restores as type list
# and this will not previously have been converted back
if isinstance(key1, list):
key1 = tuple(key1)
key = (key1, cycle, name, submit_num)
self.task_events_mgr.add_event_timer(
key,
TaskActionTimer(
ctx, delays, num, delay, timeout
)
)
else:
LOG.exception(
"%(id)s: skip action timer %(ctx_key)s" %
{"id": id_, "ctx_key": ctx_key_raw})
return
def load_db_tasks_to_hold(self):
"""Update the tasks_to_hold set with the tasks stored in the
database."""
self.tasks_to_hold.update(
(name, get_point(cycle)) for name, cycle in
self.workflow_db_mgr.pri_dao.select_tasks_to_hold()
)
def rh_release_and_queue(self, itask) -> None:
"""Release a task from runahead limiting, and queue it if ready.
Check the task against the RH limit before calling this method (in
forced triggering we need to release even if beyond the limit).
"""
if itask.state_reset(is_runahead=False):
self.data_store_mgr.delta_task_runahead(itask)
if all(itask.is_ready_to_run()):
# (otherwise waiting on xtriggers etc.)
self.queue_task(itask)
def _get_spawned_or_merged_task(
self, point: 'PointBase', name: str, flow_nums: 'FlowNums'
) -> Optional[TaskProxy]:
"""Return new or existing task point/name with merged flow_nums"""
taskid = Tokens(cycle=str(point), task=name).relative_id
ntask = (
self._get_hidden_task_by_id(taskid)
or self._get_main_task_by_id(taskid)
)
if ntask is None:
# ntask does not exist: spawn it in the flow.
ntask = self.spawn_task(name, point, flow_nums)
else:
# ntask already exists (n=0 or incomplete): merge flows.
self.merge_flows(ntask, flow_nums)
return ntask # may be None
def spawn_to_rh_limit(self, tdef, point, flow_nums) -> None:
"""Spawn parentless task instances from point to runahead limit."""
if not flow_nums:
# force-triggered no-flow task.
return
if self.runahead_limit_point is None:
self.compute_runahead()
while point is not None and (point <= self.runahead_limit_point):
if tdef.is_parentless(point):
ntask = self._get_spawned_or_merged_task(
point, tdef.name, flow_nums
)
if ntask is not None:
self.add_to_pool(ntask)
self.rh_release_and_queue(ntask)
point = tdef.next_point(point)
# Once more (for the rh-limited task: don't rh release it!)
if point is not None and tdef.is_parentless(point):
ntask = self._get_spawned_or_merged_task(
point, tdef.name, flow_nums
)
if ntask is not None:
self.add_to_pool(ntask)
def remove(self, itask, reason=""):
"""Remove a task from the pool (e.g. after a reload)."""
msg = "task proxy removed"
if reason:
msg += f" ({reason})"
try:
del self.hidden_pool[itask.point][itask.identity]
except KeyError:
pass
else:
# e.g. for suicide of partially satisfied task
self.hidden_pool_changed = True
if not self.hidden_pool[itask.point]:
del self.hidden_pool[itask.point]
LOG.debug(f"[{itask}] {msg}")
return
try:
del self.main_pool[itask.point][itask.identity]
except KeyError:
pass
else:
self.main_pool_changed = True
if not self.main_pool[itask.point]:
del self.main_pool[itask.point]
self.task_queue_mgr.remove_task(itask)
if itask.tdef.max_future_prereq_offset is not None:
self.set_max_future_offset()
# Notify the data-store manager of their removal
# (the manager uses window boundary tracking for pruning).
self.data_store_mgr.remove_pool_node(itask.tdef.name, itask.point)
# Event-driven final update of task_states table.
# TODO: same for datastore (still updated by scheduler loop)
self.workflow_db_mgr.put_update_task_state(itask)
LOG.debug(f"[{itask}] {msg}")
del itask
def get_all_tasks(self) -> List[TaskProxy]:
"""Return a list of all task proxies."""
return self.get_hidden_tasks() + self.get_tasks()
def get_tasks(self) -> List[TaskProxy]:
"""Return a list of task proxies in the main pool."""
if self.main_pool_changed:
self.main_pool_changed = False
self.main_pool_list = []
for _, itask_id_map in self.main_pool.items():
for __, itask in itask_id_map.items():
self.main_pool_list.append(itask)
return self.main_pool_list
def get_hidden_tasks(self) -> List[TaskProxy]:
"""Return a list of task proxies in the hidden pool."""
if self.hidden_pool_changed:
self.hidden_pool_changed = False
self.hidden_pool_list = []
for itask_id_maps in self.hidden_pool.values():
self.hidden_pool_list.extend(list(itask_id_maps.values()))
return self.hidden_pool_list
def get_tasks_by_point(self):
"""Return a map of task proxies by cycle point."""
point_itasks = {}
for point, itask_id_map in self.main_pool.items():
point_itasks[point] = list(itask_id_map.values())
for point, itask_id_map in self.hidden_pool.items():
if point not in point_itasks:
point_itasks[point] = list(itask_id_map.values())
else:
point_itasks[point] += list(itask_id_map.values())
return point_itasks
def _get_hidden_task_by_id(self, id_: str) -> Optional[TaskProxy]:
"""Return runahead pool task by ID if it exists, or None."""
for itask_ids in list(self.hidden_pool.values()):
with suppress(KeyError):
return itask_ids[id_]
return None
def _get_main_task_by_id(self, id_: str) -> Optional[TaskProxy]:
"""Return main pool task by ID if it exists, or None."""
for itask_ids in list(self.main_pool.values()):
with suppress(KeyError):
return itask_ids[id_]
return None
def queue_task(self, itask: TaskProxy) -> None:
"""Queue a task that is ready to run."""
if itask.state_reset(is_queued=True):
self.data_store_mgr.delta_task_queued(itask)
self.task_queue_mgr.push_task(itask)
def release_queued_tasks(self):
"""Return list of queue-released tasks awaiting job prep.
Note:
Tasks can hang about for a while between being released and
entering the PREPARING state for various reasons. This method
returns tasks which are awaiting job prep irrespective of whether
they have been previously returned.
"""
# count active tasks by name
# {task_name: number_of_active_instances, ...}
active_task_counter = Counter()
# tasks which have entered the submission pipeline but have not yet
# entered the PREPARING state
pre_prep_tasks = []
for itask in self.get_tasks():
# populate active_task_counter and pre_prep_tasks together to
# avoid iterating the task pool twice
if itask.waiting_on_job_prep:
# a task which has entered the submission pipeline
# for the purposes of queue limiting this should be treated
# the same as an active task
active_task_counter.update([itask.tdef.name])
pre_prep_tasks.append(itask)
elif itask.state(
TASK_STATUS_PREPARING,
TASK_STATUS_SUBMITTED,
TASK_STATUS_RUNNING,
):
# an active task
active_task_counter.update([itask.tdef.name])
# release queued tasks
released = self.task_queue_mgr.release_tasks(active_task_counter)
for itask in released:
itask.state_reset(is_queued=False)
itask.waiting_on_job_prep = True
self.data_store_mgr.delta_task_queued(itask)
if cylc.flow.flags.cylc7_back_compat:
# Cylc 7 Back Compat: spawn downstream to cause Cylc 7 style
# stalls - with unsatisfied waiting tasks - even with single
# prerequisites (which result in incomplete tasks in Cylc 8).
# We do it here (rather than at runhead release) to avoid
# pre-spawning out to the runahead limit.
self.spawn_on_all_outputs(itask)
# Note: released and pre_prep_tasks can overlap
return list(set(released + pre_prep_tasks))
def get_min_point(self):
"""Return the minimum cycle point currently in the pool."""
cycles = list(self.main_pool)
minc = None
if cycles:
minc = min(cycles)
return minc
def set_max_future_offset(self):
"""Calculate the latest required future trigger offset."""
orig = self.max_future_offset
max_offset = None
for itask in self.get_tasks():
if (
itask.tdef.max_future_prereq_offset is not None
and (
max_offset is None or
itask.tdef.max_future_prereq_offset > max_offset
)
):
max_offset = itask.tdef.max_future_prereq_offset
self.max_future_offset = max_offset
if max_offset != orig and self.compute_runahead(force=True):
self.release_runahead_tasks()
def set_do_reload(self, config: 'WorkflowConfig') -> None:
"""Set the task pool to reload mode."""
self.config = config
self.stop_point = config.stop_point or config.final_point
self.do_reload = True
# find any old tasks that have been removed from the workflow
old_task_name_list = self.task_name_list
self.task_name_list = self.config.get_task_name_list()
for name in old_task_name_list:
if name not in self.task_name_list:
self.orphans.append(name)
for name in self.task_name_list:
if name in self.orphans:
self.orphans.remove(name)
# adjust the new workflow config to handle the orphans
self.config.adopt_orphans(self.orphans)
def reload_taskdefs(self) -> None:
"""Reload the definitions of task proxies in the pool.
Orphaned tasks (whose definitions were removed from the workflow):
- remove if not active yet
- if active, leave them but prevent them from spawning children on
subsequent outputs
Otherwise: replace task definitions but copy over existing outputs etc.
"""
LOG.info("Reloading task definitions.")
tasks = self.get_all_tasks()
# Log tasks orphaned by a reload but not currently in the task pool.
for name in self.orphans:
if name not in (itask.tdef.name for itask in tasks):
LOG.warning("Removed task: '%s'", name)
for itask in tasks:
if itask.tdef.name in self.orphans:
if (
itask.state(TASK_STATUS_WAITING)
or itask.state.is_held
or itask.state.is_queued
):
# Remove orphaned task if it hasn't started running yet.
self.remove(itask, 'task definition removed')
else:
# Keep active orphaned task, but stop it from spawning.
itask.graph_children = {}
LOG.warning(
f"[{itask}] will not spawn children "
"- task definition removed"
)
else:
new_task = TaskProxy(
self.config.get_taskdef(itask.tdef.name),
itask.point, itask.flow_nums, itask.state.status)
itask.copy_to_reload_successor(new_task)
self._swap_out(new_task)
LOG.info(f"[{itask}] reloaded task definition")
if itask.state(*TASK_STATUSES_ACTIVE, TASK_STATUS_PREPARING):
LOG.warning(
f"[{itask}] active with pre-reload settings"
)
# Reassign live tasks to the internal queue
del self.task_queue_mgr
self.task_queue_mgr = IndepQueueManager(
self.config.cfg['scheduling']['queues'],
self.config.get_task_name_list(),
self.config.runtime['descendants']
)
# Now queue all tasks that are ready to run
for itask in self.get_tasks():
# Recreate data store elements from main pool.
self.create_data_store_elements(itask)
if itask.state.is_queued:
# Already queued
continue
ready_check_items = itask.is_ready_to_run()
# Use this periodic checking point for data-store delta
# creation, some items aren't event driven (i.e. clock).
if itask.tdef.clocktrigger_offset is not None:
self.data_store_mgr.delta_task_clock_trigger(
itask, ready_check_items)
if all(ready_check_items) and not itask.state.is_runahead:
self.queue_task(itask)
self.do_reload = False
def set_stop_point(self, stop_point: 'PointBase') -> bool:
"""Set the workflow stop cycle point.
And reset the runahead limit if less than the stop point.
"""
if self.stop_point == stop_point:
LOG.info(f"Stop point unchanged: {stop_point}")
return False
LOG.info("Setting stop point: {stop_point}")
self.stop_point = stop_point
if (
self.runahead_limit_point is not None
and self.runahead_limit_point > stop_point
):
self.runahead_limit_point = stop_point
# Now handle existing waiting tasks (e.g. xtriggered).
for itask in self.get_all_tasks():
if (
itask.point > stop_point
and itask.state(TASK_STATUS_WAITING)
and itask.state_reset(is_runahead=True)
):
self.data_store_mgr.delta_task_runahead(itask)
return True
def can_stop(self, stop_mode):
"""Return True if workflow can stop.
A task is considered active if:
* It is in the active state and not marked with a kill failure.
* It has pending event handlers.
"""
if stop_mode is None:
return False
if stop_mode == StopMode.REQUEST_NOW_NOW:
return True
if self.task_events_mgr._event_timers:
return False
return not any(
(
stop_mode in [StopMode.REQUEST_CLEAN, StopMode.REQUEST_KILL]
and itask.state(*TASK_STATUSES_ACTIVE)
and not itask.state.kill_failed
)
# we don't need to check for preparing tasks because they will be
# reset to waiting on restart
for itask in self.get_tasks()
)
def warn_stop_orphans(self):
"""Log (warning) orphaned tasks on workflow stop."""
orphans = []
orphans_kill_failed = []
for itask in self.get_tasks():
if itask.state(*TASK_STATUSES_ACTIVE):
if itask.state.kill_failed:
orphans_kill_failed.append(itask)
else:
orphans.append(itask)
if orphans_kill_failed:
LOG.warning(
"Orphaned task jobs (kill failed):\n"