debian-mirror-gitlab/lib/gitlab/metrics/samplers/base_sampler.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

92 lines
2.3 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
2018-03-17 18:26:18 +05:30
require 'logger'
module Gitlab
module Metrics
module Samplers
class BaseSampler < Daemon
2020-06-23 00:09:42 +05:30
attr_reader :interval
2018-03-17 18:26:18 +05:30
# interval - The sampling interval in seconds.
2022-03-02 08:16:31 +05:30
# warmup - When true, takes a single sample eagerly before entering the sampling loop.
# This can be useful to ensure that all metrics files exist after `start` returns,
# since prometheus-client-mmap creates them lazily upon first access.
def initialize(interval: nil, logger: Logger.new($stdout), warmup: false, **options)
2021-03-08 18:12:59 +05:30
interval ||= ENV[interval_env_key]&.to_i
interval ||= self.class::DEFAULT_SAMPLING_INTERVAL_SECONDS
2018-03-17 18:26:18 +05:30
interval_half = interval.to_f / 2
@interval = interval
@interval_steps = (-interval_half..interval_half).step(0.1).to_a
2022-03-02 08:16:31 +05:30
@logger = logger
@warmup = warmup
super(**options)
2018-03-17 18:26:18 +05:30
end
def safe_sample
sample
2021-06-08 01:23:25 +05:30
rescue StandardError => e
2022-03-02 08:16:31 +05:30
@logger.warn("#{self.class}: #{e}, stopping")
2018-03-17 18:26:18 +05:30
stop
end
def sample
raise NotImplementedError
end
# Returns the sleep interval with a random adjustment.
#
# The random adjustment is put in place to ensure we:
#
# 1. Don't generate samples at the exact same interval every time (thus
# potentially missing anything that happens in between samples).
# 2. Don't sample data at the same interval two times in a row.
def sleep_interval
while step = @interval_steps.sample
if step != @last_step
@last_step = step
return @interval + @last_step
end
end
end
private
attr_reader :running
2021-03-08 18:12:59 +05:30
def sampler_class
self.class.name.demodulize
end
def interval_env_key
"#{sampler_class.underscore.upcase}_INTERVAL_SECONDS"
end
2018-03-17 18:26:18 +05:30
def start_working
@running = true
2019-12-21 20:55:43 +05:30
2022-03-02 08:16:31 +05:30
safe_sample if @warmup
2019-12-21 20:55:43 +05:30
true
end
def run_thread
2018-03-17 18:26:18 +05:30
sleep(sleep_interval)
while running
safe_sample
sleep(sleep_interval)
end
end
def stop_working
@running = false
end
end
end
end
end