Class: MysqlS3Backup::Mysql

Inherits:
Object
  • Object
show all
Includes:
Shell
Defined in:
lib/mysql_s3_backup/mysql.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Shell

#run

Constructor Details

#initialize(options) ⇒ Mysql

Returns a new instance of Mysql.



7
8
9
10
11
12
13
14
# File 'lib/mysql_s3_backup/mysql.rb', line 7

def initialize(options)
  options = options.symbolize_keys
  @user = options[:user] || raise(ArgumentError, "user required")
  @password = options[:password]
  @database = options[:database] || raise(ArgumentError, "database required")
  @bin_log_path = options[:bin_log]
  @bin_path = options[:bin_path]
end

Instance Attribute Details

#bin_log_pathObject (readonly)

Returns the value of attribute bin_log_path.



5
6
7
# File 'lib/mysql_s3_backup/mysql.rb', line 5

def bin_log_path
  @bin_log_path
end

#databaseObject (readonly)

Returns the value of attribute database.



5
6
7
# File 'lib/mysql_s3_backup/mysql.rb', line 5

def database
  @database
end

Instance Method Details

#apply_bin_log(file) ⇒ Object



53
54
55
56
57
# File 'lib/mysql_s3_backup/mysql.rb', line 53

def apply_bin_log(file)
  cmd = "#{@bin_path}mysqlbinlog --database=#{@database} #{file} | mysql -u#{@user} "
  cmd += " -p'#{@password}' " if @password
  run cmd
end

#cli_optionsObject



16
17
18
19
20
21
# File 'lib/mysql_s3_backup/mysql.rb', line 16

def cli_options
  cmd = "-u'#{@user}'"
  cmd += " -p'#{@password}'" if @password
  cmd += " #{@database}"
  cmd
end

#dump(file) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/mysql_s3_backup/mysql.rb', line 31

def dump(file)
  cmd = "#{@bin_path}mysqldump --quick --single-transaction --create-options -u'#{@user}'"
  cmd += " --flush-logs --master-data=2 --delete-master-logs" if @bin_log_path
  cmd += " -p'#{@password}'" if @password
  cmd += " #{@database} | gzip > #{file}"
  run cmd
end

#each_bin_logObject



43
44
45
46
47
48
49
50
51
# File 'lib/mysql_s3_backup/mysql.rb', line 43

def each_bin_log
  execute "flush logs"
  logs = Dir.glob("#{@bin_log_path}.[0-9]*").sort
  logs_to_archive = logs[0..-2] # all logs except the last
  logs_to_archive.each do |log|
    yield log
  end
  execute "purge master logs to '#{File.basename(logs[-1])}'"
end

#execute(sql) ⇒ Object



23
24
25
# File 'lib/mysql_s3_backup/mysql.rb', line 23

def execute(sql)
  run %{#{@bin_path}mysql -e "#{sql}" #{cli_options}}
end

#execute_file(file) ⇒ Object



27
28
29
# File 'lib/mysql_s3_backup/mysql.rb', line 27

def execute_file(file)
  run "cat '#{file}' | #{@bin_path}mysql #{cli_options}"
end

#restore(file) ⇒ Object



39
40
41
# File 'lib/mysql_s3_backup/mysql.rb', line 39

def restore(file)
  run "gunzip -c #{file} | #{@bin_path}mysql #{cli_options}"
end