| 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/v4" |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"net/http" |
| 10 |
"strings" |
| 11 |
|
| 12 |
"go.opentelemetry.io/otel/attribute" |
| 13 |
"go.opentelemetry.io/otel/codes" |
| 14 |
) |
| 15 |
|
| 16 |
// HTTPConv are the HTTP semantic convention attributes defined for a version |
| 17 |
// of the OpenTelemetry specification. |
| 18 |
type HTTPConv struct { |
| 19 |
NetConv *NetConv |
| 20 |
|
| 21 |
EnduserIDKey attribute.Key |
| 22 |
HTTPClientIPKey attribute.Key |
| 23 |
NetProtocolNameKey attribute.Key |
| 24 |
NetProtocolVersionKey attribute.Key |
| 25 |
HTTPMethodKey attribute.Key |
| 26 |
HTTPRequestContentLengthKey attribute.Key |
| 27 |
HTTPResponseContentLengthKey attribute.Key |
| 28 |
HTTPRouteKey attribute.Key |
| 29 |
HTTPSchemeHTTP attribute.KeyValue |
| 30 |
HTTPSchemeHTTPS attribute.KeyValue |
| 31 |
HTTPStatusCodeKey attribute.Key |
| 32 |
HTTPTargetKey attribute.Key |
| 33 |
HTTPURLKey attribute.Key |
| 34 |
UserAgentOriginalKey attribute.Key |
| 35 |
} |
| 36 |
|
| 37 |
// ClientResponse returns attributes for an HTTP response received by a client |
| 38 |
// from a server. The following attributes are returned if the related values |
| 39 |
// are defined in resp: "http.status.code", "http.response_content_length". |
| 40 |
// |
| 41 |
// This does not add all OpenTelemetry required attributes for an HTTP event, |
| 42 |
// it assumes ClientRequest was used to create the span with a complete set of |
| 43 |
// attributes. If a complete set of attributes can be generated using the |
| 44 |
// request contained in resp. For example: |
| 45 |
// |
| 46 |
// append(ClientResponse(resp), ClientRequest(resp.Request)...) |
| 47 |
func (c *HTTPConv) ClientResponse(resp *http.Response) []attribute.KeyValue { |
| 48 |
var n int |
| 49 |
if resp.StatusCode > 0 { |
| 50 |
n++ |
| 51 |
} |
| 52 |
if resp.ContentLength > 0 { |
| 53 |
n++ |
| 54 |
} |
| 55 |
|
| 56 |
attrs := make([]attribute.KeyValue, 0, n) |
| 57 |
if resp.StatusCode > 0 { |
| 58 |
attrs = append(attrs, c.HTTPStatusCodeKey.Int(resp.StatusCode)) |
| 59 |
} |
| 60 |
if resp.ContentLength > 0 { |
| 61 |
attrs = append(attrs, c.HTTPResponseContentLengthKey.Int(int(resp.ContentLength))) |
| 62 |
} |
| 63 |
return attrs |
| 64 |
} |
| 65 |
|
| 66 |
// ClientRequest returns attributes for an HTTP request made by a client. The |
| 67 |
// following attributes are always returned: "http.url", "http.flavor", |
| 68 |
// "http.method", "net.peer.name". The following attributes are returned if the |
| 69 |
// related values are defined in req: "net.peer.port", "http.user_agent", |
| 70 |
// "http.request_content_length", "enduser.id". |
| 71 |
func (c *HTTPConv) ClientRequest(req *http.Request) []attribute.KeyValue { |
| 72 |
n := 3 // URL, peer name, proto, and method. |
| 73 |
var h string |
| 74 |
if req.URL != nil { |
| 75 |
h = req.URL.Host |
| 76 |
} |
| 77 |
peer, p := firstHostPort(h, req.Header.Get("Host")) |
| 78 |
port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", p) |
| 79 |
if port > 0 { |
| 80 |
n++ |
| 81 |
} |
| 82 |
useragent := req.UserAgent() |
| 83 |
if useragent != "" { |
| 84 |
n++ |
| 85 |
} |
| 86 |
if req.ContentLength > 0 { |
| 87 |
n++ |
| 88 |
} |
| 89 |
userID, _, hasUserID := req.BasicAuth() |
| 90 |
if hasUserID { |
| 91 |
n++ |
| 92 |
} |
| 93 |
attrs := make([]attribute.KeyValue, 0, n) |
| 94 |
|
| 95 |
attrs = append(attrs, c.method(req.Method), c.proto(req.Proto)) |
| 96 |
|
| 97 |
var u string |
| 98 |
if req.URL != nil { |
| 99 |
// Remove any username/password info that may be in the URL. |
| 100 |
userinfo := req.URL.User |
| 101 |
req.URL.User = nil |
| 102 |
u = req.URL.String() |
| 103 |
// Restore any username/password info that was removed. |
| 104 |
req.URL.User = userinfo |
| 105 |
} |
| 106 |
attrs = append( |
| 107 |
attrs, |
| 108 |
c.HTTPURLKey.String(u), |
| 109 |
c.NetConv.PeerName(peer), |
| 110 |
) |
| 111 |
if port > 0 { |
| 112 |
attrs = append(attrs, c.NetConv.PeerPort(port)) |
| 113 |
} |
| 114 |
|
| 115 |
if useragent != "" { |
| 116 |
attrs = append(attrs, c.UserAgentOriginalKey.String(useragent)) |
| 117 |
} |
| 118 |
|
| 119 |
if l := req.ContentLength; l > 0 { |
| 120 |
attrs = append(attrs, c.HTTPRequestContentLengthKey.Int64(l)) |
| 121 |
} |
| 122 |
|
| 123 |
if hasUserID { |
| 124 |
attrs = append(attrs, c.EnduserIDKey.String(userID)) |
| 125 |
} |
| 126 |
|
| 127 |
return attrs |
| 128 |
} |
| 129 |
|
| 130 |
// ServerRequest returns attributes for an HTTP request received by a server. |
| 131 |
// |
| 132 |
// The server must be the primary server name if it is known. For example this |
| 133 |
// would be the ServerName directive |
| 134 |
// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache |
| 135 |
// server, and the server_name directive |
| 136 |
// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an |
| 137 |
// nginx server. More generically, the primary server name would be the host |
| 138 |
// header value that matches the default virtual host of an HTTP server. It |
| 139 |
// should include the host identifier and if a port is used to route to the |
| 140 |
// server that port identifier should be included as an appropriate port |
| 141 |
// suffix. |
| 142 |
// |
| 143 |
// If the primary server name is not known, server should be an empty string. |
| 144 |
// The req Host will be used to determine the server instead. |
| 145 |
// |
| 146 |
// The following attributes are always returned: "http.method", "http.scheme", |
| 147 |
// "http.flavor", "http.target", "net.host.name". The following attributes are |
| 148 |
// returned if they related values are defined in req: "net.host.port", |
| 149 |
// "net.sock.peer.addr", "net.sock.peer.port", "http.user_agent", "enduser.id", |
| 150 |
// "http.client_ip". |
| 151 |
func (c *HTTPConv) ServerRequest(server string, req *http.Request) []attribute.KeyValue { |
| 152 |
// TODO: This currently does not add the specification required |
| 153 |
// `http.target` attribute. It has too high of a cardinality to safely be |
| 154 |
// added. An alternate should be added, or this comment removed, when it is |
| 155 |
// addressed by the specification. If it is ultimately decided to continue |
| 156 |
// not including the attribute, the HTTPTargetKey field of the HTTPConv |
| 157 |
// should be removed as well. |
| 158 |
|
| 159 |
n := 4 // Method, scheme, proto, and host name. |
| 160 |
var host string |
| 161 |
var p int |
| 162 |
if server == "" { |
| 163 |
host, p = splitHostPort(req.Host) |
| 164 |
} else { |
| 165 |
// Prioritize the primary server name. |
| 166 |
host, p = splitHostPort(server) |
| 167 |
if p < 0 { |
| 168 |
_, p = splitHostPort(req.Host) |
| 169 |
} |
| 170 |
} |
| 171 |
hostPort := requiredHTTPPort(req.TLS != nil, p) |
| 172 |
if hostPort > 0 { |
| 173 |
n++ |
| 174 |
} |
| 175 |
peer, peerPort := splitHostPort(req.RemoteAddr) |
| 176 |
if peer != "" { |
| 177 |
n++ |
| 178 |
if peerPort > 0 { |
| 179 |
n++ |
| 180 |
} |
| 181 |
} |
| 182 |
useragent := req.UserAgent() |
| 183 |
if useragent != "" { |
| 184 |
n++ |
| 185 |
} |
| 186 |
userID, _, hasUserID := req.BasicAuth() |
| 187 |
if hasUserID { |
| 188 |
n++ |
| 189 |
} |
| 190 |
clientIP := serverClientIP(req.Header.Get("X-Forwarded-For")) |
| 191 |
if clientIP != "" { |
| 192 |
n++ |
| 193 |
} |
| 194 |
attrs := make([]attribute.KeyValue, 0, n) |
| 195 |
|
| 196 |
attrs = append( |
| 197 |
attrs, |
| 198 |
c.method(req.Method), |
| 199 |
c.scheme(req.TLS != nil), |
| 200 |
c.proto(req.Proto), |
| 201 |
c.NetConv.HostName(host), |
| 202 |
) |
| 203 |
|
| 204 |
if hostPort > 0 { |
| 205 |
attrs = append(attrs, c.NetConv.HostPort(hostPort)) |
| 206 |
} |
| 207 |
|
| 208 |
if peer != "" { |
| 209 |
// The Go HTTP server sets RemoteAddr to "IP:port", this will not be a |
| 210 |
// file-path that would be interpreted with a sock family. |
| 211 |
attrs = append(attrs, c.NetConv.SockPeerAddr(peer)) |
| 212 |
if peerPort > 0 { |
| 213 |
attrs = append(attrs, c.NetConv.SockPeerPort(peerPort)) |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
if useragent != "" { |
| 218 |
attrs = append(attrs, c.UserAgentOriginalKey.String(useragent)) |
| 219 |
} |
| 220 |
|
| 221 |
if hasUserID { |
| 222 |
attrs = append(attrs, c.EnduserIDKey.String(userID)) |
| 223 |
} |
| 224 |
|
| 225 |
if clientIP != "" { |
| 226 |
attrs = append(attrs, c.HTTPClientIPKey.String(clientIP)) |
| 227 |
} |
| 228 |
|
| 229 |
return attrs |
| 230 |
} |
| 231 |
|
| 232 |
func (c *HTTPConv) method(method string) attribute.KeyValue { |
| 233 |
if method == "" { |
| 234 |
return c.HTTPMethodKey.String(http.MethodGet) |
| 235 |
} |
| 236 |
return c.HTTPMethodKey.String(method) |
| 237 |
} |
| 238 |
|
| 239 |
func (c *HTTPConv) scheme(https bool) attribute.KeyValue { // nolint:revive |
| 240 |
if https { |
| 241 |
return c.HTTPSchemeHTTPS |
| 242 |
} |
| 243 |
return c.HTTPSchemeHTTP |
| 244 |
} |
| 245 |
|
| 246 |
func (c *HTTPConv) proto(proto string) attribute.KeyValue { |
| 247 |
switch proto { |
| 248 |
case "HTTP/1.0": |
| 249 |
return c.NetProtocolVersionKey.String("1.0") |
| 250 |
case "HTTP/1.1": |
| 251 |
return c.NetProtocolVersionKey.String("1.1") |
| 252 |
case "HTTP/2": |
| 253 |
return c.NetProtocolVersionKey.String("2.0") |
| 254 |
case "HTTP/3": |
| 255 |
return c.NetProtocolVersionKey.String("3.0") |
| 256 |
default: |
| 257 |
return c.NetProtocolNameKey.String(proto) |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
func serverClientIP(xForwardedFor string) string { |
| 262 |
if idx := strings.Index(xForwardedFor, ","); idx >= 0 { |
| 263 |
xForwardedFor = xForwardedFor[:idx] |
| 264 |
} |
| 265 |
return xForwardedFor |
| 266 |
} |
| 267 |
|
| 268 |
func requiredHTTPPort(https bool, port int) int { // nolint:revive |
| 269 |
if https { |
| 270 |
if port > 0 && port != 443 { |
| 271 |
return port |
| 272 |
} |
| 273 |
} else { |
| 274 |
if port > 0 && port != 80 { |
| 275 |
return port |
| 276 |
} |
| 277 |
} |
| 278 |
return -1 |
| 279 |
} |
| 280 |
|
| 281 |
// Return the request host and port from the first non-empty source. |
| 282 |
func firstHostPort(source ...string) (host string, port int) { |
| 283 |
for _, hostport := range source { |
| 284 |
host, port = splitHostPort(hostport) |
| 285 |
if host != "" || port > 0 { |
| 286 |
break |
| 287 |
} |
| 288 |
} |
| 289 |
return host, port |
| 290 |
} |
| 291 |
|
| 292 |
// RequestHeader returns the contents of h as OpenTelemetry attributes. |
| 293 |
func (c *HTTPConv) RequestHeader(h http.Header) []attribute.KeyValue { |
| 294 |
return c.header("http.request.header", h) |
| 295 |
} |
| 296 |
|
| 297 |
// ResponseHeader returns the contents of h as OpenTelemetry attributes. |
| 298 |
func (c *HTTPConv) ResponseHeader(h http.Header) []attribute.KeyValue { |
| 299 |
return c.header("http.response.header", h) |
| 300 |
} |
| 301 |
|
| 302 |
func (*HTTPConv) header(prefix string, h http.Header) []attribute.KeyValue { |
| 303 |
key := func(k string) attribute.Key { |
| 304 |
k = strings.ToLower(k) |
| 305 |
k = strings.ReplaceAll(k, "-", "_") |
| 306 |
k = fmt.Sprintf("%s.%s", prefix, k) |
| 307 |
return attribute.Key(k) |
| 308 |
} |
| 309 |
|
| 310 |
attrs := make([]attribute.KeyValue, 0, len(h)) |
| 311 |
for k, v := range h { |
| 312 |
attrs = append(attrs, key(k).StringSlice(v)) |
| 313 |
} |
| 314 |
return attrs |
| 315 |
} |
| 316 |
|
| 317 |
// ClientStatus returns a span status code and message for an HTTP status code |
| 318 |
// value received by a client. |
| 319 |
func (*HTTPConv) ClientStatus(code int) (codes.Code, string) { |
| 320 |
stat, valid := validateHTTPStatusCode(code) |
| 321 |
if !valid { |
| 322 |
return stat, fmt.Sprintf("Invalid HTTP status code %d", code) |
| 323 |
} |
| 324 |
return stat, "" |
| 325 |
} |
| 326 |
|
| 327 |
// ServerStatus returns a span status code and message for an HTTP status code |
| 328 |
// value returned by a server. Status codes in the 400-499 range are not |
| 329 |
// returned as errors. |
| 330 |
func (*HTTPConv) ServerStatus(code int) (codes.Code, string) { |
| 331 |
stat, valid := validateHTTPStatusCode(code) |
| 332 |
if !valid { |
| 333 |
return stat, fmt.Sprintf("Invalid HTTP status code %d", code) |
| 334 |
} |
| 335 |
|
| 336 |
if code/100 == 4 { |
| 337 |
return codes.Unset, "" |
| 338 |
} |
| 339 |
return stat, "" |
| 340 |
} |
| 341 |
|
| 342 |
type codeRange struct { |
| 343 |
fromInclusive int |
| 344 |
toInclusive int |
| 345 |
} |
| 346 |
|
| 347 |
func (r codeRange) contains(code int) bool { |
| 348 |
return r.fromInclusive <= code && code <= r.toInclusive |
| 349 |
} |
| 350 |
|
| 351 |
var validRangesPerCategory = map[int][]codeRange{ |
| 352 |
1: { |
| 353 |
{http.StatusContinue, http.StatusEarlyHints}, |
| 354 |
}, |
| 355 |
2: { |
| 356 |
{http.StatusOK, http.StatusAlreadyReported}, |
| 357 |
{http.StatusIMUsed, http.StatusIMUsed}, |
| 358 |
}, |
| 359 |
3: { |
| 360 |
{http.StatusMultipleChoices, http.StatusUseProxy}, |
| 361 |
{http.StatusTemporaryRedirect, http.StatusPermanentRedirect}, |
| 362 |
}, |
| 363 |
4: { |
| 364 |
{http.StatusBadRequest, http.StatusTeapot}, // yes, teapot is so useful… |
| 365 |
{http.StatusMisdirectedRequest, http.StatusUpgradeRequired}, |
| 366 |
{http.StatusPreconditionRequired, http.StatusTooManyRequests}, |
| 367 |
{http.StatusRequestHeaderFieldsTooLarge, http.StatusRequestHeaderFieldsTooLarge}, |
| 368 |
{http.StatusUnavailableForLegalReasons, http.StatusUnavailableForLegalReasons}, |
| 369 |
}, |
| 370 |
5: { |
| 371 |
{http.StatusInternalServerError, http.StatusLoopDetected}, |
| 372 |
{http.StatusNotExtended, http.StatusNetworkAuthenticationRequired}, |
| 373 |
}, |
| 374 |
} |
| 375 |
|
| 376 |
// validateHTTPStatusCode validates the HTTP status code and returns |
| 377 |
// corresponding span status code. If the `code` is not a valid HTTP status |
| 378 |
// code, returns span status Error and false. |
| 379 |
func validateHTTPStatusCode(code int) (codes.Code, bool) { |
| 380 |
category := code / 100 |
| 381 |
ranges, ok := validRangesPerCategory[category] |
| 382 |
if !ok { |
| 383 |
return codes.Error, false |
| 384 |
} |
| 385 |
ok = false |
| 386 |
for _, crange := range ranges { |
| 387 |
ok = crange.contains(code) |
| 388 |
if ok { |
| 389 |
break |
| 390 |
} |
| 391 |
} |
| 392 |
if !ok { |
| 393 |
return codes.Error, false |
| 394 |
} |
| 395 |
if category > 0 && category < 4 { |
| 396 |
return codes.Unset, true |
| 397 |
} |
| 398 |
return codes.Error, true |
| 399 |
} |