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:

Defined Under Namespace

Classes: OS

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Connection

rubocop:disable Metrics/ClassLength



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

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)
  @files                  = {}
  @session                = nil
  @transport_options      = @options.delete(:transport_options)
  @cmd_wrapper            = nil
  @cmd_wrapper            = CommandWrapper.load(self, @transport_options)
end

Instance Method Details

#closeObject



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

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

#file(path) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/train/transports/ssh_connection.rb', line 61

def file(path)
  @files[path] ||= \
    if os.aix?
      AixFile.new(self, path)
    elsif os.solaris?
      UnixFile.new(self, path)
    else
      LinuxFile.new(self, path)
    end
end

#login_commandObject



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/train/transports/ssh_connection.rb', line 111

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

#osObject



57
58
59
# File 'lib/train/transports/ssh_connection.rb', line 57

def os
  @os ||= OS.new(self)
end

#run_command(cmd) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/train/transports/ssh_connection.rb', line 73

def run_command(cmd)
  stdout = stderr = ''
  exit_status = nil
  cmd.force_encoding('binary') if cmd.respond_to?(:force_encoding)
  logger.debug("[SSH] #{self} (#{cmd})")

  session.open_channel do |channel|
    # wrap commands if that is configured
    cmd = @cmd_wrapper.run(cmd) unless @cmd_wrapper.nil?

    channel.exec(cmd) do |_, success|
      abort 'Couldn\'t execute command on SSH.' unless success

      channel.on_data do |_, data|
        stdout += data
      end

      channel.on_extended_data do |_, _type, data|
        stderr += data
      end

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

      channel.on_request('exit-signal') do |_, data|
        exit_status = data.read_long
      end
    end
  end
  @session.loop

  CommandResult.new(stdout, stderr, exit_status)
rescue Net::SSH::Exception => ex
  raise Train::Transports::SSHFailed, "SSH command failed (#{ex.message})"
end

#upload(locals, remote) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/train/transports/ssh_connection.rb', line 130

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

    session.scp.upload!(local, remote, opts) do |_ch, name, sent, total|
      logger.debug("Uploaded #{name} (#{total} bytes)") if sent == total
    end
  end
rescue Net::SSH::Exception => ex
  raise Train::Transports::SSHFailed, "SCP upload failed (#{ex.message})"
end

#wait_until_readyObject



143
144
145
146
147
148
149
150
151
152
# File 'lib/train/transports/ssh_connection.rb', line 143

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