Debian Codegraph @

cylc/flow/scripts/graph.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 graph [OPTIONS] ARGS
20
21 Produces graphical and textual representations of workflow dependencies.
22
23 Examples:
24 # generate a graphical representation of workflow dependencies
25 # (requires graphviz to be installed in the Cylc environment)
26 $ cylc graph one
27
28 # print a textual representation of the graph of the flow one
29 $ cylc graph one --reference
30
31 # display the difference between the flows one and two
32 $ cylc graph one --diff two
33
34 # render the graph to a svg file
35 $ cylc graph one -o 'one.svg'
36 """
37
38 import asyncio
39 from difflib import unified_diff
40 from pathlib import Path
41 from shutil import which
42 from subprocess import Popen, PIPE
43 import sys
44 from tempfile import NamedTemporaryFile
45 from typing import Dict, List, Optional, TYPE_CHECKING, Tuple, Callable
46
47 from ansimarkup import ansiprint as cprint
48
49 from cylc.flow.config import WorkflowConfig
50 from cylc.flow.exceptions import InputError, CylcError
51 from cylc.flow.id import Tokens
52 from cylc.flow.id_cli import parse_id_async
53 from cylc.flow.option_parsers import (
54 AGAINST_SOURCE_OPTION,
55 WORKFLOW_ID_OR_PATH_ARG_DOC,
56 CylcOptionParser as COP,
57 icp_option,
58 )
59 from cylc.flow.pathutil import get_workflow_run_dir
60 from cylc.flow.templatevars import get_template_vars
61 from cylc.flow.terminal import cli_function
62
63 if TYPE_CHECKING:
64 from optparse import Values
65
66
67 def sort_integer_node(id_):
68 """Return sort tokens for nodes with cyclepoints in integer format.
69
70 Example:
71 >>> sort_integer_node('11/foo')
72 ('foo', 11)
73
74 """
75 tokens = Tokens(id_, relative=True)
76 return (tokens['task'], int(tokens['cycle']))
77
78
79 def sort_integer_edge(id_):
80 """Return sort tokens for edges with cyclepoints in integer format.
81
82 Example:
83 >>> sort_integer_edge(('11/foo', '12/foo', None))
84 (('foo', 11), ('foo', 12))
85 >>> sort_integer_edge(('11/foo', None , None))
86 (('foo', 11), ('', 0))
87
88 """
89
90 return (
91 sort_integer_node(id_[0]),
92 sort_integer_node(id_[1]) if id_[1] else ('', 0)
93 )
94
95
96 def sort_datetime_edge(item):
97 """Return sort tokens for edges with cyclepoints in ISO8601 format.
98
99 Example:
100 >>> sort_datetime_edge(('a', None, None))
101 ('a', '')
102
103 """
104 return (item[0], item[1] or '')
105
106
107 # node/edge types
108 Node = str # node ID
109 Edge = Tuple[str, str] # left, right
110
111
112 def get_nodes_and_edges(
113 opts,
114 workflow_id,
115 start,
116 stop,
117 flow_file,
118 ) -> Tuple[List[Node], List[Edge]]:
119 """Return graph sorted nodes and edges."""
120 config = get_config(workflow_id, opts, flow_file)
121 if opts.namespaces:
122 nodes, edges = _get_inheritance_nodes_and_edges(config)
123 else:
124 nodes, edges = _get_graph_nodes_edges(
125 config,
126 start,
127 stop,
128 grouping=opts.grouping,
129 show_suicide=opts.show_suicide,
130 )
131 return nodes, edges
132
133
134 def _get_graph_nodes_edges(
135 config,
136 start_point_str=None,
137 stop_point_str=None,
138 grouping=None,
139 show_suicide=False,
140 ) -> Tuple[List[Node], List[Edge]]:
141 """Return nodes and edges for a workflow graph."""
142 graph = config.get_graph_raw(
143 start_point_str,
144 stop_point_str,
145 grouping
146 )
147 if not graph:
148 return [], []
149
150 # set sort keys based on cycling mode
151 # (note sorting is very important for the reference format)
152 node_sort: Optional[Callable]
153 edge_sort: Optional[Callable]
154 if config.cfg['scheduling']['cycling mode'] == 'integer':
155 # integer sorting
156 node_sort = sort_integer_node
157 edge_sort = sort_integer_edge
158 else:
159 # datetime sorting
160 node_sort = None # lexicographically sortable
161 edge_sort = sort_datetime_edge
162
163 # get nodes
164 nodes = sorted(
165 {
166 node
167 for left, right, _, suicide, _ in graph
168 for node in (left, right)
169 if node
170 if show_suicide or not suicide
171 },
172 key=node_sort,
173 )
174
175 # get edges
176 edges = sorted(
177 {
178 (left, right)
179 for left, right, _, suicide, _ in graph
180 if right
181 if show_suicide or not suicide
182 },
183 key=edge_sort,
184 )
185
186 return nodes, edges
187
188
189 def _get_inheritance_nodes_and_edges(
190 config
191 ) -> Tuple[List[Node], List[Edge]]:
192 """Return nodes and edges for an inheritance graph."""
193 nodes = set()
194 edges = set()
195 for namespace, tasks in config.get_parent_lists().items():
196 nodes.add(namespace)
197 for task in tasks:
198 edges.add((task, namespace))
199 nodes.add(task)
200
201 return sorted(nodes), sorted(edges)
202
203
204 def get_config(workflow_id: str, opts: 'Values', flow_file) -> WorkflowConfig:
205 """Return a WorkflowConfig object for the provided id_ / path."""
206 template_vars = get_template_vars(opts)
207 return WorkflowConfig(
208 workflow_id, flow_file, opts, template_vars=template_vars
209 )
210
211
212 def format_graphviz(
213 opts,
214 nodes: List[Node],
215 edges: List[Edge],
216 ) -> List[str]:
217 """Write graph in graphviz format."""
218 # write graph header
219 dot_lines = [
220 'digraph {',
221 ' graph [fontname="sans" fontsize="25"]',
222 ' node [fontname="sans"]',
223 ]
224 if opts.transpose:
225 dot_lines.append(' rankdir="LR"')
226 if opts.namespaces:
227 dot_lines.append(' node [shape="rect"]')
228 dot_lines.append('')
229
230 # write nodes
231 if opts.namespaces:
232 dot_lines.extend([
233 rf' "{node}"'
234 for node in nodes
235 ])
236 dot_lines.append('')
237 else:
238 # group by cycle
239 cycles: Dict[str, List[str]] = {}
240 for node in nodes:
241 tokens = Tokens(node, relative=True)
242 cycle: str = tokens['cycle']
243 task: str = tokens['task']
244 cycles.setdefault(cycle, []).append(task)
245 # write nodes by cycle
246 if opts.cycles:
247 indent = ' '
248 else:
249 indent = ' '
250 for cycle, tasks in cycles.items():
251 if opts.cycles:
252 dot_lines.extend(
253 [
254 f' subgraph "cluster_{cycle}" {{ ',
255 f' label="{cycle}"',
256 ' style="dashed"',
257 ]
258 )
259 dot_lines.extend(
260 rf'{indent}"{cycle}/{task}" [label="{task}\n{cycle}"]'
261 for task in tasks
262 )
263 if opts.cycles:
264 dot_lines.append(' }')
265 dot_lines.append('')
266
267 # write edges
268 for left, right in edges:
269 dot_lines.append(f' "{left}" -> "{right}"')
270
271 # close graph
272 dot_lines.append('}')
273
274 return dot_lines
275
276
277 def format_cylc_reference(
278 opts,
279 nodes: List[Node],
280 edges: List[Edge],
281 ) -> List[str]:
282 """Write graph in cylc reference format."""
283 lines = []
284 # write edges
285 for left, right in edges:
286 lines.append(f'edge "{left}" "{right}"')
287
288 # write separator
289 lines.append('graph')
290
291 # write nodes
292 if opts.namespaces:
293 for node in nodes:
294 lines.append(f'node "{node}" "{node}"')
295 else:
296 for node in nodes:
297 tokens = Tokens(node, relative=True)
298 lines.append(
299 f'node "{node}" "{tokens["task"]}\\n{tokens["cycle"]}"'
300 )
301
302 # write terminator
303 lines.append('stop')
304
305 return lines
306
307
308 def render_dot(dot_lines, filename, fmt):
309 """Render graph using `dot`."""
310 # check graphviz-dot is installed
311 if not which('dot'):
312 sys.exit('Graphviz must be installed to render graphs.')
313
314 # render graph with graphviz
315 proc = Popen( # nosec
316 ['dot', f'-T{fmt}', '-o', filename],
317 stdin=PIPE,
318 text=True
319 )
320 proc.communicate('\n'.join(dot_lines))
321 proc.wait()
322 if proc.returncode:
323 raise CylcError('Graphing Failed')
324
325
326 def open_image(filename):
327 """Open an image file."""
328 try:
329 from PIL import Image
330 except ModuleNotFoundError:
331 # dependencies required to display images not present
332 pass
333 else:
334 img = Image.open(filename)
335 img.show()
336
337
338 def graph_render(opts, workflow_id, start, stop, flow_file) -> int:
339 """Render the workflow graph to the specified format.
340
341 Graph is rendered to the specified format. The Graphviz "dot" format
342 does not require Graphviz to be installed.
343
344 All other formats require Graphviz. Supported formats depend on your
345 Graphviz installation.
346 """
347 # get nodes and edges
348 nodes, edges = get_nodes_and_edges(
349 opts,
350 workflow_id,
351 start,
352 stop,
353 flow_file
354 )
355
356 if not nodes:
357 msg = 'No tasks to display.'
358 if start or stop:
359 msg += ' Try changing the start and stop values.'
360 cprint(f'<red>{msg}</red>', file=sys.stderr)
361 return 1
362
363 # format the graph in graphviz-dot format
364 dot_lines = format_graphviz(opts, nodes, edges)
365
366 # set filename and output format
367 if opts.output:
368 filename = opts.output
369 try:
370 fmt = filename.rsplit('.', 1)[1]
371 except IndexError:
372 cprint(
373 '<red>Output filename requires a format.</red>',
374 file=sys.stderr,
375 )
376 return 1
377 else:
378 filename = NamedTemporaryFile().name
379 fmt = 'png'
380
381 if fmt == 'dot':
382 # output in dot format (graphviz not needed for this)
383 with open(filename, 'w+') as dot_file:
384 dot_file.write('\n'.join(dot_lines) + '\n')
385 return 0
386
387 # render with graphviz
388 render_dot(dot_lines, filename, fmt)
389
390 # notify the user / open the graph
391 cprint(f'<green>Graph rendered to {opts.output or filename}</green>')
392 if not opts.output:
393 open_image(filename)
394 return 0
395
396
397 def graph_reference(
398 opts, workflow_id, start, stop, flow_file, write=print,
399 ) -> int:
400 """Format the workflow graph using the cylc reference format."""
401 # get nodes and edges
402 nodes, edges = get_nodes_and_edges(
403 opts,
404 workflow_id,
405 start,
406 stop,
407 flow_file
408 )
409 for line in format_cylc_reference(opts, nodes, edges):
410 write(line)
411
412 return 0
413
414
415 async def graph_diff(
416 opts, workflow_a, workflow_b, start, stop, flow_file
417 ) -> int:
418 """Difference the workflow graphs using the cylc reference format."""
419
420 workflow_b, _, flow_file_b = await parse_id_async(
421 workflow_b,
422 src=True,
423 constraint='workflows',
424 )
425
426 # load graphs
427 graph_a: List[str] = []
428 graph_b: List[str] = []
429 graph_reference(
430 opts,
431 workflow_a,
432 start,
433 stop,
434 flow_file,
435 write=graph_a.append,
436 )
437 graph_reference(
438 opts,
439 workflow_b,
440 start,
441 stop,
442 flow_file_b,
443 write=graph_b.append,
444 )
445
446 # compare graphs
447 diff_lines = list(
448 unified_diff(
449 [f'{line}\n' for line in graph_a],
450 [f'{line}\n' for line in graph_b],
451 fromfile=workflow_a,
452 tofile=workflow_b,
453 )
454 )
455
456 # return results
457 if diff_lines:
458 sys.stdout.writelines(diff_lines)
459 return 1
460 return 0
461
462
463 def get_option_parser() -> COP:
464 """CLI."""
465 parser = COP(
466 __doc__,
467 jset=True,
468 argdoc=[
469 WORKFLOW_ID_OR_PATH_ARG_DOC,
470 COP.optional(
471 ('START', 'Graph start; defaults to initial cycle point')
472 ),
473 COP.optional((
474 'STOP',
475 'Graph stop point or interval; defaults to 3 points from START'
476 ))
477 ]
478 )
479
480 parser.add_option(
481 '-g', '--group',
482 help="task family to group. Can be used multiple times. "
483 "Use '<all>' to specify all families above root.",
484 action='append', default=[], dest='grouping')
485
486 parser.add_option(
487 '-c', '--cycles',
488 help='Group tasks by cycle point.',
489 action='store_true',
490 default=False,
491 )
492
493 parser.add_option(
494 '-t', '--transpose',
495 help='Transpose graph.',
496 action='store_true',
497 default=False,
498 )
499
500 parser.add_option(
501 '-o',
502 help=(
503 'Output the graph to a file. The file extension determines the'
504 ' format. E.G. "graph.png", "graph.svg", "graph.dot".'
505 ),
506 action='store',
507 dest='output'
508 )
509
510 parser.add_option(
511 '-n', '--namespaces',
512 help='Plot the workflow namespace inheritance hierarchy '
513 '(task run time properties).',
514 action='store_true', default=False, dest='namespaces')
515
516 parser.add_option(
517 '-r', '--reference',
518 help='Output in a sorted plain text format for comparison purposes. '
519 'If not given, assume --output-file=-.',
520 action='store_true', default=False, dest='reference')
521
522 parser.add_option(
523 '--show-suicide',
524 help='Show suicide triggers. Not shown by default.',
525 action='store_true', default=False, dest='show_suicide')
526
527 parser.add_option(icp_option)
528
529 parser.add_option(
530 '--diff',
531 help='Show the difference between two workflows (implies --reference)',
532 action='store',
533 )
534
535 parser.add_option(
536 *AGAINST_SOURCE_OPTION.args, **AGAINST_SOURCE_OPTION.kwargs)
537
538 parser.add_cylc_rose_options()
539
540 return parser
541
542
543 @cli_function(get_option_parser)
544 def main(
545 parser: COP,
546 opts: 'Values',
547 workflow_id: str,
548 start: Optional[str] = None,
549 stop: Optional[str] = None
550 ) -> None:
551 result = asyncio.run(_main(opts, workflow_id, start, stop))
552 sys.exit(result)
553
554
555 async def _main(
556 opts: 'Values',
557 workflow_id: str,
558 start: Optional[str] = None,
559 stop: Optional[str] = None
560 ) -> int:
561 """Implement ``cylc graph``."""
562 if opts.grouping and opts.namespaces:
563 raise InputError('Cannot combine --group and --namespaces.')
564 if opts.cycles and opts.namespaces:
565 raise InputError('Cannot combine --cycles and --namespaces.')
566
567 workflow_id, _, flow_file = await parse_id_async(
568 workflow_id,
569 src=True,
570 constraint='workflows',
571 )
572
573 # Save the location of the existing workflow run dir in the
574 # against source option:
575 if opts.against_source:
576 opts.against_source = Path(get_workflow_run_dir(workflow_id))
577
578 if opts.diff:
579 return await graph_diff(
580 opts, workflow_id, opts.diff, start, stop, flow_file)
581 if opts.reference:
582 return graph_reference(
583 opts, workflow_id, start, stop, flow_file)
584
585 return graph_render(opts, workflow_id, start, stop, flow_file)