blazer.rb 1.9 KB

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