class Indocker::SshSession

Constants

LOCALHOST

Attributes

host[R]
logger[R]
port[R]
user[R]

Public Class Methods

new(host:, user:, port:, logger:) click to toggle source
# File lib/indocker/ssh_session.rb, line 24
def initialize(host:, user:, port:, logger:)
  @host = host
  @user = user
  @port = port
  @logger = logger

  if host != LOCALHOST
    require 'net/ssh'
    @ssh = Net::SSH.start(@host, @user, {port: @port})
  end
end

Public Instance Methods

close() click to toggle source
# File lib/indocker/ssh_session.rb, line 48
def close
  if @ssh
    @ssh.close
  end
end
exec!(command) click to toggle source
# File lib/indocker/ssh_session.rb, line 40
def exec!(command)
  if local?
    exec_locally!(command)
  else
    exec_remotely!(command)
  end
end
local?() click to toggle source
# File lib/indocker/ssh_session.rb, line 36
def local?
  !@ssh
end

Private Instance Methods

exec_locally!(command) click to toggle source
# File lib/indocker/ssh_session.rb, line 55
def exec_locally!(command)
  res = Indocker::Shell.command_with_result(command, @logger, skip_logging: false)
  ExecResult.new(res.stdout, '', res.exit_status, nil)
end
exec_remotely!(command) click to toggle source
# File lib/indocker/ssh_session.rb, line 60
def exec_remotely!(command)
  if Indocker.export_command
    command = "#{Indocker.export_command} && #{command}"
  end

  stdout_data = ''
  stderr_data = ''
  exit_code = nil
  exit_signal = nil

  @logger.debug("(#{@user}:#{@host}:#{@port}): executing command: #{command}")

  @ssh.open_channel do |channel|
    channel.exec(command) do |ch, success|
      if !success
        @logger.error("(#{@user}@#{@host}:#{@port}): couldn't execute command: #{command}")
        abort('failed')
      end

      channel.on_data do |ch,data|
        stdout_data += data
      end

      channel.on_extended_data do |ch,type,data|
        stderr_data += data
      end

      channel.on_request('exit-status') do |ch,data|
        exit_code = data.read_long
      end

      channel.on_request('exit-signal') do |ch, data|
        exit_signal = data.read_long
      end
    end
  end

  @ssh.loop

  ExecResult.new(stdout_data, stderr_data, exit_code, exit_signal)
end