forked from open-telemetry/opentelemetry-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix memory leaks with weakref module
- Loading branch information
Showing
3 changed files
with
62 additions
and
2 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import gc | ||
import logging | ||
import weakref | ||
|
||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import ( | ||
OTLPMetricExporter, | ||
) | ||
from opentelemetry.sdk.metrics import MeterProvider | ||
from opentelemetry.sdk.metrics._internal.export import ( | ||
PeriodicExportingMetricReader, | ||
) | ||
|
||
logging.basicConfig(level=logging.DEBUG) | ||
|
||
|
||
def create_and_clean(): | ||
# setup_otlp_exporter | ||
otlp_exporter = OTLPMetricExporter( | ||
endpoint="http://localhost:4318/v1/metrics" | ||
) | ||
otlp_exporter_weakref = weakref.ref(otlp_exporter) | ||
|
||
reader = PeriodicExportingMetricReader( | ||
otlp_exporter, export_interval_millis=5000 | ||
) | ||
reader_weakref = weakref.ref(reader) | ||
|
||
provider = MeterProvider(metric_readers=[reader]) | ||
provider_weakref = weakref.ref(provider) | ||
|
||
provider.shutdown() | ||
return otlp_exporter_weakref, reader_weakref, provider_weakref | ||
|
||
|
||
def check_referrers(wr, name): | ||
if wr() is not None: | ||
logging.warning("%s was not properly garbage collected", name) | ||
referrers = gc.get_referrers(wr()) | ||
logging.debug(f"Direct referrers to %s: {len(referrers)}", name) | ||
for ref in referrers: | ||
logging.debug(f"%s referrer {str(ref)} type: {type(ref)}", name) | ||
else: | ||
logging.info("%s was properly garbage collected", name) | ||
|
||
|
||
def main(): | ||
otlp_exporter_weakref, reader_weakref, provider_weakref = ( | ||
create_and_clean() | ||
) | ||
gc.collect() | ||
|
||
check_referrers(otlp_exporter_weakref, "OTLP EXPORTER") | ||
check_referrers(reader_weakref, "READER") | ||
check_referrers(provider_weakref, "PROVIDER") | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |