Skip to content

Instantly share code, notes, and snippets.

@huobazi
Created June 8, 2011 08:17
Show Gist options
  • Save huobazi/1014023 to your computer and use it in GitHub Desktop.
Save huobazi/1014023 to your computer and use it in GitHub Desktop.
Pulls sql from a remote server
#!/usr/bin/env ruby
# in the app's folder on your computer
# tube pull user@host:app_path [--from_env=production] [--to_env=development]
#
# e.g:
# tube pull host:apps/myapp
# tube pull user@host:/apps/myapp
require 'rubygems'
require 'net/ssh'
require 'thor'
require 'yaml'
def extract_host_options(host_path)
options = {}
options[:host], options[:path] = host_path.sub(/\/$/, '').split(":")
options[:user] = nil
if (host_and_user = options[:host].split("@")).size == 2
options[:user], options[:host] = host_and_user
end
options
end
class Tube < Thor
desc "pull HOST:PATH", "grabs sql from remote application"
method_options :from_env => 'production', :to_env => 'development'
def pull(host_path)
host_opts = extract_host_options(host_path)
dump = ""
say "Connecting to #{host_opts[:host]}...", :yellow
remote = false
begin
Net::SSH.start(host_opts[:host], host_opts[:user]) do |ssh|
stdout = ""
config_path = "#{host_opts[:path]}/config/database.yml"
ssh.exec!("cat #{config_path}") do |channel, stream, data|
stdout << data if stream == :stdout
end
hostname = ssh.exec!("hostname").strip
if remote = (c = YAML.load(stdout)) && c[options[:from_env]]
dump = "tmp/#{hostname}_#{remote['database']}_#{Time.now.strftime("%Y-%m-%d-%H-%M")}.sql.gz"
say "Dumping sql", :yellow
ssh.exec!("mysqldump -u#{remote['username']} -p#{remote['password']} #{remote['database']} | gzip > #{host_opts[:path]}/#{dump}")
else
say "Can't read #{config_path} on #{host_opts[:host]}", :red
end
end
rescue Errno::ECONNREFUSED
say "Can't connect to #{host_opts[:host]}", :red
end
if remote
say "Downloading to #{dump}", :yellow
`scp #{host_path}/#{dump} tmp/`
local = YAML.load_file(File.join(Dir.pwd, 'config/database.yml'))[options[:to_env]]
say "Loading into #{options[:to_env]} environment", :yellow
`gunzip -c #{dump} | mysql -u#{local['username']} #{local['password'] ? "-p#{local['password']}" : ''} #{local['database']}`
end
end
end
Tube.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment