Debian Codegraph @

cylc/flow/scripts/completion_server.py

raw
1 #!/usr/bin/env python3
2
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """cylc completion-server [OPTIONS]
20
21 A server for providing Cylc CLI completion results.
22
23 This server accepts requests containing the command line and returns responses
24 containing possible completions for the last word on the command line.
25
26 See `cylc get-resources` for available completion scripts using this server.
27 """
28
29 # NOTE: Developers
30 #
31 # This server is launched automatically in the user's shell. If it dies it
32 # gets restarted. It's important to handle error cases very carefully as
33 # we don't want these servers getting caught in crash/restart loops or causing
34 # hassle to users.
35 #
36 # This file contains:
37 # * Completion functions:
38 # Which "complete" words e.g. 'a' might match 'a1', 'a2' but not 'b1'.
39 # * Listing functions:
40 # Which provide possible values to the completion functions.
41
42 import asyncio
43 from contextlib import suppress
44 import inspect
45 import os
46 from pathlib import Path
47 import select
48 import sys
49 import typing as t
50
51 from packaging.version import parse as parse_version
52 from packaging.specifiers import SpecifierSet
53
54 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
55 from cylc.flow.exceptions import CylcError
56 from cylc.flow.id import tokenise, IDTokens, Tokens
57 from cylc.flow.network.scan import scan
58 from cylc.flow.option_parsers import CylcOptionParser as COP
59 from cylc.flow.pathutil import get_workflow_run_job_dir
60 from cylc.flow.resources import (
61 list_resources as list_resources_,
62 RESOURCE_DIR,
63 )
64 from cylc.flow.scripts.cylc import ALIASES, COMMANDS
65 from cylc.flow.scripts.scan import FLOW_STATES, get_pipe, ScanOptions
66 from cylc.flow.terminal import cli_function
67 from cylc.flow.workflow_files import infer_latest_run_from_id
68
69 if t.TYPE_CHECKING:
70 from optparse import Values
71
72 # do not list this command in `cylc help all` output
73 INTERNAL = True
74
75 # set the compatibility range for completion scripts with this server
76 # I.E. if we change the server interface, change this compatibility range.
77 # User's will be presented with an upgrade notice if this happens.
78 REQUIRED_SCRIPT_VERSION = '>=1.0.0, <2.0.0'
79
80 # register the psudo "help" and "version" commands
81 COMMAND_LIST = list(COMMANDS) + ['help', 'version']
82
83
84 def stdin(timeout: int = 2) -> t.Iterator[str]:
85 """Yield lines from stdin, stop on configured read timeout.
86
87 Args:
88 timeout:
89 Read timeout in seconds, if no new input is received within this
90 period the generator will exit.
91
92 Yields:
93 The file line by line.
94
95 """
96 while True:
97 if select.select([sys.stdin], [], [], timeout)[0]:
98 # wait for input => yield
99 yield sys.stdin.readline()
100 else:
101 # timeout => stop iterating
102 return
103
104
105 async def server(
106 listener: t.Callable,
107 responder: t.Callable,
108 once: bool = False,
109 write: t.Callable[[str], None] = print,
110 timeout: int = 60,
111 ) -> None:
112 """The bit that handles incoming requests.
113
114 * Accepts requests in the format `cylc|trigger|workfl`.
115 * Writes responses in the format cylc trigger workflow//`.
116
117 Args:
118 listener:
119 Generator function which yields requests.
120 Must accept a `timeout` (seconds) argument.
121 responder:
122 Function which yields a list of possible responses.
123 responder(commandline: List[str]) => List[str].
124 once:
125 Return after sending the first response.
126 write:
127 The function which sends the response back to the originator.
128 timeout:
129 Max time to wait for new requests.
130
131 Note:
132 The server will not play nicely with completions which contain spaces
133 (they will show as separate completions).
134
135 Completions should not contain spaces, workflows/cycles/tasks/jobs
136 cannot contain spaces (due to validation rules) so this is ok.
137
138 """
139 for line in listener(timeout=timeout):
140 try:
141 write(' '.join(
142 item
143 for item in sorted(await responder(*line[:-1].split('|')))
144 ))
145 except Exception:
146 # catch everything! If an error occurs swallow it, we don't want
147 # it to reach the CLI or to cause the server to get caught in
148 # a crash/restart loop
149 write('') # send an empty reply
150 if once:
151 return
152 sys.stdout.flush()
153
154
155 async def complete_cylc(_root: str, *items: str) -> t.List[str]:
156 """Return Cylc CLI completions for the provided args.
157
158 Args:
159 _root:
160 The root command i.e. `cylc`.
161 items:
162 The command items e.g. ['trigger', 'workfl']
163
164 Returns:
165 List of possible completions e.g. ['workflow_a//', 'workflow_b//']
166
167 """
168 length: int = len(items)
169
170 # the word to complete
171 partial: t.Optional[str] = None
172 if length > 0:
173 partial = items[-1]
174
175 # the previous word
176 previous: t.Optional[str] = None
177 if length > 1:
178 previous = items[-2]
179
180 # complete the cylc sub-command
181 if length == 0:
182 return await complete_command()
183 if length == 1:
184 return await complete_command(partial)
185 command: str = ALIASES.get(items[0], items[0]) # resolve command aliases
186
187 # special logic for the pseudo "help" and "version" commands
188 if command == 'help':
189 return complete(partial, ['id', 'all'])
190 if command == 'version':
191 return complete(partial, ['--long'])
192
193 # complete --options
194 if partial and partial.startswith('-'):
195 ret = await complete_option(command, partial)
196 if ret is not None:
197 return ret
198 if previous and previous.startswith('-'):
199 ret = await complete_option_value(
200 command,
201 previous,
202 partial,
203 items=items,
204 )
205 if ret is not None:
206 return ret
207
208 # complete positional arguments
209 return await complete_argument(command, partial)
210
211
212 def complete(
213 partial: t.Optional[str],
214 words: t.Iterable[str]
215 ) -> t.List[str]:
216 """Return only matching words.
217
218 Args:
219 partial:
220 The string to match.
221 words:
222 The list of words to match against.
223
224 Returns:
225 The filtered list of matching words.
226
227 Examples:
228 >>> complete('w', ['beans', 'walrus', 'wellington'])
229 ['walrus', 'wellington']
230
231 """
232 if partial is None:
233 return list(words)
234 return [
235 word
236 for word in words
237 if word.startswith(partial)
238 ]
239
240
241 async def complete_command(partial: t.Optional[str] = None) -> t.List[str]:
242 """Complete Cylc commands."""
243 return complete(partial, COMMAND_LIST)
244
245
246 async def complete_option(
247 command: str,
248 partial: t.Optional[str] = None
249 ) -> t.Optional[t.List[str]]:
250 """Complete --options."""
251 if partial and '=' in partial:
252 option, partial = partial.split('=', 1)
253 values = await complete_option_value(command, option, partial)
254 if values is None:
255 return None
256 return [ # filtering already performed by complete_option_value
257 f'{option}={value}'
258 for value in values
259 ]
260
261 return complete(partial, list_options(command))
262
263
264 async def complete_option_value(
265 command: str,
266 option: str,
267 partial: t.Optional[str] = None,
268 items: t.Optional[t.Iterable[str]] = None,
269 ) -> t.Optional[t.List[str]]:
270 """Complete values for --options."""
271 vals = await list_option_values(command, option, partial, items=items)
272 if vals is not None:
273 return complete(partial, vals)
274 return None
275
276
277 async def complete_argument(
278 command: str,
279 partial: t.Optional[str] = None,
280 ) -> t.List[str]:
281 """Complete arguments for commands."""
282 coro = COMMAND_MAP.get(command, list_cylc_id)
283 if coro is None:
284 # argument completion disabled for this command
285 return []
286 return complete(
287 partial,
288 await coro(partial),
289 )
290
291
292 async def list_cylc_id(partial: str) -> t.List[str]:
293 """List Cylc IDs (workflows//cycles/tasks/jobs)."""
294 partial = partial or ''
295
296 try:
297 tokens = tokenise(partial)
298 except ValueError:
299 tokens = Tokens()
300
301 # strip off any partial IDs
302 # e.g. workflow//12 => workflow//
303 # e.g. workflow//1234/ta => workflow//1234
304 if not partial.endswith('/') and not tokens.is_null:
305 tokens.pop_token()
306
307 if tokens.is_null:
308 # if there are no tokens, list all workflows
309 ids = await list_workflows()
310 else:
311 # if there are tokens, list things within that workflow
312 ids = await list_in_workflow(tokens)
313
314 return ids
315
316
317 def list_options(command: str) -> t.List[str]:
318 """List CLI options from a Cylc command.
319
320 E.G. ['--help', '--debug', '--color', ....]
321
322 Note: This provides the long formats of options e.g. `--help` not `-h`.
323 """
324 if command in COMMAND_OPTION_MAP:
325 return COMMAND_OPTION_MAP[command]
326 try:
327 entry_point = COMMANDS[command].load()
328 except KeyError:
329 return []
330 parser = entry_point.parser_function()
331 if getattr(parser, 'auto_add', None):
332 parser.add_std_options()
333 return [
334 option.get_opt_string()
335 for option in parser.option_list
336 ]
337
338
339 async def list_option_values(
340 command: str,
341 option: str,
342 partial: t.Optional[str] = '',
343 items: t.Optional[t.Iterable[str]] = None,
344 ) -> t.Optional[t.List[str]]:
345 """List values for an option in a Cylc command.
346
347 Args:
348 command:
349 The Cylc sub-command.
350 option:
351 The --option to list possible values for.
352 partial:
353 The part of the command the user is completing.
354 items:
355 The CLI context, i.e. everything that has been typed on the CLI
356 before the partial.
357
358 E.G. --flow ['new', 'none']
359 """
360 if option in OPTION_MAP:
361 list_option = OPTION_MAP[option]
362 if not list_option:
363 # do not perform completion for this option
364 return []
365 kwargs = {}
366 if 'tokens_list' in inspect.getfullargspec(list_option).args:
367 # the function requires information about tokens already specified
368 # on the CLI
369 # (e.g. the workflow//cycle/task the command is operating on)
370 tokens_list = []
371 for item in items or []:
372 # pull out things from the command which look like IDs
373 if '//' in item:
374 with suppress(ValueError):
375 tokens_list.append(Tokens(item))
376 continue
377 with suppress(ValueError):
378 tokens_list.append(Tokens(item, relative=True))
379 kwargs['tokens_list'] = tokens_list
380 return await list_option(partial, **kwargs)
381 return None
382
383
384 async def list_workflows(states: t.Optional[t.Set[str]] = None) -> t.List[str]:
385 """List workflows from run directories."""
386 pipe = get_pipe(ScanOptions(states=states or FLOW_STATES), 'None')
387 ids = []
388 async for flow in pipe:
389 ids.append(cli_detokenise(Tokens(workflow=flow['name'])))
390 return ids
391
392
393 async def list_src_workflows(_partial: str) -> t.List[str]:
394 """List workflow source directories from "source dirs"."""
395 ret = []
396 for src_dir in glbl_cfg().get(['install', 'source dirs']):
397 async for src_flow in scan(run_dir=Path(src_dir).expanduser()):
398 ret.append(src_flow['name'])
399 return ret
400
401
402 async def list_in_workflow(tokens: Tokens, infer_run=True) -> t.List[str]:
403 """List cycles/tasks/jobs from within a workflow."""
404 if not tokens.get('workflow'):
405 return []
406 parts = []
407 if tokens.get('cycle'):
408 parts.append(tokens['cycle'])
409 if tokens.get('task'):
410 parts.append(tokens['task'])
411 if tokens.get('job'):
412 parts.append(tokens['job'])
413 input_workflow = tokens['workflow'] # workflow ID as provided on the CLI
414 if infer_run:
415 # workflow ID after run name inference
416 inferred_workflow = infer_latest_run_from_id(input_workflow)
417 else:
418 inferred_workflow = input_workflow
419 job_dir = Path(get_workflow_run_job_dir(inferred_workflow, *parts))
420 if not job_dir.exists():
421 # no job dir (e.g. workflow has not been run yet)
422 return []
423 token = next_token(tokens)
424 if token:
425 return [
426 # list possible IDs
427 cli_detokenise(
428 tokens.duplicate(
429 # use the workflow ID provided on the CLI to allow
430 # run name inference
431 workflow=input_workflow,
432 **{token: path.name},
433 )
434 )
435 for path in job_dir.iterdir()
436 ]
437 return []
438
439
440 async def list_resources(_partial: str) -> t.List[str]:
441 """Return the list of resources accessible through cylc get-resources."""
442 resources: t.List[str] = []
443 list_resources_(resources.append, headers=False)
444 return [
445 resource.split('#')[0].strip()
446 for resource in resources
447 ]
448
449
450 async def list_dir(
451 partial: t.Optional[str]
452 ) -> t.List[str]:
453 """List an arbitrary dir on the filesystem.
454
455 Relative dirs are assumed relative to `$PWD`.
456 """
457 if partial:
458 path = Path(partial)
459 if not partial.endswith('/'):
460 path = path.parent
461 if path.is_absolute():
462 return list_abs_dir(path)
463 return list_rel_dir(path, Path('.'))
464
465 return list_rel_dir(Path('.'), Path('.'))
466
467
468 def list_abs_dir(path: Path) -> t.List[str]:
469 """List an absolute directory."""
470 if not path.is_dir():
471 return [str(path)]
472 return [
473 f'{sub_path}/' if sub_path.is_dir() else str(sub_path)
474 for sub_path in path.iterdir()
475 ]
476
477
478 def list_rel_dir(path: Path, base: Path) -> t.List[str]:
479 """List a relative directory.
480
481 Args:
482 path: The directory to list.
483 base: Results are given relative to this.
484
485 """
486 if not path.is_dir():
487 return [str(path)]
488 return [
489 f'{sub_path.relative_to(base)}/'
490 if sub_path.is_dir()
491 else str(sub_path.relative_to(base))
492 for sub_path in path.iterdir()
493 ]
494
495
496 async def list_flows(
497 _partial: t.Optional[str]
498 ) -> t.List[str]:
499 """List values for the --flow option."""
500 return ['none', 'new']
501
502
503 async def list_colours(
504 _partial: t.Optional[str]
505 ) -> t.List[str]:
506 """List values for the --color option."""
507 return ['never', 'auto', 'always']
508
509
510 async def list_outputs(
511 _partial: t.Optional[str],
512 tokens_list: t.Optional[t.List[Tokens]],
513 ):
514 """List task outputs."""
515 return (await _list_prereqs_and_outputs(tokens_list))[1]
516
517
518 async def list_prereqs(
519 _partial: t.Optional[str],
520 tokens_list: t.Optional[t.List[Tokens]],
521 ):
522 """List task prerequisites."""
523 return (await _list_prereqs_and_outputs(tokens_list))[0] + ['all']
524
525
526 async def _list_prereqs_and_outputs(
527 tokens_list: t.Optional[t.List[Tokens]],
528 ) -> t.Tuple[t.List[str], t.List[str]]:
529 """List task prerequisites and outputs.
530
531 Returns:
532 tuple - (prereqs, outputs)
533
534 """
535 if not tokens_list:
536 # no context information available on the CLI
537 # we can't list prereqs/outputs
538 return ([], [])
539
540 # dynamic import for this relatively unlikely case to avoid slowing down
541 # server startup unnecessarily
542 from cylc.flow.network.client_factory import get_client
543 from cylc.flow.scripts.show import prereqs_and_outputs_query
544 from types import SimpleNamespace
545
546 workflows: t.Dict[str, t.List[Tokens]] = {}
547 current_workflow = None
548 for tokens in tokens_list:
549 workflow = tokens['workflow']
550 task = tokens['task']
551 if workflow:
552 workflows.setdefault(workflow, [])
553 current_workflow = workflow
554 if current_workflow and task:
555 workflows[current_workflow].append(tokens.task)
556
557 clients = {}
558 for workflow in workflows:
559 with suppress(CylcError):
560 clients[workflow] = get_client(workflow)
561
562 if not workflows:
563 return ([], [])
564
565 json: dict = {}
566 await asyncio.gather(*(
567 prereqs_and_outputs_query(
568 workflow,
569 workflows[workflow],
570 pclient,
571 SimpleNamespace(json=True),
572 json,
573 )
574 for workflow, pclient in clients.items()
575 ))
576
577 if not json:
578 return ([], [])
579 return (
580 [
581 f"{cond['taskId']}:{cond['reqState']}"
582 for value in json.values()
583 for prerequisite in value['prerequisites']
584 for cond in prerequisite['conditions']
585 ],
586 [
587 output['label']
588 for value in json.values()
589 for output in value['outputs']
590 ],
591 )
592
593
594 # non-exhaustive list of Cylc commands which take non-workflow arguments
595 COMMAND_MAP: t.Dict[str, t.Optional[t.Callable]] = {
596 # register commands which have special positional arguments
597 'get-resources': list_resources,
598 'install': list_src_workflows,
599 'vip': list_src_workflows,
600 # commands for which we should not attempt to complete arguments
601 'cycle-point': None,
602 'hub': None,
603 'message': None,
604 'scan': None,
605 }
606
607
608 # commands we can't list options for in the standard way
609 COMMAND_OPTION_MAP = {
610 'gui': [
611 '--debug',
612 '--help',
613 '--new',
614 '--no-browser',
615 ],
616 'hub': [
617 '--debug',
618 '--help',
619 ],
620 }
621
622 # non-exhaustive list of Cylc CLI options
623 # (the ideal solution would inspect the meta-variables for each option)
624 OPTION_MAP: t.Dict[str, t.Optional[t.Callable]] = {
625 # register --options which need special treatment
626 '--set-file': list_dir,
627 '--file': list_dir,
628 '--output': list_dir,
629 '--flow': list_flows,
630 '--colour': list_colours,
631 '--color': list_colours,
632 '--out': list_outputs,
633 '--pre': list_prereqs,
634 # options for which we should not attempt to complete values for
635 '--rm': None,
636 '--run-name': None,
637 '--initial-cycle-point': None,
638 '--final-cycle-point': None,
639 '--start-cycle-point': None,
640 '--stop-cycle-point': None,
641 '--start-task': None,
642 '--hold-cycle-point': None,
643 '--host': None,
644 '--format': None,
645 '--main-loop': None,
646 }
647
648
649 def cli_detokenise(tokens: Tokens, relative=False) -> str:
650 """Format tokens for use on the command line.
651
652 I.E. add the trailing slash[es] onto the end.
653 """
654 if tokens.is_null:
655 # shouldn't happen but prevents possible error
656 return ''
657 if relative:
658 id_ = tokens.relative_id
659 else:
660 id_ = tokens.id
661 if tokens.lowest_token == IDTokens.Workflow.value:
662 return f'{id_}//'
663 return f'{id_}/'
664
665
666 def next_token(tokens: Tokens) -> t.Optional[str]:
667 """Return the first unspecified token.
668
669 Examples:
670 >>> next_token(Tokens())
671 'workflow'
672 >>> next_token(Tokens(workflow='a'))
673 'cycle'
674 >>> next_token(Tokens(workflow='a', cycle='1'))
675 'task'
676 >>> next_token(Tokens(workflow='a', cycle='1', task='x'))
677 'job'
678 >>> next_token(Tokens(workflow='a', cycle='1', task='x', job='01'))
679
680 """
681 if tokens.is_null:
682 return IDTokens.Workflow.value
683 lowest_token = IDTokens(tokens.lowest_token)
684 next_ = False
685 for token in IDTokens:
686 if next_:
687 return token.value
688 if token == lowest_token:
689 next_ = True
690 return None
691
692
693 def get_completion_script_file(completion_lang: str) -> t.Optional[Path]:
694 """Return the path of the completion script for the specified language.
695
696 Returns None if there is no completion script for the provided language.
697 """
698 completion_script = (RESOURCE_DIR / f'cylc-completion.{completion_lang}')
699 if not completion_script.exists():
700 return None
701 return completion_script
702
703
704 def get_current_completion_script_version(
705 completion_script: Path,
706 completion_lang: str,
707 ) -> t.Optional[str]:
708 """Extract the script version from the provided script.
709
710 Returns None if the script version cannot be determined.
711 """
712 if completion_lang == 'bash':
713 with open(completion_script, 'r') as script:
714 for line in script:
715 if line.startswith('export CYLC_COMPLETION_SCRIPT_VERSION='):
716 return line.replace(
717 'export CYLC_COMPLETION_SCRIPT_VERSION=',
718 ''
719 )
720 return None
721
722
723 def check_completion_script_compatibility(
724 completion_lang: str,
725 completion_script_version: str,
726 ) -> bool:
727 """Check if a completion script is compatible with this server.
728
729 Prints upgrade advice to `sys.stderr` as appropriate.
730
731 Args:
732 completion_lang:
733 The language the completion script is implemented for e.g. `Bash`.
734 completion_script_version:
735 The completion script version e.g. `1.0.0`.
736
737 Returns:
738 True if the completion script is compatible, else False.
739
740 """
741 is_compatible = True
742
743 # get the version of the completion script bundled with this version of
744 # Cylc
745 completion_script = get_completion_script_file(completion_lang)
746 if completion_script is None:
747 return False
748 current_version = get_current_completion_script_version(
749 completion_script,
750 completion_lang,
751 )
752 if current_version is None:
753 return True
754
755 current_version = parse_version(current_version)
756 installed_version = parse_version(completion_script_version)
757
758 # check that the installed completion script is compabile with this
759 # completion server version
760 if installed_version not in SpecifierSet(REQUIRED_SCRIPT_VERSION):
761 is_compatible = False
762 print(
763 f'The Cylc {completion_lang} script needs to be updated to'
764 ' work with this version of Cylc.',
765 file=sys.stderr,
766 )
767
768 # check for completion script updates
769 if installed_version < current_version:
770 print(
771 f'A new version of the Cylc {completion_lang} script is available.'
772 f'\nGet it with: cylc get-resources {completion_script.name} PATH',
773 file=sys.stderr,
774 )
775
776 return is_compatible
777
778
779 def get_option_parser() -> COP:
780 parser = COP(
781 __doc__,
782 )
783
784 parser.add_option(
785 '--timeout',
786 type='int',
787 default=900, # PT15M
788 help=(
789 'The maximum idle time before the server shuts down in seconds.'
790 )
791 )
792
793 parser.add_option(
794 '--once',
795 action='store_true',
796 default=False,
797 help=(
798 'Exit after returning the first response (for testing purposes).'
799 )
800 )
801
802 return parser
803
804
805 @cli_function(get_option_parser)
806 def main(_, opts: 'Values') -> None:
807 completion_lang = os.environ.get('CYLC_COMPLETION_LANG')
808 completion_script_version = os.environ.get(
809 'CYLC_COMPLETION_SCRIPT_VERSION'
810 )
811
812 if (
813 # if we are being called by a completion script, check the script
814 # is compatible with this server version before proceeding
815 completion_lang
816 and completion_script_version
817 and not check_completion_script_compatibility(
818 completion_lang,
819 completion_script_version,
820 )
821 ):
822 # this server version is not compatible with the script version
823 return
824
825 asyncio.run(
826 server(
827 stdin,
828 complete_cylc,
829 once=opts.once,
830 timeout=opts.timeout
831 )
832 )