change_detector_agent.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module Agents
  2. class ChangeDetectorAgent < Agent
  3. cannot_be_scheduled!
  4. description <<-MD
  5. The ChangeDetectorAgent receives a stream of events and emits a new event when a property of the received event changes.
  6. `property` specifies the property to be watched.
  7. `expected_update_period_in_days` is used to determine if the Agent is working.
  8. The resulting event will be a copy of the received event.
  9. MD
  10. event_description <<-MD
  11. This will change based on the source event. If you were event from the ShellCommandAgent, your outbound event might look like:
  12. {
  13. 'command' => 'pwd',
  14. 'path' => '/home/Huginn',
  15. 'exit_status' => '0',
  16. 'errors' => '',
  17. 'output' => '/home/Huginn'
  18. }
  19. MD
  20. def default_options
  21. {
  22. 'property' => '{{output}}',
  23. 'expected_update_period_in_days' => 1
  24. }
  25. end
  26. def validate_options
  27. unless options['property'].present? && options['expected_update_period_in_days'].present?
  28. errors.add(:base, "The property and expected_update_period_in_days fields are all required.")
  29. end
  30. end
  31. def working?
  32. event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
  33. end
  34. def receive(incoming_events)
  35. incoming_events.each do |event|
  36. handle(interpolated(event), event)
  37. end
  38. end
  39. private
  40. def handle(opts, event = nil)
  41. property = opts['property']
  42. if has_changed?(property)
  43. created_event = create_event :payload => event.payload
  44. log("Propagating new event as property has changed to #{property} from #{last_property}", :outbound_event => created_event, :inbound_event => event )
  45. update_memory(property)
  46. else
  47. log("Not propagating as incoming event has not changed from #{last_property}.", :inbound_event => event )
  48. end
  49. end
  50. def has_changed?(property)
  51. property != last_property
  52. end
  53. def last_property
  54. self.memory['last_property']
  55. end
  56. def update_memory(property)
  57. self.memory['last_property'] = property
  58. end
  59. end
  60. end