From 63103fa6fb6aec91956dddc038759685ca8d9624 Mon Sep 17 00:00:00 2001 From: Antonio Terceiro Date: Tue, 22 Mar 2022 11:24:57 -0300 Subject: [PATCH] bcc: add method to close file descriptors I have a long running process that attaches BPF programs to containers, and I want those programs to stay attached after the BPF object goes out of scope. After some time, the open file descriptors pile up and my process starts failing since it cannot open new files. This close() method allows me to create a BPF object, attach my function, then close the associated file descriptors without detaching the program. Signed-off-by: Antonio Terceiro --- src/python/bcc/__init__.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/python/bcc/__init__.py b/src/python/bcc/__init__.py index 1118698ee10b..eb95f6a7bac3 100644 --- a/src/python/bcc/__init__.py +++ b/src/python/bcc/__init__.py @@ -1736,6 +1736,20 @@ def add_module(modname): def donothing(self): """the do nothing exit handler""" + + def close(self): + """close(self) + + Closes all associated files descriptors. Attached BPF programs are not + detached. + """ + for name, fn in list(self.funcs.items()): + os.close(fn.fd) + del self.funcs[name] + if self.module: + lib.bpf_module_destroy(self.module) + self.module = None + def cleanup(self): # Clean up opened probes for k, v in list(self.kprobe_fds.items()): @@ -1763,12 +1777,8 @@ def cleanup(self): if self.tracefile: self.tracefile.close() self.tracefile = None - for name, fn in list(self.funcs.items()): - os.close(fn.fd) - del self.funcs[name] - if self.module: - lib.bpf_module_destroy(self.module) - self.module = None + + self.close() # Clean up ringbuf if self._ringbuf_manager: