Skip to content

Commit 1ea8379

Browse files
committed
ft: add instrumentation to s3
Signed-off-by: Cagri Yonca <[email protected]>
1 parent 328fd2b commit 1ea8379

File tree

2 files changed

+164
-292
lines changed

2 files changed

+164
-292
lines changed

src/instana/instrumentation/aws/s3.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# (c) Copyright IBM Corp. 2021
2+
# (c) Copyright Instana Inc. 2020
3+
4+
try:
5+
from typing import TYPE_CHECKING, Any, Callable, Dict, Sequence, Type
6+
7+
from instana.span_context import SpanContext
8+
9+
if TYPE_CHECKING:
10+
from botocore.client import BaseClient
11+
import wrapt
12+
13+
from instana.log import logger
14+
from instana.singletons import tracer
15+
from instana.util.traceutils import (
16+
get_tracer_tuple,
17+
tracing_is_off,
18+
)
19+
20+
operations = {
21+
"upload_file": "UploadFile",
22+
"upload_fileobj": "UploadFileObj",
23+
"download_file": "DownloadFile",
24+
"download_fileobj": "DownloadFileObj",
25+
}
26+
27+
def create_s3_span(
28+
wrapped: Callable[..., Dict[str, Any]],
29+
instance: Type["BaseClient"],
30+
args: Sequence[Dict[str, Any]],
31+
kwargs: Dict[str, Any],
32+
parent_context: SpanContext,
33+
) -> None:
34+
with tracer.start_as_current_span("s3", span_context=parent_context) as span:
35+
try:
36+
span.set_attribute("s3.op", args[0])
37+
if "Bucket" in args[1].keys():
38+
span.set_attribute("s3.bucket", args[1]["Bucket"])
39+
except Exception as exc:
40+
span.record_exception(exc)
41+
logger.debug("create_s3_span: collect error", exc_info=True)
42+
43+
def collect_s3_injected_attributes(
44+
wrapped: Callable[..., object],
45+
instance: Type["BaseClient"],
46+
args: Sequence[object],
47+
kwargs: Dict[str, Any],
48+
) -> Callable[..., object]:
49+
# If we're not tracing, just return
50+
if tracing_is_off():
51+
return wrapped(*args, **kwargs)
52+
53+
tracer, parent_span, _ = get_tracer_tuple()
54+
55+
parent_context = parent_span.get_span_context() if parent_span else None
56+
57+
with tracer.start_as_current_span("s3", span_context=parent_context) as span:
58+
try:
59+
span.set_attribute("s3.op", operations[wrapped.__name__])
60+
if wrapped.__name__ in ["download_file", "download_fileobj"]:
61+
span.set_attribute("s3.bucket", args[0])
62+
else:
63+
span.set_attribute("s3.bucket", args[1])
64+
return wrapped(*args, **kwargs)
65+
except Exception as exc:
66+
span.record_exception(exc)
67+
logger.debug(
68+
"collect_s3_injected_attributes: collect error", exc_info=True
69+
)
70+
71+
for method in [
72+
"upload_file",
73+
"upload_fileobj",
74+
"download_file",
75+
"download_fileobj",
76+
]:
77+
wrapt.wrap_function_wrapper(
78+
"boto3.s3.inject", method, collect_s3_injected_attributes
79+
)
80+
81+
logger.debug("Instrumenting s3")
82+
except ImportError:
83+
pass

0 commit comments

Comments
 (0)