blazer.rb 5.7 KB

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