Class: Sensu::Server

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utilities

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

Constructor Details

#initialize(options = {}) ⇒ Server

Returns a new instance of Server.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/sensu/server.rb', line 20

def initialize(options={})
  base = Base.new(options)
  @logger = base.logger
  @settings = base.settings
  @extensions = base.extensions
  base.setup_process
  @timers = Array.new
  @master_timers = Array.new
  @handlers_in_progress_count = 0
  @is_master = false
end

Instance Attribute Details

#is_masterObject (readonly)

Returns the value of attribute is_master.



10
11
12
# File 'lib/sensu/server.rb', line 10

def is_master
  @is_master
end

Class Method Details

.run(options = {}) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/sensu/server.rb', line 12

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

Instance Method Details

#action_subdued?(check, handler = nil) ⇒ Boolean

Returns:

  • (Boolean)


98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
# File 'lib/sensu/server.rb', line 98

def action_subdued?(check, handler=nil)
  subdue = false
  subdue_at = handler ? 'handler' : 'publisher'
  conditions = Array.new
  if check[:subdue]
    conditions << check[:subdue]
  end
  if handler && handler[:subdue]
    conditions << handler[:subdue]
  end
  conditions.each do |condition|
    if condition.has_key?(:begin) && condition.has_key?(:end)
      begin_time = Time.parse(condition[:begin])
      end_time = Time.parse(condition[:end])
      if end_time < begin_time
        if Time.now < end_time
          begin_time = Time.parse('12:00:00 AM')
        else
          end_time = Time.parse('11:59:59 PM')
        end
      end
      if Time.now >= begin_time && Time.now <= end_time
        subdue = true
      end
    end
    if condition.has_key?(:days)
      days = condition[:days].map(&:downcase)
      if days.include?(Time.now.strftime('%A').downcase)
        subdue = true
      end
    end
    if subdue && condition.has_key?(:exceptions)
      subdue = condition[:exceptions].none? do |exception|
        Time.now >= Time.parse(exception[:begin]) && Time.now <= Time.parse(exception[:end])
      end
    end
    if subdue
      if subdue_at == (condition[:at] || 'handler')
        break
      else
        subdue = false
      end
    end
  end
  subdue
end

#aggregate_result(result) ⇒ Object



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/sensu/server.rb', line 390

def aggregate_result(result)
  @logger.debug('adding result to aggregate', {
    :result => result
  })
  check = result[:check]
  result_set = check[:name] + ':' + check[:issued].to_s
  @redis.hset('aggregation:' + result_set, result[:client], Oj.dump(
    :output => check[:output],
    :status => check[:status]
  )) do
    SEVERITIES.each do |severity|
      @redis.hsetnx('aggregate:' + result_set, severity, 0)
    end
    severity = (SEVERITIES[check[:status]] || 'unknown')
    @redis.hincrby('aggregate:' + result_set, severity, 1) do
      @redis.hincrby('aggregate:' + result_set, 'total', 1) do
        @redis.sadd('aggregates:' + check[:name], check[:issued]) do
          @redis.sadd('aggregates', check[:name])
        end
      end
    end
  end
end

#bootstrapObject



773
774
775
776
777
778
# File 'lib/sensu/server.rb', line 773

def bootstrap
  setup_keepalives
  setup_results
  setup_master_monitor
  @state = :running
end

#complete_handlers_in_progress(&block) ⇒ Object



761
762
763
764
765
766
767
768
769
770
771
# File 'lib/sensu/server.rb', line 761

def complete_handlers_in_progress(&block)
  @logger.info('completing handlers in progress', {
    :handlers_in_progress_count => @handlers_in_progress_count
  })
  retry_until_true do
    if @handlers_in_progress_count == 0
      block.call
      true
    end
  end
end

#derive_handlers(handler_list) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/sensu/server.rb', line 178

def derive_handlers(handler_list)
  handler_list.inject(Array.new) do |handlers, handler_name|
    if @settings.handler_exists?(handler_name)
      handler = @settings[:handlers][handler_name].merge(:name => handler_name)
      if handler[:type] == 'set'
        handlers = handlers + derive_handlers(handler[:handlers])
      else
        handlers << handler
      end
    elsif @extensions.handler_exists?(handler_name)
      handlers << @extensions[:handlers][handler_name]
    else
      @logger.error('unknown handler', {
        :handler_name => handler_name
      })
    end
    handlers.uniq
  end
end

#determine_stale_clientsObject



584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'lib/sensu/server.rb', line 584

def determine_stale_clients
  @logger.info('determining stale clients')
  @redis.smembers('clients') do |clients|
    clients.each do |client_name|
      @redis.get('client:' + client_name) do |client_json|
        unless client_json.nil?
          client = Oj.load(client_json)
          check = {
            :name => 'keepalive',
            :issued => Time.now.to_i,
            :executed => Time.now.to_i
          }
          thresholds = {
            :warning => 120,
            :critical => 180
          }
          if client.has_key?(:keepalive)
            if client[:keepalive].has_key?(:handler) || client[:keepalive].has_key?(:handlers)
              check[:handlers] = Array(client[:keepalive][:handlers] || client[:keepalive][:handler])
            end
            if client[:keepalive].has_key?(:thresholds)
              thresholds.merge!(client[:keepalive][:thresholds])
            end
          end
          time_since_last_keepalive = Time.now.to_i - client[:timestamp]
          case
          when time_since_last_keepalive >= thresholds[:critical]
            check[:output] = 'No keep-alive sent from client in over '
            check[:output] << thresholds[:critical].to_s + ' seconds'
            check[:status] = 2
          when time_since_last_keepalive >= thresholds[:warning]
            check[:output] = 'No keep-alive sent from client in over '
            check[:output] << thresholds[:warning].to_s + ' seconds'
            check[:status] = 1
          else
            check[:output] = 'Keep-alive sent from client less than '
            check[:output] << thresholds[:warning].to_s + ' seconds ago'
            check[:status] = 0
          end
          publish_result(client, check)
        end
      end
    end
  end
end

#event_filtered?(filter_name, event) ⇒ Boolean

Returns:

  • (Boolean)


165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/sensu/server.rb', line 165

def event_filtered?(filter_name, event)
  if @settings.filter_exists?(filter_name)
    filter = @settings[:filters][filter_name]
    matched = filter_attributes_match?(filter[:attributes], event)
    filter[:negate] ? matched : !matched
  else
    @logger.error('unknown filter', {
      :filter_name => filter_name
    })
    false
  end
end

#event_handlers(event) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/sensu/server.rb', line 198

def event_handlers(event)
  handler_list = Array((event[:check][:handlers] || event[:check][:handler]) || 'default')
  handlers = derive_handlers(handler_list)
  event_severity = SEVERITIES[event[:check][:status]] || 'unknown'
  handlers.select do |handler|
    if event[:action] == :flapping && !handler[:handle_flapping]
      @logger.info('handler does not handle flapping events', {
        :event => event,
        :handler => handler
      })
      next
    end
    if action_subdued?(event[:check], handler)
      @logger.info('action is subdued', {
        :event => event,
        :handler => handler
      })
      next
    end
    if handler.has_key?(:severities) && !handler[:severities].include?(event_severity)
      unless event[:action] == :resolve
        @logger.debug('handler does not handle event severity', {
          :event => event,
          :handler => handler
        })
        next
      end
    end
    if handler.has_key?(:filters) || handler.has_key?(:filter)
      filter_list = Array(handler[:filters] || handler[:filter])
      filtered = filter_list.any? do |filter_name|
        event_filtered?(filter_name, event)
      end
      if filtered
        @logger.info('event filtered for handler', {
          :event => event,
          :handler => handler
        })
        next
      end
    end
    true
  end
end

#execute_command(command, data = nil, on_error = nil, &block) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/sensu/server.rb', line 243

def execute_command(command, data=nil, on_error=nil, &block)
  on_error ||= Proc.new do |error|
    @logger.error('failed to execute command', {
      :command => command,
      :data => data,
      :error => error.to_s
    })
  end
  execute = Proc.new do
    begin
      output, status = IO.popen(command, 'r+') do |child|
        unless data.nil?
          child.write(data.to_s)
        end
        child.close_write
      end
      [true, output, status]
    rescue => error
      on_error.call(error)
      [false, nil, nil]
    end
  end
  complete = Proc.new do |success, output, status|
    if success
      block.call(output, status)
    end
  end
  EM::defer(execute, complete)
end

#filter_attributes_match?(hash_one, hash_two) ⇒ Boolean

Returns:

  • (Boolean)


145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/sensu/server.rb', line 145

def filter_attributes_match?(hash_one, hash_two)
  hash_one.keys.all? do |key|
    case
    when hash_one[key] == hash_two[key]
      true
    when hash_one[key].is_a?(Hash) && hash_two[key].is_a?(Hash)
      filter_attributes_match?(hash_one[key], hash_two[key])
    when hash_one[key].is_a?(String) && hash_one[key].start_with?('eval:')
      begin
        expression = hash_one[key].gsub(/^eval:(\s+)?/, '')
        !!Sandbox.eval(expression, hash_two[key])
      rescue
        false
      end
    else
      false
    end
  end
end

#handle_event(event) ⇒ Object



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/sensu/server.rb', line 316

def handle_event(event)
  handlers = event_handlers(event)
  handlers.each do |handler|
    log_level = event[:check][:type] == 'metric' ? :debug : :info
    @logger.send(log_level, 'handling event', {
      :event => event,
      :handler => handler
    })
    @handlers_in_progress_count += 1
    on_error = Proc.new do |error|
      @logger.error('handler error', {
        :event => event,
        :handler => handler,
        :error => error.to_s
      })
      @handlers_in_progress_count -= 1
    end
    mutate_event_data(handler[:mutator], event) do |event_data|
      case handler[:type]
      when 'pipe'
        execute_command(handler[:command], event_data, on_error) do |output, status|
          output.split(/\n+/).each do |line|
            @logger.info(line)
          end
          @handlers_in_progress_count -= 1
        end
      when 'tcp'
        begin
          EM::connect(handler[:socket][:host], handler[:socket][:port], SocketHandler) do |socket|
            socket.on_success = Proc.new do
              @handlers_in_progress_count -= 1
            end
            socket.on_error = on_error
            timeout = handler[:socket][:timeout] || 10
            socket.pending_connect_timeout = timeout
            socket.comm_inactivity_timeout = timeout
            socket.send_data(event_data.to_s)
            socket.close_connection_after_writing
          end
        rescue => error
          on_error.call(error)
        end
      when 'udp'
        begin
          EM::open_datagram_socket('127.0.0.1', 0, nil) do |socket|
            socket.send_datagram(event_data.to_s, handler[:socket][:host], handler[:socket][:port])
            socket.close_connection_after_writing
            @handlers_in_progress_count -= 1
          end
        rescue => error
          on_error.call(error)
        end
      when 'amqp'
        exchange_name = handler[:exchange][:name]
        exchange_type = handler[:exchange].has_key?(:type) ? handler[:exchange][:type].to_sym : :direct
        exchange_options = handler[:exchange].reject do |key, value|
          [:name, :type].include?(key)
        end
        unless event_data.empty?
          @amq.method(exchange_type).call(exchange_name, exchange_options).publish(event_data)
        end
        @handlers_in_progress_count -= 1
      when 'extension'
        handler.run(event_data, @settings.to_hash) do |output, status|
          output.split(/\n+/).each do |line|
            @logger.info(line)
          end
          @handlers_in_progress_count -= 1
        end
      end
    end
  end
end

#master_dutiesObject



672
673
674
675
676
# File 'lib/sensu/server.rb', line 672

def master_duties
  setup_publisher
  setup_client_monitor
  setup_aggregation_pruner
end

#mutate_event_data(mutator_name, event, &block) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/sensu/server.rb', line 273

def mutate_event_data(mutator_name, event, &block)
  case
  when mutator_name.nil?
    block.call(Oj.dump(event))
  when @settings.mutator_exists?(mutator_name)
    mutator = @settings[:mutators][mutator_name]
    on_error = Proc.new do |error|
      @logger.error('mutator error', {
        :event => event,
        :mutator => mutator,
        :error => error.to_s
      })
      @handlers_in_progress_count -= 1
    end
    execute_command(mutator[:command], Oj.dump(event), on_error) do |output, status|
      if status == 0
        block.call(output)
      else
        on_error.call('non-zero exit status (' + status.to_s + '): ' + output)
      end
    end
  when @extensions.mutator_exists?(mutator_name)
    extension = @extensions[:mutators][mutator_name]
    extension.run(event, @settings.to_hash) do |output, status|
      if status == 0
        block.call(output)
      else
        @logger.error('mutator error', {
          :event => event,
          :extension => extension.definition,
          :error => 'non-zero exit status (' + status.to_s + '): ' + output
        })
        @handlers_in_progress_count -= 1
      end
    end
  else
    @logger.error('unknown mutator', {
      :mutator_name => mutator_name
    })
    @handlers_in_progress_count -= 1
  end
end

#pause(&block) ⇒ Object



786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
# File 'lib/sensu/server.rb', line 786

def pause(&block)
  unless @state == :pausing || @state == :paused
    @state = :pausing
    @timers.each do |timer|
      timer.cancel
    end
    @timers.clear
    unsubscribe
    resign_as_master do
      @state = :paused
      if block
        block.call
      end
    end
  end
end

#process_result(result) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/sensu/server.rb', line 414

def process_result(result)
  @logger.debug('processing result', {
    :result => result
  })
  @redis.get('client:' + result[:client]) do |client_json|
    unless client_json.nil?
      client = Oj.load(client_json)
      check = case
      when @settings.check_exists?(result[:check][:name])
        @settings[:checks][result[:check][:name]].merge(result[:check])
      else
        result[:check]
      end
      if check[:aggregate]
        aggregate_result(result)
      end
      @redis.sadd('history:' + client[:name], check[:name])
      history_key = 'history:' + client[:name] + ':' + check[:name]
      @redis.rpush(history_key, check[:status]) do
        execution_key = 'execution:' + client[:name] + ':' + check[:name]
        @redis.set(execution_key, check[:executed])
        @redis.lrange(history_key, -21, -1) do |history|
          check[:history] = history
          total_state_change = 0
          unless history.size < 21
            state_changes = 0
            change_weight = 0.8
            previous_status = history.first
            history.each do |status|
              unless status == previous_status
                state_changes += change_weight
              end
              change_weight += 0.02
              previous_status = status
            end
            total_state_change = (state_changes.fdiv(20) * 100).to_i
            @redis.ltrim(history_key, -21, -1)
          end
          @redis.hget('events:' + client[:name], check[:name]) do |event_json|
            previous_occurrence = event_json ? Oj.load(event_json) : false
            is_flapping = false
            if check.has_key?(:low_flap_threshold) && check.has_key?(:high_flap_threshold)
              was_flapping = previous_occurrence ? previous_occurrence[:flapping] : false
              is_flapping = case
              when total_state_change >= check[:high_flap_threshold]
                true
              when was_flapping && total_state_change <= check[:low_flap_threshold]
                false
              else
                was_flapping
              end
            end
            event = {
              :client => client,
              :check => check,
              :occurrences => 1
            }
            if check[:status] != 0 || is_flapping
              if previous_occurrence && check[:status] == previous_occurrence[:status]
                event[:occurrences] = previous_occurrence[:occurrences] + 1
              end
              @redis.hset('events:' + client[:name], check[:name], Oj.dump(
                :output => check[:output],
                :status => check[:status],
                :issued => check[:issued],
                :handlers => Array((check[:handlers] || check[:handler]) || 'default'),
                :flapping => is_flapping,
                :occurrences => event[:occurrences]
              )) do
                unless check[:handle] == false
                  event[:action] = is_flapping ? :flapping : :create
                  handle_event(event)
                end
              end
            elsif previous_occurrence
              unless check[:auto_resolve] == false && !check[:force_resolve]
                @redis.hdel('events:' + client[:name], check[:name]) do
                  unless check[:handle] == false
                    event[:occurrences] = previous_occurrence[:occurrences]
                    event[:action] = :resolve
                    handle_event(event)
                  end
                end
              end
            elsif check[:type] == 'metric'
              handle_event(event)
            end
          end
        end
      end
    end
  end
end

#prune_aggregationsObject



637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/sensu/server.rb', line 637

def prune_aggregations
  @logger.info('pruning aggregations')
  @redis.smembers('aggregates') do |checks|
    checks.each do |check_name|
      @redis.smembers('aggregates:' + check_name) do |aggregates|
        if aggregates.size > 20
          aggregates.sort!
          aggregates.take(aggregates.size - 20).each do |check_issued|
            @redis.srem('aggregates:' + check_name, check_issued) do
              result_set = check_name + ':' + check_issued.to_s
              @redis.del('aggregate:' + result_set) do
                @redis.del('aggregation:' + result_set) do
                  @logger.debug('pruned aggregation', {
                    :check => {
                      :name => check_name,
                      :issued => check_issued
                    }
                  })
                end
              end
            end
          end
        end
      end
    end
  end
end

#publish_check_request(check) ⇒ Object



524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/sensu/server.rb', line 524

def publish_check_request(check)
  payload = {
    :name => check[:name],
    :issued => Time.now.to_i
  }
  if check.has_key?(:command)
    payload[:command] = check[:command]
  end
  @logger.info('publishing check request', {
    :payload => payload,
    :subscribers => check[:subscribers]
  })
  check[:subscribers].each do |exchange_name|
    @amq.fanout(exchange_name).publish(Oj.dump(payload))
  end
end

#publish_result(client, check) ⇒ Object



573
574
575
576
577
578
579
580
581
582
# File 'lib/sensu/server.rb', line 573

def publish_result(client, check)
  payload = {
    :client => client[:name],
    :check => check
  }
  @logger.debug('publishing check result', {
    :payload => payload
  })
  @amq.direct('results').publish(Oj.dump(payload))
end

#request_master_electionObject



678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'lib/sensu/server.rb', line 678

def request_master_election
  @redis.setnx('lock:master', Time.now.to_i) do |created|
    if created
      @is_master = true
      @logger.info('i am the master')
      master_duties
    else
      @redis.get('lock:master') do |timestamp|
        if Time.now.to_i - timestamp.to_i >= 60
          @redis.getset('lock:master', Time.now.to_i) do |previous|
            if previous == timestamp
              @is_master = true
              @logger.info('i am now the master')
              master_duties
            end
          end
        end
      end
    end
  end
end

#resign_as_master(&block) ⇒ Object



713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'lib/sensu/server.rb', line 713

def resign_as_master(&block)
  block ||= Proc.new {}
  if @is_master
    @logger.warn('resigning as master')
    @master_timers.each do |timer|
      timer.cancel
    end
    @master_timers.clear
    if @redis.connected?
      @redis.del('lock:master') do
        @logger.info('removed master lock')
        @is_master = false
      end
    end
    timestamp = Time.now.to_i
    retry_until_true do
      if !@is_master
        block.call
        true
      elsif Time.now.to_i - timestamp >= 3
        @logger.warn('failed to remove master lock')
        @is_master = false
        block.call
        true
      end
    end
  else
    @logger.debug('not currently master')
    block.call
  end
end

#resumeObject



803
804
805
806
807
808
809
810
811
812
# File 'lib/sensu/server.rb', line 803

def resume
  retry_until_true(1) do
    if @state == :paused
      if @redis.connected? && @rabbitmq.connected?
        bootstrap
        true
      end
    end
  end
end

#schedule_checks(checks) ⇒ Object



541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/sensu/server.rb', line 541

def schedule_checks(checks)
  check_count = 0
  stagger = testing? ? 0 : 2
  checks.each do |check|
    check_count += 1
    scheduling_delay = stagger * check_count % 30
    @master_timers << EM::Timer.new(scheduling_delay) do
      interval = testing? ? 0.5 : check[:interval]
      @master_timers << EM::PeriodicTimer.new(interval) do
        unless action_subdued?(check)
          publish_check_request(check)
        else
          @logger.info('check request was subdued', {
            :check => check
          })
        end
      end
    end
  end
end

#setup_aggregation_prunerObject



665
666
667
668
669
670
# File 'lib/sensu/server.rb', line 665

def setup_aggregation_pruner
  @logger.debug('pruning aggregations')
  @master_timers << EM::PeriodicTimer.new(20) do
    prune_aggregations
  end
end

#setup_client_monitorObject



630
631
632
633
634
635
# File 'lib/sensu/server.rb', line 630

def setup_client_monitor
  @logger.debug('monitoring clients')
  @master_timers << EM::PeriodicTimer.new(30) do
    determine_stale_clients
  end
end

#setup_keepalivesObject



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

def setup_keepalives
  @logger.debug('subscribing to keepalives')
  @keepalive_queue = @amq.queue!('keepalives')
  @keepalive_queue.bind(@amq.direct('keepalives'))
  @keepalive_queue.subscribe(:ack => true) do |header, payload|
    client = Oj.load(payload)
    @logger.debug('received keepalive', {
      :client => client
    })
    @redis.set('client:' + client[:name], Oj.dump(client)) do
      @redis.sadd('clients', client[:name]) do
        header.ack
      end
    end
  end
end

#setup_master_monitorObject



700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/sensu/server.rb', line 700

def setup_master_monitor
  request_master_election
  @timers << EM::PeriodicTimer.new(20) do
    if @is_master
      @redis.set('lock:master', Time.now.to_i) do
        @logger.debug('updated master lock timestamp')
      end
    else
      request_master_election
    end
  end
end

#setup_publisherObject



562
563
564
565
566
567
568
569
570
571
# File 'lib/sensu/server.rb', line 562

def setup_publisher
  @logger.debug('scheduling check requests')
  standard_checks = @settings.checks.reject do |check|
    check[:standalone] || check[:publish] == false
  end
  extension_checks = @extensions.checks.reject do |check|
    check[:standalone] || check[:publish] == false || !check[:interval].is_a?(Integer)
  end
  schedule_checks(standard_checks + extension_checks)
end

#setup_rabbitmqObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/sensu/server.rb', line 55

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
    unless testing?
      @logger.warn('reconnecting to rabbitmq')
      pause
    end
  end
  @rabbitmq.after_reconnect do
    @logger.info('reconnected to rabbitmq')
    @amq.prefetch(1)
    resume
  end
  @amq = @rabbitmq.channel
  @amq.prefetch(1)
end

#setup_redisObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sensu/server.rb', line 32

def setup_redis
  @logger.debug('connecting to redis', {
    :settings => @settings[:redis]
  })
  @redis = Redis.connect(@settings[:redis])
  @redis.on_error do |error|
    @logger.fatal('redis connection error', {
      :error => error.to_s
    })
    stop
  end
  @redis.before_reconnect do
    unless testing?
      @logger.warn('reconnecting to redis')
      pause
    end
  end
  @redis.after_reconnect do
    @logger.info('reconnected to redis')
    resume
  end
end

#setup_resultsObject



508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/sensu/server.rb', line 508

def setup_results
  @logger.debug('subscribing to results')
  @result_queue = @amq.queue!('results')
  @result_queue.bind(@amq.direct('results'))
  @result_queue.subscribe(:ack => true) do |header, payload|
    result = Oj.load(payload)
    @logger.debug('received result', {
      :result => result
    })
    process_result(result)
    EM::next_tick do
      header.ack
    end
  end
end

#startObject



780
781
782
783
784
# File 'lib/sensu/server.rb', line 780

def start
  setup_redis
  setup_rabbitmq
  bootstrap
end

#stopObject



814
815
816
817
818
819
820
821
822
823
824
825
826
827
# File 'lib/sensu/server.rb', line 814

def stop
  @logger.warn('stopping')
  @state = :stopping
  pause do
    complete_handlers_in_progress do
      @extensions.stop_all do
        @redis.close
        @rabbitmq.close
        @logger.warn('stopping reactor')
        EM::stop_event_loop
      end
    end
  end
end

#trap_signalsObject



829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
# File 'lib/sensu/server.rb', line 829

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



745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
# File 'lib/sensu/server.rb', line 745

def unsubscribe
  @logger.warn('unsubscribing from keepalive and result queues')
  if @rabbitmq.connected?
    @keepalive_queue.unsubscribe
    @result_queue.unsubscribe
    @amq.recover
  else
    @keepalive_queue.before_recovery do
      @keepalive_queue.unsubscribe
    end
    @result_queue.before_recovery do
      @result_queue.unsubscribe
    end
  end
end