class Lhm::Throttler::Slave

Constants

SQL_SELECT_MAX_SLAVE_LAG
SQL_SELECT_SLAVE_HOSTS

Attributes

connection[R]
host[R]

Public Class Methods

new(host, connection_config = nil) click to toggle source
# File lib/lhm/throttler/slave_lag.rb, line 94
def initialize(host, connection_config = nil)
  @host = host
  @connection_config = prepare_connection_config(connection_config)
  @connection = client(@connection_config)
end

Public Instance Methods

lag() click to toggle source
# File lib/lhm/throttler/slave_lag.rb, line 104
def lag
  query_connection(SQL_SELECT_MAX_SLAVE_LAG, 'Seconds_Behind_Master').first.to_i
end
slave_hosts() click to toggle source
# File lib/lhm/throttler/slave_lag.rb, line 100
def slave_hosts
  Throttler.format_hosts(query_connection(SQL_SELECT_SLAVE_HOSTS, 'host'))
end

Private Instance Methods

client(config) click to toggle source
# File lib/lhm/throttler/slave_lag.rb, line 110
def client(config)
  begin
    Lhm.logger.info "Connecting to #{@host} on database: #{config[:database]}"
    Mysql2::Client.new(config)
  rescue Mysql2::Error => e
    Lhm.logger.info "Error connecting to #{@host}: #{e}"
    nil
  end
end
prepare_connection_config(config_proc) click to toggle source
# File lib/lhm/throttler/slave_lag.rb, line 120
def prepare_connection_config(config_proc)
  config = if config_proc
    if config_proc.respond_to?(:call) # if we get a proc
      config_proc.call
    else
      raise ArgumentError, "Expected #{config_proc.inspect} to respond to `call`"
    end
  else # otherwise default to ActiveRecord provided config
    ActiveRecord::Base.connection_pool.spec.config.dup
  end
  config.deep_symbolize_keys!
  config[:host] = @host
  config
end
query_connection(query, result) click to toggle source
# File lib/lhm/throttler/slave_lag.rb, line 135
def query_connection(query, result)
  begin
    @connection.query(query).map { |row| row[result] }
  rescue Mysql2::Error => e
    Lhm.logger.info "Unable to connect and/or query #{host}: #{e}"
    [nil]
  end
end