http_status_agent.rb 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 with the time that it waited for a reply.
  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. "elapsed_time": "..."
  21. }
  22. MD
  23. def working?
  24. memory['last_status'].to_i > 0
  25. end
  26. def default_options
  27. {
  28. 'url' => "http://google.com",
  29. 'disable_redirect_follow' => "true",
  30. }
  31. end
  32. def validate_options
  33. errors.add(:base, "a url must be specified") unless options['url'].present?
  34. end
  35. def check
  36. check_this_url interpolated[:url]
  37. end
  38. def receive(incoming_events)
  39. incoming_events.each do |event|
  40. interpolate_with(event) do
  41. check_this_url interpolated[:url]
  42. end
  43. end
  44. end
  45. private
  46. def check_this_url(url)
  47. measured_result = TimeTracker.track { ping(url) }
  48. if measured_result.result
  49. create_event payload: { 'url' => url, 'status' => measured_result.status.to_s, 'response_received' => true, 'elapsed_time' => measured_result.elapsed_time }
  50. memory['last_status'] = measured_result.status.to_s
  51. else
  52. create_event payload: { 'url' => url, 'response_received' => false, 'elapsed_time' => measured_result.elapsed_time }
  53. memory['last_status'] = nil
  54. end
  55. end
  56. def ping(url)
  57. result = faraday.get url
  58. result.status > 0 ? result : nil
  59. rescue
  60. nil
  61. end
  62. end
  63. end