Class: Train::Transports::SSH::Connection

Inherits:
BaseConnection
  • Object
show all
Defined in:
lib/train/transports/ssh_connection.rb

Overview

A Connection instance can be generated and re-generated, given new connection details such as connection port, hostname, credentials, etc. This object is responsible for carrying out the actions on the remote host such as executing commands, transferring files, etc.

Author:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Connection

Returns a new instance of Connection.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/train/transports/ssh_connection.rb', line 34

def initialize(options)
  super(options)
  @username               = @options.delete(:username)
  @hostname               = @options.delete(:hostname)
  @port                   = @options[:port] # don't delete from options
  @connection_retries     = @options.delete(:connection_retries)
  @connection_retry_sleep = @options.delete(:connection_retry_sleep)
  @max_wait_until_ready   = @options.delete(:max_wait_until_ready)
  @max_ssh_sessions       = @options.delete(:max_ssh_connections) { 9 }
  @session                = nil
  @transport_options      = @options.delete(:transport_options)
  @cmd_wrapper            = nil
  @cmd_wrapper            = CommandWrapper.load(self, @transport_options)
end

Instance Attribute Details

#hostnameObject (readonly)

rubocop:disable Metrics/ClassLength



33
34
35
# File 'lib/train/transports/ssh_connection.rb', line 33

def hostname
  @hostname
end

Instance Method Details

#closeObject



50
51
52
53
54
55
56
# File 'lib/train/transports/ssh_connection.rb', line 50

def close
  return if @session.nil?
  logger.debug("[SSH] closing connection to #{self}")
  session.close
ensure
  @session = nil
end

#download(remotes, local) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/train/transports/ssh_connection.rb', line 93

def download(remotes, local)
  waits = []
  Array(remotes).map do |remote|
    opts = file(remote).directory? ? { recursive: true } : {}
    waits.push session.scp.download(remote, local, opts) do |_ch, name, recv, total|
      logger.debug("Downloaded #{name} (#{total} bytes)") if recv == total
    end
    waits.shift.wait while waits.length >= @max_ssh_sessions
  end
  waits.each(&:wait)
rescue Net::SSH::Exception => ex
  raise Train::Transports::SSHFailed, "SCP download failed (#{ex.message})"
end

#login_commandObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/train/transports/ssh_connection.rb', line 59

def 
  level = logger.debug? ? 'VERBOSE' : 'ERROR'
  fwd_agent = options[:forward_agent] ? 'yes' : 'no'

  args  = %w{ -o UserKnownHostsFile=/dev/null }
  args += %w{ -o StrictHostKeyChecking=no }
  args += %w{ -o IdentitiesOnly=yes } if options[:keys]
  args += %W( -o LogLevel=#{level} )
  args += %W( -o ForwardAgent=#{fwd_agent} ) if options.key?(:forward_agent)
  Array(options[:keys]).each do |ssh_key|
    args += %W( -i #{ssh_key} )
  end
  args += %W( -p #{@port} )
  args += %W( #{@username}@#{@hostname} )

  LoginCommand.new('ssh', args)
end

#upload(locals, remote) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/train/transports/ssh_connection.rb', line 78

def upload(locals, remote)
  waits = []
  Array(locals).each do |local|
    opts = File.directory?(local) ? { recursive: true } : {}

    waits.push session.scp.upload(local, remote, opts) do |_ch, name, sent, total|
      logger.debug("Uploaded #{name} (#{total} bytes)") if sent == total
    end
    waits.shift.wait while waits.length >= @max_ssh_sessions
  end
  waits.each(&:wait)
rescue Net::SSH::Exception => ex
  raise Train::Transports::SSHFailed, "SCP upload failed (#{ex.message})"
end

#uriObject



119
120
121
# File 'lib/train/transports/ssh_connection.rb', line 119

def uri
  "ssh://#{@username}@#{@hostname}:#{@port}"
end

#wait_until_readyObject



108
109
110
111
112
113
114
115
116
117
# File 'lib/train/transports/ssh_connection.rb', line 108

def wait_until_ready
  delay = 3
  session(
    retries: @max_wait_until_ready / delay,
    delay:   delay,
    message: "Waiting for SSH service on #{@hostname}:#{@port}, " \
             "retrying in #{delay} seconds",
  )
  execute(PING_COMMAND.dup)
end