| 1 |
import logging |
| 2 |
|
| 3 |
log = logging.getLogger(__name__) |
| 4 |
|
| 5 |
ROOT = 'Root' |
| 6 |
PARENT = 'Parent' |
| 7 |
SAMPLE = 'Sampled' |
| 8 |
|
| 9 |
HEADER_DELIMITER = ";" |
| 10 |
|
| 11 |
|
| 12 |
class TraceHeader(object): |
| 13 |
""" |
| 14 |
The sampling decision and trace ID are added to HTTP requests in |
| 15 |
tracing headers named ``X-Amzn-Trace-Id``. The first X-Ray-integrated |
| 16 |
service that the request hits adds a tracing header, which is read |
| 17 |
by the X-Ray SDK and included in the response. Learn more about |
| 18 |
`Tracing Header <http://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader>`_. |
| 19 |
""" |
| 20 |
def __init__(self, root=None, parent=None, sampled=None): |
| 21 |
""" |
| 22 |
:param str root: trace id |
| 23 |
:param str parent: parent id |
| 24 |
:param int sampled: 0 means not sampled, 1 means sampled |
| 25 |
""" |
| 26 |
self._root = root |
| 27 |
self._parent = parent |
| 28 |
self._sampled = None |
| 29 |
|
| 30 |
if sampled is not None: |
| 31 |
self._sampled = int(sampled) |
| 32 |
|
| 33 |
@classmethod |
| 34 |
def from_header_str(cls, header): |
| 35 |
""" |
| 36 |
Create a TraceHeader object from a tracing header string |
| 37 |
extracted from a http request headers. |
| 38 |
""" |
| 39 |
if not header: |
| 40 |
return cls() |
| 41 |
|
| 42 |
try: |
| 43 |
params = header.strip().split(HEADER_DELIMITER) |
| 44 |
header_dict = {} |
| 45 |
|
| 46 |
for param in params: |
| 47 |
entry = param.split('=') |
| 48 |
header_dict[entry[0]] = entry[1] |
| 49 |
|
| 50 |
return cls( |
| 51 |
root=header_dict.get(ROOT, None), |
| 52 |
parent=header_dict.get(PARENT, None), |
| 53 |
sampled=header_dict.get(SAMPLE, None), |
| 54 |
) |
| 55 |
|
| 56 |
except Exception: |
| 57 |
log.warning("malformed tracing header %s, ignore.", header) |
| 58 |
return cls() |
| 59 |
|
| 60 |
def to_header_str(self): |
| 61 |
""" |
| 62 |
Convert to a tracing header string that can be injected to |
| 63 |
outgoing http request headers. |
| 64 |
""" |
| 65 |
h_str = '' |
| 66 |
if self.root: |
| 67 |
h_str = ROOT + '=' + self.root |
| 68 |
if self.parent: |
| 69 |
h_str = h_str + HEADER_DELIMITER + PARENT + '=' + self.parent |
| 70 |
if self.sampled is not None: |
| 71 |
h_str = h_str + HEADER_DELIMITER + SAMPLE + '=' + str(self.sampled) |
| 72 |
|
| 73 |
return h_str |
| 74 |
|
| 75 |
@property |
| 76 |
def root(self): |
| 77 |
""" |
| 78 |
Return trace id of the header |
| 79 |
""" |
| 80 |
return self._root |
| 81 |
|
| 82 |
@property |
| 83 |
def parent(self): |
| 84 |
""" |
| 85 |
Return the parent segment id in the header |
| 86 |
""" |
| 87 |
return self._parent |
| 88 |
|
| 89 |
@property |
| 90 |
def sampled(self): |
| 91 |
""" |
| 92 |
Return the sampling decision in the header. |
| 93 |
It's either 0 or 1. |
| 94 |
""" |
| 95 |
return self._sampled |