1 # flamegraph.py - create flame graphs from perf samples
2 # SPDX-License-Identifier: GPL-2.0
6 # perf record -a -g -F 99 sleep 60
7 # perf script report flamegraph
11 # perf script flamegraph -a -F 99 sleep 60
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>
17 from __future__ import print_function
25 def __init__(self, name, libtype=""):
27 self.libtype = libtype
41 def __init__(self, args):
43 self.stack = Node("root")
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),
55 def find_or_create_node(self, node, name, dso):
56 libtype = "kernel" if dso == "[kernel.kallsyms]" else ""
60 for child in node.children:
61 if child.name == name and child.libtype == libtype:
64 child = Node(name, libtype)
65 node.children.append(child)
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"))
75 node = self.find_or_create_node(
76 node, entry.get("symbol"), event.get("dso"))
80 json_str = json.dumps(self.stack, default=lambda x: x.toJSON())
82 if self.args.format == "html":
84 with open(self.args.template) as f:
85 output_str = f.read().replace("/** @flamegraph_json **/",
88 print("Error reading template file: {}".format(e), file=sys.stderr)
90 output_fn = self.args.output or "flamegraph.html"
93 output_fn = self.args.output or "stacks.json"
96 sys.stdout.write(output_str)
98 print("dumping data to {}".format(output_fn))
100 with open(output_fn, "w") as out:
101 out.write(output_str)
103 print("Error writing output file: {}".format(e), file=sys.stderr)
107 if __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)
120 args = parser.parse_args()
121 cli = FlameGraphCLI(args)
123 process_event = cli.process_event
124 trace_end = cli.trace_end