Class: Sensu::Plugins::Prometheus::Client

Inherits:
Object
  • Object
show all
Includes:
Utils::Log
Defined in:
lib/sensu/plugins/prometheus/client.rb

Overview

Prometheus http-client, able to query and validate results.

Instance Method Summary collapse

Methods included from Utils::Log

#log, log

Constructor Details

#initializeClient

Instantiates the http-client with ‘prometheus_endpoint`.



14
15
16
17
18
19
20
# File 'lib/sensu/plugins/prometheus/client.rb', line 14

def initialize
  host, port = prometheus_endpoint.split(':')
  log.info("Prometheus at '#{host}':'#{port}'")
  @client = Net::HTTP.new(host, port)
  @client.read_timeout = 3
  @client.open_timeout = 3
end

Instance Method Details

#percent_query_free(total, available) ⇒ Object

String placeholders to calculate percentage free.



45
46
47
# File 'lib/sensu/plugins/prometheus/client.rb', line 45

def percent_query_free(total, available)
  "100-((#{available}/#{total})*100)"
end

#query(prometheus_query) ⇒ Object

Execute query on Prometheus and validate payload. When successful it will return payload inner ‘result`, otherwise nil.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/sensu/plugins/prometheus/client.rb', line 24

def query(prometheus_query)
  log.debug("Prometheus Query: '#{prometheus_query}'")
  prometheus_query = CGI.escape(prometheus_query)

  begin
    get_request = Net::HTTP::Get.new("/api/v1/query?query=#{prometheus_query}")
    response_body = @client.request(get_request).body
  rescue SystemCallError => e
    log.error("Communication error with Prometheus: '#{e}'")
    raise "Can't send query to Prometheus!"
  end

  payload = JSON.parse(response_body)
  if !payload.key?('data') || !payload['data'].key?('result')
    log.error("Can't find 'data' and/or 'result' keys on query result!")
    return nil
  end
  payload['data']['result']
end