post_agent.rb 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. module Agents
  2. class PostAgent < Agent
  3. cannot_create_events!
  4. default_schedule "never"
  5. description <<-MD
  6. A PostAgent receives events from other agents (or runs periodically), merges those events with the contents of `payload`, and sends the results as POST requests to a specified url. The `post_url` field must specify where you would like to send requests. Please include the URI scheme (`http` or `https`).
  7. MD
  8. event_description "Does not produce events."
  9. def default_options
  10. {
  11. 'post_url' => "http://www.example.com",
  12. 'expected_receive_period_in_days' => 1,
  13. 'payload' => {
  14. 'key' => 'value'
  15. }
  16. }
  17. end
  18. def working?
  19. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  20. end
  21. def validate_options
  22. unless options['post_url'].present? && options['expected_receive_period_in_days'].present?
  23. errors.add(:base, "post_url and expected_receive_period_in_days are required fields")
  24. end
  25. if options['payload'].present? && !options['payload'].is_a?(Hash)
  26. errors.add(:base, "if provided, payload must be a hash")
  27. end
  28. end
  29. def receive(incoming_events)
  30. incoming_events.each do |event|
  31. post_data (options['payload'].presence || {}).merge(event.payload)
  32. end
  33. end
  34. def check
  35. post_data options['payload'].presence || {}
  36. end
  37. private
  38. def post_data(data)
  39. uri = URI.new(options[:post_url])
  40. req = Net::HTTP::Post.new(uri.request_uri)
  41. req.form_data = data
  42. Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == "https") { |http| http.request(req) }
  43. end
  44. end
  45. end