Debian Codegraph @

awscrt/_test.py

raw symbols SCIP
1 """
2 Private utilities for testing
3 """
4 import _awscrt
5 from awscrt import NativeResource
6 from awscrt.common import join_all_native_threads
7 import gc
8 import inspect
9 import os
10 import sys
11 import time
12 import types
13
14 from awscrt.io import ClientBootstrap, DefaultHostResolver, EventLoopGroup
15
16
17 def native_memory_usage() -> int:
18 """
19 Returns number of bytes currently allocated by awscrt's native code.
20
21 `AWS_CRT_MEMORY_TRACING `environment variable must be set before module
22 is loaded, or 0 will always be returned. Legal values are:
23
24 * `AWS_CRT_MEMORY_TRACING=0`: No tracing
25
26 * `AWS_CRT_MEMORY_TRACING=1`: Only track allocation sizes and total allocated
27
28 * `AWS_CRT_MEMORY_TRACING=2`: Capture callstacks for each allocation
29 """
30 return _awscrt.native_memory_usage()
31
32
33 def dump_native_memory():
34 """
35 If there are outstanding allocations from awscrt's native code, dump them
36 to log, along with any information gathered based on the tracing level.
37
38 In order to see the dump, logging must initialized at `LogLevel.Trace`
39 and the `AWS_CRT_MEMORY_TRACING` environment variable must be non-zero
40 when module is loaded. Legal values are:
41
42 * `AWS_CRT_MEMORY_TRACING=0`: No tracing
43
44 * `AWS_CRT_MEMORY_TRACING=1`: Only track allocation sizes and total allocated
45
46 * `AWS_CRT_MEMORY_TRACING=2`: Capture callstacks for each allocation
47 """
48 return _awscrt.native_memory_dump()
49
50
51 def check_for_leaks(*, timeout_sec=10.0):
52 """
53 Checks that all awscrt resources have been freed after a test.
54
55 If any resources still exist, debugging info is printed and an exception is raised.
56
57 Requirements:
58 * `awscrt.NativeResource._track_lifetime = True`: must be set before test begins
59 to ensure accurate tracking.
60
61 * `AWS_CRT_MEMORY_TRACING=2`: environment variable that must be set before
62 any awscrt modules are imported, to ensure accurate native leak checks.
63
64 * `AWS_CRT_MEMORY_PRINT_SECRETS_OK=1`: optional environment variable that
65 will print the full contents of leaked python objects. DO NOT SET THIS
66 if the test results will be made public as it may result in secrets
67 being leaked.
68 """
69 ClientBootstrap.release_static_default()
70 EventLoopGroup.release_static_default()
71 DefaultHostResolver.release_static_default()
72
73 if os.getenv('AWS_CRT_MEMORY_TRACING') != '2':
74 raise RuntimeError("environment variable AWS_CRT_MEMORY_TRACING=2 must be set for accurate leak checks")
75
76 if not NativeResource._track_lifetime:
77 raise RuntimeError("awscrt.NativeResource._track_lifetime=True must be set for accurate leak checks")
78
79 # Native resources might need a few more ticks to finish cleaning themselves up.
80 wait_until = time.time() + timeout_sec
81 while time.time() < wait_until:
82 if not NativeResource._living and not native_memory_usage() > 0:
83 return
84 gc.collect()
85 # join_all_native_threads() is sometimes required to get mem usage to 0
86 join_all_native_threads(timeout_sec=0.1)
87 time.sleep(0.1)
88
89 # Print out debugging info on leaking resources
90 num_living_resources = len(NativeResource._living)
91 if num_living_resources:
92
93 leak_secrets_ok = os.getenv('AWS_CRT_MEMORY_PRINT_SECRETS_OK') == '1'
94 if leak_secrets_ok:
95 print("Leaking NativeResources:")
96 else:
97 print("Leaking NativeResources (set AWS_CRT_MEMORY_PRINT_SECRETS_OK=1 env var for more detailed report):")
98
99 def _printobj(prefix, obj):
100 # be sure not to accidentally print a dictionary with a password in it
101 if leak_secrets_ok:
102 s = str(obj)
103 if len(s) > 1000:
104 s = s[:1000] + '...TRUNCATED PRINT'
105 print(prefix, s)
106 else:
107 print(prefix, type(obj))
108
109 for i in NativeResource._living:
110 _printobj('-', i)
111
112 # getrefcount(i) returns 4+ here, but 2 of those are due to debugging.
113 # Don't show:
114 # - 1 for WeakSet iterator due to this for-loop.
115 # - 1 for getrefcount(i)'s reference.
116 # But do show:
117 # - 1 for item's self-reference.
118 # - the rest are what's causing this leak.
119 refcount = sys.getrefcount(i) - 2
120
121 # Gather list of referrers, but don't show those created by the act of iterating the WeakSet
122 referrers = []
123 for r in gc.get_referrers(i):
124 if isinstance(r, types.FrameType):
125 frameinfo = inspect.getframeinfo(r)
126 our_fault = (frameinfo.filename.endswith('_weakrefset.py') or
127 frameinfo.filename.endswith('awscrt/_test.py'))
128 if our_fault:
129 continue
130
131 referrers.append(r)
132
133 print(' sys.getrefcount():', refcount)
134 print(' gc.referrers():', len(referrers))
135 for r in referrers:
136 if isinstance(r, types.FrameType):
137 _printobj(' -', inspect.getframeinfo(r))
138 else:
139 _printobj(' -', r)
140
141 mem_bytes = native_memory_usage()
142 if mem_bytes > 0:
143 print('Leaking {} bytes native memory (enable Trace logging to see more)'.format(mem_bytes))
144 dump_native_memory()
145
146 raise RuntimeError("awscrt leak check failed. {} NativeResource objects. {} bytes native memory".format(
147 num_living_resources, mem_bytes))