require 'picsolve_docker_builder/base' require 'net/ssh' module PicsolveDockerBuilder module Helpers # Ruby class that can forward a remote port over SSH class SshForward include PicsolveDockerBuilder::Base attr_reader :options def initialize(opts) @options = opts end def connection @connection ||= Net::SSH.start(ssh_host, ssh_user) end def bind_port tries = 0 port = local_port begin connection.forward.local(port, remote_host, remote_port) return port rescue Errno::EADDRINUSE => e # raise after five failed tries raise e if tries > 5 tries += 1 port += 1 retry end end def start log.debug "Connecting via ssh to host '#{ssh_user}@#{ssh_host}'" # bind remote service to local port port = bind_port # start thread with ssh @thread = Thread.new do connection.loop { true } end port end def stop return if @thread.nil? @thread.kill @thread.join log.debug \ "Disconnected ssh connection to host '#{ssh_user}@#{ssh_host}'" end def ssh_user options[:ssh_user] = 'core' end def ssh_host options[:ssh_host] end def remote_host options[:remote_host] end def remote_port options[:remote_port] end def local_port options[:local_port] || remote_port end end end end