forked from cylc/cylc-flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_events_mgr.py
More file actions
2085 lines (1865 loc) · 73.6 KB
/
task_events_mgr.py
File metadata and controls
2085 lines (1865 loc) · 73.6 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/>.
"""Task events manager.
This module provides logic to:
* Manage task messages (internal, polled or received).
* Set up retries on job failures (submission or execution).
* Generate task event handlers.
* Retrieval of log files for completed remote jobs.
* Email notification.
* Custom event handlers.
* Manage invoking and retrying of task event handlers.
"""
from contextlib import suppress
from enum import Enum
from logging import (
DEBUG,
INFO,
getLevelName,
)
import logging
import os
from pathlib import Path
import shlex
from shlex import quote
from time import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
NamedTuple,
Optional,
Sequence,
Set,
Union,
cast,
)
from cylc.flow import (
LOG,
LOG_LEVELS,
)
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
from cylc.flow.cycling.loader import get_point
from cylc.flow.exceptions import (
NoHostsError,
PlatformLookupError,
)
from cylc.flow.hostuserutil import (
get_host,
get_user,
is_remote_platform,
)
from cylc.flow.parsec.config import ItemNotFoundError
from cylc.flow.pathutil import (
get_remote_workflow_run_job_dir,
get_workflow_run_job_dir,
)
from cylc.flow.platforms import (
get_host_from_platform,
get_platform,
log_platform_event,
)
from cylc.flow.run_modes import (
JOBLESS_MODES,
RunMode,
disable_task_event_handlers,
)
from cylc.flow.subprocctx import (
SubFuncContext,
SubProcContext,
)
from cylc.flow.task_action_timer import (
TaskActionTimer,
TimerFlags,
)
from cylc.flow.task_job_logs import (
JOB_LOG_ERR,
JOB_LOG_OUT,
get_task_job_activity_log,
get_task_job_log,
)
from cylc.flow.task_message import (
ABORT_MESSAGE_PREFIX,
FAIL_MESSAGE_PREFIX,
VACATION_MESSAGE_PREFIX,
split_run_signal,
)
from cylc.flow.task_outputs import (
TASK_OUTPUT_EXPIRED,
TASK_OUTPUT_FAILED,
TASK_OUTPUT_STARTED,
TASK_OUTPUT_SUBMIT_FAILED,
TASK_OUTPUT_SUBMITTED,
TASK_OUTPUT_SUCCEEDED,
)
from cylc.flow.task_proxy import TaskProxy
from cylc.flow.task_state import (
TASK_STATUS_EXPIRED,
TASK_STATUS_FAILED,
TASK_STATUS_PREPARING,
TASK_STATUS_RUNNING,
TASK_STATUS_SUBMIT_FAILED,
TASK_STATUS_SUBMITTED,
TASK_STATUS_SUCCEEDED,
TASK_STATUS_WAITING,
TASK_STATUSES_ACTIVE,
)
from cylc.flow.wallclock import (
get_current_time_string,
get_seconds_as_interval_string as intvl_as_str,
)
from cylc.flow.workflow_events import (
EventData as WorkflowEventData,
construct_mail_cmd,
get_template_variables as get_workflow_template_variables,
process_mail_footer,
)
if TYPE_CHECKING:
from cylc.flow.broadcast_mgr import BroadcastMgr
from cylc.flow.cycling import PointBase
from cylc.flow.data_store_mgr import DataStoreMgr
from cylc.flow.id import Tokens
from cylc.flow.scheduler import Scheduler
from cylc.flow.taskdef import TaskDef
from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
from cylc.flow.xtrigger_mgr import XtriggerManager
class CustomTaskEventHandlerContext(NamedTuple):
key: Union[str, Sequence[str]]
cmd: str
class TaskEventMailContext(NamedTuple):
key: str
mail_from: str
mail_to: str
class TaskJobLogsRetrieveContext(NamedTuple):
key: Union[str, Sequence[str]]
platform_name: Optional[str]
max_size: Optional[int]
class EventKey(NamedTuple):
"""Unique identifier for a task event.
This contains event context information for event handlers.
"""
"""The event handler name."""
handler: str
"""The task event."""
event: str
"""The task event message.
Warning: This information is not currently preserved in the DB so will be
lost on restart.
"""
message: str
"""The job tokens."""
tokens: 'Tokens'
def get_event_id(event: str, itask: 'TaskProxy') -> str:
"""Return a unique event identifier.
Some events are not unique e.g. task "started" is unique in that it can
only happen once per-job, "warning", however, is not unique as this is a
message severity level which could be associated with any number of
custom task messages.
To handle this tasks track non-unique-events and number them to ensure
their EventKey's remain unique for ease of event tracking.
Examples:
>>> from types import SimpleNamespace
# regular events are passed straight through:
>>> get_event_id('whatever', SimpleNamespace())
'whatever'
# non-unique events get an integer added to the end:
>>> get_event_id('warning', SimpleNamespace(non_unique_events={
... 'warning': None,
... }))
'warning-1'
>>> get_event_id('warning', SimpleNamespace(non_unique_events={
... 'warning': 2,
... }))
'warning-2'
"""
if event in TaskEventsManager.NON_UNIQUE_EVENTS:
event = f'{event}-{itask.non_unique_events[event] or 1:d}'
return event
def log_task_job_activity(
ctx: 'SubProcContext',
workflow: str,
point: 'str | PointBase',
name: str,
submit_num: str | int | None = None,
level: int | None = None,
):
"""Log an activity for a task job."""
ctx_str = str(ctx)
if not ctx_str:
return
if isinstance(ctx.cmd_key, tuple): # An event handler
submit_num = ctx.cmd_key[-1]
job_activity_log = get_task_job_activity_log(
workflow, point, name, submit_num)
try:
with open(os.path.expandvars(job_activity_log), "ab") as handle:
handle.write((ctx_str + '\n').encode())
except IOError:
# This happens when there is no job directory. E.g., if a job host
# selection command causes a submission failure, or if a waiting task
# expires before a job log directory is otherwise needed.
# (Don't log the exception content, it looks like a bug).
level = logging.INFO
if ctx.cmd and ctx.ret_code:
level = logging.ERROR
if level is not None:
LOG.log(level, ctx_str)
class EventData(Enum):
"""The following variables are available to task event handlers.
They can be templated into event handlers with Python percent style string
formatting e.g:
.. code-block:: none
%(workflow)s is running on %(host)s
The ``%(event)s`` string, for instance, will be replaced by the actual
event name when the handler is invoked.
If no templates or arguments are specified the following default command
line will be used:
.. code-block:: none
<event-handler> %(event)s %(workflow)s %(id)s %(message)s
.. note::
Substitution patterns should not be quoted in the template strings.
This is done automatically where required.
For an explanation of the substitution syntax, see
`String Formatting Operations in the Python documentation
<https://docs.python.org/3/library/stdtypes.html
#printf-style-string-formatting>`_.
"""
Event = 'event'
"""Event name."""
Workflow = 'workflow'
"""Workflow ID."""
Suite = 'suite' # deprecated
"""Workflow ID.
.. deprecated:: 8.0.0
Use "workflow".
"""
UUID = 'uuid'
"""The unique identification string for this workflow run.
This string is preserved for the lifetime of the scheduler and is restored
from the database on restart.
"""
SuiteUUID = 'suite_uuid' # deprecated
"""The unique identification string for this workflow run.
.. deprecated:: 8.0.0
Use 'uuid'.
"""
CyclePoint = 'point'
"""The task's cycle point."""
SubmitNum = 'submit_num'
"""The job's submit number.
This starts at 1 and increments with each additional job submission.
"""
TryNum = 'try_num'
"""The job's try number.
The number of execution attempts.
It starts at 1 and increments with automatic
:cylc:conf:`flow.cylc[runtime][<namespace>]execution retry delays`.
"""
ID = 'id'
"""The task ID (i.e. ``%(point)/%(name)``)."""
Message = 'message'
"""Events message, if any."""
JobRunnerName = 'job_runner_name'
"""The job runner name."""
JobRunnerName_old = 'batch_sys_name' # deprecated
"""The job runner name.
.. deprecated:: 8.0.0
Use "job_runner_name".
"""
JobID = 'job_id'
"""The job ID in the job runner.
I.E. The job submission ID. For background jobs this is the process ID.
"""
JobID_old = 'batch_sys_job_id' # deprecated
"""The job ID in the job runner.
.. deprecated:: 8.0.0
Use "job_id".
"""
SubmitTime = 'submit_time'
"""Date-time when the job was submitted, in ISO8601 format."""
StartTime = 'start_time'
"""Date-time when the job started, in ISO8601 format."""
FinishTime = 'finish_time'
"""Date-time when the job finished, in ISO8601 format."""
PlatformName = 'platform_name'
"""The name of the platform where the job is submitted."""
UserAtHost = 'user@host'
"""The name of the platform where the job is submitted.
.. deprecated:: 8.0.0
Use "platform_name".
.. versionchanged:: 8.0.0
This now provides the platform name rather than ``user@host``.
"""
TaskName = 'name'
"""The name of the task."""
TaskURL = 'task_url' # deprecated
"""The URL defined in the task's metadata.
.. deprecated:: 8.0.0
Use ``URL`` from ``<task metadata>``.
"""
WorkflowURL = 'workflow_url' # deprecated
"""The URL defined in the workflow's metadata.
.. deprecated:: 8.0.0
Use ``workflow_URL`` from ``workflow_<workflow metadata>``.
"""
# NOTE: placeholder for task metadata (here for documentation reasons)
TaskMeta = '<task metadata>'
"""Any task metadata defined in
:cylc:conf:`flow.cylc[runtime][<namespace>][meta]` can be used e.g:
``%(title)s``
Task title
``%(URL)s``
Task URL
``%(importance)s``
Example custom task metadata
"""
# NOTE: placeholder for workflow metadata (here for documentation reasons)
WorkflowMeta = 'workflow_<workflow metadata>'
"""Any workflow metadata defined in
:cylc:conf:`flow.cylc[meta]` can be used with the ``workflow_``
e.g. prefix:
``%(workflow_title)s``
Workflow title
``%(workflow_URL)s``
Workflow URL.
``%(workflow_rating)s``
Example custom workflow metadata.
"""
def get_event_handler_data(task_cfg, workflow_cfg):
"""Extract event handler data from workflow and task metadata."""
handler_data = {}
# task metadata
for key, value in task_cfg['meta'].items():
if key == "URL":
handler_data[EventData.TaskURL.value] = quote(value)
handler_data[key] = quote(value)
# workflow metadata
for key, value in workflow_cfg['meta'].items():
if key == "URL":
handler_data[EventData.WorkflowURL.value] = quote(value)
handler_data["workflow_" + key] = quote(value)
return handler_data
class TaskEventsManager():
"""Task events manager.
This class does the following:
* Manage task messages (received or otherwise).
* Set up task (submission) retries on job (submission) failures.
* Generate and manage task event handlers.
"""
EVENT_FAILED = TASK_OUTPUT_FAILED
EVENT_LATE = "late"
EVENT_RETRY = "retry"
EVENT_STARTED = TASK_OUTPUT_STARTED
EVENT_SUBMITTED = TASK_OUTPUT_SUBMITTED
EVENT_EXPIRED = TASK_OUTPUT_EXPIRED
EVENT_SUBMIT_FAILED = "submission failed"
EVENT_SUBMIT_RETRY = "submission retry"
EVENT_SUBMIT_TIMEOUT = "submission timeout"
EVENT_EXEC_TIMEOUT = "execution timeout"
EVENT_SUCCEEDED = TASK_OUTPUT_SUCCEEDED
NON_UNIQUE_EVENTS = ('warning', 'critical', 'custom')
STD_EVENTS = [
EVENT_SUBMITTED,
EVENT_SUBMIT_TIMEOUT,
EVENT_SUBMIT_RETRY,
EVENT_SUBMIT_FAILED,
EVENT_STARTED,
EVENT_EXEC_TIMEOUT,
EVENT_RETRY,
EVENT_SUCCEEDED,
EVENT_FAILED,
EVENT_LATE,
EVENT_EXPIRED,
*NON_UNIQUE_EVENTS,
]
HANDLER_CUSTOM = "event-handler"
HANDLER_MAIL = "event-mail"
JOB_FAILED = "job failed"
HANDLER_JOB_LOGS_RETRIEVE = "job-logs-retrieve"
FLAG_INTERNAL = "(internal)"
FLAG_RECEIVED = "(received)"
FLAG_RECEIVED_IGNORED = "(received-ignored)"
FLAG_POLLED = "(polled)"
FLAG_POLLED_IGNORED = "(polled-ignored)"
KEY_EXECUTE_TIME_LIMIT = 'execution_time_limit'
JOB_SUBMIT_SUCCESS_FLAG = 0
JOB_SUBMIT_FAIL_FLAG = 1
JOB_LOGS_RETRIEVAL_EVENTS = {
EVENT_FAILED,
EVENT_RETRY,
EVENT_SUCCEEDED
}
workflow_cfg: Dict[str, Any]
uuid_str: str
# To be set by the task pool:
spawn_func: Callable[['TaskProxy', str], Any]
mail_interval: float = 0
mail_smtp: Optional[str] = None
mail_footer: Optional[str] = None
def __init__(
self, workflow, proc_pool, workflow_db_mgr, broadcast_mgr,
xtrigger_mgr, data_store_mgr, timestamp, bad_hosts,
reset_inactivity_timer_func
):
self.workflow = workflow
self.proc_pool = proc_pool
self.workflow_db_mgr: WorkflowDatabaseManager = workflow_db_mgr
self.broadcast_mgr: BroadcastMgr = broadcast_mgr
self.xtrigger_mgr: XtriggerManager = xtrigger_mgr
self.data_store_mgr: DataStoreMgr = data_store_mgr
self.next_mail_time = None
self.reset_inactivity_timer_func = reset_inactivity_timer_func
# NOTE: do not mutate directly
# use the {add,remove,unset_waiting}_event_timers methods
self._event_timers: Dict[EventKey, Any] = {}
# NOTE: flag for DB use
self.event_timers_updated = True
self.timestamp = timestamp
self.bad_hosts = bad_hosts
@staticmethod
def check_poll_time(itask, now=None):
"""Set the next task execution/submission poll time.
If now is set, set the timer only if the previous delay is done.
Return the next delay.
"""
if not itask.state(*TASK_STATUSES_ACTIVE):
# Reset, task not active
itask.timeout = None
itask.poll_timer = None
return None
ctx = (itask.submit_num, itask.state.status)
if itask.poll_timer is None or itask.poll_timer.ctx != ctx:
# Reset, timer no longer relevant
itask.timeout = None
itask.poll_timer = None
return None
if now is not None and not itask.poll_timer.is_delay_done(now):
return False
if itask.poll_timer.num is None:
itask.poll_timer.num = 0
itask.poll_timer.next(no_exhaust=True)
return True
def check_job_time(self, itask, now):
"""Check/handle job timeout and poll timer"""
can_poll = self.check_poll_time(itask, now)
if itask.timeout is None or now <= itask.timeout:
return can_poll
# Timeout reached for task, emit event and reset itask.timeout
if itask.state(TASK_STATUS_RUNNING):
time_ref = itask.summary['started_time']
event = self.EVENT_EXEC_TIMEOUT
elif itask.state(TASK_STATUS_SUBMITTED):
time_ref = itask.summary['submitted_time']
event = self.EVENT_SUBMIT_TIMEOUT
msg = event
with suppress(TypeError, ValueError):
msg += ' after %s' % intvl_as_str(itask.timeout - time_ref)
itask.timeout = None # emit event only once
if msg and event:
LOG.warning(f"[{itask}] {msg}")
self.setup_event_handlers(itask, event, msg)
return True
else:
return can_poll
def _get_remote_conf(self, itask, key):
"""Get deprecated "[remote]" items that default to platforms."""
overrides = self.broadcast_mgr.get_broadcast(itask.tokens)
SKEY = 'remote'
if SKEY not in overrides:
overrides[SKEY] = {}
return (
overrides[SKEY].get(key) or
itask.tdef.rtconfig[SKEY][key] or
itask.platform[key]
)
def _get_workflow_platforms_conf(self, itask: 'TaskProxy', key: str):
"""Return top level [runtime] items that default to platforms."""
overrides = self.broadcast_mgr.get_broadcast(itask.tokens)
return (
overrides.get(key) or
itask.tdef.rtconfig[key] or
itask.platform[key]
)
def process_events(self, schd: 'Scheduler') -> None:
"""Process task events that were created by "setup_event_handlers".
"""
ctx_groups: dict = {}
now = time()
for id_key, timer in self._event_timers.copy().items():
if timer.is_waiting:
continue
# Set timer if timeout is None.
if not timer.is_timeout_set():
if timer.next() is None:
LOG.warning(
f"{id_key.tokens.relative_id}"
f" handler:{id_key.handler}"
f" for task event:{id_key.event} failed"
)
self.remove_event_timer(id_key)
continue
# Report retries and delayed 1st try
msg = None
if timer.num > 1:
msg = (
f"handler:{id_key.handler}"
f" for task event:{id_key.event} failed,"
f" retrying in {timer.delay_timeout_as_str()}"
)
elif timer.delay:
msg = (
f"handler:{id_key.handler}"
f" for task event:{id_key.event} will"
f" run after {timer.delay_timeout_as_str()}"
)
if msg:
LOG.debug("%s %s", id_key.tokens.relative_id, msg)
# Ready to run?
if not timer.is_delay_done() or (
# Avoid flooding user's mail box with mail notification.
# Group together as many notifications as possible within a
# given interval.
isinstance(timer.ctx, TaskEventMailContext) and
not schd.stop_mode and
self.next_mail_time is not None and
self.next_mail_time > now
):
continue
timer.set_waiting()
if isinstance(timer.ctx, CustomTaskEventHandlerContext):
# Run custom event handlers on their own
self.proc_pool.put_command(
SubProcContext(
(
(id_key.handler, id_key.event),
id_key.tokens.submit_num,
),
timer.ctx.cmd,
env=os.environ,
shell=True, # nosec
), # designed to run user defined code
callback=self._custom_handler_callback,
callback_args=[schd, id_key]
)
else:
# Group together built-in event handlers, where possible
if timer.ctx not in ctx_groups:
ctx_groups[timer.ctx] = []
ctx_groups[timer.ctx].append(id_key)
next_mail_time = now + self.mail_interval
for ctx, id_keys in ctx_groups.items():
if isinstance(ctx, TaskEventMailContext):
# Set next_mail_time if any mail sent
self.next_mail_time = next_mail_time
self._process_event_email(schd, ctx, id_keys)
elif isinstance(ctx, TaskJobLogsRetrieveContext):
self._process_job_logs_retrieval(schd, ctx, id_keys)
def process_message(
self,
itask: 'TaskProxy',
severity: Union[str, int],
message: str,
event_time: Optional[str] = None,
flag: str = FLAG_INTERNAL,
submit_num: Optional[int] = None,
forced: bool = False
) -> bool:
"""Parse a task message and update task state.
Incoming, e.g. "succeeded at <TIME>", may be from task job or polling.
It is possible for the current state of a task to be inconsistent with
a message (whether internal, received or polled) e.g. due to a late
poll result, or a network outage, or manual state reset. To handle
this, if a message would take the task state backward, issue a poll to
confirm instead of changing state - then always believe the next
message. Note that the next message might not be the result of this
confirmation poll, in the unlikely event that a job emits a succession
of messages very quickly, but this is the best we can do without
somehow uniquely associating each poll with its result message.
Arguments:
itask:
The task proxy object relevant for the message.
severity:
Message severity, should be a recognised logging level.
message:
Message content.
event_time:
Event time stamp. Expect ISO8601 date time string.
If not specified, use current time.
flag:
If specified, can be:
FLAG_INTERNAL (default):
To indicate an internal message.
FLAG_RECEIVED:
To indicate a message received from a job or an
external source.
FLAG_POLLED:
To indicate a message resulted from a poll.
submit_num:
The submit number of the task relevant for the message.
If not specified, use latest submit number.
forced:
If this message is due to manual completion or not (cylc set)
Return:
False: in normal circumstances.
True: if polling is required to confirm a reversal of status.
"""
# Useful debug but currently borks tests/f/cylc-message/02-multi.t:
# (It checks all log messages in debug mode, which is unhelpful).
# TODO: https://github.com/cylc/cylc-flow/issues/6857
# LOG.debug(f'Message {flag} for {itask}: "{message}"')
# Log messages
if event_time is None:
event_time = get_current_time_string()
if submit_num is None:
submit_num = itask.submit_num
if isinstance(severity, int):
severity = cast('str', getLevelName(severity))
lseverity = str(severity).lower()
# Any message represents activity.
self.reset_inactivity_timer_func()
if not self._process_message_check(
itask, severity, message, event_time, flag, submit_num, forced
):
return False
if not forced:
# always update the workflow state summary for latest message
self.data_store_mgr.delta_job_msg(
itask.tokens.duplicate(job=str(submit_num)),
f'{message} {flag}' if flag == self.FLAG_POLLED
else message
)
# Satisfy my output, if possible, and spawn children.
# (first remove signal: failed/EXIT -> failed)
# Complete the corresponding task output, if there is one.
task_output, run_signal = split_run_signal(message)
job_aborted = (
run_signal is not None and task_output == ABORT_MESSAGE_PREFIX
)
if job_aborted:
task_output = TASK_OUTPUT_FAILED
output_completed: bool | None = False
if task_output not in {TASK_OUTPUT_SUBMIT_FAILED, TASK_OUTPUT_FAILED}:
output_completed = (
itask.state.outputs.set_message_complete(task_output, forced)
)
if output_completed:
self.data_store_mgr.delta_task_output(itask, task_output)
for implied in (
itask.state.outputs.get_incomplete_implied(task_output)
):
# Set submitted and/or started first, if skipped.
# (whether by forced set, or missed message).
LOG.info(f"[{itask}] setting implied output: {implied}")
self.process_message(
itask, INFO, implied, event_time,
self.FLAG_INTERNAL, submit_num, forced
)
if message == self.EVENT_STARTED:
if flag == self.FLAG_RECEIVED and itask.state.is_gt(
TASK_STATUS_RUNNING
):
# Already running.
return True
self._process_message_started(itask, event_time, forced)
self.spawn_children(itask, TASK_OUTPUT_STARTED, forced)
elif message == self.EVENT_SUCCEEDED:
self._process_message_succeeded(itask, event_time, forced)
self.spawn_children(itask, TASK_OUTPUT_SUCCEEDED, forced)
elif message == self.EVENT_EXPIRED:
self._process_message_expired(itask, event_time, forced)
self.spawn_children(itask, TASK_OUTPUT_EXPIRED, forced)
elif task_output == self.EVENT_FAILED:
if flag == self.FLAG_RECEIVED and itask.state.is_gt(
TASK_STATUS_FAILED
):
# Already failed.
return True
msg = self.JOB_FAILED
if run_signal is not None:
# Task received signal or aborted.
self._db_events_insert(
itask,
'aborted' if job_aborted else 'signaled',
run_signal,
)
if job_aborted:
msg = run_signal
if self._process_message_failed(
itask,
event_time,
msg,
forced,
full_message=message,
run_signal=run_signal,
):
self.spawn_children(itask, TASK_OUTPUT_FAILED, forced)
elif message == self.EVENT_SUBMIT_FAILED:
if flag == self.FLAG_RECEIVED and itask.state.is_gt(
TASK_STATUS_SUBMIT_FAILED
):
# Already submit-failed
return True
if forced or self._process_message_submit_failed(
itask, event_time
):
self.spawn_children(itask, TASK_OUTPUT_SUBMIT_FAILED, forced)
elif message == self.EVENT_SUBMITTED:
if flag == self.FLAG_RECEIVED and itask.state.is_gte(
TASK_STATUS_SUBMITTED
):
# Already submitted.
return True
if not forced:
# `cylc set --out submitted` only spawns children; it doesn't
# affect task state or anything else.
self._process_message_submitted(itask, event_time)
self.spawn_children(itask, TASK_OUTPUT_SUBMITTED, forced)
elif run_signal is not None and task_output == VACATION_MESSAGE_PREFIX:
# Task job pre-empted into a vacation state
self._db_events_insert(itask, "vacated", message)
itask.set_summary_time('started') # unset
if TimerFlags.SUBMISSION_RETRY in itask.try_timers:
itask.try_timers[TimerFlags.SUBMISSION_RETRY].num = 0
itask.job_vacated = True
# Believe this and change state without polling (could poll?).
if itask.state_reset(TASK_STATUS_SUBMITTED, forced=forced):
itask.state_reset(is_queued=False, forced=forced)
self.data_store_mgr.delta_task_state(itask)
self._reset_job_timers(itask)
# We should really have a special 'vacated' handler, but given that
# this feature can only be used on the deprecated loadleveler
# system, we should probably aim to remove support for job vacation
# instead. Otherwise, we should have:
# self.setup_event_handlers(itask, 'vacated', message)
elif output_completed:
# Must be a message of a custom task output.
# No state change.
# Log completion of o (not needed for standard outputs)
trigger = itask.state.outputs.get_trigger(message)
LOG.info(f"[{itask}] completed output {trigger}")
self.setup_event_handlers(itask, trigger, message)
self.spawn_children(itask, task_output, forced)
else:
# Unhandled messages. These include:
# * general non-output/progress messages
# * poll messages that repeat previous results
# Note that all messages are logged already at the top.
# No state change.
LOG.debug(f"[{itask}] unhandled: {message}")
self._db_events_insert(
itask, (f"message {lseverity}"), message)
if lseverity in self.NON_UNIQUE_EVENTS:
itask.non_unique_events.update({lseverity: 1})
self.setup_event_handlers(itask, lseverity, message)
return False
def _process_message_check(
self,
itask: 'TaskProxy',
severity: str,
message: str,
event_time: str,
flag: str,
submit_num: int,
forced: bool = False
) -> bool:
"""Helper for `.process_message`.
See `.process_message` for argument list
Check whether to process/skip message.
Return True if `.process_message` should continue, False otherwise.
"""
if itask.transient or forced:
return True
if self.timestamp:
timestamp = f" at {event_time}"
else:
timestamp = ""
if flag == self.FLAG_RECEIVED and submit_num != itask.submit_num:
# Ignore received messages from old jobs
LOG.warning(
f"[{itask}] "
f"{self.FLAG_RECEIVED_IGNORED}{message}{timestamp} "
f"for job({submit_num:02d}) != job({itask.submit_num:02d})"
)
return False
if (
itask.state(TASK_STATUS_WAITING)
# Polling in live mode only:
and itask.run_mode == RunMode.LIVE
and (
(
# task has a submit-retry lined up
TimerFlags.SUBMISSION_RETRY in itask.try_timers
and itask.try_timers[
TimerFlags.SUBMISSION_RETRY].num > 0
)
or
(
# task has an execution-retry lined up
TimerFlags.EXECUTION_RETRY in itask.try_timers
and itask.try_timers[
TimerFlags.EXECUTION_RETRY].num > 0
)
)
):
# Ignore messages if task has a retry lined up
# (caused by polling overlapping with task failure)
if flag == self.FLAG_RECEIVED:
LOG.warning(
f"[{itask}] "
f"{self.FLAG_RECEIVED_IGNORED}{message}{timestamp}"
)
else:
LOG.warning(
f"[{itask}] "
f"{self.FLAG_POLLED_IGNORED}{message}{timestamp}"
)
return False
severity_lvl: int = LOG_LEVELS.get(severity, INFO)
# Don't log submit/failure messages here:
if flag != self.FLAG_POLLED and message in {
self.EVENT_SUBMIT_FAILED, f'{FAIL_MESSAGE_PREFIX}/ERR'
}:
return True
# Demote log level to DEBUG if this is a message that duplicates what
# gets logged by itask state change anyway (and not manual poll)
if severity_lvl > DEBUG and flag != self.FLAG_POLLED and message in {
self.EVENT_SUBMITTED, self.EVENT_STARTED, self.EVENT_SUCCEEDED,
}:
severity_lvl = DEBUG
LOG.log(severity_lvl, f"[{itask}] {flag}{message}{timestamp}")
return True
def process_job_message(
self,
job_tokens: 'Tokens',
tdef: 'TaskDef',
message: str,
event_time: str,
) -> bool:
"""Process a job message only, without affecting its task.
E.g. for a task that is no longer in the pool because it was manually
set to completed.
Returns True if the message was handled, False otherwise.
"""
tmp_itask = TaskProxy(
job_tokens.workflow,
tdef,
get_point(job_tokens['cycle']),