Class: RedSnapper

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

Defined Under Namespace

Classes: Group

Constant Summary collapse

TARSNAP =
'tarsnap'
THREAD_POOL_SIZE =
10

Instance Method Summary collapse

Constructor Details

#initialize(archive, options = {}) ⇒ RedSnapper

Returns a new instance of RedSnapper.



24
25
26
27
28
# File 'lib/redsnapper.rb', line 24

def initialize(archive, options = {})
  @archive = archive
  @options = options
  @thread_pool_size = options[:thread_pool_size] || THREAD_POOL_SIZE
end

Instance Method Details

#file_groupsObject



64
65
66
67
68
69
70
# File 'lib/redsnapper.rb', line 64

def file_groups
  groups = (1..@thread_pool_size).map { Group.new }
  files.sort { |a, b| b.last <=> a.last }.each do |file|
    groups.sort.last.add(*file)
  end
  groups.map(&:files)
end

#filesObject



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
55
56
57
58
59
60
61
62
# File 'lib/redsnapper.rb', line 30

def files
  command = [ TARSNAP, '-tvf', @archive, *@options[:tarsnap_options] ]
  command.push(@options[:directory]) if @options[:directory]

  files = {}
  dirs = Set.new

  Open3.popen3(*command) do |_, out, _|
    out.gets(nil).split("\n").each do |entry|
      (_, _, _, _, size, _, _, _, name) = entry.split(/\s+/, 9)
      if name.end_with?('/')
        dirs.add(name)
      else
        files[name] = size.to_i
      end
    end
  end

  files.each { |f, _| dirs.delete(File.dirname(f) + '/') }

  empty_dirs = dirs.clone

  dirs.each do |dir|
    components = dir.split('/')
    components.each_with_index do |component, i|
      empty_dirs.delete(components[0, i].join('/') + '/')
    end
  end

  empty_dirs.each { |dir| files[dir] = 0 }

  files
end

#runObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/redsnapper.rb', line 72

def run
  pool = Thread.pool(@thread_pool_size)
  mutex = Mutex.new

  file_groups.each do |chunk|
    pool.process do
      command = [ TARSNAP, '-xvf', @archive, *(@options[:tarsnap_options] + chunk) ]
      Open3.popen3(*command) do |_, _, err|
        while line = err.gets
          mutex.synchronize { warn line.chomp }
        end
      end
    end
  end

  pool.shutdown
end