dry_runnable.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. module DryRunnable
  2. extend ActiveSupport::Concern
  3. def dry_run!(event = nil)
  4. @dry_run = true
  5. log = StringIO.new
  6. @dry_run_started_at = Time.zone.now
  7. @dry_run_logger = Logger.new(log).tap { |logger|
  8. logger.formatter = proc { |severity, datetime, progname, message|
  9. elapsed_time = '%02d:%02d:%02d' % 2.times.inject([datetime - @dry_run_started_at]) { |(x, *xs)|
  10. [*x.divmod(60), *xs]
  11. }
  12. "[#{elapsed_time}] #{severity} -- #{progname}: #{message}\n"
  13. }
  14. }
  15. @dry_run_results = {
  16. events: [],
  17. }
  18. begin
  19. raise "#{short_type} does not support dry-run" unless can_dry_run?
  20. readonly!
  21. @dry_run_started_at = Time.zone.now
  22. @dry_run_logger.info('Dry Run started')
  23. if event
  24. raise "This agent cannot receive an event!" unless can_receive_events?
  25. receive([event])
  26. else
  27. check
  28. end
  29. @dry_run_logger.info('Dry Run finished')
  30. rescue => e
  31. @dry_run_logger.info('Dry Run failed')
  32. error "Exception during dry-run. #{e.message}: #{e.backtrace.join("\n")}"
  33. end
  34. @dry_run_results.update(
  35. memory: memory,
  36. log: log.string,
  37. )
  38. ensure
  39. @dry_run = false
  40. end
  41. def dry_run?
  42. !!@dry_run
  43. end
  44. included do
  45. prepend Wrapper
  46. end
  47. module Wrapper
  48. attr_accessor :results
  49. def logger
  50. return super unless dry_run?
  51. @dry_run_logger
  52. end
  53. def save(options = {})
  54. return super unless dry_run?
  55. perform_validations(options)
  56. end
  57. def save!(options = {})
  58. return super unless dry_run?
  59. save(options) or raise_record_invalid
  60. end
  61. def log(message, options = {})
  62. return super unless dry_run?
  63. case options[:level] || 3
  64. when 0..2
  65. sev = Logger::DEBUG
  66. when 3
  67. sev = Logger::INFO
  68. else
  69. sev = Logger::ERROR
  70. end
  71. logger.log(sev, message)
  72. end
  73. def create_event(event)
  74. return super unless dry_run?
  75. if can_create_events?
  76. event = build_event(event)
  77. @dry_run_results[:events] << event.payload
  78. event
  79. else
  80. error "This Agent cannot create events!"
  81. end
  82. end
  83. end
  84. end