Skip to content

Commit 24370ac

Browse files
committed
enhancement: use a common method to capture custom headers
Signed-off-by: Varsha GS <[email protected]>
1 parent 61e7bef commit 24370ac

File tree

16 files changed

+55
-225
lines changed

16 files changed

+55
-225
lines changed

src/instana/instrumentation/aiohttp/client.py

+1-14
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from instana.propagators.format import Format
1313
from instana.singletons import agent
1414
from instana.util.secrets import strip_secrets_from_query
15-
from instana.util.traceutils import get_tracer_tuple, tracing_is_off
15+
from instana.util.traceutils import get_tracer_tuple, tracing_is_off, extract_custom_headers
1616

1717
try:
1818
import aiohttp
@@ -21,19 +21,6 @@
2121
from aiohttp.client import ClientSession
2222
from instana.span.span import InstanaSpan
2323

24-
def extract_custom_headers(
25-
span: "InstanaSpan", headers: Dict[str, Any]
26-
) -> None:
27-
if not agent.options.extra_http_headers or not headers:
28-
return
29-
try:
30-
for custom_header in agent.options.extra_http_headers:
31-
if custom_header in headers:
32-
span.set_attribute(
33-
f"http.header.{custom_header}", headers[custom_header]
34-
)
35-
except Exception:
36-
logger.debug("extract_custom_headers: ", exc_info=True)
3724

3825
async def stan_request_start(
3926
session: "ClientSession", trace_config_ctx: SimpleNamespace, params

src/instana/instrumentation/aiohttp/server.py

+1-14
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from instana.propagators.format import Format
1212
from instana.singletons import agent, tracer
1313
from instana.util.secrets import strip_secrets_from_query
14+
from instana.util.traceutils import extract_custom_headers
1415

1516
if TYPE_CHECKING:
1617
from instana.span.span import InstanaSpan
@@ -22,20 +23,6 @@
2223
if TYPE_CHECKING:
2324
import aiohttp.web
2425

25-
def extract_custom_headers(
26-
span: "InstanaSpan", headers: Dict[str, Any]
27-
) -> None:
28-
if not agent.options.extra_http_headers or not headers:
29-
return
30-
try:
31-
for custom_header in agent.options.extra_http_headers:
32-
if custom_header in headers:
33-
span.set_attribute(
34-
f"http.header.{custom_header}", headers[custom_header]
35-
)
36-
except Exception:
37-
logger.debug("extract_custom_headers: ", exc_info=True)
38-
3926
@middleware
4027
async def stan_middleware(
4128
request: "aiohttp.web.Request",

src/instana/instrumentation/asgi.py

+5-21
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
Instana ASGI Middleware
66
"""
77

8-
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Tuple
8+
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict
99

1010
from opentelemetry.semconv.trace import SpanAttributes
1111
from opentelemetry.trace import SpanKind
@@ -14,6 +14,7 @@
1414
from instana.propagators.format import Format
1515
from instana.singletons import agent, tracer
1616
from instana.util.secrets import strip_secrets_from_query
17+
from instana.util.traceutils import extract_custom_headers
1718

1819
if TYPE_CHECKING:
1920
from starlette.middleware.exceptions import ExceptionMiddleware
@@ -28,23 +29,6 @@ class InstanaASGIMiddleware:
2829
def __init__(self, app: "ExceptionMiddleware") -> None:
2930
self.app = app
3031

31-
def _extract_custom_headers(
32-
self, span: "InstanaSpan", headers: List[Tuple[object, ...]]
33-
) -> None:
34-
if agent.options.extra_http_headers is None:
35-
return
36-
try:
37-
for custom_header in agent.options.extra_http_headers:
38-
# Headers are in the following format: b'x-header-1'
39-
for header_pair in headers:
40-
if header_pair[0].decode("utf-8").lower() == custom_header.lower():
41-
span.set_attribute(
42-
f"http.header.{custom_header}",
43-
header_pair[1].decode("utf-8"),
44-
)
45-
except Exception:
46-
logger.debug("extract_custom_headers: ", exc_info=True)
47-
4832
def _collect_kvs(self, scope: Dict[str, Any], span: "InstanaSpan") -> None:
4933
try:
5034
span.set_attribute("span.kind", SpanKind.SERVER)
@@ -93,8 +77,8 @@ async def __call__(
9377

9478
with tracer.start_as_current_span("asgi", span_context=request_context) as span:
9579
self._collect_kvs(scope, span)
96-
if "headers" in scope and agent.options.extra_http_headers:
97-
self._extract_custom_headers(span, scope["headers"])
80+
if "headers" in scope:
81+
extract_custom_headers(span, scope["headers"])
9882

9983
instana_send = self._send_with_instana(
10084
span,
@@ -125,7 +109,7 @@ async def send_wrapper(response: Dict[str, Any]) -> Awaitable[None]:
125109

126110
headers = response.get("headers")
127111
if headers:
128-
self._extract_custom_headers(current_span, headers)
112+
extract_custom_headers(current_span, headers)
129113
tracer.inject(current_span.context, Format.BINARY, headers)
130114
except Exception:
131115
logger.debug("ASGI send_wrapper error: ", exc_info=True)

src/instana/instrumentation/boto3_inst.py

+1-16
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from instana.log import logger
1212
from instana.singletons import tracer, agent
13-
from instana.util.traceutils import get_tracer_tuple, tracing_is_off
13+
from instana.util.traceutils import get_tracer_tuple, tracing_is_off, extract_custom_headers
1414
from instana.propagators.format import Format
1515
from instana.span.span import get_current_span
1616

@@ -23,21 +23,6 @@
2323
import boto3
2424
from boto3.s3 import inject
2525

26-
def extract_custom_headers(
27-
span: "InstanaSpan", headers: Optional[Dict[str, Any]] = None
28-
) -> None:
29-
if not agent.options.extra_http_headers or not headers:
30-
return
31-
try:
32-
for custom_header in agent.options.extra_http_headers:
33-
if custom_header in headers:
34-
span.set_attribute(
35-
"http.header.%s" % custom_header, headers[custom_header]
36-
)
37-
38-
except Exception:
39-
logger.debug("extract_custom_headers: ", exc_info=True)
40-
4126
def lambda_inject_context(payload: Dict[str, Any], span: "InstanaSpan") -> None:
4227
"""
4328
When boto3 lambda client 'Invoke' is called, we want to inject the tracing context.

src/instana/instrumentation/django/middleware.py

+3-26
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@
1313
from instana.log import logger
1414
from instana.singletons import agent, tracer
1515
from instana.util.secrets import strip_secrets_from_query
16+
from instana.util.traceutils import extract_custom_headers
1617
from instana.propagators.format import Format
1718

1819
if TYPE_CHECKING:
19-
from instana.span.span import InstanaSpan
2020
from django.core.handlers.base import BaseHandler
2121
from django.http import HttpRequest, HttpResponse
2222

@@ -53,29 +53,6 @@ def __init__(
5353
super(InstanaMiddleware, self).__init__(get_response)
5454
self.get_response = get_response
5555

56-
def _extract_custom_headers(
57-
self, span: "InstanaSpan", headers: Dict[str, Any], format: bool
58-
) -> None:
59-
if agent.options.extra_http_headers is None:
60-
return
61-
62-
try:
63-
for custom_header in agent.options.extra_http_headers:
64-
# Headers are available in this format: HTTP_X_CAPTURE_THIS
65-
django_header = (
66-
("HTTP_" + custom_header.upper()).replace("-", "_")
67-
if format
68-
else custom_header
69-
)
70-
71-
if django_header in headers:
72-
span.set_attribute(
73-
f"http.header.{custom_header}", headers[django_header]
74-
)
75-
76-
except Exception:
77-
logger.debug("Instana middleware @ extract_custom_headers: ", exc_info=True)
78-
7956
def process_request(self, request: Type["HttpRequest"]) -> None:
8057
try:
8158
env = request.META
@@ -89,7 +66,7 @@ def process_request(self, request: Type["HttpRequest"]) -> None:
8966
token = context.attach(ctx)
9067
request.token = token
9168

92-
self._extract_custom_headers(span, env, format=True)
69+
extract_custom_headers(span, env, format=True)
9370

9471
request.span.set_attribute(SpanAttributes.HTTP_METHOD, request.method)
9572
if "PATH_INFO" in env:
@@ -138,7 +115,7 @@ def process_response(
138115
SpanAttributes.HTTP_STATUS_CODE, response.status_code
139116
)
140117
if hasattr(response, "headers"):
141-
self._extract_custom_headers(
118+
extract_custom_headers(
142119
request.span, response.headers, format=False
143120
)
144121
tracer.inject(request.span.context, Format.HTTP_HEADERS, response)

src/instana/instrumentation/flask/common.py

+1-27
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,15 @@
1010
from opentelemetry.semconv.trace import SpanAttributes
1111

1212
from instana.log import logger
13-
from instana.singletons import tracer, agent
13+
from instana.singletons import tracer
1414
from instana.propagators.format import Format
15-
from instana.instrumentation.flask import signals_available
1615

1716

1817
if TYPE_CHECKING:
19-
from instana.span.span import InstanaSpan
2018
from werkzeug.exceptions import HTTPException
2119
from flask.typing import ResponseReturnValue
2220
from jinja2.environment import Template
2321

24-
if signals_available:
25-
from werkzeug.datastructures.headers import Headers
26-
else:
27-
from werkzeug.datastructures import Headers
28-
29-
3022
@wrapt.patch_function_wrapper('flask', 'templating._render')
3123
def render_with_instana(
3224
wrapped: Callable[..., str],
@@ -97,21 +89,3 @@ def handle_user_exception_with_instana(
9789
logger.debug("handle_user_exception_with_instana:", exc_info=True)
9890

9991
return response
100-
101-
102-
def extract_custom_headers(
103-
span: "InstanaSpan", headers: Union[Dict[str, Any], "Headers"], format: bool
104-
) -> None:
105-
if agent.options.extra_http_headers is None:
106-
return
107-
try:
108-
for custom_header in agent.options.extra_http_headers:
109-
# Headers are available in this format: HTTP_X_CAPTURE_THIS
110-
flask_header = ('HTTP_' + custom_header.upper()).replace('-', '_') if format else custom_header
111-
if flask_header in headers:
112-
span.set_attribute(
113-
"http.header.%s" % custom_header, headers[flask_header]
114-
)
115-
116-
except Exception:
117-
logger.debug("extract_custom_headers: ", exc_info=True)

src/instana/instrumentation/flask/vanilla.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from instana.log import logger
1414
from instana.singletons import agent, tracer
1515
from instana.util.secrets import strip_secrets_from_query
16-
from instana.instrumentation.flask.common import extract_custom_headers
16+
from instana.util.traceutils import extract_custom_headers
1717
from instana.propagators.format import Format
1818

1919
path_tpl_re = re.compile('<.*>')

src/instana/instrumentation/flask/with_blinker.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from instana.log import logger
1313
from instana.util.secrets import strip_secrets_from_query
1414
from instana.singletons import agent, tracer
15-
from instana.instrumentation.flask.common import extract_custom_headers
15+
from instana.util.traceutils import extract_custom_headers
1616
from instana.propagators.format import Format
1717

1818
import flask
@@ -78,7 +78,7 @@ def request_finished_with_instana(
7878
extract_custom_headers(span, response.headers, format=False)
7979

8080
tracer.inject(span.context, Format.HTTP_HEADERS, response.headers)
81-
except:
81+
except Exception:
8282
logger.debug("Flask request_finished_with_instana", exc_info=True)
8383
finally:
8484
if span and span.is_recording():

src/instana/instrumentation/pyramid.py

+3-18
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616
from instana.log import logger
1717
from instana.singletons import tracer, agent
1818
from instana.util.secrets import strip_secrets_from_query
19+
from instana.util.traceutils import extract_custom_headers
1920
from instana.propagators.format import Format
2021

2122
if TYPE_CHECKING:
2223
from pyramid.request import Request
2324
from pyramid.response import Response
24-
from instana.span.span import InstanaSpan
2525
from pyramid.registry import Registry
2626

2727
class InstanaTweenFactory(object):
@@ -32,21 +32,6 @@ def __init__(
3232
) -> None:
3333
self.handler = handler
3434

35-
def _extract_custom_headers(
36-
self, span: "InstanaSpan", headers: Dict[str, Any]
37-
) -> None:
38-
if not agent.options.extra_http_headers:
39-
return
40-
try:
41-
for custom_header in agent.options.extra_http_headers:
42-
if custom_header in headers:
43-
span.set_attribute(
44-
f"http.header.{custom_header}", headers[custom_header]
45-
)
46-
47-
except Exception:
48-
logger.debug("extract_custom_headers: ", exc_info=True)
49-
5035
def __call__(self, request: "Request") -> "Response":
5136
ctx = tracer.extract(Format.HTTP_HEADERS, dict(request.headers))
5237

@@ -56,7 +41,7 @@ def __call__(self, request: "Request") -> "Response":
5641
span.set_attribute(SpanAttributes.HTTP_METHOD, request.method)
5742
span.set_attribute(SpanAttributes.HTTP_URL, request.path)
5843

59-
self._extract_custom_headers(span, request.headers)
44+
extract_custom_headers(span, request.headers)
6045

6146
if len(request.query_string):
6247
scrubbed_params = strip_secrets_from_query(
@@ -74,7 +59,7 @@ def __call__(self, request: "Request") -> "Response":
7459
"http.path_tpl", request.matched_route.pattern
7560
)
7661

77-
self._extract_custom_headers(span, response.headers)
62+
extract_custom_headers(span, response.headers)
7863

7964
tracer.inject(span.context, Format.HTTP_HEADERS, response.headers)
8065
except HTTPException as e:

src/instana/instrumentation/sanic_inst.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,7 @@ def request_with_instana(request: Request) -> None:
7575
)
7676
span.set_attribute("http.params", scrubbed_params)
7777

78-
if agent.options.extra_http_headers:
79-
extract_custom_headers(span, headers)
78+
extract_custom_headers(span, headers)
8079
if hasattr(request, "uri_template") and request.uri_template:
8180
span.set_attribute("http.path_tpl", request.uri_template)
8281
except Exception:
@@ -113,8 +112,7 @@ def response_with_instana(request: Request, response: HTTPResponse) -> None:
113112
span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, status_code)
114113

115114
if hasattr(response, "headers"):
116-
if agent.options.extra_http_headers:
117-
extract_custom_headers(span, response.headers)
115+
extract_custom_headers(span, response.headers)
118116
tracer.inject(span.context, Format.HTTP_HEADERS, response.headers)
119117

120118
if span.is_recording():

src/instana/instrumentation/tornado/client.py

+1-16
Original file line numberDiff line numberDiff line change
@@ -13,25 +13,10 @@
1313
from instana.log import logger
1414
from instana.singletons import agent, tracer
1515
from instana.util.secrets import strip_secrets_from_query
16+
from instana.util.traceutils import extract_custom_headers
1617
from instana.propagators.format import Format
1718
from instana.span.span import get_current_span
1819

19-
if TYPE_CHECKING:
20-
from instana.span.span import InstanaSpan
21-
22-
def extract_custom_headers(
23-
span: "InstanaSpan", headers: Dict[str, Any]
24-
) -> None:
25-
if not agent.options.extra_http_headers or not headers:
26-
return
27-
try:
28-
for custom_header in agent.options.extra_http_headers:
29-
if custom_header in headers:
30-
span.set_attribute(
31-
f"http.header.{custom_header}", headers[custom_header]
32-
)
33-
except Exception:
34-
logger.debug("extract_custom_headers: ", exc_info=True)
3520

3621
@wrapt.patch_function_wrapper('tornado.httpclient', 'AsyncHTTPClient.fetch')
3722
def fetch_with_instana(wrapped, instance, argv, kwargs):

0 commit comments

Comments
 (0)