Class: Filbert::Task

Inherits:
Thor
  • Object
show all
Includes:
Thor::Actions
Defined in:
lib/filbert/task.rb

Instance Method Summary collapse

Instance Method Details

#backupObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/filbert/task.rb', line 12

def backup
  say "Looking for the follower DB..."
  db_name = run!("heroku pg:info --app #{options[:app]} | grep -A 1 Followers | awk 'NR==2'").strip
  say "Found the follower: #{db_name}. Capturing..."
  backup_id = run!("heroku pgbackups:capture #{db_name} --expire --app #{options[:app]} | grep backup | awk '/--->/ { print $3}'").strip
  if backup_id != "error"
    say "Backup id: #{backup_id}"
    say "Fetching backup S3 URL"
    backup_url = run!("heroku pgbackups:url #{backup_id} --app #{options[:app]} ").strip.gsub("\"", "")
    say "Downloading #{backup_url}"
    get backup_url, file_path
    say file_path
    Log.new(:backup, db_name, options[:log]).success if File.exists?(file_path) && options[:log]
    invoke :cleanup, [], {}
  else
    say "Error capturing #{db_name}. Run `heroku pgbackups --app #{options[:app]}` to see if there are any transfers in progress."
    exit! 1
  end
end

#cleanupObject



34
35
36
37
38
39
40
41
42
# File 'lib/filbert/task.rb', line 34

def cleanup
  pretend = options[:pretend]
  say "Would remove:" if pretend
  filter = File.join(backups_dir, "*.dump")
  CleanFiles::Cleaner.new(filter, pretend: pretend, verbose: pretend, threshold: 6.months.ago, monthly: true).start
  CleanFiles::Cleaner.new(filter, pretend: pretend, verbose: pretend, threshold: 3.months.ago, weekly: true).start
  CleanFiles::Cleaner.new(filter, pretend: pretend, verbose: pretend, threshold: 3.days.ago,   daily: true).start
  CleanFiles::Cleaner.new(filter, pretend: pretend, verbose: pretend, threshold: 12.hours.ago, hourly: true).start
end

#kill_connectionsObject



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/filbert/task.rb', line 65

def kill_connections
  database = db_config.database
  user = db_config.username

  ENV['PGPASSWORD'] = db_config.password
  sql = "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();"
  run! "echo \"#{sql}\" |  psql -d #{database} -U #{user}"
  say "Killed connections to #{database} as #{user}"
ensure
  ENV['PGPASSWORD'] = nil
end

#restoreObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/filbert/task.rb', line 47

def restore
  most_recent_file = ordered_dumps.last
  check_dump_ready(most_recent_file)

  say "Restoring: #{db_config.database} <--- #{most_recent_file.path}"
  invoke :kill_connections
  ENV['PGPASSWORD'] = db_config.password
  run! "pg_restore --clean --no-acl --no-owner -U #{db_config.username} -d #{db_config.database} -w #{most_recent_file.path}"

rescue Errno::ENOENT
  say "Could not find config file #{options[:config]}. Please pass in --config with a path to database.yml"
ensure
  ENV['PGPASSWORD'] = nil
end