Class: Thirtysix::Rack::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/thirtysix/rack/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



8
9
10
11
# File 'lib/thirtysix/rack/middleware.rb', line 8

def initialize(app)
  puts "Thirtysix: Initializing Middleware"
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/thirtysix/rack/middleware.rb', line 13

def call(env)
  start_time    = Time.now
  start_memory  = get_memory
  start_objects = ObjectSpace.count_objects_size
  
  status, headers, body = @app.call(env)

  if env["ORIGINAL_FULLPATH"].include? "assets"
    puts "Thirtysix: Skipping instrumentation for assets requests"
  else
    end_time    = Time.now
    end_memory  = get_memory
    end_objects = ObjectSpace.count_objects_size

    app_request = Thirtysix::AppRequest.new
    app_request.request_time_in_milliseconds = ((end_time - start_time) * 1000).to_i
    app_request.memory_in_mb = end_memory - start_memory
    app_request.build(start_objects, end_objects, env)

    push app_request
  end
  
  [status, headers, body]
end

#endpoint_uriObject



61
62
63
# File 'lib/thirtysix/rack/middleware.rb', line 61

def endpoint_uri
  @endpoint_uri ||= URI(thirtysix_url + thirtysix_path)
end

#get_memoryObject

Returns current process’ memory usage in MB Returns nil if any error occurred Only works on Darwin10 Shamelessly stolen from:

https://github.com/newrelic/rpm/blob/master/lib/new_relic/agent/samplers/memory_sampler.rb


45
46
47
# File 'lib/thirtysix/rack/middleware.rb', line 45

def get_memory
  (`ps -o rss #{$$}`.split("\n")[1].to_f / 1024.0) rescue nil
end

#push(app_request) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/thirtysix/rack/middleware.rb', line 65

def push(app_request)
  begin
    http = Net::HTTP.new(endpoint_uri.host, endpoint_uri.port)
    http.open_timeout = 0.2
    http.read_timeout = 0.2
    headers = {'Content-Type' => 'text/json', 'X-THIRTYSIX-API-KEY' => thirtysix_api_key}
    request = Net::HTTP::Post.new(endpoint_uri.request_uri, headers)
    request.body = app_request.to_json
    response = http.request(request)
  rescue Exception => e
    puts "Thirtysix: We could not contact the Thirtysix client on #{thirtysix_url} [#{e.message}]"
  end        
end

#thirtysix_api_keyObject



49
50
51
# File 'lib/thirtysix/rack/middleware.rb', line 49

def thirtysix_api_key
  ENV['THIRTYSIX_API_KEY']
end

#thirtysix_pathObject



57
58
59
# File 'lib/thirtysix/rack/middleware.rb', line 57

def thirtysix_path
  "/api/app_requests"
end

#thirtysix_urlObject



53
54
55
# File 'lib/thirtysix/rack/middleware.rb', line 53

def thirtysix_url
  ENV['THIRTYSIX_URL']
end