Class: God::Task
- Inherits:
-
Object
- Object
- God::Task
- Defined in:
- lib/god/task.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#autostart ⇒ Object
writeonly
Public: Sets whether the task should autostart when god starts.
-
#behaviors ⇒ Object
api.
-
#directory ⇒ Object
api.
-
#driver ⇒ Object
Gets/Sets the Driver for this task.
-
#group ⇒ Object
Public: Gets/Sets the String group name of the task.
-
#initial_state ⇒ Object
Public: Gets/Sets the Symbol initial state of the state machine.
-
#interval ⇒ Object
Public: Gets/Sets the Numeric default interval to be used between poll events.
-
#metrics ⇒ Object
api.
-
#name ⇒ Object
Public: Gets/Sets the String name of the task.
-
#state ⇒ Object
api.
-
#valid_states ⇒ Object
Public: Gets/Sets the Array of Symbol valid states for the state machine.
Instance Method Summary collapse
-
#action(action, condition = nil) ⇒ Object
Perform the given action.
-
#attach(condition) ⇒ Object
Events.
-
#autostart? ⇒ Boolean
Returns true if autostart is enabled, false if not.
-
#canonical_hash_form(to) ⇒ Object
Convert the given input into canonical hash form which looks like:.
-
#dest_desc(metric, condition) ⇒ Object
Format the destination specification for use in debug logging.
- #detach(condition) ⇒ Object
-
#handle_event(condition) ⇒ Object
Asynchronously evaluate and handle the given event condition.
-
#handle_poll(condition) ⇒ Object
Evaluate and handle the given poll condition.
-
#initialize ⇒ Task
constructor
A new instance of Task.
-
#lifecycle {|m| ... } ⇒ Object
Public: Define a lifecycle handler.
-
#log_line(watch, metric, condition, result) ⇒ Object
Log info about the condition and return the list of messages logged.
-
#method_missing(sym, *args) ⇒ Object
Actions.
-
#monitor ⇒ Object
Enable monitoring.
-
#move(to_state) ⇒ Object
Move to the given state.
-
#notify(condition, message) ⇒ Object
Notify all recipients of the given condition with the specified message.
-
#prepare ⇒ Object
Initialize the metrics to an empty state.
-
#register! ⇒ Object
Registration.
- #signal(sig) ⇒ Object
-
#transition(start_states, end_states) ⇒ Object
Public: Define a transition handler which consists of a set of conditions.
-
#trigger(condition) ⇒ Object
Notify the Driver that an EventCondition has triggered.
-
#trigger?(metric, result) ⇒ Boolean
Determine whether a trigger happened.
-
#unmonitor ⇒ Object
Disable monitoring.
- #unregister! ⇒ Object
-
#valid? ⇒ Boolean
Verify that the minimum set of configuration requirements has been met.
Constructor Details
#initialize ⇒ Task
Returns a new instance of Task.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/god/task.rb', line 36 def initialize @autostart = true # initial state is unmonitored self.state = :unmonitored # the list of behaviors self.behaviors = [] # the list of conditions for each action self.metrics = { nil => [], :unmonitored => [], :stop => [] } # the condition -> metric lookup self.directory = {} # driver self.driver = Driver.new(self) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(sym, *args) ⇒ Object
Actions
258 259 260 261 262 263 264 265 266 267 |
# File 'lib/god/task.rb', line 258 def method_missing(sym, *args) super unless /=$/.match?(sym.to_s) base = sym.to_s.chop.intern super unless valid_states.include?(base) self.class.send(:attr_accessor, base) send(sym, *args) end |
Instance Attribute Details
#autostart=(value) ⇒ Object (writeonly)
Public: Sets whether the task should autostart when god starts. Defaults to true (enabled).
26 27 28 |
# File 'lib/god/task.rb', line 26 def autostart=(value) @autostart = value end |
#behaviors ⇒ Object
api
34 35 36 |
# File 'lib/god/task.rb', line 34 def behaviors @behaviors end |
#directory ⇒ Object
api
34 35 36 |
# File 'lib/god/task.rb', line 34 def directory @directory end |
#driver ⇒ Object
Gets/Sets the Driver for this task.
22 23 24 |
# File 'lib/god/task.rb', line 22 def driver @driver end |
#group ⇒ Object
Public: Gets/Sets the String group name of the task.
13 14 15 |
# File 'lib/god/task.rb', line 13 def group @group end |
#initial_state ⇒ Object
Public: Gets/Sets the Symbol initial state of the state machine.
19 20 21 |
# File 'lib/god/task.rb', line 19 def initial_state @initial_state end |
#interval ⇒ Object
Public: Gets/Sets the Numeric default interval to be used between poll events.
10 11 12 |
# File 'lib/god/task.rb', line 10 def interval @interval end |
#metrics ⇒ Object
api
34 35 36 |
# File 'lib/god/task.rb', line 34 def metrics @metrics end |
#name ⇒ Object
Public: Gets/Sets the String name of the task.
6 7 8 |
# File 'lib/god/task.rb', line 6 def name @name end |
#state ⇒ Object
api
34 35 36 |
# File 'lib/god/task.rb', line 34 def state @state end |
#valid_states ⇒ Object
Public: Gets/Sets the Array of Symbol valid states for the state machine.
16 17 18 |
# File 'lib/god/task.rb', line 16 def valid_states @valid_states end |
Instance Method Details
#action(action, condition = nil) ⇒ Object
Perform the given action.
action - The Symbol action. condition - The Condition.
Returns this Task.
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/god/task.rb', line 275 def action(action, condition = nil) if !driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. driver.(:action, [action, condition]) elsif respond_to?(action) # Called from within Driver. command = send(action) case command when String msg = "#{name} #{action}: #{command}" applog(self, :info, msg) system(command) when Proc msg = "#{name} #{action}: lambda" applog(self, :info, msg) command.call else raise NotImplementedError end end end |
#attach(condition) ⇒ Object
Events
306 307 308 309 310 311 312 313 |
# File 'lib/god/task.rb', line 306 def attach(condition) case condition when PollCondition driver.schedule(condition, 0) when EventCondition, TriggerCondition condition.register end end |
#autostart? ⇒ Boolean
Returns true if autostart is enabled, false if not.
29 30 31 |
# File 'lib/god/task.rb', line 29 def autostart? @autostart end |
#canonical_hash_form(to) ⇒ Object
Convert the given input into canonical hash form which looks like:
{ true => :state } or { true => :state, false => :otherstate }
to - The Symbol or Hash destination.
Returns the canonical Hash.
104 105 106 |
# File 'lib/god/task.rb', line 104 def canonical_hash_form(to) to.instance_of?(Symbol) ? { true => to } : to end |
#dest_desc(metric, condition) ⇒ Object
Format the destination specification for use in debug logging.
metric - The Metric. condition - The Condition.
Returns the formatted String.
478 479 480 481 482 483 484 485 486 |
# File 'lib/god/task.rb', line 478 def dest_desc(metric, condition) if condition.transition { true => condition.transition }.inspect elsif metric.destination metric.destination.inspect else 'none' end end |
#detach(condition) ⇒ Object
315 316 317 318 319 320 321 322 |
# File 'lib/god/task.rb', line 315 def detach(condition) case condition when PollCondition condition.reset when EventCondition, TriggerCondition condition.deregister end end |
#handle_event(condition) ⇒ Object
Asynchronously evaluate and handle the given event condition. Handles logging notifications, and moving to the new state if necessary.
condition - The Condition to handle.
Returns nothing.
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 |
# File 'lib/god/task.rb', line 408 def handle_event(condition) # Lookup metric. metric = directory[condition] # Log. = log_line(self, metric, condition, true) # Notify. notify(condition, .last) if condition.notify # Get the destination. dest = condition.transition || (metric.destination && metric.destination[true]) return unless dest move(dest) end |
#handle_poll(condition) ⇒ Object
Evaluate and handle the given poll condition. Handles logging notifications, and moving to the new state if necessary.
condition - The Condition to handle.
Returns nothing.
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 389 390 391 392 393 394 395 396 397 398 399 400 |
# File 'lib/god/task.rb', line 350 def handle_poll(condition) # Lookup metric. metric = directory[condition] # Run the test. begin result = condition.test rescue Object => e cname = condition.class.to_s.split('::').last = format("Unhandled exception in %{cname} condition - (%{class}): %{message}\n%{backtrace}", cname: cname, class: e.class, message: e., backtrace: e.backtrace.join("\n")) applog(self, :error, ) result = false end # Log. = log_line(self, metric, condition, result) # Notify. notify(condition, .last) if result && condition.notify # After-condition. condition.after # Get the destination. dest = if result && condition.transition # Condition override. condition.transition else # Regular. metric.destination && metric.destination[result] end # Transition or reschedule. if dest # Transition. begin move(dest) rescue EventRegistrationFailedError msg = "#{name} Event registration failed, moving back to previous state" applog(self, :info, msg) dest = state retry end else # Reschedule. driver.schedule(condition) end end |
#lifecycle {|m| ... } ⇒ Object
Public: Define a lifecycle handler. Conditions that belong to a lifecycle are active as long as the process is being monitored.
Returns nothing.
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/god/task.rb', line 154 def lifecycle # Create a new metric to hold the task and conditions. m = Metric.new(self) # Let the config file define some conditions on the metric. yield(m) # Populate the condition -> metric directory. m.conditions.each do |c| directory[c] = m end # Record the metric. metrics[nil] << m end |
#log_line(watch, metric, condition, result) ⇒ Object
Log info about the condition and return the list of messages logged.
watch - The Watch. metric - The Metric. condition - The Condition. result - The Boolean result of the condition test evaluation.
Returns the Array of String messages.
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 |
# File 'lib/god/task.rb', line 444 def log_line(watch, metric, condition, result) status = if trigger?(metric, result) '[trigger]' else '[ok]' end = [] # Log info if available. if condition.info Array(condition.info).each do |condition_info| << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})" applog(watch, :info, .last) end else << "#{watch.name} #{status} (#{condition.base_name})" applog(watch, :info, .last) end # Log. = "#{watch.name} #{condition.base_name} [#{result}] #{dest_desc(metric, condition)}" applog(watch, :debug, ) end |
#monitor ⇒ Object
Enable monitoring.
Returns nothing.
179 180 181 |
# File 'lib/god/task.rb', line 179 def monitor move(initial_state) end |
#move(to_state) ⇒ Object
Move to the given state.
to_state - The Symbol representing the state to move to.
Returns this Task.
195 196 197 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 |
# File 'lib/god/task.rb', line 195 def move(to_state) if driver.in_driver_context? # Called from within Driver. Record original info. orig_to_state = to_state from_state = state # Log. msg = "#{name} move '#{from_state}' to '#{to_state}'" applog(self, :info, msg) # Cleanup from current state. driver.clear_events metrics[from_state].each(&:disable) metrics[nil].each(&:disable) if to_state == :unmonitored # Perform action. action(to_state) # Enable simple mode. to_state = :up if [:start, :restart].include?(to_state) && metrics[to_state].empty? # Move to new state. metrics[to_state].each(&:enable) # If no from state, enable lifecycle metric. metrics[nil].each(&:enable) if from_state == :unmonitored # Set state. self.state = to_state # Broadcast to interested TriggerConditions. Trigger.broadcast(self, :state_change, [from_state, orig_to_state]) # Log. msg = "#{name} moved '#{from_state}' to '#{to_state}'" applog(self, :info, msg) else # Called from outside Driver. Send an async message to Driver. driver.(:move, [to_state]) end self end |
#notify(condition, message) ⇒ Object
Notify all recipients of the given condition with the specified message.
condition - The Condition. message - The String message to send.
Returns nothing.
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# File 'lib/god/task.rb', line 494 def notify(condition, ) spec = Contact.normalize(condition.notify) unmatched = [] # Resolve contacts. resolved_contacts = spec[:contacts].inject([]) do |acc, contact_name_or_group| cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group]) unmatched << contact_name_or_group if cons.empty? acc += cons acc end # Warn about unmatched contacts. unless unmatched.empty? msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(', ')}'" applog(condition.watch, :warn, msg) end # Notify each contact. resolved_contacts.each do |c| host = `hostname`.chomp rescue 'none' begin c.notify(, Time.now, spec[:priority], spec[:category], host) msg = "#{condition.watch.name} #{c.info || "notification sent for contact: #{c.name}"} (#{c.base_name})" applog(condition.watch, :info, msg) rescue Exception => e applog(condition.watch, :error, "#{e.} #{e.backtrace}") msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})" applog(condition.watch, :error, msg) end end end |
#prepare ⇒ Object
Initialize the metrics to an empty state.
Returns nothing.
58 59 60 61 62 |
# File 'lib/god/task.rb', line 58 def prepare valid_states.each do |state| metrics[state] ||= [] end end |
#register! ⇒ Object
Registration
330 331 332 |
# File 'lib/god/task.rb', line 330 def register! # override if necessary end |
#signal(sig) ⇒ Object
248 249 250 |
# File 'lib/god/task.rb', line 248 def signal(sig) # noop end |
#transition(start_states, end_states) ⇒ Object
Public: Define a transition handler which consists of a set of conditions
start_states - The Symbol or Array of Symbols start state(s). end_states - The Symbol or Hash end states.
Yields the Metric for this transition.
Returns nothing.
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 |
# File 'lib/god/task.rb', line 116 def transition(start_states, end_states) # Convert end_states into canonical hash form. canonical_end_states = canonical_hash_form(end_states) Array(start_states).each do |start_state| # Validate start state. unless valid_states.include?(start_state) abort "Invalid state :#{start_state}. Must be one of the symbols #{valid_states.map { |x| ":#{x}" }.join(', ')}" end # Create a new metric to hold the task, end states, and conditions. m = Metric.new(self, canonical_end_states) if block_given? # Let the config file define some conditions on the metric. yield(m) else # Add an :always condition if no block was given. m.condition(:always) do |c| c.what = true end end # Populate the condition -> metric directory. m.conditions.each do |c| directory[c] = m end # Record the metric. metrics[start_state] ||= [] metrics[start_state] << m end end |
#trigger(condition) ⇒ Object
Notify the Driver that an EventCondition has triggered.
condition - The Condition.
Returns nothing.
244 245 246 |
# File 'lib/god/task.rb', line 244 def trigger(condition) driver.(:handle_event, [condition]) end |
#trigger?(metric, result) ⇒ Boolean
Determine whether a trigger happened.
metric - The Metric. result - The Boolean result from the condition’s test.
Returns Boolean
432 433 434 |
# File 'lib/god/task.rb', line 432 def trigger?(metric, result) metric.destination && metric.destination[result] end |
#unmonitor ⇒ Object
Disable monitoring.
Returns nothing.
186 187 188 |
# File 'lib/god/task.rb', line 186 def unmonitor move(:unmonitored) end |
#unregister! ⇒ Object
334 335 336 |
# File 'lib/god/task.rb', line 334 def unregister! driver.shutdown end |
#valid? ⇒ Boolean
Verify that the minimum set of configuration requirements has been met.
Returns true if valid, false if not.
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/god/task.rb', line 67 def valid? valid = true # A name must be specified. if name.nil? valid = false applog(self, :error, 'No name String was specified.') end # Valid states must be specified. if valid_states.nil? valid = false applog(self, :error, 'No valid_states Array or Symbols was specified.') end # An initial state must be specified. if initial_state.nil? valid = false applog(self, :error, 'No initial_state Symbol was specified.') end valid end |