1# flamegraph.py - create flame graphs from perf samples
2# SPDX-License-Identifier: GPL-2.0
3#
4# Usage:
5#
6#     perf record -a -g -F 99 sleep 60
7#     perf script report flamegraph
8#
9# Combined:
10#
11#     perf script flamegraph -a -F 99 sleep 60
12#
13# Written by Andreas Gerstmayr <agerstmayr@redhat.com>
14# Flame Graphs invented by Brendan Gregg <bgregg@netflix.com>
15# Works in tandem with d3-flame-graph by Martin Spier <mspier@netflix.com>
16
17from __future__ import print_function
18import sys
19import os
20import argparse
21import json
22
23
24class Node:
25    def __init__(self, name, libtype=""):
26        self.name = name
27        self.libtype = libtype
28        self.value = 0
29        self.children = []
30
31    def toJSON(self):
32        return {
33            "n": self.name,
34            "l": self.libtype,
35            "v": self.value,
36            "c": self.children
37        }
38
39
40class FlameGraphCLI:
41    def __init__(self, args):
42        self.args = args
43        self.stack = Node("root")
44
45        if self.args.format == "html" and \
46                not os.path.isfile(self.args.template):
47            print("Flame Graph template {} does not exist. Please install "
48                  "the js-d3-flame-graph (RPM) or libjs-d3-flame-graph (deb) "
49                  "package, specify an existing flame graph template "
50                  "(--template PATH) or another output format "
51                  "(--format FORMAT).".format(self.args.template),
52                  file=sys.stderr)
53            sys.exit(1)
54
55    def find_or_create_node(self, node, name, dso):
56        libtype = "kernel" if dso == "[kernel.kallsyms]" else ""
57        if name is None:
58            name = "[unknown]"
59
60        for child in node.children:
61            if child.name == name and child.libtype == libtype:
62                return child
63
64        child = Node(name, libtype)
65        node.children.append(child)
66        return child
67
68    def process_event(self, event):
69        node = self.find_or_create_node(self.stack, event["comm"], None)
70        if "callchain" in event:
71            for entry in reversed(event['callchain']):
72                node = self.find_or_create_node(
73                    node, entry.get("sym", {}).get("name"), event.get("dso"))
74        else:
75            node = self.find_or_create_node(
76                node, entry.get("symbol"), event.get("dso"))
77        node.value += 1
78
79    def trace_end(self):
80        json_str = json.dumps(self.stack, default=lambda x: x.toJSON())
81
82        if self.args.format == "html":
83            try:
84                with open(self.args.template) as f:
85                    output_str = f.read().replace("/** @flamegraph_json **/",
86                                                  json_str)
87            except IOError as e:
88                print("Error reading template file: {}".format(e), file=sys.stderr)
89                sys.exit(1)
90            output_fn = self.args.output or "flamegraph.html"
91        else:
92            output_str = json_str
93            output_fn = self.args.output or "stacks.json"
94
95        if output_fn == "-":
96            sys.stdout.write(output_str)
97        else:
98            print("dumping data to {}".format(output_fn))
99            try:
100                with open(output_fn, "w") as out:
101                    out.write(output_str)
102            except IOError as e:
103                print("Error writing output file: {}".format(e), file=sys.stderr)
104                sys.exit(1)
105
106
107if __name__ == "__main__":
108    parser = argparse.ArgumentParser(description="Create flame graphs.")
109    parser.add_argument("-f", "--format",
110                        default="html", choices=["json", "html"],
111                        help="output file format")
112    parser.add_argument("-o", "--output",
113                        help="output file name")
114    parser.add_argument("--template",
115                        default="/usr/share/d3-flame-graph/d3-flamegraph-base.html",
116                        help="path to flamegraph HTML template")
117    parser.add_argument("-i", "--input",
118                        help=argparse.SUPPRESS)
119
120    args = parser.parse_args()
121    cli = FlameGraphCLI(args)
122
123    process_event = cli.process_event
124    trace_end = cli.trace_end
125