summaryrefslogtreecommitdiff
path: root/lib/gitlab/memory/watchdog/monitor_state.rb
blob: bb083fedf2ccc0b7521339649dbe15ff343b44e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# frozen_string_literal: true

module Gitlab
  module Memory
    class Watchdog
      class MonitorState
        class Result
          attr_reader :payload, :monitor_name

          def initialize(strikes_exceeded:, threshold_violated:, monitor_name:, payload:)
            @strikes_exceeded = strikes_exceeded
            @threshold_violated = threshold_violated
            @monitor_name = monitor_name.to_s.to_sym
            @payload = payload
          end

          def strikes_exceeded?
            @strikes_exceeded
          end

          def threshold_violated?
            @threshold_violated
          end
        end

        def initialize(monitor, max_strikes:, monitor_name:)
          @monitor = monitor
          @max_strikes = max_strikes
          @monitor_name = monitor_name
          @strikes = 0
        end

        def call
          reset_strikes if strikes_exceeded?

          monitor_result = @monitor.call

          if monitor_result[:threshold_violated]
            issue_strike
          else
            reset_strikes
          end

          build_result(monitor_result)
        end

        private

        def build_result(monitor_result)
          Result.new(
            strikes_exceeded: strikes_exceeded?,
            monitor_name: @monitor_name,
            threshold_violated: monitor_result[:threshold_violated],
            payload: payload.merge(monitor_result[:payload]))
        end

        def payload
          {
            memwd_max_strikes: @max_strikes,
            memwd_cur_strikes: @strikes
          }
        end

        def strikes_exceeded?
          @strikes > @max_strikes
        end

        def issue_strike
          @strikes += 1
        end

        def reset_strikes
          @strikes = 0
        end
      end
    end
  end
end