blazer.rb 6.2 KB

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