Class: Rubber::Commands::Backup

Inherits:
Clamp::Command
  • Object
show all
Defined in:
lib/rubber/commands/util.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.descriptionObject



69
70
71
# File 'lib/rubber/commands/util.rb', line 69

def self.description
  "Performs a cyclical backup by storing the results of COMMAND to the backup\ndirectory (and the cloud)"
end

.subcommand_descriptionObject



65
66
67
# File 'lib/rubber/commands/util.rb', line 65

def self.subcommand_description
  "Performs a cyclical backup"
end

.subcommand_nameObject



61
62
63
# File 'lib/rubber/commands/util.rb', line 61

def self.subcommand_name
  "util:backup"
end

Instance Method Details

#executeObject



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/rubber/commands/util.rb', line 88

def execute
  signal_usage_error "NAME, DIRECTORY and COMMAND are required" unless name && directory && command
  
  # extra variables for command interpolation
  time_stamp = Time.now.strftime("%Y-%m-%d_%H-%M")
  dir = directory
  
  # differentiate by env
  cloud_prefix = "#{name}/"
  self.name = "#{Rubber.env}_#{self.name}"

  FileUtils.mkdir_p(directory)

  backup_cmd = command.gsub(/%([^%]+)%/, '#{\1}')
  backup_cmd = eval('%Q{' + backup_cmd + '}')

  puts "Backing up with command: '#{backup_cmd}'"
  system backup_cmd || fail("Command failed: '#{backup_cmd.inspect}'")
  puts "Backup created"

  backup_bucket = Rubber.cloud.env.backup_bucket
  if backup_bucket
    newest = Dir.entries(directory).grep(/^[^.]/).sort_by {|f| File.mtime(File.join(directory,f))}.last
    dest = "#{cloud_prefix}#{newest}"
    puts "Saving backup to cloud: #{backup_bucket}:#{dest}"
    Rubber.cloud.storage(backup_bucket).store(dest, open(File.join(directory, newest)))
  end

  tdate = Date.today - age
  threshold = Time.local(tdate.year, tdate.month, tdate.day)
  puts "Cleaning backups older than #{age} days"
  Dir["#{directory}/*"].each do |file|
    if File.mtime(file) < threshold
      puts "Deleting #{file}"
      FileUtils.rm_f(file)
    end
  end

  if backup_bucket
    puts "Cleaning cloud backups older than #{age} days from: #{backup_bucket}:#{cloud_prefix}"
    Rubber.cloud.storage(backup_bucket).walk_tree(cloud_prefix) do |f|
      if f.last_modified < threshold
        puts "Deleting #{f.key}"
        f.destroy
      end
    end
  end
end