Class: Instana::Rack

Inherits:
Object
  • Object
show all
Defined in:
lib/instana/instrumentation/rack.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Rack

Returns a new instance of Rack.



7
8
9
# File 'lib/instana/instrumentation/rack.rb', line 7

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/instana/instrumentation/rack.rb', line 11

def call(env)
  kvs = { :http => {} }
  kvs[:http][:method] = env['REQUEST_METHOD']
  kvs[:http][:url] = ::CGI.unescape(env['PATH_INFO'])

  if env.key?('HTTP_HOST')
    kvs[:http][:host] = env['HTTP_HOST']
  elsif env.key?('SERVER_NAME')
    kvs[:http][:host] = env['SERVER_NAME']
  end

  if ENV.key?('INSTANA_SERVICE_NAME')
    kvs[:service] = ENV['INSTANA_SERVICE_NAME']
  end

  if ::Instana.agent.extra_headers
    ::Instana.agent.extra_headers.each { |custom_header|
      # Headers are available in this format: HTTP_X_CAPTURE_THIS
      rack_header = 'HTTP_' + custom_header.upcase
      rack_header.tr!('-', '_')
      if env.key?(rack_header)
        kvs["http.#{custom_header}"] = env[rack_header]
      end
    }
  end

  # Check incoming context
  incoming_context = {}
  if env.key?('HTTP_X_INSTANA_T')
    incoming_context[:trace_id]  = ::Instana::Util.header_to_id(env['HTTP_X_INSTANA_T'])
    incoming_context[:span_id]   = ::Instana::Util.header_to_id(env['HTTP_X_INSTANA_S']) if env.key?('HTTP_X_INSTANA_S')
    incoming_context[:level]     = env['HTTP_X_INSTANA_L'] if env.key?('HTTP_X_INSTANA_L')
  end

  ::Instana.tracer.log_start_or_continue(:rack, {}, incoming_context)

  status, headers, response = @app.call(env)

  if ::Instana.tracer.tracing?
    kvs[:http][:status] = status

    if !status.is_a?(Integer) || status.between?(500, 511)
      # Because of the 5xx response, we flag this span as errored but
      # without a backtrace (no exception)
      ::Instana.tracer.log_error(nil)
    end

    # Save the IDs before the trace ends so we can place
    # them in the response headers in the ensure block
    trace_id = ::Instana.tracer.current_span.trace_id
    span_id = ::Instana.tracer.current_span.id
  end

  [status, headers, response]
rescue Exception => e
  ::Instana.tracer.log_error(e)
  raise
ensure
  if headers && ::Instana.tracer.tracing?
    # Set reponse headers; encode as hex string
    headers['X-Instana-T'] = ::Instana::Util.id_to_header(trace_id)
    headers['X-Instana-S'] = ::Instana::Util.id_to_header(span_id)
  end
  ::Instana.tracer.log_end(:rack, kvs)
end