Class: CortexClient::Metric

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(metric_name) ⇒ Metric

Returns a new instance of Metric.



4
5
6
7
8
9
10
11
12
13
# File 'lib/cortex_client/metric/metric.rb', line 4

def initialize(metric_name)
  @config = CortexClient.configuration
  @labels = []
  @samples = []
  @error = nil
  @prom_message = nil
  # a label with __name__ is required by cortex
  # to identify the metric name
  add_label(name: '__name__', value: metric_name)
end

Instance Attribute Details

#custom_error_messageObject (readonly)

Returns the value of attribute custom_error_message.



3
4
5
# File 'lib/cortex_client/metric/metric.rb', line 3

def custom_error_message
  @custom_error_message
end

#errorObject (readonly)

Returns the value of attribute error.



3
4
5
# File 'lib/cortex_client/metric/metric.rb', line 3

def error
  @error
end

#labelsObject (readonly)

Returns the value of attribute labels.



3
4
5
# File 'lib/cortex_client/metric/metric.rb', line 3

def labels
  @labels
end

#prom_messageObject (readonly)

Returns the value of attribute prom_message.



3
4
5
# File 'lib/cortex_client/metric/metric.rb', line 3

def prom_message
  @prom_message
end

#samplesObject (readonly)

Returns the value of attribute samples.



3
4
5
# File 'lib/cortex_client/metric/metric.rb', line 3

def samples
  @samples
end

Instance Method Details

#add_label(name:, value:) ⇒ Object



15
16
17
18
19
# File 'lib/cortex_client/metric/metric.rb', line 15

def add_label(name:, value:)
  label = Prometheus::Label.new(name: name, value: value)
  @labels.push(label)
  self
end

#add_sample(value: 1) ⇒ Object



21
22
23
24
25
26
# File 'lib/cortex_client/metric/metric.rb', line 21

def add_sample(value: 1)
  time = (Time.now.to_f * 1000).to_i
  sample = Prometheus::Sample.new(timestamp: time, value: value)
  @samples.push(sample)
  self
end

#pushObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/cortex_client/metric/metric.rb', line 28

def push
  if @labels.size <= 1 || @samples.size == 0
    @error = 'Use add_label and add_sample at-least once'
    return
  end

  timeseries = Prometheus::TimeSeries.new(labels: @labels, samples: @samples)
  writerequest = Prometheus::WriteRequest.new(timeseries: [].push(timeseries))
  compressed_data = Snappy.compress(Prometheus::WriteRequest.encode(writerequest))
  response = CortexClient::Http::Request.new.post(@config.metrics_push_api_path, compressed_data)
  if response.ok?
    @prom_message = response.body.to_s
    @error = nil
  else
    @prom_message = nil
    @error = response_formatter(response: response, custom_message: 'Metric couldn\'t be posted')
  end
end