Class: God::Task

Inherits:
Object
  • Object
show all
Defined in:
lib/god/task.rb

Direct Known Subclasses

Watch

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTask

Returns a new instance of Task


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/god/task.rb', line 35

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


263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/god/task.rb', line 263

def method_missing(sym, *args)
  unless (sym.to_s =~ /=$/)
    super
  end

  base = sym.to_s.chop.intern

  unless self.valid_states.include?(base)
    super
  end

  self.class.send(:attr_accessor, base)
  self.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).


25
26
27
# File 'lib/god/task.rb', line 25

def autostart=(value)
  @autostart = value
end

#behaviorsObject

api


33
34
35
# File 'lib/god/task.rb', line 33

def behaviors
  @behaviors
end

#directoryObject

api


33
34
35
# File 'lib/god/task.rb', line 33

def directory
  @directory
end

#driverObject

Gets/Sets the Driver for this task.


21
22
23
# File 'lib/god/task.rb', line 21

def driver
  @driver
end

#groupObject

Public: Gets/Sets the String group name of the task.


12
13
14
# File 'lib/god/task.rb', line 12

def group
  @group
end

#initial_stateObject

Public: Gets/Sets the Symbol initial state of the state machine.


18
19
20
# File 'lib/god/task.rb', line 18

def initial_state
  @initial_state
end

#intervalObject

Public: Gets/Sets the Numeric default interval to be used between poll events.


9
10
11
# File 'lib/god/task.rb', line 9

def interval
  @interval
end

#metricsObject

api


33
34
35
# File 'lib/god/task.rb', line 33

def metrics
  @metrics
end

#nameObject

Public: Gets/Sets the String name of the task.


5
6
7
# File 'lib/god/task.rb', line 5

def name
  @name
end

#stateObject

api


33
34
35
# File 'lib/god/task.rb', line 33

def state
  @state
end

#valid_statesObject

Public: Gets/Sets the Array of Symbol valid states for the state machine.


15
16
17
# File 'lib/god/task.rb', line 15

def valid_states
  @valid_states
end

Instance Method Details

#action(a, c = nil) ⇒ Object

Perform the given action.

a - The Symbol action. c - The Condition.

Returns this Task.


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
# File 'lib/god/task.rb', line 284

def action(a, c = nil)
  if !self.driver.in_driver_context?
    # Called from outside Driver. Send an async message to Driver.
    self.driver.message(:action, [a, c])
  else
    # Called from within Driver.
    if self.respond_to?(a)
      command = self.send(a)

      case command
        when String
          msg = "#{self.name} #{a}: #{command}"
          applog(self, :info, msg)

          system(command)
        when Proc
          msg = "#{self.name} #{a}: lambda"
          applog(self, :info, msg)

          command.call
        else
          raise NotImplementedError
      end
    end
  end
end

#attach(condition) ⇒ Object

Events


317
318
319
320
321
322
323
324
# File 'lib/god/task.rb', line 317

def attach(condition)
  case condition
    when PollCondition
      self.driver.schedule(condition, 0)
    when EventCondition, TriggerCondition
      condition.register
  end
end

#autostart?Boolean

Returns true if autostart is enabled, false if not.

Returns:

  • (Boolean)

28
29
30
# File 'lib/god/task.rb', line 28

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.


103
104
105
# File 'lib/god/task.rb', line 103

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.


500
501
502
503
504
505
506
507
508
509
510
# File 'lib/god/task.rb', line 500

def dest_desc(metric, condition)
  if condition.transition
    {true => condition.transition}.inspect
  else
    if metric.destination
      metric.destination.inspect
    else
      'none'
    end
  end
end

#detach(condition) ⇒ Object


326
327
328
329
330
331
332
333
# File 'lib/god/task.rb', line 326

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.


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
# File 'lib/god/task.rb', line 421

def handle_event(condition)
  # Lookup metric.
  metric = self.directory[condition]

  # Log.
  messages = self.log_line(self, metric, condition, true)

  # Notify.
  if condition.notify
    self.notify(condition, messages.last)
  end

  # Get the destination.
  dest =
  if condition.transition
    # Condition override.
    condition.transition
  else
    # Regular.
    metric.destination && metric.destination[true]
  end

  if dest
    self.move(dest)
  end
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.


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
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/god/task.rb', line 361

def handle_poll(condition)
  # Lookup metric.
  metric = self.directory[condition]

  # Run the test.
  begin
    result = condition.test
  rescue Object => e
    cname = condition.class.to_s.split('::').last
    message = format("Unhandled exception in %s condition - (%s): %s\n%s",
                     cname, e.class, e.message, e.backtrace.join("\n"))
    applog(self, :error, message)
    result = false
  end

  # Log.
  messages = self.log_line(self, metric, condition, result)

  # Notify.
  if result && condition.notify
    self.notify(condition, messages.last)
  end

  # 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
      self.move(dest)
    rescue EventRegistrationFailedError
      msg = self.name + ' Event registration failed, moving back to previous state'
      applog(self, :info, msg)

      dest = self.state
      retry
    end
  else
    # Reschedule.
    self.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.

Yields:

  • (m)

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/god/task.rb', line 153

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|
    self.directory[c] = m
  end

  # Record the metric.
  self.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.


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
# File 'lib/god/task.rb', line 466

def log_line(watch, metric, condition, result)
  status =
  if self.trigger?(metric, result)
    "[trigger]"
  else
    "[ok]"
  end

  messages = []

  # Log info if available.
  if condition.info
    Array(condition.info).each do |condition_info|
      messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})"
      applog(watch, :info, messages.last)
    end
  else
    messages << "#{watch.name} #{status} (#{condition.base_name})"
    applog(watch, :info, messages.last)
  end

  # Log.
  debug_message = watch.name + ' ' + condition.base_name + " [#{result}] " + self.dest_desc(metric, condition)
  applog(watch, :debug, debug_message)

  messages
end

#monitorObject

Enable monitoring.

Returns nothing.


178
179
180
# File 'lib/god/task.rb', line 178

def monitor
  self.move(self.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.


194
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
238
239
240
241
242
# File 'lib/god/task.rb', line 194

def move(to_state)
  if !self.driver.in_driver_context?
    # Called from outside Driver. Send an async message to Driver.
    self.driver.message(:move, [to_state])
  else
    # Called from within Driver. Record original info.
    orig_to_state = to_state
    from_state = self.state

    # Log.
    msg = "#{self.name} move '#{from_state}' to '#{to_state}'"
    applog(self, :info, msg)

    # Cleanup from current state.
    self.driver.clear_events
    self.metrics[from_state].each { |m| m.disable }
    if to_state == :unmonitored
      self.metrics[nil].each { |m| m.disable }
    end

    # Perform action.
    self.action(to_state)

    # Enable simple mode.
    if [:start, :restart].include?(to_state) && self.metrics[to_state].empty?
      to_state = :up
    end

    # Move to new state.
    self.metrics[to_state].each { |m| m.enable }

    # If no from state, enable lifecycle metric.
    if from_state == :unmonitored
      self.metrics[nil].each { |m| m.enable }
    end

    # Set state.
    self.state = to_state

    # Broadcast to interested TriggerConditions.
    Trigger.broadcast(self, :state_change, [from_state, orig_to_state])

    # Log.
    msg = "#{self.name} moved '#{from_state}' to '#{to_state}'"
    applog(self, :info, msg)
  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.


518
519
520
521
522
523
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
# File 'lib/god/task.rb', line 518

def notify(condition, message)
  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(message, Time.now, spec[:priority], spec[:category], host)
      msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})"
      applog(condition.watch, :info, msg % [])
    rescue Exception => e
      applog(condition.watch, :error, "#{e.message} #{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

#prepareObject

Initialize the metrics to an empty state.

Returns nothing.


57
58
59
60
61
# File 'lib/god/task.rb', line 57

def prepare
  self.valid_states.each do |state|
    self.metrics[state] ||= []
  end
end

#register!Object

Registration


341
342
343
# File 'lib/god/task.rb', line 341

def register!
  # override if necessary
end

#signal(sig) ⇒ Object


253
254
255
# File 'lib/god/task.rb', line 253

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.


115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/god/task.rb', line 115

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 self.valid_states.include?(start_state)
      abort "Invalid state :#{start_state}. Must be one of the symbols #{self.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|
      self.directory[c] = m
    end

    # Record the metric.
    self.metrics[start_state] ||= []
    self.metrics[start_state] << m
  end
end

#trigger(condition) ⇒ Object

Notify the Driver that an EventCondition has triggered.

condition - The Condition.

Returns nothing.


249
250
251
# File 'lib/god/task.rb', line 249

def trigger(condition)
  self.driver.message(: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

Returns:

  • (Boolean)

454
455
456
# File 'lib/god/task.rb', line 454

def trigger?(metric, result)
  metric.destination && metric.destination[result]
end

#unmonitorObject

Disable monitoring.

Returns nothing.


185
186
187
# File 'lib/god/task.rb', line 185

def unmonitor
  self.move(:unmonitored)
end

#unregister!Object


345
346
347
# File 'lib/god/task.rb', line 345

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.

Returns:

  • (Boolean)

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/god/task.rb', line 66

def valid?
  valid = true

  # A name must be specified.
  if self.name.nil?
    valid = false
    applog(self, :error, "No name String was specified.")
  end

  # Valid states must be specified.
  if self.valid_states.nil?
    valid = false
    applog(self, :error, "No valid_states Array or Symbols was specified.")
  end

  # An initial state must be specified.
  if self.initial_state.nil?
    valid = false
    applog(self, :error, "No initial_state Symbol was specified.")
  end

  valid
end