-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbackup.rb
More file actions
54 lines (47 loc) · 1.59 KB
/
backup.rb
File metadata and controls
54 lines (47 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
require 'dropbox'
require 'date'
##################
# Setup
##################
dropbox_access_token = 'user_access_token'
db_user = "rails" # User to access database
db_pass = "db_pass" # password of the user to access database
db_to_backup = "app_production" # name of the database to backup
###################
# Naming & paths
###################
now = Time.now
backup_name = "#{now.to_s.gsub(' ', '_')}.pg_dump" # name of the created backup file
backup_file_path = "/tmp/#{backup_name}"
backup_files = "/tmp/*.pg_dump"
backup_folder = "/#{db_to_backup}"
oldest_backup_date = (now.to_datetime << 1).to_time # More than a month old
#############################
# Backup & upload to dropbox
#############################
print "Backing up #{db_to_backup}\n"
system(
"PGPASSWORD=\"#{db_pass}\" " +
"pg_dump " +
"-U #{db_user} " + # user
"-Fc " + # Format=custom
"-a " + # data only
"-h localhost " + # host
"-p 5432 " + # port
db_to_backup +
" > #{backup_file_path}"
)
print "Uploading #{backup_file_path} to #{backup_folder}/#{backup_name} (~#{(File.size(backup_file_path) / (1024 * 1024)).round(2)} MB)\n"
client = Dropbox::Client.new(dropbox_access_token)
client.upload "#{backup_folder}/#{backup_name}", File.read(backup_file_path)
#####################
# Delete old backups in dropbox
#####################
files = client.list_folder backup_folder
files.each do |file|
if file.server_modified < oldest_backup_date
print "Detected #{file.path_lower} is older than permitted date, deleting...\n"
client.delete file.path_lower
end
end
system("rm", backup_files)