From 6537b6e88a97a65014c7c413dce02f310741a7d1 Mon Sep 17 00:00:00 2001 From: Albert Wang Date: Sat, 30 Dec 2023 14:25:45 -0800 Subject: [PATCH] Gracefully error out when there are concurrent profilers --- project/tests/test_collector.py | 15 +++++++++++++++ silk/collector.py | 8 +++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/project/tests/test_collector.py b/project/tests/test_collector.py index cd00a67b..dd35410f 100644 --- a/project/tests/test_collector.py +++ b/project/tests/test_collector.py @@ -1,3 +1,6 @@ +import cProfile +import sys + from django.test import TestCase from tests.util import DictStorage @@ -47,6 +50,18 @@ def test_finalise(self): self.assertTrue(content) self.assertGreater(len(content), 0) + def test_configure_exception(self): + other_profiler = cProfile.Profile() + other_profiler.enable() + collector = DataCollector() + collector.configure() + other_profiler.disable() + if sys.version_info >= (3, 12): + self.assertEqual(collector.local.pythonprofiler, None) + else: + self.assertIsNotNone(collector.local.pythonprofiler) + collector.stop_python_profiler() + def test_profile_file_name_with_disabled_extended_file_name(self): SilkyConfig().SILKY_PYTHON_PROFILER_EXTENDED_FILE_NAME = False request_path = 'normal/uri/' diff --git a/silk/collector.py b/silk/collector.py index 6c7f854b..912b9298 100644 --- a/silk/collector.py +++ b/silk/collector.py @@ -92,7 +92,13 @@ def configure(self, request=None, should_profile=True): self._configure() if should_profile: self.local.pythonprofiler = cProfile.Profile() - self.local.pythonprofiler.enable() + try: + self.local.pythonprofiler.enable() + except ValueError as e: + # Deal with cProfile not being allowed to run concurrently + # https://github.com/jazzband/django-silk/issues/682 + Logger.error('Could not enable python profiler, %s' % str(e), exc_info=True) + self.local.pythonprofiler = None def clear(self): self.request = None