trigger_agent.rb 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. module Agents
  2. class TriggerAgent < Agent
  3. cannot_be_scheduled!
  4. can_dry_run!
  5. VALID_COMPARISON_TYPES = %w[regex !regex field<value field<=value field==value field!=value field>=value field>value not\ in]
  6. description <<-MD
  7. The Trigger Agent will watch for a specific value in an Event payload.
  8. The `rules` array contains a mixture of strings and hashes.
  9. A string rule is a Liquid template and counts as a match when it expands to `true`.
  10. A hash rule consists of the following keys: `path`, `value`, and `type`.
  11. The `path` value is a dotted path through a hash in [JSONPaths](http://goessner.net/articles/JsonPath/) syntax. For simple events, this is usually just the name of the field you want, like 'text' for the text key of the event.
  12. The `type` can be one of #{VALID_COMPARISON_TYPES.map { |t| "`#{t}`" }.to_sentence} and compares with the `value`. Note that regex patterns are matched case insensitively. If you want case sensitive matching, prefix your pattern with `(?-i)`.
  13. In any `type` including regex Liquid variables can be used normally. To search for just a word matching the concatenation of `foo` and variable `bar` would use `value` of `foo{{bar}}`. Note that note that starting/ending delimiters like `/` or `|` are not required for regex.
  14. The `value` can be a single value or an array of values. In the case of an array, all items must be strings, and if one or more values match, then the rule matches. Note: avoid using `field!=value` with arrays, you should use `not in` instead.
  15. By default, all rules must match for the Agent to trigger. You can switch this so that only one rule must match by
  16. setting `must_match` to `1`.
  17. The resulting Event will have a payload message of `message`. You can use liquid templating in the `message, have a look at the [Wiki](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) for details.
  18. Set `keep_event` to `true` if you'd like to re-emit the incoming event, optionally merged with 'message' when provided.
  19. 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.
  20. MD
  21. event_description <<-MD
  22. Events look like this:
  23. { "message": "Your message" }
  24. MD
  25. private def valid_rule?(rule)
  26. case rule
  27. when String
  28. true
  29. when Hash
  30. rule.values_at('type', 'value', 'path').all?(&:present?) &&
  31. VALID_COMPARISON_TYPES.include?(rule['type'])
  32. else
  33. false
  34. end
  35. end
  36. def validate_options
  37. unless options['expected_receive_period_in_days'].present? &&
  38. options['rules'].present? &&
  39. options['rules'].all? { |rule| valid_rule?(rule) }
  40. errors.add(:base, "expected_receive_period_in_days, message, and rules, with a type, value, and path for every rule, are required")
  41. end
  42. errors.add(:base, "message is required unless 'keep_event' is 'true'") unless options['message'].present? || keep_event?
  43. errors.add(:base, "keep_event, when present, must be 'true' or 'false'") unless options['keep_event'].blank? || %w[true false].include?(options['keep_event'])
  44. if options['must_match'].present?
  45. if options['must_match'].to_i < 1
  46. errors.add(:base, "If used, the 'must_match' option must be a positive integer")
  47. elsif options['must_match'].to_i > options['rules'].length
  48. errors.add(:base, "If used, the 'must_match' option must be equal to or less than the number of rules")
  49. end
  50. end
  51. end
  52. def default_options
  53. {
  54. 'expected_receive_period_in_days' => "2",
  55. 'keep_event' => 'false',
  56. 'rules' => [{
  57. 'type' => "regex",
  58. 'value' => "foo\\d+bar",
  59. 'path' => "topkey.subkey.subkey.goal",
  60. }],
  61. 'message' => "Looks like your pattern matched in '{{value}}'!"
  62. }
  63. end
  64. def working?
  65. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  66. end
  67. def receive(incoming_events)
  68. incoming_events.each do |event|
  69. opts = interpolated(event)
  70. match_results = opts['rules'].map do |rule|
  71. if rule.is_a?(String)
  72. next boolify(rule)
  73. end
  74. value_at_path = Utils.value_at(event['payload'], rule['path'])
  75. rule_values = rule['value']
  76. rule_values = [rule_values] unless rule_values.is_a?(Array)
  77. if rule['type'] == 'not in'
  78. !rule_values.include?(value_at_path.to_s)
  79. elsif rule['type'] == 'field==value'
  80. rule_values.include?(value_at_path.to_s)
  81. else
  82. rule_values.any? do |rule_value|
  83. case rule['type']
  84. when "regex"
  85. value_at_path.to_s =~ Regexp.new(rule_value, Regexp::IGNORECASE)
  86. when "!regex"
  87. value_at_path.to_s !~ Regexp.new(rule_value, Regexp::IGNORECASE)
  88. when "field>value"
  89. value_at_path.to_f > rule_value.to_f
  90. when "field>=value"
  91. value_at_path.to_f >= rule_value.to_f
  92. when "field<value"
  93. value_at_path.to_f < rule_value.to_f
  94. when "field<=value"
  95. value_at_path.to_f <= rule_value.to_f
  96. when "field!=value"
  97. value_at_path.to_s != rule_value.to_s
  98. else
  99. raise "Invalid type of #{rule['type']} in TriggerAgent##{id}"
  100. end
  101. end
  102. end
  103. end
  104. if matches?(match_results)
  105. if keep_event?
  106. payload = event.payload.dup
  107. payload['message'] = opts['message'] if opts['message'].present?
  108. else
  109. payload = { 'message' => opts['message'] }
  110. end
  111. create_event :payload => payload
  112. end
  113. end
  114. end
  115. def matches?(matches)
  116. if options['must_match'].present?
  117. matches.select { |match| match }.length >= options['must_match'].to_i
  118. else
  119. matches.all?
  120. end
  121. end
  122. def keep_event?
  123. boolify(interpolated['keep_event'])
  124. end
  125. end
  126. end