Repository navigation
Expand file tree
/
Copy pathttimechart.py
More file actions
executable file
·1806 lines (1593 loc) · 72 KB
/
Copy pathttimechart.py
File metadata and controls
executable file
·1806 lines (1593 loc) · 72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
"""ttimechart.py - interactive perf timechart written using textual.
Reads a perf.data file, typically created with 'perf timechart record', and
displays per-CPU and per-task timelines in the terminal. Scheduler
(sched:sched_switch, sched:sched_wakeup), power (power:cpu_idle,
power:cpu_frequency) and I/O syscall (perf timechart record -I) tracepoints
are understood. Unlike 'perf timechart', which writes an SVG file, the
timeline can be zoomed, panned and queried interactively.
Usage:
perf timechart record -- <workload>
perf timechart --tui
or:
perf script ttimechart [-i perf.data]
"""
from __future__ import annotations
from abc import ABC, abstractmethod
import argparse
import bisect
from collections import defaultdict
from dataclasses import dataclass, replace
import math
import os
import sys
import threading
from time import monotonic
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple
import perf
from rich.segment import Segment
from rich.style import Style
from textual import events, on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.color import Color
from textual.geometry import Size
from textual.message import Message
from textual.reactive import reactive
from textual.scroll_view import ScrollView
from textual.strip import Strip
from textual.widgets import DataTable, Footer, Header, Static, TabbedContent, TabPane
from textual.widgets.data_table import CellDoesNotExist, RowDoesNotExist
# Task states, SLEEPING and UNKNOWN aren't drawn.
STATE_UNKNOWN = -1
STATE_SLEEPING = 0
STATE_RUNNING = 1
STATE_WAITING = 2
STATE_BLOCKED = 3
NUM_STATES = 4
STATE_NAMES = {
STATE_UNKNOWN: "unknown",
STATE_SLEEPING: "sleeping",
STATE_RUNNING: "running",
STATE_WAITING: "runnable (waiting for a CPU)",
STATE_BLOCKED: "blocked (uninterruptible)",
}
# I/O types, matching builtin-timechart.c.
IOTYPE_READ = 0
IOTYPE_WRITE = 1
IOTYPE_SYNC = 2
IOTYPE_TX = 3
IOTYPE_RX = 4
IOTYPE_POLL = 5
NUM_IOTYPES = 6
IOTYPE_NAMES = ["read", "write", "sync", "tx", "rx", "poll"]
IO_SYSCALLS = {
"read": IOTYPE_READ, "pread64": IOTYPE_READ, "readv": IOTYPE_READ,
"preadv": IOTYPE_READ,
"write": IOTYPE_WRITE, "pwrite64": IOTYPE_WRITE, "writev": IOTYPE_WRITE,
"pwritev": IOTYPE_WRITE,
"sync": IOTYPE_SYNC, "sync_file_range": IOTYPE_SYNC, "fsync": IOTYPE_SYNC,
"msync": IOTYPE_SYNC,
"recvfrom": IOTYPE_RX, "recvmmsg": IOTYPE_RX, "recvmsg": IOTYPE_RX,
"sendto": IOTYPE_TX, "sendmsg": IOTYPE_TX, "sendmmsg": IOTYPE_TX,
"epoll_pwait": IOTYPE_POLL, "epoll_wait": IOTYPE_POLL, "poll": IOTYPE_POLL,
"ppoll": IOTYPE_POLL, "pselect6": IOTYPE_POLL, "select": IOTYPE_POLL,
}
# Trace flags for interrupt context in the common_flags tracepoint field.
TRACE_FLAG_HARDIRQ = 0x08
TRACE_FLAG_SOFTIRQ = 0x10
# Value of state in power:cpu_idle when leaving idle.
PWR_EVENT_EXIT = 0xffffffff
# Width of the row label column.
LABEL_WIDTH = 28
# Characters for drawing fractional bars.
BARS = " ▁▂▃▄▅▆▇█"
NSEC_PER_SEC = 1_000_000_000
def fmt_duration(nsecs: float) -> str:
"""Format a duration in nanoseconds with an appropriate unit."""
if nsecs >= NSEC_PER_SEC:
return f"{nsecs / NSEC_PER_SEC:.3f}s"
if nsecs >= 1_000_000:
return f"{nsecs / 1_000_000:.3f}ms"
if nsecs >= 1_000:
return f"{nsecs / 1_000:.3f}us"
return f"{nsecs:.0f}ns"
def escape(text: str) -> str:
"""Escape text, such as a task name, for use in textual markup.
rich.markup.escape doesn't escape tags like "[1]", the name given to tasks
with an unknown command, but textual fails to parse them.
"""
return text.replace("[", "\\[")
def make_fixed_length_string(s: str, length: int, pad_char: str = ' ') -> str:
"""Truncate or right pad s so that it is length characters long."""
return s[:length] if len(s) > length else s.ljust(length, pad_char)
def bar_char(frac: float) -> str:
"""A block character whose height represents frac, in the range [0, 1]."""
if frac <= 0:
return BARS[0]
return BARS[max(1, min(8, round(frac * 8)))]
class SegmentList:
"""A time ordered list of non-overlapping [start, end) segments.
Each segment has a small integer key, used for computing coverage, and
arbitrary associated data.
"""
def __init__(self) -> None:
self.starts: List[int] = []
self.ends: List[int] = []
self.keys: List[int] = []
self.data: List[Any] = []
def __len__(self) -> int:
return len(self.starts)
def add(self, start: int, end: int, key: int, data: Any = None) -> None:
"""Append a segment, segments must be added in time order."""
if end <= start:
return
if self.ends and start < self.ends[-1]:
# Clip overlaps caused by inconsistent data.
start = self.ends[-1]
if end <= start:
return
self.starts.append(start)
self.ends.append(end)
self.keys.append(key)
self.data.append(data)
def find(self, time: float) -> int:
"""Index of the segment containing time or -1."""
i = bisect.bisect_right(self.starts, time) - 1
if i >= 0 and time < self.ends[i]:
return i
return -1
def last_before(self, time: float) -> int:
"""Index of the last segment starting at or before time or -1."""
return bisect.bisect_right(self.starts, time) - 1
def next_change(self, time: float) -> Optional[int]:
"""The first segment start or end after time."""
candidates = []
i = bisect.bisect_right(self.starts, time)
if i < len(self.starts):
candidates.append(self.starts[i])
i = bisect.bisect_right(self.ends, time)
if i < len(self.ends):
candidates.append(self.ends[i])
return min(candidates) if candidates else None
def prev_change(self, time: float) -> Optional[int]:
"""The last segment start or end before time."""
candidates = []
i = bisect.bisect_left(self.starts, time) - 1
if i >= 0:
candidates.append(self.starts[i])
i = bisect.bisect_left(self.ends, time) - 1
if i >= 0:
candidates.append(self.ends[i])
return max(candidates) if candidates else None
def coverage(self, t0: float, dt: float, width: int, nkeys: int,
weight_fn=None) -> List[List[float]]:
"""Time covered by each key in each of width columns of size dt.
If weight_fn is given then, rather than the time covered, the time
covered multiplied by weight_fn(data) is accumulated.
"""
cols = [[0.0] * nkeys for _ in range(width)]
t1 = t0 + dt * width
i = bisect.bisect_right(self.ends, t0)
num = len(self.starts)
while i < num and self.starts[i] < t1:
start = max(self.starts[i], t0)
end = min(self.ends[i], t1)
key = self.keys[i]
weight = weight_fn(self.data[i]) if weight_fn else 1.0
x0 = min(int((start - t0) / dt), width - 1)
x1 = min(int((end - t0) / dt), width - 1)
if x0 == x1:
cols[x0][key] += (end - start) * weight
else:
cols[x0][key] += (t0 + (x0 + 1) * dt - start) * weight
for x in range(x0 + 1, x1):
cols[x][key] += dt * weight
cols[x1][key] += (end - (t0 + x1 * dt)) * weight
i += 1
return cols
class Task:
"""Scheduling and I/O history of a single thread."""
def __init__(self, tid: int, comm: str) -> None:
self.tid = tid
self.comm = comm
self.comms: List[str] = [comm]
self.state = STATE_UNKNOWN
self.since = 0
self.cpu = -1
# Segments with a state key and the CPU as data.
self.segs = SegmentList()
# Segments with an I/O type key and (fd, ret) as data.
self.io = SegmentList()
self.io_pending: Optional[Tuple[int, int, int]] = None
# Wakeups of this task as (time, waker tid) pairs.
self.wakeups: List[Tuple[int, int]] = []
self.totals = [0] * NUM_STATES
self.switches = 0
self.io_bytes = 0
def name(self) -> str:
"""Name for the task used in labels."""
return f"{self.comm} ({self.tid})"
def set_comm(self, comm: Optional[str]) -> None:
"""Update the task's command name."""
if not comm or comm == self.comm:
return
self.comm = comm
if comm not in self.comms:
self.comms.append(comm)
def change_state(self, time: int, state: int, cpu: int = -1) -> None:
"""Record the current state as a segment and switch to a new state."""
if self.state in (STATE_RUNNING, STATE_WAITING, STATE_BLOCKED) and time > self.since:
self.segs.add(self.since, time, self.state, self.cpu)
self.totals[self.state] += time - self.since
self.state = state
self.since = time
if cpu >= 0:
self.cpu = cpu
def passes_filter(self, filters: Sequence[str]) -> bool:
"""Does the task match one of the process filters (pid or name)?"""
if not filters:
return True
return any(f == str(self.tid) or f in self.comms for f in filters)
class Cpu:
"""Activity on a single CPU."""
def __init__(self, cpu: int) -> None:
self.cpu = cpu
self.cur_tid = -1
self.since = 0
# Busy segments, key 1, with the running tid as data.
self.run = SegmentList()
# Idle state segments, key 1, with the C-state as data.
self.cstate = SegmentList()
self.cstate_cur: Optional[Tuple[int, int]] = None
# Frequency segments, key 1, with the frequency in kHz as data.
self.pstate = SegmentList()
self.pstate_cur: Optional[Tuple[int, int]] = None
class LoadCancelled(Exception):
"""Raised from the sample callback to stop processing events early."""
class TimechartData:
"""Builds per-task and per-CPU timelines from perf events.
The data may be displayed while it is loaded in another thread, lock must
be held when modifying it or when reading it from another thread.
"""
# Number of samples between checks for cancellation and progress.
PROGRESS_INTERVAL = 1000
# Minimum and maximum time between calls to the progress callback.
PROGRESS_SECONDS = 1.0
PROGRESS_MAX_SECONDS = 10.0
# Updating the views costs more as more data is loaded, so the time between
# progress calls grows as this fraction of the time spent loading. This
# bounds the fraction of the load time spent updating the views.
PROGRESS_FRACTION = 0.25
def __init__(self) -> None:
self.tasks: Dict[int, Task] = {}
self.cpus: Dict[int, Cpu] = {}
self.first_time = 0
self.last_time = 0
self.min_freq = 0
self.max_freq = 0
self.max_cstate = 0
self.sched_events = 0
self.power_events = 0
self.io_events = 0
self.nr_samples = 0
self.unhandled: Dict[str, int] = defaultdict(int)
self.session: Optional[perf.session] = None
# Evsel name and event handler, keyed by sample ID.
self._handlers: Dict[int, Tuple[str, Optional[Callable[[int, perf.sample_event],
None]]]] = {}
self.lock = threading.Lock()
# Set, possibly from another thread, to stop processing events.
self.cancelled = False
# Called periodically, see PROGRESS_FRACTION, while processing events.
self.progress: Optional[Callable[[], None]] = None
self.start_progress = monotonic()
self.last_progress = self.start_progress
def has_events(self) -> bool:
"""Were any events that can be displayed processed?"""
return bool(self.sched_events or self.power_events or self.io_events)
def task(self, tid: int, comm: Optional[str] = None) -> Task:
"""Find or create a task."""
task = self.tasks.get(tid)
if task is None:
if not comm and self.session:
try:
thread = self.session.find_thread(tid, tid)
comm = thread.comm() if thread else None
except (OSError, ValueError, KeyError, RuntimeError, TypeError, AttributeError):
comm = None
task = Task(tid, comm or f"[{tid}]")
self.tasks[tid] = task
else:
task.set_comm(comm)
return task
def cpu(self, cpu: int) -> Cpu:
"""Find or create a CPU."""
c = self.cpus.get(cpu)
if c is None:
c = Cpu(cpu)
self.cpus[cpu] = c
return c
def sched_switch(self, time: int, cpu: int, prev_tid: int, prev_comm: Optional[str],
prev_state: int, next_tid: int, next_comm: Optional[str]) -> None:
"""Process a sched:sched_switch event."""
self.sched_events += 1
c = self.cpu(cpu)
if c.cur_tid == -1 and prev_tid != 0:
# Assume the task was running from the start of the trace.
c.cur_tid = prev_tid
c.since = self.first_time
if c.cur_tid > 0:
c.run.add(c.since, time, 1, c.cur_tid)
c.cur_tid = next_tid
c.since = time
if prev_tid != 0:
prev = self.task(prev_tid, prev_comm)
if prev.state == STATE_UNKNOWN:
prev.state = STATE_RUNNING
prev.since = self.first_time
prev.cpu = cpu
# Ignore bits like TASK_REPORT_MAX used to report preemption.
state = prev_state & 0xff
if state == 0:
new_state = STATE_WAITING
elif state & 2:
new_state = STATE_BLOCKED
else:
new_state = STATE_SLEEPING
prev.change_state(time, new_state)
prev.switches += 1
if next_tid != 0:
nxt = self.task(next_tid, next_comm)
nxt.change_state(time, STATE_RUNNING, cpu)
def sched_wakeup(self, time: int, wakee: int, comm: Optional[str], waker: int) -> None:
"""Process a sched:sched_wakeup or sched:sched_wakeup_new event."""
self.sched_events += 1
if wakee == 0:
return
task = self.task(wakee, comm)
task.wakeups.append((time, waker))
if task.state in (STATE_UNKNOWN, STATE_SLEEPING, STATE_BLOCKED):
task.change_state(time, STATE_WAITING)
def cstate_start(self, time: int, cpu: int, state: int) -> None:
"""Enter an idle state."""
self.power_events += 1
c = self.cpu(cpu)
if c.cstate_cur:
c.cstate.add(c.cstate_cur[0], time, 1, c.cstate_cur[1])
c.cstate_cur = (time, state)
self.max_cstate = max(self.max_cstate, state)
def cstate_end(self, time: int, cpu: int) -> None:
"""Leave an idle state."""
self.power_events += 1
c = self.cpu(cpu)
if c.cstate_cur:
c.cstate.add(c.cstate_cur[0], time, 1, c.cstate_cur[1])
c.cstate_cur = None
def pstate_change(self, time: int, cpu: int, freq: int) -> None:
"""Change of CPU frequency, freq is in kHz."""
if freq <= 0 or freq > 8000000:
return
self.power_events += 1
c = self.cpu(cpu)
if c.pstate_cur:
c.pstate.add(c.pstate_cur[0], time, 1, c.pstate_cur[1])
c.pstate_cur = (time, freq)
self.max_freq = max(self.max_freq, freq)
self.min_freq = freq if not self.min_freq else min(self.min_freq, freq)
def io_enter(self, time: int, tid: int, iotype: int, fd: int) -> None:
"""Entry to an I/O syscall."""
self.io_events += 1
self.task(tid).io_pending = (time, iotype, fd)
def io_exit(self, time: int, tid: int, iotype: int, ret: int) -> None:
"""Exit from an I/O syscall."""
self.io_events += 1
task = self.task(tid)
pending = task.io_pending
task.io_pending = None
if not pending or pending[1] != iotype:
return
start = pending[0]
task.io.add(start, max(time, start + 1), iotype, (pending[2], ret))
if ret > 0 and iotype in (IOTYPE_READ, IOTYPE_WRITE, IOTYPE_TX, IOTYPE_RX):
task.io_bytes += ret
def _on_sched_switch(self, time: int, sample: perf.sample_event) -> None:
self.sched_switch(time, sample.sample_cpu, sample.prev_pid,
getattr(sample, "prev_comm", None), sample.prev_state,
sample.next_pid, getattr(sample, "next_comm", None))
def _on_sched_wakeup(self, time: int, sample: perf.sample_event) -> None:
waker = getattr(sample, "common_pid", sample.sample_tid)
flags = getattr(sample, "common_flags", 0)
if flags & (TRACE_FLAG_HARDIRQ | TRACE_FLAG_SOFTIRQ):
waker = -1
self.sched_wakeup(time, sample.pid, getattr(sample, "comm", None), waker)
def _cstate(self, time: int, cpu: int, state: int) -> None:
if (state & 0xffffffff) == PWR_EVENT_EXIT:
self.cstate_end(time, cpu)
else:
self.cstate_start(time, cpu, state)
def _on_cpu_idle(self, time: int, sample: perf.sample_event) -> None:
self._cstate(time, sample.cpu_id, sample.state)
def _on_power_start(self, time: int, sample: perf.sample_event) -> None:
self._cstate(time, sample.cpu_id, sample.value)
def _on_power_end(self, time: int, sample: perf.sample_event) -> None:
self.cstate_end(time, sample.sample_cpu)
def _on_cpu_frequency(self, time: int, sample: perf.sample_event) -> None:
self.pstate_change(time, sample.cpu_id, sample.state)
def _on_power_frequency(self, time: int, sample: perf.sample_event) -> None:
self.pstate_change(time, sample.cpu_id, sample.value)
def _handler_for(self, name: str) -> Optional[Callable[[int, perf.sample_event], None]]:
"""Find the handler for events with the given evsel name."""
handlers: Dict[str, Callable[[int, perf.sample_event], None]] = {
"sched:sched_switch": self._on_sched_switch,
"sched:sched_wakeup": self._on_sched_wakeup,
"sched:sched_wakeup_new": self._on_sched_wakeup,
"power:cpu_idle": self._on_cpu_idle,
"power:power_start": self._on_power_start,
"power:power_end": self._on_power_end,
"power:cpu_frequency": self._on_cpu_frequency,
"power:power_frequency": self._on_power_frequency,
}
if name in handlers:
return handlers[name]
if name.startswith("syscalls:sys_enter_") and name[19:] in IO_SYSCALLS:
iotype = IO_SYSCALLS[name[19:]]
return lambda time, sample: self.io_enter(time, sample.sample_tid, iotype,
getattr(sample, "fd", -1))
if name.startswith("syscalls:sys_exit_") and name[18:] in IO_SYSCALLS:
iotype = IO_SYSCALLS[name[18:]]
return lambda time, sample: self.io_exit(time, sample.sample_tid, iotype,
sample.ret)
return None
def process_event(self, sample: perf.sample_event) -> None:
"""Callback from perf.session for each sample."""
self.nr_samples += 1
if self.nr_samples % self.PROGRESS_INTERVAL == 0:
if self.cancelled:
raise LoadCancelled()
now = monotonic()
interval = min(max(self.PROGRESS_SECONDS,
(now - self.start_progress) * self.PROGRESS_FRACTION),
self.PROGRESS_MAX_SECONDS)
if self.progress and now - self.last_progress >= interval:
with self.lock:
self.update_comms()
# Must not hold the lock as the callback may read the data.
self.progress()
# Time from when the callback, that may block, returns.
self.last_progress = monotonic()
with self.lock:
self._process_event(sample)
def _process_event(self, sample: perf.sample_event) -> None:
"""Update the data from a sample, the lock must be held."""
time = sample.sample_time
if not self.first_time or time < self.first_time:
self.first_time = time
self.last_time = max(self.last_time, time)
# Computing the evsel name and matching it is relatively expensive,
# so cache the result by sample ID. Each ID belongs to a single evsel.
sample_id = sample.sample_id
cached = self._handlers.get(sample_id)
if cached is None:
name = str(sample.evsel)
if name.startswith("evsel(") and name.endswith(")"):
name = name[6:-1]
cached = (name, self._handler_for(name))
self._handlers[sample_id] = cached
name, handler = cached
if handler is None:
self.unhandled[name] += 1
return
try:
handler(time, sample)
except AttributeError:
self.unhandled[name] += 1
def update_comms(self) -> None:
"""Refresh task command names from the session, the lock must be held."""
if not self.session:
return
for tid, task in self.tasks.items():
try:
thread = self.session.find_thread(tid, tid)
if thread:
task.set_comm(thread.comm())
except (OSError, ValueError, KeyError, RuntimeError, TypeError, AttributeError):
pass
def finish(self) -> None:
"""Close open segments at the end of the trace."""
with self.lock:
self.update_comms()
end = self.last_time
for task in self.tasks.values():
task.change_state(end, STATE_UNKNOWN)
for c in self.cpus.values():
if c.cur_tid > 0:
c.run.add(c.since, end, 1, c.cur_tid)
if c.cstate_cur:
c.cstate.add(c.cstate_cur[0], end, 1, c.cstate_cur[1])
c.cstate_cur = None
if c.pstate_cur:
c.pstate.add(c.pstate_cur[0], end, 1, c.pstate_cur[1])
c.pstate_cur = None
def fmt_time(self, time: float) -> str:
"""Format an absolute timestamp relative to the trace start."""
return f"{(time - self.first_time) / NSEC_PER_SEC:.6f}s"
def task_name(self, tid: int) -> str:
"""Name of a task, or a description for special tids."""
if tid == 0:
return "idle"
if tid < 0:
return "interrupt"
task = self.tasks.get(tid)
return task.name() if task else f"[{tid}]"
def sched_tasks(self, filters: Sequence[str]) -> List[Task]:
"""Tasks with scheduling history passing the filters, sorted by tid."""
return sorted((t for t in self.tasks.values()
if len(t.segs) and t.passes_filter(filters)),
key=lambda t: t.tid)
def io_tasks(self, filters: Sequence[str]) -> List[Task]:
"""Tasks with I/O passing the filters, most I/O first."""
return sorted((t for t in self.tasks.values()
if len(t.io) and t.passes_filter(filters)),
key=lambda t: -len(t.io))
def dump(self, power_only: bool, tasks_only: bool, filters: Sequence[str]) -> None:
"""Print a plain text summary, for use without a terminal UI."""
duration = self.last_time - self.first_time
span = max(duration, 1)
tasks = self.sched_tasks(filters)
io_tasks = self.io_tasks(filters)
print(f"Duration: {fmt_duration(duration)}, CPUs: {len(self.cpus)}, "
f"tasks: {len(tasks) or len(io_tasks)}, sched events: {self.sched_events}, "
f"power events: {self.power_events}, I/O events: {self.io_events}")
if not tasks_only:
for c in sorted(self.cpus.values(), key=lambda c: c.cpu):
busy = sum(e - s for s, e in zip(c.run.starts, c.run.ends))
print(f"CPU {c.cpu}: busy {busy * 100 / span:.1f}%, "
f"{len(c.run)} runs, {len(c.cstate)} idle periods, "
f"{len(c.pstate)} frequency periods")
if power_only:
return
print(f"{'Task':<24} {'TID':>8} {'Running':>12} {'Waiting':>12} {'Blocked':>12} "
f"{'Switches':>9} {'Wakeups':>8}")
for task in sorted(tasks, key=lambda t: -t.totals[STATE_RUNNING]):
print(f"{task.comm[:24]:<24} {task.tid:>8} "
f"{fmt_duration(task.totals[STATE_RUNNING]):>12} "
f"{fmt_duration(task.totals[STATE_WAITING]):>12} "
f"{fmt_duration(task.totals[STATE_BLOCKED]):>12} "
f"{task.switches:>9} {len(task.wakeups):>8}")
for task in io_tasks:
print(f"I/O {task.name()}: {len(task.io)} syscalls, {task.io_bytes} bytes")
Cell = Tuple[str, Style]
class ThemeColors:
"""Colors and Rich styles derived from the active Textual theme."""
def __init__(self, theme_variables: Mapping[str, str]) -> None:
self.running = theme_variables["primary"]
self.waiting = theme_variables["error"]
self.blocked = theme_variables["warning"]
self.idle_light = theme_variables["secondary-lighten-2"]
self.idle_dark = theme_variables["secondary-darken-2"]
self.freq_low = theme_variables["success"]
self.freq_high = theme_variables["error"]
self.io = [
theme_variables["success"],
theme_variables["error"],
theme_variables["warning"],
theme_variables["accent"],
theme_variables["primary"],
theme_variables["secondary-lighten-2"],
]
run_color = Color.parse(self.running).rich_color
wait_color = Color.parse(self.waiting).rich_color
block_color = Color.parse(self.blocked).rich_color
self.run_style = Style(color=run_color)
self.wait_style = Style(color=run_color, bgcolor=wait_color)
self.block_style = Style(color=run_color, bgcolor=block_color)
low = Color.parse(self.freq_low)
high = Color.parse(self.freq_high)
self.freq_styles = [Style(color=low.blend(high, x / 8).rich_color) for x in range(9)]
light = Color.parse(self.idle_light)
dark = Color.parse(self.idle_dark)
self.idle_styles = [Style(color=light.blend(dark, x / 8).rich_color) for x in range(9)]
self.io_styles = [Style(color=Color.parse(c).rich_color) for c in self.io]
self.io_err_styles = [Style(color=Color.parse(c).rich_color, underline=True)
for c in self.io]
accent = Color.parse(theme_variables["accent"]).rich_color
accent_muted = Color.parse(theme_variables["accent-muted"]).rich_color
self.selected_style = Style(color=accent, bgcolor=accent_muted, bold=True)
class Row(ABC):
"""A row within a timeline view."""
def __init__(self, label: str) -> None:
self._label = label
def label(self) -> str:
"""Label shown to the left of the row."""
return self._label
@abstractmethod
def segments(self) -> SegmentList:
"""Segments used for navigating between changes."""
@abstractmethod
def cells(self, t0: float, dt: float, width: int, colors: ThemeColors) -> List[Cell]:
"""Cells for the columns starting at time t0 and dt wide."""
@abstractmethod
def describe(self, time: float, t0: float, t1: float) -> str:
"""Rich markup describing the row at time within the window [t0, t1)."""
class TaskRow(Row):
"""Row showing the running, waiting and blocked states of a task.
The height of the bar shows the fraction of the time running, the
background shows waiting for a CPU or being blocked.
"""
def __init__(self, data: TimechartData, task: Task) -> None:
super().__init__(task.name())
self.data = data
self.task = task
def label(self) -> str:
return self.task.name()
def segments(self) -> SegmentList:
return self.task.segs
def cells(self, t0: float, dt: float, width: int, colors: ThemeColors) -> List[Cell]:
result = []
for col in self.task.segs.coverage(t0, dt, width, NUM_STATES):
run = col[STATE_RUNNING] / dt
wait = col[STATE_WAITING]
block = col[STATE_BLOCKED]
if wait > 0 and wait >= block:
style = colors.wait_style
elif block > 0:
style = colors.block_style
else:
style = colors.run_style
result.append((bar_char(run), style))
return result
def describe(self, time: float, t0: float, t1: float) -> str:
task = self.task
i = task.segs.find(time)
if i >= 0:
state = task.segs.keys[i]
desc = STATE_NAMES[state]
if state == STATE_RUNNING:
desc += f" on CPU {task.segs.data[i]}"
elif state == STATE_WAITING and task.segs.data[i] >= 0:
desc += f", last ran on CPU {task.segs.data[i]}"
start = task.segs.starts[i]
end = task.segs.ends[i]
desc += (f" from {self.data.fmt_time(start)} for "
f"{fmt_duration(end - start)}")
else:
desc = "sleeping or not traced"
window = task.segs.coverage(t0, max(t1 - t0, 1), 1, NUM_STATES)[0]
span = max(t1 - t0, 1)
lines = [
f"[b]{escape(task.name())}[/b]: {desc}",
f"In view: running {window[STATE_RUNNING] * 100 / span:.1f}%, "
f"waiting {window[STATE_WAITING] * 100 / span:.1f}%, "
f"blocked {window[STATE_BLOCKED] * 100 / span:.1f}%",
f"Total: running {fmt_duration(task.totals[STATE_RUNNING])}, "
f"waiting {fmt_duration(task.totals[STATE_WAITING])}, "
f"blocked {fmt_duration(task.totals[STATE_BLOCKED])}, "
f"{task.switches} switches, {len(task.wakeups)} wakeups",
]
idx = bisect.bisect_right(task.wakeups, (time, sys.maxsize)) - 1
if idx >= 0:
wake_time, waker = task.wakeups[idx]
lines.append(f"Last woken at {self.data.fmt_time(wake_time)} by "
f"{escape(self.data.task_name(waker))} (press 'w' to go to waker)")
if len(task.comms) > 1:
lines.append(f"Names: {escape(', '.join(task.comms))}")
return "\n".join(lines)
class CpuRow(Row):
"""Row showing how busy a CPU is, colored by frequency if known."""
def __init__(self, data: TimechartData, cpu: Cpu) -> None:
super().__init__(f"CPU {cpu.cpu}")
self.data = data
self.cpu = cpu
def segments(self) -> SegmentList:
return self.cpu.run
def cells(self, t0: float, dt: float, width: int, colors: ThemeColors) -> List[Cell]:
busy = self.cpu.run.coverage(t0, dt, width, 2)
freqs: Optional[List[List[float]]] = None
weighted: Optional[List[List[float]]] = None
if len(self.cpu.pstate) and self.data.max_freq > self.data.min_freq:
freqs = self.cpu.pstate.coverage(t0, dt, width, 2)
weighted = self.cpu.pstate.coverage(t0, dt, width, 2, weight_fn=float)
result = []
for x in range(width):
style = colors.run_style
if freqs and weighted and freqs[x][1] > 0:
freq = weighted[x][1] / freqs[x][1]
frac = (freq - self.data.min_freq) / (self.data.max_freq - self.data.min_freq)
style = colors.freq_styles[max(0, min(8, round(frac * 8)))]
result.append((bar_char(busy[x][1] / dt), style))
return result
def describe(self, time: float, t0: float, t1: float) -> str:
c = self.cpu
i = c.run.find(time)
if i >= 0:
desc = (f"running {escape(self.data.task_name(c.run.data[i]))} from "
f"{self.data.fmt_time(c.run.starts[i])} for "
f"{fmt_duration(c.run.ends[i] - c.run.starts[i])}")
else:
desc = "idle"
i = c.cstate.find(time)
if i >= 0:
desc += f", C-state C{c.cstate.data[i]}"
i = c.pstate.find(time)
if i >= 0:
desc += f", {c.pstate.data[i] / 1000:.0f} MHz"
span = max(t1 - t0, 1)
window = c.run.coverage(t0, span, 1, 2)[0]
return "\n".join([
f"[b]CPU {c.cpu}[/b]: {desc}",
f"In view: busy {window[1] * 100 / span:.1f}%",
"Bar height is the fraction of time busy" +
(", color is the frequency from low to high"
if len(c.pstate) else ""),
])
class CStateRow(Row):
"""Row showing the idle states of a CPU."""
def __init__(self, data: TimechartData, cpu: Cpu) -> None:
super().__init__(f" CPU {cpu.cpu} idle")
self.data = data
self.cpu = cpu
def segments(self) -> SegmentList:
return self.cpu.cstate
def cells(self, t0: float, dt: float, width: int, colors: ThemeColors) -> List[Cell]:
cov = self.cpu.cstate.coverage(t0, dt, width, 2)
depth = self.cpu.cstate.coverage(t0, dt, width, 2, weight_fn=float)
max_cstate = max(self.data.max_cstate, 1)
result = []
for x in range(width):
frac = cov[x][1] / dt
style = colors.idle_styles[0]
if cov[x][1] > 0:
avg = depth[x][1] / cov[x][1]
style = colors.idle_styles[max(0, min(8, round(avg * 8 / max_cstate)))]
result.append((bar_char(frac), style))
return result
def describe(self, time: float, t0: float, t1: float) -> str:
c = self.cpu
i = c.cstate.find(time)
if i >= 0:
desc = (f"C{c.cstate.data[i]} from {self.data.fmt_time(c.cstate.starts[i])} for "
f"{fmt_duration(c.cstate.ends[i] - c.cstate.starts[i])}")
else:
desc = "not idle"
span = max(t1 - t0, 1)
window = c.cstate.coverage(t0, span, 1, 2)[0]
return "\n".join([
f"[b]CPU {c.cpu} idle state[/b]: {desc}",
f"In view: idle {window[1] * 100 / span:.1f}%",
"Bar height is the fraction of time idle, darker colors are deeper C-states",
])
class FreqRow(Row):
"""Row showing the frequency of a CPU."""
def __init__(self, data: TimechartData, cpu: Cpu) -> None:
super().__init__(f" CPU {cpu.cpu} freq")
self.data = data
self.cpu = cpu
def segments(self) -> SegmentList:
return self.cpu.pstate
def cells(self, t0: float, dt: float, width: int, colors: ThemeColors) -> List[Cell]:
cov = self.cpu.pstate.coverage(t0, dt, width, 2)
weighted = self.cpu.pstate.coverage(t0, dt, width, 2, weight_fn=float)
max_freq = max(self.data.max_freq, 1)
min_freq = self.data.min_freq
result = []
for x in range(width):
if cov[x][1] <= 0:
result.append((" ", colors.freq_styles[0]))
continue
freq = weighted[x][1] / cov[x][1]
frac = (freq - min_freq) / (max_freq - min_freq) if max_freq > min_freq else 1.0
result.append((bar_char(max(freq / max_freq, 1 / 8)),
colors.freq_styles[max(0, min(8, round(frac * 8)))]))
return result
def describe(self, time: float, t0: float, t1: float) -> str:
c = self.cpu
i = c.pstate.find(time)
if i >= 0:
desc = (f"{c.pstate.data[i] / 1000:.0f} MHz from "
f"{self.data.fmt_time(c.pstate.starts[i])} for "
f"{fmt_duration(c.pstate.ends[i] - c.pstate.starts[i])}")
else:
desc = "unknown"
return "\n".join([
f"[b]CPU {c.cpu} frequency[/b]: {desc}",
f"Range: {self.data.min_freq / 1000:.0f} - {self.data.max_freq / 1000:.0f} MHz",
"Bar height is the frequency relative to the maximum",
])
class IoRow(Row):
"""Row showing the I/O syscalls of a task."""
def __init__(self, data: TimechartData, task: Task) -> None:
super().__init__(task.name())
self.data = data
self.task = task
def label(self) -> str:
return self.task.name()
def segments(self) -> SegmentList:
return self.task.io
def cells(self, t0: float, dt: float, width: int, colors: ThemeColors) -> List[Cell]:
errs = self.task.io.coverage(t0, dt, width, NUM_IOTYPES,
weight_fn=lambda d: 1.0 if d[1] < 0 else 0.0)
result = []
for x, col in enumerate(self.task.io.coverage(t0, dt, width, NUM_IOTYPES)):
total = sum(col)
if total <= 0:
result.append((" ", colors.io_styles[0]))
continue
iotype = col.index(max(col))
styles = colors.io_err_styles if sum(errs[x]) > 0 else colors.io_styles
result.append((bar_char(max(total / dt, 1 / 8)), styles[iotype]))
return result
def describe(self, time: float, t0: float, t1: float) -> str:
task = self.task
i = task.io.find(time)
if i < 0:
i = task.io.last_before(time)
prefix = "last I/O"
else:
prefix = "in"
if i >= 0:
fd, ret = task.io.data[i]
result = f"returned {ret}" if ret >= 0 else f"failed with error {-ret}"
desc = (f"{prefix} {IOTYPE_NAMES[task.io.keys[i]]} fd={fd} at "
f"{self.data.fmt_time(task.io.starts[i])} for "
f"{fmt_duration(task.io.ends[i] - task.io.starts[i])}, {result}")
else:
desc = "no I/O"
span = max(t1 - t0, 1)
window = task.io.coverage(t0, span, 1, NUM_IOTYPES)[0]
in_view = ", ".join(f"{IOTYPE_NAMES[t]} {window[t] * 100 / span:.1f}%"
for t in range(NUM_IOTYPES) if window[t] > 0)
return "\n".join([
f"[b]{escape(task.name())}[/b]: {desc}",
f"In view: {in_view or 'no I/O'}",
f"Total: {len(task.io)} I/O syscalls, {task.io_bytes} bytes",
])
@dataclass(frozen=True)
class TimeWindow:
"""The visible time range and the cursor, shared between views.
Immutable so that it can be a reactive value, the methods return new windows.
"""
first: int
last: int
start: float
end: float
cursor: float
@staticmethod
def whole(first: int, last: int) -> "TimeWindow":
"""A window showing the whole trace with the cursor at the start."""
last = max(last, first + 1)
return TimeWindow(first, last, first, last, first)
def span(self) -> float:
"""Length of the visible time range."""
return self.end - self.start
def reset(self) -> "TimeWindow":
"""Show the whole trace."""
return replace(self, start=self.first, end=self.last)
def with_range(self, start: float, span: float) -> "TimeWindow":
"""Set the visible range clamped to the trace."""
span = min(max(span, 100.0), self.last - self.first)
start = min(max(start, self.first), self.last - span)
return replace(self, start=start, end=start + span)
def zoom(self, factor: float) -> "TimeWindow":
"""Zoom by factor keeping the cursor at the same position."""
cursor = self.cursor
if not self.start <= cursor <= self.end:
cursor = (self.start + self.end) / 2
rel = (cursor - self.start) / self.span()
span = self.span() * factor
return replace(self, cursor=cursor).with_range(cursor - rel * span, span)
def pan(self, frac: float) -> "TimeWindow":