-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathsw_aiohttp.py
More file actions
127 lines (96 loc) · 4.64 KB
/
sw_aiohttp.py
File metadata and controls
127 lines (96 loc) · 4.64 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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
from skywalking import Layer, Component, config
from skywalking.trace.carrier import Carrier
from skywalking.trace.context import get_context, NoopContext
from skywalking.trace.span import NoopSpan
from skywalking.trace.tags import TagHttpMethod, TagHttpURL, TagHttpStatusCode
link_vector = ['https://docs.aiohttp.org']
support_matrix = {
'aiohttp': {
'>=3.10': ['3.9.*', '3.11.*'],
}
}
note = """"""
def install():
from aiohttp import ClientSession
from aiohttp.web_protocol import RequestHandler
from aiohttp.web_request import BaseRequest
from multidict import CIMultiDict, MultiDict, MultiDictProxy
from yarl import URL
_request = ClientSession._request
async def _sw_request(self: ClientSession, method: str, str_or_url, **kwargs):
abs_url = self._build_url(str_or_url) if hasattr(self, '_build_url') else URL(str_or_url)
url = abs_url.with_user(None).with_password(None)
peer = f"{url.host or ''}:{url.port or ''}"
if config.agent_protocol == 'http' and config.agent_collector_backend_services.rstrip('/') \
.endswith(f'{url.host}:{url.port}'):
return _request
span = NoopSpan(NoopContext()) if config.ignore_http_method_check(method) \
else get_context().new_exit_span(op=url.path or '/', peer=peer, component=Component.AioHttp)
with span:
span.layer = Layer.Http
span.tag(TagHttpMethod(method.upper())) # pyre-ignore
span.tag(TagHttpURL(str(url.with_password(None)))) # pyre-ignore
carrier = span.inject()
headers = kwargs.get('headers')
if headers is None:
headers = kwargs['headers'] = CIMultiDict()
elif not isinstance(headers, (MultiDictProxy, MultiDict)):
headers = CIMultiDict(headers)
kwargs['headers'] = headers
for item in carrier:
headers.add(item.key, item.val)
res = await _request(self, method, str_or_url, **kwargs)
span.tag(TagHttpStatusCode(res.status))
if res.status >= 400:
span.error_occurred = True
return res
ClientSession._request = _sw_request
_handle_request = RequestHandler._handle_request
async def _sw_handle_request(self, request: BaseRequest, start_time: float, *args, **kwargs):
if config.agent_protocol == 'http' and config.agent_collector_backend_services.rstrip('/') \
.endswith(f'{request.url.host}:{request.url.port}'):
return _handle_request
carrier = Carrier()
method = request.method
for item in carrier:
val = request.headers.get(item.key)
if val is not None:
item.val = val
span = NoopSpan(NoopContext()) if config.ignore_http_method_check(method) \
else get_context().new_entry_span(op=request.path, carrier=carrier)
with span:
span.layer = Layer.Http
span.component = Component.AioHttp
peer_name = request._transport_peername
if isinstance(peer_name, (list, tuple)):
span.peer = f'{peer_name[0]}:{peer_name[1]}'
else:
span.peer = f'{peer_name}'
span.tag(TagHttpMethod(method)) # pyre-ignore
try:
span.tag(TagHttpURL(str(request.url))) # pyre-ignore
except ValueError:
# yarl >= 1.18 rejects host:port in URL.build; fallback to path
span.tag(TagHttpURL(f'{request.scheme}://{request.host}{request.path}'))
resp, reset = await _handle_request(self, request, start_time, *args, **kwargs)
span.tag(TagHttpStatusCode(resp.status))
if resp.status >= 400:
span.error_occurred = True
return resp, reset
RequestHandler._handle_request = _sw_handle_request