Class: Cronitor::Monitor

Inherits:
Object
  • Object
show all
Defined in:
lib/cronitor/monitor.rb

Defined Under Namespace

Modules: Formats, Headers

Constant Summary collapse

PING_RETRY_THRESHOLD =
5

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, api_key: nil, env: nil) ⇒ Monitor

Returns a new instance of Monitor.



97
98
99
100
101
# File 'lib/cronitor/monitor.rb', line 97

def initialize(key, api_key: nil, env: nil)
  @key = key
  @api_key = api_key || Cronitor.api_key
  @env = env || Cronitor.environment
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



5
6
7
# File 'lib/cronitor/monitor.rb', line 5

def api_key
  @api_key
end

#api_versionObject (readonly)

Returns the value of attribute api_version.



5
6
7
# File 'lib/cronitor/monitor.rb', line 5

def api_version
  @api_version
end

#envObject (readonly)

Returns the value of attribute env.



5
6
7
# File 'lib/cronitor/monitor.rb', line 5

def env
  @env
end

#keyObject (readonly)

Returns the value of attribute key.



5
6
7
# File 'lib/cronitor/monitor.rb', line 5

def key
  @key
end

Class Method Details

.delete(key) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/cronitor/monitor.rb', line 80

def self.delete(key)
  resp = HTTParty.delete(
    "#{Cronitor.monitor_api_url}/#{key}",
    timeout: Cronitor.timeout,
    basic_auth: {
      username: Cronitor.api_key,
      password: ''
    },
    headers: Cronitor::Monitor::Headers::JSON
  )
  if resp.code != 204
    Cronitor.logger&.error("Error deleting monitor: #{key}")
    return false
  end
  true
end

.put(opts = {}) ⇒ Object



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
# File 'lib/cronitor/monitor.rb', line 27

def self.put(opts = {})
  rollback = opts[:rollback] || false
  opts.delete(:rollback)

  monitors = opts[:monitors] || [opts]

  if opts[:format] == Cronitor::Monitor::Formats::YAML
    url = "#{Cronitor.monitor_api_url}.yaml"
    monitors['rollback'] = true if rollback
    body = YAML.dump(monitors)
    headers = Cronitor::Monitor::Headers::YAML
  else
    url = Cronitor.monitor_api_url
    body = {
      monitors: monitors,
      rollback: rollback
    }.to_json
    headers = Cronitor::Monitor::Headers::JSON
  end

  resp = HTTParty.put(
    url,
    basic_auth: {
      username: Cronitor.api_key,
      password: ''
    },
    body: body,
    headers: headers,
    timeout: opts[:timeout] || Cronitor.timeout
  )

  case resp.code
  when 200
    if opts[:format] == Cronitor::Monitor::Formats::YAML
      YAML.safe_load(resp.body)
    else
      out = []
      data = JSON.parse(resp.body)

      (data['monitors'] || []).each do |md|
        m = Monitor.new(md['key'])
        m.data = Cronitor.symbolize_keys(md)
        out << m
      end
      out.length == 1 ? out[0] : out
    end
  when 400
    raise ValidationError.new(resp.body)
  else
    raise Error.new("Error connecting to Cronitor: #{resp.code}\n #{resp.body}")
  end
end

Instance Method Details

#dataObject



103
104
105
106
107
108
# File 'lib/cronitor/monitor.rb', line 103

def data
  return @data if defined?(@data)

  @data = fetch
  @data
end

#data=(data) ⇒ Object



110
111
112
# File 'lib/cronitor/monitor.rb', line 110

def data=(data)
  @data = Cronitor.symbolize_keys(data)
end

#fallback_ping_api_urlObject



186
187
188
# File 'lib/cronitor/monitor.rb', line 186

def fallback_ping_api_url
  "https://cronitor.io/p/#{api_key}/#{key}"
end

#monitor_api_urlObject



190
191
192
# File 'lib/cronitor/monitor.rb', line 190

def monitor_api_url
  "#{Cronitor.monitor_api_url}/#{key}"
end

#okObject



157
158
159
# File 'lib/cronitor/monitor.rb', line 157

def ok
  ping(state: 'ok')
end

#pause(hours = nil) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/cronitor/monitor.rb', line 161

def pause(hours = nil)
  pause_url = "#{monitor_api_url}/pause"
  pause_url += "/#{hours}" unless hours.nil?

  resp = HTTParty.get(
    pause_url,
    timeout: Cronitor.timeout,
    headers: Cronitor::Monitor::Headers::JSON,
    basic_auth: {
      username: api_key,
      password: ''
    }
  )
  puts(resp.code)
  resp.code == 200
end

#ping(params = {}) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/cronitor/monitor.rb', line 114

def ping(params = {})
  retry_count = params[:retry_count] || 0
  if api_key.nil?
    Cronitor.logger&.error('No API key detected. Set Cronitor.api_key or initialize Monitor with an api_key:')
    return false
  end

  begin
    ping_url = ping_api_url
    ping_url = fallback_ping_api_url if retry_count > (PING_RETRY_THRESHOLD / 2)

    response = HTTParty.get(
      ping_url,
      query: clean_params(params),
      timeout: Cronitor.ping_timeout,
      headers: Cronitor::Monitor::Headers::JSON,
      query_string_normalizer: lambda do |query|
        query.compact!
        metrics = query[:metric]
        query.delete(:metric)
        out = query.map { |k, v| "#{k}=#{v}" }
        out += metrics.map { |m| "metric=#{m}" } unless metrics.nil?
        out.join('&')
      end
      # query_string_normalizer for metrics. instead of metric[]=foo:1 we want metric=foo:1
    )

    if response.code != 200
      Cronitor.logger&.error("Cronitor Telemetry Error: #{response.code}")
      return false
    end
    true
  rescue StandardError => e
    # rescue instances of StandardError i.e. Timeout::Error, SocketError, etc
    Cronitor.logger&.error("Cronitor Telemetry Error: #{e}")
    return false if retry_count >= Monitor::PING_RETRY_THRESHOLD

    # apply a backoff before sending the next ping
    sleep(retry_count * 1.5 * rand)
    ping(params.merge(retry_count: retry_count + 1))
  end
end

#ping_api_urlObject



182
183
184
# File 'lib/cronitor/monitor.rb', line 182

def ping_api_url
  "https://cronitor.link/p/#{api_key}/#{key}"
end

#unpauseObject



178
179
180
# File 'lib/cronitor/monitor.rb', line 178

def unpause
  pause(0)
end