Class: Aptible::CLI::Helpers::Tunnel

Inherits:
Object
  • Object
show all
Defined in:
lib/aptible/cli/helpers/tunnel.rb

Instance Method Summary collapse

Constructor Details

#initialize(env, ssh_cmd) ⇒ Tunnel

Returns a new instance of Tunnel.



8
9
10
11
# File 'lib/aptible/cli/helpers/tunnel.rb', line 8

def initialize(env, ssh_cmd)
  @env = env
  @ssh_cmd = ssh_cmd
end

Instance Method Details

#portObject



75
76
77
78
# File 'lib/aptible/cli/helpers/tunnel.rb', line 75

def port
  fail 'You must call #start before calling #port!' if @local_port.nil?
  @local_port
end

#start(desired_port = 0) ⇒ Object



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
# File 'lib/aptible/cli/helpers/tunnel.rb', line 13

def start(desired_port = 0)
  @local_port = desired_port
  @local_port = random_local_port if @local_port.zero?

  # First, grab a remote port
  out, err, status = Open3.capture3(@env, *@ssh_cmd)
  fail "Failed to request remote port: #{err}" unless status.success?
  remote_port = out.chomp

  # Then, spin up a SSH session using that port and port forwarding.
  # Pass ExitOnForwardFailure to ensure nothing else can be listening
  # on this port (thanks to Diego Argueta for reporting this issue).
  tunnel_env = @env.merge(
    'TUNNEL_PORT' => remote_port, # Request a specific port
    'TUNNEL_SIGNAL_OPEN' => '1'   # Request signal when tunnel is up
  )

  # TODO: Dynamically compose SendEnv from tunnel_env
  tunnel_cmd = @ssh_cmd + [
    '-L', "#{@local_port}:localhost:#{remote_port}",
    '-o', 'SendEnv=TUNNEL_PORT',
    '-o', 'SendEnv=TUNNEL_SIGNAL_OPEN',
    '-o', 'ExitOnForwardFailure=yes'
  ]

  out_read, out_write = IO.pipe
  err_read, err_write = IO.pipe
  @pid = Process.spawn(tunnel_env, *tunnel_cmd, in: :close,
                                                out: out_write,
                                                err: err_write)

  # Wait for the tunnel to come up before returning. The other end
  # will send a message on stdout to indicate that the tunnel is ready.
  [out_write, err_write].map(&:close)
  begin
    out_read.readline
  rescue EOFError
    stop
    e = 'Tunnel did not come up, is something else listening on port ' \
        "#{@local_port}?\n#{err_read.read}"
    raise e
  ensure
    [out_read, err_read].map(&:close)
  end
end

#stopObject



59
60
61
62
63
64
65
66
67
# File 'lib/aptible/cli/helpers/tunnel.rb', line 59

def stop
  fail 'You must call #start before calling #stop' if @pid.nil?
  begin
    Process.kill('HUP', @pid)
  rescue Errno::ESRCH
    nil # Dear Rubocop: I know what I'm doing.
  end
  wait
end

#waitObject



69
70
71
72
73
# File 'lib/aptible/cli/helpers/tunnel.rb', line 69

def wait
  Process.wait @pid
rescue Errno::ECHILD
  nil
end