blazer.rb 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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_accessor :user_class
  28. attr_accessor :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.settings
  60. @settings ||= begin
  61. path = Rails.root.join("config", "blazer.yml").to_s
  62. if File.exist?(path)
  63. YAML.load(ERB.new(File.read(path)).result)
  64. else
  65. {}
  66. end
  67. end
  68. end
  69. def self.data_sources
  70. @data_sources ||= begin
  71. ds = Hash[
  72. settings["data_sources"].map do |id, s|
  73. [id, Blazer::DataSource.new(id, s)]
  74. end
  75. ]
  76. ds.default = ds.values.first
  77. ds
  78. # TODO Blazer 2.0
  79. # ds2 = Hash.new { |hash, key| raise Blazer::Error, "Unknown data source: #{key}" }
  80. # ds.each do |k, v|
  81. # ds2[k] = v
  82. # end
  83. # ds2
  84. end
  85. end
  86. def self.extract_vars(statement)
  87. # strip commented out lines
  88. # and regex {1} or {1,2}
  89. statement.gsub(/\-\-.+/, "").gsub(/\/\*.+\*\//m, "").scan(/\{\w*?\}/i).map { |v| v[1...-1] }.reject { |v| /\A\d+(\,\d+)?\z/.match(v) || v.empty? }.uniq
  90. end
  91. def self.run_checks(schedule: nil)
  92. checks = Blazer::Check.includes(:query)
  93. checks = checks.where(schedule: schedule) if schedule
  94. checks.find_each do |check|
  95. next if check.state == "disabled"
  96. Safely.safely { run_check(check) }
  97. end
  98. end
  99. def self.run_check(check)
  100. rows = nil
  101. error = nil
  102. tries = 1
  103. ActiveSupport::Notifications.instrument("run_check.blazer", check_id: check.id, query_id: check.query.id, state_was: check.state) do |instrument|
  104. # try 3 times on timeout errors
  105. data_source = data_sources[check.query.data_source]
  106. statement = check.query.statement
  107. Blazer.transform_statement.call(data_source, statement) if Blazer.transform_statement
  108. while tries <= 3
  109. result = data_source.run_statement(statement, refresh_cache: true, check: check, query: check.query)
  110. if result.timed_out?
  111. Rails.logger.info "[blazer timeout] query=#{check.query.name}"
  112. tries += 1
  113. sleep(10)
  114. elsif result.error.to_s.start_with?("PG::ConnectionBad")
  115. data_source.reconnect
  116. Rails.logger.info "[blazer reconnect] query=#{check.query.name}"
  117. tries += 1
  118. sleep(10)
  119. else
  120. break
  121. end
  122. end
  123. begin
  124. check.reload # in case state has changed since job started
  125. check.update_state(result)
  126. rescue ActiveRecord::RecordNotFound
  127. # check deleted
  128. end
  129. # TODO use proper logfmt
  130. Rails.logger.info "[blazer check] query=#{check.query.name} state=#{check.state} rows=#{result.rows.try(:size)} error=#{result.error}"
  131. instrument[:statement] = statement
  132. instrument[:data_source] = data_source
  133. instrument[:state] = check.state
  134. instrument[:rows] = result.rows.try(:size)
  135. instrument[:error] = result.error
  136. instrument[:tries] = tries
  137. end
  138. end
  139. def self.send_failing_checks
  140. emails = {}
  141. Blazer::Check.includes(:query).where(state: ["failing", "error", "timed out", "disabled"]).find_each do |check|
  142. check.split_emails.each do |email|
  143. (emails[email] ||= []) << check
  144. end
  145. end
  146. emails.each do |email, checks|
  147. Safely.safely do
  148. Blazer::CheckMailer.failing_checks(email, checks).deliver_now
  149. end
  150. end
  151. end
  152. def self.adapters
  153. @adapters ||= {}
  154. end
  155. def self.register_adapter(name, adapter)
  156. adapters[name] = adapter
  157. end
  158. end
  159. Blazer.register_adapter "athena", Blazer::Adapters::AthenaAdapter
  160. Blazer.register_adapter "bigquery", Blazer::Adapters::BigQueryAdapter
  161. Blazer.register_adapter "cassandra", Blazer::Adapters::CassandraAdapter
  162. Blazer.register_adapter "drill", Blazer::Adapters::DrillAdapter
  163. Blazer.register_adapter "druid", Blazer::Adapters::DruidAdapter
  164. Blazer.register_adapter "elasticsearch", Blazer::Adapters::ElasticsearchAdapter
  165. Blazer.register_adapter "presto", Blazer::Adapters::PrestoAdapter
  166. Blazer.register_adapter "mongodb", Blazer::Adapters::MongodbAdapter
  167. Blazer.register_adapter "sql", Blazer::Adapters::SqlAdapter