Class: Librato::Metrics::Client

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/librato/metrics/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#api_keyObject

Returns the value of attribute api_key.



9
10
11
# File 'lib/librato/metrics/client.rb', line 9

def api_key
  @api_key
end

#emailObject

Returns the value of attribute email.



9
10
11
# File 'lib/librato/metrics/client.rb', line 9

def email
  @email
end

Instance Method Details

#agent_identifier(*args) ⇒ Object

Provide agent identifier for the developer program. See: support.metrics.librato.com/knowledgebase/articles/53548-developer-program

Examples:

Have the gem build your identifier string

Librato::Metrics.agent_identifier 'flintstone', '0.5', 'fred'

Provide your own identifier string

Librato::Metrics.agent_identifier 'flintstone/0.5 (dev_id:fred)'

Remove identifier string

Librato::Metrics.agent_identifier ''


22
23
24
25
26
27
28
29
30
31
# File 'lib/librato/metrics/client.rb', line 22

def agent_identifier(*args)
  if args.length == 1
    @agent_identifier = args.first
  elsif args.length == 3
    @agent_identifier = "#{args[0]}/#{args[1]} (dev_id:#{args[2]})"
  elsif ![0,1,3].include?(args.length)
    raise ArgumentError, 'invalid arguments, see method documentation'
  end
  @agent_identifier ||= ''
end

#annotatorObject



33
34
35
# File 'lib/librato/metrics/client.rb', line 33

def annotator
  @annotator ||= Annotator.new(:client => self)
end

#api_endpointString

API endpoint to use for queries and direct persistence.

Returns:

  • (String)

    api_endpoint



41
42
43
# File 'lib/librato/metrics/client.rb', line 41

def api_endpoint
  @api_endpoint ||= 'https://metrics-api.librato.com'
end

#api_endpoint=(endpoint) ⇒ Object

Set API endpoint for use with queries and direct persistence. Generally you should not need to set this as it will default to the current Librato Metrics endpoint.



50
51
52
# File 'lib/librato/metrics/client.rb', line 50

def api_endpoint=(endpoint)
  @api_endpoint = endpoint
end

#authenticate(email, api_key) ⇒ Object

Authenticate for direct persistence

Parameters:

  • email (String)
  • api_key (String)


58
59
60
61
# File 'lib/librato/metrics/client.rb', line 58

def authenticate(email, api_key)
  flush_authentication
  self.email, self.api_key = email, api_key
end

#connectionObject

Current connection object

Raises:



65
66
67
68
69
70
# File 'lib/librato/metrics/client.rb', line 65

def connection
  # prevent successful creation if no credentials set
  raise CredentialsMissing unless (self.email and self.api_key)
  @connection ||= Connection.new(:client => self, :api_endpoint => api_endpoint,
                                 :adapter => faraday_adapter)
end

#create_snapshot(options = {}) ⇒ Object

Create a snapshot of an instrument

Examples:

Take a snapshot of the instrument at metrics-api.librato.com/v1/instruments/42 using a

duration of 3 hours and ending at now.
Librato::Metrics.snapshot(subject: {instrument: {href: "https://metrics-api.librato.com/v1/instruments/42"}},
                          duration: 3.hours, end_time: Time.now)

Parameters:

  • Hash

    options Params for the snapshot



425
426
427
428
429
430
431
432
# File 'lib/librato/metrics/client.rb', line 425

def create_snapshot(options = {})
  url = "snapshots"
  response = connection.post do |request|
    request.url connection.build_url(url)
    request.body = SmartJSON.write(options)
  end
  parsed = SmartJSON.read(response.body)
end

#custom_user_agentObject



81
82
83
# File 'lib/librato/metrics/client.rb', line 81

def custom_user_agent
  @user_agent
end

#custom_user_agent=(agent) ⇒ Object

Overrride user agent for this client’s connections. If you are trying to specify an agent identifier for developer program, see #agent_identifier.



76
77
78
79
# File 'lib/librato/metrics/client.rb', line 76

def custom_user_agent=(agent)
  @user_agent = agent
  @connection = nil
end

#delete(*metric_names) ⇒ Object

Deprecated.

Use #delete_metrics instead

Completely delete metrics with the given names. Be careful with this, this is instant and permanent.



116
# File 'lib/librato/metrics/client.rb', line 116

def delete(*metric_names); delete_metrics(*metric_names); end

#delete_metrics(*metric_names) ⇒ Object

Completely delete metrics with the given names. Be careful with this, this is instant and permanent.

Examples:

Delete metric ‘temperature’

Librato::Metrics.delete_metrics :temperature

Delete metrics ‘foo’ and ‘bar’

Librato::Metrics.delete_metrics :foo, :bar

Delete metrics that start with ‘foo’ except ‘foobar’

Librato::Metrics.delete_metrics :names => 'foo*', :exclude => ['foobar']

Raises:



97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/librato/metrics/client.rb', line 97

def delete_metrics(*metric_names)
  raise(NoMetricsProvided, 'Metric name missing.') if metric_names.empty?
  if metric_names[0].respond_to?(:keys) # hash form
    params = metric_names[0]
  else
    params = { :names => metric_names.map(&:to_s) }
  end
  connection.delete do |request|
    request.url connection.build_url("metrics")
    request.body = SmartJSON.write(params)
  end
  # expects 204, middleware will raise exception otherwise.
  true
end

#faraday_adapterObject

Return current adapter this client will use. Defaults to Metrics.faraday_adapter if set, otherwise Faraday.default_adapter



121
122
123
# File 'lib/librato/metrics/client.rb', line 121

def faraday_adapter
  @faraday_adapter ||= default_faraday_adapter
end

#faraday_adapter=(adapter) ⇒ Object

Set faraday adapter this client will use



126
127
128
# File 'lib/librato/metrics/client.rb', line 126

def faraday_adapter=(adapter)
  @faraday_adapter = adapter
end

#fetch(metric, options = {}) ⇒ Object

Deprecated.

Use #get_metric or #get_measurements instead.

Query metric data

A full list of query parameters can be found in the API documentation: http://dev.librato.com/v1/get/metrics/:name

Examples:

Get attributes for a metric

attrs = Librato::Metrics.fetch :temperature

Get 20 most recent data points for metric

data = Librato::Metrics.fetch :temperature, :count => 20

Get 20 most recent data points for a specific source

data = Librato::Metrics.fetch :temperature, :count => 20,
                              :source => 'app1'

Get the 20 most recent 15 minute data point rollups

data = Librato::Metrics.fetch :temperature, :count => 20,
                              :resolution => 900

Get data points for the last hour

data = Librato::Metrics.fetch :start_time => Time.now-3600

Get 15 min data points from two hours to an hour ago

data = Librato::Metrics.fetch :start_time => Time.now-7200,
                              :end_time => Time.now-3600,
                              :resolution => 900

Parameters:

  • metric (Symbol|String)

    Metric name

  • options (Hash) (defaults to: {})

    Query options



161
162
163
164
# File 'lib/librato/metrics/client.rb', line 161

def fetch(metric, options={})
  metric = get_metric(metric, options)
  options.empty? ? metric : metric["measurements"]
end

#flush_authenticationObject

Purge current credentials and connection.



256
257
258
259
260
# File 'lib/librato/metrics/client.rb', line 256

def flush_authentication
  self.email = nil
  self.api_key = nil
  @connection = nil
end

#get_composite(definition, options = {}) ⇒ Object

Retrieve measurements for a given composite metric definition. :start_time and :resolution are required options, :end_time is optional.

Examples:

Get 5m moving average of ‘foo’

measurements = Librato::Metrics.get_composite
  'moving_average(mean(series("foo", "*"), {size: "5"}))',
  :start_time => Time.now.to_i - 60*60, :resolution => 300

Parameters:

  • definition (String)

    Composite definition

  • options (hash) (defaults to: {})

    Query options



177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/librato/metrics/client.rb', line 177

def get_composite(definition, options={})
  unless options[:start_time] && options[:resolution]
    raise "You must provide a :start_time and :resolution"
  end
  query = options.dup
  query[:compose] = definition
  url = connection.build_url("metrics", query)
  response = connection.get(url)
  parsed = SmartJSON.read(response.body)
  # TODO: pagination support
  parsed
end

#get_measurements(metric_name, options = {}) ⇒ Object

Retrieve data points for a specific metric

A full list of query parameters can be found in the API documentation: http://dev.librato.com/v1/get/metrics/:name

Examples:

Get 20 most recent data points for metric

data = Librato::Metrics.get_measurements :temperature, :count => 20

Get 20 most recent data points for a specific source

data = Librato::Metrics.get_measurements :temperature, :count => 20,
                                         :source => 'app1'

Get the 20 most recent 15 minute data point rollups

data = Librato::Metrics.get_measurements :temperature, :count => 20,
                                         :resolution => 900

Get data points for the last hour

data = Librato::Metrics.get_measurements :start_time => Time.now-3600

Get 15 min data points from two hours to an hour ago

data = Librato::Metrics.get_measurements :start_time => Time.now-7200,
                                         :end_time => Time.now-3600,
                                         :resolution => 900

Parameters:

  • metric_name (Symbol|String)

    Metric name

  • options (Hash) (defaults to: {})

    Query options

Raises:

  • (ArgumentError)


249
250
251
252
# File 'lib/librato/metrics/client.rb', line 249

def get_measurements(metric_name, options = {})
  raise ArgumentError, "you must provide at least a :start_time or :count" if options.empty?
  get_metric(metric_name, options)["measurements"]
end

#get_metric(name, options = {}) ⇒ Object

Retrieve a specific metric by name, optionally including data points

A full list of query parameters can be found in the API documentation: http://dev.librato.com/v1/get/metrics/:name

Examples:

Get attributes for a metric

metric = Librato::Metrics.get_metric :temperature

Get a metric and its 20 most recent data points

metric = Librato::Metrics.get_metric :temperature, :count => 20
metric['measurements'] # => {...}

Parameters:

  • name (Symbol|String)

    Metric name

  • options (Hash) (defaults to: {})

    Query options



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/librato/metrics/client.rb', line 204

def get_metric(name, options = {})
  query = options.dup
  if query[:start_time].respond_to?(:year)
    query[:start_time] = query[:start_time].to_i
  end
  if query[:end_time].respond_to?(:year)
    query[:end_time] = query[:end_time].to_i
  end
  unless query.empty?
    query[:resolution] ||= 1
  end
  # expects 200
  url = connection.build_url("metrics/#{name}", query)
  response = connection.get(url)
  parsed = SmartJSON.read(response.body)
  # TODO: pagination support
  parsed
end

#get_snapshot(id) ⇒ Object

Retrive a snapshot, to check its progress or find its image_href

Examples:

Get a snapshot identified by 42

Librato::Metrics.get_snapshot 42

Parameters:

  • id (Integer|String)


440
441
442
443
444
# File 'lib/librato/metrics/client.rb', line 440

def get_snapshot(id)
  url = "snapshots/#{id}"
  response = connection.get(url)
  parsed = SmartJSON.read(response.body)
end

#get_source(name) ⇒ Object

Retrieve a single source by name. See dev.librato.com/v1/get/sources/:name

Examples:

Get the source for a particular EC2 instance from Cloudwatch

Librato::Metrics.source "us-east-1b.i-f1bc8c9c"

Parameters:

  • String

    name



393
394
395
396
397
# File 'lib/librato/metrics/client.rb', line 393

def get_source(name)
  url = connection.build_url("sources/#{name}")
  response = connection.get(url)
  parsed = SmartJSON.read(response.body)
end

#list(options = {}) ⇒ Object

Deprecated.

Use #metrics instead

List currently existing metrics



282
# File 'lib/librato/metrics/client.rb', line 282

def list(options={}); metrics(options); end

#metrics(options = {}) ⇒ Object

List currently existing metrics

Examples:

List all metrics

Librato::Metrics.metrics

List metrics with ‘foo’ in the name

Librato::Metrics.metrics :name => 'foo'

Parameters:

  • options (Hash) (defaults to: {})


271
272
273
274
275
276
277
# File 'lib/librato/metrics/client.rb', line 271

def metrics(options={})
  query = {}
  query[:name] = options[:name] if options[:name]
  offset = 0
  path = "metrics"
  Collection.paginated_metrics(connection, path, query)
end

#new_queue(options = {}) ⇒ Queue

Create a new queue which uses this client.

Returns:



287
288
289
290
# File 'lib/librato/metrics/client.rb', line 287

def new_queue(options={})
  options[:client] = self
  Queue.new(options)
end

#persistenceSymbol

Persistence type to use when saving metrics. Default is :direct.

Returns:

  • (Symbol)


296
297
298
# File 'lib/librato/metrics/client.rb', line 296

def persistence
  @persistence ||= :direct
end

#persistence=(persist_method) ⇒ Object

Set persistence type to use when saving metrics.

Parameters:

  • persist_method (Symbol)


303
304
305
# File 'lib/librato/metrics/client.rb', line 303

def persistence=(persist_method)
  @persistence = persist_method
end

#persisterObject

Current persister object.



308
309
310
# File 'lib/librato/metrics/client.rb', line 308

def persister
  @queue ? @queue.persister : nil
end

#sources(filter = {}) ⇒ Object

List sources, optionally limited by a name. See dev.librato.com/v1/sources and dev.librato.com/v1/get/sources

Examples:

Get sources matching “production”

Librato::Metrics.sources name: "production"

Parameters:

  • filter (Hash) (defaults to: {})


381
382
383
384
385
# File 'lib/librato/metrics/client.rb', line 381

def sources(filter = {})
  query = filter[:name] if filter.has_key?(:name)
  path = "sources"
  Collection.paginated_collection("sources", connection, path, query)
end

#submit(args) ⇒ Object

Submit all queued metrics.



314
315
316
317
318
319
320
# File 'lib/librato/metrics/client.rb', line 314

def submit(args)
  @queue ||= Queue.new(:client => self,
                       :skip_measurement_times => true,
                       :clear_failures => true)
  @queue.add args
  @queue.submit
end

#update_metric(metric, options = {}) ⇒ Object Also known as: update

Update a single metric with new attributes.

Examples:

Update metric ‘temperature’

Librato::Metrics.update_metric :temperature, :period => 15, :attributes => { :color => 'F00' }

Update metric ‘humidity’, creating it if it doesn’t exist

Librato::Metrics.update_metric 'humidity', :type => :gauge, :period => 60, :display_name => 'Humidity'


330
331
332
333
334
335
336
# File 'lib/librato/metrics/client.rb', line 330

def update_metric(metric, options = {})
  url = "metrics/#{metric}"
  connection.put do |request|
    request.url connection.build_url(url)
    request.body = SmartJSON.write(options)
  end
end

#update_metrics(metrics) ⇒ Object

Update multiple metrics.

Examples:

Update multiple metrics by name

Librato::Metrics.update_metrics :names => ["foo", "bar"], :period => 60

Update all metrics that start with ‘foo’ that aren’t ‘foobar’

Librato::Metrics.update_metrics :names => 'foo*', :exclude => ['foobar'], :display_min => 0


346
347
348
349
350
351
352
# File 'lib/librato/metrics/client.rb', line 346

def update_metrics(metrics)
  url = "metrics" # update multiple metrics
  connection.put do |request|
    request.url connection.build_url(url)
    request.body = SmartJSON.write(metrics)
  end
end

#update_source(name, options = {}) ⇒ Object

Update a source by name. See dev.librato.com/v1/get/sources/:name

Examples:

Update the source display name for a particular EC2 instance from Cloudwatch

Librato::Metrics.source "us-east-1b.i-f1bc8c9c", display_name: "Production Web 1"

Parameters:

  • String

    name

  • Hash

    options



406
407
408
409
410
411
412
# File 'lib/librato/metrics/client.rb', line 406

def update_source(name, options = {})
  url = "sources/#{name}"
  connection.put do |request|
    request.url connection.build_url(url)
    request.body = SmartJSON.write(options)
  end
end