Class: Aptible::CLI::Helpers::Tunnel
- Inherits:
-
Object
- Object
- Aptible::CLI::Helpers::Tunnel
- Defined in:
- lib/aptible/cli/helpers/tunnel.rb
Instance Method Summary collapse
-
#initialize(env, cmd) ⇒ Tunnel
constructor
A new instance of Tunnel.
- #port ⇒ Object
- #start(desired_port = 0, err_fd = $stderr) ⇒ Object
- #stop ⇒ Object
- #wait ⇒ Object
Constructor Details
#initialize(env, cmd) ⇒ Tunnel
Returns a new instance of Tunnel.
8 9 10 11 |
# File 'lib/aptible/cli/helpers/tunnel.rb', line 8 def initialize(env, cmd) @env = env @cmd = cmd end |
Instance Method Details
#port ⇒ Object
59 60 61 62 |
# File 'lib/aptible/cli/helpers/tunnel.rb', line 59 def port fail 'You must call #start before calling #port!' if @local_port.nil? @local_port end |
#start(desired_port = 0, err_fd = $stderr) ⇒ 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 |
# File 'lib/aptible/cli/helpers/tunnel.rb', line 13 def start(desired_port = 0, err_fd = $stderr) @local_port = desired_port @local_port = random_local_port if @local_port == 0 # First, grab a remote port out, err, status = Open3.capture3(@env, *@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 tunnel_env = @env.merge( 'TUNNEL_PORT' => remote_port, # Request a specific port 'TUNNEL_SIGNAL_OPEN' => '1' # Request signal when tunnel is up ) tunnel_cmd = @cmd + [ '-L', "#{@local_port}:localhost:#{remote_port}", '-o', 'SendEnv=TUNNEL_PORT', '-o', 'SendEnv=TUNNEL_SIGNAL_OPEN' ] r_pipe, w_pipe = IO.pipe @pid = Process.spawn(tunnel_env, *tunnel_cmd, in: :close, out: w_pipe, err: err_fd) # 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. w_pipe.close begin r_pipe.readline rescue EOFError raise 'Server closed the tunnel' end end |
#stop ⇒ Object
49 50 51 52 53 |
# File 'lib/aptible/cli/helpers/tunnel.rb', line 49 def stop fail 'You must call #start before calling #stop' if @pid.nil? Process.kill('HUP', @pid) wait end |
#wait ⇒ Object
55 56 57 |
# File 'lib/aptible/cli/helpers/tunnel.rb', line 55 def wait Process.wait @pid end |