http_status_agent.rb 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. module Agents
  2. class HttpStatusAgent < Agent
  3. include WebRequestConcern
  4. include FormConfigurable
  5. can_dry_run!
  6. can_order_created_events!
  7. default_schedule "every_12h"
  8. form_configurable :url
  9. form_configurable :disable_redirect_follow, type: :array, values: ['true', 'false']
  10. description <<-MD
  11. The HttpStatusAgent will check a url and emit the resulting HTTP status code.
  12. Specify a `Url` and the Http Status Agent will produce an event with the http status code.
  13. The `disable redirect follow` option causes the Agent to not follow HTTP redirects. For example, setting this to `true` will cause an agent that receives a 301 redirect to `http://yahoo.com` to return a status of 301 instead of following the redirect and returning 200.
  14. MD
  15. event_description <<-MD
  16. Events will have the following fields:
  17. {
  18. "url": "...",
  19. "status": "..."
  20. }
  21. MD
  22. def working?
  23. memory['last_status'].to_i > 0
  24. end
  25. def default_options
  26. {
  27. 'url' => "http://google.com",
  28. 'disable_redirect_follow' => "true",
  29. }
  30. end
  31. def validate_options
  32. errors.add(:base, "a url must be specified") unless options['url'].present?
  33. end
  34. def check
  35. check_this_url interpolated[:url]
  36. end
  37. def receive(incoming_events)
  38. incoming_events.each do |event|
  39. interpolate_with(event) do
  40. check_this_url interpolated[:url]
  41. end
  42. end
  43. end
  44. private
  45. def check_this_url(url)
  46. if result = ping(url)
  47. create_event payload: { 'url' => url, 'status' => result.status.to_s, 'response_received' => true }
  48. memory['last_status'] = result.status.to_s
  49. else
  50. create_event payload: { 'url' => url, 'response_received' => false }
  51. memory['last_status'] = nil
  52. end
  53. end
  54. def ping(url)
  55. result = faraday.get url
  56. result.status > 0 ? result : nil
  57. rescue
  58. nil
  59. end
  60. end
  61. end