blazer.rb 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. require "csv"
  2. require "yaml"
  3. require "chartkick"
  4. require "safely/core"
  5. require "blazer/version"
  6. require "blazer/data_source"
  7. require "blazer/result"
  8. require "blazer/run_statement"
  9. require "blazer/adapters/base_adapter"
  10. require "blazer/adapters/bigquery_adapter"
  11. require "blazer/adapters/drill_adapter"
  12. require "blazer/adapters/elasticsearch_adapter"
  13. require "blazer/adapters/mongodb_adapter"
  14. require "blazer/adapters/presto_adapter"
  15. require "blazer/adapters/sql_adapter"
  16. require "blazer/engine"
  17. module Blazer
  18. class Error < StandardError; end
  19. class TimeoutNotSupported < Error; end
  20. class << self
  21. attr_accessor :audit
  22. attr_reader :time_zone
  23. attr_accessor :user_name
  24. attr_accessor :user_class
  25. attr_accessor :user_method
  26. attr_accessor :before_action
  27. attr_accessor :from_email
  28. attr_accessor :cache
  29. attr_accessor :transform_statement
  30. attr_accessor :check_schedules
  31. attr_accessor :anomaly_checks
  32. attr_accessor :async
  33. attr_accessor :images
  34. attr_accessor :query_editable
  35. end
  36. self.audit = true
  37. self.user_name = :name
  38. self.check_schedules = ["5 minutes", "1 hour", "1 day"]
  39. self.anomaly_checks = false
  40. self.async = false
  41. self.images = false
  42. TIMEOUT_MESSAGE = "Query timed out :("
  43. TIMEOUT_ERRORS = [
  44. "canceling statement due to statement timeout", # postgres
  45. "canceling statement due to conflict with recovery", # postgres
  46. "cancelled on user's request", # redshift
  47. "canceled on user's request", # redshift
  48. "system requested abort", # redshift
  49. "maximum statement execution time exceeded" # mysql
  50. ]
  51. BELONGS_TO_OPTIONAL = {}
  52. BELONGS_TO_OPTIONAL[:optional] = true if Rails::VERSION::MAJOR >= 5
  53. def self.time_zone=(time_zone)
  54. @time_zone = time_zone.is_a?(ActiveSupport::TimeZone) ? time_zone : ActiveSupport::TimeZone[time_zone.to_s]
  55. end
  56. def self.settings
  57. @settings ||= begin
  58. path = Rails.root.join("config", "blazer.yml").to_s
  59. if File.exist?(path)
  60. YAML.load(ERB.new(File.read(path)).result)
  61. else
  62. {}
  63. end
  64. end
  65. end
  66. def self.data_sources
  67. @data_sources ||= begin
  68. ds = Hash[
  69. settings["data_sources"].map do |id, s|
  70. [id, Blazer::DataSource.new(id, s)]
  71. end
  72. ]
  73. ds.default = ds.values.first
  74. ds
  75. # TODO Blazer 2.0
  76. # ds2 = Hash.new { |hash, key| raise Blazer::Error, "Unknown data source: #{key}" }
  77. # ds.each do |k, v|
  78. # ds2[k] = v
  79. # end
  80. # ds2
  81. end
  82. end
  83. def self.extract_vars(statement)
  84. # strip commented out lines
  85. # and regex {1} or {1,2}
  86. statement.gsub(/\-\-.+/, "").gsub(/\/\*.+\*\//m, "").scan(/\{\w*?\}/i).map { |v| v[1...-1] }.reject { |v| /\A\d+(\,\d+)?\z/.match(v) || v.empty? }.uniq
  87. end
  88. def self.run_checks(schedule: nil)
  89. checks = Blazer::Check.includes(:query)
  90. checks = checks.where(schedule: schedule) if schedule
  91. checks.find_each do |check|
  92. next if check.state == "disabled"
  93. Safely.safely { run_check(check) }
  94. end
  95. end
  96. def self.run_check(check)
  97. rows = nil
  98. error = nil
  99. tries = 1
  100. ActiveSupport::Notifications.instrument("run_check.blazer", check_id: check.id, query_id: check.query.id, state_was: check.state) do |instrument|
  101. # try 3 times on timeout errors
  102. data_source = data_sources[check.query.data_source]
  103. statement = check.query.statement
  104. Blazer.transform_statement.call(data_source, statement) if Blazer.transform_statement
  105. while tries <= 3
  106. result = data_source.run_statement(statement, refresh_cache: true, check: check, query: check.query)
  107. if result.timed_out?
  108. Rails.logger.info "[blazer timeout] query=#{check.query.name}"
  109. tries += 1
  110. sleep(10)
  111. elsif result.error.to_s.start_with?("PG::ConnectionBad")
  112. data_source.reconnect
  113. Rails.logger.info "[blazer reconnect] query=#{check.query.name}"
  114. tries += 1
  115. sleep(10)
  116. else
  117. break
  118. end
  119. end
  120. check.update_state(result)
  121. # TODO use proper logfmt
  122. Rails.logger.info "[blazer check] query=#{check.query.name} state=#{check.state} rows=#{result.rows.try(:size)} error=#{result.error}"
  123. instrument[:statement] = statement
  124. instrument[:data_source] = data_source
  125. instrument[:state] = check.state
  126. instrument[:rows] = result.rows.try(:size)
  127. instrument[:error] = result.error
  128. instrument[:tries] = tries
  129. end
  130. end
  131. def self.send_failing_checks
  132. emails = {}
  133. Blazer::Check.includes(:query).where(state: ["failing", "error", "timed out", "disabled"]).find_each do |check|
  134. check.split_emails.each do |email|
  135. (emails[email] ||= []) << check
  136. end
  137. end
  138. emails.each do |email, checks|
  139. Safely.safely do
  140. Blazer::CheckMailer.failing_checks(email, checks).deliver_now
  141. end
  142. end
  143. end
  144. def self.adapters
  145. @adapters ||= {}
  146. end
  147. def self.register_adapter(name, adapter)
  148. adapters[name] = adapter
  149. end
  150. end
  151. Blazer.register_adapter "drill", Blazer::Adapters::DrillAdapter
  152. Blazer.register_adapter "bigquery", Blazer::Adapters::BigQueryAdapter
  153. Blazer.register_adapter "elasticsearch", Blazer::Adapters::ElasticsearchAdapter
  154. Blazer.register_adapter "mongodb", Blazer::Adapters::MongodbAdapter
  155. Blazer.register_adapter "presto", Blazer::Adapters::PrestoAdapter
  156. Blazer.register_adapter "sql", Blazer::Adapters::SqlAdapter