Debian Codegraph @

cylc/flow/scripts/scan.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 """cylc scan [OPTIONS]
19
20 List your source, and/or installed, and/or running workflows.
21
22 By default, running workflows are listed as indicated by the presence of
23 scheduler contact files, ~/cylc-run/<Workflow-ID>/.service/contact.
24
25 With "--ping" or "-t rich", attempt to contact the schedulers. If any are not
26 found to be running, their contact files will be removed (these files may left
27 behind if the scheduler did not shut down cleanly).
28
29 Examples:
30 # list all active workflows (i.e. running or paused)
31 $ cylc scan
32
33 # show more information about active workflows
34 $ cylc scan -t rich
35
36 # don't rely on colour for job state totals
37 $ cylc scan -t rich --colour-blind
38
39 # list workflows that are installed but stopped or not run yet
40 $ cylc scan --state stopped
41
42 # list all workflows (active or inactive)
43 $ cylc scan --state=running,paused,stopped
44 $ cylc scan --state=all # or using the shorthand
45
46 # filter workflows by name
47 $ cylc scan --name '^f.*' # show only flows starting with "f"
48
49 # list source workflows in tree format
50 # (looks in the dirs configured by "global.cylc[install]source dirs")
51 $ cylc scan --source -t tree
52
53 # print contact file data in JSON format
54 $ cylc scan -t json
55 """
56
57 import asyncio
58 import json
59 from pathlib import Path
60 from typing import Callable, Optional, TYPE_CHECKING
61
62 from ansimarkup import ansiprint as cprint
63
64 from cylc.flow import LOG
65 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
66 from cylc.flow.exceptions import InputError
67 from cylc.flow.network.scan import (
68 contact_info,
69 filter_name,
70 graphql_query,
71 is_active,
72 scan,
73 scan_multi,
74 )
75 from cylc.flow.option_parsers import (
76 CylcOptionParser as COP,
77 Options
78 )
79 from cylc.flow.print_tree import get_tree
80 from cylc.flow.terminal import cli_function, DIM
81 from cylc.flow.util import natural_sort_key
82 from cylc.flow.workflow_files import ContactFileFields as Cont
83
84 if TYPE_CHECKING:
85 from optparse import Values
86
87 # all supported workflow states
88 FLOW_STATES = {
89 'running',
90 'paused',
91 'stopping',
92 'stopped'
93 }
94
95
96 # workflow status colours
97 FLOW_STATE_CMAP = {
98 # workflow state: term colour
99 'running': 'green',
100 'paused': 'fg 172',
101 'stopping': 'fg 201',
102 'stopped': 'red'
103 }
104
105
106 # workflow status symbols
107 FLOW_STATE_SYMBOLS = {
108 # NOTE: the standard media control characters ▶️,, ⏸️,, ⏹️
109 # can appear wildly different font-depending and may not
110 # even be monospace
111 'running': '▶',
112 'paused': '‖',
113 'stopping': '◧',
114 'stopped': '■'
115 }
116
117
118 # document the flow states
119 __doc__ += '\n '.join(
120 [
121 '\nWorkflow States:'
122 ] + [
123 (
124 f'<{FLOW_STATE_CMAP[state]}>'
125 f'{FLOW_STATE_SYMBOLS[state]}'
126 f' {state}'
127 f'</{FLOW_STATE_CMAP[state]}>'
128 )
129 for state in FLOW_STATES
130 ]
131 )
132
133
134 # job icon colours
135 JOB_COLOURS = {
136 # job status: term colour
137 'submitted': 'fg 44',
138 'submit-failed': 'fg 13',
139 'running': 'fg 32',
140 'succeeded': 'fg 35',
141 'failed': 'fg 124'
142 }
143
144
145 # document the task states
146 __doc__ += '\n '.join(
147 [
148 '\n\nTask States:'
149 ] + [
150 f'<{tag}>■ {state}</{tag}>'
151 for state, tag in JOB_COLOURS.items()
152 ]
153 )
154
155
156 # graphql fields to request from the workflow for the "rich" format
157 RICH_FIELDS = {
158 'status': None,
159 'stateTotals': None,
160 'cylcVersion': None,
161 'meta': {
162 'title',
163 'description',
164 },
165
166 }
167
168
169 BAD_CONTACT_FILE_MSG = "Bad contact file: {flow_name}"
170
171
172 def get_option_parser() -> COP:
173 """CLI opts for "cylc scan"."""
174 parser = COP(
175 __doc__, comms=True
176 )
177
178 parser.add_option(
179 '--name', '-n',
180 help=(
181 'Filter workflows by registered name using a regex.'
182 ' Can be used multiple times, workflows will be displayed if'
183 ' their name matches ANY of the provided regexes.'
184 ),
185 action='append'
186 )
187
188 parser.add_option(
189 '--states',
190 help=(
191 'Choose which workflows to display by providing a list of states'
192 ' or "all" to show everything. See the full `cylc scan` help'
193 ' for a list of supported states.'
194 ),
195 default='running,paused,stopping',
196 action='store'
197 )
198
199 parser.add_option(
200 '--source', '-s',
201 help=(
202 'List source workflows from configured source'
203 ' directories (overrides the --states option).'
204 ),
205 default=False,
206 action='store_true'
207 )
208
209 parser.add_option(
210 '--format', '-t',
211 help=(
212 r'Output data and format (default "%default").'
213 ' ("name": list the workflow IDs only)'
214 ' ("plain": name,host:port,PID on one line)'
215 ' ("tree": name,host:port,PID in tree format)'
216 ' ("json": full contact data in JSON format)'
217 ' ("rich": include task state summary data)'
218 ),
219 choices=('rich', 'plain', 'json', 'tree', 'name'),
220 default='plain'
221 )
222
223 parser.add_option(
224 '--sort',
225 help='Sort flows by name before writing them (takes longer).',
226 action='store_true'
227 )
228
229 parser.add_option(
230 '--colour-blind', '--color-blind',
231 help=(
232 "Don't depend on colour to convey information. "
233 'Use this rather than --color=never so you still get bold text.'
234 ),
235 action='store_true'
236 )
237
238 parser.add_option(
239 '--ping',
240 help=(
241 "Connect to schedulers and remove contact files if they are not "
242 "found to be running. Contact files can be left behind when "
243 "schedulers get killed."
244 ),
245 action='store_true'
246 )
247
248 return parser
249
250
251 def state_totals(totals, colour_blind=False):
252 """Return a string with a visual representation of workflow state totals.
253
254 Args:
255 totals (dict):
256 State totals dictionary.
257 colour_blind (bool):
258 If True then we will not depend on colour to convey information.
259
260 Returns:
261 str
262
263 """
264 ret = []
265 for state, tag in JOB_COLOURS.items():
266 number = totals[state]
267 if number == 0:
268 continue
269 if colour_blind:
270 ret.append(f'<{tag}>{state}:{number}</{tag}>')
271 else:
272 ret.append(f'<{tag}>{number} ■</{tag}>')
273 return ' '.join(ret)
274
275
276 def state_totals_key():
277 """Return a key to accompany state_totals."""
278 return '<b>Job State Key: </b>' + ' '.join(
279 f'<{tag}>\u25A0 {name}</{tag}>'
280 for name, tag in JOB_COLOURS.items()
281 )
282
283
284 def _format_json(items, _):
285 """A JSON formatter."""
286 return json.dumps(
287 [
288 {
289 key: str(value) if isinstance(value, Path) else value
290 for key, value in flow.items()
291 }
292 for flow in items
293 ],
294 indent=4,
295 sort_keys=True
296 )
297
298
299 def _format_plain(flow, _):
300 """A single line format of the form: <name> [<host>:<port>]"""
301 if flow.get('contact'):
302 try:
303 return (
304 f"<b>{flow['name']}</b> "
305 f"{flow[Cont.HOST]}:{flow[Cont.PORT]} "
306 f"{flow[Cont.PID]}"
307 )
308 except KeyError:
309 LOG.warning(BAD_CONTACT_FILE_MSG.format(flow_name=flow['name']))
310 return None
311 else:
312 return f'<{DIM}><b>{flow["name"]}</b></{DIM}>'
313
314
315 def _format_name_only(flow, _):
316 """A single line format of the form: <name> [<host>:<port>]"""
317 return flow['name']
318
319
320 def _format_rich(flow, opts):
321 """A multiline format which pulls in metadata."""
322 status = flow.get('status', 'stopped')
323 if opts.colour_blind:
324 name = f'{flow["name"]} ({status})'
325 else:
326 symbol = FLOW_STATE_SYMBOLS[status]
327 tag = FLOW_STATE_CMAP[status]
328 name = f'<{tag}>{symbol}</{tag}> {flow["name"]}'
329 if not flow.get('contact') or 'status' not in flow:
330 ret = [f'<{DIM}><b>{name}</b></{DIM}>']
331 else:
332 ret = [f'<b>{name}</b>']
333
334 display = {
335 'state totals': state_totals(
336 flow['stateTotals'], opts.colour_blind
337 ),
338 **{
339 key: flow['meta'][key] or f'<{DIM}>*null*</{DIM}>'
340 for key in (
341 'title',
342 'description'
343 )
344 },
345 **{
346 name: flow[key]
347 for name, key in (
348 ('version', 'cylcVersion'),
349 ('host', Cont.HOST),
350 ('port', Cont.PORT),
351 ('PID', Cont.PID)
352 )
353 }
354 }
355 maxlen = max(len(key) for key in display)
356 for key, value in display.items():
357 # format multiline strings by whitespace padding the lines
358 value = ('\n' + (' ' * (maxlen + 7))).join(value.splitlines())
359 # write out the key: value pairs
360 ret.append(f' {key: <{maxlen}} {value}')
361 return '\n'.join(ret)
362
363
364 def sort_function(flow):
365 if (
366 flow.get('status') == 'running'
367 or flow.get('status') == 'paused'
368 ):
369 state = 0
370 elif flow.get('contact'):
371 state = 2
372 else:
373 state = 3
374 return (state, *natural_sort_key(flow['name']))
375
376
377 async def _sorted(pipe, formatter, opts, write):
378 """List all flows, sort, then print them individually."""
379 ret = []
380 async for item in pipe:
381 ret.append(item)
382 for flow in sorted(ret, key=sort_function):
383 out = formatter(flow, opts)
384 if out is not None:
385 write(out)
386
387
388 async def _serial(pipe, formatter, opts, write):
389 """List all flows, then print them as one."""
390 ret = []
391 async for item in pipe:
392 ret.append(item)
393 out = formatter(ret, opts)
394 if out is not None:
395 write(out)
396
397
398 async def _async(pipe, formatter, opts, write):
399 """List and print flows individually."""
400 async for flow in pipe:
401 out = formatter(flow, opts)
402 if out is not None:
403 write(out)
404
405
406 async def _tree(pipe, formatter, opts, write):
407 """List all flows, sort, then print them as a tree."""
408 # get list of flows
409 ret = []
410 async for flow in pipe:
411 ret.append(flow)
412
413 tree = {}
414 _construct_tree(ret, tree, formatter, opts, write)
415
416 # print tree
417 ret = get_tree(tree, '', sort=False, use_unicode=True)
418 if ret:
419 write('\n'.join(ret))
420
421
422 def _construct_tree(flows, tree, formatter, opts, write):
423 """Construct the tree, for given flows and formatter."""
424 for flow in sorted(flows, key=lambda f: f['name']):
425 parts = Path(flow['name']).parts
426 pointer = tree
427 for part in parts[:-1]:
428 if part not in pointer:
429 pointer[part] = {}
430 pointer = pointer[part]
431 flow['name'] = parts[-1]
432 item = formatter(flow, opts)
433 if item is None:
434 continue
435
436 if len(parts) > 1:
437 item = f' {item}'
438 pointer[item] = ''
439
440
441 def get_pipe(opts, formatter, scan_dir=None):
442 """Construct a pipe for listing flows."""
443 if scan_dir:
444 pipe = scan(scan_dir=scan_dir)
445 elif opts.source:
446 pipe = scan_multi(
447 Path(path).expanduser()
448 for path in glbl_cfg().get(['install', 'source dirs'])
449 )
450 opts.states = {'stopped'}
451 else:
452 pipe = scan
453
454 show_running = 'running' in opts.states
455 show_paused = 'paused' in opts.states
456 show_active = show_running or show_paused or 'stopping' in opts.states
457 # show_active = bool({'running', 'paused'} & opts.states)
458 show_inactive = bool({'stopped'} & opts.states)
459
460 # filter by flow name
461 if opts.name:
462 pipe |= filter_name(*opts.name)
463
464 # filter by flow state
465 if show_active:
466 pipe |= is_active(True, filter_stop=(not show_inactive))
467 elif show_inactive:
468 pipe |= is_active(False)
469
470 # get contact file information
471 if show_active:
472 pipe |= contact_info
473
474 graphql_fields = {}
475 graphql_filters = set()
476
477 # filter paused/running flows
478 if show_active and not (show_running and show_paused):
479 graphql_fields['status'] = None
480 graphql_filters.add((('status',), tuple(opts.states)))
481
482 # get fancy data if requested
483 if formatter == _format_rich:
484 # graphql_fields['status'] = None
485 graphql_fields.update(RICH_FIELDS)
486
487 # add graphql queries / filters to the pipe
488 if show_active and graphql_fields:
489 pipe |= graphql_query(graphql_fields, filters=graphql_filters)
490 elif opts.ping:
491 # check the flow is running even if not required
492 # by display format or filters
493 pipe |= graphql_query({'status': None})
494
495 # yield results as they are processed
496 pipe.preserve_order = False
497
498 return pipe
499
500
501 def get_formatter(opts):
502 """Return the appropriate formatter and method for the provided opts."""
503 formatter = None
504 method = None
505
506 if opts.format == 'plain':
507 formatter = _format_plain
508 method = _async
509 elif opts.format == 'json':
510 formatter = _format_json
511 method = _serial
512 elif opts.format == 'rich':
513 formatter = _format_rich
514 method = _async
515 elif opts.format == 'tree':
516 formatter = _format_plain
517 method = _tree
518 elif opts.format == 'name': # noqa: SIM106
519 formatter = _format_name_only
520 method = _async
521 else:
522 raise NotImplementedError
523
524 if opts.sort and method == _serial:
525 raise ValueError(f'--sort is incompatible with --format {opts.format}')
526 elif opts.sort:
527 method = _sorted
528
529 return formatter, method
530
531
532 async def scanner(opts, write, scan_dir=None):
533 """Print workflows to stdout."""
534 formatter, method = get_formatter(opts)
535 pipe = get_pipe(opts, formatter, scan_dir)
536
537 LOG.debug(f'pipe: {repr(pipe)}')
538
539 await method(pipe, formatter, opts, write)
540
541
542 async def main(
543 opts: 'Values',
544 color: bool = False,
545 scan_dir: Optional[Path] = None,
546 write: Callable = cprint
547 ) -> None:
548 """Open up a Python API for testing purposes.
549
550 Note:
551 Don't use this API for anything other than testing, there is a
552 proper Python API for these purposes.
553
554 """
555 # validate / standardise the list of workflow states
556 opts.states = set(opts.states.split(','))
557 if 'all' in opts.states:
558 opts.states = FLOW_STATES
559 elif (
560 not opts.states
561 or not all(
562 state in FLOW_STATES
563 for state in opts.states
564 )
565 ):
566 raise InputError(
567 '--states must be a comma separated list of workflow states.'
568 '\nSee `cylc scan --help` for supported states.'
569 )
570
571 if not color:
572 # we cannot support colour or have been requested not to use it
573 opts.colour_blind = True
574
575 # print state totals key as needed
576 if opts.format == 'rich' and not opts.colour_blind:
577 cprint(state_totals_key() + '\n')
578
579 await scanner(opts, write, scan_dir)
580
581
582 @cli_function(get_option_parser)
583 def cli(_, opts: 'Values', color: bool) -> None:
584 """Implement `cylc scan`."""
585 asyncio.run(
586 main(opts, color)
587 )
588
589
590 ScanOptions = Options(get_option_parser())