BigW Consortium Gitlab

files.rb 1.25 KB
Newer Older
1 2 3 4
require 'open3'

module Backup
  class Files
Jacob Vosmaer committed
5
    attr_reader :name, :app_files_dir, :backup_tarball, :files_parent_dir
6

7 8
    def initialize(name, app_files_dir)
      @name = name
9 10
      @app_files_dir = File.realpath(app_files_dir)
      @files_parent_dir = File.realpath(File.join(@app_files_dir, '..'))
Jacob Vosmaer committed
11
      @backup_tarball = File.join(Gitlab.config.backup.path, name + '.tar.gz')
12 13 14 15 16
    end

    # Copy files from public/files to backup/files
    def dump
      FileUtils.mkdir_p(Gitlab.config.backup.path)
17
      FileUtils.rm_f(backup_tarball)
18
      run_pipeline!([%W(tar -C #{app_files_dir} -cf - .), %W(gzip -c -1)], out: [backup_tarball, 'w', 0600])
19 20 21 22
    end

    def restore
      backup_existing_files_dir
23
      create_files_dir
24

25
      run_pipeline!([%W(gzip -cd), %W(tar -C #{app_files_dir} -xf -)], in: backup_tarball)
26 27 28 29
    end

    def backup_existing_files_dir
      timestamped_files_path = File.join(files_parent_dir, "#{name}.#{Time.now.to_i}")
30
      if File.exist?(app_files_dir)
31 32 33 34 35 36 37 38 39 40
        FileUtils.mv(app_files_dir, File.expand_path(timestamped_files_path))
      end
    end

    def run_pipeline!(cmd_list, options={})
      status_list = Open3.pipeline(*cmd_list, options)
      abort 'Backup failed' unless status_list.compact.all?(&:success?)
    end
  end
end