blazer.rb 5.6 KB

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