|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | +# contributor license agreements. See the NOTICE file distributed with |
| 4 | +# this work for additional information regarding copyright ownership. |
| 5 | +# The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | +# (the "License"); you may not use this file except in compliance with |
| 7 | +# the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | + |
| 18 | +import logging |
| 19 | + |
| 20 | +from skywalking import Layer, Component |
| 21 | +from skywalking.trace import tags |
| 22 | +from skywalking.trace.carrier import Carrier |
| 23 | +from skywalking.trace.context import get_context |
| 24 | +from skywalking.trace.tags import Tag |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +def install(): |
| 30 | + # noinspection PyBroadException |
| 31 | + try: |
| 32 | + from urllib3.request import RequestMethods |
| 33 | + |
| 34 | + _request = RequestMethods.request |
| 35 | + |
| 36 | + def _sw_request(this: RequestMethods, method, url, fields=None, headers=None, **urlopen_kw): |
| 37 | + |
| 38 | + from urllib.parse import urlparse |
| 39 | + url_param = urlparse(url) |
| 40 | + carrier = Carrier() |
| 41 | + context = get_context() |
| 42 | + with context.new_exit_span(op=url_param.path or "/", peer=url_param.netloc, carrier=carrier) as span: |
| 43 | + span.layer = Layer.Http |
| 44 | + span.component = Component.Urllib3 |
| 45 | + |
| 46 | + if headers is None: |
| 47 | + headers = {} |
| 48 | + for item in carrier: |
| 49 | + headers[item.key] = item.val |
| 50 | + else: |
| 51 | + for item in carrier: |
| 52 | + headers[item.key] = item.val |
| 53 | + |
| 54 | + try: |
| 55 | + res = _request(this, method, url, fields=fields, headers=headers, **urlopen_kw) |
| 56 | + |
| 57 | + span.tag(Tag(key=tags.HttpMethod, val=method.upper())) |
| 58 | + span.tag(Tag(key=tags.HttpUrl, val=url)) |
| 59 | + span.tag(Tag(key=tags.HttpStatus, val=res.status)) |
| 60 | + if res.status >= 400: |
| 61 | + span.error_occurred = True |
| 62 | + except BaseException as e: |
| 63 | + span.raised() |
| 64 | + raise e |
| 65 | + return res |
| 66 | + |
| 67 | + RequestMethods.request = _sw_request |
| 68 | + except Exception: |
| 69 | + logger.warning('failed to install plugin %s', __name__) |
0 commit comments