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
17 # pylint: disable=missing-module-docstring
18 # pylint: disable=missing-class-docstring
19 # pylint: disable=missing-function-docstring
21 from __future__ import print_function
29 # pylint: disable=too-few-public-methods
31 def __init__(self, name, libtype):
33 # "root" | "kernel" | ""
34 # "" indicates user space
35 self.libtype = libtype
49 def __init__(self, args):
51 self.stack = Node("all", "root")
53 if self.args.format == "html" and \
54 not os.path.isfile(self.args.template):
55 print("Flame Graph template {} does not exist. Please install "
56 "the js-d3-flame-graph (RPM) or libjs-d3-flame-graph (deb) "
57 "package, specify an existing flame graph template "
58 "(--template PATH) or another output format "
59 "(--format FORMAT).".format(self.args.template),
64 def get_libtype_from_dso(dso):
66 when kernel-debuginfo is installed,
67 dso points to /usr/lib/debug/lib/modules/*/vmlinux
69 if dso and (dso == "[kernel.kallsyms]" or dso.endswith("/vmlinux")):
75 def find_or_create_node(node, name, libtype):
76 for child in node.children:
77 if child.name == name:
80 child = Node(name, libtype)
81 node.children.append(child)
84 def process_event(self, event):
85 pid = event.get("sample", {}).get("pid", 0)
86 # event["dso"] sometimes contains /usr/lib/debug/lib/modules/*/vmlinux
87 # for user-space processes; let's use pid for kernel or user-space distinction
92 comm = "{} ({})".format(event["comm"], pid)
94 node = self.find_or_create_node(self.stack, comm, libtype)
96 if "callchain" in event:
97 for entry in reversed(event["callchain"]):
98 name = entry.get("sym", {}).get("name", "[unknown]")
99 libtype = self.get_libtype_from_dso(entry.get("dso"))
100 node = self.find_or_create_node(node, name, libtype)
102 name = event.get("symbol", "[unknown]")
103 libtype = self.get_libtype_from_dso(event.get("dso"))
104 node = self.find_or_create_node(node, name, libtype)
107 def get_report_header(self):
108 if self.args.input == "-":
109 # when this script is invoked with "perf script flamegraph",
110 # no perf.data is created and we cannot read the header of it
114 output = subprocess.check_output(["perf", "report", "--header-only"])
115 return output.decode("utf-8")
116 except Exception as err: # pylint: disable=broad-except
117 print("Error reading report header: {}".format(err), file=sys.stderr)
121 stacks_json = json.dumps(self.stack, default=lambda x: x.to_json())
123 if self.args.format == "html":
124 report_header = self.get_report_header()
126 "colorscheme": self.args.colorscheme,
127 "context": report_header
129 options_json = json.dumps(options)
132 with io.open(self.args.template, encoding="utf-8") as template:
135 .replace("/** @options_json **/", options_json)
136 .replace("/** @flamegraph_json **/", stacks_json)
138 except IOError as err:
139 print("Error reading template file: {}".format(err), file=sys.stderr)
141 output_fn = self.args.output or "flamegraph.html"
143 output_str = stacks_json
144 output_fn = self.args.output or "stacks.json"
147 with io.open(sys.stdout.fileno(), "w", encoding="utf-8", closefd=False) as out:
148 out.write(output_str)
150 print("dumping data to {}".format(output_fn))
152 with io.open(output_fn, "w", encoding="utf-8") as out:
153 out.write(output_str)
154 except IOError as err:
155 print("Error writing output file: {}".format(err), file=sys.stderr)
159 if __name__ == "__main__":
160 parser = argparse.ArgumentParser(description="Create flame graphs.")
161 parser.add_argument("-f", "--format",
162 default="html", choices=["json", "html"],
163 help="output file format")
164 parser.add_argument("-o", "--output",
165 help="output file name")
166 parser.add_argument("--template",
167 default="/usr/share/d3-flame-graph/d3-flamegraph-base.html",
168 help="path to flame graph HTML template")
169 parser.add_argument("--colorscheme",
170 default="blue-green",
171 help="flame graph color scheme",
172 choices=["blue-green", "orange"])
173 parser.add_argument("-i", "--input",
174 help=argparse.SUPPRESS)
176 cli_args = parser.parse_args()
177 cli = FlameGraphCLI(cli_args)
179 process_event = cli.process_event
180 trace_end = cli.trace_end