Debian Codegraph @

cylc/flow/scheduler_cli.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Common logic for "cylc play" CLI."""
17
18 import asyncio
19 from copy import deepcopy
20 from functools import lru_cache
21 from itertools import zip_longest
22 import logging
23 from pathlib import Path
24 from shlex import quote
25 import sys
26 from typing import (
27 TYPE_CHECKING,
28 Tuple,
29 )
30
31 from ansimarkup import parse as cparse
32 from packaging.version import Version
33
34 from cylc.flow import (
35 LOG,
36 __version__,
37 )
38 from cylc.flow.exceptions import (
39 CylcError,
40 ServiceFileError,
41 WorkflowStopped,
42 )
43 import cylc.flow.flags
44 from cylc.flow.host_select import select_workflow_host
45 from cylc.flow.hostuserutil import is_remote_host
46 from cylc.flow.id import upgrade_legacy_ids
47 from cylc.flow.id_cli import parse_ids_async
48 from cylc.flow.loggingutil import (
49 RotatingLogFileHandler,
50 close_log,
51 )
52 from cylc.flow.network.client import WorkflowRuntimeClient
53 from cylc.flow.network.log_stream_handler import ProtobufStreamHandler
54 from cylc.flow.option_parsers import (
55 ICP_OPTION,
56 SHORTLINK_TO_ICP_DOCS,
57 WORKFLOW_ID_ARG_DOC,
58 CylcOptionParser as COP,
59 Options,
60 OptionSettings,
61 )
62 from cylc.flow.pathutil import get_workflow_run_scheduler_log_path
63 from cylc.flow.remote import cylc_server_cmd
64 from cylc.flow.run_modes import WORKFLOW_RUN_MODES
65 from cylc.flow.scheduler import (
66 Scheduler,
67 SchedulerError,
68 )
69 from cylc.flow.scripts.common import cylc_header
70 from cylc.flow.scripts.ping import run as cylc_ping
71 from cylc.flow.terminal import (
72 cli_function,
73 is_terminal,
74 prompt,
75 )
76 from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
77 from cylc.flow.workflow_files import (
78 SUITERC_DEPR_MSG,
79 get_workflow_srv_dir,
80 )
81
82
83 if TYPE_CHECKING:
84 from optparse import Values
85
86
87 PLAY_DOC = r"""cylc play [OPTIONS] ARGS
88
89 Start, resume, or restart a workflow.
90
91 The scheduler will run as a daemon unless you specify --no-detach.
92
93 To avoid overwriting existing run directories, workflows that already ran can
94 only be restarted from prior state. To start again, "cylc install" a new copy
95 or "cylc clean" the existing run directory.
96
97 By default, new runs begin at the start of the graph (at the "initial cycle
98 point") and continue to the end of the graph (the "final cycle point", which
99 can be overriden with the --final-cycle-point command option).
100
101 However you can begin a run part way into the graph (with --start-cycle-point
102 or --start-task) and finish before the end of the graph (by configuring
103 "stop after cycle point" or with the --stop-cycle-point command option).
104
105 Note if you override a configured stop or final cycle point with these command
106 options, the new values will be stored in the DB and persist over restarts. To
107 revert to configured values on restart use (e.g.) --final-cycle-point=reload.
108
109 For convenience, any dependence on tasks prior to the start cycle point (or to
110 the cycle point of the earliest task specified by --start-task) will be taken
111 as satisfied.
112
113 Examples:
114 # Start (at the initial cycle point), restart, or resume workflow WORKFLOW
115 $ cylc play WORKFLOW
116
117 # Start a new run from a cycle point after the initial cycle point
118 # (integer cycling)
119 $ cylc play --start-cycle-point=3 WORKFLOW
120 # (datetime cycling):
121 $ cylc play --start-cycle-point=20250101T0000Z WORKFLOW
122
123 # Start a new run from specified tasks in the graph
124 $ cylc play --start-task=3/foo WORKFLOW
125 $ cylc play -t 3/foo -t 3/bar WORKFLOW
126
127 # Start, restart or resume the second installed run of the workflow
128 # "dogs/fido"
129 $ cylc play dogs/fido/run2
130
131 At restart, tasks recorded as submitted or running are polled to determine what
132 happened to them while the workflow was down.
133 """
134
135
136 RESUME_MUTATION = '''
137 mutation (
138 $wFlows: [WorkflowID]!
139 ) {
140 resume (
141 workflows: $wFlows
142 ) {
143 result
144 }
145 }
146 '''
147
148 PLAY_ICP_OPTION = deepcopy(ICP_OPTION)
149 PLAY_ICP_OPTION.sources = {'play'}
150
151 RUN_MODE = OptionSettings(
152 ["-m", "--mode"],
153 help=(
154 f"Run mode: {sorted(WORKFLOW_RUN_MODES)} (default live)."
155 " Live mode executes the tasks as defined in the runtime"
156 " section."
157 " Simulation and dummy modes ignore task 'script'"
158 " items and related job settings. They are"
159 " designed for testing."
160 ),
161 metavar="STRING", action='store', dest="run_mode",
162 choices=list(WORKFLOW_RUN_MODES),
163 )
164
165 PLAY_RUN_MODE = deepcopy(RUN_MODE)
166 PLAY_RUN_MODE.sources = {'play'}
167
168 PLAY_OPTIONS = [
169 OptionSettings(
170 ["-N", "--no-detach", "--non-daemon"],
171 help="Do not daemonize the scheduler (infers --format=plain)",
172 action='store_true', dest="no_detach", sources={'play'}),
173 OptionSettings(
174 ["--profile"],
175 help="Output profiling (performance) information",
176 action='store_true',
177 default=False,
178 dest="profile_mode",
179 sources={'play'},
180 ),
181 OptionSettings(
182 ["--start-cycle-point", "--startcp"],
183 help=(
184 "Set the start cycle point, which may be after "
185 "the initial cycle point. "
186 "If the specified start point is not in the sequence, the next "
187 "on-sequence point will be used.\n"
188 "Can be an absolute point or an offset relative to the "
189 "current time, like the --initial-cycle-point option - see "
190 f"{SHORTLINK_TO_ICP_DOCS} (Cylc documentation link)."
191 ),
192 metavar="CYCLE_POINT",
193 action='store',
194 dest="startcp",
195 sources={'play'},
196 ),
197 OptionSettings(
198 ["--final-cycle-point", "--fcp"],
199 help=(
200 "Set the final cycle point. This command line option overrides"
201 " the workflow config option '[scheduling]final cycle point'."
202 " The new value will persist over restarts unless you use"
203 " --fcp=reload to revert to the configured value."
204 ),
205 metavar="CYCLE_POINT or 'reload'",
206 action='store',
207 dest="fcp",
208 sources={'play'},
209 ),
210 OptionSettings(
211 ["--stop-cycle-point", "--stopcp"],
212 help=(
213 "Set the stop cycle point. Shut down after all"
214 " have PASSED this cycle point. (Not to be confused"
215 " the final cycle point.) This command line option overrides"
216 " the workflow config option"
217 " '[scheduling]stop after cycle point'."
218 " The new value will persist over restarts unless you use"
219 " --stopcp=reload to revert to the configured value."
220 ),
221 metavar="CYCLE_POINT or 'reload'",
222 action='store',
223 dest="stopcp",
224 sources={'play'},
225 ),
226 OptionSettings(
227 ["--start-task", "--starttask", "-t"],
228 help=(
229 "Start from this task instance instead of the beginning of the"
230 " graph. Dependence on other tasks is ignored but clock and"
231 " xtriggers are respected. Reuse the option for multiple start"
232 " tasks. Any dependence on cycle points prior to the earliest"
233 " start task will be ignored throughout the graph. Check that"
234 " start tasks flow into the full downstream graph, if needed."
235 ),
236 metavar="TASK_ID",
237 action='append',
238 dest="starttask",
239 sources={'play'},
240 ),
241 OptionSettings(
242 ["--pause"],
243 help="Pause the workflow immediately on start up.",
244 action='store_true',
245 default=False,
246 dest="paused_start",
247 sources={'play'},
248 ),
249 OptionSettings(
250 ["--hold-after", "--hold-cycle-point", "--holdcp"],
251 help="Hold all tasks after this cycle point.",
252 metavar="CYCLE_POINT",
253 action='store',
254 dest="holdcp",
255 sources={'play'},
256 ),
257 OptionSettings(
258 ["--reference-log"],
259 help="Generate a reference log for use in reference ",
260 action='store_true',
261 default=False,
262 dest="genref",
263 sources={'play'},
264 ),
265 OptionSettings(
266 ["--reference-test"],
267 help="Do a test run against a previously generated reference.",
268 action='store_true',
269 default=False,
270 dest="reftest",
271 sources={'play'},
272 ),
273 OptionSettings(
274 ["--host"],
275 help=(
276 "Specify the host on which to start-up the workflow."
277 " If not specified, a host will be selected using"
278 " the '[scheduler]run hosts' global config."),
279 metavar="HOST",
280 action='store',
281 dest="host",
282 sources={'play'},
283 ),
284 OptionSettings(
285 ["--format"],
286 help="The format of the output: 'plain'=human readable, 'json'",
287 choices=('plain', 'json'),
288 default="plain",
289 dest='format',
290 sources={'play'},
291 ),
292 OptionSettings(
293 ["--main-loop"],
294 help=(
295 "Specify an additional plugin to run in the main"
296 " These are used in combination with those specified"
297 " [scheduler][main loop]plugins. Can be used multiple times."),
298 metavar="PLUGIN_NAME",
299 action='append',
300 dest="main_loop",
301 sources={'play'},
302 ),
303 OptionSettings(
304 ["--abort-if-any-task-fails"],
305 help="If set workflow will abort with status 1 if any task fails.",
306 action='store_true',
307 default=False,
308 dest="abort_if_any_task_fails",
309 sources={'play'},
310 ),
311 PLAY_ICP_OPTION,
312 PLAY_RUN_MODE,
313 OptionSettings(
314 ['--downgrade'],
315 help=(
316 'Allow the workflow to be restarted with an'
317 ' older version of Cylc, NOT RECOMMENDED.'
318 ' By default Cylc prevents you from restarting'
319 ' a workflow with an older version of Cylc than'
320 ' it was previously run with. Use this flag'
321 ' to disable this check.'
322 ),
323 action='store_true',
324 default=False,
325 sources={'play'}
326 ),
327 OptionSettings(
328 ['--upgrade'],
329 help=(
330 'Allow the workflow to be restarted with'
331 ' a newer version of Cylc.'
332 ),
333 action='store_true',
334 default=False,
335 sources={'play'}
336 ),
337 ]
338
339
340 @lru_cache()
341 def get_option_parser(add_std_opts: bool = False) -> COP:
342 """Parse CLI for "cylc play"."""
343 parser = COP(
344 PLAY_DOC,
345 jset=True,
346 comms=True,
347 argdoc=[WORKFLOW_ID_ARG_DOC]
348 )
349
350 for option in PLAY_OPTIONS:
351 parser.add_option(*option.args, **option.kwargs)
352
353 if add_std_opts:
354 # This is for the API wrapper for integration tests. Otherwise (CLI
355 # use) "standard options" are added later in options.parse_args().
356 # They should really be added in options.__init__() but that requires a
357 # bit of refactoring because option clashes are handled bass-ackwards
358 # ("overrides" are added before standard options).
359 parser.add_std_options()
360
361 return parser
362
363
364 # options we cannot simply extract from the parser
365 DEFAULT_OPTS = {
366 'debug': False,
367 'verbose': False,
368 'templatevars': None,
369 'templatevars_file': None
370 }
371
372
373 RunOptions = Options(get_option_parser(add_std_opts=True), DEFAULT_OPTS)
374
375
376 def _open_logs(
377 schd: Scheduler,
378 id_: str,
379 no_detach: bool,
380 restart_num: int,
381 ) -> None:
382 """Open Cylc log handlers for a new scheduler instance."""
383 if not no_detach:
384 while LOG.handlers:
385 LOG.handlers[0].close()
386 LOG.removeHandler(LOG.handlers[0])
387 log_path = get_workflow_run_scheduler_log_path(id_)
388 LOG.addHandler(
389 RotatingLogFileHandler(
390 log_path,
391 no_detach,
392 restart_num=restart_num
393 )
394 )
395 handler = ProtobufStreamHandler(
396 schd,
397 level=logging.WARNING,
398 )
399 handler.setFormatter(logging.Formatter())
400 LOG.addHandler(handler)
401
402
403 async def _scheduler_cli_1(
404 options: 'Values',
405 workflow_id_raw: str,
406 parse_workflow_id: bool = True
407 ) -> Tuple[Scheduler, str]:
408 """Run the workflow (part 1 - async).
409
410 This function should contain all of the command line facing
411 functionality of the Scheduler, exit codes, logging, etc.
412
413 The Scheduler itself should be a Python object you can import and
414 run in a regular Python session so cannot contain this kind of
415 functionality.
416
417 """
418 if options.starttask:
419 options.starttask = upgrade_legacy_ids(
420 *options.starttask,
421 relative=True,
422 )
423
424 # Parse workflow name but delay Cylc 7 suite.rc deprecation warning
425 # until after the start-up splash is printed.
426 # TODO: singleton
427 if parse_workflow_id:
428 (workflow_id,), _ = await parse_ids_async(
429 workflow_id_raw,
430 constraint='workflows',
431 max_workflows=1,
432 # warn_depr=False, # TODO
433 )
434 else:
435 workflow_id = workflow_id_raw
436
437 # resume the workflow if it is already running
438 await _resume(workflow_id, options)
439
440 # check the workflow can be safely restarted with this version of Cylc
441 db_file = Path(get_workflow_srv_dir(workflow_id), 'db')
442 if not _version_check(db_file, options):
443 sys.exit(1)
444
445 # upgrade the workflow DB (after user has confirmed upgrade)
446 _upgrade_database(db_file)
447
448 # print the start message
449 _print_startup_message(options)
450
451 # re-execute on another host if required
452 _distribute(workflow_id_raw, workflow_id, options)
453
454 # setup the scheduler
455 # NOTE: asyncio.run opens an event loop, runs your coro,
456 # then shutdown async generators and closes the event loop
457 scheduler = Scheduler(workflow_id, options)
458 await _setup(scheduler)
459
460 return scheduler, workflow_id
461
462
463 def _scheduler_cli_2(
464 options: 'Values',
465 scheduler: Scheduler,
466 ) -> None:
467 """Run the workflow (part 2 - sync)."""
468 # daemonize if requested
469 # NOTE: asyncio event loops cannot persist across daemonization
470 # ensure you have tidied up all threads etc before daemonizing
471 if not options.no_detach:
472 from cylc.flow.daemonize import daemonize
473 daemonize(scheduler)
474
475
476 async def _scheduler_cli_3(
477 options: 'Values',
478 workflow_id: str,
479 scheduler: Scheduler,
480 ) -> None:
481 """Run the workflow (part 3 - async)."""
482 # setup loggers
483 _open_logs(
484 scheduler,
485 workflow_id,
486 options.no_detach,
487 restart_num=scheduler.get_restart_num()
488 )
489
490 # run the workflow
491 ret = await _run(scheduler)
492
493 # exit
494 # NOTE: we must clean up all asyncio / threading stuff before exiting
495 # NOTE: any threads which include sleep statements could cause
496 # sys.exit to hang if not shutdown properly
497 LOG.info("DONE")
498 close_log(LOG)
499 sys.exit(ret)
500
501
502 async def _resume(workflow_id, options):
503 """Resume the workflow if it is already running."""
504 try:
505 pclient = WorkflowRuntimeClient(
506 workflow_id,
507 timeout=options.comms_timeout,
508 )
509 except WorkflowStopped:
510 # Not running - don't resume.
511 return
512
513 # Is it running? If yes, send resume command.
514 try:
515 await cylc_ping(options, workflow_id, pclient)
516 except WorkflowStopped:
517 # Not running, restart instead of resume.
518 # (Orphaned contact file will be removed by cylc_ping client logic).
519 return
520 except CylcError as exc:
521 # PID check failed - abort.
522 LOG.error(exc)
523 LOG.critical('Cannot tell if the workflow is running')
524 sys.exit(1)
525 else:
526 # It's running but the user has specified --pause:
527 if options.paused_start:
528 LOG.warning('Workflow already running: Remove --pause to resume.')
529 sys.exit(0)
530
531 # It's running: resume it and exit.
532 print("Resuming already-running workflow")
533 mutation_kwargs = {
534 'request_string': RESUME_MUTATION,
535 'variables': {
536 'wFlows': [workflow_id]
537 }
538 }
539 await pclient.async_request('graphql', mutation_kwargs)
540 sys.exit(0)
541
542
543 def _version_check(
544 db_file: Path,
545 options: 'Values',
546 ) -> bool:
547 """Check the workflow can be safely restarted with this version of Cylc."""
548 if not db_file.is_file():
549 # not a restart
550 return True
551 this_version = Version(__version__)
552 last_run_version = WorkflowDatabaseManager.check_db_compatibility(db_file)
553
554 for itt, (this, that) in enumerate(zip_longest(
555 this_version.release,
556 last_run_version.release,
557 fillvalue=-1,
558 )):
559 if this < that:
560 # restart would REDUCE the Cylc version
561 if options.downgrade:
562 # permission to downgrade given in CLI flags
563 LOG.warning(
564 'Restarting with an older version of Cylc'
565 f' ({last_run_version} -> {__version__})'
566 )
567 return True
568 print(cparse(
569 '<red>'
570 'It is not advisible to restart a workflow with an older'
571 ' version of Cylc than it was previously run with.'
572 '</red>'
573
574 '\n* This workflow was previously run with'
575 f' <green>{last_run_version}</green>.'
576 f'\n* This version of Cylc is <red>{__version__}</red>.'
577
578 '\nUse --downgrade to disable this check (NOT RECOMMENDED!) or'
579 ' use a more recent version e.g:'
580 '<blue>'
581 f'\n$ CYLC_VERSION={last_run_version}'
582 f' {" ".join(['cylc'] + sys.argv[1:])}'
583 '</blue>'
584 ), file=sys.stderr)
585 return False
586 elif itt < 2 and this > that:
587 # restart would INCREASE the Cylc version in a big way
588 if options.upgrade:
589 # permission to upgrade given in CLI flags
590 LOG.warning(
591 'Restarting with a newer version of Cylc'
592 f' ({last_run_version} -> {__version__})'
593 )
594 return True
595 print(cparse(
596 'This workflow was previously run with'
597 f' <yellow>{last_run_version}</yellow>.'
598 f'\nThis version of Cylc is <green>{__version__}</green>.'
599 ))
600 if is_terminal():
601 # we are in interactive mode, ask the user if this is ok
602 options.upgrade = prompt(
603 cparse(
604 'Are you sure you want to upgrade from'
605 f' <yellow>{last_run_version}</yellow>'
606 f' to <green>{__version__}</green>?'
607 ),
608 {'y': True, 'n': False},
609 process=str.lower,
610 )
611 return options.upgrade
612 # we are in non-interactive mode, abort abort abort
613 print('Use "--upgrade" to upgrade the workflow.', file=sys.stderr)
614 return False
615 elif itt > 2 and this > that:
616 # restart would INCREASE the Cylc version in a little way
617 return True
618 return True
619
620
621 def _upgrade_database(db_file: Path) -> None:
622 """Upgrade the workflow database if needed.
623
624 Note:
625 Do this after the user has confirmed that they want to upgrade!
626
627 """
628 if db_file.is_file():
629 WorkflowDatabaseManager.upgrade(db_file)
630
631
632 def _print_startup_message(options):
633 """Print the Cylc header including the CLI logo to the user's terminal."""
634 if (
635 cylc.flow.flags.verbosity > -1
636 and (options.no_detach or options.format == 'plain')
637 # don't print the startup message on reinvocation (note
638 # --host=localhost is the best indication we have that reinvokation has
639 # happened)
640 and options.host != 'localhost'
641 ):
642 print(
643 cparse(
644 cylc_header()
645 )
646 )
647
648 if cylc.flow.flags.cylc7_back_compat:
649 LOG.warning(SUITERC_DEPR_MSG)
650
651
652 def _distribute(
653 workflow_id_raw: str, workflow_id: str, options: 'Values'
654 ) -> None:
655 """Re-invoke this command on a different host if requested.
656
657 Args:
658 workflow_id_raw:
659 The workflow ID as it appears in the CLI arguments.
660 workflow_id:
661 The workflow ID after it has gone through the CLI.
662 This may be different (i.e. the run name may have been inferred).
663 options:
664 The CLI options.
665
666 """
667 # Check whether a run host is explicitly specified, else select one.
668 host = options.host or select_workflow_host()[0]
669 if is_remote_host(host):
670 # Protect command args from second shell interpretation
671 cmd = list(map(quote, sys.argv[1:]))
672
673 # Ensure the whole workflow ID is used
674 if workflow_id_raw != workflow_id:
675 # The CLI can infer run names but when we re-invoke the command
676 # we would prefer it to use the full workflow ID to better
677 # support monitoring systems.
678 for ind, item in enumerate(cmd):
679 if item == workflow_id_raw:
680 cmd[ind] = workflow_id
681
682 # Prevent recursive host selection
683 cmd.append("--host=localhost")
684
685 # Ensure interactive upgrade carries over:
686 if options.upgrade and '--upgrade' not in cmd:
687 cmd.append('--upgrade')
688
689 # Preserve CLI colour
690 if is_terminal() and options.color != 'never':
691 # the detached process doesn't pass the is_terminal test
692 # so we have to explicitly tell Cylc to use color
693 cmd.append('--color=always')
694 else:
695 # otherwise set --color=never to make testing easier
696 cmd.append('--color=never')
697
698 # Re-invoke the command
699 # NOTE: has the potential to raise NoHostsError, however, this will
700 # most likely have been raised during host-selection
701 sys.exit(
702 cylc_server_cmd(cmd, host=host)
703 )
704
705
706 async def _setup(scheduler: Scheduler) -> None:
707 """Initialise the scheduler."""
708 try:
709 await scheduler.install()
710 except ServiceFileError as exc:
711 sys.exit(str(exc))
712
713
714 async def _run(scheduler: Scheduler) -> int:
715 """Run the workflow and handle exceptions."""
716 # run cylc run
717 ret = 0
718 try:
719 await scheduler.run()
720
721 # stop cylc stop
722 except SchedulerError:
723 ret = 1
724 except Exception:
725 ret = 3
726
727 # kthxbye
728 return ret
729
730
731 @cli_function(get_option_parser)
732 def play(parser: COP, options: 'Values', id_: str):
733 cylc_play(options, id_)
734
735
736 def cylc_play(options: 'Values', id_: str, parse_workflow_id=True) -> None:
737 """Implement cylc play.
738
739 Raises:
740 CylcError:
741 If this function is called whilst an asyncio event loop is running.
742
743 Because the scheduler process can be daemonised, this must not be
744 called whilst an asyncio event loop is active as memory associated
745 with this event loop will also exist in the new fork leading to
746 potentially strange problems.
747
748 See https://github.com/cylc/cylc-flow/issues/6291
749
750 """
751 try:
752 # try opening an event loop to make sure there isn't one already open
753 asyncio.get_running_loop()
754 except RuntimeError:
755 # start/restart/resume the workflow
756 scheduler, workflow_id = asyncio.run(
757 _scheduler_cli_1(options, id_, parse_workflow_id=parse_workflow_id)
758 )
759 _scheduler_cli_2(options, scheduler)
760 asyncio.run(_scheduler_cli_3(options, workflow_id, scheduler))
761 else:
762 # if this line every gets hit then there is a bug within Cylc
763 raise CylcError(
764 'cylc_play called whilst asyncio event loop is running'
765 ) from None