Class: Newrelic::Metrics

Inherits:
Object
  • Object
show all
Defined in:
lib/scaltainer/newrelic/metrics.rb

Constant Summary collapse

PERMANENT_ERROR_STATUSES =

New Relic reports failures as an error body alongside an HTTP status. These statuses mean the request can never succeed as configured (unknown application id, rejected API key), so they are permanent. Anything else (rate limiting, 5xx) is transient and worth retrying on the next tick.

[400, 401, 403, 404].freeze

Instance Method Summary collapse

Constructor Details

#initialize(license_key) ⇒ Metrics

Returns a new instance of Metrics.



9
10
11
12
# File 'lib/scaltainer/newrelic/metrics.rb', line 9

def initialize(license_key)
  @headers = {"X-Api-Key" => license_key}
  @base_url = "https://api.newrelic.com/v2"
end

Instance Method Details

#get_avg_response_time(app_id, from, to) ⇒ Object

https://docs.newrelic.com/docs/apis/rest-api-v2/application-examples-v2/average-response-time-examples-v2 Returns the average response time, or nil when New Relic holds no data for the requested window. Callers must treat nil as "no metric for this resource" rather than as a response time.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/scaltainer/newrelic/metrics.rb', line 18

def get_avg_response_time(app_id, from, to)
  url = "#{@base_url}/applications/#{app_id}/metrics/data.json"
  conn = Excon.new(url, persistent: true, tcp_nodelay: true)
  time_range = "from=#{from.iso8601}&to=#{to.iso8601}"
  metric_names_array = %w(
    names[]=HttpDispatcher&values[]=average_call_time&values[]=call_count
    names[]=WebFrontend/QueueTime&values[]=call_count&values[]=average_response_time
  )
  http_values, webfe_values = request(conn, metric_names_array, time_range)

  # an application that dispatched nothing in the window has no response time
  return nil unless http_values
  http_call_count = numeric_value http_values, "call_count"
  return nil if http_call_count.zero?
  http_average_call_time = numeric_value http_values, "average_call_time"

  # queue time is an additive correction and is absent for applications that
  # do not sit behind a request queue, in which case it contributes nothing
  webfe_call_count = webfe_values ? numeric_value(webfe_values, "call_count") : 0
  webfe_average_response_time = webfe_values ? numeric_value(webfe_values, "average_response_time") : 0

  http_average_call_time + (1.0 * webfe_call_count * webfe_average_response_time / http_call_count)
end