xref: /aosp_15_r20/external/bcc/tools/oomkill.py (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1#!/usr/bin/env python
2#
3# oomkill   Trace oom_kill_process(). For Linux, uses BCC, eBPF.
4#
5# This traces the kernel out-of-memory killer, and prints basic details,
6# including the system load averages. This can provide more context on the
7# system state at the time of OOM: was it getting busier or steady, based
8# on the load averages? This tool may also be useful to customize for
9# investigations; for example, by adding other task_struct details at the time
10# of OOM.
11#
12# Copyright 2016 Netflix, Inc.
13# Licensed under the Apache License, Version 2.0 (the "License")
14#
15# 09-Feb-2016   Brendan Gregg   Created this.
16
17from bcc import BPF
18from time import strftime
19
20# linux stats
21loadavg = "/proc/loadavg"
22
23# define BPF program
24bpf_text = """
25#include <uapi/linux/ptrace.h>
26#include <linux/oom.h>
27
28struct data_t {
29    u32 fpid;
30    u32 tpid;
31    u64 pages;
32    char fcomm[TASK_COMM_LEN];
33    char tcomm[TASK_COMM_LEN];
34};
35
36BPF_PERF_OUTPUT(events);
37
38void kprobe__oom_kill_process(struct pt_regs *ctx, struct oom_control *oc, const char *message)
39{
40    struct task_struct *p = oc->chosen;
41    struct data_t data = {};
42    u32 pid = bpf_get_current_pid_tgid() >> 32;
43
44    data.fpid = pid;
45    data.tpid = p->tgid;
46    data.pages = oc->totalpages;
47    bpf_get_current_comm(&data.fcomm, sizeof(data.fcomm));
48    bpf_probe_read_kernel(&data.tcomm, sizeof(data.tcomm), p->comm);
49    events.perf_submit(ctx, &data, sizeof(data));
50}
51"""
52
53# process event
54def print_event(cpu, data, size):
55    event = b["events"].event(data)
56    with open(loadavg) as stats:
57        avgline = stats.read().rstrip()
58    print(("%s Triggered by PID %d (\"%s\"), OOM kill of PID %d (\"%s\")"
59        ", %d pages, loadavg: %s") % (strftime("%H:%M:%S"), event.fpid,
60        event.fcomm.decode('utf-8', 'replace'), event.tpid,
61        event.tcomm.decode('utf-8', 'replace'), event.pages, avgline))
62
63# initialize BPF
64b = BPF(text=bpf_text)
65print("Tracing OOM kills... Ctrl-C to stop.")
66b["events"].open_perf_buffer(print_event)
67while 1:
68    try:
69        b.perf_buffer_poll()
70    except KeyboardInterrupt:
71        exit()
72