blazer.rb 2.0 KB

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