-
Notifications
You must be signed in to change notification settings - Fork 824
Expand file tree
/
Copy pathaws.go
More file actions
189 lines (162 loc) · 6.51 KB
/
Copy pathaws.go
File metadata and controls
189 lines (162 loc) · 6.51 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Package otelaws provides instrumentation for the AWS SDK.
package otelaws
import (
"context"
"errors"
"net/http"
"time"
v2Middleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"go.opentelemetry.io/otel/trace"
)
const (
// ScopeName is the instrumentation scope name.
ScopeName = "go.opentelemetry.io/contrib/instrumentation/github.com/aws/aws-sdk-go-v2/otelaws"
)
type spanTimestampKey struct{}
// AttributeBuilder returns an array of KeyValue pairs, it can be used to set custom attributes.
type AttributeBuilder func(ctx context.Context, in middleware.InitializeInput, out middleware.InitializeOutput) []attribute.KeyValue
type otelMiddlewares struct {
tracer trace.Tracer
propagator propagation.TextMapPropagator
attributeBuilders []AttributeBuilder
}
func (otelMiddlewares) initializeMiddlewareBefore(stack *middleware.Stack) error {
return stack.Initialize.Add(middleware.InitializeMiddlewareFunc("OTelInitializeMiddlewareBefore", func(
ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
ctx = context.WithValue(ctx, spanTimestampKey{}, time.Now())
return next.HandleInitialize(ctx, in)
}),
middleware.Before)
}
func (m otelMiddlewares) initializeMiddlewareAfter(stack *middleware.Stack) error {
return stack.Initialize.Add(middleware.InitializeMiddlewareFunc("OTelInitializeMiddlewareAfter", func(
ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
serviceID := v2Middleware.GetServiceID(ctx)
operation := v2Middleware.GetOperationName(ctx)
region := v2Middleware.GetRegion(ctx)
attributes := []attribute.KeyValue{
SystemAttr(),
MethodAttr(serviceID, operation),
RegionAttr(region),
}
ctx, span := m.tracer.Start(
ctx, spanName(serviceID, operation),
trace.WithTimestamp(ctx.Value(spanTimestampKey{}).(time.Time)),
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(attributes...),
)
defer span.End()
out, metadata, err = next.HandleInitialize(ctx, in)
span.SetAttributes(m.buildAttributes(ctx, in, out)...)
if err != nil && !isNotModifiedStatus(err) {
span.SetAttributes(semconv.ErrorType(err))
span.SetStatus(codes.Error, err.Error())
}
return out, metadata, err
}),
middleware.After)
}
func (m otelMiddlewares) finalizeMiddlewareAfter(stack *middleware.Stack) error {
return stack.Finalize.Add(middleware.FinalizeMiddlewareFunc("OTelFinalizeMiddleware", func(
ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (
out middleware.FinalizeOutput, metadata middleware.Metadata, err error,
) {
// Propagate the Trace information by injecting it into the HTTP request.
switch req := in.Request.(type) {
case *smithyhttp.Request:
m.propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))
default:
}
return next.HandleFinalize(ctx, in)
}),
middleware.After)
}
func (otelMiddlewares) deserializeMiddleware(stack *middleware.Stack) error {
return stack.Deserialize.Add(middleware.DeserializeMiddlewareFunc("OTelDeserializeMiddleware", func(
ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
resp, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
// No raw response to wrap with.
return out, metadata, err
}
span := trace.SpanFromContext(ctx)
span.SetAttributes(semconv.HTTPResponseStatusCode(resp.StatusCode))
requestID, ok := v2Middleware.GetRequestIDMetadata(metadata)
if ok {
span.SetAttributes(RequestIDAttr(requestID))
}
return out, metadata, err
}),
middleware.Before)
}
func (m otelMiddlewares) buildAttributes(ctx context.Context, in middleware.InitializeInput, out middleware.InitializeOutput) (attributes []attribute.KeyValue) {
for _, builder := range m.attributeBuilders {
attributes = append(attributes, builder(ctx, in, out)...)
}
return attributes
}
// responseStatusCode reports the HTTP status code carried by err, if err
// wraps a *smithyhttp.ResponseError.
func responseStatusCode(err error) (code int, ok bool) {
var respErr *smithyhttp.ResponseError
if !errors.As(err, &respErr) {
return 0, false
}
return respErr.HTTPStatusCode(), true
}
// isNotModifiedStatus reports whether err wraps an HTTP response error with
// a 304 Not Modified status code. This is returned, for example, by a
// conditional S3 GetObject request whose precondition (such as
// IfModifiedSince) was not satisfied. It indicates the precondition was not
// met, not a failure of the request, and should not be recorded as a span
// error. Other 3xx status codes (e.g. a 301 signaling a misconfigured
// bucket region) can indicate a real problem and are still recorded.
func isNotModifiedStatus(err error) bool {
code, ok := responseStatusCode(err)
return ok && code == http.StatusNotModified
}
func spanName(serviceID, operation string) string {
spanName := serviceID
if operation != "" {
spanName += "." + operation
}
return spanName
}
// AppendMiddlewares attaches OTel middlewares to the AWS Go SDK V2 for instrumentation.
// OTel middlewares can be appended to either all aws clients or a specific operation.
// Please see more details in https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/middleware.html
func AppendMiddlewares(apiOptions *[]func(*middleware.Stack) error, opts ...Option) {
cfg := config{
TracerProvider: otel.GetTracerProvider(),
TextMapPropagator: otel.GetTextMapPropagator(),
}
for _, opt := range opts {
opt.apply(&cfg)
}
if cfg.AttributeBuilders == nil {
cfg.AttributeBuilders = []AttributeBuilder{DefaultAttributeBuilder}
}
m := otelMiddlewares{
tracer: cfg.TracerProvider.Tracer(ScopeName,
trace.WithInstrumentationVersion(Version)),
propagator: cfg.TextMapPropagator,
attributeBuilders: cfg.AttributeBuilders,
}
*apiOptions = append(*apiOptions, m.initializeMiddlewareBefore, m.initializeMiddlewareAfter, m.finalizeMiddlewareAfter, m.deserializeMiddleware)
}