Debian Codegraph @

cylc/flow/task_state.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Task state related logic."""
18
19 from typing import (
20 TYPE_CHECKING,
21 Dict,
22 List,
23 Optional,
24 )
25
26 from cylc.flow.prerequisite import Prerequisite
27 from cylc.flow.task_outputs import (
28 TASK_OUTPUT_EXPIRED,
29 TASK_OUTPUT_FAILED,
30 TASK_OUTPUT_STARTED,
31 TASK_OUTPUT_SUBMIT_FAILED,
32 TASK_OUTPUT_SUBMITTED,
33 TASK_OUTPUT_SUCCEEDED,
34 TaskOutputs,
35 )
36 from cylc.flow.wallclock import get_current_time_string
37
38
39 if TYPE_CHECKING:
40 from cylc.flow.cycling import PointBase
41 from cylc.flow.prerequisite import PrereqTuple
42 from cylc.flow.taskdef import TaskDef
43
44
45 # Task status names and meanings.
46 # Held back from job submission due to un-met prerequisites:
47 TASK_STATUS_WAITING = "waiting"
48 # Preparing for job submission
49 TASK_STATUS_PREPARING = "preparing"
50 # Prerequisites unmet for too long - will never be submitted now:
51 TASK_STATUS_EXPIRED = "expired"
52 # Job submitted to run:
53 TASK_STATUS_SUBMITTED = "submitted"
54 # Job submission failed:
55 TASK_STATUS_SUBMIT_FAILED = "submit-failed"
56 # Job submission failed but will try again soon:
57 # Job execution started, but not completed yet:
58 TASK_STATUS_RUNNING = "running"
59 # Job execution completed successfully:
60 TASK_STATUS_SUCCEEDED = "succeeded"
61 # Job execution failed:
62 TASK_STATUS_FAILED = "failed"
63 # Job execution failed, but will try again soon:
64
65 TASK_STATUS_DESC = {
66 TASK_STATUS_WAITING:
67 'Waiting for dependencies to be satisfied.',
68 TASK_STATUS_EXPIRED:
69 'Execution skipped.',
70 TASK_STATUS_PREPARING:
71 'Cylc is preparing a job for submission.',
72 TASK_STATUS_SUBMIT_FAILED:
73 'Job submission has failed.',
74 TASK_STATUS_SUBMITTED:
75 'Job has been submitted.',
76 TASK_STATUS_RUNNING:
77 'Job is running.',
78 TASK_STATUS_FAILED:
79 'Job has returned non-zero exit code.',
80 TASK_STATUS_SUCCEEDED:
81 'Job has returned zero exit code.'
82 }
83
84 # Task statuses ordered according to task runtime progression.
85 TASK_STATUSES_ORDERED = [
86 TASK_STATUS_WAITING,
87 TASK_STATUS_EXPIRED,
88 TASK_STATUS_PREPARING,
89 TASK_STATUS_SUBMIT_FAILED,
90 TASK_STATUS_SUBMITTED,
91 TASK_STATUS_RUNNING,
92 TASK_STATUS_FAILED,
93 TASK_STATUS_SUCCEEDED
94 ]
95
96 # Task statuses ordered according to display importance
97 TASK_STATUS_DISPLAY_ORDER = [
98 TASK_STATUS_SUBMIT_FAILED,
99 TASK_STATUS_FAILED,
100 TASK_STATUS_RUNNING,
101 TASK_STATUS_SUBMITTED,
102 TASK_STATUS_EXPIRED,
103 TASK_STATUS_PREPARING,
104 TASK_STATUS_SUCCEEDED,
105 TASK_STATUS_WAITING,
106 ]
107
108 TASK_STATUSES_ALL = set(TASK_STATUSES_ORDERED)
109
110 # Tasks statuses to show in restricted monitoring mode.
111 TASK_STATUSES_RESTRICTED = {
112 TASK_STATUS_EXPIRED,
113 TASK_STATUS_SUBMITTED,
114 TASK_STATUS_SUBMIT_FAILED,
115 TASK_STATUS_RUNNING,
116 TASK_STATUS_FAILED,
117 }
118
119 # Tasks statuses to show in restricted monitoring mode.
120 TASK_STATUSES_NO_JOB_FILE = {
121 TASK_STATUS_WAITING,
122 TASK_STATUS_PREPARING,
123 TASK_STATUS_EXPIRED,
124 }
125
126 # Task statuses we can manually reset a task TO.
127 TASK_STATUSES_CAN_RESET_TO = {
128 TASK_STATUS_SUBMITTED,
129 TASK_STATUS_SUBMIT_FAILED,
130 TASK_STATUS_RUNNING,
131 TASK_STATUS_WAITING,
132 TASK_STATUS_EXPIRED,
133 TASK_STATUS_SUCCEEDED,
134 TASK_STATUS_FAILED,
135 }
136
137 # Task statuses that are final.
138 TASK_STATUSES_SUCCESS = {
139 TASK_STATUS_EXPIRED,
140 TASK_STATUS_SUCCEEDED,
141 }
142 TASK_STATUSES_FAILURE = {
143 TASK_STATUS_FAILED,
144 TASK_STATUS_SUBMIT_FAILED,
145 }
146 TASK_STATUSES_FINAL = TASK_STATUSES_SUCCESS | TASK_STATUSES_FAILURE
147
148 # Task statuses that are never active.
149 # For tasks that have never been submitted, but excluding:
150 # - expired: which is effectively the "succeeded" final state.
151 # - held: which is placeholder state, not a real state.
152 TASK_STATUSES_NEVER_ACTIVE = {
153 TASK_STATUS_WAITING,
154 TASK_STATUS_PREPARING,
155 }
156
157 # Task statuses that are externally active
158 TASK_STATUSES_ACTIVE = {
159 TASK_STATUS_SUBMITTED,
160 TASK_STATUS_RUNNING,
161 }
162
163 # Mapping between task outputs and their corresponding states
164 TASK_STATE_MAP = {
165 # status: trigger
166 TASK_STATUS_WAITING: None,
167 TASK_STATUS_EXPIRED: TASK_OUTPUT_EXPIRED,
168 TASK_STATUS_PREPARING: None,
169 TASK_STATUS_SUBMIT_FAILED: TASK_OUTPUT_SUBMIT_FAILED,
170 TASK_STATUS_SUBMITTED: TASK_OUTPUT_SUBMITTED,
171 TASK_STATUS_RUNNING: TASK_OUTPUT_STARTED,
172 TASK_STATUS_FAILED: TASK_OUTPUT_FAILED,
173 TASK_STATUS_SUCCEEDED: TASK_OUTPUT_SUCCEEDED,
174 }
175
176
177 def status_leq(status_a, status_b):
178 """"Return True if status_a <= status_b"""
179 return (TASK_STATUSES_ORDERED.index(status_a) <=
180 TASK_STATUSES_ORDERED.index(status_b))
181
182
183 def status_geq(status_a, status_b):
184 """"Return True if status_a >= status_b"""
185 return (TASK_STATUSES_ORDERED.index(status_a) >=
186 TASK_STATUSES_ORDERED.index(status_b))
187
188
189 class TaskState:
190 """Task status and utilities.
191
192 Attributes:
193 .external_triggers (dict):
194 External triggers as {trigger (str): satisfied (boolean), ...}.
195 .is_held (bool):
196 True if the task is held else False.
197 .is_queued (bool):
198 True if the task is queued else False.
199 .is_runahead (bool):
200 True if the task is runahead limited else False.
201 Automatically true until released by the scheduler.
202 .is_updated (boolean):
203 Has the status been updated since previous update?
204 .kill_failed (boolean):
205 Has a job kill attempt failed since previous status change?
206 .outputs (cylc.flow.task_outputs.TaskOutputs):
207 Known outputs of the task.
208 .prerequisites (list<cylc.flow.prerequisite.Prerequisite>):
209 List of prerequisites of the task.
210 .status (str):
211 The current status of the task.
212 .suicide_prerequisites (list<cylc.flow.prerequisite.Prerequisite>):
213 List of prerequisites that will cause the task to suicide.
214 .time_updated (str):
215 Time string of latest update time.
216 .xtriggers (dict):
217 xtriggers as {trigger (str): satisfied (boolean), ...}.
218 """
219
220 # Memory optimization - constrain possible attributes to this list.
221 __slots__ = [
222 "external_triggers",
223 "is_held",
224 "is_queued",
225 "is_runahead",
226 "is_updated",
227 "kill_failed",
228 "outputs",
229 "prerequisites",
230 "status",
231 "suicide_prerequisites",
232 "time_updated",
233 "xtriggers",
234 ]
235
236 def __init__(self, tdef, point, status, is_held):
237 self.status = status
238 self.is_held = is_held
239 self.is_queued = False
240 self.is_runahead = True
241 self.is_updated = False
242 self.time_updated = None
243
244 # Prerequisites.
245 self.prerequisites: List[Prerequisite] = []
246 self.suicide_prerequisites: List[Prerequisite] = []
247 self._add_prerequisites(point, tdef)
248
249 # External Triggers.
250 self.external_triggers = {}
251 for ext in tdef.external_triggers:
252 # Allow cycle-point-specific external triggers - GitHub #1893.
253 if '$CYLC_TASK_CYCLE_POINT' in ext:
254 ext = ext.replace('$CYLC_TASK_CYCLE_POINT', str(point))
255 # set unsatisfied
256 self.external_triggers[ext] = False
257
258 # xtriggers (represented by labels) satisfied or not
259 self.xtriggers = {}
260 self._add_xtriggers(point, tdef)
261
262 # Message outputs.
263 self.outputs = TaskOutputs(tdef)
264 self.kill_failed = False
265
266 def __str__(self):
267 """Print status(is_held)(is_queued)(is_runahead)."""
268 ret = self.status
269 if self.is_held:
270 ret += '(held)'
271 if self.is_queued:
272 ret += '(queued)'
273 if self.is_runahead:
274 ret += '(runahead)'
275 return ret
276
277 def __repr__(self) -> str:
278 return f"<{type(self).__name__} {self}>"
279
280 def __call__(
281 self,
282 *status: Optional[str],
283 is_held: Optional[bool] = None,
284 is_queued: Optional[bool] = None,
285 is_runahead: Optional[bool] = None,
286 ) -> bool:
287 """Compare task state attributes.
288
289 Args:
290 status:
291 Check if the task status is one of the ones provided, or
292 do not check the task state if None.
293 is_held:
294 Check the task is_held attribute is the same as provided, or
295 do not check the is_held attribute if None.
296 is_queued:
297 Check the task is_queued attribute is the same as provided, or
298 do not check the is_queued attribute if None.
299 is_runahead:
300 Check the task is_runahead attribute is as provided, or
301 do not check the is_runahead attribute if None.
302
303 """
304 return (
305 (
306 not status
307 or self.status in status
308 ) and (
309 is_held is None
310 or self.is_held == is_held
311 ) and (
312 is_queued is None
313 or self.is_queued == is_queued
314 ) and (
315 is_runahead is None
316 or self.is_runahead == is_runahead
317 )
318 )
319
320 def xtriggers_all_satisfied(self):
321 """Return True if all xtriggers are satisfied."""
322 return all(self.xtriggers.values())
323
324 def external_triggers_all_satisfied(self):
325 """Return True if all external triggers are satisfied."""
326 return all(self.external_triggers.values())
327
328 def prerequisites_all_satisfied(self):
329 """Return True if (non-suicide) prerequisites are fully satisfied."""
330 return all(preq.is_satisfied() for preq in self.prerequisites)
331
332 def prerequisites_are_not_all_satisfied(self):
333 """Return True if (any) prerequisites are not fully satisfied."""
334 return (not self.prerequisites_all_satisfied() or
335 not self.suicide_prerequisites_all_satisfied())
336
337 def suicide_prerequisites_all_satisfied(self):
338 """Return True if all suicide prerequisites are satisfied."""
339 return all(preq.is_satisfied() for preq in self.suicide_prerequisites)
340
341 def prerequisites_get_target_points(self):
342 """Return a list of cycle points targeted by each prerequisite."""
343 return {
344 point
345 for prerequisite in self.prerequisites
346 for point in prerequisite.get_target_points()
347 }
348
349 def prerequisites_eval_all(self) -> None:
350 """Evaluate satisifaction of all prerequisites and
351 suicide prerequisites.
352
353 Provides validation - will abort on illegal trigger expressions.
354 """
355 for preqs in [self.prerequisites, self.suicide_prerequisites]:
356 for preq in preqs:
357 preq.is_satisfied()
358
359 def set_all_task_prerequisites_satisfied(self):
360 """Set all task prerequisites satisfied."""
361 for prereq in self.prerequisites:
362 prereq.set_satisfied()
363
364 def get_resolved_dependencies(self):
365 """Return a list of dependencies which have been met for this task
366 (ignoring the specific output in the depedency).
367
368 E.G: ['1/foo', '2/bar']
369
370 The returned list is sorted to allow comparison with reference run
371 task with lots of near-simultaneous triggers.
372
373 """
374 return sorted(
375 task_output.get_id()
376 for prereq in self.prerequisites
377 for task_output, satisfied in prereq._satisfied.items()
378 if satisfied
379 )
380
381 def reset(
382 self, status=None, is_held=None, is_queued=None, is_runahead=None,
383 forced=False
384 ):
385 """Change status.
386
387 Args:
388 status (str):
389 Task status to reset to or None to leave the status unchanged.
390 is_held (bool):
391 Set the task to be held or not, or None to leave this property
392 unchanged.
393 forced (bool):
394 If called as a result of a forced change (via "cylc set")
395
396 Returns:
397 Whether state changed or not (bool)
398
399 """
400 req = status
401
402 if forced and req in [TASK_STATUS_SUBMITTED, TASK_STATUS_RUNNING]:
403 # Can't force change to an active state because there's no job.
404 return False
405
406 current_status = (
407 self.status,
408 self.is_held,
409 self.is_queued,
410 self.is_runahead
411 )
412 requested_status = (
413 status if status is not None else self.status,
414 is_held if is_held is not None else self.is_held,
415 is_queued if is_queued is not None else self.is_queued,
416 is_runahead if is_runahead is not None else self.is_runahead
417 )
418 if current_status == requested_status:
419 # no change - do nothing
420 return False
421
422 # perform the state change
423 self.status, self.is_held, self.is_queued, self.is_runahead = (
424 requested_status
425 )
426
427 self.time_updated = get_current_time_string()
428 self.is_updated = True
429 self.kill_failed = False
430
431 if status is None:
432 # NOTE: status is None if the task is being released
433 status = self.status
434
435 return True
436
437 def is_gt(self, status):
438 """"Return True if self.status > status."""
439 return (TASK_STATUSES_ORDERED.index(self.status) >
440 TASK_STATUSES_ORDERED.index(status))
441
442 def is_gte(self, status):
443 """"Return True if self.status >= status."""
444 return (TASK_STATUSES_ORDERED.index(self.status) >=
445 TASK_STATUSES_ORDERED.index(status))
446
447 def _add_prerequisites(self, point: 'PointBase', tdef: 'TaskDef'):
448 """Add task prerequisites."""
449 # Triggers for sequence_i only used if my cycle point is a
450 # valid member of sequence_i's sequence of cycle points.
451
452 # Use dicts to avoid generating duplicate prerequisites from sequences
453 # with coincident cycle points.
454 prerequisites: Dict[int, Prerequisite] = {}
455 suicide_prerequisites: Dict[int, Prerequisite] = {}
456
457 for sequence, dependencies in tdef.dependencies.items():
458 if not sequence.is_valid(point):
459 continue
460 for dependency in dependencies:
461 cpre = dependency.get_prerequisite(point, tdef)
462 if dependency.suicide:
463 suicide_prerequisites[cpre.instantaneous_hash()] = cpre
464 else:
465 prerequisites[cpre.instantaneous_hash()] = cpre
466
467 if tdef.sequential:
468 # Add a previous-instance succeeded prerequisite.
469 adjusted = []
470 for seq in tdef.sequences:
471 prv = seq.get_nearest_prev_point(point)
472 if prv:
473 # None if out of sequence bounds.
474 adjusted.append(prv)
475 if adjusted:
476 p_prev = max(adjusted)
477 cpre = Prerequisite(point)
478 cpre[(p_prev, tdef.name, TASK_STATUS_SUCCEEDED)] = (
479 p_prev < tdef.start_point
480 )
481 cpre.set_conditional_expr(tdef.name)
482 prerequisites[cpre.instantaneous_hash()] = cpre
483
484 self.suicide_prerequisites = list(suicide_prerequisites.values())
485 self.prerequisites = list(prerequisites.values())
486
487 def add_xtrigger(self, label, satisfied=False):
488 self.xtriggers[label] = satisfied
489
490 def get_xtrigger(self, label):
491 return self.xtriggers[label]
492
493 def _add_xtriggers(self, point, tdef):
494 """Add task xtriggers valid for the current sequence.
495
496 Initialize each one to unsatisfied.
497 """
498 # Triggers for sequence_i only used if my cycle point is a
499 # valid member of sequence_i's sequence of cycle points.
500 for sequence, xtrig_labels in tdef.xtrig_labels.items():
501 if not sequence.is_valid(point):
502 continue
503 for xtrig_label in xtrig_labels:
504 self.add_xtrigger(xtrig_label)
505
506 def get_unsatisfied_prerequisites(self) -> List['PrereqTuple']:
507 return [
508 key
509 for prereq in self.prerequisites if not prereq.is_satisfied()
510 for key, satisfied in prereq.items() if not satisfied
511 ]
512
513 def any_satisfied_prerequisite_outputs(self) -> bool:
514 """Return True if any of this task's prerequisite outputs are
515 satisfied."""
516 return any(
517 satisfied
518 for prereq in self.prerequisites
519 for satisfied in prereq._satisfied.values()
520 )