Module: Cloner::Postgres

Extended by:
ActiveSupport::Concern
Included in:
Internal
Defined in:
lib/cloner/postgres.rb

Instance Method Summary collapse

Instance Method Details

#ar_confObject



4
5
6
7
8
# File 'lib/cloner/postgres.rb', line 4

def ar_conf
  @conf ||= begin
    YAML.load_file(Rails.root.join('config', 'database.yml'))[Rails.env]
  end
end

#ar_r_confObject



14
15
16
17
18
19
20
21
22
# File 'lib/cloner/postgres.rb', line 14

def ar_r_conf
  @ar_r_conf ||= begin
    Net::SSH.start(ssh_host, ssh_user, ssh_opts) do |ssh|
      ret = ssh_exec!(ssh, "cat #{remote_app_path}/config/database.yml")
      check_ssh_err(ret)
      YAML.load(ret[0])[env_from]
    end
  end
end

#ar_toObject



10
11
12
# File 'lib/cloner/postgres.rb', line 10

def ar_to
  ar_conf['database']
end

#clone_pgObject



77
78
79
80
81
# File 'lib/cloner/postgres.rb', line 77

def clone_pg
  pg_dump_remote()
  pg_dump_copy()
  pg_dump_restore()
end

#pg_dump_copyObject



71
72
73
74
75
# File 'lib/cloner/postgres.rb', line 71

def pg_dump_copy
  FileUtils.mkdir_p(pg_path)
  `mkdir -p #{pg_path}`
  rsync("#{remote_dump_path}/", pg_path)
end

#pg_dump_remoteObject



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/cloner/postgres.rb', line 40

def pg_dump_remote
  puts "backup remote DB via ssh"
  Net::SSH.start(ssh_host, ssh_user, ssh_opts) do |ssh|
    ssh.exec!("rm -R #{remote_dump_path}")
    ret = ssh_exec!(ssh, "mkdir -p #{remote_dump_path}")
    check_ssh_err(ret)
    dump = pg_remote_auth + "pg_dump -Fc -U #{ar_r_conf['username']} #{ar_r_conf['database']} > #{remote_dump_path}/tmp.bak"
    puts dump if verbose?
    ret = ssh_exec!(ssh, dump)
    check_ssh_err(ret)
  end
end

#pg_dump_restoreObject



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/cloner/postgres.rb', line 53

def pg_dump_restore
  puts "restoring DB"
  restore = pg_local_auth + "pg_restore -Fc -U #{ar_conf['username']} -d #{ar_to} #{pg_path}/tmp.bak"
  puts restore if verbose?
  pipe = IO.popen(restore)
  while (line = pipe.gets)
    print line if verbose?
  end
  ret = $?.to_i
  if ret != 0 
    puts "Error: local command exited with #{ret}"
  end
end

#pg_local_authObject



24
25
26
27
28
29
30
# File 'lib/cloner/postgres.rb', line 24

def pg_local_auth
  if ar_conf['password'].nil?
    ""
  else
    "PGPASSWORD='#{ar_conf['password']}' "
  end
end

#pg_pathObject



67
68
69
# File 'lib/cloner/postgres.rb', line 67

def pg_path
  Rails.root.join("tmp", "dump").to_s
end

#pg_remote_authObject



32
33
34
35
36
37
38
# File 'lib/cloner/postgres.rb', line 32

def pg_remote_auth
  if ar_r_conf['password'].nil?
    ""
  else
    "PGPASSWORD='#{ar_r_conf['password']}' "
  end
end