-
Notifications
You must be signed in to change notification settings - Fork 0
/
rdbsync.rb
executable file
·94 lines (76 loc) · 2.46 KB
/
rdbsync.rb
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/ruby
require 'yaml'
require 'net/ftp'
require "net/http"
require 'json'
WORKING_DIR = Dir.pwd
DUMP_FILENAME = "rdbsync.sql"
SCRIPT_FILENAME = "rdbsync.php"
CONFIG_PATH = File.join(WORKING_DIR, "rdbsync.yml")
CONFIG = YAML::load(File.open(CONFIG_PATH), symbolize_names: true)[:config]
def string_merge_params(string, params)
params.merge!({
dump_filename: DUMP_FILENAME,
script_filename: SCRIPT_FILENAME,
mysql_password_option: (params[:password] ? "-p#{params[:password]}" : "")
})
params.keys.each{|k| string.gsub!(":#{k}", params[k].to_s)}
string
end
def ftp_run
config_ftp = CONFIG[:remote][:ftp]
begin
ftp = Net::FTP.new(config_ftp[:host])
ftp.login config_ftp[:username], config_ftp[:password]
ftp.chdir(config_ftp[:dir])
ftp.put File.join(File.expand_path(File.dirname(__FILE__)), SCRIPT_FILENAME)
yield(ftp) if block_given? # run &block in ftp context
ftp.delete SCRIPT_FILENAME
ftp.delete DUMP_FILENAME
ftp.close
rescue StandardError => e
puts "FTP ERROR: #{e.message}"
puts "#{e.backtrace.join "\n"}"
end
end
def remote_action_url(action)
path = string_merge_params(
":script_filename?action=#{action}&host=:host&username=:username&password=:password&name=:name",
CONFIG[:remote][:db]
)
url = File.join CONFIG[:remote][:url], path
#puts url
url
end
def pull
ftp_run do |f|
remote_url = remote_action_url("remote_export")
result = JSON.parse(Net::HTTP.get(URI.parse(remote_url)))
puts result
f.getbinaryfile(DUMP_FILENAME);
print "import LOCAL? [y/n]:"
local_import if gets.chomp == "y"
end
end
def push
local_export
print "import REMOTE? [y/n]:"
ftp_run do |f|
f.putbinaryfile(DUMP_FILENAME);
remote_url = remote_action_url("remote_import")
result = JSON.parse(Net::HTTP.get(URI.parse(remote_url)))
puts result
end if gets.chomp == "y"
end
def local_import
command = string_merge_params("mysql -h :host -u :username :mysql_password_option :name < :dump_filename", CONFIG[:local][:db])
result = %x[ #{command} ]
puts "LOCAL - IMPORT #{CONFIG[:local][:db][:name]}"
end
def local_export
command = string_merge_params("(mysqldump -h :host -u :username :mysql_password_option :name > :dump_filename) 2>&1", CONFIG[:local][:db])
result = %x[ #{command} ]
puts "LOCAL - EXPORT #{CONFIG[:local][:db][:name]}"
end
puts "usage: ruby rdbsync.rb [push|pull]" if ARGV.length == 0
send(ARGV.shift) if ARGV.length > 0 && defined?(ARGV[0])