Skip to content

Commit 9f3d0df

Browse files
authored
Pid namespace support (#5101)
cpudist.py supports run in pid namespace
1 parent 6acb86e commit 9f3d0df

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

tools/cpudist.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from bcc import BPF
2121
from time import sleep, strftime
2222
import argparse
23+
import os
2324

2425
examples = """examples:
2526
cpudist # summarize on-CPU time as a histogram
@@ -130,8 +131,17 @@
130131
u32 tgid = pid_tgid >> 32, pid = pid_tgid;
131132
u32 cpu = bpf_get_smp_processor_id();
132133
134+
struct bpf_pidns_info ns = {};
135+
if (USE_PIDNS && !bpf_get_ns_current_pid_tgid(PIDNS_DEV, PIDNS_INO, &ns, sizeof(struct bpf_pidns_info))) {
136+
PID_STORE
137+
138+
tgid = ns.tgid;
139+
pid = ns.pid;
140+
}
141+
133142
u32 prev_pid = prev->pid;
134143
u32 prev_tgid = prev->tgid;
144+
PID_TRANSLATE
135145
#ifdef ONCPU
136146
update_hist(prev_tgid, prev_pid, cpu, ts);
137147
#else
@@ -169,6 +179,32 @@
169179

170180
storage_str = ""
171181
store_str = ""
182+
pid_store = ""
183+
pid_translate = ""
184+
185+
try:
186+
devinfo = os.stat("/proc/self/ns/pid")
187+
version = "".join([ver.zfill(2) for ver in os.uname().release.split(".")])
188+
# Need Linux >= 5.7 to have helper bpf_get_ns_current_pid_tgid() available:
189+
assert(version[:4] >= "0507")
190+
bpf_text = bpf_text.replace('USE_PIDNS', "1")
191+
bpf_text = bpf_text.replace('PIDNS_DEV', str(devinfo.st_dev))
192+
bpf_text = bpf_text.replace('PIDNS_INO', str(devinfo.st_ino))
193+
storage_str = "BPF_HASH(ns_pid, u32, u32, MAX_PID);\n"
194+
pid_store = """ns_pid.update(&pid, &ns.pid);
195+
ns_pid.update(&tgid, &ns.tgid);"""
196+
pid_translate = """
197+
u32 *ns_pid_val = ns_pid.lookup(&prev_pid);
198+
u32 *ns_tgid_val = ns_pid.lookup(&prev_tgid);
199+
if (ns_pid_val && ns_tgid_val) {
200+
prev_pid = *ns_pid_val;
201+
prev_tgid = *ns_tgid_val;
202+
}
203+
"""
204+
except:
205+
bpf_text = bpf_text.replace('USE_PIDNS', "0")
206+
bpf_text = bpf_text.replace('PIDNS_DEV', "0")
207+
bpf_text = bpf_text.replace('PIDNS_INO', "0")
172208

173209
if args.pids or args.tids:
174210
section = "pid"
@@ -197,6 +233,8 @@
197233
}
198234
"""
199235

236+
bpf_text = bpf_text.replace("PID_STORE", pid_store)
237+
bpf_text = bpf_text.replace("PID_TRANSLATE", pid_translate)
200238
bpf_text = bpf_text.replace("STORAGE", storage_str)
201239
bpf_text = bpf_text.replace("STORE", store_str)
202240

0 commit comments

Comments
 (0)