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.



3
4
5
# File 'lib/instana/instrumentation/rack.rb', line 3

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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

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

  # 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.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.trace_id
    span_id = ::Instana.tracer.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