Class: Backupper

Inherits:
Object
  • Object
show all
Defined in:
lib/backupper/version.rb,
lib/backupper/backupper.rb

Constant Summary collapse

VERSION =
'0.3.0'

Instance Method Summary collapse

Constructor Details

#initialize(conf_file_path) ⇒ Backupper

Returns a new instance of Backupper.



18
19
20
21
22
23
24
# File 'lib/backupper/backupper.rb', line 18

def initialize(conf_file_path)
  conf = YAML.load_file(conf_file_path)
  @default = conf['default'] || {}
  @mailer = conf['mailer'] || {}
  @conf = conf.select{|k, v| !%w(default mailer).include?(k) && (v['disabled'].nil? || v['disabled'] == false)}
  @report = {}
end

Instance Method Details

#backup!Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/backupper/backupper.rb', line 26

def backup!
  @conf.each do |k, options|
    puts "⬇️  backing up #{k}..."
    o, err = setup_options(options)
    if err
      error(k, err)
      puts err
      next
    end
    begin
      download_dump(
        key:          k,
        adapter:      o['adapter'],
        url:          o['url'],
        password:     o['password'],
        database:     o['database'],
        db_username:  o['db_username'],
        db_password:  o['db_password'],
        dump_options: o['dump_options'],
        outdir:       o['outdir'],
        extra_copy:   o['extra_copy']
      )
    rescue SSHKit::Runner::ExecuteError => e
      error(k, e.to_s)
      puts e
    end
  end
  send_report_email!
end

#download_dump(key:, adapter: 'mysql', url:, password: nil, database:, db_username: 'root', db_password: nil, dump_options: nil, outdir:, extra_copy: nil) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/backupper/backupper.rb', line 56

def download_dump(key:, adapter: 'mysql', url:, password: nil, database:, db_username: 'root', db_password: nil, dump_options: nil, outdir:, extra_copy: nil)
  t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  path = nil
  filename = "#{key}__#{database}.sql.bz2"
  tempfile = File.join('/tmp', filename)
  dumpname = "#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}__#{filename}"
  path = File.join(outdir, dumpname)
  on(url) do |client|
    client.password = password
    execute 'set -o pipefail; ' + DumpCommand.send(adapter, database: database, username: db_username, password: db_password, dump_options: dump_options, outfile: tempfile)
    download! tempfile, path
    execute :rm, tempfile
  end
  extra_copy = check_dir(extra_copy)
  FileUtils.cp(path, extra_copy) if extra_copy
  @report[key] = {
    path: File.absolute_path(path),
    size: (File.size(path).to_f / 2**20).round(2),
    time: (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t).round(2)
  }
  @report[key].merge!({extra_copy: File.absolute_path(File.join(extra_copy, dumpname))}) if extra_copy
end