blazer.rb 1.9 KB

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