1#!/usr/bin/env python3
2#
3# Copyright (C) 2023 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17# TODO(b/267675642): this is the sample code shared by QNX to convert traceprinter
18# output to json file. We will clean it up and improve it as we make changes.
19# For example:
20# Using stdlib to do the JSON conversion.
21# Add helper function for timestamp conversion.
22#
23# Usage:
24# python3 qnx_perfetto.py qnx_traceprinter_output_file qnx_trace.json
25#
26#
27import sys
28import re
29
30trace_input_regex = re.compile( r"(?P<CPU>\d+) (?P<time_s>\d+)\.(?P<time_ns>\d+)\.(?P<time_us>\d+)us (?P<etype>\w*) (?P<ename>\w*).*?pid:(?P<pid>\-?\d+)" )
31
32def main():
33    if len( sys.argv ) < 2:
34        print(f'Missing trace output path argument. Correct usage: {sys.argv[0]} <trace_output_path>')
35        sys.exit(1)
36
37    first_line_written = False
38    with open( sys.argv[1], 'r' ) as trace_input:
39        with open( '{}.json'.format( sys.argv[1] ), 'w' ) as converted_output:
40            converted_output.write( '{\n  "traceEvents": [' )
41            trace_lines = trace_input.readlines()
42            for (index, line) in enumerate( trace_lines ):
43                match = trace_input_regex.match(line)
44                if match != None:
45                    line_output = '"name": "{}", "cat": "{}", "ph": "i", "ts": {}, "pid": {}, "s": "g"'.format(
46                        match.group( 'ename' ),
47                        match.group( 'etype' ),
48                        (int(match.group( 'time_s' )) * 1000000) + (int(match.group( 'time_ns' )) * 1000) + int(match.group( 'time_us' )),
49                        int(match.group( 'pid' ))
50                    )
51
52                    if first_line_written  and index + 1 <= len( trace_lines ):
53                        converted_output.write( ',')
54                    converted_output.write( "\n    { " + line_output + " }" )
55                    first_line_written = True
56            converted_output.write( '\n]}\n' )
57
58if __name__ == '__main__':
59    main()
60