ilist.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  3. """Interactive perf list."""
  4. from abc import ABC, abstractmethod
  5. import argparse
  6. from dataclasses import dataclass
  7. import math
  8. from typing import Any, Dict, Optional, Tuple
  9. import perf
  10. from textual import on
  11. from textual.app import App, ComposeResult
  12. from textual.binding import Binding
  13. from textual.containers import Horizontal, HorizontalGroup, Vertical, VerticalScroll
  14. from textual.css.query import NoMatches
  15. from textual.command import SearchIcon
  16. from textual.screen import ModalScreen
  17. from textual.widgets import Button, Footer, Header, Input, Label, Sparkline, Static, Tree
  18. from textual.widgets.tree import TreeNode
  19. def get_info(info: Dict[str, str], key: str):
  20. return (info[key] + "\n") if key in info else ""
  21. class TreeValue(ABC):
  22. """Abstraction for the data of value in the tree."""
  23. @abstractmethod
  24. def name(self) -> str:
  25. pass
  26. @abstractmethod
  27. def description(self) -> str:
  28. pass
  29. @abstractmethod
  30. def matches(self, query: str) -> bool:
  31. pass
  32. @abstractmethod
  33. def parse(self) -> perf.evlist:
  34. pass
  35. @abstractmethod
  36. def value(self, evlist: perf.evlist, evsel: perf.evsel, cpu: int, thread: int) -> float:
  37. pass
  38. @dataclass
  39. class Metric(TreeValue):
  40. """A metric in the tree."""
  41. metric_name: str
  42. metric_pmu: str
  43. def name(self) -> str:
  44. return self.metric_name
  45. def description(self) -> str:
  46. """Find and format metric description."""
  47. for metric in perf.metrics():
  48. if metric["MetricName"] != self.metric_name:
  49. continue
  50. if self.metric_pmu and metric["PMU"] != self.metric_pmu:
  51. continue
  52. desc = get_info(metric, "BriefDescription")
  53. desc += get_info(metric, "PublicDescription")
  54. desc += get_info(metric, "MetricExpr")
  55. desc += get_info(metric, "MetricThreshold")
  56. return desc
  57. return "description"
  58. def matches(self, query: str) -> bool:
  59. return query in self.metric_name
  60. def parse(self) -> perf.evlist:
  61. return perf.parse_metrics(self.metric_name, self.metric_pmu)
  62. def value(self, evlist: perf.evlist, evsel: perf.evsel, cpu: int, thread: int) -> float:
  63. try:
  64. val = evlist.compute_metric(self.metric_name, cpu, thread)
  65. return 0 if math.isnan(val) else val
  66. except:
  67. # Be tolerant of failures to compute metrics on particular CPUs/threads.
  68. return 0
  69. @dataclass
  70. class PmuEvent(TreeValue):
  71. """A PMU and event within the tree."""
  72. pmu: str
  73. event: str
  74. def name(self) -> str:
  75. if self.event.startswith(self.pmu) or ':' in self.event:
  76. return self.event
  77. else:
  78. return f"{self.pmu}/{self.event}/"
  79. def description(self) -> str:
  80. """Find and format event description for {pmu}/{event}/."""
  81. for p in perf.pmus():
  82. if p.name() != self.pmu:
  83. continue
  84. for info in p.events():
  85. if "name" not in info or info["name"] != self.event:
  86. continue
  87. desc = get_info(info, "topic")
  88. desc += get_info(info, "event_type_desc")
  89. desc += get_info(info, "desc")
  90. desc += get_info(info, "long_desc")
  91. desc += get_info(info, "encoding_desc")
  92. return desc
  93. return "description"
  94. def matches(self, query: str) -> bool:
  95. return query in self.pmu or query in self.event
  96. def parse(self) -> perf.evlist:
  97. return perf.parse_events(self.name())
  98. def value(self, evlist: perf.evlist, evsel: perf.evsel, cpu: int, thread: int) -> float:
  99. return evsel.read(cpu, thread).val
  100. class ErrorScreen(ModalScreen[bool]):
  101. """Pop up dialog for errors."""
  102. CSS = """
  103. ErrorScreen {
  104. align: center middle;
  105. }
  106. """
  107. def __init__(self, error: str):
  108. self.error = error
  109. super().__init__()
  110. def compose(self) -> ComposeResult:
  111. yield Button(f"Error: {self.error}", variant="primary", id="error")
  112. def on_button_pressed(self, event: Button.Pressed) -> None:
  113. self.dismiss(True)
  114. class SearchScreen(ModalScreen[str]):
  115. """Pop up dialog for search."""
  116. CSS = """
  117. SearchScreen Horizontal {
  118. align: center middle;
  119. margin-top: 1;
  120. }
  121. SearchScreen Input {
  122. width: 1fr;
  123. }
  124. """
  125. def compose(self) -> ComposeResult:
  126. yield Horizontal(SearchIcon(), Input(placeholder="Event name"))
  127. def on_input_submitted(self, event: Input.Submitted) -> None:
  128. """Handle the user pressing Enter in the input field."""
  129. self.dismiss(event.value)
  130. class Counter(HorizontalGroup):
  131. """Two labels for a CPU and its counter value."""
  132. CSS = """
  133. Label {
  134. gutter: 1;
  135. }
  136. """
  137. def __init__(self, cpu: int) -> None:
  138. self.cpu = cpu
  139. super().__init__()
  140. def compose(self) -> ComposeResult:
  141. label = f"cpu{self.cpu}" if self.cpu >= 0 else "total"
  142. yield Label(label + " ")
  143. yield Label("0", id=f"counter_{label}")
  144. class CounterSparkline(HorizontalGroup):
  145. """A Sparkline for a performance counter."""
  146. def __init__(self, cpu: int) -> None:
  147. self.cpu = cpu
  148. super().__init__()
  149. def compose(self) -> ComposeResult:
  150. label = f"cpu{self.cpu}" if self.cpu >= 0 else "total"
  151. yield Label(label)
  152. yield Sparkline([], summary_function=max, id=f"sparkline_{label}")
  153. class IListApp(App):
  154. TITLE = "Interactive Perf List"
  155. BINDINGS = [
  156. Binding(key="s", action="search", description="Search",
  157. tooltip="Search events and PMUs"),
  158. Binding(key="n", action="next", description="Next",
  159. tooltip="Next search result or item"),
  160. Binding(key="p", action="prev", description="Previous",
  161. tooltip="Previous search result or item"),
  162. Binding(key="c", action="collapse", description="Collapse",
  163. tooltip="Collapse the current PMU"),
  164. Binding(key="^q", action="quit", description="Quit",
  165. tooltip="Quit the app"),
  166. ]
  167. CSS = """
  168. /* Make the 'total' sparkline a different color. */
  169. #sparkline_total > .sparkline--min-color {
  170. color: $accent;
  171. }
  172. #sparkline_total > .sparkline--max-color {
  173. color: $accent 30%;
  174. }
  175. /*
  176. * Make the active_search initially not displayed with the text in
  177. * the middle of the line.
  178. */
  179. #active_search {
  180. display: none;
  181. width: 100%;
  182. text-align: center;
  183. }
  184. """
  185. def __init__(self, interval: float) -> None:
  186. self.interval = interval
  187. self.evlist = None
  188. self.selected: Optional[TreeValue] = None
  189. self.search_results: list[TreeNode[TreeValue]] = []
  190. self.cur_search_result: TreeNode[TreeValue] | None = None
  191. super().__init__()
  192. def expand_and_select(self, node: TreeNode[Any]) -> None:
  193. """Expand select a node in the tree."""
  194. if node.parent:
  195. node.parent.expand()
  196. if node.parent.parent:
  197. node.parent.parent.expand()
  198. node.expand()
  199. node.tree.select_node(node)
  200. node.tree.scroll_to_node(node)
  201. def set_searched_tree_node(self, previous: bool) -> None:
  202. """Set the cur_search_result node to either the next or previous."""
  203. l = len(self.search_results)
  204. if l < 1:
  205. tree: Tree[TreeValue] = self.query_one("#root", Tree)
  206. if previous:
  207. tree.action_cursor_up()
  208. else:
  209. tree.action_cursor_down()
  210. return
  211. if self.cur_search_result:
  212. idx = self.search_results.index(self.cur_search_result)
  213. if previous:
  214. idx = idx - 1 if idx > 0 else l - 1
  215. else:
  216. idx = idx + 1 if idx < l - 1 else 0
  217. else:
  218. idx = l - 1 if previous else 0
  219. node = self.search_results[idx]
  220. if node == self.cur_search_result:
  221. return
  222. self.cur_search_result = node
  223. self.expand_and_select(node)
  224. def action_search(self) -> None:
  225. """Search was chosen."""
  226. def set_initial_focus(event: str | None) -> None:
  227. """Sets the focus after the SearchScreen is dismissed."""
  228. search_label = self.query_one("#active_search", Label)
  229. search_label.display = True if event else False
  230. if not event:
  231. return
  232. event = event.lower()
  233. search_label.update(f'Searching for events matching "{event}"')
  234. tree: Tree[str] = self.query_one("#root", Tree)
  235. def find_search_results(event: str, node: TreeNode[str],
  236. cursor_seen: bool = False,
  237. match_after_cursor: Optional[TreeNode[str]] = None
  238. ) -> Tuple[bool, Optional[TreeNode[str]]]:
  239. """Find nodes that match the search remembering the one after the cursor."""
  240. if not cursor_seen and node == tree.cursor_node:
  241. cursor_seen = True
  242. if node.data and node.data.matches(event):
  243. if cursor_seen and not match_after_cursor:
  244. match_after_cursor = node
  245. self.search_results.append(node)
  246. if node.children:
  247. for child in node.children:
  248. (cursor_seen, match_after_cursor) = \
  249. find_search_results(event, child, cursor_seen, match_after_cursor)
  250. return (cursor_seen, match_after_cursor)
  251. self.search_results.clear()
  252. (_, self.cur_search_result) = find_search_results(event, tree.root)
  253. if len(self.search_results) < 1:
  254. self.push_screen(ErrorScreen(f"Failed to find pmu/event or metric {event}"))
  255. search_label.display = False
  256. elif self.cur_search_result:
  257. self.expand_and_select(self.cur_search_result)
  258. else:
  259. self.set_searched_tree_node(previous=False)
  260. self.push_screen(SearchScreen(), set_initial_focus)
  261. def action_next(self) -> None:
  262. """Next was chosen."""
  263. self.set_searched_tree_node(previous=False)
  264. def action_prev(self) -> None:
  265. """Previous was chosen."""
  266. self.set_searched_tree_node(previous=True)
  267. def action_collapse(self) -> None:
  268. """Collapse the part of the tree currently on."""
  269. tree: Tree[str] = self.query_one("#root", Tree)
  270. node = tree.cursor_node
  271. if node and node.parent:
  272. node.parent.collapse_all()
  273. node.tree.scroll_to_node(node.parent)
  274. def update_counts(self) -> None:
  275. """Called every interval to update counts."""
  276. if not self.selected or not self.evlist:
  277. return
  278. def update_count(cpu: int, count: int):
  279. # Update the raw count display.
  280. counter: Label = self.query(f"#counter_cpu{cpu}" if cpu >= 0 else "#counter_total")
  281. if not counter:
  282. return
  283. counter = counter.first(Label)
  284. counter.update(str(count))
  285. # Update the sparkline.
  286. line: Sparkline = self.query(f"#sparkline_cpu{cpu}" if cpu >= 0 else "#sparkline_total")
  287. if not line:
  288. return
  289. line = line.first(Sparkline)
  290. # If there are more events than the width, remove the front event.
  291. if len(line.data) > line.size.width:
  292. line.data.pop(0)
  293. line.data.append(count)
  294. line.mutate_reactive(Sparkline.data)
  295. # Update the total and each CPU counts, assume there's just 1 evsel.
  296. total = 0
  297. self.evlist.disable()
  298. for evsel in self.evlist:
  299. for cpu in evsel.cpus():
  300. aggr = 0
  301. for thread in evsel.threads():
  302. aggr += self.selected.value(self.evlist, evsel, cpu, thread)
  303. update_count(cpu, aggr)
  304. total += aggr
  305. update_count(-1, total)
  306. self.evlist.enable()
  307. def on_mount(self) -> None:
  308. """When App starts set up periodic event updating."""
  309. self.update_counts()
  310. self.set_interval(self.interval, self.update_counts)
  311. def set_selected(self, value: TreeValue) -> None:
  312. """Updates the event/description and starts the counters."""
  313. try:
  314. label_name = self.query_one("#event_name", Label)
  315. event_description = self.query_one("#event_description", Static)
  316. lines = self.query_one("#lines")
  317. except NoMatches:
  318. # A race with rendering, ignore the update as we can't
  319. # mount the assumed output widgets.
  320. return
  321. self.selected = value
  322. # Remove previous event information.
  323. if self.evlist:
  324. self.evlist.disable()
  325. self.evlist.close()
  326. old_lines = self.query(CounterSparkline)
  327. for line in old_lines:
  328. line.remove()
  329. old_counters = self.query(Counter)
  330. for counter in old_counters:
  331. counter.remove()
  332. # Update event/metric text and description.
  333. label_name.update(value.name())
  334. event_description.update(value.description())
  335. # Open the event.
  336. try:
  337. self.evlist = value.parse()
  338. if self.evlist:
  339. self.evlist.open()
  340. self.evlist.enable()
  341. except:
  342. self.evlist = None
  343. if not self.evlist:
  344. self.push_screen(ErrorScreen(f"Failed to open {value.name()}"))
  345. return
  346. # Add spark lines for all the CPUs. Note, must be done after
  347. # open so that the evlist CPUs have been computed by propagate
  348. # maps.
  349. line = CounterSparkline(cpu=-1)
  350. lines.mount(line)
  351. for cpu in self.evlist.all_cpus():
  352. line = CounterSparkline(cpu)
  353. lines.mount(line)
  354. line = Counter(cpu=-1)
  355. lines.mount(line)
  356. for cpu in self.evlist.all_cpus():
  357. line = Counter(cpu)
  358. lines.mount(line)
  359. def compose(self) -> ComposeResult:
  360. """Draws the app."""
  361. def metric_event_tree() -> Tree:
  362. """Create tree of PMUs and metricgroups with events or metrics under."""
  363. tree: Tree[TreeValue] = Tree("Root", id="root")
  364. pmus = tree.root.add("PMUs")
  365. for pmu in perf.pmus():
  366. pmu_name = pmu.name().lower()
  367. pmu_node = pmus.add(pmu_name)
  368. try:
  369. for event in sorted(pmu.events(), key=lambda x: x["name"]):
  370. if "deprecated" in event:
  371. continue
  372. if "name" in event:
  373. e = event["name"].lower()
  374. if "alias" in event:
  375. pmu_node.add_leaf(f'{e} ({event["alias"]})',
  376. data=PmuEvent(pmu_name, e))
  377. else:
  378. pmu_node.add_leaf(e, data=PmuEvent(pmu_name, e))
  379. except:
  380. # Reading events may fail with EPERM, ignore.
  381. pass
  382. metrics = tree.root.add("Metrics")
  383. groups = set()
  384. for metric in perf.metrics():
  385. groups.update(metric["MetricGroup"])
  386. def add_metrics_to_tree(node: TreeNode[TreeValue], parent: str, pmu: str = None):
  387. for metric in sorted(perf.metrics(), key=lambda x: x["MetricName"]):
  388. metric_pmu = metric.get('PMU')
  389. if pmu and metric_pmu and metric_pmu != pmu:
  390. continue
  391. if parent in metric["MetricGroup"]:
  392. name = metric["MetricName"]
  393. display_name = name
  394. if metric_pmu:
  395. display_name += f" ({metric_pmu})"
  396. node.add_leaf(display_name, data=Metric(name, metric_pmu))
  397. child_group_name = f'{name}_group'
  398. if child_group_name in groups:
  399. display_child_group_name = child_group_name
  400. if metric_pmu:
  401. display_child_group_name += f" ({metric_pmu})"
  402. add_metrics_to_tree(node.add(display_child_group_name),
  403. child_group_name,
  404. metric_pmu)
  405. for group in sorted(groups):
  406. if group.endswith('_group'):
  407. continue
  408. add_metrics_to_tree(metrics.add(group), group)
  409. tree.root.expand()
  410. return tree
  411. yield Header(id="header")
  412. yield Horizontal(Vertical(metric_event_tree(), id="events"),
  413. Vertical(Label("event name", id="event_name"),
  414. Static("description", markup=False, id="event_description"),
  415. ))
  416. yield Label(id="active_search")
  417. yield VerticalScroll(id="lines")
  418. yield Footer(id="footer")
  419. @on(Tree.NodeSelected)
  420. def on_tree_node_selected(self, event: Tree.NodeSelected[TreeValue]) -> None:
  421. """Called when a tree node is selected, selecting the event."""
  422. if event.node.data:
  423. self.set_selected(event.node.data)
  424. if __name__ == "__main__":
  425. ap = argparse.ArgumentParser()
  426. ap.add_argument('-I', '--interval', help="Counter update interval in seconds", default=0.1)
  427. args = ap.parse_args()
  428. app = IListApp(float(args.interval))
  429. app.run()