Debian Codegraph @

cylc/flow/scripts/cylc.py

raw
1 #!/usr/bin/env python3
2 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
3 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 """cylc main entry point"""
18
19 import os
20 import sys
21
22
23 def pythonpath_manip():
24 """Stop PYTHONPATH contaminating the Cylc Environment
25
26 * Remove PYTHONPATH items from sys.path to prevent PYTHONPATH
27 contaminating the Cylc Environment.
28 * Add items from CYLC_PYTHONPATH to sys.path.
29
30 See Also:
31 https://github.com/cylc/cylc-flow/issues/5124
32 """
33 if 'CYLC_PYTHONPATH' in os.environ:
34 paths = [
35 os.path.abspath(item)
36 for item in os.environ['CYLC_PYTHONPATH'].split(os.pathsep)
37 ]
38 paths.extend(sys.path)
39 sys.path = paths
40 if 'PYTHONPATH' in os.environ:
41 for item in os.environ['PYTHONPATH'].split(os.pathsep):
42 abspath = os.path.abspath(item)
43 if abspath in sys.path:
44 sys.path.remove(abspath)
45
46
47 pythonpath_manip()
48
49 import argparse
50 from contextlib import contextmanager
51 from importlib.metadata import (
52 entry_points,
53 files,
54 )
55 from typing import (
56 Iterator,
57 Optional,
58 Tuple,
59 )
60
61 from ansimarkup import parse as cparse
62
63 from cylc.flow import (
64 __version__,
65 iter_entry_points,
66 )
67 from cylc.flow.option_parsers import (
68 format_help_headings,
69 format_shell_examples,
70 )
71 from cylc.flow.scripts.common import cylc_header
72
73
74 def get_version(long=False):
75 """Return version string, and (if long is True) install location.
76
77 The install location returned is the top directory of the virtual
78 environment, obtained from the Python executable path. (cylc-flow file
79 locations are buried deep in the library and don't always give the right
80 result, e.g. if installed with `pip install -e .`).
81 """
82 from pathlib import Path
83 version = f"{__version__}"
84 if long:
85 version += f" ({Path(sys.argv[0])})"
86 return version
87
88
89 USAGE = f"""{cylc_header()}
90 Cylc ("silk") efficiently manages distributed cycling workflows.
91 Cylc is Open Source software (GPL-3.0): see "cylc help license".
92
93 Version:
94 $ cylc version --long
95 {get_version(True)}
96
97 Quick Start:
98 $ cylc install <path> # install a workflow
99 $ cylc play <workflow_id> # run or resume a workflow
100 $ cylc stop <workflow_id> # stop a workflow
101 $ cylc clean <workflow_id> # delete an installed workflow
102 $ cylc gui # start the in-browser web UI
103 $ cylc tui <workflow_id> # start the in-terminal UI
104
105 $ cylc help all # see all cylc commands
106 $ cylc <command> --help # specific command help
107
108 Cylc IDs:
109 Workflows and tasks are identified by IDs of the form:
110 workflow//cycle/task
111
112 You can split an ID at the // so following two IDs are equivalent:
113 workflow//cycle1 workflow//cycle2
114 workflow// //cycle1 //cycle2
115
116 IDs can be written as globs:
117 *// # All workflows
118 workflow//* # All cycle points in "workflow"
119 workflow//cycle/* # All tasks in cycle point "cycle" of "workflow"
120
121 $ cylc help id # More information on IDs
122
123 Cylc commands can be abbreviated:
124 $ cylc trigger workflow//cycle/task # trigger task in workflow
125 $ cylc trig workflow//cycle/task # trigger task in workflow
126 $ cylc t # error: trigger or tui?
127 """
128
129 ID_HELP = '''
130 Workflow IDs:
131 Every Installed Cylc workflow has an ID.
132
133 For example if we install a workflow like so:
134 $ cylc install --workflow-name=foo
135
136 We will end up with a workflow with the ID "foo/run1".
137
138 This ID can be used to interact with the workflow:
139 $ cylc play foo/run1
140 $ cylc pause foo/run1
141 $ cylc stop foo/run1
142
143 If you omit run number ("run1", "run2", ...) Cylc will infer latest run.
144 $ cylc play foo
145 $ cylc pause foo
146 $ cylc stop foo
147
148 Workflows can be installed hierarchically:
149 $ cylc install --workflow-name=foo/bar/baz
150
151 # play the workflow with the ID "foo/bar/baz"
152 $ cylc play foo/bar/baz
153
154 The full format of a workflow ID is:
155 ~user/workflow-id
156
157 You can omit the user name when working on your own workflows.
158
159 Cycle / Family / Task / Job IDs:
160 Just as workflows have IDs, so do objects within workflows:
161 cycle/task_or_family/job
162
163 Examples:
164 1 # The cycle point "1"
165 1/a # The task "a" in cycle point "1"
166 1/a/1 # The first job of the task "a" in the cycle point "1".
167
168 Full ID
169 Join workflow and cycle/task/job IDs with //: workflow//cycle/task/job
170
171 Examples:
172 w// # The workflow "w"
173 w//1 # The cycle "1" in the workflow "w"
174 w//1/a # The task "a" in the cycle "1" in the workflow "w"
175 w//1/a/1 # The first job of w//1/a/1
176 ~alice/test # The workflow "test" installed under the user
177 # account "alice"
178
179 Patterns
180 Patterns can be used in Cylc IDs:
181 * # Matches everything.
182 ? # Matches any single character.
183 [seq] # Matches any character in "seq".
184 [!seq] # Matches any character not in "seq".
185
186 Examples:
187 * # All workflows
188 test* # All workflows starting "test".
189 test/* # All workflows starting "test/".
190 workflow//* # All active cycles in workflow
191 workflow//cycle/* # All tasks in workflow//cycle
192 workflow//cycle/task/* # All jobs in workflow//cycle/job
193
194 Warning:
195 Quote IDs on the command line to protect them from shell expansion.
196
197 Selectors
198 Selectors allow you to filter for specific states.
199
200 Selectors are prefixed by a colon (:).
201
202 Examples:
203 *:running # All running workflows
204 workflow//*:running # All running tasks in workflow
205 workflow//cycle/*:running # All running tasks in workflow//cycle
206 workflow//cycle/task/*:running # All running jobs in
207 # workflow//cycle/task
208
209 When selectors are applied to tasks, they will only match active tasks.
210 I.e, "workflow//*:failed" will only select active failed tasks, not all
211 historical failed tasks going back to the start of the workflow.
212 '''
213
214
215 # because this command is not served from behind cli_function like the
216 # other cylc commands we have to manually patch in colour support
217 USAGE = cparse(format_help_headings(format_shell_examples(USAGE)))
218
219 # all sub-commands
220 # {name: entry_point}
221 COMMANDS: dict = {
222 entry_point.name: entry_point
223 for entry_point in iter_entry_points('cylc.command')
224 }
225
226
227 # aliases for sub-commands
228 # {alias_name: command_name}
229 ALIASES = {
230 'bcast': 'broadcast',
231 'compare': 'diff',
232 'cyclepoint': 'cycle-point',
233 'cycletime': 'cycle-point',
234 'datetime': 'cycle-point',
235 'external-trigger': 'ext-trigger',
236 'get-contact': 'get-workflow-contact',
237 'get-cylc-version': 'get-workflow-version',
238 'log': 'cat-log',
239 'ls': 'list',
240 'shutdown': 'stop',
241 'task-message': 'message',
242 'unhold': 'release',
243 'validate-install-play': 'vip',
244 'validate-reinstall': 'vr',
245 }
246
247
248 # aliases for sub-commands which no longer exist
249 # {alias_name: message_to_user}
250 # fmt: off
251 DEAD_ENDS = {
252 'check-software':
253 'use standard tools to inspect the environment'
254 ' e.g. https://pypi.org/project/pipdeptree/',
255 'checkpoint':
256 'DB checkpoints have been removed. You can now "rewind" a'
257 ' workflow by triggering the flow anywhere in the graph.',
258 'conditions':
259 'cylc conditions has been replaced by cylc help license',
260 'documentation':
261 'Cylc documentation is now at http://cylc.org',
262 'edit':
263 'Command removed, please edit the workflow in source directory',
264 'get-directory':
265 'cylc get-directory has been removed.',
266 'get-config':
267 'cylc get-config has been replaced by cylc config',
268 'get-site-config':
269 'cylc get-site-config has been replaced by cylc config',
270 'get-suite-config':
271 'cylc get-suite-config has been replaced by cylc config',
272 'get-global-config':
273 'cylc get-global-config has been replaced by cylc config',
274 'graph-diff':
275 'cylc graph-diff has been removed,'
276 ' use cylc graph <flow1> --diff <flow2>',
277 'gscan':
278 'cylc gscan has been removed, use the web UI',
279 'insert':
280 'Insertion is no longer required, `cylc set` and `cylc trigger`'
281 ' will insert tasks automatically.',
282 'jobscript':
283 'cylc jobscript has been removed',
284 'nudge':
285 'cylc nudge has been removed',
286 'print':
287 'cylc print has been removed; use `cylc scan --states=all`',
288 'register':
289 'cylc register has been removed; use cylc install or cylc play',
290 'reset':
291 'cylc reset has been replaced by cylc set',
292 'set-outputs':
293 'cylc set-outputs (cylc 8.0-8.2) has been replaced by cylc set',
294 'restart':
295 'cylc run & cylc restart have been replaced by cylc play',
296 'suite-state':
297 'cylc suite-state has been replaced by cylc workflow-state',
298 'run':
299 'cylc run & cylc restart have been replaced by cylc play',
300 'search':
301 'cylc search has been removed; please use `grep` or a text editor',
302 'spawn':
303 'cylc spawn has been removed; spawning is now performed automatically',
304 'submit':
305 'cylc submit has been removed',
306 'start':
307 'cylc start & cylc restart have been replaced by cylc play',
308 'set-verbosity':
309 'cylc set-verbosity has been replaced by cylc verbosity',
310 'warranty':
311 'cylc warranty has been replaced by cylc help license',
312 }
313 # fmt: on
314
315
316 def execute_cmd(cmd: str, *args: str) -> int:
317 """Execute a sub-command.
318
319 Args:
320 cmd: The name of the command.
321 args: Command line arguments to pass to that command.
322
323 """
324 entry_point = COMMANDS[cmd]
325 try:
326 entry_point.load()(*args)
327 except ModuleNotFoundError as exc:
328 msg = handle_missing_dependency(entry_point, exc)
329 print(msg, file=sys.stderr)
330 return 1
331 return 0
332
333
334 def match_command(command):
335 """Permit abbreviated commands (e.g. tri -> trigger).
336
337 Args:
338 command (string):
339 The input string to match.
340
341 Returns:
342 string - The matched command.
343
344 Exits:
345 1:
346 If the number of command matches != 1
347
348 """
349 possible_cmds = {
350 *{
351 # search commands
352 cmd
353 for cmd in COMMANDS
354 if cmd.startswith(command)
355 },
356 }
357 if len(possible_cmds) == 0:
358 print(
359 f"cylc {command}: unknown utility. Abort.\n"
360 'Type "cylc help all" for a list of utilities.',
361 file=sys.stderr
362 )
363 sys.exit(1)
364 elif len(possible_cmds) > 1:
365 print(
366 "cylc {}: is ambiguous for:\n{}".format(
367 command,
368 "\n".join(
369 [
370 f" cylc {cmd}"
371 for cmd in sorted(possible_cmds)
372 ]
373 ),
374 ),
375 file=sys.stderr,
376 )
377 sys.exit(1)
378 else:
379 command = possible_cmds.pop()
380 return command
381
382
383 def parse_docstring(docstring):
384 """Extract the description and usage lines from a sub-command docstring.
385
386 Args:
387 docstring (str):
388 Multiline string i.e. __doc__
389
390 Returns:
391 tuple - (usage, description)
392
393 """
394 lines = [
395 line
396 for line in docstring.splitlines()
397 if line
398 ]
399 usage = None
400 desc = None
401 if len(lines) > 0:
402 usage = lines[0]
403 if len(lines) > 1:
404 desc = lines[1]
405 return (usage, desc)
406
407
408 def iter_commands() -> Iterator[Tuple[str, Optional[str], Optional[str]]]:
409 """Yield all Cylc sub-commands that are available.
410
411 Skips sub-commands that require missing optional dependencies.
412
413 Yields:
414 (command, description, usage)
415
416 """
417 for cmd, entry_point in sorted(COMMANDS.items()):
418 try:
419 module = __import__(entry_point.module, fromlist=[''])
420 except ModuleNotFoundError as exc:
421 handle_missing_dependency(entry_point, exc)
422 continue
423 if getattr(module, 'INTERNAL', False):
424 # do not list internal commands
425 continue
426 usage, desc = parse_docstring(module.__doc__)
427 yield (cmd, desc, usage)
428
429
430 def print_id_help():
431 print(ID_HELP)
432
433
434 def print_license() -> None:
435 for file in files('cylc-flow') or []:
436 if file.name == 'COPYING':
437 print(file.read_text())
438 return
439
440
441 def print_command_list(commands=None, indent=0):
442 """Print list of Cylc commands.
443
444 Args:
445 commands (list):
446 List of commands to display.
447 indent (int):
448 Number of spaces to put at the start of each line.
449
450 """
451 from cylc.flow.terminal import print_contents
452 contents = [
453 (cmd, desc)
454 for cmd, desc, _, in iter_commands()
455 if not commands
456 or cmd in commands
457 ]
458 print_contents(contents, indent=indent, char=cparse('<dim>.</dim>'))
459
460
461 def cli_help():
462 """Display the main Cylc help page."""
463 # add a splash of colour
464 # we need to do this explicitly as this command is not behind cli_function
465 # (assume the cylc help is only ever requested interactively in a
466 # modern terminal)
467 from colorama import init as color_init
468 color_init(autoreset=True, strip=False)
469 print(USAGE)
470
471
472 def cli_version(long_fmt=False):
473 """Wrapper for get_version."""
474 print(get_version(long_fmt))
475 if long_fmt:
476 print(cparse(list_plugins()))
477
478
479 def list_plugins():
480 from cylc.flow.terminal import DIM, format_grid
481 # go through all Cylc entry points
482 _dists = set()
483 __entry_points = {}
484 for entry_point in entry_points():
485 if (
486 # all Cylc entry points are under the "cylc" namespace
487 entry_point.group.startswith('cylc.')
488 # don't list cylc-flow entry-points (i.e. built-ins)
489 and not entry_point.value.startswith('cylc.flow')
490 ):
491 _dists.add(entry_point.dist)
492 __entry_points.setdefault(
493 entry_point.group,
494 [],
495 ).append(entry_point)
496
497 # list all the distriutions which provide Cylc entry points
498 _plugins = []
499 for dist in _dists:
500 _plugins.append((
501 '',
502 f'<light-blue>{dist.name}</light-blue>',
503 dist.version,
504 f'<{DIM}>{dist.locate_file("__init__.py").parent}</{DIM}>',
505 ))
506
507 # list all of the entry points by "group" (e.g. "cylc.command")
508 _entry_points = []
509 for group, points in sorted(__entry_points.items()):
510 _entry_points.append((f' {group}:', '', ''))
511 for entry_point in points:
512 _entry_points.append((
513 f' {entry_point.name}',
514 f'<light-blue>{entry_point.dist.name}</light-blue>',
515 f'<{DIM}>{entry_point.value}</{DIM}>',
516 ))
517
518 return '\n'.join((
519 '\n<bold>Plugins:</bold>',
520 *format_grid(_plugins),
521 '\n<bold>Entry Points:</bold>',
522 *format_grid(
523 _entry_points
524 ),
525 ))
526
527
528 @contextmanager
529 def pycoverage(cmd_args): # pragma: no cover
530 """Capture code coverage if configured to do so.
531
532 This requires Cylc to be installed in editable mode
533 (i.e. `pip install -e`) in order to access the coverage configuration
534 file, etc.
535
536 $ pip install -e /cylc/working/directory
537
538 Set the CYLC_COVERAGE env var as appropriate before running tests
539
540 $ export CYLC_COVERAGE=1
541
542 Coverage files will be written out to the working copy irrespective
543 of where in the filesystem the `cylc` command was run.
544
545 $ cd /cylc/working/directory
546 $ coverage combine
547 $ coverage report
548
549 For remote tasks the coverage files will be written to the cylc
550 working directory on the remote so you will have to scp them back
551 to your local working directory before running coverage combine:
552
553 $ cd /cylc/working/directory
554 $ ssh remote-host cd /cylc/remote/working/directory && coverage combine
555 $ scp \
556 > remote-host/cylc/remote/working/directory/.coverage \
557 > .coverage.remote-host.12345.12345
558 $ coverage combine
559 $ coverage report
560
561 Environment Variables:
562 CYLC_COVERAGE:
563 '0'
564 Do nothing / run as normal.
565 '1'
566 Collect coverage data.
567 '2'
568 Collect coverage data and log every command for which
569 coverage data was successfully recorded to
570 a .coverage_commands_captured file in the Cylc
571 working directory.
572
573 """
574 cylc_coverage = os.environ.get('CYLC_COVERAGE')
575 if cylc_coverage not in ('1', '2'):
576 yield
577 return
578
579 # import here to avoid unnecessary imports when not running coverage
580 import cylc.flow
581 import coverage
582 from pathlib import Path
583 import signal
584
585 # the cylc working directory
586 if 'CYLC_COVERAGE_BASE' in os.environ:
587 cylc_wc = Path(os.environ['CYLC_COVERAGE_BASE'])
588 else:
589 cylc_wc = Path(cylc.flow.__file__).parents[2]
590
591 # initiate coverage
592 try:
593 cov = coverage.Coverage(
594 # NOTE: coverage paths are all relative so we must hack them here
595 # to absolute values, otherwise when `cylc` scripts are run
596 # elsewhere on the filesystem they will fail to capture coverage
597 # data and will dump empty coverage files where they run.
598 config_file=str(cylc_wc / '.coveragerc'),
599 data_file=str(cylc_wc / '.coverage'),
600 source=[str(cylc_wc / 'cylc')]
601 )
602 except coverage.misc.CoverageException as exc:
603 raise Exception(
604 # make sure this exception is visible in the traceback
605 '\n\n*****************************\n\n'
606 'Could not initiate coverage, likely because Cylc was not '
607 'installed in editable mode.'
608 '\n\n*****************************\n\n'
609 ) from exc
610
611 def cov_stop(*a, **k):
612 cov.stop()
613 cov.save()
614 if cylc_coverage == '2':
615 with open(cylc_wc / '.coverage_commands_captured', 'a+') as ccc:
616 ccc.write(
617 '$ cylc ' + (' '.join(cmd_args) + '\n'),
618 )
619
620 # start the coverage running
621 cov.start()
622 signal.signal(signal.SIGINT, cov_stop)
623 try:
624 # yield control back to cylc, return once the command exits
625 yield
626 finally:
627 # stop the coverage and save the data
628 cov_stop()
629
630
631 def get_arg_parser():
632 parser = argparse.ArgumentParser(add_help=False)
633 parser.add_argument(
634 '--help', '-h',
635 action='store_true',
636 default=False,
637 dest='help_'
638 )
639 parser.add_argument(
640 '--version', '-V',
641 action='store_true',
642 default=False,
643 dest='version'
644 )
645 return parser
646
647
648 def main() -> None: # pragma: no cover
649 opts, cmd_args = get_arg_parser().parse_known_args()
650 with pycoverage(cmd_args):
651 ret = _main(opts, cmd_args)
652 sys.exit(ret)
653
654
655 def _main(opts, cmd_args: list[str]) -> int:
656 """Implemnent the Cylc CLI.
657
658 Returns the exit code as an integer.
659 """
660 if not cmd_args:
661 if opts.version:
662 cli_version()
663 return 0
664 else:
665 cli_help()
666 return 0
667 else:
668 cmd_args = list(cmd_args)
669 command: str = cmd_args.pop(0)
670
671 if command == "version":
672 cli_version("--long" in cmd_args)
673 return 0
674
675 if command == "help":
676 opts.help_ = True
677 if not len(cmd_args):
678 cli_help()
679 return 0
680 elif cmd_args == ['all']:
681 print_command_list()
682 return 0
683 elif cmd_args == ['id']:
684 print_id_help()
685 return 0
686 if cmd_args in (['license'], ['licence']):
687 print_license()
688 return 0
689 else:
690 command = cmd_args.pop(0)
691
692 # this is an alias to a command
693 command = ALIASES.get(command, command)
694
695 if command in DEAD_ENDS:
696 # this command has been removed but not aliased
697 # display a helpful message and move on#
698 print(
699 cparse(
700 f'<red>{DEAD_ENDS[command]}</red>'
701 )
702 )
703 return 42
704
705 if command not in COMMANDS:
706 # check if this is a command abbreviation or exit
707 command = match_command(command)
708 if opts.help_:
709 cmd_args.append('--help')
710 return execute_cmd(command, *cmd_args)
711
712
713 def handle_missing_dependency(
714 entry_point,
715 err: ModuleNotFoundError
716 ) -> str:
717 """Return a suitable error message for a missing optional dependency.
718
719 Args:
720 entry_point: The entry point that was attempted to load but caused
721 a ModuleNotFoundError.
722 err: The ModuleNotFoundError that was caught.
723
724 Re-raises the given ModuleNotFoundError if it is unexpected.
725 """
726 msg = f'"cylc {entry_point.name}" requires "{entry_point.dist.name}'
727 if entry_point.extras:
728 msg += f'[{",".join(entry_point.extras)}]'
729 msg += f'"\n\n{err.__class__.__name__}: {err}'
730 return msg