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
|
# File 'lib/newrelic-metrics.rb', line 45
def metrics(options={})
resource_id = options[:application] || options[:server]
resource = options[:application] ? 'applications' : 'servers'
metrics = options[:metrics]
range = options[:range] || {}
summarize = options[:summarize] || false
conditions = []
raise ArgumentError.new("Need to define either an application or server id") unless resource_id
raise ArgumentError.new("Need to define either an application or server id, but not both") if options[:application] && options[:server]
raise ArgumentError.new("Metrics must be set") unless metrics
raise ArgumentError.new("Metrics must be an hash") unless metrics.is_a?(Hash)
raise ArgumentError.new("Metric keys must be string") unless metrics.keys.all?{|k| k.is_a?(String)}
raise ArgumentError.new("Metric values must be arrays") unless metrics.values.all?{|k| k.is_a?(Array)}
raise ArgumentError.new("Metric values must be an array of strings") unless metrics.values.all?{|k| k.all?{|v| v.is_a?(String)} }
if range && range!={}
raise ArgumentError.new("Range must only contain a :to and :from time") unless range.keys.all?{|k| k==:to || k==:from }
raise ArgumentError.new("Range must contain a :from time") unless range.keys.include?(:from)
end
metrics.keys.each {|name| conditions << "names[]=#{URI.encode(name)}" }
metrics.values.flatten.each {|val| conditions << "values[]=#{URI.encode(val)}" }
if range[:from]
from_time = range[:from].is_a?(String) ? Chronic.parse(range[:from], context: :past) : range[:from]
to_time = range[:to].is_a?(String) ? Chronic.parse(range[:to]) : range[:to] if range[:to]
to_time ||= Time.now
if from_time
conditions << "from=#{from_time.getlocal('+00:00').iso8601}"
conditions << "to=#{to_time.getlocal('+00:00').iso8601}"
end
end
conditions << "summarize=true" if summarize
query = conditions.join('&')
get(resource, resource_id, "metrics/data", query)['metric_data']
end
|