Skip to content

Instantly share code, notes, and snippets.

@alzabo
Created October 31, 2014 22:16
Show Gist options
  • Save alzabo/a930ccd05179dd9665e7 to your computer and use it in GitHub Desktop.
Save alzabo/a930ccd05179dd9665e7 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby -w
require 'optparse'
require 'augeas'
class Replica
def initialize(host, password=nil, target=nil, port=nil)
@target = target
@password = password
@host = host
@port = port
@health_test = nil
Augeas::open do |aug|
unless @target
# Match the last target that contains a comment referencing the hostname
path = "/files/etc/my.cnf/target[#comment =~ regexp(\".*#@host.*\")][last()]"
@target = aug.get(path)
end
path = "/files/etc/my.cnf/target[. = \"#@target\"]"
@datadir = aug.get("#{path}/datadir")
@socket = aug.get("#{path}/socket")
unless @password
my_cnf = File.expand_path "#@datadir/../../../root/.my.cnf"
path = "/files#{my_cnf}/target[.=\"client\"]"
aug.transform(:lens => 'MySQL.lns', :incl => my_cnf)
aug.load
@password = aug.get("#{path}/password") || aug.get("#{path}/pass")
end
unless @port
aug.match('/files/etc/stunnel/stunnel.conf/*').each do |item|
@port = aug.get("#{item}/accept").split(':')[-1] if item[@host]
end
end
end
end
def enable_replication(start_from_beginning=false,
repl_user=nil,
master_log=nil,
master_log_pos=nil)
unless self.healthy?
res = %x{
"/opt/imh-python/bin/mysqlreplicate"\
"--master=root:#@password@localhost:#@port"\
"--slave=root:#@password@localhost:#@socket"\
"--rpl-user=repl:FOOBAR"\
"--master-log-file=mysql-bin.000001"\
"--master-log-pos=107"
}
puts res
end
end
def health_test
@health_test || @health_test = %x{
"/opt/imh-python/bin/mysqlrpladmin"\
"health"\
"--master=root:#@password@localhost:#@port"\
"--slaves=root:#@password@localhost:#@socket"
}
end
def healthy?
/(.*\blocalhost\b.*\bOK\b.*\n){2}/ =~ self.health_test ? true : false
end
end
options = {}
OptionParser.new do |opt|
opt.on('-s', '--slave-id [ID]',
'Slave server ID as known to mysqld_multi') do |val|
options[:slave] = val
end
opt.on('-p', '--password [PASS]',
'MySQL root password. Should be the same for both databases') do |val|
options[:password] = val
end
opt.on('-h', '--host [HOST]',
'Hostname of master server') do |val|
options[:host] = val
end
end.parse!
bar = Replica.new(options[:host])
puts bar.health_test
puts bar.healthy?
#bar.enable_replication
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment