post_agent.rb 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. module Agents
  2. class PostAgent < Agent
  3. cannot_be_scheduled!
  4. description <<-MD
  5. Post Agent receives events from other agents and send those events as the contents of a post request to a specified url. `post_url` field must specify where you would like to receive post requests and do not forget to include URI scheme(`http` or `https`)
  6. MD
  7. event_description <<-MD
  8. Does not produce any event.
  9. MD
  10. def default_options
  11. {
  12. :post_url => "http://www.example.com",
  13. :expected_receive_period_in_days => 1
  14. }
  15. end
  16. def working?
  17. last_receive_at && last_receive_at > options[:expected_receive_period_in_days].to_i.days.ago
  18. end
  19. def validate_options
  20. unless options[:post_url].present? && options[:expected_receive_period_in_days].present?
  21. errors.add(:base, "post_url and expected_receive_period_in_days are required fields")
  22. end
  23. end
  24. def post_event(uri,event)
  25. req = Net::HTTP::Post.new(uri.request_uri)
  26. req.form_data = event
  27. Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == "https") { |http| http.request(req) }
  28. end
  29. def receive(incoming_events)
  30. incoming_events.each do |event|
  31. uri = URI options[:post_url]
  32. post_event uri, event.payload
  33. end
  34. end
  35. end
  36. end