blazer.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. require "csv"
  2. require "chartkick"
  3. require "blazer/version"
  4. require "blazer/data_source"
  5. require "blazer/engine"
  6. require "blazer/tasks"
  7. module Blazer
  8. class << self
  9. attr_accessor :audit
  10. attr_reader :time_zone
  11. attr_accessor :user_name
  12. attr_accessor :user_class
  13. attr_accessor :user_method
  14. attr_accessor :from_email
  15. attr_accessor :cache
  16. end
  17. self.audit = true
  18. self.user_name = :name
  19. def self.time_zone=(time_zone)
  20. @time_zone = time_zone.is_a?(ActiveSupport::TimeZone) ? time_zone : ActiveSupport::TimeZone[time_zone.to_s]
  21. end
  22. def self.settings
  23. @settings ||= begin
  24. path = Rails.root.join("config", "blazer.yml").to_s
  25. if File.exist?(path)
  26. YAML.load(ERB.new(File.read(path)).result)
  27. else
  28. {}
  29. end
  30. end
  31. end
  32. def self.data_sources
  33. @data_sources ||= begin
  34. ds = Hash[
  35. settings["data_sources"].map do |id, s|
  36. [id, Blazer::DataSource.new(id, s)]
  37. end
  38. ]
  39. ds.default = ds.values.first
  40. ds
  41. end
  42. end
  43. def self.run_checks
  44. Blazer::Check.includes(:query).find_each do |check|
  45. rows = nil
  46. error = nil
  47. tries = 0
  48. # try 3 times on timeout errors
  49. begin
  50. rows, error, cached_at = data_sources[check.query.data_source].run_statement(check.query.statement, refresh_cache: true)
  51. tries += 1
  52. end while error && error.include?("canceling statement due to statement timeout") && tries < 3
  53. check.update_state(rows, error)
  54. end
  55. end
  56. def self.send_failing_checks
  57. emails = {}
  58. Blazer::Check.includes(:query).where(state: %w[failing error]).find_each do |check|
  59. check.split_emails.each do |email|
  60. (emails[email] ||= []) << check
  61. end
  62. end
  63. emails.each do |email, checks|
  64. Blazer::CheckMailer.failing_checks(email, checks).deliver_later
  65. end
  66. end
  67. end