-
Notifications
You must be signed in to change notification settings - Fork 170
/
tracer_middleware.rb
203 lines (168 loc) · 7.52 KB
/
tracer_middleware.rb
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# frozen_string_literal: true
# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
require 'opentelemetry/trace/status'
require_relative '../util/queue_time'
module OpenTelemetry
module Instrumentation
module Rack
module Middlewares
# TracerMiddleware propagates context and instruments Rack requests
# by way of its middleware system
class TracerMiddleware # rubocop:disable Metrics/ClassLength
class << self
def allowed_rack_request_headers
@allowed_rack_request_headers ||= Array(config[:allowed_request_headers]).each_with_object({}) do |header, memo|
key = header.to_s.upcase.gsub(/[-\s]/, '_')
case key
when 'CONTENT_TYPE', 'CONTENT_LENGTH'
memo[key] = build_attribute_name('http.request.header.', header)
else
memo["HTTP_#{key}"] = build_attribute_name('http.request.header.', header)
end
end
end
def allowed_response_headers
@allowed_response_headers ||= Array(config[:allowed_response_headers]).each_with_object({}) do |header, memo|
memo[header] = build_attribute_name('http.response.header.', header)
memo[header.to_s.upcase] = build_attribute_name('http.response.header.', header)
end
end
def build_attribute_name(prefix, suffix)
prefix + suffix.to_s.downcase.gsub(/[-\s]/, '_')
end
def config
Rack::Instrumentation.instance.config
end
private
def clear_cached_config
@allowed_rack_request_headers = nil
@allowed_response_headers = nil
end
end
EMPTY_HASH = {}.freeze
def initialize(app)
@app = app
@untraced_endpoints = config[:untraced_endpoints]
end
def call(env) # rubocop:disable Metrics/MethodLength
if untraced_request?(env)
OpenTelemetry::Common::Utilities.untraced do
return @app.call(env)
end
end
original_env = env.dup
extracted_context = OpenTelemetry.propagation.extract(
env,
getter: OpenTelemetry::Common::Propagation.rack_env_getter
)
frontend_context = create_frontend_span(env, extracted_context)
# restore extracted context in this process:
OpenTelemetry::Context.with_current(frontend_context || extracted_context) do
request_span_name = create_request_span_name(env['REQUEST_URI'] || original_env['PATH_INFO'], env)
request_span_kind = frontend_context.nil? ? :server : :internal
tracer.in_span(request_span_name,
attributes: request_span_attributes(env: env),
kind: request_span_kind) do |request_span|
OpenTelemetry::Instrumentation::Rack.with_span(request_span) do
@app.call(env).tap do |status, headers, response|
set_attributes_after_request(request_span, status, headers, response)
config[:response_propagators].each { |propagator| propagator.inject(headers) }
end
end
end
end
ensure
finish_span(frontend_context)
end
private
def untraced_request?(env)
return true if @untraced_endpoints.include?(env['PATH_INFO'])
return true if config[:untraced_requests]&.call(env)
false
end
# return Context with the frontend span as the current span
def create_frontend_span(env, extracted_context)
request_start_time = OpenTelemetry::Instrumentation::Rack::Util::QueueTime.get_request_start(env)
return unless config[:record_frontend_span] && !request_start_time.nil?
span = tracer.start_span('http_server.proxy',
with_parent: extracted_context,
start_timestamp: request_start_time,
kind: :server)
OpenTelemetry::Trace.context_with_span(span, parent_context: extracted_context)
end
def finish_span(context)
OpenTelemetry::Trace.current_span(context).finish if context
end
def tracer
OpenTelemetry::Instrumentation::Rack::Instrumentation.instance.tracer
end
def request_span_attributes(env:)
attributes = {
'http.method' => env['REQUEST_METHOD'],
'http.host' => env['HTTP_HOST'] || 'unknown',
'http.scheme' => env['rack.url_scheme'],
'http.target' => env['QUERY_STRING'].empty? ? env['PATH_INFO'] : "#{env['PATH_INFO']}?#{env['QUERY_STRING']}"
}
attributes['http.user_agent'] = env['HTTP_USER_AGENT'] if env['HTTP_USER_AGENT']
attributes.merge!(allowed_request_headers(env))
end
# https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md#name
#
# recommendation: span.name(s) should be low-cardinality (e.g.,
# strip off query param value, keep param name)
#
# see http://github.com/open-telemetry/opentelemetry-specification/pull/416/files
def create_request_span_name(request_uri_or_path_info, env)
# NOTE: dd-trace-rb has implemented 'quantization' (which lowers url cardinality)
# see Datadog::Quantization::HTTP.url
if (implementation = config[:url_quantization])
implementation.call(request_uri_or_path_info, env)
else
"HTTP #{env['REQUEST_METHOD']}"
end
end
def set_attributes_after_request(span, status, headers, _response)
span.status = OpenTelemetry::Trace::Status.error unless (100..499).include?(status.to_i)
span.set_attribute('http.status_code', status)
# NOTE: if data is available, it would be good to do this:
# set_attribute('http.route', ...
# e.g., "/users/:userID?
allowed_response_headers(headers).each { |k, v| span.set_attribute(k, v) }
end
def allowed_request_headers(env)
return EMPTY_HASH if self.class.allowed_rack_request_headers.empty?
{}.tap do |result|
self.class.allowed_rack_request_headers.each do |key, value|
result[value] = env[key] if env.key?(key)
end
end
end
def allowed_response_headers(headers)
return EMPTY_HASH if headers.nil?
return EMPTY_HASH if self.class.allowed_response_headers.empty?
{}.tap do |result|
self.class.allowed_response_headers.each do |key, value|
if headers.key?(key)
result[value] = headers[key]
else
# do case-insensitive match:
headers.each do |k, v|
if k.upcase == key
result[value] = v
break
end
end
end
end
end
end
def config
Rack::Instrumentation.instance.config
end
end
end
end
end
end