Class: MysqlBackup::App

Inherits:
Object
  • Object
show all
Defined in:
lib/mysql_backup.rb

Instance Method Summary collapse

Instance Method Details

#_remote_path?(path) ⇒ Boolean

is this path on a remote server? do we need to use scp to copy the backup there?

Returns:

  • (Boolean)


86
87
88
89
# File 'lib/mysql_backup.rb', line 86

def _remote_path?(path)
  # not exactly foolproof, but it will do for now
  path.include? ':'
end

#cleanObject



62
63
64
# File 'lib/mysql_backup.rb', line 62

def clean
  File.delete tmp_path
end

#create_backupObject



43
44
45
46
47
48
49
# File 'lib/mysql_backup.rb', line 43

def create_backup
  password = ''
  password = "-p#{@config.password}" if @config.password?
  options = '--skip-comments'
  tables = @config.tables.join ' '
  run! "mysqldump -u #{@config.username} #{password} --host=#{@config.server} #{options} #{@config.database} #{tables} | gzip > #{tmp_path}"
end

#filenameObject



66
67
68
# File 'lib/mysql_backup.rb', line 66

def filename
  @output_file
end

#mainObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mysql_backup.rb', line 7

def main

  opts = Trollop::options do
    version "mysql-backup #{MysqlBackup::VERSION} (c) 2015 @reednj"
    opt :config, "YAML config file", :type => :string
    opt :filename, "Name of backup output file", :type => :string
  end

  Dir.mkdir tmp_dir if !File.exist? tmp_dir
  @seed = (rand() * 10000).round.to_s

  Trollop::educate unless opts[:config]

  begin
    config_path = opts[:config] || 'mysql-backup.conf'
    @config = BackupConfig.load_from config_path
  rescue => e
    puts "Error: Could not load config file at '#{config_path}' - #{e.message}"
    return
  end
  
  @output_file = opts[:filename] || "#{@config.database}.#{Date.today}.#{@seed}.sql.gz"
  self.create_backup

  @config.save_to.each do |path|
    begin
      self.save path
      puts File.join(path, filename)
    rescue => e
      puts "Could not save backup to #{path} - #{e.message}"
    end
  end

  self.clean
end

#run!(cmd) ⇒ Object

runs a shell command in such a way that if it fails (according to the exit status) and exception will be raised with the stderr output



80
81
82
83
# File 'lib/mysql_backup.rb', line 80

def run!(cmd)
  output = `(#{cmd}) 2>&1`
  raise "#{output}" if $?.exitstatus != 0
end

#save(to_dir) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/mysql_backup.rb', line 51

def save(to_dir)
  if _remote_path? to_dir
    dest = File.join(to_dir, filename)
    run! "scp #{tmp_path} #{dest}"
  else
    p = File.expand_path to_dir
    dest = File.join(p, filename)
    FileUtils.copy tmp_path, dest
  end
end

#tmp_dirObject



70
71
72
# File 'lib/mysql_backup.rb', line 70

def tmp_dir
  File.expand_path "~/.tmp/"
end

#tmp_pathObject



74
75
76
# File 'lib/mysql_backup.rb', line 74

def tmp_path
  File.join tmp_dir, "mysql.#{@seed}.bak"
end