This repository was archived by the owner on Sep 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathtrace.py
More file actions
131 lines (113 loc) · 4.45 KB
/
trace.py
File metadata and controls
131 lines (113 loc) · 4.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# Copyright 2017, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import logging
import wrapt
from aiohttp import InvalidURL, ServerTimeoutError
from yarl import URL
from opencensus.trace import (
attributes_helper,
exceptions_status,
execution_context,
utils,
)
from opencensus.trace.span import SpanKind
logger = logging.getLogger(__name__)
MODULE_NAME = "aiohttp"
COMPONENT = attributes_helper.COMMON_ATTRIBUTES["COMPONENT"]
HTTP_COMPONENT = "HTTP"
HTTP_HOST = attributes_helper.COMMON_ATTRIBUTES["HTTP_HOST"]
HTTP_METHOD = attributes_helper.COMMON_ATTRIBUTES["HTTP_METHOD"]
HTTP_PATH = attributes_helper.COMMON_ATTRIBUTES["HTTP_PATH"]
HTTP_ROUTE = attributes_helper.COMMON_ATTRIBUTES["HTTP_ROUTE"]
HTTP_STATUS_CODE = attributes_helper.COMMON_ATTRIBUTES["HTTP_STATUS_CODE"]
HTTP_URL = attributes_helper.COMMON_ATTRIBUTES["HTTP_URL"]
def trace_integration(tracer=None):
"""Wrap the aiohttp library to trace it."""
logger.info("Integrated module: {}".format(MODULE_NAME))
if tracer is not None:
# The execution_context tracer should never be None - if it has not
# been set it returns a no-op tracer. Most code in this library does
# not handle None being used in the execution context.
execution_context.set_opencensus_tracer(tracer)
# Wrap Session class
wrapt.wrap_function_wrapper(
module=MODULE_NAME, name="ClientSession._request", wrapper=wrap_session_request
)
async def wrap_session_request(wrapped, _, args, kwargs):
"""Wrap the session function to trace it."""
if execution_context.is_exporter():
return await wrapped(*args, **kwargs)
method = kwargs.get("method") or args[0]
str_or_url = kwargs.get("str_or_url") or args[1]
try:
url = URL(str_or_url)
except ValueError as e:
raise InvalidURL(str_or_url) from e
excludelist_hostnames = execution_context.get_opencensus_attr(
"excludelist_hostnames"
)
url_host_with_port = url.host + (f":{url.port}" if url.port else "")
if utils.disable_tracing_hostname(url_host_with_port, excludelist_hostnames):
return await wrapped(*args, **kwargs)
url_path = url.path or "/"
tracer = execution_context.get_opencensus_tracer()
with tracer.span(name=url_path) as span:
span.span_kind = SpanKind.CLIENT
try:
tracer_headers = tracer.propagator.to_headers(
span_context=tracer.span_context,
)
kwargs.setdefault("headers", {}).update(tracer_headers)
except Exception:
pass
span.add_attribute(
attribute_key=COMPONENT,
attribute_value=HTTP_COMPONENT,
)
span.add_attribute(
attribute_key=HTTP_HOST,
attribute_value=url_host_with_port,
)
span.add_attribute(
attribute_key=HTTP_METHOD,
attribute_value=method.upper(),
)
span.add_attribute(
attribute_key=HTTP_PATH,
attribute_value=url_path,
)
span.add_attribute(
attribute_key=HTTP_URL,
attribute_value=str(url),
)
try:
result = await wrapped(*args, **kwargs)
except (ServerTimeoutError, asyncio.TimeoutError):
span.set_status(exceptions_status.TIMEOUT)
raise
except InvalidURL:
span.set_status(exceptions_status.INVALID_URL)
raise
except Exception as e:
span.set_status(exceptions_status.unknown(e))
raise
else:
status_code = int(result.status)
span.add_attribute(
attribute_key=HTTP_STATUS_CODE,
attribute_value=status_code,
)
span.set_status(utils.status_from_http_code(http_code=status_code))
return result