Class: Sensu::Server::Process
- Inherits:
-
Object
- Object
- Sensu::Server::Process
- Defined in:
- lib/sensu/server/process.rb
Constant Summary collapse
- STANDARD_CHECK_TYPE =
"standard".freeze
- METRIC_CHECK_TYPE =
"metric".freeze
- EVENT_FLAPPING_ACTION =
"flapping".freeze
- DEFAULT_HANDLER_NAME =
"default".freeze
Constants included from Filter
Instance Attribute Summary collapse
-
#in_progress ⇒ Object
readonly
Returns the value of attribute in_progress.
-
#is_leader ⇒ Object
readonly
Returns the value of attribute is_leader.
Attributes included from Daemon
Class Method Summary collapse
-
.run(options = {}) ⇒ Object
Create an instance of the Sensu server process, start the server within the EventMachine event loop, and set up server process signal traps (for stopping).
Instance Method Summary collapse
-
#aggregate_check_result(client, check) ⇒ Object
Add a check result to one or more aggregates.
-
#become_the_leader ⇒ Object
Become the Sensu server leader, responsible for specific duties (‘leader_duties()`).
-
#bootstrap ⇒ Object
Bootstrap the Sensu server process, setting up the keepalive and check result consumers, and attemping to become the leader to carry out its duties.
-
#calculate_check_execution_splay(check) ⇒ Object
Calculate a check execution splay, taking into account the current time and the execution interval to ensure it’s consistent between process restarts.
-
#check_flapping?(stored_event, check) ⇒ TrueClass, FalseClass
Determine if a check state is flapping, rapidly changing between an OK and non-OK state.
-
#check_history(client, check) {|history, total_state_change| ... } ⇒ Object
Fetch the execution history for a client/check pair, the 21 most recent check result statuses.
-
#complete_in_progress { ... } ⇒ Object
Complete in progress work and then call the provided callback.
-
#create_client(name) ⇒ Hash
Create a blank client (data).
-
#create_client_keepalive_check_results(clients) { ... } ⇒ Object
Create client keepalive check results.
-
#create_client_registration_event(client) ⇒ Object
Create and process a client registration event.
-
#create_event(client, check) {|event| ... } ⇒ Object
Create an event, using the provided client and check result data.
-
#create_keepalive_check(client) ⇒ Object
Create a keepalive check definition for a client.
-
#create_lock_timestamp ⇒ Integer
Create a lock timestamp (integer), current time including milliseconds.
-
#create_registration_check(client) ⇒ Object
Create a registration check definition for a client.
-
#derive_handlers(handler_list, depth = 0) ⇒ Array
Derive an array of handler definitions from a list of handler names.
-
#determine_stale_check_results(interval = 30) ⇒ Object
Determine stale check results, those that have not executed in a specified amount of time (check TTL).
-
#determine_stale_clients ⇒ Object
Determine stale clients, those that have not sent a keepalive in a specified amount of time.
-
#event_bridges(event) ⇒ Object
Run event bridge extensions, within the Sensu EventMachine reactor (event loop).
-
#event_silenced?(event) ⇒ Boolean
Determine if an event has been silenced.
-
#expand_handler_sets(handler, depth = 0) ⇒ Array, ...
Expand event handler sets, creating an array of handler definitions.
-
#initialize(options = {}) ⇒ Process
constructor
Override Daemon initialize() to support Sensu server leader election and the handling event count.
-
#keepalive_event_exists?(client_name) ⇒ TrueClass, FalseClass
Determine if a keepalive event exists for a client.
-
#leader_duties ⇒ Object
Set up the leader duties, tasks only performed by a single Sensu server at a time.
-
#leader_id ⇒ String
Create/return the unique Sensu server leader ID for the current process.
-
#pause ⇒ Object
Pause the Sensu server process, unless it is being paused or has already been paused.
-
#process_check_result(result) ⇒ Object
Process a check result, storing its data, inspecting its contents, and taking the appropriate actions (eg. update the event registry).
-
#process_client_registration(client) ⇒ Object
Process an initial client registration, when it is first added to the client registry.
-
#process_event(event) ⇒ Object
Process an event: filter -> mutate -> handle.
-
#publish_check_request(check) ⇒ Object
Publish a check request to the Transport.
-
#publish_check_result(client_name, check) ⇒ Object
Publish a check result to the Transport for processing.
-
#request_leader_election ⇒ Object
Request a leader election, a process to determine if the current process is the Sensu server leader, with its own/unique duties.
-
#resign_as_leader ⇒ Object
Resign as leader, if the current process is the Sensu server leader.
-
#resume ⇒ Object
Resume the Sensu server process if it is currently or will soon be paused.
-
#retrieve_client(result) {|client| ... } ⇒ Object
Retrieve a client (data) from Redis if it exists.
-
#schedule_check_executions(checks) ⇒ Object
Schedule check executions, using EventMachine periodic timers, using a calculated execution splay.
-
#setup_check_request_publisher ⇒ Object
Set up the check request publisher.
-
#setup_check_result_monitor(interval = 30) ⇒ Object
Set up the check result monitor, a periodic timer to run ‘determine_stale_check_results()` every 30 seconds.
-
#setup_client_monitor ⇒ Object
Set up the client monitor, a periodic timer to run ‘determine_stale_clients()` every 30 seconds.
-
#setup_connections { ... } ⇒ Object
Set up the Redis and Transport connection objects, ‘@redis` and `@transport`.
-
#setup_keepalives ⇒ Object
Set up the client keepalive consumer, keeping the Sensu client registry updated.
-
#setup_leader_monitor ⇒ Object
Set up the leader monitor.
-
#setup_results ⇒ Object
Set up the check result consumer.
-
#start ⇒ Object
Start the Sensu server process, connecting to Redis, the Transport, and calling the ‘bootstrap()` method.
-
#stop ⇒ Object
Stop the Sensu server process, pausing it, completing event handling in progress, closing the Redis and transport connections, and exiting the process (exit 0).
-
#store_check_result(client, check) { ... } ⇒ Object
Store check result data.
-
#transport_publish_options(subscription, message) ⇒ Array
Determine the Sensu Transport publish options for a subscription.
-
#truncate_check_output(check) ⇒ Hash
Truncate check output.
-
#unsubscribe ⇒ Object
Unsubscribe from transport subscriptions (all of them).
-
#update_client_registry(client) {|success| ... } ⇒ Object
Update the Sensu client registry, stored in Redis.
-
#update_event_registry(event) {|process| ... } ⇒ Object
Update the event registry, stored in Redis.
-
#update_leader_lock ⇒ Object
Updates the Sensu server leader lock timestamp.
Methods included from Handle
#handle_event, #handler_error, #handler_extension, #handler_type_router, #pipe_handler, #tcp_handler, #transport_handler, #udp_handler
Methods included from Mutate
#mutate_event, #mutator_callback, #mutator_extension, #pipe_mutator
Methods included from Filter
#eval_attribute_value, #event_filter, #event_filtered?, #extension_filter, #filter_attributes_match?, #filter_event, #handle_action?, #handle_severity?, #handler_silenced?, #handling_disabled?, #in_filter_time_windows?, #native_filter, #process_eval_string
Methods included from Daemon
#load_extensions, #load_settings, #log_notices, #print_settings!, #setup_logger, #setup_process, #setup_redis, #setup_signal_traps, #setup_spawn, #setup_transport, #validate_settings!
Methods included from Utilities
#check_subdued?, #deep_merge, #find_attribute_value, #in_time_window?, #in_time_windows?, #random_uuid, #redact_sensitive, #retry_until_true, #substitute_tokens, #testing?
Constructor Details
#initialize(options = {}) ⇒ Process
Override Daemon initialize() to support Sensu server leader election and the handling event count.
41 42 43 44 45 46 |
# File 'lib/sensu/server/process.rb', line 41 def initialize(={}) super @is_leader = false @timers[:leader] = Array.new @in_progress = Hash.new(0) end |
Instance Attribute Details
#in_progress ⇒ Object (readonly)
Returns the value of attribute in_progress.
14 15 16 |
# File 'lib/sensu/server/process.rb', line 14 def in_progress @in_progress end |
#is_leader ⇒ Object (readonly)
Returns the value of attribute is_leader.
14 15 16 |
# File 'lib/sensu/server/process.rb', line 14 def is_leader @is_leader end |
Class Method Details
.run(options = {}) ⇒ Object
Create an instance of the Sensu server process, start the server within the EventMachine event loop, and set up server process signal traps (for stopping).
29 30 31 32 33 34 35 |
# File 'lib/sensu/server/process.rb', line 29 def self.run(={}) server = self.new() EM::run do server.start server.setup_signal_traps end end |
Instance Method Details
#aggregate_check_result(client, check) ⇒ Object
Add a check result to one or more aggregates. The aggregate name is determined by the value of check ‘:aggregates` array, if present, and falling back to `:aggregate` otherwise.
When one or more aggregates are specified as ‘:aggregates`, the client name and check are updated on each aggregate.
When no aggregates are specified as ‘:aggregates`, and `:aggregate` is `true` (legacy), the check `:name` is used as the aggregate name.
When no aggregates are specified as ‘:aggregates` and check `:aggregate` is a string, it used as the aggregate name.
This method will add the client name to configured aggregates, all other processing (e.g. counters) is done by the Sensu API on request.
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
# File 'lib/sensu/server/process.rb', line 295 def aggregate_check_result(client, check) check_aggregate = (check[:aggregate].is_a?(String) ? check[:aggregate] : check[:name]) aggregate_list = Array(check[:aggregates] || check_aggregate) aggregate_list.each do |aggregate| @logger.debug("adding check result to aggregate", { :aggregate => aggregate, :client => client, :check => check }) aggregate_member = "#{client[:name]}:#{check[:name]}" @redis.sadd("aggregates:#{aggregate}", aggregate_member) do @redis.sadd("aggregates", aggregate) end end end |
#become_the_leader ⇒ Object
Become the Sensu server leader, responsible for specific duties (‘leader_duties()`). Unless the current process is already the leader, this method sets the leader ID stored in Redis to the unique random leader ID for the process. If the leader ID in Redis is successfully updated, `@is_leader` is set to true and `leader_duties()` is called to begin the tasks/duties of the Sensu server leader.
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 |
# File 'lib/sensu/server/process.rb', line 1029 def become_the_leader unless @is_leader @redis.set("leader", leader_id) do @logger.info("i am now the leader") @is_leader = true leader_duties end else @logger.debug("i am already the leader") end end |
#bootstrap ⇒ Object
Bootstrap the Sensu server process, setting up the keepalive and check result consumers, and attemping to become the leader to carry out its duties. This method sets the process/daemon ‘@state` to `:running`.
1161 1162 1163 1164 1165 1166 |
# File 'lib/sensu/server/process.rb', line 1161 def bootstrap setup_keepalives setup_results setup_leader_monitor @state = :running end |
#calculate_check_execution_splay(check) ⇒ Object
Calculate a check execution splay, taking into account the current time and the execution interval to ensure it’s consistent between process restarts.
767 768 769 770 771 |
# File 'lib/sensu/server/process.rb', line 767 def calculate_check_execution_splay(check) splay_hash = Digest::MD5.digest(check[:name]).unpack('Q<').first current_time = (Time.now.to_f * 1000).to_i (splay_hash - current_time) % (check[:interval] * 1000) / 1000.0 end |
#check_flapping?(stored_event, check) ⇒ TrueClass, FalseClass
Determine if a check state is flapping, rapidly changing between an OK and non-OK state. Flap detection is only done for checks that have defined low and hight flap detection thresholds, ‘:low_flap_threshold` and `:high_flap_threshold`. The `check_history()` method provides the check history and more importantly the total state change precentage value that is compared with the configured thresholds defined in the check data. If a check hasn’t been flapping, the ‘:total_state_change` must be equal to or higher than the `:high_flap_threshold` to be changed to flapping. If a check has been flapping, the `:total_state_change` must be equal to or lower than the `:low_flap_threshold` to no longer be flapping. This method uses the same algorithm as Nagios: nagios.sourceforge.net/docs/3_0/flapping.html
423 424 425 426 427 428 429 430 431 432 433 434 |
# File 'lib/sensu/server/process.rb', line 423 def check_flapping?(stored_event, check) if check.has_key?(:low_flap_threshold) && check.has_key?(:high_flap_threshold) was_flapping = stored_event && stored_event[:action] == EVENT_FLAPPING_ACTION if was_flapping check[:total_state_change] > check[:low_flap_threshold] else check[:total_state_change] >= check[:high_flap_threshold] end else false end end |
#check_history(client, check) {|history, total_state_change| ... } ⇒ Object
Fetch the execution history for a client/check pair, the 21 most recent check result statuses. This method also calculates the total state change percentage for the history, this value is use for check state flap detection, using a similar algorithm to Nagios: nagios.sourceforge.net/docs/3_0/flapping.html
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'lib/sensu/server/process.rb', line 384 def check_history(client, check) history_key = "history:#{client[:name]}:#{check[:name]}" @redis.lrange(history_key, -21, -1) do |history| total_state_change = 0 unless history.length < 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 end yield(history, total_state_change) end end |
#complete_in_progress { ... } ⇒ Object
Complete in progress work and then call the provided callback. This method will wait until all counters stored in the ‘@in_progress` hash equal `0`.
1147 1148 1149 1150 1151 1152 1153 1154 1155 |
# File 'lib/sensu/server/process.rb', line 1147 def complete_in_progress @logger.info("completing work in progress", :in_progress => @in_progress) retry_until_true do if @in_progress.values.all? { |count| count == 0 } yield true end end end |
#create_client(name) ⇒ Hash
Create a blank client (data). Only the client name is known, the other client attributes must be updated via the API (POST /clients:client). Dynamically created clients and those updated via the API will have client keepalives disabled by default, ‘:keepalives` is set to `false`.
581 582 583 584 585 586 587 588 589 |
# File 'lib/sensu/server/process.rb', line 581 def create_client(name) { :name => name, :address => "unknown", :subscriptions => ["client:#{name}"], :keepalives => false, :version => VERSION } end |
#create_client_keepalive_check_results(clients) { ... } ⇒ Object
Create client keepalive check results. This method will retrieve clients from the registry, creating a keepalive check definition for each client, using the ‘create_keepalive_check()` method, containing client specific keepalive thresholds. If the time since the latest keepalive is equal to or greater than a threshold, the check `:output` is set to a descriptive message, and `:status` is set to the appropriate non-zero value. If a client has been sending keepalives, `:output` and `:status` are set to indicate an OK state. The `publish_check_result()` method is used to publish the client keepalive check results.
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 |
# File 'lib/sensu/server/process.rb', line 885 def create_client_keepalive_check_results(clients) client_keys = clients.map { |client_name| "client:#{client_name}" } @redis.mget(*client_keys) do |client_json_objects| client_json_objects.each do |client_json| unless client_json.nil? client = Sensu::JSON.load(client_json) next if client[:keepalives] == false check = create_keepalive_check(client) time_since_last_keepalive = Time.now.to_i - client[:timestamp] check[:output] = "No keepalive sent from client for " check[:output] << "#{time_since_last_keepalive} seconds" case when time_since_last_keepalive >= check[:thresholds][:critical] check[:output] << " (>=#{check[:thresholds][:critical]})" check[:status] = 2 when time_since_last_keepalive >= check[:thresholds][:warning] check[:output] << " (>=#{check[:thresholds][:warning]})" check[:status] = 1 else check[:output] = "Keepalive sent from client " check[:output] << "#{time_since_last_keepalive} seconds ago" check[:status] = 0 end publish_check_result(client[:name], check) end end yield end end |
#create_client_registration_event(client) ⇒ Object
Create and process a client registration event. A registration event is created when a Sensu client is first added to the client registry. The ‘create_registration_check()` method is called to create a registration check definition for the client.
99 100 101 102 103 104 105 |
# File 'lib/sensu/server/process.rb', line 99 def create_client_registration_event(client) check = create_registration_check(client) create_event(client, check) do |event| event_bridges(event) process_event(event) end end |
#create_event(client, check) {|event| ... } ⇒ Object
Create an event, using the provided client and check result data. Existing event data for the client/check pair is fetched from the event registry to be used in the composition of the new event. The silenced registry is used to determine if the event has been silenced.
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
# File 'lib/sensu/server/process.rb', line 524 def create_event(client, check) check_history(client, check) do |history, total_state_change| check[:history] = history check[:total_state_change] = total_state_change @redis.hget("events:#{client[:name]}", check[:name]) do |event_json| stored_event = event_json ? Sensu::JSON.load(event_json) : nil flapping = check_flapping?(stored_event, check) event = { :client => client, :check => check, :occurrences => 1, :occurrences_watermark => 1, :action => (flapping ? :flapping : :create), :timestamp => Time.now.to_i } if stored_event event[:id] = stored_event[:id] event[:last_state_change] = stored_event[:last_state_change] event[:last_ok] = stored_event[:last_ok] event[:occurrences] = stored_event[:occurrences] event[:occurrences_watermark] = stored_event[:occurrences_watermark] || event[:occurrences] else event[:id] = random_uuid event[:last_ok] = event[:timestamp] end if check[:status] != 0 || flapping if history[-1] == history[-2] event[:occurrences] += 1 if event[:occurrences] > event[:occurrences_watermark] event[:occurrences_watermark] = event[:occurrences] end else event[:occurrences] = 1 event[:last_state_change] = event[:timestamp] end elsif stored_event event[:last_state_change] = event[:timestamp] event[:action] = :resolve end if check[:status] == 0 event[:last_ok] = event[:timestamp] end event_silenced?(event) do |event| yield(event) end end end end |
#create_keepalive_check(client) ⇒ Object
Create a keepalive check definition for a client. Client definitions may contain ‘:keepalive` configuration, containing specific thresholds and handler information. The keepalive check definition creation begins with default thresholds, and sets the `:handler` to `keepalive`, if the handler has a local definition. If the client provides its own `:keepalive` configuration, it’s deep merged with the defaults. The check ‘:name`, `:issued`, and `:executed` values are always overridden to guard against an invalid definition.
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 |
# File 'lib/sensu/server/process.rb', line 853 def create_keepalive_check(client) check = { :thresholds => { :warning => 120, :critical => 180 } } if @settings.handler_exists?(:keepalive) check[:handler] = "keepalive" end if client.has_key?(:keepalive) check = deep_merge(check, client[:keepalive]) end = Time.now.to_i check.merge(:name => "keepalive", :issued => , :executed => ) end |
#create_lock_timestamp ⇒ Integer
Create a lock timestamp (integer), current time including milliseconds. This method is used by Sensu server leader election.
1010 1011 1012 |
# File 'lib/sensu/server/process.rb', line 1010 def (Time.now.to_f * 1000).to_i end |
#create_registration_check(client) ⇒ Object
Create a registration check definition for a client. Client definitions may contain ‘:registration` configuration, containing custom attributes and handler information. By default, the registration check definition sets the `:handler` to `registration`. If the client provides its own `:registration` configuration, it’s deep merged with the defaults. The check ‘:name`, `:output`, `:issued`, and `:executed` values are always overridden to guard against an invalid definition.
77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/sensu/server/process.rb', line 77 def create_registration_check(client) check = {:handler => "registration", :status => 1} if client.has_key?(:registration) check = deep_merge(check, client[:registration]) end = Time.now.to_i overrides = { :name => "registration", :output => "new client registration", :issued => , :executed => } check.merge(overrides) end |
#derive_handlers(handler_list, depth = 0) ⇒ Array
Derive an array of handler definitions from a list of handler names. This method first checks for the existence of standard handlers, followed by handler extensions. If a handler does not exist for a name, it is logged and ignored. Duplicate handler definitions are removed.
222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/sensu/server/process.rb', line 222 def derive_handlers(handler_list, depth=0) handler_list.compact.map { |handler_name| case when @settings.handler_exists?(handler_name) handler = @settings[:handlers][handler_name].merge(:name => handler_name) (handler, depth) when @extensions.handler_exists?(handler_name) @extensions[:handlers][handler_name] else @logger.error("unknown handler", :handler_name => handler_name) nil end }.flatten.compact.uniq end |
#determine_stale_check_results(interval = 30) ⇒ Object
Determine stale check results, those that have not executed in a specified amount of time (check TTL). This method iterates through stored check results that have a defined TTL value (in seconds). The time since last check execution (in seconds) is calculated for each check result. If the time since last execution is equal to or greater than the check TTL, a warning check result is published with the appropriate check output.
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 |
# File 'lib/sensu/server/process.rb', line 956 def determine_stale_check_results(interval = 30) @logger.info("determining stale check results") @redis.smembers("ttl") do |result_keys| result_keys.each do |result_key| @redis.get("result:#{result_key}") do |result_json| unless result_json.nil? check = Sensu::JSON.load(result_json) next unless check[:ttl] && check[:executed] && !check[:force_resolve] time_since_last_execution = Time.now.to_i - check[:executed] if time_since_last_execution >= check[:ttl] client_name = result_key.split(":").first keepalive_event_exists?(client_name) do |event_exists| unless event_exists check[:output] = "Last check execution was " check[:output] << "#{time_since_last_execution} seconds ago" check[:status] = check[:ttl_status] || 1 check[:interval] = interval publish_check_result(client_name, check) end end end else @redis.srem("ttl", result_key) end end end end end |
#determine_stale_clients ⇒ Object
Determine stale clients, those that have not sent a keepalive in a specified amount of time. This method iterates through the client registry, creating a keepalive check result for each client. The ‘create_client_keepalive_check_results()` method is used to inspect and create keepalive check results for each slice of clients from the registry. A relatively small clients slice size (20) is used to reduce the number of clients inspected within a single tick of the EM reactor.
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
# File 'lib/sensu/server/process.rb', line 923 def determine_stale_clients @logger.info("determining stale clients") @redis.smembers("clients") do |clients| client_count = clients.length keepalive_check_results = Proc.new do |slice_start, slice_size| unless slice_start > client_count - 1 clients_slice = clients.slice(slice_start..slice_size) create_client_keepalive_check_results(clients_slice) do keepalive_check_results.call(slice_start + 20, slice_size + 20) end end end keepalive_check_results.call(0, 19) end end |
#event_bridges(event) ⇒ Object
Run event bridge extensions, within the Sensu EventMachine reactor (event loop). The extension API ‘safe_run()` method is used to guard against most errors. Bridges are for relaying Sensu event data to other services.
266 267 268 269 270 271 272 273 274 275 |
# File 'lib/sensu/server/process.rb', line 266 def event_bridges(event) @extensions[:bridges].each do |name, bridge| bridge.safe_run(event) do |output, status| @logger.debug("bridge extension output", { :extension => bridge.definition, :output => output }) end end end |
#event_silenced?(event) ⇒ Boolean
Determine if an event has been silenced. This method compiles an array of possible silenced registry entry keys for the event. An attempt is made to fetch one or more of the silenced registry entries to determine if the event has been silenced. The event data is updated to indicate if the event has been silenced. If the event is silenced and the event action is ‘:resolve`, silenced registry entries with `:expire_on_resolve` set to true will be deleted. Silencing is disabled for events with a check status of `0` (OK), unless the event action is `:resolve` or `:flapping`.
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 |
# File 'lib/sensu/server/process.rb', line 450 def event_silenced?(event) event[:silenced] = false event[:silenced_by] = [] if event[:check][:status] != 0 || event[:action] != :create check_name = event[:check][:name] silenced_keys = event[:client][:subscriptions].map { |subscription| ["silence:#{subscription}:*", "silence:#{subscription}:#{check_name}"] }.flatten silenced_keys << "silence:*:#{check_name}" @redis.mget(*silenced_keys) do |silenced| silenced.compact! silenced.each do |silenced_json| silenced_info = Sensu::JSON.load(silenced_json) if silenced_info[:expire_on_resolve] && event[:action] == :resolve silenced_key = "silence:#{silenced_info[:id]}" @redis.srem("silenced", silenced_key) @redis.del(silenced_key) else event[:silenced_by] << silenced_info[:id] end end event[:silenced] = !event[:silenced_by].empty? yield(event) end else yield(event) end end |
#expand_handler_sets(handler, depth = 0) ⇒ Array, ...
Expand event handler sets, creating an array of handler definitions. Handler sets cannot be deeply nested (by choice), this method will return ‘nil` if an attempt is made to deeply nest. If the provided handler definition is not a set, it is returned.
200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/sensu/server/process.rb', line 200 def (handler, depth=0) if handler[:type] == "set" if depth < 2 derive_handlers(handler[:handlers], depth + 1) else @logger.error("handler sets cannot be deeply nested", :handler => handler) nil end else handler end end |
#keepalive_event_exists?(client_name) ⇒ TrueClass, FalseClass
Determine if a keepalive event exists for a client.
634 635 636 637 638 |
# File 'lib/sensu/server/process.rb', line 634 def keepalive_event_exists?(client_name) @redis.hexists("events:#{client_name}", "keepalive") do |event_exists| yield(event_exists) end end |
#leader_duties ⇒ Object
Set up the leader duties, tasks only performed by a single Sensu server at a time. The duties include publishing check requests, monitoring for stale clients, and pruning check result aggregations.
999 1000 1001 1002 1003 |
# File 'lib/sensu/server/process.rb', line 999 def leader_duties setup_check_request_publisher setup_client_monitor setup_check_result_monitor end |
#leader_id ⇒ String
Create/return the unique Sensu server leader ID for the current process.
1018 1019 1020 |
# File 'lib/sensu/server/process.rb', line 1018 def leader_id @leader_id ||= random_uuid end |
#pause ⇒ Object
Pause the Sensu server process, unless it is being paused or has already been paused. The process/daemon ‘@state` is first set to `:pausing`, to indicate that it’s in progress. All run timers are cancelled, and the references are cleared. The Sensu server will unsubscribe from all transport subscriptions, resign as leader (if currently the leader), then set the process/daemon ‘@state` to `:paused`.
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 |
# File 'lib/sensu/server/process.rb', line 1183 def pause unless @state == :pausing || @state == :paused @state = :pausing @timers[:run].each do |timer| timer.cancel end @timers[:run].clear unsubscribe resign_as_leader @state = :paused end end |
#process_check_result(result) ⇒ Object
Process a check result, storing its data, inspecting its contents, and taking the appropriate actions (eg. update the event registry). The ‘@in_progress` counter is incremented by `1` prior to check result processing and then decremented by `1` after updating the event registry. A check result must have a valid client name, associated with a client in the registry or one will be created. If a local check definition exists for the check name, and the check result is not from a standalone check execution, it’s merged with the check result for more context.
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 |
# File 'lib/sensu/server/process.rb', line 652 def process_check_result(result) @in_progress[:check_results] += 1 @logger.debug("processing result", :result => result) retrieve_client(result) do |client| unless client.nil? check = case when @settings.check_exists?(result[:check][:name]) && !result[:check][:standalone] @settings[:checks][result[:check][:name]].merge(result[:check]) else result[:check] end check[:type] ||= STANDARD_CHECK_TYPE check[:origin] = result[:client] if check[:source] aggregate_check_result(client, check) if check[:aggregates] || check[:aggregate] store_check_result(client, check) do create_event(client, check) do |event| event_bridges(event) update_event_registry(event) do |process| process_event(event) if process @in_progress[:check_results] -= 1 end end end else @logger.warn("halting result processing", :result => result) @in_progress[:check_results] -= 1 end end end |
#process_client_registration(client) ⇒ Object
Process an initial client registration, when it is first added to the client registry. If a registration handler is defined or the client specifies one, a client registration event is created and processed (handled, etc.) for the client (‘create_client_registration_event()`).
114 115 116 117 118 |
# File 'lib/sensu/server/process.rb', line 114 def process_client_registration(client) if @settings.handler_exists?("registration") || client[:registration] create_client_registration_event(client) end end |
#process_event(event) ⇒ Object
Process an event: filter -> mutate -> handle.
This method determines the appropriate handlers for an event, filtering and mutating the event data for each of them. The ‘@in_progress` counter is incremented by `1`, for each event handler chain (filter -> mutate -> handle).
245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# File 'lib/sensu/server/process.rb', line 245 def process_event(event) log_level = event[:check][:type] == METRIC_CHECK_TYPE ? :debug : :info @logger.send(log_level, "processing event", :event => event) handler_list = Array((event[:check][:handlers] || event[:check][:handler]) || DEFAULT_HANDLER_NAME) handlers = derive_handlers(handler_list) handlers.each do |handler| @in_progress[:events] += 1 filter_event(handler, event) do |event| mutate_event(handler, event) do |event_data| handle_event(handler, event_data) end end end end |
#publish_check_request(check) ⇒ Object
Publish a check request to the Transport. A check request is composed of a check definition (minus ‘:subscribers` and `:interval`) and an `:issued` timestamp. The check request is published to a Transport pipe, for each of the check `:subscribers` in its definition, eg. “webserver”. JSON serialization is used when publishing the check request payload to the Transport pipes. Transport errors are logged.
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 |
# File 'lib/sensu/server/process.rb', line 739 def publish_check_request(check) payload = check.reject do |key, value| [:subscribers, :interval].include?(key) end payload[:issued] = Time.now.to_i @logger.info("publishing check request", { :payload => payload, :subscribers => check[:subscribers] }) check[:subscribers].each do |subscription| = (subscription, Sensu::JSON.dump(payload)) @transport.publish(*) do |info| if info[:error] @logger.error("failed to publish check request", { :subscription => subscription, :payload => payload, :error => info[:error].to_s }) end end end end |
#publish_check_result(client_name, check) ⇒ Object
Publish a check result to the Transport for processing. A check result is composed of a client name and a check definition, containing check ‘:output` and `:status`. A client signature is added to the check result payload if one is registered for the client. JSON serialization is used when publishing the check result payload to the Transport pipe. Transport errors are logged.
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 |
# File 'lib/sensu/server/process.rb', line 825 def publish_check_result(client_name, check) payload = { :client => client_name, :check => check } @redis.get("client:#{client_name}:signature") do |signature| payload[:signature] = signature if signature @logger.debug("publishing check result", :payload => payload) @transport.publish(:direct, "results", Sensu::JSON.dump(payload)) do |info| if info[:error] @logger.error("failed to publish check result", { :payload => payload, :error => info[:error].to_s }) end end end end |
#request_leader_election ⇒ Object
Request a leader election, a process to determine if the current process is the Sensu server leader, with its own/unique duties. A Redis key/value is used as a central lock, using the “SETNX” Redis command to set the key/value if it does not exist, using a timestamp for the value. If the current process was able to create the key/value, it is the leader, and must do the duties of the leader. If the current process was not able to create the key/value, but the current timestamp value is equal to or over 30 seconds ago, the “GETSET” Redis command is used to set a new timestamp and fetch the previous value to compare them, to determine if it was set by the current process. If the current process is able to set the timestamp value, it becomes the leader.
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 |
# File 'lib/sensu/server/process.rb', line 1095 def request_leader_election @redis.setnx("lock:leader", ) do |created| if created become_the_leader else @redis.get("lock:leader") do || = if - .to_i >= 30000 @redis.getset("lock:leader", ) do || if == become_the_leader end end end end end end end |
#resign_as_leader ⇒ Object
Resign as leader, if the current process is the Sensu server leader. This method cancels and clears the leader timers, those with references stored in the timers hash under ‘:leader`, and `@is_leader` is set to `false`. The leader ID and leader lock are not removed from Redis, as they will be updated when another server is elected to be the leader, this method does not need to handle Redis connectivity issues.
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 |
# File 'lib/sensu/server/process.rb', line 1048 def resign_as_leader if @is_leader @logger.warn("resigning as leader") @timers[:leader].each do |timer| timer.cancel end @timers[:leader].clear @is_leader = false else @logger.debug("not currently the leader") end end |
#resume ⇒ Object
Resume the Sensu server process if it is currently or will soon be paused. The ‘retry_until_true` helper method is used to determine if the process is paused and if the Redis and transport connections are initiated and connected. If the conditions are met, `bootstrap()` will be called and true is returned to stop `retry_until_true`. If the transport has not yet been initiated, true is is returned, without calling bootstrap, as we expect bootstrap will be called after the transport initializes.
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 |
# File 'lib/sensu/server/process.rb', line 1205 def resume retry_until_true(1) do if @state == :paused if @redis.connected? if @transport if @transport.connected? bootstrap true end else true end end end end end |
#retrieve_client(result) {|client| ... } ⇒ Object
Retrieve a client (data) from Redis if it exists. If a client does not already exist, create one (a blank) using the ‘client_key` as the client name. Dynamically create client data can be updated using the API (POST /clients/:client). If a client does exist and it has a client signature, the check result must have a matching signature or it is discarded.
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/process.rb', line 602 def retrieve_client(result) client_key = result[:check][:source] || result[:client] @redis.get("client:#{client_key}") do |client_json| unless client_json.nil? client = Sensu::JSON.load(client_json) if client[:signature] if client[:signature] == result[:signature] yield(client) else @logger.warn("invalid check result signature", { :result => result, :client => client }) @logger.warn("not retrieving client from the registry", :result => result) yield(nil) end else yield(client) end else client = create_client(client_key) update_client_registry(client) do yield(client) end end end end |
#schedule_check_executions(checks) ⇒ Object
Schedule check executions, using EventMachine periodic timers, using a calculated execution splay. The timers are stored in the timers hash under ‘:leader`, as check request publishing is a task for only the Sensu server leader, so they can be cancelled etc. Check requests are not published if subdued.
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 |
# File 'lib/sensu/server/process.rb', line 780 def schedule_check_executions(checks) checks.each do |check| create_check_request = Proc.new do unless check_subdued?(check) publish_check_request(check) else @logger.info("check request was subdued", :check => check) end end execution_splay = testing? ? 0 : calculate_check_execution_splay(check) interval = testing? ? 0.5 : check[:interval] @timers[:leader] << EM::Timer.new(execution_splay) do create_check_request.call @timers[:leader] << EM::PeriodicTimer.new(interval, &create_check_request) end end end |
#setup_check_request_publisher ⇒ Object
Set up the check request publisher. This method creates an array of check definitions, that are not standalone checks, and do not have ‘:publish` set to `false`. The array of check definitions includes those from standard checks and extensions (with a defined execution `:interval`). The array is provided to the `schedule_check_executions()` method.
804 805 806 807 808 809 810 811 812 813 |
# File 'lib/sensu/server/process.rb', line 804 def setup_check_request_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_check_executions(standard_checks + extension_checks) end |
#setup_check_result_monitor(interval = 30) ⇒ Object
Set up the check result monitor, a periodic timer to run ‘determine_stale_check_results()` every 30 seconds. The timer is stored in the timers hash under `:leader`.
988 989 990 991 992 993 |
# File 'lib/sensu/server/process.rb', line 988 def setup_check_result_monitor(interval = 30) @logger.debug("monitoring check results") @timers[:leader] << EM::PeriodicTimer.new(interval) do determine_stale_check_results(interval) end end |
#setup_client_monitor ⇒ Object
Set up the client monitor, a periodic timer to run ‘determine_stale_clients()` every 30 seconds. The timer is stored in the timers hash under `:leader`.
942 943 944 945 946 947 |
# File 'lib/sensu/server/process.rb', line 942 def setup_client_monitor @logger.debug("monitoring client keepalives") @timers[:leader] << EM::PeriodicTimer.new(30) do determine_stale_clients end end |
#setup_connections { ... } ⇒ Object
Set up the Redis and Transport connection objects, ‘@redis` and `@transport`. This method updates the Redis on error callback to reset the in progress check result counter. This method “drys” up many instances of `setup_redis()` and `setup_transport()`, particularly in the specs.
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/sensu/server/process.rb', line 56 def setup_connections setup_redis do @redis.on_error do |error| @logger.error("redis connection error", :error => error.to_s) @in_progress[:check_results] = 0 end setup_transport do yield end end end |
#setup_keepalives ⇒ Object
Set up the client keepalive consumer, keeping the Sensu client registry updated. The consumer receives JSON serialized client keepalives from the transport, parses them, and calls ‘update_client_registry()` with the client data to update the registry. Transport message acknowledgements are used to ensure the client registry is updated successfully. Keepalive JSON parsing errors are logged.
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
# File 'lib/sensu/server/process.rb', line 172 def setup_keepalives @logger.debug("subscribing to keepalives") @transport.subscribe(:direct, "keepalives", "keepalives", :ack => true) do |, | @logger.debug("received keepalive", :message => ) begin client = Sensu::JSON.load() update_client_registry(client) do @transport.ack() end rescue Sensu::JSON::ParseError => error @logger.error("failed to parse keepalive payload", { :message => , :error => error.to_s }) @transport.ack() end end end |
#setup_leader_monitor ⇒ Object
Set up the leader monitor. A one-time timer is used to run ‘request_leader_exection()` in 2 seconds. A periodic timer is used to update the leader lock timestamp if the current process is the leader, or to run `request_leader_election(), every 10 seconds. The timers are stored in the timers hash under `:run`.
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 |
# File 'lib/sensu/server/process.rb', line 1120 def setup_leader_monitor @timers[:run] << EM::Timer.new(2) do request_leader_election end @timers[:run] << EM::PeriodicTimer.new(10) do if @is_leader update_leader_lock else request_leader_election end end end |
#setup_results ⇒ Object
Set up the check result consumer. The consumer receives JSON serialized check results from the transport, parses them, and calls ‘process_check_result()` with the result data to be processed. Transport message acknowledgements are used to ensure that results make it to processing. The transport message acknowledgements are currently done in the next tick of the EventMachine reactor (event loop), as a flow control mechanism. Result JSON parsing errors are logged.
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 |
# File 'lib/sensu/server/process.rb', line 690 def setup_results @logger.debug("subscribing to results") @transport.subscribe(:direct, "results", "results", :ack => true) do |, | begin result = Sensu::JSON.load() @logger.debug("received result", :result => result) process_check_result(result) rescue Sensu::JSON::ParseError => error @logger.error("failed to parse result payload", { :message => , :error => error.to_s }) end EM::next_tick do @transport.ack() end end end |
#start ⇒ Object
Start the Sensu server process, connecting to Redis, the Transport, and calling the ‘bootstrap()` method.
1170 1171 1172 1173 1174 |
# File 'lib/sensu/server/process.rb', line 1170 def start setup_connections do bootstrap end end |
#stop ⇒ Object
Stop the Sensu server process, pausing it, completing event handling in progress, closing the Redis and transport connections, and exiting the process (exit 0). After pausing the process, the process/daemon ‘@state` is set to `:stopping`.
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 |
# File 'lib/sensu/server/process.rb', line 1227 def stop @logger.warn("stopping") pause @state = :stopping complete_in_progress do @redis.close if @redis @transport.close if @transport super end end |
#store_check_result(client, check) { ... } ⇒ Object
Store check result data. This method stores check result data and the 21 most recent check result statuses for a client/check pair, this history is used for event context and flap detection. The check execution timestamp is also stored, to provide an indication of how recent the data is. Check output is truncated by ‘truncate_check_output()` before it is stored.
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 |
# File 'lib/sensu/server/process.rb', line 352 def store_check_result(client, check) @logger.debug("storing check result", :check => check) result_key = "#{client[:name]}:#{check[:name]}" history_key = "history:#{result_key}" check_truncated = truncate_check_output(check) @redis.multi @redis.sadd("result:#{client[:name]}", check[:name]) @redis.set("result:#{result_key}", Sensu::JSON.dump(check_truncated)) @redis.sadd("ttl", result_key) if check[:ttl] @redis.rpush(history_key, check[:status]) @redis.ltrim(history_key, -21, -1) @redis.exec do yield end end |
#transport_publish_options(subscription, message) ⇒ Array
Determine the Sensu Transport publish options for a subscription. If a subscription begins with a Transport pipe type, either “direct:” or “roundrobin:”, the subscription uses a direct Transport pipe. If a subscription does not specify a Transport pipe type, a fanout Transport pipe is used.
720 721 722 723 724 725 726 727 728 |
# File 'lib/sensu/server/process.rb', line 720 def (subscription, ) _, raw_type = subscription.split(":", 2).reverse case raw_type when "direct", "roundrobin" [:direct, subscription, ] else [:fanout, subscription, ] end end |
#truncate_check_output(check) ⇒ Hash
Truncate check output. For metric checks, (‘“type”: “metric”`), check output is truncated to a single line and a maximum of 255 characters. Check output is currently left unmodified for standard checks.
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
# File 'lib/sensu/server/process.rb', line 318 def truncate_check_output(check) case check[:type] when METRIC_CHECK_TYPE begin output_lines = check[:output].split("\n") rescue ArgumentError utf8_output = check[:output].encode("UTF-8", "binary", { :invalid => :replace, :undef => :replace, :replace => "" }) output_lines = utf8_output.split("\n") end output = output_lines.first || check[:output] if output_lines.length > 1 || output.length > 255 output = output[0..255] + "\n..." end check.merge(:output => output) else check end end |
#unsubscribe ⇒ Object
Unsubscribe from transport subscriptions (all of them). This method is called when there are issues with connectivity, or the process is stopping.
1136 1137 1138 1139 |
# File 'lib/sensu/server/process.rb', line 1136 def unsubscribe @logger.warn("unsubscribing from keepalive and result queues") @transport.unsubscribe if @transport end |
#update_client_registry(client) {|success| ... } ⇒ Object
Update the Sensu client registry, stored in Redis. Sensu client data is used to provide additional event context and enable agent health monitoring. The client registry supports client signatures, unique string identifiers used for keepalive and result source verification. If a client has a signature, all further registry updates for the client must have the same signature. A client can begin to use a signature if one was not previously configured. JSON serialization is used for the stored client data.
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
# File 'lib/sensu/server/process.rb', line 136 def update_client_registry(client) @logger.debug("updating client registry", :client => client) client_key = "client:#{client[:name]}" signature_key = "#{client_key}:signature" @redis.setnx(signature_key, client[:signature]) do |created| process_client_registration(client) if created @redis.get(signature_key) do |signature| if (signature.nil? || signature.empty?) && client[:signature] @redis.set(signature_key, client[:signature]) end if signature.nil? || signature.empty? || (client[:signature] == signature) @redis.multi @redis.set(client_key, Sensu::JSON.dump(client)) @redis.sadd("clients", client[:name]) @redis.exec do yield(true) if block_given? end else @logger.warn("invalid client signature", { :client => client, :signature => signature }) @logger.warn("not updating client in the registry", :client => client) yield(false) if block_given? end end end end |
#update_event_registry(event) {|process| ... } ⇒ Object
Update the event registry, stored in Redis. This method determines if event data warrants in the creation or update of event data in the registry. If a check ‘:status` is not `0`, or it has been flapping, an event is created/updated in the registry. If the event `:action` is `:resolve`, the event is removed (resolved) from the registry. If the previous conditions are not met and check `:type` is `metric`, the registry is not updated, but further event processing is required (`yield(true)`). JSON serialization is used when storing data in the registry.
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
# File 'lib/sensu/server/process.rb', line 495 def update_event_registry(event) client_name = event[:client][:name] if event[:check][:status] != 0 || event[:action] == :flapping @redis.hset("events:#{client_name}", event[:check][:name], Sensu::JSON.dump(event)) do yield(true) end elsif event[:action] == :resolve && (event[:check][:auto_resolve] != false || event[:check][:force_resolve]) @redis.hdel("events:#{client_name}", event[:check][:name]) do yield(true) end elsif event[:check][:type] == METRIC_CHECK_TYPE yield(true) else yield(false) end end |
#update_leader_lock ⇒ Object
Updates the Sensu server leader lock timestamp. The current leader ID is retrieved from Redis and compared with the leader ID of the current process to determine if it is still the Sensu server leader. If the current process is still the leader, the leader lock timestamp is updated. If the current process is no longer the leader (regicide), ‘resign_as_leader()` is called for cleanup, so there is not more than one leader.
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 |
# File 'lib/sensu/server/process.rb', line 1069 def update_leader_lock @redis.get("leader") do |current_leader_id| if current_leader_id == leader_id @redis.set("lock:leader", ) do @logger.debug("updated leader lock timestamp") end else @logger.warn("another sensu server has been elected as leader") resign_as_leader end end end |