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