Debian Codegraph @

cylc/flow/task_proxy.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 """Provide a class to represent a task proxy in a running workflow."""
18
19 from collections import Counter
20 from fnmatch import fnmatchcase
21 from time import time
22 from typing import (
23 TYPE_CHECKING,
24 Any,
25 Callable,
26 Counter as TypingCounter,
27 Dict,
28 Iterable,
29 List,
30 Optional,
31 Set,
32 )
33
34 from metomi.isodatetime.timezone import get_local_time_zone
35
36 from cylc.flow import LOG
37 from cylc.flow.cycling.iso8601 import (
38 interval_parse,
39 point_parse,
40 )
41 from cylc.flow.flow_mgr import repr_flow_nums
42 from cylc.flow.platforms import get_platform
43 from cylc.flow.run_modes import RunMode
44 from cylc.flow.task_action_timer import TimerFlags
45 from cylc.flow.task_state import (
46 TASK_STATUS_EXPIRED,
47 TASK_STATUS_WAITING,
48 TaskState,
49 )
50 from cylc.flow.taskdef import generate_graph_children
51 from cylc.flow.wallclock import get_unix_time_from_time_string as str2time
52
53
54 if TYPE_CHECKING:
55 from cylc.flow.cycling import PointBase
56 from cylc.flow.flow_mgr import FlowNums
57 from cylc.flow.id import Tokens, TaskTokens
58 from cylc.flow.prerequisite import (
59 PrereqTuple,
60 SatisfiedState,
61 )
62 from cylc.flow.run_modes.simulation import ModeSettings
63 from cylc.flow.task_action_timer import TaskActionTimer
64 from cylc.flow.taskdef import TaskDef
65
66
67 class TaskProxy:
68 """Represent an instance of a cycling task in a running workflow.
69
70 Attributes:
71 .clock_trigger_times:
72 Memoization of clock trigger times (Used for wall_clock xtrigger):
73 {offset string: seconds from epoch}
74 .expire_time:
75 Time in seconds since epoch when this task is considered expired.
76 .identity:
77 Task ID in POINT/NAME syntax.
78 .tokens:
79 Task ID tokens.
80 .is_late:
81 Is the task late?
82 .is_manual_submit:
83 Is the latest job submission due to a manual trigger?
84 .job_vacated:
85 Is the latest job pre-empted (or vacated)?
86 .jobs:
87 A list of job ids associated with the task proxy.
88 .local_job_file_path:
89 Path on workflow host to the latest job script for the task.
90 .late_time:
91 Time in seconds since epoch, beyond which the task is considered
92 late if it is never active.
93 .non_unique_events (collections.Counter):
94 Count non-unique events (e.g. critical, warning, custom).
95 .point:
96 Cycle point of the task.
97 .point_as_seconds:
98 Cycle point as seconds since epoch.
99 .poll_timer:
100 Schedule for polling submitted or running jobs.
101 .reload_successor:
102 The task proxy object that replaces the current instance on reload.
103 This attribute provides a useful link to the latest replacement
104 instance while the current object may still be referenced by a job
105 manipulation command.
106 .submit_num:
107 Number of times the task has attempted job submission.
108 .summary (dict):
109 job_runner_name (str):
110 Name of job runner where latest job is submitted.
111 description (str):
112 Same as the .tdef.rtconfig['meta']['description'] attribute.
113 execution_time_limit (float):
114 Execution time limit of latest job.
115 finished_time (float):
116 Latest job exit time.
117 finished_time_string (str):
118 Latest job exit time as string.
119 platforms_used (dict):
120 Jobs' platform by submit number.
121 label (str):
122 The .point attribute as string.
123 name (str):
124 Same as the .tdef.name attribute.
125 started_time (float):
126 Latest job execution start time.
127 started_time_string (str):
128 Latest job execution start time as string.
129 submit_method_id (str):
130 Latest ID of job in job runner.
131 submit_num (int):
132 Same as the .submit_num attribute.
133 submitted_time (float):
134 Latest job submission time.
135 submitted_time_string (str):
136 Latest job submission time as string.
137 title (str):
138 Same as the .tdef.rtconfig['meta']['title'] attribute.
139 .state:
140 Object representing the state of this task.
141 .platform:
142 Dict containing info for platform where latest job is submitted.
143 .tdef:
144 The definition object of this task.
145 .timeout:
146 Timeout value in seconds since epoch for latest job
147 submission/execution.
148 .try_timers:
149 Retry schedules as cylc.flow.task_action_timer.TaskActionTimer
150 objects.
151 .graph_children (dict)
152 graph children: {msg: [(name, point), ...]}
153 .flow_nums:
154 flows I belong to (if empty, belongs to 'none' flow)
155 .flow_wait:
156 wait for flow merge before spawning children
157 .waiting_on_job_prep:
158 True whilst task is awaiting job prep, reset to False once the
159 preparation has completed.
160 .transient:
161 This is a transient proxy - not to be added to the task pool, but
162 used e.g. to spawn children, or to get task-specific information.
163 .is_xtrigger_sequential:
164 A flag used to determine whether this task needs to wait for
165 xtrigger satisfaction to spawn.
166 .removed:
167 A flag to indicate this task has been removed by command (used
168 e.g. to disable failed/submit-failed event handlers).
169
170 Args:
171 tdef: The definition object of this task.
172 start_point: Start point to calculate the task's cycle point on
173 start-up or the cycle point for subsequent tasks.
174 flow_nums: Which flows this task belongs to.
175 status: Task state string.
176 is_held: True if the task is held, else False.
177 submit_num: Number of times the task has attempted job submission.
178 is_late: Is the task late?
179 data_mode: Reduced store reference data.
180 """
181
182 # Memory optimization - constrain possible attributes to this list.
183 __slots__ = (
184 'clock_trigger_times',
185 'expire_time',
186 'identity',
187 'is_late',
188 'is_manual_submit',
189 'job_vacated',
190 'jobs',
191 'late_time',
192 'local_job_file_path',
193 'non_unique_events',
194 'point',
195 'point_as_seconds',
196 'poll_timer',
197 'reload_successor',
198 'run_mode',
199 'submit_num',
200 'tdef',
201 'state',
202 'summary',
203 'flow_nums',
204 'flow_wait',
205 'graph_children',
206 'platform',
207 'timeout',
208 'tokens',
209 'try_timers',
210 'waiting_on_job_prep',
211 'mode_settings',
212 'transient',
213 'is_xtrigger_sequential',
214 'removed',
215 )
216
217 def __init__(
218 self,
219 scheduler_tokens: 'Tokens',
220 tdef: 'TaskDef',
221 point: 'PointBase',
222 flow_nums: 'FlowNums | None' = None,
223 status: str = TASK_STATUS_WAITING,
224 is_held: bool = False,
225 submit_num: int | None = 0,
226 is_late: bool = False,
227 is_manual_submit: bool = False,
228 flow_wait: bool = False,
229 data_mode: bool = False,
230 transient: bool = False,
231 sequential_xtrigger_labels: Optional[Set[str]] = None,
232 ) -> None:
233
234 self.tdef = tdef
235 if submit_num is None:
236 submit_num = 0
237 self.submit_num = submit_num
238 self.jobs: List[dict] = []
239 if flow_nums is None:
240 self.flow_nums = set()
241 else:
242 # (don't share flow_nums ref with parent task)
243 self.flow_nums = flow_nums.copy()
244 self.flow_wait = flow_wait
245 self.point = point
246 self.tokens: TaskTokens = scheduler_tokens.duplicate(
247 cycle=str(self.point),
248 task=self.tdef.name,
249 )
250 self.identity = self.tokens.relative_id
251 self.reload_successor: Optional['TaskProxy'] = None
252 self.point_as_seconds: Optional[int] = None
253
254 self.is_manual_submit = is_manual_submit
255 self.summary: Dict[str, Any] = {
256 'submitted_time': None,
257 'submitted_time_string': None,
258 'started_time': None,
259 'started_time_string': None,
260 'finished_time': None,
261 'finished_time_string': None,
262 'platforms_used': {},
263 'execution_time_limit': None,
264 'job_runner_name': None,
265 'submit_method_id': None,
266 'flow_nums': set(),
267 'flow_wait': self.flow_wait
268 }
269
270 self.local_job_file_path: Optional[str] = None
271
272 if data_mode:
273 self.platform = {}
274 else:
275 self.platform = get_platform()
276
277 self.transient = transient
278
279 self.job_vacated = False
280 self.poll_timer: Optional['TaskActionTimer'] = None
281 self.timeout: Optional[float] = None
282 self.try_timers: Dict[str, 'TaskActionTimer'] = {}
283 self.non_unique_events: TypingCounter[str] = Counter()
284
285 self.clock_trigger_times: Dict[str, int] = {}
286 self.expire_time: Optional[float] = None
287 self.late_time: Optional[float] = None
288 self.is_late = is_late
289 self.waiting_on_job_prep = False
290 self.removed: bool = False
291
292 self.state = TaskState(tdef, self.point, status, is_held)
293
294 # Set xtrigger checking type, which effects parentless spawning.
295 self.is_xtrigger_sequential = bool(
296 sequential_xtrigger_labels
297 and self.tdef.is_parentless(
298 self.point, cutoff=self.tdef.initial_point
299 )
300 and sequential_xtrigger_labels.intersection(self.state.xtriggers)
301 )
302
303 # Determine graph children of this task (for spawning).
304 if data_mode:
305 self.graph_children = {}
306 else:
307 self.graph_children = generate_graph_children(tdef, self.point)
308
309 self.mode_settings: Optional['ModeSettings'] = None
310 self.run_mode: Optional[RunMode] = None
311
312 if self.tdef.expiration_offset is not None:
313 self.expire_time = (
314 self.get_point_as_seconds() +
315 self.get_offset_as_seconds(
316 self.tdef.expiration_offset
317 )
318 )
319
320 @property
321 def job_tokens(self) -> 'Tokens':
322 """Return the job tokens for this task proxy."""
323 return self.tokens.duplicate(job=str(self.submit_num))
324
325 def __repr__(self) -> str:
326 return f"<{type(self).__name__} {self.identity} {self.state}>"
327
328 def __str__(self) -> str:
329 """Stringify with tokens, state, submit_num, and flow_nums.
330
331 Don't print submit number for pre job-prep states.
332
333 Format: "<point>/<name>/<job>{<flows>}:status".
334 """
335 id_ = self.identity
336 if not self.state(TASK_STATUS_WAITING, TASK_STATUS_EXPIRED):
337 id_ += f"/{self.submit_num:02d}"
338 return (
339 f"{id_}{repr_flow_nums(self.flow_nums)}:{self.state}"
340 )
341
342 def copy_to_reload_successor(
343 self,
344 reload_successor: 'TaskProxy',
345 check_output: Callable[[str, str, str, 'FlowNums'], 'SatisfiedState'],
346 ):
347 """Copy attributes to successor on reload of this task proxy."""
348 self.reload_successor = reload_successor
349 reload_successor.submit_num = self.submit_num
350 reload_successor.flow_wait = self.flow_wait
351 reload_successor.is_manual_submit = self.is_manual_submit
352 reload_successor.summary = self.summary
353 reload_successor.local_job_file_path = self.local_job_file_path
354 reload_successor.try_timers = self.try_timers
355 reload_successor.platform = self.platform
356 reload_successor.job_vacated = self.job_vacated
357 reload_successor.poll_timer = self.poll_timer
358 reload_successor.timeout = self.timeout
359 reload_successor.state.outputs = self.state.outputs
360 reload_successor.state.is_held = self.state.is_held
361 reload_successor.state.is_runahead = self.state.is_runahead
362 reload_successor.state.is_updated = self.state.is_updated
363 reload_successor.mode_settings = self.mode_settings
364
365 # Prerequisites: the graph might have changed before reload, so
366 # we need to use the new prerequisites but update them with the
367 # pre-reload state of prerequisites that still exist post-reload.
368
369 # Get all prereq states, e.g. {('1', 'c', 'succeeded'): False, ...}
370 pre_reload: Dict[PrereqTuple, SatisfiedState] = {
371 k: v
372 for pre in self.state.prerequisites
373 for (k, v) in pre.items()
374 }
375 # Use them to update the new prerequisites.
376 # - unchanged prerequisites will keep their pre-reload state.
377 # - removed prerequisites will not be carried over
378 # - added prerequisites will be recorded as unsatisfied
379 # NOTE: even if the corresponding output was completed pre-reload!
380 for pre in reload_successor.state.prerequisites:
381 for k in pre:
382 pre[k] = pre_reload.get(
383 k,
384 # Else look thru task outputs to see if it's been satisfied
385 check_output(*k, self.flow_nums)
386 )
387
388 # Carry over any satisfied xtrigger prerequisites.
389 for xtrig in reload_successor.state.xtriggers:
390 reload_successor.state.xtriggers[xtrig] = (
391 self.state.xtriggers.get(xtrig, False)
392 )
393
394 reload_successor.state.xtriggers.update({
395 # Copy across any auto-defined "_cylc" xtriggers runtime (retries),
396 # but avoid "_cylc_wallclock" xtriggers which are user-defined.
397 key: value
398 for key, value in self.state.xtriggers.items()
399 if (
400 key.startswith('_cylc') and not
401 key.startswith('_cylc_wallclock')
402 )
403 })
404 reload_successor.jobs = self.jobs
405
406 @staticmethod
407 def get_offset_as_seconds(offset):
408 """Return an ISO interval as seconds."""
409 iso_offset = interval_parse(str(offset))
410 return int(iso_offset.get_seconds())
411
412 def get_late_time(self):
413 """Compute and store late time as seconds since epoch."""
414 if self.late_time is None:
415 if self.tdef.rtconfig['events']['late offset']:
416 self.late_time = (
417 self.get_point_as_seconds() +
418 self.tdef.rtconfig['events']['late offset'])
419 else:
420 # Not used, but allow skip of the above "is None" test
421 self.late_time = 0
422 return self.late_time
423
424 def get_point_as_seconds(self):
425 """Compute and store my cycle point as seconds since epoch."""
426 if self.point_as_seconds is None:
427 iso_timepoint = point_parse(str(self.point))
428 self.point_as_seconds = int(iso_timepoint.seconds_since_unix_epoch)
429 if iso_timepoint.time_zone.unknown:
430 utc_offset_hours, utc_offset_minutes = (
431 get_local_time_zone())
432 utc_offset_in_seconds = (
433 3600 * utc_offset_hours + 60 * utc_offset_minutes)
434 self.point_as_seconds += utc_offset_in_seconds
435 return self.point_as_seconds
436
437 def get_clock_trigger_time(
438 self,
439 point: 'PointBase', offset_str: Optional[str] = None
440 ) -> int:
441 """Compute, cache and return trigger time relative to cycle point.
442
443 Args:
444 point: Task's cycle point.
445 offset_str: ISO8601 interval string, e.g. "PT2M".
446 Can be None for zero offset.
447 Returns:
448 Absolute trigger time in seconds since Unix epoch.
449
450 """
451 offset_str = offset_str if offset_str else 'P0Y'
452 if offset_str not in self.clock_trigger_times:
453 # Convert ISO8601Point into metomi-isodatetime TimePoint at full
454 # second precision (N.B. it still dumps at the same precision
455 # as workflow cycle point format):
456 point_time = point_parse(str(point))
457 if offset_str == 'P0Y':
458 trigger_time = point_time
459 else:
460 trigger_time = point_time + interval_parse(offset_str)
461
462 self.clock_trigger_times[offset_str] = int(
463 trigger_time.seconds_since_unix_epoch
464 )
465 return self.clock_trigger_times[offset_str]
466
467 def get_try_num(self):
468 """Return the number of automatic tries (try number)."""
469 try:
470 return self.try_timers[TimerFlags.EXECUTION_RETRY].num + 1
471 except (AttributeError, KeyError):
472 return 0
473
474 def is_ready_to_run(self) -> bool:
475 """Is this task ready to run?
476
477 Return True if not held, no active try timers, and prerequisites done.
478
479 """
480 if self.state.is_held:
481 # A held task is not ready to run.
482 return False
483 if self.state.status in self.try_timers:
484 # A try timer is still active.
485 return self.try_timers[self.state.status].is_delay_done()
486 return (
487 self.state(TASK_STATUS_WAITING)
488 and self.prereqs_are_satisfied()
489 and self.state.external_triggers_all_satisfied()
490 and self.state.xtriggers_all_satisfied()
491 )
492
493 def set_summary_time(self, event_key, time_str=None):
494 """Set an event time in self.summary
495
496 Set values of both event_key + "_time" and event_key + "_time_string".
497 """
498 if time_str is None:
499 self.summary[event_key + '_time'] = None
500 else:
501 self.summary[event_key + '_time'] = float(str2time(time_str))
502 self.summary[event_key + '_time_string'] = time_str
503
504 def prereqs_are_satisfied(self) -> bool:
505 """Are all task prerequisites satisfied?"""
506 return all(pre.is_satisfied() for pre in self.state.prerequisites)
507
508 def reset_try_timers(self):
509 # unset any retry delay timers
510 for timer in self.try_timers.values():
511 timer.timeout = None
512
513 def status_match(self, status: Optional[str]) -> bool:
514 """Return whether a string matches the task's status.
515
516 None/an empty string is treated as a match.
517 """
518 return (not status) or self.state.status == status
519
520 def name_match(
521 self,
522 value: str,
523 match_func: Callable[[Any, Any], bool] = fnmatchcase
524 ) -> bool:
525 """Return whether a string/pattern matches the task's name or any of
526 its parent family names."""
527 return match_func(self.tdef.name, value) or any(
528 match_func(ns, value) for ns in self.tdef.namespace_hierarchy
529 )
530
531 def match_flows(self, flow_nums: 'FlowNums') -> 'FlowNums':
532 """Return which of the given flow numbers the task belongs to.
533
534 NOTE: If `flow_nums` is empty, it means 'all', whereas
535 if `self.flow_nums` is empty, it means this task is in the 'none' flow
536 and will not match.
537 """
538 if not flow_nums or not self.flow_nums:
539 return self.flow_nums.copy()
540 return self.flow_nums.intersection(flow_nums)
541
542 def merge_flows(self, flow_nums: Set) -> None:
543 """Merge another set of flow_nums with mine."""
544 self.flow_nums.update(flow_nums)
545 LOG.info(
546 f"[{self}] merged in flow(s) "
547 f"{','.join(str(f) for f in flow_nums)}"
548 )
549
550 def state_reset(
551 self, status=None, is_held=None, is_queued=None, is_runahead=None,
552 silent=False, forced=False
553 ) -> bool:
554 """Set new state and log the change. Return whether it changed.
555
556 """
557 before = str(self)
558
559 if status == TASK_STATUS_EXPIRED:
560 is_queued = False
561 is_runahead = False
562
563 if self.state.reset(
564 status, is_held, is_queued, is_runahead, forced
565 ):
566 if not silent and not self.transient:
567 LOG.info(f"[{before}] => {self.state}")
568 return True
569
570 return False
571
572 def satisfy_me(
573 self,
574 task_messages: 'Iterable[Tokens]',
575 mode: Optional[RunMode] = RunMode.LIVE,
576 ) -> None:
577 """Try to satisfy my prerequisites with given task output messages.
578
579 Output format: "cycle/task:message"
580
581 """
582 for prereq in (
583 *self.state.prerequisites, *self.state.suicide_prerequisites
584 ):
585 prereq.satisfy_me(task_messages, mode=mode)
586
587 def force_satisfy(
588 self, prereqs: 'Iterable[PrereqTuple]', set_all: bool = False
589 ) -> None:
590 """Force satisfy given task prerequisites.
591
592 Only called via "cylc set" command so no need to record run mode.
593
594 """
595 for prereq in self.state.prerequisites:
596 for pre, state in prereq.items():
597 # (PrereqTuple, False or "satisfied naturally" etc.)
598 if not set_all and pre not in prereqs:
599 continue
600 if not state:
601 prereq[pre] = "force satisfied"
602 LOG.info(
603 f"[{self}] prerequisite force-satisfied:"
604 f" {pre.get_id(True)}"
605 )
606 else:
607 LOG.info(
608 f"[{self}] prerequisite already satisfied:"
609 f" {pre.get_id(True)}"
610 )
611
612 def force_satisfy_external_triggers(self):
613 """Set all external triggers to satisfied - via 'cylc trigger'."""
614 for ext in self.state.external_triggers:
615 LOG.info(f'[{self}] external trigger force-satisfied: "{ext}"')
616 self.state.external_triggers[ext] = True
617
618 def clock_expire(self) -> bool:
619 """Return True if clock expire time is up, else False."""
620 if (
621 self.expire_time is None # expiry not configured
622 or self.state(TASK_STATUS_EXPIRED) # already expired
623 or time() < self.expire_time # not time yet
624 ):
625 return False
626 return True
627
628 def is_complete(self) -> bool:
629 """Return True if complete or expired."""
630 return self.state.outputs.is_complete()