base_sampler.rb 1.49 KB
Newer Older
1
require 'logger'
2

3 4 5
module Gitlab
  module Metrics
    module Samplers
6
      class BaseSampler < Daemon
7 8 9 10 11 12 13
        # interval - The sampling interval in seconds.
        def initialize(interval)
          interval_half = interval.to_f / 2

          @interval = interval
          @interval_steps = (-interval_half..interval_half).step(0.1).to_a

14
          super()
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
        end

        def safe_sample
          sample
        rescue => e
          Rails.logger.warn("#{self.class}: #{e}, stopping")
          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
44 45 46

        private

47 48
        attr_reader :running

49 50 51 52 53
        def start_working
          @running = true
          sleep(sleep_interval)
          while running
            safe_sample
54
            sleep(sleep_interval)
55 56 57 58 59 60
          end
        end

        def stop_working
          @running = false
        end
61 62 63
      end
    end
  end
64
end