Skip to content

Instantly share code, notes, and snippets.

@danhigham
Created February 6, 2013 15:49
Show Gist options
  • Save danhigham/4723434 to your computer and use it in GitHub Desktop.
Save danhigham/4723434 to your computer and use it in GitHub Desktop.
Dump Controller
require 'cfoundry'
require 'tempfile'
require 'zip/zip'
require 'tunnel-vmc-plugin/tunnel'
CF_ENDPOINT = 'http://api.cloudfoundry.com'
class DumpController < ApplicationController
def new
return if request[:user_name].nil?
client = CFoundry::Client.new CF_ENDPOINT
creds = { :username => request[:user_name], :password => request[:password] }
client.login creds
service_name = request[:service_name]
service = client.service_instance_by_name service_name
puts "*" * 100
puts service.inspect
return if service.nil?
tunnel = CFTunnel.new client, service
c = tunnel.open!
return if c.nil?
# prepare temp file to write output to..
tempfile = Tempfile.new(service_name)
cmd = "#{Rails.root}/bin/mysqldump --protocol=TCP --host=#{c['host']} --port=#{c['port']} --user=#{c['user']} --password=#{c['password']} #{c['name']}"
out = `#{cmd}`
tempfile.write out
tempfile.close
temp_zip_file = Tempfile.new("#{service_name}.zip")
temp_folder = temp_zip_file.path.match(/(.+)\/([^\/]+)$/)[1]
backup_time = Time.now.strftime '%Y%m%d-%H%M'
temp_zip_path = "#{temp_folder}/#{service_name}-#{backup_time}.zip"
Zip::ZipFile.open(temp_zip_path, Zip::ZipFile::CREATE) do |zipfile|
zipfile.add('db.sql', tempfile.path)
end
response.headers['Content-Type'] = 'application/octet-stream'
response.headers['Content-Disposition'] = "attachment; filename=#{service_name}.zip"
render :text => open(temp_zip_path).read
# tempfile.unlink
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment