blazer.rb 1.9 KB

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