Class: Fulmar::Infrastructure::Service::TunnelService

Inherits:
Object
  • Object
show all
Defined in:
lib/fulmar/infrastructure/service/tunnel_service.rb

Overview

Opens an ssh tunnel to a remote host so other services can access mysql for example

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, remote_host = 'localhost') ⇒ TunnelService

Returns a new instance of TunnelService.



10
11
12
13
14
15
16
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 10

def initialize(host, port, remote_host = 'localhost')
  @host = host
  @remote_port = port
  @remote_host = remote_host.nil? ? 'localhost' : remote_host
  @local_port = 0
  @tunnel_pid = 0
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



8
9
10
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 8

def host
  @host
end

#local_portObject (readonly)

Returns the value of attribute local_port.



8
9
10
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 8

def local_port
  @local_port
end

#remote_portObject (readonly)

Returns the value of attribute remote_port.



8
9
10
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 8

def remote_port
  @remote_port
end

Instance Method Details

#closeObject



24
25
26
27
28
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 24

def close
  Process.kill 'TERM', @tunnel_pid if @tunnel_pid > 0
  @local_port = 0
  @tunnel_pid = 0
end

#free_portObject



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 34

def free_port
  (60_000..61_000).each do |port|
    begin
      socket = TCPSocket.new('localhost', port)
      socket.close
    rescue Errno::ECONNREFUSED
      return port
    end
  end

  fail 'Cannot find an open local port'
end

#openObject



18
19
20
21
22
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 18

def open
  @local_port = free_port
  @tunnel_pid = Process.spawn "ssh #{@host} -q -L #{@local_port}:#{@remote_host}:#{@remote_port} -N"
  sleep 1
end

#open?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/fulmar/infrastructure/service/tunnel_service.rb', line 30

def open?
  @tunnel_pid > 0
end