Debian Codegraph @

cylc/flow/scripts/report_timings.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 report-timings [OPTIONS] ARGS
20
21 Display workflow timing information.
22
23 Retrieve workflow timing information for wait and run time performance
24 analysis. Raw output and summary output (in text or HTML format) are available.
25 Output is sent to standard output, unless an output filename is supplied.
26
27 Summary Output (the default):
28 Data stratified by host and job runner that provides a statistical
29 summary of:
30 1. Queue wait time (duration between task submission and start times)
31 2. Task run time (duration between start and succeed times)
32 3. Total run time (duration between task submission and succeed times)
33 Summary tables can be output in plain text format, or HTML with embedded SVG
34 boxplots. Both summary options require the Pandas library, and the HTML
35 summary option requires the Matplotlib library.
36
37 Raw Output:
38 A flat list of tabular data that provides (for each task and cycle) the
39 1. Time of successful submission
40 2. Time of task start
41 3. Time of task successful completion
42 as well as information about the job runner and remote host to permit
43 stratification/grouping if desired by downstream processors.
44
45 Timings are shown only for succeeded tasks.
46
47 For long-running or large workflows (i.e. workflows with many task events),
48 the database query to obtain the timing information may take some time.
49 """
50
51 import contextlib
52 import io as StringIO
53 import sys
54 from collections import Counter
55 from typing import TYPE_CHECKING
56
57 from cylc.flow import LOG
58 from cylc.flow.exceptions import CylcError
59 from cylc.flow.id_cli import parse_id
60 from cylc.flow.option_parsers import (
61 WORKFLOW_ID_ARG_DOC,
62 CylcOptionParser as COP,
63 )
64 from cylc.flow.pathutil import get_workflow_run_pub_db_path
65 from cylc.flow.rundb import CylcWorkflowDAO
66 from cylc.flow.terminal import cli_function
67
68
69 if TYPE_CHECKING:
70 from optparse import Values
71
72
73 @contextlib.contextmanager
74 def smart_open(filename=None):
75 """
76 Allow context management for output to either a file or
77 to standard output transparently.
78
79 See https://stackoverflow.com/a/17603000
80
81 """
82 if filename and filename != '-':
83 fh = open(filename, 'w') # noqa SIM115 (close done in finally block)
84 else:
85 fh = sys.stdout
86 try:
87 yield fh
88 finally:
89 if fh is not sys.stdout:
90 fh.close()
91
92
93 def get_option_parser() -> COP:
94 parser = COP(
95 __doc__,
96 argdoc=[WORKFLOW_ID_ARG_DOC]
97 )
98 parser.add_option(
99 "-r", "--raw",
100 help="Show raw timing output suitable for custom diagnostics.",
101 action="store_true", default=False, dest="show_raw"
102 )
103 parser.add_option(
104 "-s", "--summary",
105 help="Show textual summary timing output for tasks.",
106 action="store_true", default=False, dest="show_summary"
107 )
108 parser.add_option(
109 "-w", "--web-summary",
110 help="Show HTML summary timing output for tasks.",
111 action="store_true", default=False, dest="html_summary"
112 )
113 parser.add_option(
114 "-O", "--output-file",
115 help="Output to a specific file",
116 action="store", default=None, dest="output_filename")
117
118 return parser
119
120
121 @cli_function(get_option_parser)
122 def main(parser: COP, options: 'Values', workflow_id: str) -> None:
123 workflow_id, *_ = parse_id(
124 workflow_id,
125 constraint='workflows',
126 )
127
128 LOG.warning(
129 "cylc report-timings is deprecated."
130 " The analysis view in the GUI provides"
131 " similar functionality."
132 )
133
134 output_options = [
135 options.show_raw, options.show_summary, options.html_summary
136 ]
137 if output_options.count(True) > 1:
138 parser.error('Cannot combine output formats (choose one)')
139 if not any(output_options):
140 # No output specified - choose summary by default
141 options.show_summary = True
142
143 db_file = get_workflow_run_pub_db_path(workflow_id)
144 with CylcWorkflowDAO(db_file, is_public=True) as dao:
145 row_buf = format_rows(*dao.select_task_times())
146 with smart_open(options.output_filename) as output:
147 if options.show_raw:
148 output.write(row_buf.getvalue())
149 else:
150 summary: TimingSummary
151 if options.show_summary:
152 summary = TextTimingSummary(row_buf)
153 elif options.html_summary:
154 summary = HTMLTimingSummary(row_buf)
155 summary.write_summary(output)
156
157
158 def format_rows(header, rows):
159 """Write the rows in tabular format to a string buffer.
160
161 Ensure that each column is wide enough to contain the widest data
162 value and the widest header value.
163
164 """
165 sio = StringIO.StringIO()
166 max_lengths = [
167 max(data_len, head_len)
168 for data_len, head_len in zip(
169 (max(len(r[i]) for r in rows) for i in range(len(header))),
170 (len(h) for h in header)
171 )
172 ]
173 formatter = ' '.join('%%-%ds' % line for line in max_lengths) + '\n'
174 sio.write(formatter % header)
175 for r in rows:
176 sio.write(formatter % r)
177 sio.seek(0)
178 return sio
179
180
181 class TimingSummary:
182 """Base class for summarizing timing output from cylc.flow run database."""
183
184 def __init__(self, filepath_or_buffer=None):
185 """Set up internal dataframe storage for time durations."""
186
187 self._check_imports()
188 if filepath_or_buffer is not None:
189 self.read_timings(filepath_or_buffer)
190 else:
191 self.df = None
192 self.by_host_and_job_runner = None
193
194 def read_timings(self, filepath_or_buffer):
195 """
196 Set up time duration dataframe storage based on start/stop/succeed
197 times from flat database output.
198
199 """
200 import pandas as pd
201
202 # Avoid truncation of content in columns.
203 pd.set_option('display.max_colwidth', 10000)
204
205 df = pd.read_csv(
206 filepath_or_buffer, delim_whitespace=True, index_col=[0, 1, 2, 3],
207 parse_dates=[4, 5, 6]
208 )
209 self.df = pd.DataFrame({
210 'queue_time': (
211 df['start_time'] - df['submit_time']).apply(self._dt_to_s),
212 'run_time': (
213 df['succeed_time'] - df['start_time']).apply(self._dt_to_s),
214 'total_time': (
215 df['succeed_time'] - df['submit_time']).apply(self._dt_to_s),
216 })
217 self.df = self.df.rename_axis('timing_category', axis='columns')
218 self.by_host_and_job_runner = self.df.groupby(
219 level=['host', 'job_runner']
220 )
221
222 def write_summary(self, buf=None):
223 """Using the stored timings dataframe, output the data summary."""
224
225 if buf is None:
226 buf = sys.stdout
227 self.write_summary_header(buf)
228 for group, df in self.by_host_and_job_runner:
229 self.write_group_header(buf, group)
230 df_reshape = self._reshape_timings(df)
231 df_describe = df.groupby(level='name').describe()
232 if df_describe.index.nlevels > 1:
233 df_describe = df_describe.unstack() # for pandas < 0.20.0
234 df_describe.index.rename(None, inplace=True)
235 for timing_category in self.df.columns:
236 self.write_category(
237 buf, timing_category, df_reshape, df_describe
238 )
239 self.write_summary_footer(buf)
240
241 def write_summary_header(self, buf):
242 pass
243
244 def write_summary_footer(self, buf):
245 pass
246
247 def write_group_header(self, buf, group):
248 pass
249
250 def write_category(self, buf, category, df_reshape, df_describe):
251 pass
252
253 def _check_imports(self):
254 try:
255 import pandas
256 except ImportError:
257 raise CylcError(
258 'Cannot import pandas - summary unavailable.'
259 ' try: pip install cylc-flow[report-timings]'
260 ) from None
261 else:
262 del pandas
263
264 @staticmethod
265 def _reshape_timings(timings):
266 """
267 Given a dataframe of timings returned from the Cylc DAO methods
268 indexed by (task, cycle point, ...) with columns for the various
269 timing categories, return a dataframe reshaped with an index of
270 (timing category, cycle point, ...) with columns for each task.
271
272 Need a special method rather than standard Pandas pivot-table
273 to handle duplicated index entries properly.
274
275 """
276 if timings.index.duplicated().any():
277 # The 'unstack' used to pivot the dataframe gives an error if
278 # there are duplicate entries in the index (see #2509). The
279 # best way around this seems to be to add an intermediate index
280 # level (in this case a retry counter) to de-duplicate indices.
281 counts = Counter()
282 retry = []
283 for t in timings.index:
284 counts[t] += 1
285 retry.append(counts[t])
286 timings = timings.assign(retry=retry)
287 timings = timings.set_index('retry', append=True)
288
289 return timings.unstack('name').stack(level=0)
290
291 @staticmethod
292 def _dt_to_s(dt):
293 import pandas as pd
294 try:
295 return dt.total_seconds()
296 except AttributeError:
297 # Older versions of pandas have the timedelta as a numpy
298 # timedelta64 type, which didn't support total_seconds
299 return pd.Timedelta(dt).total_seconds()
300
301
302 class TextTimingSummary(TimingSummary):
303 """Timing summary in text form."""
304
305 line_width = 80
306
307 def write_group_header(self, buf, group):
308 title = 'Host: %s\tJob Runner: %s' % group
309 buf.write('=' * self.line_width + '\n')
310 buf.write(title.center(self.line_width - 1) + '\n')
311 buf.write('=' * self.line_width + '\n')
312
313 def write_category(self, buf, category, df_reshape, df_describe):
314 buf.write(category.center(self.line_width) + '\n')
315 buf.write(('-' * len(category)).center(self.line_width) + '\n')
316 buf.write(df_describe[category].to_string())
317 buf.write('\n\n')
318
319
320 class HTMLTimingSummary(TimingSummary):
321 """Timing summary in HTML form."""
322
323 def write_summary_header(self, buf):
324 css = """
325 body {
326 font-family: Sans-Serif;
327 text-align: center;
328 }
329 h1 {
330 background-color: grey;
331 }
332 h2 {
333 width: 85%;
334 background-color: #f0f0f0;
335 margin: auto;
336 }
337 table {
338 width: 75%;
339 margin: auto;
340 border-collapse: collapse;
341 }
342 tr:nth-child(even) {
343 background-color: #f2f2f2;
344 }
345 td {
346 text-align: right;
347 }
348 th, td {
349 border-bottom: 1px solid grey;
350 }
351 svg {
352 width: 65%;
353 height: auto;
354 margin: auto;
355 display: block;
356 }
357 .timing {
358 padding-bottom: 40px;
359 }
360 """
361
362 buf.write('<html><head><style>%s</style></head><body>' % css)
363
364 def write_summary_footer(self, buf):
365 buf.write('</body></html>')
366
367 def write_group_header(self, buf, group):
368 buf.write('<h1>Timings for host %s using job runner %s</h1>' % group)
369
370 def write_category(self, buf, category, df_reshape, df_describe):
371 import matplotlib.pyplot as plt
372 buf.write('<div class="timing" id=%s>' % category)
373 buf.write('<h2>%s</h2>\n' % (category.replace('_', ' ').title()))
374 ax = (
375 df_reshape
376 .xs(category, level='timing_category')
377 .plot(kind='box', vert=False)
378 )
379 ax.invert_yaxis()
380 ax.set_xlabel('Seconds')
381 plt.tight_layout()
382 plt.gcf().savefig(buf, format='svg')
383 try:
384 table = df_describe[category].to_html(
385 classes="summary", index_names=False, border=0
386 )
387 except TypeError:
388 # older pandas don't support the "border" argument
389 # so explicitly remove it
390 table = df_describe[category].to_html(
391 classes="summary", index_names=False
392 )
393 table = table.replace('border="1"', '')
394 buf.write(table)
395 buf.write('</div>')
396 pass
397
398 def _check_imports(self):
399 try:
400 import matplotlib
401 matplotlib.use('Agg')
402 except ImportError:
403 raise CylcError(
404 'Cannot import matplotlib - HTML summary unavailable.'
405 ) from None
406 super(HTMLTimingSummary, self)._check_imports()