| 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 |
"""Cylc scheduler server.""" |
| 17 |
|
| 18 |
import asyncio |
| 19 |
from collections import deque |
| 20 |
from contextlib import suppress |
| 21 |
import logging |
| 22 |
import os |
| 23 |
from pathlib import Path |
| 24 |
from queue import ( |
| 25 |
Empty, |
| 26 |
Queue, |
| 27 |
) |
| 28 |
from shlex import quote |
| 29 |
import signal |
| 30 |
from subprocess import ( |
| 31 |
DEVNULL, |
| 32 |
PIPE, |
| 33 |
Popen, |
| 34 |
) |
| 35 |
import sys |
| 36 |
from threading import ( |
| 37 |
Barrier, |
| 38 |
Thread, |
| 39 |
) |
| 40 |
from time import ( |
| 41 |
sleep, |
| 42 |
time, |
| 43 |
) |
| 44 |
import traceback |
| 45 |
from typing import ( |
| 46 |
TYPE_CHECKING, |
| 47 |
Any, |
| 48 |
AsyncGenerator, |
| 49 |
Dict, |
| 50 |
Iterable, |
| 51 |
List, |
| 52 |
Literal, |
| 53 |
NoReturn, |
| 54 |
Optional, |
| 55 |
Set, |
| 56 |
Tuple, |
| 57 |
Union, |
| 58 |
) |
| 59 |
from uuid import uuid4 |
| 60 |
|
| 61 |
from metomi.isodatetime.exceptions import TimePointDumperBoundsError |
| 62 |
import psutil |
| 63 |
|
| 64 |
from cylc.flow import ( |
| 65 |
LOG, |
| 66 |
__version__ as CYLC_VERSION, |
| 67 |
command_validation, |
| 68 |
commands, |
| 69 |
main_loop, |
| 70 |
workflow_files, |
| 71 |
) |
| 72 |
from cylc.flow.broadcast_mgr import BroadcastMgr |
| 73 |
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg |
| 74 |
from cylc.flow.config import WorkflowConfig |
| 75 |
from cylc.flow.data_store_mgr import DataStoreMgr |
| 76 |
from cylc.flow.exceptions import ( |
| 77 |
CommandFailedError, |
| 78 |
CylcError, |
| 79 |
InputError, |
| 80 |
WorkflowConfigError, |
| 81 |
) |
| 82 |
import cylc.flow.flags |
| 83 |
from cylc.flow.flow_mgr import ( |
| 84 |
FLOW_NEW, |
| 85 |
FLOW_NONE, |
| 86 |
FlowMgr, |
| 87 |
stringify_flow_nums, |
| 88 |
) |
| 89 |
from cylc.flow.host_select import ( |
| 90 |
HostSelectException, |
| 91 |
select_workflow_host, |
| 92 |
) |
| 93 |
from cylc.flow.hostuserutil import ( |
| 94 |
get_host, |
| 95 |
get_user, |
| 96 |
is_remote_platform, |
| 97 |
) |
| 98 |
from cylc.flow.id import Tokens |
| 99 |
from cylc.flow.log_level import ( |
| 100 |
verbosity_to_env, |
| 101 |
verbosity_to_opts, |
| 102 |
) |
| 103 |
from cylc.flow.loggingutil import ( |
| 104 |
ReferenceLogFileHandler, |
| 105 |
RotatingLogFileHandler, |
| 106 |
get_next_log_number, |
| 107 |
get_reload_start_number, |
| 108 |
get_sorted_logs_by_time, |
| 109 |
patch_log_level, |
| 110 |
) |
| 111 |
from cylc.flow.network import API |
| 112 |
from cylc.flow.network.authentication import key_housekeeping |
| 113 |
from cylc.flow.network.server import WorkflowRuntimeServer |
| 114 |
from cylc.flow.parsec.exceptions import ParsecError |
| 115 |
from cylc.flow.parsec.OrderedDict import DictTree |
| 116 |
from cylc.flow.parsec.validate import DurationFloat |
| 117 |
from cylc.flow.pathutil import ( |
| 118 |
get_workflow_name_from_id, |
| 119 |
get_workflow_run_config_log_dir, |
| 120 |
get_workflow_run_dir, |
| 121 |
get_workflow_run_scheduler_log_dir, |
| 122 |
get_workflow_run_share_dir, |
| 123 |
get_workflow_run_work_dir, |
| 124 |
get_workflow_test_log_path, |
| 125 |
make_workflow_run_tree, |
| 126 |
) |
| 127 |
from cylc.flow.platforms import ( |
| 128 |
get_install_target_from_platform, |
| 129 |
get_localhost_install_target, |
| 130 |
get_platform, |
| 131 |
is_platform_with_target_in_list, |
| 132 |
) |
| 133 |
from cylc.flow.profiler import Profiler |
| 134 |
from cylc.flow.resources import get_resources |
| 135 |
from cylc.flow.run_modes import RunMode |
| 136 |
from cylc.flow.run_modes.simulation import sim_time_check |
| 137 |
from cylc.flow.subprocpool import SubProcPool |
| 138 |
from cylc.flow.task_events_mgr import TaskEventsManager |
| 139 |
from cylc.flow.task_job_mgr import TaskJobManager |
| 140 |
from cylc.flow.task_pool import TaskPool |
| 141 |
from cylc.flow.task_remote_mgr import ( |
| 142 |
REMOTE_FILE_INSTALL_255, |
| 143 |
REMOTE_FILE_INSTALL_DONE, |
| 144 |
REMOTE_FILE_INSTALL_FAILED, |
| 145 |
REMOTE_INIT_255, |
| 146 |
REMOTE_INIT_DONE, |
| 147 |
REMOTE_INIT_FAILED, |
| 148 |
) |
| 149 |
from cylc.flow.task_state import ( |
| 150 |
TASK_STATUS_FAILED, |
| 151 |
TASK_STATUS_PREPARING, |
| 152 |
TASK_STATUS_RUNNING, |
| 153 |
TASK_STATUS_SUBMITTED, |
| 154 |
TASK_STATUS_WAITING, |
| 155 |
TASK_STATUSES_ACTIVE, |
| 156 |
TASK_STATUSES_NEVER_ACTIVE, |
| 157 |
) |
| 158 |
from cylc.flow.taskdef import TaskDef |
| 159 |
from cylc.flow.templatevars import ( |
| 160 |
eval_var, |
| 161 |
get_template_vars, |
| 162 |
) |
| 163 |
from cylc.flow.timer import Timer |
| 164 |
from cylc.flow.util import cli_format |
| 165 |
from cylc.flow.wallclock import ( |
| 166 |
get_current_time_string, |
| 167 |
get_time_string_from_unix_time as time2str, |
| 168 |
get_utc_mode, |
| 169 |
) |
| 170 |
from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager |
| 171 |
from cylc.flow.workflow_events import WorkflowEventHandler |
| 172 |
from cylc.flow.workflow_status import ( |
| 173 |
AutoRestartMode, |
| 174 |
StopMode, |
| 175 |
) |
| 176 |
from cylc.flow.xtrigger_mgr import XtriggerManager |
| 177 |
|
| 178 |
|
| 179 |
if TYPE_CHECKING: |
| 180 |
from optparse import Values |
| 181 |
|
| 182 |
from cylc.flow.network.resolvers import TaskMsg |
| 183 |
from cylc.flow.task_proxy import TaskProxy |
| 184 |
|
| 185 |
|
| 186 |
class SchedulerStop(CylcError): |
| 187 |
"""Scheduler normal stop.""" |
| 188 |
|
| 189 |
|
| 190 |
class SchedulerError(CylcError): |
| 191 |
"""Scheduler expected error stop.""" |
| 192 |
|
| 193 |
|
| 194 |
class Scheduler: |
| 195 |
"""Cylc scheduler server.""" |
| 196 |
|
| 197 |
EVENT_STARTUP = WorkflowEventHandler.EVENT_STARTUP |
| 198 |
EVENT_SHUTDOWN = WorkflowEventHandler.EVENT_SHUTDOWN |
| 199 |
EVENT_ABORTED = WorkflowEventHandler.EVENT_ABORTED |
| 200 |
EVENT_WORKFLOW_TIMEOUT = WorkflowEventHandler.EVENT_WORKFLOW_TIMEOUT |
| 201 |
EVENT_STALL = WorkflowEventHandler.EVENT_STALL |
| 202 |
EVENT_STALL_TIMEOUT = WorkflowEventHandler.EVENT_STALL_TIMEOUT |
| 203 |
EVENT_RESTART_TIMEOUT = WorkflowEventHandler.EVENT_RESTART_TIMEOUT |
| 204 |
EVENT_INACTIVITY_TIMEOUT = WorkflowEventHandler.EVENT_INACTIVITY_TIMEOUT |
| 205 |
|
| 206 |
# Intervals in seconds |
| 207 |
INTERVAL_MAIN_LOOP = 1.0 |
| 208 |
INTERVAL_MAIN_LOOP_QUICK = 0.5 |
| 209 |
INTERVAL_STOP_KILL = 10.0 |
| 210 |
INTERVAL_STOP_PROCESS_POOL_EMPTY = 0.5 |
| 211 |
INTERVAL_AUTO_RESTART_ERROR = 5 |
| 212 |
|
| 213 |
START_MESSAGE_PREFIX = 'Scheduler: ' |
| 214 |
START_MESSAGE_TMPL = ( |
| 215 |
START_MESSAGE_PREFIX + |
| 216 |
'url=%(comms_method)s://%(host)s:%(port)s pid=%(pid)s') |
| 217 |
START_PUB_MESSAGE_PREFIX = 'Workflow publisher: ' |
| 218 |
START_PUB_MESSAGE_TMPL = ( |
| 219 |
START_PUB_MESSAGE_PREFIX + |
| 220 |
'url=%(comms_method)s://%(host)s:%(port)s') |
| 221 |
|
| 222 |
# flow information |
| 223 |
workflow: str |
| 224 |
owner: str |
| 225 |
host: str |
| 226 |
id: str # noqa: A003 (instance attr not local) |
| 227 |
uuid_str: str |
| 228 |
is_restart: bool |
| 229 |
bad_hosts: Set[str] |
| 230 |
|
| 231 |
# directories |
| 232 |
workflow_log_dir: str |
| 233 |
workflow_run_dir: str |
| 234 |
workflow_share_dir: str |
| 235 |
workflow_work_dir: str |
| 236 |
|
| 237 |
# managers |
| 238 |
profiler: Profiler |
| 239 |
pool: TaskPool |
| 240 |
proc_pool: SubProcPool |
| 241 |
task_job_mgr: TaskJobManager |
| 242 |
task_events_mgr: TaskEventsManager |
| 243 |
workflow_event_handler: WorkflowEventHandler |
| 244 |
data_store_mgr: DataStoreMgr |
| 245 |
workflow_db_mgr: WorkflowDatabaseManager |
| 246 |
broadcast_mgr: BroadcastMgr |
| 247 |
xtrigger_mgr: XtriggerManager |
| 248 |
flow_mgr: FlowMgr |
| 249 |
|
| 250 |
# queues |
| 251 |
command_queue: 'Queue[Tuple[str, str, AsyncGenerator]]' |
| 252 |
message_queue: 'Queue[TaskMsg]' |
| 253 |
ext_trigger_queue: Queue |
| 254 |
|
| 255 |
# configuration |
| 256 |
config: WorkflowConfig # flow config |
| 257 |
options: 'Values' |
| 258 |
cylc_config: DictTree # [scheduler] config |
| 259 |
template_vars: Dict[str, Any] |
| 260 |
|
| 261 |
# tcp / zmq |
| 262 |
server: WorkflowRuntimeServer |
| 263 |
|
| 264 |
# Note: attributes without a default must come before those with defaults |
| 265 |
|
| 266 |
# flow information |
| 267 |
contact_data: Optional[dict] = None |
| 268 |
|
| 269 |
# configuration |
| 270 |
flow_file: Optional[str] = None |
| 271 |
flow_file_update_time: Optional[float] = None |
| 272 |
|
| 273 |
# workflow params |
| 274 |
stop_mode: Optional[StopMode] = None |
| 275 |
stop_task: Optional[str] = None |
| 276 |
stop_clock_time: Optional[int] = None |
| 277 |
reload_pending: 'Union[Literal[False], str]' = False |
| 278 |
|
| 279 |
# task event loop |
| 280 |
is_paused = False |
| 281 |
is_updated = False |
| 282 |
is_stalled = False |
| 283 |
is_restart_timeout_wait = False |
| 284 |
is_reloaded = False |
| 285 |
|
| 286 |
# main loop |
| 287 |
main_loop_intervals: deque = deque(maxlen=10) |
| 288 |
main_loop_plugins: Optional[dict] = None |
| 289 |
auto_restart_mode: Optional[AutoRestartMode] = None |
| 290 |
auto_restart_time: Optional[float] = None |
| 291 |
|
| 292 |
# profiling |
| 293 |
_profile_amounts: Optional[dict] = None |
| 294 |
_profile_update_times: Optional[dict] = None |
| 295 |
previous_profile_point: float = 0 |
| 296 |
count: int = 0 |
| 297 |
|
| 298 |
time_next_kill: Optional[float] = None |
| 299 |
|
| 300 |
def __init__(self, id_: str, options: 'Values') -> None: |
| 301 |
# flow information |
| 302 |
self.workflow = id_ |
| 303 |
self.workflow_name = get_workflow_name_from_id(self.workflow) |
| 304 |
self.owner = get_user() |
| 305 |
self.host = get_host() |
| 306 |
self.tokens = Tokens( |
| 307 |
user=self.owner, |
| 308 |
workflow=self.workflow, |
| 309 |
) |
| 310 |
self.id = self.tokens.id |
| 311 |
self.options = options |
| 312 |
self.template_vars = get_template_vars(self.options) |
| 313 |
|
| 314 |
# mutable defaults |
| 315 |
self._profile_amounts = {} |
| 316 |
self._profile_update_times = {} |
| 317 |
self.bad_hosts: Set[str] = set() |
| 318 |
|
| 319 |
self.restored_stop_task_id: Optional[str] = None |
| 320 |
|
| 321 |
self.timers: Dict[str, Timer] = {} |
| 322 |
|
| 323 |
self.workflow_run_dir = get_workflow_run_dir(self.workflow) |
| 324 |
self.workflow_work_dir = get_workflow_run_work_dir(self.workflow) |
| 325 |
self.workflow_share_dir = get_workflow_run_share_dir(self.workflow) |
| 326 |
self.workflow_log_dir = get_workflow_run_scheduler_log_dir( |
| 327 |
self.workflow |
| 328 |
) |
| 329 |
|
| 330 |
self.workflow_db_mgr = WorkflowDatabaseManager( |
| 331 |
pri_d=workflow_files.get_workflow_srv_dir(self.workflow), |
| 332 |
pub_d=os.path.join(self.workflow_run_dir, 'log') |
| 333 |
) |
| 334 |
self.is_restart = Path(self.workflow_db_mgr.pri_path).is_file() |
| 335 |
if ( |
| 336 |
not self.is_restart |
| 337 |
and Path(self.workflow_db_mgr.pub_path).is_file() |
| 338 |
): |
| 339 |
# Delete pub DB if pri DB doesn't exist, as we don't want to |
| 340 |
# load anything (e.g. template variables) from it |
| 341 |
os.unlink(self.workflow_db_mgr.pub_path) |
| 342 |
|
| 343 |
# Map used to track incomplete remote inits for restart |
| 344 |
# {install_target: platform} |
| 345 |
self.incomplete_ri_map: Dict[str, Dict] = {} |
| 346 |
|
| 347 |
async def install(self): |
| 348 |
"""Get the filesystem in the right state to run the flow. |
| 349 |
* Validate flowfiles |
| 350 |
* Install authentication files. |
| 351 |
* Build the directory tree. |
| 352 |
* Copy Python files. |
| 353 |
|
| 354 |
""" |
| 355 |
if self.is_restart: |
| 356 |
self.workflow_db_mgr.restart_check() |
| 357 |
|
| 358 |
# Install |
| 359 |
source, _ = workflow_files.get_workflow_source_dir(Path.cwd()) |
| 360 |
if source is None: |
| 361 |
# register workflow |
| 362 |
rund = get_workflow_run_dir(self.workflow) |
| 363 |
workflow_files.register(self.workflow, source=rund) |
| 364 |
|
| 365 |
make_workflow_run_tree(self.workflow) |
| 366 |
|
| 367 |
# Get & check workflow file |
| 368 |
self.flow_file = workflow_files.get_flow_file(self.workflow) |
| 369 |
|
| 370 |
# Create ZMQ keys |
| 371 |
key_housekeeping( |
| 372 |
self.workflow, platform=self.options.host or 'localhost' |
| 373 |
) |
| 374 |
|
| 375 |
# Extract job.sh from library, for use in job scripts. |
| 376 |
get_resources( |
| 377 |
'job.sh', |
| 378 |
os.path.join( |
| 379 |
workflow_files.get_workflow_srv_dir(self.workflow), 'etc', |
| 380 |
), |
| 381 |
) |
| 382 |
# Add python dirs to sys.path |
| 383 |
for sub_dir in ["python", os.path.join("lib", "python")]: |
| 384 |
# TODO - eventually drop the deprecated "python" sub-dir. |
| 385 |
workflow_py = os.path.join(self.workflow_run_dir, sub_dir) |
| 386 |
if os.path.isdir(workflow_py): |
| 387 |
sys.path.append(os.path.join(self.workflow_run_dir, sub_dir)) |
| 388 |
|
| 389 |
async def initialise(self): |
| 390 |
"""Initialise the components and sub-systems required to run the flow. |
| 391 |
|
| 392 |
* Initialise the network components. |
| 393 |
* Initialise managers. |
| 394 |
|
| 395 |
""" |
| 396 |
self.data_store_mgr = DataStoreMgr(self) |
| 397 |
self.broadcast_mgr = BroadcastMgr(self) |
| 398 |
|
| 399 |
self.server = WorkflowRuntimeServer(self) |
| 400 |
|
| 401 |
self.proc_pool = SubProcPool() |
| 402 |
self.command_queue = Queue() |
| 403 |
self.message_queue = Queue() |
| 404 |
self.ext_trigger_queue = Queue() |
| 405 |
self.workflow_event_handler = WorkflowEventHandler(self.proc_pool) |
| 406 |
|
| 407 |
self.xtrigger_mgr = XtriggerManager( |
| 408 |
self, |
| 409 |
workflow_run_dir=self.workflow_run_dir, |
| 410 |
workflow_share_dir=self.workflow_share_dir, |
| 411 |
) |
| 412 |
|
| 413 |
self.task_events_mgr = TaskEventsManager( |
| 414 |
self.workflow, |
| 415 |
self.proc_pool, |
| 416 |
self.workflow_db_mgr, |
| 417 |
self.broadcast_mgr, |
| 418 |
self.xtrigger_mgr, |
| 419 |
self.data_store_mgr, |
| 420 |
self.options.log_timestamp, |
| 421 |
self.bad_hosts, |
| 422 |
self.reset_inactivity_timer |
| 423 |
) |
| 424 |
|
| 425 |
self.task_job_mgr = TaskJobManager( |
| 426 |
self.workflow, |
| 427 |
self.proc_pool, |
| 428 |
self.workflow_db_mgr, |
| 429 |
self.task_events_mgr, |
| 430 |
self.data_store_mgr, |
| 431 |
self.bad_hosts, |
| 432 |
self.server, |
| 433 |
) |
| 434 |
|
| 435 |
self.profiler = Profiler(self, self.options.profile_mode) |
| 436 |
|
| 437 |
async def configure(self, params): |
| 438 |
"""Configure the scheduler. |
| 439 |
|
| 440 |
* Load the flow configuration. |
| 441 |
* Load/write workflow parameters from the DB. |
| 442 |
* Get the data store rolling. |
| 443 |
|
| 444 |
""" |
| 445 |
# Print workflow name to disambiguate in case of inferred run number |
| 446 |
# while in no-detach mode |
| 447 |
with patch_log_level(LOG): |
| 448 |
LOG.info(f"Workflow: {self.workflow}") |
| 449 |
|
| 450 |
self.profiler.log_memory("scheduler.py: start configure") |
| 451 |
|
| 452 |
self._check_startup_opts() |
| 453 |
|
| 454 |
if self.is_restart: |
| 455 |
run_mode = self.get_run_mode() |
| 456 |
self._set_workflow_params(params) |
| 457 |
# Prevent changing run mode on restart: |
| 458 |
og_run_mode = self.get_run_mode() |
| 459 |
if run_mode != og_run_mode: |
| 460 |
raise InputError( |
| 461 |
"This workflow was originally run in " |
| 462 |
f"{og_run_mode.value} mode:" |
| 463 |
f" You can't restart it in {run_mode.value} mode." |
| 464 |
) |
| 465 |
|
| 466 |
if self.options.paused_start: |
| 467 |
self.pause_workflow('Paused on start up') |
| 468 |
|
| 469 |
self.profiler.log_memory("scheduler.py: before load_flow_file") |
| 470 |
try: |
| 471 |
cfg = self.load_flow_file() |
| 472 |
self.apply_new_config(cfg, is_reload=False) |
| 473 |
except ParsecError as exc: |
| 474 |
# Mark this exc as expected (see docstring for .schd_expected): |
| 475 |
exc.schd_expected = True |
| 476 |
raise exc |
| 477 |
self.profiler.log_memory("scheduler.py: after load_flow_file") |
| 478 |
|
| 479 |
self.workflow_db_mgr.on_workflow_start(self.is_restart) |
| 480 |
|
| 481 |
if not self.is_restart: |
| 482 |
# Set workflow params that would otherwise be loaded from database: |
| 483 |
self.options.utc_mode = get_utc_mode() |
| 484 |
self.options.cycle_point_tz = ( |
| 485 |
self.config.cfg['scheduler']['cycle point time zone']) |
| 486 |
|
| 487 |
self.flow_mgr = FlowMgr(self.workflow_db_mgr, self.options.utc_mode) |
| 488 |
|
| 489 |
# Note that daemonization happens after this: |
| 490 |
self.log_start() |
| 491 |
|
| 492 |
self.broadcast_mgr.linearized_ancestors.update( |
| 493 |
self.config.get_linearized_ancestors()) |
| 494 |
self.task_events_mgr.mail_interval = self.cylc_config['mail'][ |
| 495 |
"task event batch interval"] |
| 496 |
self.task_events_mgr.mail_smtp = self._get_events_conf("smtp") |
| 497 |
self.task_events_mgr.mail_footer = self._get_events_conf("footer") |
| 498 |
self.task_events_mgr.workflow_cfg = self.config.cfg |
| 499 |
if self.options.genref: |
| 500 |
LOG.addHandler(ReferenceLogFileHandler( |
| 501 |
self.config.get_ref_log_name())) |
| 502 |
elif self.options.reftest: |
| 503 |
LOG.addHandler(ReferenceLogFileHandler( |
| 504 |
get_workflow_test_log_path(self.workflow))) |
| 505 |
|
| 506 |
self.pool = TaskPool( |
| 507 |
self.tokens, |
| 508 |
self.config, |
| 509 |
self.workflow_db_mgr, |
| 510 |
self.task_events_mgr, |
| 511 |
self.xtrigger_mgr, |
| 512 |
self.data_store_mgr, |
| 513 |
self.flow_mgr |
| 514 |
) |
| 515 |
|
| 516 |
self.data_store_mgr.initiate_data_model() |
| 517 |
|
| 518 |
self.profiler.log_memory("scheduler.py: before load_tasks") |
| 519 |
if self.is_restart: |
| 520 |
self._load_pool_from_db() |
| 521 |
if self.restored_stop_task_id is not None: |
| 522 |
self.pool.set_stop_task(self.restored_stop_task_id) |
| 523 |
elif self.options.starttask: |
| 524 |
self._load_pool_from_tasks() |
| 525 |
else: |
| 526 |
self._load_pool_from_point() |
| 527 |
|
| 528 |
# BACK COMPAT: spawn the task pool out to RH limit on startup. |
| 529 |
# Not strictly necessary, it will spawn ahead per main loop iteration, |
| 530 |
# but useful back-compat for tests that expect this prior to |
| 531 |
# https://github.com/cylc/cylc-flow/pull/7237 |
| 532 |
# FROM: 8.6.x |
| 533 |
# TO: 8.7.0 |
| 534 |
# REMOVE AT: 8.7.0 |
| 535 |
self.pool.compute_runahead() |
| 536 |
for _ in range(10): |
| 537 |
# (Arbitrary limit to avoid infinite loop if something goes wrong) |
| 538 |
if not self.pool.release_runahead_tasks(): |
| 539 |
for itask in self.pool.get_tasks(): |
| 540 |
self.pool.queue_if_ready(itask) |
| 541 |
break |
| 542 |
|
| 543 |
self.profiler.log_memory("scheduler.py: after load_tasks") |
| 544 |
|
| 545 |
self.workflow_db_mgr.put_workflow_params(self) |
| 546 |
self.workflow_db_mgr.put_workflow_template_vars(self.template_vars) |
| 547 |
self.workflow_db_mgr.put_runtime_inheritance(self.config) |
| 548 |
|
| 549 |
# Create and set workflow timers. |
| 550 |
event = self.EVENT_INACTIVITY_TIMEOUT |
| 551 |
if self.options.reftest: |
| 552 |
self.config.cfg['scheduler']['events'][f'abort on {event}'] = True |
| 553 |
if not self.config.cfg['scheduler']['events'][event]: |
| 554 |
self.config.cfg['scheduler']['events'][event] = DurationFloat( |
| 555 |
180 |
| 556 |
) |
| 557 |
for event, start_now, log_reset_func in [ |
| 558 |
(self.EVENT_INACTIVITY_TIMEOUT, True, LOG.debug), |
| 559 |
(self.EVENT_WORKFLOW_TIMEOUT, True, None), |
| 560 |
(self.EVENT_STALL_TIMEOUT, False, None), |
| 561 |
(self.EVENT_RESTART_TIMEOUT, False, None) |
| 562 |
]: |
| 563 |
interval = self._get_events_conf(event) |
| 564 |
if interval is not None: |
| 565 |
timer = Timer(event, interval, log_reset_func) |
| 566 |
if start_now: |
| 567 |
timer.reset() |
| 568 |
self.timers[event] = timer |
| 569 |
|
| 570 |
if self.is_restart and ( |
| 571 |
# workflow has completed |
| 572 |
not self.pool.get_tasks() |
| 573 |
# workflow has hit the "stop after cycle point" |
| 574 |
or ( |
| 575 |
self.config.stop_point |
| 576 |
and all( |
| 577 |
cycle > self.config.stop_point |
| 578 |
for cycle in { |
| 579 |
itask.point for itask in self.pool.get_tasks() |
| 580 |
} |
| 581 |
) |
| 582 |
) |
| 583 |
): |
| 584 |
# This workflow will shut down immediately once restarted |
| 585 |
# => Give the user a grace period to intervene first |
| 586 |
with suppress(KeyError): |
| 587 |
self.timers[self.EVENT_RESTART_TIMEOUT].reset() |
| 588 |
self.is_restart_timeout_wait = True |
| 589 |
LOG.warning( |
| 590 |
"This workflow already ran to completion." |
| 591 |
"\nTo make it continue, trigger new tasks" |
| 592 |
" before the restart timeout." |
| 593 |
) |
| 594 |
|
| 595 |
# Main loop plugins |
| 596 |
self.main_loop_plugins = main_loop.load( |
| 597 |
self.cylc_config.get('main loop', {}), |
| 598 |
self.options.main_loop |
| 599 |
) |
| 600 |
|
| 601 |
holdcp = None |
| 602 |
if self.options.holdcp: |
| 603 |
holdcp = self.options.holdcp |
| 604 |
elif self.config.cfg['scheduling']['hold after cycle point']: |
| 605 |
holdcp = self.config.cfg['scheduling']['hold after cycle point'] |
| 606 |
if holdcp is not None: |
| 607 |
await commands.run_cmd(commands.set_hold_point(self, holdcp)) |
| 608 |
|
| 609 |
self.profiler.log_memory("scheduler.py: begin run while loop") |
| 610 |
self.is_updated = True |
| 611 |
if self.options.profile_mode: |
| 612 |
self.previous_profile_point = 0 |
| 613 |
self.count = 0 |
| 614 |
|
| 615 |
self.process_workflow_db_queue() |
| 616 |
|
| 617 |
self.profiler.log_memory("scheduler.py: end configure") |
| 618 |
|
| 619 |
def log_start(self) -> None: |
| 620 |
"""Log headers, that also get logged on each rollover. |
| 621 |
|
| 622 |
Note: daemonize polls for 2 of these headers before detaching. |
| 623 |
""" |
| 624 |
# Temporarily lower logging level if necessary to log important info |
| 625 |
with patch_log_level(LOG): |
| 626 |
# `daemonize` polls for these next 2 before detaching: |
| 627 |
LOG.info( |
| 628 |
self.START_MESSAGE_TMPL % { |
| 629 |
'comms_method': 'tcp', |
| 630 |
'host': self.host, |
| 631 |
'port': self.server.port, |
| 632 |
'pid': os.getpid()}, |
| 633 |
extra=RotatingLogFileHandler.header_extra, |
| 634 |
) |
| 635 |
LOG.info( |
| 636 |
self.START_PUB_MESSAGE_TMPL % { |
| 637 |
'comms_method': 'tcp', |
| 638 |
'host': self.host, |
| 639 |
'port': self.server.pub_port}, |
| 640 |
extra=RotatingLogFileHandler.header_extra, |
| 641 |
) |
| 642 |
|
| 643 |
restart_num = self.get_restart_num() + 1 |
| 644 |
LOG.info( |
| 645 |
f'Run: (re)start number={restart_num}, log rollover=%d', |
| 646 |
# Hard code 1 in args, gets updated on log rollover (NOTE: this |
| 647 |
# must be the only positional arg): |
| 648 |
1, |
| 649 |
extra={ |
| 650 |
**RotatingLogFileHandler.header_extra, |
| 651 |
RotatingLogFileHandler.ROLLOVER_NUM: 1 |
| 652 |
} |
| 653 |
) |
| 654 |
LOG.info( |
| 655 |
f'Cylc version: {CYLC_VERSION}', |
| 656 |
extra=RotatingLogFileHandler.header_extra |
| 657 |
) |
| 658 |
|
| 659 |
# Note that the following lines must be present at the top of |
| 660 |
# the workflow log file for use in reference test runs. |
| 661 |
LOG.info( |
| 662 |
f'Run mode: {self.get_run_mode().value}', |
| 663 |
extra=RotatingLogFileHandler.header_extra |
| 664 |
) |
| 665 |
LOG.info( |
| 666 |
f'Initial point: {self.config.initial_point}', |
| 667 |
extra=RotatingLogFileHandler.header_extra |
| 668 |
) |
| 669 |
if self.config.start_point != self.config.initial_point: |
| 670 |
LOG.info( |
| 671 |
f'Start point: {self.config.start_point}', |
| 672 |
extra=RotatingLogFileHandler.header_extra |
| 673 |
) |
| 674 |
LOG.info( |
| 675 |
f'Final point: {self.config.final_point}', |
| 676 |
extra=RotatingLogFileHandler.header_extra |
| 677 |
) |
| 678 |
if self.config.stop_point: |
| 679 |
LOG.info( |
| 680 |
f'Stop point: {self.config.stop_point}', |
| 681 |
extra=RotatingLogFileHandler.header_extra |
| 682 |
) |
| 683 |
|
| 684 |
async def run_scheduler(self) -> None: |
| 685 |
"""Start the scheduler main loop.""" |
| 686 |
try: |
| 687 |
if self.is_restart: |
| 688 |
self.task_job_mgr.task_remote_mgr.is_restart = True |
| 689 |
self.task_job_mgr.task_remote_mgr.rsync_includes = ( |
| 690 |
self.config.get_validated_rsync_includes()) |
| 691 |
if self.pool.get_tasks(): |
| 692 |
# (If we're not restarting a finished workflow) |
| 693 |
self.restart_remote_init() |
| 694 |
await commands.run_cmd(commands.poll_tasks(self, ['*/*'])) |
| 695 |
|
| 696 |
# If we shut down with manually triggered waiting tasks, |
| 697 |
# submit them to run now. |
| 698 |
pre_prep_tasks = [] |
| 699 |
for itask in self.pool.get_tasks(): |
| 700 |
if ( |
| 701 |
itask.is_manual_submit |
| 702 |
and itask.state(TASK_STATUS_WAITING) |
| 703 |
): |
| 704 |
itask.waiting_on_job_prep = True |
| 705 |
pre_prep_tasks.append(itask) |
| 706 |
|
| 707 |
self.start_job_submission(pre_prep_tasks) |
| 708 |
|
| 709 |
self.run_event_handlers(self.EVENT_STARTUP, 'workflow starting') |
| 710 |
await asyncio.gather( |
| 711 |
*main_loop.get_runners( |
| 712 |
self.main_loop_plugins, |
| 713 |
main_loop.CoroTypes.StartUp, |
| 714 |
self |
| 715 |
) |
| 716 |
) |
| 717 |
self.server.publish_queue.put( |
| 718 |
self.data_store_mgr.publish_deltas) |
| 719 |
# Non-async sleep - yield to other threads rather than event loop |
| 720 |
sleep(0) |
| 721 |
self.profiler.start() |
| 722 |
while True: # MAIN LOOP |
| 723 |
await self._main_loop() |
| 724 |
|
| 725 |
except SchedulerStop as exc: |
| 726 |
# deliberate stop |
| 727 |
await self.shutdown(exc) |
| 728 |
try: |
| 729 |
if self.auto_restart_mode == AutoRestartMode.RESTART_NORMAL: |
| 730 |
self.workflow_auto_restart() |
| 731 |
# run shutdown coros |
| 732 |
await asyncio.gather( |
| 733 |
*main_loop.get_runners( |
| 734 |
self.main_loop_plugins, |
| 735 |
main_loop.CoroTypes.ShutDown, |
| 736 |
self |
| 737 |
) |
| 738 |
) |
| 739 |
except Exception as exc: |
| 740 |
# Need to log traceback manually because otherwise this |
| 741 |
# exception gets swallowed |
| 742 |
LOG.exception(exc) |
| 743 |
raise |
| 744 |
|
| 745 |
except asyncio.CancelledError as exc: |
| 746 |
await self.handle_exception(exc) |
| 747 |
|
| 748 |
except CylcError as exc: # Includes SchedulerError |
| 749 |
# catch "expected" errors |
| 750 |
await self.handle_exception(exc) |
| 751 |
|
| 752 |
except Exception as exc: |
| 753 |
# catch "unexpected" errors |
| 754 |
with suppress(Exception): |
| 755 |
LOG.critical( |
| 756 |
'An uncaught error caused Cylc to shut down.' |
| 757 |
'\nIf you think this was an issue in Cylc,' |
| 758 |
' please report the following traceback to the developers.' |
| 759 |
'\nhttps://github.com/cylc/cylc-flow/issues/new' |
| 760 |
'?assignees=&labels=bug&template=bug.md&title=;' |
| 761 |
) |
| 762 |
await self.handle_exception(exc) |
| 763 |
|
| 764 |
else: |
| 765 |
# main loop ends (not used?) |
| 766 |
await self.shutdown(SchedulerStop(StopMode.AUTO.value)) |
| 767 |
|
| 768 |
finally: |
| 769 |
self.profiler.stop() |
| 770 |
|
| 771 |
def load_workflow_params_and_tmpl_vars(self) -> List[Tuple[str, str]]: |
| 772 |
"""Load workflow params and template variables""" |
| 773 |
with self.workflow_db_mgr.get_pri_dao() as pri_dao: |
| 774 |
# This logic handles lack of initial cycle point in flow.cylc and |
| 775 |
# things that can't change on workflow restart/reload. |
| 776 |
pri_dao.select_workflow_template_vars(self._load_template_vars) |
| 777 |
pri_dao.execute_queued_items() |
| 778 |
return list(pri_dao.select_workflow_params()) |
| 779 |
|
| 780 |
async def start(self): |
| 781 |
"""Run the startup sequence but don't set the main loop running. |
| 782 |
|
| 783 |
Lightweight wrapper for testing convenience. |
| 784 |
|
| 785 |
""" |
| 786 |
if self.is_restart: |
| 787 |
params = self.load_workflow_params_and_tmpl_vars() |
| 788 |
else: |
| 789 |
params = [] |
| 790 |
|
| 791 |
try: |
| 792 |
await self.initialise() |
| 793 |
|
| 794 |
# Start Server before logging ports/host(s). |
| 795 |
# create thread sync barrier for setup |
| 796 |
barrier = Barrier(2, timeout=10) |
| 797 |
self.server.thread = Thread( |
| 798 |
target=self.server.start, |
| 799 |
args=(barrier,), |
| 800 |
daemon=False |
| 801 |
) |
| 802 |
self.server.thread.start() |
| 803 |
barrier.wait() |
| 804 |
|
| 805 |
# Get UUID now: |
| 806 |
if self.is_restart: |
| 807 |
self.uuid_str = dict(params)['uuid_str'] |
| 808 |
else: |
| 809 |
self.uuid_str = str(uuid4()) |
| 810 |
self.task_events_mgr.uuid_str = self.uuid_str |
| 811 |
|
| 812 |
self._configure_contact() |
| 813 |
await self.configure(params) |
| 814 |
except (KeyboardInterrupt, asyncio.CancelledError, Exception) as exc: |
| 815 |
await self.handle_exception(exc) |
| 816 |
|
| 817 |
async def run(self): |
| 818 |
"""Run the startup sequence and set the main loop running. |
| 819 |
|
| 820 |
Lightweight wrapper for testing convenience. |
| 821 |
""" |
| 822 |
# register signal handlers |
| 823 |
for sig in ( |
| 824 |
# ctrl+c |
| 825 |
signal.SIGINT, |
| 826 |
# the "stop please" signal |
| 827 |
signal.SIGTERM, |
| 828 |
# the controlling process bailed |
| 829 |
# (e.g. terminal quit in no detach mode) |
| 830 |
signal.SIGHUP, |
| 831 |
): |
| 832 |
signal.signal(sig, self._handle_signal) |
| 833 |
|
| 834 |
await self.start() |
| 835 |
# note run_scheduler handles its own shutdown logic |
| 836 |
await self.run_scheduler() |
| 837 |
|
| 838 |
def _handle_signal(self, sig: int, frame) -> None: |
| 839 |
"""Handle a signal.""" |
| 840 |
LOG.critical(f'Signal {signal.Signals(sig).name} received') |
| 841 |
if sig in {signal.SIGINT, signal.SIGTERM, signal.SIGHUP}: |
| 842 |
if self.stop_mode == StopMode.REQUEST_NOW: |
| 843 |
# already shutting down NOW -> escalate to NOW_NOW |
| 844 |
# (i.e. don't run/wait for event handlers) |
| 845 |
stop_mode = StopMode.REQUEST_NOW_NOW |
| 846 |
else: |
| 847 |
# stop NOW (orphan running tasks) |
| 848 |
stop_mode = StopMode.REQUEST_NOW |
| 849 |
|
| 850 |
self._set_stop(stop_mode) |
| 851 |
|
| 852 |
def _load_pool_from_tasks(self): |
| 853 |
"""Load task pool with specified tasks, for a new run.""" |
| 854 |
LOG.info(f"Start task: {self.options.starttask}") |
| 855 |
start_tasks = command_validation.is_tasks(self.options.starttask) |
| 856 |
# flow number set in this call: |
| 857 |
self.pool.set_prereqs_and_outputs( |
| 858 |
start_tasks, |
| 859 |
outputs=[], |
| 860 |
prereqs=["all"], |
| 861 |
flow=[FLOW_NEW], |
| 862 |
flow_descr=f"original flow from {self.options.starttask}" |
| 863 |
) |
| 864 |
|
| 865 |
def _load_pool_from_point(self): |
| 866 |
"""Load task pool for a cycle point, for a new run. |
| 867 |
|
| 868 |
Iterate through all sequences to find the first instance of each task. |
| 869 |
Add it to the pool if it has no parents at or after the start point. |
| 870 |
|
| 871 |
(Later on, tasks with parents will be spawned on demand, and tasks with |
| 872 |
no parents will be auto-spawned when their previous instances are |
| 873 |
released from runhead.) |
| 874 |
|
| 875 |
""" |
| 876 |
start_type = ( |
| 877 |
"Warm" if self.config.start_point > self.config.initial_point |
| 878 |
else "Cold" |
| 879 |
) |
| 880 |
LOG.info(f"{start_type} start from {self.config.start_point}") |
| 881 |
self.pool.load_from_point() |
| 882 |
|
| 883 |
def _load_pool_from_db(self): |
| 884 |
"""Load task pool from DB, for a restart.""" |
| 885 |
self.workflow_db_mgr.pri_dao.select_broadcast_states( |
| 886 |
self.broadcast_mgr.load_db_broadcast_states) |
| 887 |
self.broadcast_mgr.post_load_db_coerce() |
| 888 |
self.workflow_db_mgr.pri_dao.select_task_job_run_times( |
| 889 |
self._load_task_run_times) |
| 890 |
self.workflow_db_mgr.pri_dao.select_task_pool_for_restart( |
| 891 |
self.pool.load_db_task_pool_for_restart) |
| 892 |
self.workflow_db_mgr.pri_dao.select_jobs_for_restart( |
| 893 |
self.data_store_mgr.insert_db_job) |
| 894 |
self.workflow_db_mgr.pri_dao.select_task_action_timers( |
| 895 |
self.pool.load_db_task_action_timers) |
| 896 |
self.workflow_db_mgr.pri_dao.select_xtriggers_for_restart( |
| 897 |
self.xtrigger_mgr.load_xtrigger_for_restart) |
| 898 |
self.workflow_db_mgr.pri_dao.select_abs_outputs_for_restart( |
| 899 |
self.pool.load_abs_outputs_for_restart) |
| 900 |
|
| 901 |
self.pool.load_db_tasks_to_hold() |
| 902 |
self.pool.update_flow_mgr() |
| 903 |
|
| 904 |
def restart_remote_init(self): |
| 905 |
"""Remote init for all submitted/running tasks in the pool.""" |
| 906 |
self.task_job_mgr.task_remote_mgr.is_restart = True |
| 907 |
distinct_install_target_platforms = [] |
| 908 |
for itask in self.pool.get_tasks(): |
| 909 |
itask.platform['install target'] = ( |
| 910 |
get_install_target_from_platform(itask.platform)) |
| 911 |
if ( |
| 912 |
# we don't need to remote-init for preparing tasks because |
| 913 |
# they will be reset to waiting on restart |
| 914 |
itask.state(*TASK_STATUSES_ACTIVE) |
| 915 |
and not ( |
| 916 |
is_platform_with_target_in_list( |
| 917 |
itask.platform['install target'], |
| 918 |
distinct_install_target_platforms |
| 919 |
) |
| 920 |
) |
| 921 |
): |
| 922 |
distinct_install_target_platforms.append(itask.platform) |
| 923 |
|
| 924 |
for platform in distinct_install_target_platforms: |
| 925 |
# skip remote init for localhost |
| 926 |
install_target = platform['install target'] |
| 927 |
if install_target == get_localhost_install_target(): |
| 928 |
continue |
| 929 |
# set off remote init |
| 930 |
self.task_job_mgr.task_remote_mgr.remote_init(platform) |
| 931 |
# Remote init/file-install is done via process pool |
| 932 |
self.proc_pool.process() |
| 933 |
# add platform to map (to be picked up on main loop) |
| 934 |
self.incomplete_ri_map[install_target] = platform |
| 935 |
|
| 936 |
def manage_remote_init(self): |
| 937 |
"""Manage the remote init/file install process for restarts. |
| 938 |
|
| 939 |
* Called within the main loop. |
| 940 |
* Starts file installation when Remote init is complete. |
| 941 |
* Retries remote init/file install on SSH failure (255). |
| 942 |
* Removes complete or fatally failed installations. |
| 943 |
* The bad_hosts logic already handles unreachable hosts. |
| 944 |
""" |
| 945 |
for install_target, platform in list(self.incomplete_ri_map.items()): |
| 946 |
remote_mgr = self.task_job_mgr.task_remote_mgr |
| 947 |
status = remote_mgr.remote_init_map[install_target] |
| 948 |
if status == REMOTE_INIT_DONE: |
| 949 |
remote_mgr.file_install(platform) |
| 950 |
elif status == REMOTE_INIT_255: |
| 951 |
# Remote init failed due to unreachable host, retry. |
| 952 |
remote_mgr.remote_init(platform) |
| 953 |
elif status == REMOTE_FILE_INSTALL_255: |
| 954 |
# File install failed due to unreachable host, retry. |
| 955 |
remote_mgr.file_install(platform) |
| 956 |
elif status in [REMOTE_FILE_INSTALL_DONE, |
| 957 |
REMOTE_INIT_FAILED, |
| 958 |
REMOTE_FILE_INSTALL_FAILED]: |
| 959 |
# Complete or fatally failed, remove install target. |
| 960 |
self.incomplete_ri_map.pop(install_target) |
| 961 |
|
| 962 |
def _load_task_run_times(self, row_idx, row): |
| 963 |
"""Load run times of previously succeeded task jobs.""" |
| 964 |
if row_idx == 0: |
| 965 |
LOG.debug("LOADING task run times") |
| 966 |
name, run_times_str = row |
| 967 |
try: |
| 968 |
taskdef = self.config.taskdefs[name] |
| 969 |
maxlen = TaskDef.MAX_LEN_ELAPSED_TIMES |
| 970 |
for run_time_str in run_times_str.rsplit(",", maxlen)[-maxlen:]: |
| 971 |
run_time = int(run_time_str) |
| 972 |
taskdef.elapsed_times.append(run_time) |
| 973 |
LOG.debug("+ %s: %s" % ( |
| 974 |
name, ",".join(str(s) for s in taskdef.elapsed_times))) |
| 975 |
except (KeyError, ValueError, AttributeError): |
| 976 |
return |
| 977 |
|
| 978 |
def process_queued_task_messages(self) -> None: |
| 979 |
"""Process incoming task messages for each task proxy. |
| 980 |
|
| 981 |
""" |
| 982 |
messages: dict[str, list[TaskMsg]] = {} |
| 983 |
|
| 984 |
# Retrieve queued messages |
| 985 |
while self.message_queue.qsize(): |
| 986 |
try: |
| 987 |
task_msg = self.message_queue.get(block=False) |
| 988 |
except Empty: |
| 989 |
break |
| 990 |
self.message_queue.task_done() |
| 991 |
# task ID (job stripped) |
| 992 |
task_id = task_msg.job_id.duplicate(job=None).relative_id |
| 993 |
messages.setdefault(task_id, []).append(task_msg) |
| 994 |
|
| 995 |
unprocessed_messages: List[TaskMsg] = [] |
| 996 |
# Poll tasks for which messages caused a backward state change. |
| 997 |
to_poll_tasks: List[TaskProxy] = [] |
| 998 |
for task_id, message_items in messages.items(): |
| 999 |
itask = self.pool._get_task_by_id(task_id) |
| 1000 |
if itask is None: |
| 1001 |
unprocessed_messages.extend(message_items) |
| 1002 |
continue |
| 1003 |
should_poll = False |
| 1004 |
for tm in message_items: |
| 1005 |
if self.task_events_mgr.process_message( |
| 1006 |
itask, tm.severity, tm.message, tm.event_time, |
| 1007 |
self.task_events_mgr.FLAG_RECEIVED, tm.job_id.submit_num |
| 1008 |
): |
| 1009 |
should_poll = True |
| 1010 |
if should_poll: |
| 1011 |
to_poll_tasks.append(itask) |
| 1012 |
if to_poll_tasks: |
| 1013 |
self.task_job_mgr.poll_task_jobs(to_poll_tasks) |
| 1014 |
|
| 1015 |
# Remaining unprocessed messages have no corresponding task proxy. |
| 1016 |
# For example, if I manually set a running task to succeeded, the |
| 1017 |
# proxy can be removed, but the orphaned job still sends messages. |
| 1018 |
warn = "" |
| 1019 |
for tm in unprocessed_messages: |
| 1020 |
job_tokens = self.tokens.duplicate(tm.job_id) |
| 1021 |
try: |
| 1022 |
tdef = self.config.get_taskdef(job_tokens['task']) |
| 1023 |
except WorkflowConfigError as exc: |
| 1024 |
LOG.error(exc) |
| 1025 |
warn += f'\n {tm.job_id}: {tm.severity} - "{tm.message}"' |
| 1026 |
continue |
| 1027 |
if not self.task_events_mgr.process_job_message( |
| 1028 |
job_tokens, tdef, tm.message, tm.event_time |
| 1029 |
): |
| 1030 |
warn += f'\n {tm.job_id}: {tm.severity} - "{tm.message}"' |
| 1031 |
if warn: |
| 1032 |
LOG.warning( |
| 1033 |
f"Undeliverable task messages received and ignored:{warn}" |
| 1034 |
) |
| 1035 |
|
| 1036 |
async def process_command_queue(self) -> None: |
| 1037 |
"""Process queued commands.""" |
| 1038 |
qsize = self.command_queue.qsize() |
| 1039 |
if qsize <= 0: |
| 1040 |
return |
| 1041 |
LOG.debug(f"Processing {qsize} queued command(s)") |
| 1042 |
while True: |
| 1043 |
uuid: str |
| 1044 |
name: str |
| 1045 |
cmd: AsyncGenerator |
| 1046 |
try: |
| 1047 |
uuid, name, cmd = self.command_queue.get(False) |
| 1048 |
except Empty: |
| 1049 |
break |
| 1050 |
msg = f'Command "{name}" ' + '{result}' + f'. ID={uuid}' |
| 1051 |
try: |
| 1052 |
n_warnings: Optional[int] = None |
| 1053 |
with suppress(StopAsyncIteration): |
| 1054 |
n_warnings = await cmd.__anext__() |
| 1055 |
except Exception as exc: |
| 1056 |
# Don't let a bad command bring the workflow down. |
| 1057 |
if ( |
| 1058 |
cylc.flow.flags.verbosity > 1 or |
| 1059 |
not isinstance(exc, CommandFailedError) |
| 1060 |
): |
| 1061 |
LOG.error(traceback.format_exc()) |
| 1062 |
LOG.error( |
| 1063 |
msg.format(result="failed") + f"\n{exc}" |
| 1064 |
) |
| 1065 |
else: |
| 1066 |
if n_warnings: |
| 1067 |
LOG.info( |
| 1068 |
msg.format( |
| 1069 |
result=f"actioned with {n_warnings} warnings" |
| 1070 |
) |
| 1071 |
) |
| 1072 |
else: |
| 1073 |
LOG.info(msg.format(result="actioned")) |
| 1074 |
self.is_updated = True |
| 1075 |
|
| 1076 |
self.command_queue.task_done() |
| 1077 |
|
| 1078 |
def _set_stop(self, stop_mode: Optional[StopMode] = None) -> None: |
| 1079 |
"""Set shutdown mode.""" |
| 1080 |
self.proc_pool.set_stopping() |
| 1081 |
self.stop_mode = stop_mode |
| 1082 |
self.update_data_store() |
| 1083 |
|
| 1084 |
def kill_tasks( |
| 1085 |
self, itasks: 'Iterable[TaskProxy]', warn: bool = True |
| 1086 |
) -> int: |
| 1087 |
"""Kill tasks if they are in a killable state. |
| 1088 |
|
| 1089 |
Args: |
| 1090 |
itasks: Tasks to kill. |
| 1091 |
warn: Whether to warn about tasks that are not in a killable state. |
| 1092 |
|
| 1093 |
Returns number of tasks that could not be killed. |
| 1094 |
""" |
| 1095 |
jobless = self.get_run_mode() == RunMode.SIMULATION |
| 1096 |
to_kill: List[TaskProxy] = [] |
| 1097 |
unkillable: List[TaskProxy] = [] |
| 1098 |
for itask in itasks: |
| 1099 |
if not itask.state(TASK_STATUS_PREPARING, *TASK_STATUSES_ACTIVE): |
| 1100 |
unkillable.append(itask) |
| 1101 |
continue |
| 1102 |
self.pool.hold_active_task(itask) |
| 1103 |
if itask.state(TASK_STATUS_PREPARING): |
| 1104 |
self.task_job_mgr.kill_prep_task(itask) |
| 1105 |
else: |
| 1106 |
to_kill.append(itask) |
| 1107 |
if jobless: |
| 1108 |
# Directly set failed in sim mode: |
| 1109 |
self.task_events_mgr.process_message( |
| 1110 |
itask, 'CRITICAL', TASK_STATUS_FAILED, |
| 1111 |
flag=self.task_events_mgr.FLAG_RECEIVED |
| 1112 |
) |
| 1113 |
if warn and unkillable: |
| 1114 |
LOG.warning( |
| 1115 |
"Tasks not killable: " |
| 1116 |
f"{', '.join(sorted(t.identity for t in unkillable))}" |
| 1117 |
) |
| 1118 |
if not jobless: |
| 1119 |
self.task_job_mgr.kill_task_jobs(to_kill) |
| 1120 |
|
| 1121 |
return len(unkillable) |
| 1122 |
|
| 1123 |
def get_restart_num(self) -> int: |
| 1124 |
"""Return the number of the restart, else 0 if not a restart. |
| 1125 |
|
| 1126 |
Performs DB restart-check the first time this is called. |
| 1127 |
""" |
| 1128 |
if not self.is_restart: |
| 1129 |
return 0 |
| 1130 |
if self.workflow_db_mgr.n_restart == 0: |
| 1131 |
self.workflow_db_mgr.restart_check() |
| 1132 |
return self.workflow_db_mgr.n_restart |
| 1133 |
|
| 1134 |
def get_contact_data(self) -> Dict[str, str]: |
| 1135 |
"""Extract contact data from this Scheduler. |
| 1136 |
|
| 1137 |
This provides the information that is written to the contact file. |
| 1138 |
""" |
| 1139 |
fields = workflow_files.ContactFileFields |
| 1140 |
proc = psutil.Process() |
| 1141 |
platform = get_platform() |
| 1142 |
# fmt: off |
| 1143 |
return { |
| 1144 |
fields.API: |
| 1145 |
str(API), |
| 1146 |
fields.HOST: |
| 1147 |
self.host, |
| 1148 |
fields.NAME: |
| 1149 |
self.workflow, |
| 1150 |
fields.OWNER: |
| 1151 |
self.owner, |
| 1152 |
fields.PORT: |
| 1153 |
str(self.server.port), |
| 1154 |
fields.PID: |
| 1155 |
str(proc.pid), |
| 1156 |
fields.COMMAND: |
| 1157 |
cli_format(proc.cmdline()), |
| 1158 |
fields.PUBLISH_PORT: |
| 1159 |
str(self.server.pub_port), |
| 1160 |
fields.WORKFLOW_RUN_DIR_ON_WORKFLOW_HOST: |
| 1161 |
self.workflow_run_dir, |
| 1162 |
fields.UUID: |
| 1163 |
self.uuid_str, |
| 1164 |
fields.VERSION: |
| 1165 |
CYLC_VERSION, |
| 1166 |
fields.SCHEDULER_SSH_COMMAND: |
| 1167 |
str(platform['ssh command']), |
| 1168 |
fields.SCHEDULER_CYLC_PATH: |
| 1169 |
str(platform['cylc path']), |
| 1170 |
fields.SCHEDULER_USE_LOGIN_SHELL: |
| 1171 |
str(platform['use login shell']) |
| 1172 |
} |
| 1173 |
# fmt: on |
| 1174 |
|
| 1175 |
def _configure_contact(self) -> None: |
| 1176 |
"""Create contact file.""" |
| 1177 |
# Make sure another workflow of the same name hasn't started while this |
| 1178 |
# one is starting |
| 1179 |
# NOTE: raises SchedulerAlive if workflow is running |
| 1180 |
workflow_files.detect_old_contact_file(self.workflow) |
| 1181 |
|
| 1182 |
# Extract contact data. |
| 1183 |
contact_data = self.get_contact_data() |
| 1184 |
|
| 1185 |
# Write workflow contact file. |
| 1186 |
# Preserve contact data in memory, for regular health check. |
| 1187 |
workflow_files.dump_contact_file(self.workflow, contact_data) |
| 1188 |
self.contact_data = contact_data |
| 1189 |
|
| 1190 |
def load_flow_file(self, is_reload=False): |
| 1191 |
"""Load, and log the workflow definition.""" |
| 1192 |
return WorkflowConfig( |
| 1193 |
self.workflow, |
| 1194 |
self.flow_file, |
| 1195 |
self.options, |
| 1196 |
self.template_vars, |
| 1197 |
mem_log_func=self.profiler.log_memory, |
| 1198 |
output_fname=os.path.join( |
| 1199 |
self.workflow_run_dir, 'log', 'config', |
| 1200 |
workflow_files.WorkflowFiles.FLOW_FILE_PROCESSED |
| 1201 |
), |
| 1202 |
run_dir=self.workflow_run_dir, |
| 1203 |
log_dir=self.workflow_log_dir, |
| 1204 |
work_dir=self.workflow_work_dir, |
| 1205 |
share_dir=self.workflow_share_dir, |
| 1206 |
) |
| 1207 |
|
| 1208 |
def apply_new_config(self, config, is_reload=False): |
| 1209 |
self.config = config |
| 1210 |
self.cylc_config = DictTree( |
| 1211 |
self.config.cfg['scheduler'], |
| 1212 |
glbl_cfg().get(['scheduler']) |
| 1213 |
) |
| 1214 |
self.flow_file_update_time = time() |
| 1215 |
# Dump the loaded flow.cylc file for future reference. |
| 1216 |
config_dir = get_workflow_run_config_log_dir( |
| 1217 |
self.workflow) |
| 1218 |
config_logs = get_sorted_logs_by_time(config_dir, "*[0-9].cylc") |
| 1219 |
log_num = get_next_log_number(config_logs[-1]) if config_logs else 1 |
| 1220 |
if is_reload: |
| 1221 |
load_type = "reload" |
| 1222 |
load_type_num = get_reload_start_number(config_logs) |
| 1223 |
elif self.is_restart: |
| 1224 |
load_type = "restart" |
| 1225 |
restart_num = self.get_restart_num() + 1 |
| 1226 |
load_type_num = f'{restart_num:02d}' |
| 1227 |
else: |
| 1228 |
load_type = "start" |
| 1229 |
load_type_num = '01' |
| 1230 |
file_name = get_workflow_run_config_log_dir( |
| 1231 |
self.workflow, f"{log_num:02d}-{load_type}-{load_type_num}.cylc") |
| 1232 |
with open(file_name, "w") as handle: |
| 1233 |
handle.write("# cylc-version: %s\n" % CYLC_VERSION) |
| 1234 |
self.config.pcfg.idump(sparse=True, handle=handle) |
| 1235 |
|
| 1236 |
# Pass static cylc and workflow variables to job script generation code |
| 1237 |
self.task_job_mgr.job_file_writer.set_workflow_env({ |
| 1238 |
**verbosity_to_env(cylc.flow.flags.verbosity), |
| 1239 |
'CYLC_UTC': str(get_utc_mode()), |
| 1240 |
'CYLC_WORKFLOW_ID': self.workflow, |
| 1241 |
'CYLC_WORKFLOW_NAME': self.workflow_name, |
| 1242 |
'CYLC_WORKFLOW_NAME_BASE': str(Path(self.workflow_name).name), |
| 1243 |
'CYLC_CYCLING_MODE': str( |
| 1244 |
self.config.cfg['scheduling']['cycling mode'] |
| 1245 |
), |
| 1246 |
'CYLC_WORKFLOW_INITIAL_CYCLE_POINT': str( |
| 1247 |
self.config.initial_point |
| 1248 |
), |
| 1249 |
'CYLC_WORKFLOW_FINAL_CYCLE_POINT': str(self.config.final_point), |
| 1250 |
}) |
| 1251 |
|
| 1252 |
def _set_workflow_params( |
| 1253 |
self, params: Iterable[tuple[str, str | None]] |
| 1254 |
) -> None: |
| 1255 |
"""Set workflow params on restart/reload. |
| 1256 |
|
| 1257 |
This currently includes: |
| 1258 |
* Initial/Final cycle points. |
| 1259 |
* Start/Stop Cycle points. |
| 1260 |
* Stop task. |
| 1261 |
* Workflow UUID. |
| 1262 |
* A flag to indicate if the workflow should be paused or not. |
| 1263 |
* Original workflow run time zone. |
| 1264 |
""" |
| 1265 |
LOG.info("LOADING saved workflow parameters") |
| 1266 |
for key, value in params: |
| 1267 |
if key == self.workflow_db_mgr.KEY_RUN_MODE: |
| 1268 |
self.options.run_mode = value or RunMode.LIVE.value |
| 1269 |
LOG.info(f"+ run mode = {value}") |
| 1270 |
if value is None: |
| 1271 |
continue |
| 1272 |
if key == self.workflow_db_mgr.KEY_INITIAL_CYCLE_POINT: |
| 1273 |
self.options.icp = value |
| 1274 |
LOG.info(f"+ initial point = {value}") |
| 1275 |
elif key == self.workflow_db_mgr.KEY_START_CYCLE_POINT: |
| 1276 |
self.options.startcp = value |
| 1277 |
LOG.info(f"+ start point = {value}") |
| 1278 |
elif key == self.workflow_db_mgr.KEY_FINAL_CYCLE_POINT: |
| 1279 |
if self.is_restart and self.options.fcp == 'reload': |
| 1280 |
LOG.debug(f"- final point = {value} (ignored)") |
| 1281 |
elif self.options.fcp is None: |
| 1282 |
self.options.fcp = value |
| 1283 |
LOG.info(f"+ final point = {value}") |
| 1284 |
elif key == self.workflow_db_mgr.KEY_STOP_CYCLE_POINT: |
| 1285 |
if self.is_restart and self.options.stopcp == 'reload': |
| 1286 |
LOG.debug(f"- stop point = {value} (ignored)") |
| 1287 |
elif self.options.stopcp is None: |
| 1288 |
self.options.stopcp = value |
| 1289 |
LOG.info(f"+ stop point = {value}") |
| 1290 |
elif key == self.workflow_db_mgr.KEY_UUID_STR: |
| 1291 |
self.uuid_str = value |
| 1292 |
LOG.info(f"+ workflow UUID = {value}") |
| 1293 |
elif key == self.workflow_db_mgr.KEY_PAUSED: |
| 1294 |
bool_val = bool(int(value)) |
| 1295 |
if bool_val and not self.options.paused_start: |
| 1296 |
self.options.paused_start = bool_val |
| 1297 |
LOG.info(f"+ paused = {bool_val}") |
| 1298 |
elif ( |
| 1299 |
key == self.workflow_db_mgr.KEY_HOLD_CYCLE_POINT |
| 1300 |
and self.options.holdcp is None |
| 1301 |
): |
| 1302 |
self.options.holdcp = value |
| 1303 |
LOG.info(f"+ hold point = {value}") |
| 1304 |
elif key == self.workflow_db_mgr.KEY_STOP_CLOCK_TIME: |
| 1305 |
int_val = int(value) |
| 1306 |
msg = f"stop clock time = {int_val} ({time2str(int_val)})" |
| 1307 |
if time() <= int_val: |
| 1308 |
self.stop_clock_time = int_val |
| 1309 |
LOG.info(f"+ {msg}") |
| 1310 |
else: |
| 1311 |
LOG.debug(f"- {msg} (ignored)") |
| 1312 |
elif key == self.workflow_db_mgr.KEY_STOP_TASK: |
| 1313 |
self.restored_stop_task_id = value |
| 1314 |
LOG.info(f"+ stop task = {value}") |
| 1315 |
elif key == self.workflow_db_mgr.KEY_UTC_MODE: |
| 1316 |
bool_val = bool(int(value)) |
| 1317 |
self.options.utc_mode = bool_val |
| 1318 |
LOG.info(f"+ UTC mode = {bool_val}") |
| 1319 |
elif key == self.workflow_db_mgr.KEY_CYCLE_POINT_TIME_ZONE: |
| 1320 |
self.options.cycle_point_tz = value |
| 1321 |
LOG.info(f"+ cycle point time zone = {value}") |
| 1322 |
|
| 1323 |
def _load_template_vars(self, _, row): |
| 1324 |
"""Load workflow start up template variables.""" |
| 1325 |
key, value = row |
| 1326 |
# Command line argument takes precedence |
| 1327 |
if key not in self.template_vars: |
| 1328 |
self.template_vars[key] = eval_var(value) |
| 1329 |
|
| 1330 |
def run_event_handlers(self, event, reason=""): |
| 1331 |
"""Run a workflow event handler. |
| 1332 |
|
| 1333 |
Run workflow events only in live mode or skip mode. |
| 1334 |
""" |
| 1335 |
if self.get_run_mode() in {RunMode.SIMULATION, RunMode.DUMMY}: |
| 1336 |
return |
| 1337 |
self.workflow_event_handler.handle(self, event, str(reason)) |
| 1338 |
|
| 1339 |
def release_tasks_to_run(self) -> bool: |
| 1340 |
"""Release queued or manually submitted tasks, and submit jobs. |
| 1341 |
|
| 1342 |
The task queue manages references to task proxies in the task pool. |
| 1343 |
|
| 1344 |
Tasks which have entered the submission pipeline but not yet finished |
| 1345 |
(pre_prep_tasks) are passed to job submission multiple times until they |
| 1346 |
have passed through a series of asynchronous operations (host select, |
| 1347 |
remote init, remote file install, etc). |
| 1348 |
|
| 1349 |
Note: |
| 1350 |
We do not maintain a list of "pre_prep_tasks" between iterations |
| 1351 |
of this method as this creates an intermediate task staging pool |
| 1352 |
which has nasty consequences: |
| 1353 |
|
| 1354 |
* https://github.com/cylc/cylc-flow/pull/4620 |
| 1355 |
* https://github.com/cylc/cylc-flow/issues/4974 |
| 1356 |
|
| 1357 |
Returns: |
| 1358 |
True if tasks were passed through the submit-pipeline |
| 1359 |
(i.e. new waiting tasks have entered the preparing state OR |
| 1360 |
preparing tasks have been passed back through for |
| 1361 |
submission). |
| 1362 |
|
| 1363 |
""" |
| 1364 |
pre_prep_tasks: Set['TaskProxy'] = set() |
| 1365 |
if ( |
| 1366 |
not self.stop_mode |
| 1367 |
and self.auto_restart_time is None |
| 1368 |
and self.reload_pending is False |
| 1369 |
): |
| 1370 |
if self.pool.tasks_to_trigger_now: |
| 1371 |
# manually triggered tasks to run now. |
| 1372 |
pre_prep_tasks.update(self.pool.tasks_to_trigger_now) |
| 1373 |
self.pool.tasks_to_trigger_now = set() |
| 1374 |
|
| 1375 |
if not self.is_paused: |
| 1376 |
# release queued tasks |
| 1377 |
pre_prep_tasks.update(self.pool.release_queued_tasks()) |
| 1378 |
|
| 1379 |
if ( |
| 1380 |
# Manually triggered tasks will be preparing and should |
| 1381 |
# be submitted even if paused (unless workflow is stopping). |
| 1382 |
self.is_paused and not self.stop_mode |
| 1383 |
) or ( |
| 1384 |
# Need to get preparing tasks to submit before auto restart |
| 1385 |
self.should_auto_restart_now() |
| 1386 |
and self.auto_restart_mode == AutoRestartMode.RESTART_NORMAL |
| 1387 |
) or ( |
| 1388 |
# Need to get preparing tasks to submit before reload |
| 1389 |
self.reload_pending |
| 1390 |
): |
| 1391 |
pre_prep_tasks.update({ |
| 1392 |
itask |
| 1393 |
for itask in self.pool.get_tasks() |
| 1394 |
if itask.waiting_on_job_prep |
| 1395 |
}) |
| 1396 |
|
| 1397 |
# Return, if no tasks to submit. |
| 1398 |
if not pre_prep_tasks: |
| 1399 |
return False |
| 1400 |
|
| 1401 |
return self.start_job_submission(pre_prep_tasks) |
| 1402 |
|
| 1403 |
def start_job_submission(self, itasks: 'Iterable[TaskProxy]') -> bool: |
| 1404 |
"""Start the job submission process for some tasks. |
| 1405 |
|
| 1406 |
Return True if any were started, else False. |
| 1407 |
|
| 1408 |
""" |
| 1409 |
if self.stop_mode is not None: |
| 1410 |
return False |
| 1411 |
|
| 1412 |
self.is_updated = True |
| 1413 |
self.reset_inactivity_timer() |
| 1414 |
|
| 1415 |
self.task_job_mgr.task_remote_mgr.rsync_includes = ( |
| 1416 |
self.config.get_validated_rsync_includes()) |
| 1417 |
|
| 1418 |
submitted = self.submit_task_jobs(itasks) |
| 1419 |
if not submitted: |
| 1420 |
return False |
| 1421 |
|
| 1422 |
log_lvl = logging.DEBUG |
| 1423 |
if self.options.reftest or self.options.genref: |
| 1424 |
log_lvl = logging.INFO |
| 1425 |
|
| 1426 |
for itask in submitted: |
| 1427 |
flow = stringify_flow_nums(itask.flow_nums) or FLOW_NONE |
| 1428 |
if itask.is_manual_submit: |
| 1429 |
off = f"[] in flow {flow}" |
| 1430 |
else: |
| 1431 |
off = ( |
| 1432 |
f"{itask.state.get_resolved_dependencies()}" |
| 1433 |
f" in flow {flow}" |
| 1434 |
) |
| 1435 |
LOG.log(log_lvl, f"{itask.identity} -triggered off {off}") |
| 1436 |
|
| 1437 |
# one or more tasks were passed through the submission pipeline |
| 1438 |
return True |
| 1439 |
|
| 1440 |
def submit_task_jobs( |
| 1441 |
self, itasks: 'Iterable[TaskProxy]' |
| 1442 |
) -> 'List[TaskProxy]': |
| 1443 |
"""Submit task jobs, return tasks that attempted submission.""" |
| 1444 |
# Note: keep this as simple wrapper for task job mgr's method |
| 1445 |
return self.task_job_mgr.submit_task_jobs(itasks, self.get_run_mode()) |
| 1446 |
|
| 1447 |
def process_workflow_db_queue(self): |
| 1448 |
"""Update workflow DB.""" |
| 1449 |
self.workflow_db_mgr.process_queued_ops() |
| 1450 |
|
| 1451 |
def database_health_check(self): |
| 1452 |
"""If public database is stuck, blast it away by copying the content |
| 1453 |
of the private database into it.""" |
| 1454 |
self.workflow_db_mgr.recover_pub_from_pri() |
| 1455 |
|
| 1456 |
def late_tasks_check(self): |
| 1457 |
"""Report tasks that are never active and are late.""" |
| 1458 |
now = time() |
| 1459 |
for itask in self.pool.get_tasks(): |
| 1460 |
if ( |
| 1461 |
not itask.is_late |
| 1462 |
and itask.get_late_time() |
| 1463 |
and itask.state(*TASK_STATUSES_NEVER_ACTIVE) |
| 1464 |
and now > itask.get_late_time() |
| 1465 |
): |
| 1466 |
msg = '%s (late-time=%s)' % ( |
| 1467 |
self.task_events_mgr.EVENT_LATE, |
| 1468 |
time2str(itask.get_late_time())) |
| 1469 |
itask.is_late = True |
| 1470 |
LOG.warning(f"[{itask}] {msg}") |
| 1471 |
self.task_events_mgr.setup_event_handlers( |
| 1472 |
itask, self.task_events_mgr.EVENT_LATE, msg) |
| 1473 |
self.workflow_db_mgr.put_insert_task_late_flags(itask) |
| 1474 |
|
| 1475 |
def reset_inactivity_timer(self): |
| 1476 |
"""Reset inactivity timer - method passed to task event manager.""" |
| 1477 |
with suppress(KeyError): |
| 1478 |
self.timers[self.EVENT_INACTIVITY_TIMEOUT].reset() |
| 1479 |
|
| 1480 |
def timeout_check(self): |
| 1481 |
"""Check workflow and task timers.""" |
| 1482 |
self.check_workflow_timers() |
| 1483 |
# check submission and execution timeout and polling timers |
| 1484 |
if self.get_run_mode() != RunMode.SIMULATION: |
| 1485 |
self.task_job_mgr.check_task_jobs(self.pool) |
| 1486 |
|
| 1487 |
async def workflow_shutdown(self): |
| 1488 |
"""Determines if the workflow can be shutdown yet.""" |
| 1489 |
if self.pool.check_abort_on_task_fails(): |
| 1490 |
self._set_stop(StopMode.AUTO_ON_TASK_FAILURE) |
| 1491 |
|
| 1492 |
# Can workflow shut down automatically? |
| 1493 |
if self.stop_mode is None and ( |
| 1494 |
self.stop_clock_done() or |
| 1495 |
self.pool.stop_task_done() or |
| 1496 |
self.check_auto_shutdown() |
| 1497 |
): |
| 1498 |
self._set_stop(StopMode.AUTO) |
| 1499 |
|
| 1500 |
# Is the workflow ready to shut down now? |
| 1501 |
if self.pool.can_stop(self.stop_mode): |
| 1502 |
await self.update_data_structure() |
| 1503 |
self.proc_pool.close() |
| 1504 |
if self.stop_mode != StopMode.REQUEST_NOW_NOW: |
| 1505 |
# Wait for process pool to complete, |
| 1506 |
# unless --now --now is requested |
| 1507 |
stop_process_pool_empty_msg = ( |
| 1508 |
"Waiting for the command process pool to empty" + |
| 1509 |
" for shutdown") |
| 1510 |
while self.proc_pool.is_not_done(): |
| 1511 |
sleep(self.INTERVAL_STOP_PROCESS_POOL_EMPTY) |
| 1512 |
if stop_process_pool_empty_msg: |
| 1513 |
LOG.info(stop_process_pool_empty_msg) |
| 1514 |
stop_process_pool_empty_msg = None |
| 1515 |
self.proc_pool.process() |
| 1516 |
await self.process_command_queue() |
| 1517 |
if self.options.profile_mode: |
| 1518 |
self.profiler.log_memory( |
| 1519 |
"scheduler.py: end main loop (total loops %d): %s" % |
| 1520 |
(self.count, get_current_time_string())) |
| 1521 |
if self.stop_mode == StopMode.AUTO_ON_TASK_FAILURE: |
| 1522 |
raise SchedulerError(self.stop_mode.value) |
| 1523 |
else: |
| 1524 |
raise SchedulerStop(self.stop_mode.value) |
| 1525 |
elif ( |
| 1526 |
self.time_next_kill is not None |
| 1527 |
and time() > self.time_next_kill |
| 1528 |
): |
| 1529 |
self.task_job_mgr.poll_task_jobs(self.pool.get_tasks()) |
| 1530 |
self.kill_tasks(self.pool.get_tasks(), warn=False) |
| 1531 |
self.time_next_kill = time() + self.INTERVAL_STOP_KILL |
| 1532 |
|
| 1533 |
# Is the workflow set to auto stop [+restart] now ... |
| 1534 |
if not self.should_auto_restart_now(): |
| 1535 |
# ... no |
| 1536 |
pass |
| 1537 |
elif self.auto_restart_mode == AutoRestartMode.RESTART_NORMAL: |
| 1538 |
|
| 1539 |
# ... yes - wait for preparing jobs to see if they're local and |
| 1540 |
# wait for local jobs to complete before restarting |
| 1541 |
# * Avoid polling issues - see #2843 |
| 1542 |
# * Ensure the host can be safely taken down once the |
| 1543 |
# workflow has stopped running. |
| 1544 |
for itask in self.pool.get_tasks(): |
| 1545 |
if itask.state(TASK_STATUS_PREPARING): |
| 1546 |
LOG.info( |
| 1547 |
"Waiting for preparing jobs to submit before " |
| 1548 |
"attempting restart" |
| 1549 |
) |
| 1550 |
break |
| 1551 |
if ( |
| 1552 |
itask.state(*TASK_STATUSES_ACTIVE) |
| 1553 |
and itask.summary['job_runner_name'] |
| 1554 |
and not is_remote_platform(itask.platform) |
| 1555 |
and self.task_job_mgr.job_runner_mgr.is_job_local_to_host( |
| 1556 |
itask.summary['job_runner_name']) |
| 1557 |
): |
| 1558 |
LOG.info('Waiting for jobs running on localhost to ' |
| 1559 |
'complete before attempting restart') |
| 1560 |
break |
| 1561 |
else: # no break |
| 1562 |
if self.pool.pre_start_tasks_to_trigger: |
| 1563 |
LOG.info( |
| 1564 |
'Waiting for pre start-cycle tasks to complete before' |
| 1565 |
' attempting restart' |
| 1566 |
) |
| 1567 |
else: |
| 1568 |
self._set_stop(StopMode.REQUEST_NOW_NOW) |
| 1569 |
elif ( # noqa: SIM106 |
| 1570 |
self.auto_restart_mode == AutoRestartMode.FORCE_STOP |
| 1571 |
): |
| 1572 |
# ... yes - leave local jobs running then stop the workflow |
| 1573 |
# (no restart) |
| 1574 |
self._set_stop(StopMode.REQUEST_NOW) |
| 1575 |
else: |
| 1576 |
raise SchedulerError( |
| 1577 |
'Invalid auto_restart_mode=%s' % self.auto_restart_mode) |
| 1578 |
|
| 1579 |
def should_auto_restart_now(self) -> bool: |
| 1580 |
"""Is it time for the scheduler to auto stop + restart?""" |
| 1581 |
return ( |
| 1582 |
self.auto_restart_time is not None and |
| 1583 |
time() >= self.auto_restart_time |
| 1584 |
) |
| 1585 |
|
| 1586 |
def workflow_auto_restart(self, max_retries: int = 3) -> bool: |
| 1587 |
"""Attempt to restart the workflow assuming it has already stopped.""" |
| 1588 |
cmd = [ |
| 1589 |
'cylc', 'play', quote(self.workflow), |
| 1590 |
*verbosity_to_opts(cylc.flow.flags.verbosity) |
| 1591 |
] |
| 1592 |
if self.options.abort_if_any_task_fails: |
| 1593 |
cmd.append('--abort-if-any-task-fails') |
| 1594 |
for attempt_no in range(max_retries): |
| 1595 |
error: Optional[str] = None |
| 1596 |
proc = None |
| 1597 |
try: |
| 1598 |
new_host = select_workflow_host(cached=False)[0] |
| 1599 |
except HostSelectException as exc: |
| 1600 |
error = str(exc) |
| 1601 |
else: |
| 1602 |
LOG.info(f'Attempting to restart on "{new_host}"') |
| 1603 |
# proc will start with current env (incl CYLC_HOME etc) |
| 1604 |
proc = Popen( # nosec |
| 1605 |
[*cmd, f'--host={new_host}'], |
| 1606 |
stdin=DEVNULL, |
| 1607 |
stdout=PIPE, |
| 1608 |
stderr=PIPE, |
| 1609 |
text=True |
| 1610 |
) |
| 1611 |
if proc.wait(): |
| 1612 |
error = proc.communicate()[1] |
| 1613 |
# * new_host comes from internal interface which can only return |
| 1614 |
# host names |
| 1615 |
if error is not None: |
| 1616 |
msg = 'Could not restart workflow' |
| 1617 |
if attempt_no < max_retries: |
| 1618 |
msg += ( |
| 1619 |
f' will retry in {self.INTERVAL_AUTO_RESTART_ERROR}s') |
| 1620 |
LOG.critical(f"{msg}. Restart error:\n{error}") |
| 1621 |
sleep(self.INTERVAL_AUTO_RESTART_ERROR) |
| 1622 |
else: |
| 1623 |
LOG.info(f'Workflow now running on "{new_host}".') |
| 1624 |
return True |
| 1625 |
LOG.critical( |
| 1626 |
'Workflow unable to automatically restart after ' |
| 1627 |
f'{max_retries} tries - manual restart required.') |
| 1628 |
return False |
| 1629 |
|
| 1630 |
def update_profiler_logs(self, tinit): |
| 1631 |
"""Update info for profiler.""" |
| 1632 |
now = time() |
| 1633 |
self._update_profile_info("scheduler loop dt (s)", now - tinit, |
| 1634 |
amount_format="%.3f") |
| 1635 |
self._update_cpu_usage() |
| 1636 |
if now - self.previous_profile_point >= 60: |
| 1637 |
# Only get this every minute. |
| 1638 |
self.previous_profile_point = now |
| 1639 |
self.profiler.log_memory("scheduler.py: loop #%d: %s" % ( |
| 1640 |
self.count, get_current_time_string())) |
| 1641 |
self.count += 1 |
| 1642 |
|
| 1643 |
async def _main_loop(self) -> None: |
| 1644 |
"""A single iteration of the main loop.""" |
| 1645 |
|
| 1646 |
tinit = time() |
| 1647 |
|
| 1648 |
# Useful for debugging core scheduler issues: |
| 1649 |
# import logging |
| 1650 |
# self.pool.log_task_pool(logging.CRITICAL) |
| 1651 |
if self.incomplete_ri_map: |
| 1652 |
self.manage_remote_init() |
| 1653 |
|
| 1654 |
await self.process_command_queue() |
| 1655 |
self.proc_pool.process() |
| 1656 |
|
| 1657 |
# Unqueued tasks with satisfied prerequisites must be waiting on |
| 1658 |
# xtriggers or ext_triggers. Check these and queue tasks if ready. |
| 1659 |
for itask in self.pool.get_tasks(): |
| 1660 |
if ( |
| 1661 |
not itask.state(TASK_STATUS_WAITING) |
| 1662 |
or itask.state.is_queued |
| 1663 |
or itask.state.is_runahead |
| 1664 |
): |
| 1665 |
continue |
| 1666 |
|
| 1667 |
if ( |
| 1668 |
itask.state.xtriggers |
| 1669 |
and not itask.state.xtriggers_all_satisfied() |
| 1670 |
): |
| 1671 |
self.xtrigger_mgr.call_xtriggers_async(itask) |
| 1672 |
|
| 1673 |
if ( |
| 1674 |
itask.state.external_triggers |
| 1675 |
and not itask.state.external_triggers_all_satisfied() |
| 1676 |
): |
| 1677 |
self.broadcast_mgr.check_ext_triggers( |
| 1678 |
itask, self.ext_trigger_queue) |
| 1679 |
|
| 1680 |
self.pool.spawn_psx_task(itask) |
| 1681 |
self.pool.queue_if_ready(itask) |
| 1682 |
|
| 1683 |
if self.xtrigger_mgr.do_housekeeping: |
| 1684 |
self.xtrigger_mgr.housekeep(self.pool.get_tasks()) |
| 1685 |
|
| 1686 |
self.pool.clock_expire_tasks() |
| 1687 |
self.release_tasks_to_run() |
| 1688 |
|
| 1689 |
if ( |
| 1690 |
self.get_run_mode() == RunMode.SIMULATION |
| 1691 |
and sim_time_check( |
| 1692 |
self.task_events_mgr, |
| 1693 |
self.pool.get_tasks(), |
| 1694 |
self.workflow_db_mgr, |
| 1695 |
) |
| 1696 |
): |
| 1697 |
# A simulated task state change occurred. |
| 1698 |
self.reset_inactivity_timer() |
| 1699 |
|
| 1700 |
# auto expire broadcasts |
| 1701 |
if not self.is_paused: |
| 1702 |
# NOTE: Don't auto-expire broadcasts whilst the scheduler is |
| 1703 |
# paused. This allows broadcast-and-trigger beyond the expiry |
| 1704 |
# limit, by pausing before doing it (after which the expiry |
| 1705 |
# limit moves back). |
| 1706 |
with suppress(TimePointDumperBoundsError): |
| 1707 |
# NOTE: TimePointDumperBoundsError will be raised for negative |
| 1708 |
# cycle points, we skip broadcast expiry in this circumstance |
| 1709 |
# (pre-initial condition) |
| 1710 |
if min_point := self.pool.get_min_point(): |
| 1711 |
# NOTE: the broadcast expire limit is the oldest active |
| 1712 |
# cycle MINUS the longest cycling interval |
| 1713 |
self.broadcast_mgr.expire_broadcast( |
| 1714 |
min_point - self.config.interval_of_longest_sequence |
| 1715 |
) |
| 1716 |
|
| 1717 |
self.late_tasks_check() |
| 1718 |
|
| 1719 |
self.process_queued_task_messages() |
| 1720 |
await self.process_command_queue() |
| 1721 |
self.task_events_mgr.process_events(self) |
| 1722 |
|
| 1723 |
# Update state summary, database, and uifeed |
| 1724 |
self.workflow_db_mgr.put_task_event_timers(self.task_events_mgr) |
| 1725 |
|
| 1726 |
# List of task whose states have changed. |
| 1727 |
updated_task_list = [ |
| 1728 |
t for t in self.pool.get_tasks() if t.state.is_updated] |
| 1729 |
if updated_task_list and self.is_restart_timeout_wait: |
| 1730 |
# Stop restart timeout if action has been triggered. |
| 1731 |
with suppress(KeyError): |
| 1732 |
self.timers[self.EVENT_RESTART_TIMEOUT].stop() |
| 1733 |
self.is_restart_timeout_wait = False |
| 1734 |
|
| 1735 |
has_updated = ( |
| 1736 |
bool(updated_task_list) |
| 1737 |
or self.is_updated |
| 1738 |
or self.pool.tasks_removed |
| 1739 |
) |
| 1740 |
|
| 1741 |
if has_updated: |
| 1742 |
# The runahead limit might need recomputing. |
| 1743 |
self.pool.compute_runahead() |
| 1744 |
self.pool.release_runahead_tasks() |
| 1745 |
|
| 1746 |
if not self.is_reloaded and self.is_stalled: |
| 1747 |
# (A reload cannot un-stall workflow by itself) |
| 1748 |
self.is_stalled = False |
| 1749 |
self.update_data_store() |
| 1750 |
|
| 1751 |
self.is_reloaded = False |
| 1752 |
self.pool.tasks_removed = False |
| 1753 |
# Reset workflow and task updated flags. |
| 1754 |
self.is_updated = False |
| 1755 |
for itask in updated_task_list: |
| 1756 |
itask.state.is_updated = False |
| 1757 |
|
| 1758 |
if not self.is_stalled: |
| 1759 |
# Stop the stalled timer. |
| 1760 |
with suppress(KeyError): |
| 1761 |
self.timers[self.EVENT_STALL_TIMEOUT].stop() |
| 1762 |
elif not self.stop_mode: |
| 1763 |
# Has the workflow stalled? |
| 1764 |
self.check_workflow_stalled() |
| 1765 |
|
| 1766 |
if has_updated or self.data_store_mgr.updates_pending: |
| 1767 |
await self.update_data_structure() |
| 1768 |
|
| 1769 |
self.process_workflow_db_queue() |
| 1770 |
|
| 1771 |
# If public database is stuck, blast it away by copying the content |
| 1772 |
# of the private database into it. |
| 1773 |
self.database_health_check() |
| 1774 |
|
| 1775 |
# Shutdown workflow if timeouts have occurred |
| 1776 |
self.timeout_check() |
| 1777 |
|
| 1778 |
if self.options.profile_mode: |
| 1779 |
self.update_profiler_logs(tinit) |
| 1780 |
|
| 1781 |
# Run plugin functions |
| 1782 |
await asyncio.gather( |
| 1783 |
*main_loop.get_runners( |
| 1784 |
self.main_loop_plugins, |
| 1785 |
main_loop.CoroTypes.Periodic, |
| 1786 |
self |
| 1787 |
) |
| 1788 |
) |
| 1789 |
# Sleep a bit for things to catch up. |
| 1790 |
# Quick sleep if there are items pending in process pool. |
| 1791 |
# (Should probably use quick sleep logic for other queues?) |
| 1792 |
elapsed = time() - tinit |
| 1793 |
quick_mode = self.proc_pool.is_not_done() |
| 1794 |
if (elapsed >= self.INTERVAL_MAIN_LOOP or |
| 1795 |
quick_mode and elapsed >= self.INTERVAL_MAIN_LOOP_QUICK): |
| 1796 |
# Main loop has taken quite a bit to get through |
| 1797 |
# Still yield control to other async tasks by sleep(0) |
| 1798 |
duration: float = 0 |
| 1799 |
elif quick_mode: |
| 1800 |
duration = self.INTERVAL_MAIN_LOOP_QUICK - elapsed |
| 1801 |
else: |
| 1802 |
duration = self.INTERVAL_MAIN_LOOP - elapsed |
| 1803 |
await asyncio.sleep(duration) |
| 1804 |
# Record latest main loop interval |
| 1805 |
self.main_loop_intervals.append(time() - tinit) |
| 1806 |
|
| 1807 |
# If applicable, set stop mode or shutdown on task failure: |
| 1808 |
await self.workflow_shutdown() |
| 1809 |
# END MAIN LOOP |
| 1810 |
|
| 1811 |
def _update_workflow_state(self): |
| 1812 |
"""Update workflow state in the data store and push out any deltas. |
| 1813 |
|
| 1814 |
A cut-down version of update_data_structure which only considers |
| 1815 |
workflow state changes e.g. status, status message, state totals, etc. |
| 1816 |
""" |
| 1817 |
# Publish any existing before potentially creating more |
| 1818 |
self._publish_deltas() |
| 1819 |
# update the workflow state in the data store |
| 1820 |
self.data_store_mgr.update_workflow_states() |
| 1821 |
self._publish_deltas() |
| 1822 |
|
| 1823 |
async def update_data_structure(self, reloaded: bool = False): |
| 1824 |
"""Update DB, UIS, Summary data elements""" |
| 1825 |
# Publish any existing before potentially creating more |
| 1826 |
self._publish_deltas() |
| 1827 |
# Collect/apply data store updates/deltas |
| 1828 |
self.data_store_mgr.update_data_structure() |
| 1829 |
self._publish_deltas() |
| 1830 |
# Database update |
| 1831 |
self.workflow_db_mgr.put_task_pool(self.pool) |
| 1832 |
|
| 1833 |
def _publish_deltas(self): |
| 1834 |
"""Publish pending deltas.""" |
| 1835 |
if self.data_store_mgr.publish_pending: |
| 1836 |
self.data_store_mgr.publish_pending = False |
| 1837 |
self.server.publish_queue.put( |
| 1838 |
self.data_store_mgr.publish_deltas) |
| 1839 |
# Non-async sleep - yield to other threads rather |
| 1840 |
# than event loop |
| 1841 |
sleep(0) |
| 1842 |
|
| 1843 |
def check_workflow_timers(self): |
| 1844 |
"""Check timers, and abort or run event handlers as configured.""" |
| 1845 |
for event, timer in self.timers.items(): |
| 1846 |
if not timer.timed_out(): |
| 1847 |
continue |
| 1848 |
self.run_event_handlers(event) |
| 1849 |
abort_conf = f"abort on {event}" |
| 1850 |
if self._get_events_conf(abort_conf): |
| 1851 |
# "cylc play" needs to exit with error status here. |
| 1852 |
raise SchedulerError(f'"{abort_conf}" is set') |
| 1853 |
if event == self.EVENT_RESTART_TIMEOUT: |
| 1854 |
# Unset wait flag to allow normal shutdown. |
| 1855 |
self.is_restart_timeout_wait = False |
| 1856 |
|
| 1857 |
def check_workflow_stalled(self) -> bool: |
| 1858 |
"""Check if workflow is stalled or not.""" |
| 1859 |
if self.is_stalled: # already reported |
| 1860 |
return True |
| 1861 |
if self.is_paused: # cannot be stalled it's not even running |
| 1862 |
return False |
| 1863 |
if self.pool.is_stalled(): |
| 1864 |
self.is_stalled = True |
| 1865 |
self.update_data_store() |
| 1866 |
LOG.critical("Workflow stalled") |
| 1867 |
self.run_event_handlers(self.EVENT_STALL, 'workflow stalled') |
| 1868 |
with suppress(KeyError): |
| 1869 |
# Start stall timeout timer |
| 1870 |
self.timers[self.EVENT_STALL_TIMEOUT].reset() |
| 1871 |
return self.is_stalled |
| 1872 |
|
| 1873 |
async def shutdown(self, reason: BaseException) -> None: |
| 1874 |
"""Gracefully shut down the scheduler.""" |
| 1875 |
# At the moment this method must be called from the main_loop. |
| 1876 |
# In the future it should shutdown the main_loop itself but |
| 1877 |
# we're not quite there yet. |
| 1878 |
|
| 1879 |
# cancel signal handlers |
| 1880 |
def _handle_signal(sig, frame): |
| 1881 |
LOG.warning( |
| 1882 |
f'Signal {signal.Signals(sig).name} received,' |
| 1883 |
' already shutting down' |
| 1884 |
) |
| 1885 |
|
| 1886 |
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): |
| 1887 |
signal.signal(sig, _handle_signal) |
| 1888 |
|
| 1889 |
try: |
| 1890 |
# action shutdown |
| 1891 |
await self._shutdown(reason) |
| 1892 |
except (asyncio.CancelledError, Exception) as exc: |
| 1893 |
# In case of exception in the shutdown method itself. |
| 1894 |
LOG.error("Error during shutdown") |
| 1895 |
# Suppress the reason for shutdown, which is logged separately |
| 1896 |
exc.__suppress_context__ = True |
| 1897 |
if isinstance(exc, CylcError): |
| 1898 |
LOG.error(f"{exc.__class__.__name__}: {exc}") |
| 1899 |
if cylc.flow.flags.verbosity > 1: |
| 1900 |
LOG.exception(exc) |
| 1901 |
else: |
| 1902 |
LOG.exception(exc) |
| 1903 |
# Re-raise exception to be caught higher up (sets the exit code) |
| 1904 |
raise exc from None |
| 1905 |
|
| 1906 |
async def _shutdown(self, reason: BaseException) -> None: |
| 1907 |
"""Shutdown the workflow.""" |
| 1908 |
self._log_shutdown_reason(reason) |
| 1909 |
|
| 1910 |
if hasattr(self, 'proc_pool'): |
| 1911 |
try: |
| 1912 |
self.proc_pool.close() |
| 1913 |
if self.proc_pool.is_not_done(): |
| 1914 |
self.proc_pool.terminate() |
| 1915 |
self.proc_pool.process() |
| 1916 |
except Exception as exc: |
| 1917 |
LOG.exception(exc) |
| 1918 |
|
| 1919 |
if hasattr(self, 'pool'): |
| 1920 |
try: |
| 1921 |
if not self.is_stalled: |
| 1922 |
# (else already logged) |
| 1923 |
# Log partially satisfied dependencies and incomplete tasks |
| 1924 |
self.pool.is_stalled() |
| 1925 |
self.pool.warn_stop_orphans() |
| 1926 |
self.workflow_db_mgr.put_task_event_timers( |
| 1927 |
self.task_events_mgr |
| 1928 |
) |
| 1929 |
self.workflow_db_mgr.put_task_pool(self.pool) |
| 1930 |
except Exception as exc: |
| 1931 |
LOG.exception(exc) |
| 1932 |
|
| 1933 |
if self.server: |
| 1934 |
await self.server.stop(reason) |
| 1935 |
|
| 1936 |
# Flush errors and info before removing workflow contact file |
| 1937 |
sys.stdout.flush() |
| 1938 |
sys.stderr.flush() |
| 1939 |
|
| 1940 |
if ( |
| 1941 |
self.workflow_db_mgr.pri_path |
| 1942 |
and Path(self.workflow_db_mgr.pri_path).exists() |
| 1943 |
): |
| 1944 |
# only attempt remote tidy if the workflow has been started |
| 1945 |
self.task_job_mgr.task_remote_mgr.remote_tidy() |
| 1946 |
|
| 1947 |
try: |
| 1948 |
# Remove ZMQ keys from scheduler |
| 1949 |
LOG.debug("Removing authentication keys from scheduler") |
| 1950 |
key_housekeeping(self.workflow, create=False) |
| 1951 |
except Exception as ex: |
| 1952 |
LOG.exception(ex) |
| 1953 |
# disconnect from workflow-db, stop db queue |
| 1954 |
try: |
| 1955 |
self.process_workflow_db_queue() |
| 1956 |
self.workflow_db_mgr.on_workflow_shutdown() |
| 1957 |
except Exception as exc: |
| 1958 |
LOG.exception(exc) |
| 1959 |
|
| 1960 |
# NOTE: Removing the contact file should happen last of all (apart |
| 1961 |
# from running event handlers), because the existence of the file is |
| 1962 |
# used to determine if the workflow is running |
| 1963 |
if self.contact_data: |
| 1964 |
fname = workflow_files.get_contact_file_path(self.workflow) |
| 1965 |
try: |
| 1966 |
os.unlink(fname) |
| 1967 |
except OSError as exc: |
| 1968 |
LOG.warning(f"failed to remove workflow contact file: {fname}") |
| 1969 |
LOG.exception(exc) |
| 1970 |
else: |
| 1971 |
# Useful to identify that this Scheduler has shut down |
| 1972 |
# properly (e.g. in tests): |
| 1973 |
self.contact_data = None |
| 1974 |
|
| 1975 |
# The getattr() calls and if tests below are used in case the |
| 1976 |
# workflow is not fully configured before the shutdown is called. |
| 1977 |
if getattr(self, "config", None) is not None: |
| 1978 |
# run shutdown handlers |
| 1979 |
if isinstance(reason, CylcError): |
| 1980 |
self.run_event_handlers(self.EVENT_SHUTDOWN, reason.args[0]) |
| 1981 |
else: |
| 1982 |
self.run_event_handlers(self.EVENT_ABORTED, str(reason)) |
| 1983 |
|
| 1984 |
def _log_shutdown_reason(self, reason: BaseException) -> None: |
| 1985 |
"""Appropriately log the reason for scheduler shutdown.""" |
| 1986 |
shutdown_msg = "Workflow shutting down" |
| 1987 |
with patch_log_level(LOG): |
| 1988 |
if isinstance(reason, SchedulerStop): |
| 1989 |
LOG.info(f'{shutdown_msg} - {reason.args[0]}') |
| 1990 |
# Unset the "paused" status of the workflow if not |
| 1991 |
# auto-restarting |
| 1992 |
if self.auto_restart_mode != AutoRestartMode.RESTART_NORMAL: |
| 1993 |
self.resume_workflow(quiet=True) |
| 1994 |
elif isinstance(reason, SchedulerError): |
| 1995 |
LOG.error(f"{shutdown_msg} - {reason}") |
| 1996 |
elif isinstance(reason, CylcError) or ( |
| 1997 |
isinstance(reason, ParsecError) and reason.schd_expected |
| 1998 |
): |
| 1999 |
LOG.error( |
| 2000 |
f"{shutdown_msg} - {type(reason).__name__}: {reason}" |
| 2001 |
) |
| 2002 |
if cylc.flow.flags.verbosity > 1: |
| 2003 |
# Print traceback |
| 2004 |
LOG.exception(reason) |
| 2005 |
else: |
| 2006 |
LOG.exception(reason) |
| 2007 |
if str(reason): |
| 2008 |
shutdown_msg += f" - {reason}" |
| 2009 |
LOG.critical(shutdown_msg) |
| 2010 |
|
| 2011 |
def set_stop_clock(self, unix_time): |
| 2012 |
"""Set stop clock time.""" |
| 2013 |
LOG.info( |
| 2014 |
"Setting stop clock time: %s (unix time: %s)", |
| 2015 |
time2str(unix_time), |
| 2016 |
unix_time) |
| 2017 |
self.stop_clock_time = unix_time |
| 2018 |
self.workflow_db_mgr.put_workflow_stop_clock_time(self.stop_clock_time) |
| 2019 |
self.update_data_store() |
| 2020 |
|
| 2021 |
def stop_clock_done(self): |
| 2022 |
"""Return True if wall clock stop time reached.""" |
| 2023 |
if self.stop_clock_time is None: |
| 2024 |
return |
| 2025 |
now = time() |
| 2026 |
if now > self.stop_clock_time: |
| 2027 |
LOG.info("Wall clock stop time reached: %s", time2str( |
| 2028 |
self.stop_clock_time)) |
| 2029 |
self.stop_clock_time = None |
| 2030 |
self.workflow_db_mgr.put_workflow_stop_clock_time(None) |
| 2031 |
self.update_data_store() |
| 2032 |
return True |
| 2033 |
LOG.debug("stop time=%d; current time=%d", self.stop_clock_time, now) |
| 2034 |
return False |
| 2035 |
|
| 2036 |
def check_auto_shutdown(self): |
| 2037 |
"""Check if we should shut down now.""" |
| 2038 |
if ( |
| 2039 |
self.is_paused or |
| 2040 |
self.is_restart_timeout_wait or |
| 2041 |
self.check_workflow_stalled() or |
| 2042 |
# if more tasks to run (if waiting and not |
| 2043 |
# runahead, then held, queued, or xtriggered). |
| 2044 |
any( |
| 2045 |
itask for itask in self.pool.get_tasks() |
| 2046 |
if itask.state( |
| 2047 |
TASK_STATUS_PREPARING, |
| 2048 |
TASK_STATUS_SUBMITTED, |
| 2049 |
TASK_STATUS_RUNNING, |
| 2050 |
) or ( |
| 2051 |
# This is because runahead limit gets truncated |
| 2052 |
# to stop_point if there is one, so tasks spawned |
| 2053 |
# beyond the stop_point must be runahead limited. |
| 2054 |
itask.state(TASK_STATUS_WAITING) |
| 2055 |
and not itask.state.is_runahead |
| 2056 |
) |
| 2057 |
) |
| 2058 |
): |
| 2059 |
return False |
| 2060 |
|
| 2061 |
# Can shut down. |
| 2062 |
if self.pool.stop_point: |
| 2063 |
# Forget early stop point in case of a restart. |
| 2064 |
self.workflow_db_mgr.put_workflow_stop_cycle_point(None) |
| 2065 |
|
| 2066 |
return True |
| 2067 |
|
| 2068 |
def pause_workflow(self, msg: Optional[str] = None) -> None: |
| 2069 |
"""Pause the workflow. |
| 2070 |
|
| 2071 |
Args: |
| 2072 |
msg: |
| 2073 |
A user-facing string explaining why the workflow was paused if |
| 2074 |
helpful. |
| 2075 |
|
| 2076 |
""" |
| 2077 |
if self.is_paused: |
| 2078 |
LOG.info("Workflow is already paused") |
| 2079 |
return |
| 2080 |
_msg = "Pausing the workflow" |
| 2081 |
if msg: |
| 2082 |
_msg += f': {msg}' |
| 2083 |
LOG.info(_msg) |
| 2084 |
self.is_paused = True |
| 2085 |
self.workflow_db_mgr.put_workflow_paused(True) |
| 2086 |
self.update_data_store() |
| 2087 |
|
| 2088 |
def resume_workflow(self, quiet: bool = False) -> None: |
| 2089 |
"""Resume the workflow. |
| 2090 |
|
| 2091 |
Args: |
| 2092 |
quiet: |
| 2093 |
Whether to log anything in the event the workflow is not |
| 2094 |
paused. |
| 2095 |
|
| 2096 |
""" |
| 2097 |
if self.reload_pending: |
| 2098 |
LOG.warning('Cannot resume - workflow is reloading') |
| 2099 |
return |
| 2100 |
if not self.is_paused: |
| 2101 |
if not quiet: |
| 2102 |
LOG.info("No need to resume - workflow is not paused") |
| 2103 |
return |
| 2104 |
if not quiet: |
| 2105 |
LOG.info("RESUMING the workflow now") |
| 2106 |
self.is_paused = False |
| 2107 |
self.workflow_db_mgr.put_workflow_paused(False) |
| 2108 |
self.update_data_store() |
| 2109 |
|
| 2110 |
def _update_profile_info(self, category, amount, amount_format="%s"): |
| 2111 |
"""Update the 1, 5, 15 minute dt averages for a given category.""" |
| 2112 |
now = time() |
| 2113 |
self._profile_amounts.setdefault(category, []) |
| 2114 |
amounts = self._profile_amounts[category] |
| 2115 |
amounts.append((now, amount)) |
| 2116 |
self._profile_update_times.setdefault(category, None) |
| 2117 |
last_update = self._profile_update_times[category] |
| 2118 |
if last_update is not None and now < last_update + 60: |
| 2119 |
return |
| 2120 |
self._profile_update_times[category] = now |
| 2121 |
averages = {1: [], 5: [], 15: []} |
| 2122 |
for then, amount in list(amounts): |
| 2123 |
age = (now - then) / 60.0 |
| 2124 |
if age > 15: |
| 2125 |
amounts.remove((then, amount)) |
| 2126 |
continue |
| 2127 |
for minute_num in averages: |
| 2128 |
if age <= minute_num: |
| 2129 |
averages[minute_num].append(amount) |
| 2130 |
output_text = "PROFILE: %s:" % category |
| 2131 |
for minute_num, minute_amounts in sorted(averages.items()): |
| 2132 |
averages[minute_num] = sum(minute_amounts) / len(minute_amounts) |
| 2133 |
output_text += (" %d: " + amount_format) % ( |
| 2134 |
minute_num, averages[minute_num]) |
| 2135 |
LOG.info(output_text) |
| 2136 |
|
| 2137 |
def _update_cpu_usage(self): |
| 2138 |
"""Obtain CPU usage statistics.""" |
| 2139 |
proc = Popen( # nosec |
| 2140 |
["ps", "-o%cpu= ", str(os.getpid())], |
| 2141 |
stdin=DEVNULL, |
| 2142 |
stdout=PIPE, |
| 2143 |
) |
| 2144 |
# * there is no untrusted input |
| 2145 |
try: |
| 2146 |
cpu_frac = float(proc.communicate()[0]) |
| 2147 |
except (TypeError, OSError, ValueError) as exc: |
| 2148 |
LOG.warning("Cannot get CPU % statistics: %s" % exc) |
| 2149 |
return |
| 2150 |
self._update_profile_info("CPU %", cpu_frac, amount_format="%.1f") |
| 2151 |
|
| 2152 |
def _get_events_conf(self, key, default=None): |
| 2153 |
"""Return a named [scheduler][[events]] configuration.""" |
| 2154 |
return self.workflow_event_handler.get_events_conf( |
| 2155 |
self.config, key, default) |
| 2156 |
|
| 2157 |
def _check_startup_opts(self) -> None: |
| 2158 |
"""Abort if "cylc play" options are not consistent with type of start. |
| 2159 |
|
| 2160 |
* Start from cycle point or task is not valid for a restart. |
| 2161 |
* Reloading of cycle points is not valid for a new run. |
| 2162 |
""" |
| 2163 |
for opt in ('icp', 'startcp', 'starttask'): |
| 2164 |
value = getattr(self.options, opt, None) |
| 2165 |
if self.is_restart: |
| 2166 |
if value is not None: |
| 2167 |
raise InputError( |
| 2168 |
f"option --{opt} is not valid for restart" |
| 2169 |
) |
| 2170 |
elif value == 'reload': |
| 2171 |
raise InputError( |
| 2172 |
f"option --{opt}=reload is not valid " |
| 2173 |
"(only --fcp and --stopcp can be 'reload')" |
| 2174 |
) |
| 2175 |
if not self.is_restart: |
| 2176 |
for opt in ('fcp', 'stopcp'): |
| 2177 |
if getattr(self.options, opt, None) == 'reload': |
| 2178 |
raise InputError( |
| 2179 |
f"option --{opt}=reload is only valid for restart" |
| 2180 |
) |
| 2181 |
|
| 2182 |
def get_run_mode(self) -> RunMode: |
| 2183 |
return RunMode.get(self.options) |
| 2184 |
|
| 2185 |
async def handle_exception(self, exc: BaseException) -> NoReturn: |
| 2186 |
"""Gracefully shut down the scheduler given a caught exception. |
| 2187 |
|
| 2188 |
Re-raises the exception to be caught higher up (sets the exit code). |
| 2189 |
|
| 2190 |
Args: |
| 2191 |
exc: The caught exception to be logged during the shutdown. |
| 2192 |
""" |
| 2193 |
await self.shutdown(exc) |
| 2194 |
raise exc from None |
| 2195 |
|
| 2196 |
def update_data_store(self): |
| 2197 |
"""Sets the update flag on the data store. |
| 2198 |
|
| 2199 |
Call this method whenever the Scheduler's state has changed in a way |
| 2200 |
that requires a data store update. |
| 2201 |
See cylc.flow.workflow_status.get_workflow_status_msg() for a |
| 2202 |
(non-exhaustive?) list of properties that if changed will require |
| 2203 |
this update. |
| 2204 |
|
| 2205 |
This call should often be associated with a database update. |
| 2206 |
|
| 2207 |
Note that must updates e.g. task / job states are handled elsewhere, |
| 2208 |
this applies to changes made directly to scheduler attributes etc. |
| 2209 |
""" |
| 2210 |
self.data_store_mgr.updates_pending = True |