Class: Kitchen::Transport::Ssh::Connection

Inherits:
Base::Connection show all
Defined in:
lib/kitchen/transport/ssh.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 Method Summary collapse

Methods inherited from Base::Connection

#execute_with_retry, #retry?

Methods included from Logging

#banner, #debug, #error, #fatal, #info, #warn

Constructor Details

#initialize(config = {}) {|self| ... } ⇒ Object

Create a new Connection instance.

Yields:

  • (self)

    yields itself for block-style invocation



125
126
127
128
# File 'lib/kitchen/transport/ssh.rb', line 125

def initialize(config = {})
  super(config)
  @session = nil
end

Instance Method Details

#closeObject

Closes the session connection, if it is still active.



131
132
133
134
135
136
137
138
139
140
# File 'lib/kitchen/transport/ssh.rb', line 131

def close
  return if @session.nil?

  string_to_mask = "[SSH] closing connection to #{self}"
  masked_string = Util.mask_values(string_to_mask, %w{password ssh_http_proxy_password})
  logger.debug(masked_string)
  session.close
ensure
  @session = nil
end

#download(remotes, local) ⇒ Object

Download remote files or directories to local host.

Raises:

  • (TransportFailed)

    if the files could not all be downloaded successfully, which may vary by implementation



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/kitchen/transport/ssh.rb', line 207

def download(remotes, local)
  # ensure the parent dir of the local target exists
  FileUtils.mkdir_p(File.dirname(local))

  Array(remotes).each do |file|
    logger.debug("Attempting to download '#{file}' as file")
    session.scp.download!(file, local)
  rescue Net::SCP::Error
    begin
      logger.debug("Attempting to download '#{file}' as directory")
      session.scp.download!(file, local, recursive: true)
    rescue Net::SCP::Error
      logger.warn(
        "SCP download failed for file or directory '#{file}', perhaps it does not exist?"
      )
    end
  end
rescue Net::SSH::Exception => ex
  raise SshFailed, "SCP download failed (#{ex.message})"
end

#execute(command) ⇒ Object

Execute a command on the remote host.

Raises:

  • (TransportFailed)

    if the command does not exit successfully, which may vary by implementation



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/kitchen/transport/ssh.rb', line 143

def execute(command)
  return if command.nil?

  string_to_mask = "[SSH] #{self} (#{command})"
  masked_string = Util.mask_values(string_to_mask, %w{password ssh_http_proxy_password})
  logger.debug(masked_string)
  exit_code = execute_with_exit_code(command)

  if exit_code != 0
    raise Transport::SshFailed.new(
      "SSH exited (#{exit_code}) for command: [#{command}]",
      exit_code
    )
  end
rescue Net::SSH::Exception => ex
  raise SshFailed, "SSH command failed (#{ex.message})"
end

#login_commandLoginCommand

Builds a LoginCommand which can be used to open an interactive session on the remote host.

Raises:



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/kitchen/transport/ssh.rb', line 162

def 
  args  = %w{ -o UserKnownHostsFile=/dev/null }
  args += %w{ -o StrictHostKeyChecking=no }
  args += %w{ -o IdentitiesOnly=yes } if options[:keys]
  args += %W{ -o LogLevel=#{logger.debug? ? "VERBOSE" : "ERROR"} }
  if options.key?(:forward_agent)
    args += %W{ -o ForwardAgent=#{options[:forward_agent] ? "yes" : "no"} }
  end
  if ssh_proxy_command
    args += %W{ -o ProxyCommand=#{ssh_proxy_command} }
  elsif ssh_gateway
    gateway_command = "ssh -q #{ssh_gateway_username}@#{ssh_gateway} nc #{hostname} #{port}"
    args += %W{ -o ProxyCommand=#{gateway_command} -p #{ssh_gateway_port} }
  end
  Array(options[:keys]).each { |ssh_key| args += %W{ -i #{ssh_key} } }
  args += %W{ -p #{port} }
  args += %W{ #{username}@#{hostname} }

  LoginCommand.new("ssh", args)
end

#upload(locals, remote) ⇒ Object

Uploads local files or directories to remote host.

Raises:

  • (TransportFailed)

    if the files could not all be uploaded successfully, which may vary by implementation



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/kitchen/transport/ssh.rb', line 184

def upload(locals, remote)
  logger.debug("TIMING: scp async upload (Kitchen::Transport::Ssh)")
  elapsed = Benchmark.measure do
    waits = []
    Array(locals).map do |local|
      opts = File.directory?(local) ? { recursive: true } : {}

      waits.push(
        session.scp.upload(local, remote, opts) do |_ch, name, sent, total|
          logger.debug("Async Uploaded #{name} (#{total} bytes)") if sent == total
        end
      )
      waits.shift.wait while waits.length >= max_ssh_sessions
    end
    waits.each(&:wait)
  end
  delta = Util.duration(elapsed.real)
  logger.debug("TIMING: scp async upload (Kitchen::Transport::Ssh) took #{delta}")
rescue Net::SSH::Exception => ex
  raise SshFailed, "SCP upload failed (#{ex.message})"
end

#wait_until_readyObject

Block and return only when the remote host is prepared and ready to execute command and upload files. The semantics and details will vary by implementation, but a round trip through the hosted service is preferred to simply waiting on a socket to become available.



229
230
231
232
233
234
235
236
237
238
# File 'lib/kitchen/transport/ssh.rb', line 229

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