Sha256: 1c91079e854a4955b15e1463d98c799aee8b515324fc9633a1e248d57e01be8b

Contents?: true

Size: 1.21 KB

Versions: 29

Compression:

Stored size: 1.21 KB

Contents

require 'socket'

module Fulmar
  module Infrastructure
    module Service
      # Opens an ssh tunnel to a remote host so other services can access mysql for example
      class TunnelService
        attr_reader :host, :remote_port, :local_port

        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

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

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

        def open?
          @tunnel_pid > 0
        end

        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
      end
    end
  end
end

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
fulmar-2.2.6 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.2.5 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.2.4 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.2.3 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.2.2 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.2.1 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.2.0 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.1.2 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.1.1 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.1.0 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.0.2 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.0.1 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-2.0.0 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-1.10.1 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-1.10.0 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-1.9.2 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-1.9.1 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-1.9.0 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-1.8.15 lib/fulmar/infrastructure/service/tunnel_service.rb
fulmar-1.8.14 lib/fulmar/infrastructure/service/tunnel_service.rb