Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the issue of duplicate traceId and spanId caused by RandomIdGenerator #4377

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/id_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
15 changes: 15 additions & 0 deletions opentelemetry-sdk/tests/trace/test_id_generator.py
Original file line number Diff line number Diff line change
@@ -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)