cli: add --test-compatibility option to check the trace only
[deliverable/lttng-analyses.git] / lttnganalyses / cli / command.py
CommitLineData
4ed24f86
JD
1# The MIT License (MIT)
2#
a3fa57c0 3# Copyright (C) 2015 - Julien Desfossez <jdesfossez@efficios.com>
cee855a2 4# 2015 - Philippe Proulx <pproulx@efficios.com>
0b250a71 5# 2015 - Antoine Busque <abusque@efficios.com>
4ed24f86
JD
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in
15# all copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
24
323b3fd6 25import argparse
a0acc08c 26import json
4ac5e240 27import os
a0acc08c 28import re
0b250a71
AB
29import sys
30import subprocess
31from babeltrace import TraceCollection
9079847d
AB
32from . import mi, progressbar
33from .. import _version, __version__
0b250a71 34from ..core import analysis
9079847d
AB
35from ..common import (
36 format_utils, parse_utils, time_utils, trace_utils, version_utils
37)
0b250a71 38from ..linuxautomaton import automaton
323b3fd6
PP
39
40
41class Command:
a0acc08c
PP
42 _MI_BASE_TAGS = ['linux-kernel', 'lttng-analyses']
43 _MI_AUTHORS = [
44 'Julien Desfossez',
45 'Antoine Busque',
46 'Philippe Proulx',
47 ]
48 _MI_URL = 'https://github.com/lttng/lttng-analyses'
49
50 def __init__(self, mi_mode=False):
b6d9132b
AB
51 self._analysis = None
52 self._analysis_conf = None
53 self._args = None
54 self._handles = None
55 self._traces = None
a0acc08c
PP
56 self._ticks = 0
57 self._mi_mode = mi_mode
323b3fd6 58 self._create_automaton()
a0acc08c
PP
59 self._mi_setup()
60
61 @property
62 def mi_mode(self):
63 return self._mi_mode
323b3fd6 64
b6d9132b 65 def run(self):
74d112b5
AB
66 try:
67 self._parse_args()
68 self._open_trace()
69 self._create_analysis()
ee39b192
PP
70
71 if self._mi_mode and not self._args.test_compatibility:
72 self._run_analysis()
73
74d112b5
AB
74 self._close_trace()
75 except KeyboardInterrupt:
76 sys.exit(0)
b6d9132b 77
8311b968
PP
78 def _mi_error(self, msg, code=None):
79 print(json.dumps(mi.get_error(msg, code)))
80
81 def _non_mi_error(self, msg):
d6c76c60
PP
82 try:
83 import termcolor
84
85 msg = termcolor.colored(msg, 'red', attrs=['bold'])
05684c5e 86 except ImportError:
d6c76c60
PP
87 pass
88
323b3fd6 89 print(msg, file=sys.stderr)
8311b968
PP
90
91 def _error(self, msg, code, exit_code=1):
92 if self._mi_mode:
93 self._mi_error(msg)
94 else:
95 self._non_mi_error(msg)
96
323b3fd6
PP
97 sys.exit(exit_code)
98
99 def _gen_error(self, msg, exit_code=1):
100 self._error('Error: {}'.format(msg), exit_code)
101
102 def _cmdline_error(self, msg, exit_code=1):
103 self._error('Command line error: {}'.format(msg), exit_code)
104
a0acc08c
PP
105 def _print(self, msg):
106 if not self._mi_mode:
107 print(msg)
108
109 def _mi_create_result_table(self, table_class_name, begin, end,
110 subtitle=None):
111 return mi.ResultTable(self._mi_table_classes[table_class_name],
112 begin, end, subtitle)
113
114 def _mi_setup(self):
115 self._mi_table_classes = {}
116
117 for tc_tuple in self._MI_TABLE_CLASSES:
118 table_class = mi.TableClass(tc_tuple[0], tc_tuple[1], tc_tuple[2])
119 self._mi_table_classes[table_class.name] = table_class
120
121 self._mi_clear_result_tables()
122
123 def _mi_print_metadata(self):
124 tags = self._MI_BASE_TAGS + self._MI_TAGS
125 infos = mi.get_metadata(version=self._MI_VERSION, title=self._MI_TITLE,
126 description=self._MI_DESCRIPTION,
127 authors=self._MI_AUTHORS, url=self._MI_URL,
128 tags=tags,
129 table_classes=self._mi_table_classes.values())
130 print(json.dumps(infos))
131
132 def _mi_append_result_table(self, result_table):
133 if not result_table or not result_table.rows:
134 return
135
136 tc_name = result_table.table_class.name
137 self._mi_get_result_tables(tc_name).append(result_table)
138
139 def _mi_append_result_tables(self, result_tables):
140 if not result_tables:
141 return
142
143 for result_table in result_tables:
144 self._mi_append_result_table(result_table)
145
146 def _mi_clear_result_tables(self):
147 self._result_tables = {}
148
149 def _mi_get_result_tables(self, table_class_name):
150 if table_class_name not in self._result_tables:
151 self._result_tables[table_class_name] = []
152
153 return self._result_tables[table_class_name]
154
155 def _mi_print(self):
156 results = []
157
158 for result_tables in self._result_tables.values():
159 for result_table in result_tables:
160 results.append(result_table.to_native_object())
161
162 obj = {
163 'results': results,
164 }
165
166 print(json.dumps(obj))
167
168 def _create_summary_result_tables(self):
169 pass
170
bd3cd7c5
JD
171 def _open_trace(self):
172 traces = TraceCollection()
b6d9132b 173 handles = traces.add_traces_recursive(self._args.path, 'ctf')
ced36aab 174 if handles == {}:
b6d9132b 175 self._gen_error('Failed to open ' + self._args.path, -1)
ced36aab 176 self._handles = handles
bd3cd7c5 177 self._traces = traces
dd2efe70
PP
178 self._ts_begin = traces.timestamp_begin
179 self._ts_end = traces.timestamp_end
652bc6b7 180 self._process_date_args()
ee6a5866 181 self._read_tracer_version()
b6d9132b 182 if not self._args.skip_validation:
d3014022 183 self._check_lost_events()
bd3cd7c5
JD
184
185 def _close_trace(self):
ced36aab
AB
186 for handle in self._handles.values():
187 self._traces.remove_trace(handle)
bd3cd7c5 188
ee6a5866 189 def _read_tracer_version(self):
4ac5e240 190 kernel_path = None
2dca9c55
JD
191 # remove the trailing /
192 while self._args.path.endswith('/'):
193 self._args.path = self._args.path[:-1]
4ac5e240
AB
194 for root, _, _ in os.walk(self._args.path):
195 if root.endswith('kernel'):
196 kernel_path = root
197 break
198
199 if kernel_path is None:
200 self._gen_error('Could not find kernel trace directory')
201
ee6a5866 202 try:
0349f942 203 ret, metadata = subprocess.getstatusoutput(
4ac5e240 204 'babeltrace -o ctf-metadata "%s"' % kernel_path)
ee6a5866
AB
205 except subprocess.CalledProcessError:
206 self._gen_error('Cannot run babeltrace on the trace, cannot read'
207 ' tracer version')
208
0349f942
JD
209 # fallback to reading the text metadata if babeltrace failed to
210 # output the CTF metadata
211 if ret != 0:
212 try:
213 metadata = subprocess.getoutput(
214 'cat "%s"' % os.path.join(kernel_path, 'metadata'))
215 except subprocess.CalledProcessError:
216 self._gen_error('Cannot read the metadata of the trace, cannot'
217 'extract tracer version')
218
219 major_match = re.search(r'tracer_major = "*(\d+)"*', metadata)
220 minor_match = re.search(r'tracer_minor = "*(\d+)"*', metadata)
221 patch_match = re.search(r'tracer_patchlevel = "*(\d+)"*', metadata)
ee6a5866
AB
222
223 if not major_match or not minor_match or not patch_match:
224 self._gen_error('Malformed metadata, cannot read tracer version')
225
226 self.state.tracer_version = version_utils.Version(
227 int(major_match.group(1)),
228 int(minor_match.group(1)),
229 int(patch_match.group(1)),
230 )
231
d3014022 232 def _check_lost_events(self):
73f9d005
PP
233 msg = 'Checking the trace for lost events...'
234 self._print(msg)
235
236 if self._mi_mode and self._args.output_progress:
237 mi.print_progress(0, msg)
238
d3014022 239 try:
e0bc16fe 240 subprocess.check_output('babeltrace "%s"' % self._args.path,
d3014022
JD
241 shell=True)
242 except subprocess.CalledProcessError:
b9f05f8d
AB
243 self._gen_error('Cannot run babeltrace on the trace, cannot verify'
244 ' if events were lost during the trace recording')
a0acc08c
PP
245
246 def _pre_analysis(self):
247 pass
248
249 def _post_analysis(self):
250 if not self._mi_mode:
251 return
252
253 if self._ticks > 1:
254 self._create_summary_result_tables()
255
256 self._mi_print()
d3014022 257
73f9d005 258 def _pb_setup(self):
dd2efe70
PP
259 if self._args.no_progress:
260 return
261
262 ts_end = self._ts_end
263
264 if self._analysis_conf.end_ts is not None:
265 ts_end = self._analysis_conf.end_ts
73f9d005 266
73f9d005 267 if self._mi_mode:
dd2efe70 268 cls = progressbar.MiProgress
73f9d005 269 else:
dd2efe70
PP
270 cls = progressbar.FancyProgressBar
271
272 self._progress = cls(self._ts_begin, ts_end, self._args.path,
273 self._args.progress_use_size)
274
275 def _pb_update(self, event):
276 if self._args.no_progress:
277 return
278
279 self._progress.update(event)
73f9d005
PP
280
281 def _pb_finish(self):
dd2efe70
PP
282 if self._args.no_progress:
283 return
284
285 self._progress.finalize()
73f9d005 286
b6d9132b 287 def _run_analysis(self):
a0acc08c 288 self._pre_analysis()
73f9d005 289 self._pb_setup()
b6d9132b 290
bd3cd7c5 291 for event in self._traces.events:
dd2efe70 292 self._pb_update(event)
bd3cd7c5 293 self._analysis.process_event(event)
b6d9132b
AB
294 if self._analysis.ended:
295 break
47ba125c 296 self._automaton.process_event(event)
bd3cd7c5 297
73f9d005 298 self._pb_finish()
b6d9132b 299 self._analysis.end()
a0acc08c 300 self._post_analysis()
bd3cd7c5 301
3664e4b0 302 def _print_date(self, begin_ns, end_ns):
9079847d
AB
303 time_range_str = format_utils.format_time_range(
304 begin_ns, end_ns, print_date=True, gmt=self._args.gmt
305 )
306 date = 'Timerange: {}'.format(time_range_str)
307
a0acc08c 308 self._print(date)
3664e4b0 309
9079847d
AB
310 def _format_timestamp(self, timestamp):
311 return format_utils.format_timestamp(
312 timestamp, print_date=self._args.multi_day, gmt=self._args.gmt
313 )
314
dbbdd963
PP
315 def _get_uniform_freq_values(self, durations):
316 if self._args.uniform_step is not None:
317 return (self._args.uniform_min, self._args.uniform_max,
318 self._args.uniform_step)
319
320 if self._args.min is not None:
321 self._args.uniform_min = self._args.min
322 else:
323 self._args.uniform_min = min(durations)
324 if self._args.max is not None:
325 self._args.uniform_max = self._args.max
326 else:
327 self._args.uniform_max = max(durations)
328
329 # ns to µs
330 self._args.uniform_min /= 1000
331 self._args.uniform_max /= 1000
332 self._args.uniform_step = (
333 (self._args.uniform_max - self._args.uniform_min) /
334 self._args.freq_resolution
335 )
336
337 return self._args.uniform_min, self._args.uniform_max, \
650e7f57 338 self._args.uniform_step
dbbdd963 339
bd3cd7c5 340 def _validate_transform_common_args(self, args):
83ad157b
AB
341 refresh_period_ns = None
342 if args.refresh is not None:
343 try:
9079847d 344 refresh_period_ns = parse_utils.parse_duration(args.refresh)
83ad157b
AB
345 except ValueError as e:
346 self._cmdline_error(str(e))
347
b6d9132b 348 self._analysis_conf = analysis.AnalysisConfig()
83ad157b 349 self._analysis_conf.refresh_period = refresh_period_ns
43a3c04c
AB
350 self._analysis_conf.period_begin_ev_name = args.period_begin
351 self._analysis_conf.period_end_ev_name = args.period_end
05684c5e 352 self._analysis_conf.period_begin_key_fields = \
007d3fe0 353 args.period_begin_key.split(',')
05684c5e
AB
354
355 if args.period_end_key:
356 self._analysis_conf.period_end_key_fields = \
007d3fe0 357 args.period_end_key.split(',')
05684c5e
AB
358 else:
359 self._analysis_conf.period_end_key_fields = \
007d3fe0 360 self._analysis_conf.period_begin_key_fields
05684c5e
AB
361
362 if args.period_key_value:
363 self._analysis_conf.period_key_value = \
007d3fe0 364 tuple(args.period_key_value.split(','))
05684c5e 365
a621ba35
AB
366 if args.cpu:
367 self._analysis_conf.cpu_list = args.cpu.split(',')
368 self._analysis_conf.cpu_list = [int(cpu) for cpu in
369 self._analysis_conf.cpu_list]
b6d9132b
AB
370
371 # convert min/max args from µs to ns, if needed
372 if hasattr(args, 'min') and args.min is not None:
373 args.min *= 1000
374 self._analysis_conf.min_duration = args.min
375 if hasattr(args, 'max') and args.max is not None:
376 args.max *= 1000
377 self._analysis_conf.max_duration = args.max
378
379 if hasattr(args, 'procname'):
47ba125c 380 if args.procname:
43b66dd6 381 self._analysis_conf.proc_list = args.procname.split(',')
28ad5ec8 382
43b66dd6
AB
383 if hasattr(args, 'tid'):
384 if args.tid:
385 self._analysis_conf.tid_list = args.tid.split(',')
386 self._analysis_conf.tid_list = [int(tid) for tid in
387 self._analysis_conf.tid_list]
f89605f0 388
1a68e04c
AB
389 if hasattr(args, 'freq'):
390 args.uniform_min = None
391 args.uniform_max = None
392 args.uniform_step = None
393
dbbdd963
PP
394 if args.freq_series:
395 # implies uniform buckets
396 args.freq_uniform = True
397
a0acc08c 398 if self._mi_mode:
1ab6b93a
PP
399 # print MI version if required
400 if args.mi_version:
401 print(mi.get_version_string())
402 sys.exit(0)
403
a0acc08c
PP
404 # print MI metadata if required
405 if args.metadata:
406 self._mi_print_metadata()
407 sys.exit(0)
408
409 # validate path argument (required at this point)
410 if not args.path:
411 self._cmdline_error('Please specify a trace path')
412
413 if type(args.path) is list:
414 args.path = args.path[0]
415
b6d9132b
AB
416 def _validate_transform_args(self, args):
417 pass
f89605f0 418
323b3fd6
PP
419 def _parse_args(self):
420 ap = argparse.ArgumentParser(description=self._DESC)
421
422 # common arguments
83ad157b
AB
423 ap.add_argument('-r', '--refresh', type=str,
424 help='Refresh period, with optional units suffix '
425 '(default units: s)')
a0acc08c
PP
426 ap.add_argument('--gmt', action='store_true',
427 help='Manipulate timestamps based on GMT instead '
428 'of local time')
73b71522 429 ap.add_argument('--skip-validation', action='store_true',
d3014022 430 help='Skip the trace validation')
bd3cd7c5
JD
431 ap.add_argument('--begin', type=str, help='start time: '
432 'hh:mm:ss[.nnnnnnnnn]')
433 ap.add_argument('--end', type=str, help='end time: '
434 'hh:mm:ss[.nnnnnnnnn]')
43a3c04c
AB
435 ap.add_argument('--period-begin', type=str,
436 help='Analysis period start marker event name')
437 ap.add_argument('--period-end', type=str,
438 help='Analysis period end marker event name '
439 '(requires --period-begin)')
05684c5e 440 ap.add_argument('--period-begin-key', type=str, default='cpu_id',
b9f05f8d
AB
441 help='Optional, list of event field names used to '
442 'match period markers (default: cpu_id)')
05684c5e
AB
443 ap.add_argument('--period-end-key', type=str,
444 help='Optional, list of event field names used to '
445 'match period marker. If none specified, use the same '
446 ' --period-begin-key')
447 ap.add_argument('--period-key-value', type=str,
448 help='Optional, define a fixed key value to which a'
449 ' period must correspond to be considered.')
a621ba35
AB
450 ap.add_argument('--cpu', type=str,
451 help='Filter the results only for this list of '
452 'CPU IDs')
a0acc08c
PP
453 ap.add_argument('--timerange', type=str, help='time range: '
454 '[begin,end]')
dd2efe70
PP
455 ap.add_argument('--progress-use-size', action='store_true',
456 help='use trace size to approximate progress')
323b3fd6 457 ap.add_argument('-V', '--version', action='version',
d97f5cb2 458 version='LTTng Analyses v' + __version__)
323b3fd6 459
a0acc08c
PP
460 # MI mode-dependent arguments
461 if self._mi_mode:
1ab6b93a
PP
462 ap.add_argument('--mi-version', action='store_true',
463 help='Print MI version')
a0acc08c 464 ap.add_argument('--metadata', action='store_true',
1ab6b93a 465 help='Print analysis\' metadata')
ee39b192
PP
466 ap.add_argument('--test-compatibility', action='store_true',
467 help='Check if the provided trace is supported and exit')
b9f05f8d
AB
468 ap.add_argument('path', metavar='<path/to/trace>',
469 help='trace path', nargs='*')
73f9d005
PP
470 ap.add_argument('--output-progress', action='store_true',
471 help='Print progress indication lines')
a0acc08c
PP
472 else:
473 ap.add_argument('--no-progress', action='store_true',
474 help='Don\'t display the progress bar')
b9f05f8d
AB
475 ap.add_argument('path', metavar='<path/to/trace>',
476 help='trace path')
a0acc08c 477
b6d9132b
AB
478 # Used to add command-specific args
479 self._add_arguments(ap)
323b3fd6 480
b6d9132b 481 args = ap.parse_args()
dd2efe70
PP
482
483 if self._mi_mode:
484 args.no_progress = True
485
486 if args.output_progress:
487 args.no_progress = False
488
bd3cd7c5 489 self._validate_transform_common_args(args)
b6d9132b 490 self._validate_transform_args(args)
323b3fd6
PP
491 self._args = args
492
b6d9132b
AB
493 @staticmethod
494 def _add_proc_filter_args(ap):
495 ap.add_argument('--procname', type=str,
496 help='Filter the results only for this list of '
497 'process names')
43b66dd6
AB
498 ap.add_argument('--tid', type=str,
499 help='Filter the results only for this list of TIDs')
b6d9132b
AB
500
501 @staticmethod
502 def _add_min_max_args(ap):
503 ap.add_argument('--min', type=float,
504 help='Filter out durations shorter than min usec')
505 ap.add_argument('--max', type=float,
506 help='Filter out durations longer than max usec')
507
508 @staticmethod
509 def _add_freq_args(ap, help=None):
510 if not help:
511 help = 'Output the frequency distribution'
512
513 ap.add_argument('--freq', action='store_true', help=help)
514 ap.add_argument('--freq-resolution', type=int, default=20,
515 help='Frequency distribution resolution '
516 '(default 20)')
1a68e04c
AB
517 ap.add_argument('--freq-uniform', action='store_true',
518 help='Use a uniform resolution across distributions')
86ea0394 519 ap.add_argument('--freq-series', action='store_true',
650e7f57
AB
520 help='Consolidate frequency distribution histogram '
521 'as a single one')
b6d9132b
AB
522
523 @staticmethod
524 def _add_log_args(ap, help=None):
525 if not help:
526 help = 'Output the events in chronological order'
527
528 ap.add_argument('--log', action='store_true', help=help)
529
b9f05f8d
AB
530 @staticmethod
531 def _add_top_args(ap, help=None):
532 if not help:
533 help = 'Output the top results'
534
535 ap.add_argument('--limit', type=int, default=10,
536 help='Limit to top X (default = 10)')
537 ap.add_argument('--top', action='store_true', help=help)
538
b6d9132b
AB
539 @staticmethod
540 def _add_stats_args(ap, help=None):
541 if not help:
542 help = 'Output statistics'
543
544 ap.add_argument('--stats', action='store_true', help=help)
545
546 def _add_arguments(self, ap):
547 pass
548
652bc6b7 549 def _process_date_args(self):
9079847d
AB
550 def parse_date(date):
551 try:
552 ts = parse_utils.parse_trace_collection_date(
553 self._traces, date, self._args.gmt
554 )
555 except ValueError as e:
556 self._cmdline_error(str(e))
b6d9132b
AB
557
558 return ts
559
9079847d
AB
560 self._args.multi_day = trace_utils.is_multi_day_trace_collection(
561 self._traces
562 )
602ac199
PP
563 begin_ts = None
564 end_ts = None
565
566 if self._args.timerange:
9079847d
AB
567 try:
568 begin_ts, end_ts = (
569 parse_utils.parse_trace_collection_time_range(
570 self._traces, self._args.timerange, self._args.gmt
571 )
572 )
573 except ValueError as e:
574 self._cmdline_error(str(e))
652bc6b7 575 else:
b6d9132b 576 if self._args.begin:
9079847d 577 begin_ts = parse_date(self._args.begin)
b6d9132b 578 if self._args.end:
9079847d 579 end_ts = parse_date(self._args.end)
652bc6b7 580
93c7af7d
AB
581 # We have to check if timestamp_begin is None, which
582 # it always is in older versions of babeltrace. In
583 # that case, the test is simply skipped and an invalid
584 # --end value will cause an empty analysis
dd2efe70
PP
585 if self._ts_begin is not None and \
586 end_ts < self._ts_begin:
b6d9132b
AB
587 self._cmdline_error(
588 '--end timestamp before beginning of trace')
589
602ac199
PP
590 self._analysis_conf.begin_ts = begin_ts
591 self._analysis_conf.end_ts = end_ts
b6d9132b
AB
592
593 def _create_analysis(self):
594 notification_cbs = {
a0acc08c 595 analysis.Analysis.TICK_CB: self._analysis_tick_cb
b6d9132b
AB
596 }
597
598 self._analysis = self._ANALYSIS_CLASS(self.state, self._analysis_conf)
599 self._analysis.register_notification_cbs(notification_cbs)
93c7af7d 600
323b3fd6 601 def _create_automaton(self):
56936af2 602 self._automaton = automaton.Automaton()
6e01ed18 603 self.state = self._automaton.state
bfb81992 604
a0acc08c 605 def _analysis_tick_cb(self, **kwargs):
b6d9132b
AB
606 begin_ns = kwargs['begin_ns']
607 end_ns = kwargs['end_ns']
608
a0acc08c
PP
609 self._analysis_tick(begin_ns, end_ns)
610 self._ticks += 1
b6d9132b 611
a0acc08c 612 def _analysis_tick(self, begin_ns, end_ns):
b6d9132b
AB
613 raise NotImplementedError()
614
a0acc08c
PP
615
616# create MI version
617_cmd_version = _version.get_versions()['version']
618_version_match = re.match(r'(\d+)\.(\d+)\.(\d+)(.*)', _cmd_version)
3101128e 619Command._MI_VERSION = version_utils.Version(
a0acc08c
PP
620 int(_version_match.group(1)),
621 int(_version_match.group(2)),
622 int(_version_match.group(3)),
623 _version_match.group(4),
3101128e 624)
This page took 0.081454 seconds and 5 git commands to generate.