Skip to content
This repository was archived by the owner on Jun 13, 2023. It is now read-only.

Commit 5b300ab

Browse files
authored
fix(tornado.py): fix tornado mis-handle of 404s (#314)
1 parent 1ab8c52 commit 5b300ab

7 files changed

Lines changed: 75 additions & 21 deletions

File tree

epsagon/events/redis.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
from ..event import BaseEvent
1010
from ..trace import trace_factory
11+
from ..utils import add_data_if_needed
12+
1113

1214
MAX_VALUE_SIZE = 1024
1315
MAX_CMD_PIPELINE = 10
@@ -110,6 +112,13 @@ def __init__(self, wrapped, instance, args, kwargs, start_time, response,
110112
self.resource['operation'] = operation
111113
self.resource['metadata']['Redis Key'] = key
112114

115+
if response:
116+
add_data_if_needed(
117+
self.resource['metadata'],
118+
'redis.response',
119+
response
120+
)
121+
113122

114123
class RedisMultiExecutionEvent(BaseRedisEvent):
115124
"""

epsagon/events/urllib3.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,16 +113,20 @@ def update_response(self, response):
113113
'response_headers',
114114
headers
115115
)
116-
response_body = response.peek()
116+
response_body = getattr(response, 'data', None)
117+
if not response_body and getattr(response, 'peek', None):
118+
response_body = response.peek()
117119
if isinstance(response_body, bytes):
118120
try:
119121
response_body = response_body.decode('utf-8')
120122
except UnicodeDecodeError:
121123
response_body = str(response_body)
122-
add_data_if_needed(
123-
self.resource['metadata'],
124-
'response_body',
125-
response_body)
124+
if response_body:
125+
add_data_if_needed(
126+
self.resource['metadata'],
127+
'response_body',
128+
response_body
129+
)
126130

127131
# Detect errors based on status code
128132
if response.status >= HTTP_ERR_CODE:

epsagon/modules/logging.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import wrapt
1212

1313
from ..trace import trace_factory
14-
from ..utils import print_debug
14+
from ..utils import print_debug, get_trace_log_config
1515

1616
LOGGING_FUNCTIONS = (
1717
'info',
@@ -99,7 +99,7 @@ def patch():
9999
wrapt.wrap_function_wrapper('logging', 'Logger.exception', _wrapper)
100100

101101
# Instrument logging with Epsagon trace ID
102-
if trace_factory.is_logging_tracing_enabled():
102+
if get_trace_log_config():
103103
wrapt.wrap_function_wrapper(
104104
'logging',
105105
'Logger.log',

epsagon/modules/redis.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ def patch():
4444
'Redis.execute_command',
4545
_single_wrapper
4646
)
47+
# Version < 3.0
48+
wrapt.wrap_function_wrapper(
49+
'redis',
50+
'StrictRedis.execute_command',
51+
_single_wrapper
52+
)
4753
wrapt.wrap_function_wrapper(
4854
'redis.client',
4955
'Pipeline.immediate_execute_command',

epsagon/modules/tornado.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import epsagon.trace
1212
from epsagon.runners.tornado import TornadoRunner
1313
from epsagon.http_filters import ignore_request, is_ignored_endpoint
14-
from epsagon.utils import collect_container_metadata
14+
from epsagon.utils import collect_container_metadata, print_debug
1515

1616
TORNADO_TRACE_ID = 'epsagon_tornado_trace_key'
1717

@@ -31,6 +31,7 @@ def before_request(cls, wrapped, instance, args, kwargs):
3131
:param args: wrapt's args
3232
:param kwargs: wrapt's kwargs
3333
"""
34+
print_debug('before_request Tornado request')
3435
try:
3536
ignored = ignore_request('', instance.request.path)
3637
if not ignored and not is_ignored_endpoint(instance.request.path):
@@ -48,6 +49,7 @@ def before_request(cls, wrapped, instance, args, kwargs):
4849
)
4950

5051
trace.set_runner(cls.RUNNERS[unique_id])
52+
print_debug('Created Tornado Runner')
5153

5254
# Collect metadata in case this is a container.
5355
collect_container_metadata(
@@ -69,9 +71,18 @@ def after_request(cls, wrapped, instance, args, kwargs):
6971
:param args: wrapt's args
7072
:param kwargs: wrapt's kwargs
7173
"""
72-
response_body = getattr(instance, '_write_buffer', None)
73-
if response_body and isinstance(response_body, list):
74-
response_body = b''.join(response_body)
74+
print_debug('after_request Tornado request')
75+
response_body = None
76+
try:
77+
response_body = getattr(instance, '_write_buffer', None)
78+
if response_body and isinstance(response_body, list):
79+
response_body = b''.join(response_body)
80+
except Exception as instrumentation_exception: # pylint: disable=W0703
81+
epsagon.trace.trace_factory.add_exception(
82+
instrumentation_exception,
83+
traceback.format_exc()
84+
)
85+
7586
res = wrapped(*args, **kwargs)
7687
try:
7788
unique_id = getattr(instance, TORNADO_TRACE_ID, None)
@@ -80,6 +91,11 @@ def after_request(cls, wrapped, instance, args, kwargs):
8091

8192
tornado_runner = cls.RUNNERS.pop(unique_id)
8293

94+
# Ignoring 404s
95+
if getattr(instance, '_status_code', None) == 404:
96+
print_debug('Ignoring 404 Tornado request')
97+
return res
98+
8399
trace = epsagon.trace.trace_factory.switch_active_trace(
84100
unique_id
85101
)
@@ -111,6 +127,7 @@ def collect_exception(cls, wrapped, instance, args, kwargs):
111127
:param args: wrapt's args
112128
:param kwargs: wrapt's kwargs
113129
"""
130+
print_debug('collect_exception Tornado request')
114131
try:
115132
unique_id = getattr(instance, TORNADO_TRACE_ID, None)
116133

epsagon/runners/tornado.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from __future__ import absolute_import
77
import uuid
88
from ..event import BaseEvent
9-
from ..utils import add_data_if_needed
9+
from ..utils import add_data_if_needed, print_debug
1010
from ..constants import EPSAGON_HEADER_TITLE
1111

1212
MAX_PAYLOAD_BYTES = 2000
@@ -69,6 +69,19 @@ def __init__(self, start_time, request):
6969
request_headers
7070
)
7171

72+
try:
73+
if request.body:
74+
body = request.body
75+
if isinstance(body, bytes):
76+
body = body.decode('utf-8')
77+
add_data_if_needed(
78+
self.resource['metadata'],
79+
'Request Data',
80+
body
81+
)
82+
except Exception as exception: # pylint: disable=broad-except
83+
print_debug('Could not extract body: {}'.format(exception))
84+
7285
def update_response(self, response, response_body=None):
7386
"""
7487
Adds response data to event.

epsagon/utils.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,19 @@ def get_tc_url(use_ssl):
9595
return TRACE_COLLECTOR_URL.format(protocol=protocol, region=REGION)
9696

9797

98+
def get_trace_log_config():
99+
"""Returns the trace log correlation configuration"""
100+
# In case we're running on AWS Lambda, logging correlation is disabled
101+
if is_lambda_env():
102+
return False
103+
104+
# If EPSAGON_LOGGING_TRACING_ENABLED exists as an env var - use it
105+
if os.getenv('EPSAGON_LOGGING_TRACING_ENABLED'):
106+
return os.getenv('EPSAGON_LOGGING_TRACING_ENABLED').upper() == 'TRUE'
107+
108+
return True
109+
110+
98111
def init(
99112
token='',
100113
app_name='Application',
@@ -174,15 +187,7 @@ def init(
174187
if os.getenv('EPSAGON_METADATA'):
175188
metadata_only = (os.getenv('EPSAGON_METADATA') or '').upper() == 'TRUE'
176189

177-
# If EPSAGON_LOGGING_TRACING_ENABLED exists as an env var - use it
178-
if os.getenv('EPSAGON_LOGGING_TRACING_ENABLED'):
179-
logging_tracing_enabled = (
180-
os.getenv('EPSAGON_LOGGING_TRACING_ENABLED') or ''
181-
).upper() == 'TRUE'
182-
183-
# In case we're running on AWS Lambda, logging correlation is disabled
184-
if is_lambda_env():
185-
logging_tracing_enabled = False
190+
logging_tracing_enabled = get_trace_log_config()
186191

187192
if os.getenv('EPSAGON_SAMPLE_RATE'):
188193
sample_rate = float(os.getenv('EPSAGON_SAMPLE_RATE'))

0 commit comments

Comments
 (0)