BigW Consortium Gitlab

files.rb 1.76 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, '..'))
11
      @backup_files_dir = File.join(Gitlab.config.backup.path, File.basename(@app_files_dir) )
Jacob Vosmaer committed
12
      @backup_tarball = File.join(Gitlab.config.backup.path, name + '.tar.gz')
13 14 15 16 17
    end

    # Copy files from public/files to backup/files
    def dump
      FileUtils.mkdir_p(Gitlab.config.backup.path)
18
      FileUtils.rm_f(backup_tarball)
19 20 21 22 23 24 25 26 27 28

      if ENV['STRATEGY'] == 'copy'
        cmd = %W(cp -a #{app_files_dir} #{Gitlab.config.backup.path})
        output, status = Gitlab::Popen.popen(cmd)

        unless status.zero?
          puts output
          abort 'Backup failed'
        end

29
        run_pipeline!([%W(tar -C #{@backup_files_dir} -cf - .), %w(gzip -c -1)], out: [backup_tarball, 'w', 0600])
30 31
        FileUtils.rm_rf(@backup_files_dir)
      else
32
        run_pipeline!([%W(tar -C #{app_files_dir} -cf - .), %w(gzip -c -1)], out: [backup_tarball, 'w', 0600])
33
      end
34 35 36 37
    end

    def restore
      backup_existing_files_dir
38
      create_files_dir
39

40
      run_pipeline!([%w(gzip -cd), %W(tar -C #{app_files_dir} -xf -)], in: backup_tarball)
41 42 43 44
    end

    def backup_existing_files_dir
      timestamped_files_path = File.join(files_parent_dir, "#{name}.#{Time.now.to_i}")
45
      if File.exist?(app_files_dir)
46 47 48 49
        FileUtils.mv(app_files_dir, File.expand_path(timestamped_files_path))
      end
    end

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