Debian Codegraph @

semconv/internal/http.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package internal provides common semconv functionality.
5 package internal // import "go.opentelemetry.io/otel/semconv/internal"
6
7 import (
8 "fmt"
9 "net"
10 "net/http"
11 "strconv"
12 "strings"
13
14 "go.opentelemetry.io/otel/attribute"
15 "go.opentelemetry.io/otel/codes"
16 "go.opentelemetry.io/otel/trace"
17 )
18
19 // SemanticConventions are the semantic convention values defined for a
20 // version of the OpenTelemetry specification.
21 type SemanticConventions struct {
22 EnduserIDKey attribute.Key
23 HTTPClientIPKey attribute.Key
24 HTTPFlavorKey attribute.Key
25 HTTPHostKey attribute.Key
26 HTTPMethodKey attribute.Key
27 HTTPRequestContentLengthKey attribute.Key
28 HTTPRouteKey attribute.Key
29 HTTPSchemeHTTP attribute.KeyValue
30 HTTPSchemeHTTPS attribute.KeyValue
31 HTTPServerNameKey attribute.Key
32 HTTPStatusCodeKey attribute.Key
33 HTTPTargetKey attribute.Key
34 HTTPURLKey attribute.Key
35 HTTPUserAgentKey attribute.Key
36 NetHostIPKey attribute.Key
37 NetHostNameKey attribute.Key
38 NetHostPortKey attribute.Key
39 NetPeerIPKey attribute.Key
40 NetPeerNameKey attribute.Key
41 NetPeerPortKey attribute.Key
42 NetTransportIP attribute.KeyValue
43 NetTransportOther attribute.KeyValue
44 NetTransportTCP attribute.KeyValue
45 NetTransportUDP attribute.KeyValue
46 NetTransportUnix attribute.KeyValue
47 }
48
49 // NetAttributesFromHTTPRequest generates attributes of the net
50 // namespace as specified by the OpenTelemetry specification for a
51 // span. The network parameter is a string that net.Dial function
52 // from standard library can understand.
53 func (sc *SemanticConventions) NetAttributesFromHTTPRequest(
54 network string,
55 request *http.Request,
56 ) []attribute.KeyValue {
57 attrs := []attribute.KeyValue{}
58
59 switch network {
60 case "tcp", "tcp4", "tcp6":
61 attrs = append(attrs, sc.NetTransportTCP)
62 case "udp", "udp4", "udp6":
63 attrs = append(attrs, sc.NetTransportUDP)
64 case "ip", "ip4", "ip6":
65 attrs = append(attrs, sc.NetTransportIP)
66 case "unix", "unixgram", "unixpacket":
67 attrs = append(attrs, sc.NetTransportUnix)
68 default:
69 attrs = append(attrs, sc.NetTransportOther)
70 }
71
72 peerIP, peerName, peerPort := hostIPNamePort(request.RemoteAddr)
73 if peerIP != "" {
74 attrs = append(attrs, sc.NetPeerIPKey.String(peerIP))
75 }
76 if peerName != "" {
77 attrs = append(attrs, sc.NetPeerNameKey.String(peerName))
78 }
79 if peerPort != 0 {
80 attrs = append(attrs, sc.NetPeerPortKey.Int(peerPort))
81 }
82
83 hostIP, hostName, hostPort := "", "", 0
84 for _, someHost := range []string{request.Host, request.Header.Get("Host"), request.URL.Host} {
85 hostIP, hostName, hostPort = hostIPNamePort(someHost)
86 if hostIP != "" || hostName != "" || hostPort != 0 {
87 break
88 }
89 }
90 if hostIP != "" {
91 attrs = append(attrs, sc.NetHostIPKey.String(hostIP))
92 }
93 if hostName != "" {
94 attrs = append(attrs, sc.NetHostNameKey.String(hostName))
95 }
96 if hostPort != 0 {
97 attrs = append(attrs, sc.NetHostPortKey.Int(hostPort))
98 }
99
100 return attrs
101 }
102
103 // hostIPNamePort extracts the IP address, name and (optional) port from hostWithPort.
104 // It handles both IPv4 and IPv6 addresses. If the host portion is not recognized
105 // as a valid IPv4 or IPv6 address, the `ip` result will be empty and the
106 // host portion will instead be returned in `name`.
107 func hostIPNamePort(hostWithPort string) (ip, name string, port int) {
108 var (
109 hostPart, portPart string
110 parsedPort uint64
111 err error
112 )
113 if hostPart, portPart, err = net.SplitHostPort(hostWithPort); err != nil {
114 hostPart, portPart = hostWithPort, ""
115 }
116 if parsedIP := net.ParseIP(hostPart); parsedIP != nil {
117 ip = parsedIP.String()
118 } else {
119 name = hostPart
120 }
121 if parsedPort, err = strconv.ParseUint(portPart, 10, 16); err == nil {
122 port = int(parsedPort) // nolint: gosec // Bit size of 16 checked above.
123 }
124 return ip, name, port
125 }
126
127 // EndUserAttributesFromHTTPRequest generates attributes of the
128 // enduser namespace as specified by the OpenTelemetry specification
129 // for a span.
130 func (sc *SemanticConventions) EndUserAttributesFromHTTPRequest(request *http.Request) []attribute.KeyValue {
131 if username, _, ok := request.BasicAuth(); ok {
132 return []attribute.KeyValue{sc.EnduserIDKey.String(username)}
133 }
134 return nil
135 }
136
137 // HTTPClientAttributesFromHTTPRequest generates attributes of the
138 // http namespace as specified by the OpenTelemetry specification for
139 // a span on the client side.
140 func (sc *SemanticConventions) HTTPClientAttributesFromHTTPRequest(request *http.Request) []attribute.KeyValue {
141 attrs := []attribute.KeyValue{}
142
143 // remove any username/password info that may be in the URL
144 // before adding it to the attributes
145 userinfo := request.URL.User
146 request.URL.User = nil
147
148 attrs = append(attrs, sc.HTTPURLKey.String(request.URL.String()))
149
150 // restore any username/password info that was removed
151 request.URL.User = userinfo
152
153 return append(attrs, sc.httpCommonAttributesFromHTTPRequest(request)...)
154 }
155
156 func (sc *SemanticConventions) httpCommonAttributesFromHTTPRequest(request *http.Request) []attribute.KeyValue {
157 attrs := []attribute.KeyValue{}
158 if ua := request.UserAgent(); ua != "" {
159 attrs = append(attrs, sc.HTTPUserAgentKey.String(ua))
160 }
161 if request.ContentLength > 0 {
162 attrs = append(attrs, sc.HTTPRequestContentLengthKey.Int64(request.ContentLength))
163 }
164
165 return append(attrs, sc.httpBasicAttributesFromHTTPRequest(request)...)
166 }
167
168 func (sc *SemanticConventions) httpBasicAttributesFromHTTPRequest(request *http.Request) []attribute.KeyValue {
169 // as these attributes are used by HTTPServerMetricAttributesFromHTTPRequest, they should be low-cardinality
170 attrs := []attribute.KeyValue{}
171
172 if request.TLS != nil {
173 attrs = append(attrs, sc.HTTPSchemeHTTPS)
174 } else {
175 attrs = append(attrs, sc.HTTPSchemeHTTP)
176 }
177
178 if request.Host != "" {
179 attrs = append(attrs, sc.HTTPHostKey.String(request.Host))
180 } else if request.URL != nil && request.URL.Host != "" {
181 attrs = append(attrs, sc.HTTPHostKey.String(request.URL.Host))
182 }
183
184 flavor := ""
185 switch request.ProtoMajor {
186 case 1:
187 flavor = fmt.Sprintf("1.%d", request.ProtoMinor)
188 case 2:
189 flavor = "2"
190 }
191 if flavor != "" {
192 attrs = append(attrs, sc.HTTPFlavorKey.String(flavor))
193 }
194
195 if request.Method != "" {
196 attrs = append(attrs, sc.HTTPMethodKey.String(request.Method))
197 } else {
198 attrs = append(attrs, sc.HTTPMethodKey.String(http.MethodGet))
199 }
200
201 return attrs
202 }
203
204 // HTTPServerMetricAttributesFromHTTPRequest generates low-cardinality attributes
205 // to be used with server-side HTTP metrics.
206 func (sc *SemanticConventions) HTTPServerMetricAttributesFromHTTPRequest(
207 serverName string,
208 request *http.Request,
209 ) []attribute.KeyValue {
210 attrs := []attribute.KeyValue{}
211 if serverName != "" {
212 attrs = append(attrs, sc.HTTPServerNameKey.String(serverName))
213 }
214 return append(attrs, sc.httpBasicAttributesFromHTTPRequest(request)...)
215 }
216
217 // HTTPServerAttributesFromHTTPRequest generates attributes of the
218 // http namespace as specified by the OpenTelemetry specification for
219 // a span on the server side. Currently, only basic authentication is
220 // supported.
221 func (sc *SemanticConventions) HTTPServerAttributesFromHTTPRequest(
222 serverName, route string,
223 request *http.Request,
224 ) []attribute.KeyValue {
225 attrs := []attribute.KeyValue{
226 sc.HTTPTargetKey.String(request.RequestURI),
227 }
228
229 if serverName != "" {
230 attrs = append(attrs, sc.HTTPServerNameKey.String(serverName))
231 }
232 if route != "" {
233 attrs = append(attrs, sc.HTTPRouteKey.String(route))
234 }
235 if values := request.Header["X-Forwarded-For"]; len(values) > 0 {
236 addr := values[0]
237 if i := strings.Index(addr, ","); i > 0 {
238 addr = addr[:i]
239 }
240 attrs = append(attrs, sc.HTTPClientIPKey.String(addr))
241 }
242
243 return append(attrs, sc.httpCommonAttributesFromHTTPRequest(request)...)
244 }
245
246 // HTTPAttributesFromHTTPStatusCode generates attributes of the http
247 // namespace as specified by the OpenTelemetry specification for a
248 // span.
249 func (sc *SemanticConventions) HTTPAttributesFromHTTPStatusCode(code int) []attribute.KeyValue {
250 attrs := []attribute.KeyValue{
251 sc.HTTPStatusCodeKey.Int(code),
252 }
253 return attrs
254 }
255
256 type codeRange struct {
257 fromInclusive int
258 toInclusive int
259 }
260
261 func (r codeRange) contains(code int) bool {
262 return r.fromInclusive <= code && code <= r.toInclusive
263 }
264
265 var validRangesPerCategory = map[int][]codeRange{
266 1: {
267 {http.StatusContinue, http.StatusEarlyHints},
268 },
269 2: {
270 {http.StatusOK, http.StatusAlreadyReported},
271 {http.StatusIMUsed, http.StatusIMUsed},
272 },
273 3: {
274 {http.StatusMultipleChoices, http.StatusUseProxy},
275 {http.StatusTemporaryRedirect, http.StatusPermanentRedirect},
276 },
277 4: {
278 {http.StatusBadRequest, http.StatusTeapot}, // yes, teapot is so useful…
279 {http.StatusMisdirectedRequest, http.StatusUpgradeRequired},
280 {http.StatusPreconditionRequired, http.StatusTooManyRequests},
281 {http.StatusRequestHeaderFieldsTooLarge, http.StatusRequestHeaderFieldsTooLarge},
282 {http.StatusUnavailableForLegalReasons, http.StatusUnavailableForLegalReasons},
283 },
284 5: {
285 {http.StatusInternalServerError, http.StatusLoopDetected},
286 {http.StatusNotExtended, http.StatusNetworkAuthenticationRequired},
287 },
288 }
289
290 // SpanStatusFromHTTPStatusCode generates a status code and a message
291 // as specified by the OpenTelemetry specification for a span.
292 func SpanStatusFromHTTPStatusCode(code int) (codes.Code, string) {
293 spanCode, valid := validateHTTPStatusCode(code)
294 if !valid {
295 return spanCode, fmt.Sprintf("Invalid HTTP status code %d", code)
296 }
297 return spanCode, ""
298 }
299
300 // SpanStatusFromHTTPStatusCodeAndSpanKind generates a status code and a message
301 // as specified by the OpenTelemetry specification for a span.
302 // Exclude 4xx for SERVER to set the appropriate status.
303 func SpanStatusFromHTTPStatusCodeAndSpanKind(code int, spanKind trace.SpanKind) (codes.Code, string) {
304 spanCode, valid := validateHTTPStatusCode(code)
305 if !valid {
306 return spanCode, fmt.Sprintf("Invalid HTTP status code %d", code)
307 }
308 category := code / 100
309 if spanKind == trace.SpanKindServer && category == 4 {
310 return codes.Unset, ""
311 }
312 return spanCode, ""
313 }
314
315 // validateHTTPStatusCode validates the HTTP status code and returns
316 // corresponding span status code. If the `code` is not a valid HTTP status
317 // code, returns span status Error and false.
318 func validateHTTPStatusCode(code int) (codes.Code, bool) {
319 category := code / 100
320 ranges, ok := validRangesPerCategory[category]
321 if !ok {
322 return codes.Error, false
323 }
324 ok = false
325 for _, crange := range ranges {
326 ok = crange.contains(code)
327 if ok {
328 break
329 }
330 }
331 if !ok {
332 return codes.Error, false
333 }
334 if category > 0 && category < 4 {
335 return codes.Unset, true
336 }
337 return codes.Error, true
338 }