Method: TonnelRunner#run

Defined in:
lib/dblink/tonnel_runner.rb

#runObject


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
# File 'lib/dblink/tonnel_runner.rb', line 13

def run
  ssh_command = SSH_TONNEL_COMMAND.gsub('{{local_port}}', @local_port.to_s)

  puts "Copying pem file to tmp folder" if @verbose

  tmp_pem = @tmp_dir + '/share.pem'
  File.open(tmp_pem, 'w') do |file|
    file.write(File.read(PEM_FILE))
  end
  File.chmod(0600, tmp_pem)

  ssh_command.gsub!('{{pem}}', tmp_pem)

  if @verbose
    puts "EXEC #{ssh_command}"
  end
  Open3.popen3(ssh_command) {|stdin, stdout, stderr, wait_thr|
    @runner_pid = wait_thr.pid # pid of the started process.
    #p "process_started: #{pid}"
    Thread.new do
      begin
        while line = stdout.gets
          puts "STDOUT: #{line}" if @verbose
        end
      rescue Exception => error
        puts error.message
        puts error.backtrace
      end
    end
    Thread.new do
      begin
        while line = stderr.gets
          #puts "STDERR: #{line}"
          if line =~ /Allocated port/
            @remote_port = line.match(/Allocated port (\d+)\s/)[1].to_i
            #puts "Remote port: #{@remote_port}"
          end
        end
      rescue Exception => error
        puts error.message
        puts error.backtrace
      end
    end
    exit_status = wait_thr.value # Process::Status object returned.
    puts "SSH tonnel: process stoped: #{exit_status}" if @verbose
  }

  self
end