Skip to content

Commit 9ed7b34

Browse files
committed
Proper ID generation and conversion
1 parent 9047f7a commit 9ed7b34

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

instana/util.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import random
2+
import os
3+
import time
4+
import struct
5+
import binascii
6+
7+
_rnd = random.Random()
8+
_current_pid = 0
9+
10+
11+
def generate_id():
12+
""" Generate a 64bit signed integer for use as a Span or Trace ID """
13+
global _current_pid
14+
15+
pid = os.getpid()
16+
if (_current_pid != pid):
17+
_current_pid = pid
18+
_rnd.seed(int(1000000 * time.time()) ^ pid)
19+
return _rnd.randint(-9223372036854775808, 9223372036854775807)
20+
21+
22+
def id_to_header(id):
23+
""" Convert a 64bit signed integer to an unsigned base 16 hex string """
24+
25+
if not isinstance(id, int):
26+
return ""
27+
28+
byteString = struct.pack('>q', id)
29+
return binascii.hexlify(byteString).lstrip('0')
30+
31+
32+
def header_to_id(header):
33+
""" Convert an unsigned base 16 hex string into a 64bit signed integer """
34+
35+
if not isinstance(header, basestring):
36+
return 0
37+
38+
# Pad the header to 16 chars
39+
header = header.zfill(16)
40+
r = binascii.unhexlify(header)
41+
return struct.unpack('>q', r)[0]

0 commit comments

Comments
 (0)