From 22a5a84be25d97eefc3cce9224c1cf4733d378db Mon Sep 17 00:00:00 2001 From: "lurious.lyh" Date: Fri, 3 Jan 2025 13:52:39 +0800 Subject: [PATCH] Fix the issue of duplicate traceId and spanId caused by RandomIdGenerator. --- .../src/opentelemetry/sdk/trace/id_generator.py | 11 +++++++---- .../tests/trace/test_id_generator.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 opentelemetry-sdk/tests/trace/test_id_generator.py diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/id_generator.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/id_generator.py index cd1f89bcde2..febaa38baf6 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/id_generator.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/id_generator.py @@ -47,14 +47,17 @@ class RandomIdGenerator(IdGenerator): bits when generating IDs. """ + def __init__(self): + self._rand = random.Random() + def generate_span_id(self) -> int: - span_id = random.getrandbits(64) + span_id = self._rand.getrandbits(64) while span_id == trace.INVALID_SPAN_ID: - span_id = random.getrandbits(64) + span_id = self._rand.getrandbits(64) return span_id def generate_trace_id(self) -> int: - trace_id = random.getrandbits(128) + trace_id = self._rand.getrandbits(128) while trace_id == trace.INVALID_TRACE_ID: - trace_id = random.getrandbits(128) + trace_id = self._rand.getrandbits(128) return trace_id diff --git a/opentelemetry-sdk/tests/trace/test_id_generator.py b/opentelemetry-sdk/tests/trace/test_id_generator.py new file mode 100644 index 00000000000..f43b0730bc5 --- /dev/null +++ b/opentelemetry-sdk/tests/trace/test_id_generator.py @@ -0,0 +1,15 @@ +import unittest + +from opentelemetry.sdk.trace import RandomIdGenerator + + +class TestIdGenerator(unittest.TestCase): + + def test_random_id_generator(self): + import random + random.seed(10) + id_generator = RandomIdGenerator() + trace_id = id_generator.generate_trace_id() + span_id = id_generator.generate_span_id() + self.assertNotEqual(trace_id, 164207228320579316746596838417247989971) + self.assertNotEqual(span_id, 273610340023782072)