peak_detector_agent.rb 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. require 'pp'
  2. module Agents
  3. class PeakDetectorAgent < Agent
  4. cannot_be_scheduled!
  5. DEFAULT_SEARCH_URL = 'https://twitter.com/search?q={q}'
  6. description <<-MD
  7. The Peak Detector Agent will watch for peaks in an event stream. When a peak is detected, the resulting Event will have a payload message of `message`. You can include extractions in the message, for example: `I saw a bar of: {{foo.bar}}`, have a look at the [Wiki](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) for details.
  8. The `value_path` value is a [JSONPath](http://goessner.net/articles/JsonPath/) to the value of interest. `group_by_path` is a JSONPath that will be used to group values, if present.
  9. Set `expected_receive_period_in_days` to the maximum amount of time that you'd expect to pass between Events being received by this Agent.
  10. You may set `window_duration_in_days` to change the default memory window length of `14` days, `min_peak_spacing_in_days` to change the default minimum peak spacing of `2` days (peaks closer together will be ignored), and `std_multiple` to change the default standard deviation threshold multiple of `3`.
  11. You may set `min_events` for the minimal number of accumulated events before the agent starts detecting.
  12. You may set `search_url` to point to something else than Twitter search, using the URI Template syntax defined in [RFC 6570](https://tools.ietf.org/html/rfc6570). Default value is `#{DEFAULT_SEARCH_URL}` where `{q}` will be replaced with group name.
  13. MD
  14. event_description <<-MD
  15. Events look like:
  16. {
  17. "message": "Your message",
  18. "peak": 6,
  19. "peak_time": 3456789242,
  20. "grouped_by": "something"
  21. }
  22. MD
  23. def validate_options
  24. unless options['expected_receive_period_in_days'].present? && options['message'].present? && options['value_path'].present? && options['min_events'].present?
  25. errors.add(:base, "expected_receive_period_in_days, value_path, min_events and message are required")
  26. end
  27. begin
  28. tmpl = search_url
  29. rescue => e
  30. errors.add(:base, "search_url must be a valid URI template: #{e.message}")
  31. else
  32. unless tmpl.keys.include?('q')
  33. errors.add(:base, "search_url must include a variable named 'q'")
  34. end
  35. end
  36. end
  37. def default_options
  38. {
  39. 'expected_receive_period_in_days' => "2",
  40. 'group_by_path' => "filter",
  41. 'value_path' => "count",
  42. 'message' => "A peak of {{count}} was found in {{filter}}",
  43. 'min_events' => '4',
  44. }
  45. end
  46. def working?
  47. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  48. end
  49. def receive(incoming_events)
  50. incoming_events.sort_by(&:created_at).each do |event|
  51. group = group_for(event)
  52. remember group, event
  53. check_for_peak group, event
  54. end
  55. end
  56. def search_url
  57. Addressable::Template.new(options[:search_url].presence || DEFAULT_SEARCH_URL)
  58. end
  59. private
  60. def check_for_peak(group, event)
  61. memory['peaks'] ||= {}
  62. memory['peaks'][group] ||= []
  63. return if memory['data'][group].length <= options['min_events'].to_i
  64. if memory['peaks'][group].empty? || memory['peaks'][group].last < event.created_at.to_i - peak_spacing
  65. average_value, standard_deviation = stats_for(group, :skip_last => 1)
  66. newest_value, newest_time = memory['data'][group][-1].map(&:to_f)
  67. if newest_value > average_value + std_multiple * standard_deviation
  68. memory['peaks'][group] << newest_time
  69. memory['peaks'][group].reject! { |p| p <= newest_time - window_duration }
  70. create_event :payload => { 'message' => interpolated(event)['message'], 'peak' => newest_value, 'peak_time' => newest_time, 'grouped_by' => group.to_s }
  71. end
  72. end
  73. end
  74. def stats_for(group, options = {})
  75. data = memory['data'][group].map { |d| d.first.to_f }
  76. data = data[0...(data.length - (options[:skip_last] || 0))]
  77. length = data.length.to_f
  78. mean = 0
  79. mean_variance = 0
  80. data.each do |value|
  81. mean += value
  82. end
  83. mean /= length
  84. data.each do |value|
  85. variance = (value - mean)**2
  86. mean_variance += variance
  87. end
  88. mean_variance /= length
  89. standard_deviation = Math.sqrt(mean_variance)
  90. [mean, standard_deviation]
  91. end
  92. def window_duration
  93. if interpolated['window_duration'].present? # The older option
  94. interpolated['window_duration'].to_i
  95. else
  96. (interpolated['window_duration_in_days'] || 14).to_f.days
  97. end
  98. end
  99. def std_multiple
  100. (interpolated['std_multiple'] || 3).to_f
  101. end
  102. def peak_spacing
  103. if interpolated['peak_spacing'].present? # The older option
  104. interpolated['peak_spacing'].to_i
  105. else
  106. (interpolated['min_peak_spacing_in_days'] || 2).to_f.days
  107. end
  108. end
  109. def group_for(event)
  110. ((interpolated['group_by_path'].present? && Utils.value_at(event.payload, interpolated['group_by_path'])) || 'no_group')
  111. end
  112. def remember(group, event)
  113. memory['data'] ||= {}
  114. memory['data'][group] ||= []
  115. memory['data'][group] << [ Utils.value_at(event.payload, interpolated['value_path']).to_f, event.created_at.to_i ]
  116. cleanup group
  117. end
  118. def cleanup(group)
  119. newest_time = memory['data'][group].last.last
  120. memory['data'][group].reject! { |value, time| time <= newest_time - window_duration }
  121. end
  122. end
  123. end