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

chord(flake8,black): ignore W504 and E231 not respected by black #1185

Merged
merged 3 commits into from
Feb 3, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
68 changes: 35 additions & 33 deletions ddtrace/contrib/django/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,33 +17,33 @@

try:
from django.utils.deprecation import MiddlewareMixin

MiddlewareClass = MiddlewareMixin
except ImportError:
MiddlewareClass = object

log = get_logger(__name__)

EXCEPTION_MIDDLEWARE = 'ddtrace.contrib.django.TraceExceptionMiddleware'
TRACE_MIDDLEWARE = 'ddtrace.contrib.django.TraceMiddleware'
MIDDLEWARE = 'MIDDLEWARE'
MIDDLEWARE_CLASSES = 'MIDDLEWARE_CLASSES'
EXCEPTION_MIDDLEWARE = "ddtrace.contrib.django.TraceExceptionMiddleware"
TRACE_MIDDLEWARE = "ddtrace.contrib.django.TraceMiddleware"
MIDDLEWARE = "MIDDLEWARE"
MIDDLEWARE_CLASSES = "MIDDLEWARE_CLASSES"

# Default views list available from:
# https://github.com/django/django/blob/38e2fdadfd9952e751deed662edf4c496d238f28/django/views/defaults.py
# DEV: Django doesn't call `process_view` when falling back to one of these internal error handling views
# DEV: We only use these names when `span.resource == 'unknown'` and we have one of these status codes
_django_default_views = {
400: 'django.views.defaults.bad_request',
403: 'django.views.defaults.permission_denied',
404: 'django.views.defaults.page_not_found',
500: 'django.views.defaults.server_error',
400: "django.views.defaults.bad_request",
403: "django.views.defaults.permission_denied",
404: "django.views.defaults.page_not_found",
500: "django.views.defaults.server_error",
}


def _analytics_enabled():
return (
(config.analytics_enabled and settings.ANALYTICS_ENABLED is not False) or
settings.ANALYTICS_ENABLED is True
(config.analytics_enabled and settings.ANALYTICS_ENABLED is not False) or settings.ANALYTICS_ENABLED is True
) and settings.ANALYTICS_SAMPLE_RATE is not None


Expand Down Expand Up @@ -87,6 +87,7 @@ class InstrumentationMixin(MiddlewareClass):
"""
Useful mixin base class for tracing middlewares
"""

def __init__(self, get_response=None):
# disable the middleware if the tracer is not enabled
# or if the auto instrumentation is disabled
Expand All @@ -99,20 +100,22 @@ class TraceExceptionMiddleware(InstrumentationMixin):
"""
Middleware that traces exceptions raised
"""

def process_exception(self, request, exception):
try:
span = _get_req_span(request)
if span:
span.set_tag(http.STATUS_CODE, '500')
span.set_tag(http.STATUS_CODE, "500")
span.set_traceback() # will set the exception info
except Exception:
log.debug('error processing exception', exc_info=True)
log.debug("error processing exception", exc_info=True)


class TraceMiddleware(InstrumentationMixin):
"""
Middleware that traces Django requests
"""

def process_request(self, request):
tracer = settings.TRACER
if settings.DISTRIBUTED_TRACING:
Expand All @@ -123,18 +126,17 @@ def process_request(self, request):
tracer.context_provider.activate(context)
try:
span = tracer.trace(
'django.request',
"django.request",
service=settings.DEFAULT_SERVICE,
resource='unknown', # will be filled by process view
resource="unknown", # will be filled by process view
span_type=SpanTypes.WEB,
)

# set analytics sample rate
# DEV: django is special case maintains separate configuration from config api
if _analytics_enabled() and settings.ANALYTICS_SAMPLE_RATE is not None:
span.set_tag(
ANALYTICS_SAMPLE_RATE_KEY,
settings.ANALYTICS_SAMPLE_RATE,
ANALYTICS_SAMPLE_RATE_KEY, settings.ANALYTICS_SAMPLE_RATE,
)

# Set HTTP Request tags
Expand All @@ -144,10 +146,10 @@ def process_request(self, request):
if trace_query_string is None:
trace_query_string = config.django.trace_query_string
if trace_query_string:
span.set_tag(http.QUERY_STRING, request.META['QUERY_STRING'])
span.set_tag(http.QUERY_STRING, request.META["QUERY_STRING"])
_set_req_span(request, span)
except Exception:
log.debug('error tracing request', exc_info=True)
log.debug("error tracing request", exc_info=True)

def process_view(self, request, view_func, *args, **kwargs):
span = _get_req_span(request)
Expand All @@ -166,63 +168,63 @@ def process_response(self, request, response):
# If `process_view` was not called, try to determine the correct `span.resource` to set
# DEV: `process_view` won't get called if a middle `process_request` returns an HttpResponse
# DEV: `process_view` won't get called when internal error handlers are used (e.g. for 404 responses)
if span.resource == 'unknown':
if span.resource == "unknown":
try:
# Attempt to lookup the view function from the url resolver
# https://github.com/django/django/blob/38e2fdadfd9952e751deed662edf4c496d238f28/django/core/handlers/base.py#L104-L113 # noqa
urlconf = None
if hasattr(request, 'urlconf'):
if hasattr(request, "urlconf"):
urlconf = request.urlconf
resolver = get_resolver(urlconf)

# Try to resolve the Django view for handling this request
if getattr(request, 'request_match', None):
if getattr(request, "request_match", None):
request_match = request.request_match
else:
# This may raise a `django.urls.exceptions.Resolver404` exception
request_match = resolver.resolve(request.path_info)
span.resource = func_name(request_match.func)
except Exception:
log.debug('error determining request view function', exc_info=True)
log.debug("error determining request view function", exc_info=True)

# If the view could not be found, try to set from a static list of
# known internal error handler views
span.resource = _django_default_views.get(response.status_code, 'unknown')
span.resource = _django_default_views.get(response.status_code, "unknown")

span.set_tag(http.STATUS_CODE, response.status_code)
span = _set_auth_tags(span, request)
span.finish()
except Exception:
log.debug('error tracing request', exc_info=True)
log.debug("error tracing request", exc_info=True)
finally:
return response


def _get_req_span(request):
""" Return the datadog span from the given request. """
return getattr(request, '_datadog_request_span', None)
return getattr(request, "_datadog_request_span", None)


def _set_req_span(request, span):
""" Set the datadog span on the given request. """
return setattr(request, '_datadog_request_span', span)
return setattr(request, "_datadog_request_span", span)


def _set_auth_tags(span, request):
""" Patch any available auth tags from the request onto the span. """
user = getattr(request, 'user', None)
user = getattr(request, "user", None)
if not user:
return span

if hasattr(user, 'is_authenticated'):
span.set_tag('django.user.is_authenticated', user_is_authenticated(user))
if hasattr(user, "is_authenticated"):
span.set_tag("django.user.is_authenticated", user_is_authenticated(user))

uid = getattr(user, 'pk', None)
uid = getattr(user, "pk", None)
if uid:
span.set_tag('django.user.id', uid)
span.set_tag("django.user.id", uid)

uname = getattr(user, 'username', None)
uname = getattr(user, "username", None)
if uname:
span.set_tag('django.user.name', uname)
span.set_tag("django.user.name", uname)

return span
51 changes: 20 additions & 31 deletions ddtrace/contrib/grpc/client_interceptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def create_client_interceptor(pin, host, port):
def intercept_channel(wrapped, instance, args, kwargs):
channel = args[0]
interceptors = args[1:]
if isinstance(getattr(channel, '_interceptor', None), _ClientInterceptor):
if isinstance(getattr(channel, "_interceptor", None), _ClientInterceptor):
dd_interceptor = channel._interceptor
base_channel = getattr(channel, '_channel', None)
base_channel = getattr(channel, "_channel", None)
if base_channel:
new_channel = wrapped(channel._channel, *interceptors)
return grpc.intercept_channel(new_channel, dd_interceptor)
Expand All @@ -39,10 +39,9 @@ def intercept_channel(wrapped, instance, args, kwargs):


class _ClientCallDetails(
collections.namedtuple(
'_ClientCallDetails',
('method', 'timeout', 'metadata', 'credentials')),
grpc.ClientCallDetails):
collections.namedtuple("_ClientCallDetails", ("method", "timeout", "metadata", "credentials")),
grpc.ClientCallDetails,
):
pass


Expand Down Expand Up @@ -74,9 +73,9 @@ def _handle_error(span, response_error, status_code):
# exception() and traceback() methods if a computation has resulted in an
# exception being raised
if (
not callable(getattr(response_error, 'cancelled', None)) and
not callable(getattr(response_error, 'exception', None)) and
not callable(getattr(response_error, 'traceback', None))
not callable(getattr(response_error, "cancelled", None))
and not callable(getattr(response_error, "exception", None))
and not callable(getattr(response_error, "traceback", None))
):
return

Expand Down Expand Up @@ -129,7 +128,7 @@ def __next__(self):
raise
except Exception:
# DEV: added for safety though should not be reached since wrapped response
log.debug('unexpected non-grpc exception raised, closing open span', exc_info=True)
log.debug("unexpected non-grpc exception raised, closing open span", exc_info=True)
self._span.set_traceback()
self._span.finish()
raise
Expand All @@ -139,9 +138,11 @@ def next(self):


class _ClientInterceptor(
grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor,
grpc.StreamUnaryClientInterceptor, grpc.StreamStreamClientInterceptor):

grpc.UnaryUnaryClientInterceptor,
grpc.UnaryStreamClientInterceptor,
grpc.StreamUnaryClientInterceptor,
grpc.StreamStreamClientInterceptor,
):
def __init__(self, pin, host, port):
self._pin = pin
self._host = host
Expand All @@ -151,10 +152,7 @@ def _intercept_client_call(self, method_kind, client_call_details):
tracer = self._pin.tracer

span = tracer.trace(
'grpc',
span_type=SpanTypes.GRPC,
service=self._pin.service,
resource=client_call_details.method,
"grpc", span_type=SpanTypes.GRPC, service=self._pin.service, resource=client_call_details.method,
)

# tags for method details
Expand Down Expand Up @@ -189,19 +187,13 @@ def _intercept_client_call(self, method_kind, client_call_details):
metadata.extend(headers.items())

client_call_details = _ClientCallDetails(
client_call_details.method,
client_call_details.timeout,
metadata,
client_call_details.credentials,
client_call_details.method, client_call_details.timeout, metadata, client_call_details.credentials,
)

return span, client_call_details

def intercept_unary_unary(self, continuation, client_call_details, request):
span, client_call_details = self._intercept_client_call(
constants.GRPC_METHOD_KIND_UNARY,
client_call_details,
)
span, client_call_details = self._intercept_client_call(constants.GRPC_METHOD_KIND_UNARY, client_call_details,)
try:
response = continuation(client_call_details, request)
_handle_response(span, response)
Expand All @@ -216,17 +208,15 @@ def intercept_unary_unary(self, continuation, client_call_details, request):

def intercept_unary_stream(self, continuation, client_call_details, request):
span, client_call_details = self._intercept_client_call(
constants.GRPC_METHOD_KIND_SERVER_STREAMING,
client_call_details,
constants.GRPC_METHOD_KIND_SERVER_STREAMING, client_call_details,
)
response_iterator = continuation(client_call_details, request)
response_iterator = _WrappedResponseCallFuture(response_iterator, span)
return response_iterator

def intercept_stream_unary(self, continuation, client_call_details, request_iterator):
span, client_call_details = self._intercept_client_call(
constants.GRPC_METHOD_KIND_CLIENT_STREAMING,
client_call_details,
constants.GRPC_METHOD_KIND_CLIENT_STREAMING, client_call_details,
)
try:
response = continuation(client_call_details, request_iterator)
Expand All @@ -242,8 +232,7 @@ def intercept_stream_unary(self, continuation, client_call_details, request_iter

def intercept_stream_stream(self, continuation, client_call_details, request_iterator):
span, client_call_details = self._intercept_client_call(
constants.GRPC_METHOD_KIND_BIDI_STREAMING,
client_call_details,
constants.GRPC_METHOD_KIND_BIDI_STREAMING, client_call_details,
)
response_iterator = continuation(client_call_details, request_iterator)
response_iterator = _WrappedResponseCallFuture(response_iterator, span)
Expand Down
Loading