| 1 |
import logging |
| 2 |
import os |
| 3 |
import binascii |
| 4 |
import time |
| 5 |
import string |
| 6 |
|
| 7 |
import jsonpickle |
| 8 |
|
| 9 |
from ..utils.compat import annotation_value_types, string_types |
| 10 |
from .throwable import Throwable |
| 11 |
from . import http |
| 12 |
from ..exceptions.exceptions import AlreadyEndedException |
| 13 |
|
| 14 |
|
| 15 |
log = logging.getLogger(__name__) |
| 16 |
|
| 17 |
# List of valid characters found at http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html |
| •18 |
_valid_name_characters = string.ascii_letters + string.digits + r'_.:/%&#=+\-@ ' |
| 19 |
|
| 20 |
|
| 21 |
class Entity(object): |
| 22 |
""" |
| 23 |
The parent class for segment/subsegment. It holds common properties |
| 24 |
and methods on segment and subsegment. |
| 25 |
""" |
| 26 |
|
| 27 |
def __init__(self, name): |
| 28 |
|
| 29 |
# required attributes |
| 30 |
self.id = self._generate_random_id() |
| 31 |
self.name = name |
| 32 |
self.name = ''.join([c for c in name if c in _valid_name_characters]) |
| 33 |
self.start_time = time.time() |
| 34 |
self.parent_id = None |
| 35 |
|
| 36 |
if self.name != name: |
| 37 |
log.warning("Removing Segment/Subsugment Name invalid characters.") |
| 38 |
|
| 39 |
# sampling |
| 40 |
self.sampled = True |
| 41 |
|
| 42 |
# state |
| 43 |
self.in_progress = True |
| 44 |
|
| 45 |
# meta fields |
| 46 |
self.http = {} |
| 47 |
self.annotations = {} |
| 48 |
self.metadata = {} |
| 49 |
self.aws = {} |
| 50 |
self.cause = {} |
| 51 |
|
| 52 |
# child subsegments |
| 53 |
# list is thread-safe |
| 54 |
self.subsegments = [] |
| 55 |
|
| 56 |
self.user = None |
| 57 |
|
| 58 |
def close(self, end_time=None): |
| 59 |
""" |
| 60 |
Close the trace entity by setting `end_time` |
| 61 |
and flip the in progress flag to False. |
| 62 |
|
| 63 |
:param int end_time: Epoch in seconds. If not specified |
| 64 |
current time will be used. |
| 65 |
""" |
| 66 |
self._check_ended() |
| 67 |
|
| 68 |
if end_time: |
| 69 |
self.end_time = end_time |
| 70 |
else: |
| 71 |
self.end_time = time.time() |
| 72 |
self.in_progress = False |
| 73 |
|
| 74 |
def add_subsegment(self, subsegment): |
| 75 |
""" |
| 76 |
Add input subsegment as a child subsegment. |
| 77 |
""" |
| 78 |
self._check_ended() |
| 79 |
subsegment.parent_id = self.id |
| 80 |
self.subsegments.append(subsegment) |
| 81 |
|
| 82 |
def remove_subsegment(self, subsegment): |
| 83 |
""" |
| 84 |
Remove input subsegment from child subsegments. |
| 85 |
""" |
| 86 |
self._check_ended() |
| 87 |
self.subsegments.remove(subsegment) |
| 88 |
|
| 89 |
def put_http_meta(self, key, value): |
| 90 |
""" |
| 91 |
Add http related metadata. |
| 92 |
|
| 93 |
:param str key: Currently supported keys are: |
| 94 |
* url |
| 95 |
* method |
| 96 |
* user_agent |
| 97 |
* client_ip |
| 98 |
* status |
| 99 |
* content_length |
| 100 |
:param value: status and content_length are int and for other |
| 101 |
supported keys string should be used. |
| 102 |
""" |
| 103 |
self._check_ended() |
| 104 |
|
| 105 |
if value is None: |
| 106 |
return |
| 107 |
|
| 108 |
if key == http.STATUS: |
| 109 |
if isinstance(value, string_types): |
| 110 |
value = int(value) |
| 111 |
self.apply_status_code(value) |
| 112 |
|
| 113 |
if key in http.request_keys: |
| 114 |
if 'request' not in self.http: |
| 115 |
self.http['request'] = {} |
| 116 |
self.http['request'][key] = value |
| 117 |
elif key in http.response_keys: |
| 118 |
if 'response' not in self.http: |
| 119 |
self.http['response'] = {} |
| 120 |
self.http['response'][key] = value |
| 121 |
else: |
| 122 |
log.warning("ignoring unsupported key %s in http meta.", key) |
| 123 |
|
| 124 |
def put_annotation(self, key, value): |
| 125 |
""" |
| 126 |
Annotate segment or subsegment with a key-value pair. |
| 127 |
Annotations will be indexed for later search query. |
| 128 |
|
| 129 |
:param str key: annotation key |
| 130 |
:param object value: annotation value. Any type other than |
| 131 |
string/number/bool will be dropped |
| 132 |
""" |
| 133 |
self._check_ended() |
| 134 |
|
| 135 |
if not isinstance(key, string_types): |
| 136 |
log.warning("ignoring non string type annotation key with type %s.", type(key)) |
| 137 |
return |
| 138 |
|
| 139 |
if not isinstance(value, annotation_value_types): |
| 140 |
log.warning("ignoring unsupported annotation value type %s.", type(value)) |
| 141 |
return |
| 142 |
|
| 143 |
self.annotations[key] = value |
| 144 |
|
| 145 |
def put_metadata(self, key, value, namespace='default'): |
| 146 |
""" |
| 147 |
Add metadata to segment or subsegment. Metadata is not indexed |
| 148 |
but can be later retrieved by BatchGetTraces API. |
| 149 |
|
| 150 |
:param str namespace: optional. Default namespace is `default`. |
| 151 |
It must be a string and prefix `AWS.` is reserved. |
| 152 |
:param str key: metadata key under specified namespace |
| 153 |
:param object value: any object that can be serialized into JSON string |
| 154 |
""" |
| 155 |
self._check_ended() |
| 156 |
|
| 157 |
if not isinstance(namespace, string_types): |
| 158 |
log.warning("ignoring non string type metadata namespace") |
| 159 |
return |
| 160 |
|
| 161 |
if namespace.startswith('AWS.'): |
| 162 |
log.warning("Prefix 'AWS.' is reserved, drop metadata with namespace %s", namespace) |
| 163 |
return |
| 164 |
|
| 165 |
if self.metadata.get(namespace, None): |
| 166 |
self.metadata[namespace][key] = value |
| 167 |
else: |
| 168 |
self.metadata[namespace] = {key: value} |
| 169 |
|
| 170 |
def set_aws(self, aws_meta): |
| 171 |
""" |
| 172 |
set aws section of the entity. |
| 173 |
This method is called by global recorder and botocore patcher |
| 174 |
to provide additonal information about AWS runtime. |
| 175 |
It is not recommended to manually set aws section. |
| 176 |
""" |
| 177 |
self._check_ended() |
| 178 |
self.aws = aws_meta |
| 179 |
|
| 180 |
def set_user(self, user): |
| 181 |
""" |
| 182 |
set user of an segment or subsegment. |
| 183 |
one segment or subsegment can only hold one user. |
| 184 |
User is indexed and can be later queried. |
| 185 |
""" |
| 186 |
self._check_ended() |
| 187 |
self.user = user |
| 188 |
|
| 189 |
def add_throttle_flag(self): |
| 190 |
self.throttle = True |
| 191 |
|
| 192 |
def add_fault_flag(self): |
| 193 |
self.fault = True |
| 194 |
|
| 195 |
def add_error_flag(self): |
| 196 |
self.error = True |
| 197 |
|
| 198 |
def apply_status_code(self, status_code): |
| 199 |
""" |
| 200 |
When a trace entity is generated under the http context, |
| 201 |
the status code will affect this entity's fault/error/throttle flags. |
| 202 |
Flip these flags based on status code. |
| 203 |
""" |
| 204 |
self._check_ended() |
| 205 |
if not status_code: |
| 206 |
return |
| 207 |
|
| 208 |
if status_code >= 500: |
| 209 |
self.add_fault_flag() |
| 210 |
elif status_code == 429: |
| 211 |
self.add_throttle_flag() |
| 212 |
self.add_error_flag() |
| 213 |
elif status_code >= 400: |
| 214 |
self.add_error_flag() |
| 215 |
|
| 216 |
def add_exception(self, exception, stack, remote=False): |
| 217 |
""" |
| 218 |
Add an exception to trace entities. |
| 219 |
|
| 220 |
:param Exception exception: the catched exception. |
| 221 |
:param list stack: the output from python built-in |
| 222 |
`traceback.extract_stack()`. |
| 223 |
:param bool remote: If False it means it's a client error |
| 224 |
instead of a downstream service. |
| 225 |
""" |
| 226 |
self._check_ended() |
| 227 |
self.add_fault_flag() |
| 228 |
|
| 229 |
if hasattr(exception, '_recorded'): |
| 230 |
setattr(self, 'cause', getattr(exception, '_cause_id')) |
| 231 |
return |
| 232 |
|
| 233 |
exceptions = [] |
| 234 |
exceptions.append(Throwable(exception, stack, remote)) |
| 235 |
|
| 236 |
self.cause['exceptions'] = exceptions |
| 237 |
self.cause['working_directory'] = os.getcwd() |
| 238 |
|
| 239 |
def serialize(self): |
| 240 |
""" |
| 241 |
Serialize to JSON document that can be accepted by the |
| 242 |
X-Ray backend service. It uses jsonpickle to perform |
| 243 |
serialization. |
| 244 |
""" |
| 245 |
try: |
| 246 |
return jsonpickle.encode(self, unpicklable=False) |
| 247 |
except Exception: |
| 248 |
log.exception("got an exception during serialization") |
| 249 |
|
| 250 |
def _delete_empty_properties(self, properties): |
| 251 |
""" |
| 252 |
Delete empty properties before serialization to avoid |
| 253 |
extra keys with empty values in the output json. |
| 254 |
""" |
| 255 |
if not self.parent_id: |
| 256 |
del properties['parent_id'] |
| 257 |
if not self.subsegments: |
| 258 |
del properties['subsegments'] |
| 259 |
if not self.aws: |
| 260 |
del properties['aws'] |
| 261 |
if not self.http: |
| 262 |
del properties['http'] |
| 263 |
if not self.cause: |
| 264 |
del properties['cause'] |
| 265 |
if not self.annotations: |
| 266 |
del properties['annotations'] |
| 267 |
if not self.metadata: |
| 268 |
del properties['metadata'] |
| 269 |
if not self.user: |
| 270 |
del properties['user'] |
| 271 |
|
| 272 |
del properties['sampled'] |
| 273 |
|
| 274 |
def _check_ended(self): |
| 275 |
if not self.in_progress: |
| 276 |
raise AlreadyEndedException("Already ended segment and subsegment cannot be modified.") |
| 277 |
|
| 278 |
def _generate_random_id(self): |
| 279 |
""" |
| 280 |
Generate a random 16-digit hex str. |
| 281 |
This is used for generating segment/subsegment id. |
| 282 |
""" |
| 283 |
return binascii.b2a_hex(os.urandom(8)).decode('utf-8') |