Last active
September 5, 2018 11:19
-
-
Save mhils/5565e7584dc5c847edcf4071cfec9619 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Memory Finder | |
- Use case: Find out what's holding on to a flow to troubleshoot garbage collection | |
- Holds a reference to the first flow in a capture | |
- Prints out who else is holding on to the flow every second | |
""" | |
import threading | |
import weakref | |
import gc | |
import time | |
import inspect | |
first_flow = lambda: None | |
def pprint(x, indent=""): | |
print(indent + type(x).__name__ + "@" + str(id(x)) + ": " + str(x).replace("\r\n",";")[:60]) | |
def print_refs(x, depth, parent=None, indent = ""): | |
gc.collect() | |
refs = tuple(sorted(gc.get_referrers(x), key=id)) | |
for ref in refs: | |
if ref in (parent, inspect.currentframe()): | |
continue | |
pprint(ref, indent) | |
print(indent + "-" * 10) | |
if depth: | |
print_refs(ref, depth-1, refs, indent + " " * 4) | |
def print_state(): | |
cframe = inspect.currentframe() | |
while True: | |
print("#" * 10) | |
gc.collect() | |
f = first_flow() | |
if f: | |
print(">" * 10) | |
print_refs(f, 2, cframe) | |
f = None | |
time.sleep(1) | |
class MemFinder: | |
done: bool = False | |
def load(self, loader): | |
print("start") | |
threading.Thread(target=print_state, daemon=True).start() | |
def request(self, flow): | |
""" | |
Called when a server response has been received. | |
""" | |
if not self.done: | |
global first_flow | |
first_flow = weakref.ref(flow) | |
self.done = True | |
addons = [ | |
MemFinder() | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment