Class: Circonus

Inherits:
Object
  • Object
show all
Defined in:
lib/circonus.rb

Defined Under Namespace

Classes: Timeout

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :timeout => 300,
  :open_timeout => 300,
  :verify_ssl => false
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(apitoken, appname, agent = nil, options = {}) ⇒ Circonus

Returns a new instance of Circonus.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/circonus.rb', line 38

def initialize(apitoken,appname,agent=nil, options={})
  @apitoken = apitoken
  @debug = true
  @raise_errors = false
  @appname = appname
  @agent = agent
  @headers = {
    "X-Circonus-Auth-Token" => @apitoken,
    "X-Circonus-App-Name" => @appname,
    "Accept" => 'application/json',
    "Content-Type" => "application/json"
  }
  @url_prefix = "https://api.circonus.com/v2/"
  @options = DEFAULT_OPTIONS.merge(options)
end

Instance Attribute Details

#agentObject

Returns the value of attribute agent.



13
14
15
# File 'lib/circonus.rb', line 13

def agent
  @agent
end

#debugObject

Returns the value of attribute debug.



15
16
17
# File 'lib/circonus.rb', line 15

def debug
  @debug
end

#raise_errorsObject

Returns the value of attribute raise_errors.



14
15
16
# File 'lib/circonus.rb', line 14

def raise_errors
  @raise_errors
end

Instance Method Details

#_composite_formula(formula, graph) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/circonus.rb', line 185

def _composite_formula(formula,graph)
  formula = formula.clone
  formula.tr!('^A-Za-z0-9/+.*_)(-','' ) # prevent injection
  formula.tr!('A-Z','a-z')
  formula.gsub!(/[a-z]+/) { |n| "var_#{n}" } # prevent clobbering of ruby keywords
  dps = graph['datapoints']
  ndps = dps.length
  nvals = dps.first['data'].length
  data = []
  (0...nvals).each do |n|
    evalstr = ""
    ('a'..'zzzz').each_with_index do |x,i|
      break if i == ndps
      evalstr += "var_#{x}=#{dps[i]['data'][n].last.to_f.to_s}\n" # force an s->i->s conversion to prevent injection in the values
    end
    res = eval "#{evalstr}\n#{formula}\n"
    data[n] = [dps.first['data'][n].first,res]
  end
  return data
end

#_data_derive(data, datapoint) ⇒ Object



177
178
179
180
181
182
183
# File 'lib/circonus.rb', line 177

def _data_derive(data,datapoint)
  derive = datapoint['derive']
  derive = 'value' if derive == 'gauge'
  data = data.map { |m| [m[0],(m[1] ? m[1][derive] : nil)] }
  data = _data_formula(datapoint['data_formula'],data) if datapoint['data_formula']
  return data
end

#_data_formula(formula, data) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/circonus.rb', line 164

def _data_formula(formula,data)
  vals = []
  formula = formula.clone
  formula.tr!('^A-Za-z0-9/+.*_)(-','' ) # prevent injection
  formula.tr!('A-Z','a-z')
  formula.gsub!(/[a-z]+/) { |n| "var_#{n}" } # prevent clobbering of ruby keywords
  data.each_with_index do |v,i|
    res = eval "var_val=#{v[1]}\n#{formula}\n"
    vals[i] = [v[0],res]
  end
  return vals
end

#_rest(type, url, headers, data = nil) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/circonus.rb', line 54

def _rest(type,url,headers,data=nil)
  #STDERR.puts "_rest: type=#{type} url=#{url} headers=#{headers.inspect} data=#{data.inspect}"
  begin
    resource = RestClient::Resource.new url, :timeout => @options[:timeout], :open_timeout => @options[:open_timeout], :verify_ssl => @options[:verify_ssl]
    case type
    when 'delete'
      r = resource.delete headers
    when 'post'
      r = resource.post Yajl::Encoder.encode(data), headers
    when 'put'
      r = resource.put Yajl::Encoder.encode(data), headers
    else 'get'
      r = resource.get headers
    end
  rescue RestClient::Forbidden,RestClient::BadRequest,RestClient::InternalServerError,RestClient::MethodNotAllowed => e
    err = Yajl::Parser.parse(e.response)
    print "Error (#{e.http_code}): ",err['error']," [#{e.http_body}]\n" if @debug
    raise if @raise_errors
    return nil,err
  rescue RestClient::RequestTimeout
    raise Circonus::Timeout
  end
  return r
end

#add(method, data) ⇒ Object



96
97
98
99
100
# File 'lib/circonus.rb', line 96

def add(method,data)
  r, err = _rest('post',@url_prefix + method, @headers, data)
  return nil,err if r.nil?
  return Yajl::Parser.parse(r)
end

#delete(method, id) ⇒ Object



88
89
90
91
92
93
94
# File 'lib/circonus.rb', line 88

def delete(method,id)
  cid = id.to_s.split('/').last
  url = @url_prefix + method + '/' + URI.escape(cid)
  r,err = _rest('delete',url, @headers)
  return nil,err if r.nil?
  return Yajl::Parser.parse(r)
end

#get(method, id) ⇒ Object



79
80
81
82
83
84
85
86
# File 'lib/circonus.rb', line 79

def get(method,id)
  cid = id.to_s.split('/').last
  url = @url_prefix + method + '/' + URI.escape(cid)
  #print "url=#{url}\n"
  r,err = _rest('get',url, @headers)
  return nil,err if r.nil?
  return Yajl::Parser.parse(r)
end

#get_data(cid, metric, params = {}) ⇒ Object

extraction of time ranged data (this one is a bit different from the other v2 ones)



152
153
154
155
156
157
158
159
160
161
162
# File 'lib/circonus.rb', line 152

def get_data(cid,metric,params = {})
  params['start'] = (Time.now - 3600).to_i unless params.has_key? 'start'
  params['end'] = Time.now.to_i unless params.has_key? 'end'
  params['period'] = 300 unless params.has_key? 'period'
  params['type'] = 'numeric' unless params.has_key? 'type'
  url = @url_prefix + 'data' + '/' + URI.escape(cid.to_s.split('/').last) + '_' + URI::escape(metric)
  headers = @headers.merge({:params => params})
  r,err = _rest('get',url, headers)
  return nil,err if r.nil?
  return Yajl::Parser.parse(r)
end

#get_graph_data(gid, t_start = nil, t_end = nil) ⇒ Object

Get the range of data values from start to end time This calculates out the datapoints and composites using the formulas in each graph –TODO This is very slow at the moment.……



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/circonus.rb', line 209

def get_graph_data(gid,t_start=nil,t_end=nil)
  t_end ||= Time.new.to_i
  t_start ||= (t_end - 600)
  g = get_graph(gid)
  params = {'end'=>t_end.to_i,'start'=>t_start.to_i}
  g['datapoints'].each do |dp|
    res = get_data(dp['check_id'],dp['metric_name'],params)
    data = res['data']
    dp['data'] = _data_derive(data,dp)
  end
  g['composites'].each do |cmp|
    cmp['data'] = _composite_formula(cmp['data_formula'],g)
  end
  return g
end

#list(method, filter = nil) ⇒ Object



109
110
111
112
113
114
115
116
117
118
# File 'lib/circonus.rb', line 109

def list(method,filter=nil)
  url = @url_prefix + method
  if (not filter.nil?) and filter.any?
    query_string = filter.map { |k,v| [v].flatten.map { |val|"f_#{URI::escape(k)}=#{URI::escape(val)}" } }.flatten.join('&')
    url += '?' + query_string
  end
  r, err = _rest('get',url,@headers)
  return nil,err if r.nil?
  return Yajl::Parser.parse(r)
end

#set_apitoken(apitoken) ⇒ Object



26
27
28
# File 'lib/circonus.rb', line 26

def set_apitoken(apitoken)
  @apitoken = apitoken
end

#set_appname(appname) ⇒ Object



30
31
32
# File 'lib/circonus.rb', line 30

def set_appname(appname)
  @appname = appname
end

#set_server(server) ⇒ Object



34
35
36
# File 'lib/circonus.rb', line 34

def set_server(server)
  @url_prefix = "https://#{server}/v2/"
end

#update(method, id, data) ⇒ Object



102
103
104
105
106
107
# File 'lib/circonus.rb', line 102

def update(method,id,data)
  cid = id.to_s.split('/').last
  r, err = _rest('put',@url_prefix + method + '/' + URI.escape(cid), @headers, data)
  return nil,err if r.nil?
  return Yajl::Parser.parse(r)
end