Class: Sensu::Client

Inherits:
Object
  • Object
show all
Includes:
Utilities
Defined in:
lib/sensu/client.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utilities

#deep_diff, #deep_merge, #indifferent_hash, #redact_sensitive, #retry_until_true, #testing?, #with_indifferent_access

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/sensu/client.rb', line 18

def initialize(options={})
  base = Base.new(options)
  @logger = base.logger
  @settings = base.settings
  @extensions = base.extensions
  base.setup_process
  @extensions.load_settings(@settings.to_hash)
  @timers = Array.new
  @checks_in_progress = Array.new
  @safe_mode = @settings[:client][:safe_mode] || false
end

Instance Attribute Details

#safe_modeObject

Returns the value of attribute safe_mode.



8
9
10
# File 'lib/sensu/client.rb', line 8

def safe_mode
  @safe_mode
end

Class Method Details

.run(options = {}) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/sensu/client.rb', line 10

def self.run(options={})
  client = self.new(options)
  EM::run do
    client.start
    client.trap_signals
  end
end

Instance Method Details

#complete_checks_in_progress(&block) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
# File 'lib/sensu/client.rb', line 276

def complete_checks_in_progress(&block)
  @logger.info('completing checks in progress', {
    :checks_in_progress => @checks_in_progress
  })
  retry_until_true do
    if @checks_in_progress.empty?
      block.call
      true
    end
  end
end

#execute_check_command(check) ⇒ Object



113
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
# File 'lib/sensu/client.rb', line 113

def execute_check_command(check)
  @logger.debug('attempting to execute check command', {
    :check => check
  })
  unless @checks_in_progress.include?(check[:name])
    @checks_in_progress << check[:name]
    command, unmatched_tokens = substitute_command_tokens(check)
    check[:executed] = Time.now.to_i
    if unmatched_tokens.empty?
      execute = Proc.new do
        @logger.debug('executing check command', {
          :check => check
        })
        started = Time.now.to_f
        begin
          check[:output], check[:status] = IO.popen(command, 'r', check[:timeout])
        rescue => error
          check[:output] = 'Unexpected error: ' + error.to_s
          check[:status] = 2
        end
        check[:duration] = ('%.3f' % (Time.now.to_f - started)).to_f
        check
      end
      publish = Proc.new do |check|
        publish_result(check)
        @checks_in_progress.delete(check[:name])
      end
      EM::defer(execute, publish)
    else
      check[:output] = 'Unmatched command tokens: ' + unmatched_tokens.join(', ')
      check[:status] = 3
      check[:handle] = false
      publish_result(check)
      @checks_in_progress.delete(check[:name])
    end
  else
    @logger.warn('previous check command execution in progress', {
      :check => check
    })
  end
end

#process_check(check) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/sensu/client.rb', line 168

def process_check(check)
  @logger.debug('processing check', {
    :check => check
  })
  if check.has_key?(:command)
    if @settings.check_exists?(check[:name])
      check.merge!(@settings[:checks][check[:name]])
      execute_check_command(check)
    elsif @safe_mode
      check[:output] = 'Check is not locally defined (safe mode)'
      check[:status] = 3
      check[:handle] = false
      check[:executed] = Time.now.to_i
      publish_result(check)
    else
      execute_check_command(check)
    end
  else
    if @extensions.check_exists?(check[:name])
      run_check_extension(check)
    else
      @logger.warn('unknown check extension', {
        :check => check
      })
    end
  end
end

#publish_keepaliveObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/sensu/client.rb', line 50

def publish_keepalive
  keepalive = @settings[:client].merge(:timestamp => Time.now.to_i)
  payload = redact_sensitive(keepalive, @settings[:client][:redact])
  @logger.debug('publishing keepalive', {
    :payload => payload
  })
  begin
    @amq.direct('keepalives').publish(Oj.dump(payload))
  rescue AMQ::Client::ConnectionClosedError => error
    @logger.error('failed to publish keepalive', {
      :payload => payload,
      :error => error.to_s
    })
  end
end

#publish_result(check) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/sensu/client.rb', line 76

def publish_result(check)
  payload = {
    :client => @settings[:client][:name],
    :check => check
  }
  @logger.info('publishing check result', {
    :payload => payload
  })
  begin
    @amq.direct('results').publish(Oj.dump(payload))
  rescue AMQ::Client::ConnectionClosedError => error
    @logger.error('failed to publish check result', {
      :payload => payload,
      :error => error.to_s
    })
  end
end

#run_check_extension(check) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/sensu/client.rb', line 155

def run_check_extension(check)
  @logger.debug('attempting to run check extension', {
    :check => check
  })
  check[:executed] = Time.now.to_i
  extension = @extensions[:checks][check[:name]]
  extension.safe_run do |output, status|
    check[:output] = output
    check[:status] = status
    publish_result(check)
  end
end

#schedule_checks(checks) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/sensu/client.rb', line 216

def schedule_checks(checks)
  check_count = 0
  stagger = testing? ? 0 : 2
  checks.each do |check|
    check_count += 1
    scheduling_delay = stagger * check_count % 30
    @timers << EM::Timer.new(scheduling_delay) do
      interval = testing? ? 0.5 : check[:interval]
      @timers << EM::PeriodicTimer.new(interval) do
        if @rabbitmq.connected?
          check[:issued] = Time.now.to_i
          process_check(check)
        end
      end
    end
  end
end

#setup_keepalivesObject



66
67
68
69
70
71
72
73
74
# File 'lib/sensu/client.rb', line 66

def setup_keepalives
  @logger.debug('scheduling keepalives')
  publish_keepalive
  @timers << EM::PeriodicTimer.new(20) do
    if @rabbitmq.connected?
      publish_keepalive
    end
  end
end

#setup_rabbitmqObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/sensu/client.rb', line 30

def setup_rabbitmq
  @logger.debug('connecting to rabbitmq', {
    :settings => @settings[:rabbitmq]
  })
  @rabbitmq = RabbitMQ.connect(@settings[:rabbitmq])
  @rabbitmq.on_error do |error|
    @logger.fatal('rabbitmq connection error', {
      :error => error.to_s
    })
    stop
  end
  @rabbitmq.before_reconnect do
    @logger.warn('reconnecting to rabbitmq')
  end
  @rabbitmq.after_reconnect do
    @logger.info('reconnected to rabbitmq')
  end
  @amq = @rabbitmq.channel
end

#setup_socketsObject



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/sensu/client.rb', line 245

def setup_sockets
  options = @settings[:client][:socket] || Hash.new
  options[:bind] ||= '127.0.0.1'
  options[:port] ||= 3030
  @logger.debug('binding client tcp and udp sockets', {
    :options => options
  })
  EM::start_server(options[:bind], options[:port], Socket) do |socket|
    socket.logger = @logger
    socket.settings = @settings
    socket.amq = @amq
  end
  EM::open_datagram_socket(options[:bind], options[:port], Socket) do |socket|
    socket.logger = @logger
    socket.settings = @settings
    socket.amq = @amq
    socket.reply = false
  end
end

#setup_standaloneObject



234
235
236
237
238
239
240
241
242
243
# File 'lib/sensu/client.rb', line 234

def setup_standalone
  @logger.debug('scheduling standalone checks')
  standard_checks = @settings.checks.select do |check|
    check[:standalone]
  end
  extension_checks = @extensions.checks.select do |check|
    check[:standalone] && check[:interval].is_a?(Integer)
  end
  schedule_checks(standard_checks + extension_checks)
end

#setup_subscriptionsObject



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/sensu/client.rb', line 196

def setup_subscriptions
  @logger.debug('subscribing to client subscriptions')
  @check_request_queue = @amq.queue('', :auto_delete => true) do |queue|
    @settings[:client][:subscriptions].each do |exchange_name|
      @logger.debug('binding queue to exchange', {
        :queue_name => queue.name,
        :exchange_name => exchange_name
      })
      queue.bind(@amq.fanout(exchange_name))
    end
    queue.subscribe do |payload|
      check = Oj.load(payload)
      @logger.info('received check request', {
        :check => check
      })
      process_check(check)
    end
  end
end

#startObject



288
289
290
291
292
293
294
# File 'lib/sensu/client.rb', line 288

def start
  setup_rabbitmq
  setup_keepalives
  setup_subscriptions
  setup_standalone
  setup_sockets
end

#stopObject



296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/sensu/client.rb', line 296

def stop
  @logger.warn('stopping')
  @timers.each do |timer|
    timer.cancel
  end
  unsubscribe
  complete_checks_in_progress do
    @extensions.stop_all do
      @rabbitmq.close
      @logger.warn('stopping reactor')
      EM::stop_event_loop
    end
  end
end

#substitute_command_tokens(check) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/sensu/client.rb', line 94

def substitute_command_tokens(check)
  unmatched_tokens = Array.new
  substituted = check[:command].gsub(/:::(.*?):::/) do
    token, default = $1.to_s.split('|', -1)
    matched = token.split('.').inject(@settings[:client]) do |client, attribute|
      if client[attribute].nil?
        default.nil? ? break : default
      else
        client[attribute]
      end
    end
    if matched.nil?
      unmatched_tokens << token
    end
    matched
  end
  [substituted, unmatched_tokens]
end

#trap_signalsObject



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/sensu/client.rb', line 311

def trap_signals
  @signals = Array.new
  STOP_SIGNALS.each do |signal|
    Signal.trap(signal) do
      @signals << signal
    end
  end
  EM::PeriodicTimer.new(1) do
    signal = @signals.shift
    if STOP_SIGNALS.include?(signal)
      @logger.warn('received signal', {
        :signal => signal
      })
      stop
    end
  end
end

#unsubscribeObject



265
266
267
268
269
270
271
272
273
274
# File 'lib/sensu/client.rb', line 265

def unsubscribe
  @logger.warn('unsubscribing from client subscriptions')
  if @rabbitmq.connected?
    @check_request_queue.unsubscribe
  else
    @check_request_queue.before_recovery do
      @check_request_queue.unsubscribe
    end
  end
end