Class: Chef::Provisioning::Transport::SSH

Inherits:
Chef::Provisioning::Transport show all
Defined in:
lib/chef/provisioning/transport/ssh.rb

Defined Under Namespace

Classes: InitialConnectTimeout, SSHResult

Constant Summary

Constants inherited from Chef::Provisioning::Transport

DEFAULT_TIMEOUT

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, username, ssh_options, options, global_config) ⇒ SSH

Create a new SSH transport.

Arguments

  • host: the host to connect to, e.g. ‘145.14.51.45’

  • username: the username to connect with

  • ssh_options: a list of options to Net::SSH.start

  • options: a hash of options for the transport itself, including:

    • :prefix: a prefix to send before each command (e.g. “sudo ”)

    • :ssh_pty_enable: set to false to disable pty (some instances don’t support this, most do)

    • :ssh_gateway: the gateway to use, e.g. “[email protected]:222”. nil (the default) means no gateway.

  • global_config: an options hash that looks suspiciously similar to Chef::Config, containing at least the key :log_level.

The options are used in

Net::SSH.start(host, username, ssh_options)


34
35
36
37
38
39
40
# File 'lib/chef/provisioning/transport/ssh.rb', line 34

def initialize(host, username, ssh_options, options, global_config)
  @host = host
  @username = username
  @ssh_options = ssh_options
  @options = options
  @config = global_config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



46
47
48
# File 'lib/chef/provisioning/transport/ssh.rb', line 46

def config
  @config
end

#hostObject (readonly)

Returns the value of attribute host.



42
43
44
# File 'lib/chef/provisioning/transport/ssh.rb', line 42

def host
  @host
end

#optionsObject (readonly)

Returns the value of attribute options.



45
46
47
# File 'lib/chef/provisioning/transport/ssh.rb', line 45

def options
  @options
end

#ssh_optionsObject (readonly)

Returns the value of attribute ssh_options.



44
45
46
# File 'lib/chef/provisioning/transport/ssh.rb', line 44

def ssh_options
  @ssh_options
end

#usernameObject (readonly)

Returns the value of attribute username.



43
44
45
# File 'lib/chef/provisioning/transport/ssh.rb', line 43

def username
  @username
end

Instance Method Details

#available?Boolean

Returns:

  • (Boolean)


166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/chef/provisioning/transport/ssh.rb', line 166

def available?
  # If you can't pwd within 10 seconds, you can't pwd
  execute('pwd', :timeout => 10)
  true
rescue Timeout::Error, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::EHOSTDOWN, Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, Net::SSH::Disconnect
  Chef::Log.debug("#{username}@#{host} unavailable: network connection failed or broke: #{$!.inspect}")
  disconnect
  false
rescue Net::SSH::AuthenticationFailed, Net::SSH::HostKeyMismatch
  Chef::Log.debug("#{username}@#{host} unavailable: SSH authentication error: #{$!.inspect} ")
  disconnect
  false
end

#disconnectObject



154
155
156
157
158
159
160
161
162
163
164
# File 'lib/chef/provisioning/transport/ssh.rb', line 154

def disconnect
  if @session
    begin
      Chef::Log.debug("Closing SSH session on #{username}@#{host}")
      @session.close
    rescue
    ensure
      @session = nil
    end
  end
end

#download_file(path, local_path) ⇒ Object



98
99
100
101
# File 'lib/chef/provisioning/transport/ssh.rb', line 98

def download_file(path, local_path)
  Chef::Log.debug("Downloading file #{path} from #{username}@#{host} to local #{local_path}")
  download(path, local_path)
end

#execute(command, execute_options = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/chef/provisioning/transport/ssh.rb', line 48

def execute(command, execute_options = {})
  Chef::Log.info("Executing #{options[:prefix]}#{command} on #{username}@#{host}")
  stdout = ''
  stderr = ''
  exitstatus = nil
  session # grab session outside timeout, it has its own timeout
  with_execute_timeout(execute_options) do
    channel = session.open_channel do |channel|
      # Enable PTY unless otherwise specified, some instances require this
      unless options[:ssh_pty_enable] == false
        channel.request_pty do |chan, success|
           raise "could not get pty" if !success && options[:ssh_pty_enable]
        end
      end

      channel.exec("#{options[:prefix]}#{command}") do |ch, success|
        raise "could not execute command: #{command.inspect}" unless success

        channel.on_data do |ch2, data|
          stdout << data
          stream_chunk(execute_options, data, nil)
        end

        channel.on_extended_data do |ch2, type, data|
          stderr << data
          stream_chunk(execute_options, nil, data)
        end

        channel.on_request "exit-status" do |ch, data|
          exitstatus = data.read_long
        end
      end
    end

    channel.wait
  end

  Chef::Log.info("Completed #{command} on #{username}@#{host}: exit status #{exitstatus}")
  Chef::Log.debug("Stdout was:\n#{stdout}") if stdout != '' && !options[:stream] && !options[:stream_stdout] && config[:log_level] != :debug
  Chef::Log.info("Stderr was:\n#{stderr}") if stderr != '' && !options[:stream] && !options[:stream_stderr] && config[:log_level] != :debug
  SSHResult.new(command, execute_options, stdout, stderr, exitstatus)
end

#make_url_available_to_remote(local_url) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/chef/provisioning/transport/ssh.rb', line 136

def make_url_available_to_remote(local_url)
  uri = URI(local_url)
  if is_local_machine(uri.host)
    port, host = forward_port(uri.port, uri.host, uri.port, 'localhost')
    if !port
      # Try harder if the port is already taken
      port, host = forward_port(uri.port, uri.host, 0, 'localhost')
      if !port
        raise "Error forwarding port: could not forward #{uri.port} or 0"
      end
    end
    uri.host = host
    uri.port = port
  end
  Chef::Log.info("Port forwarded: local URL #{local_url} is available to #{self.host} as #{uri.to_s} for the duration of this SSH connection.")
  uri.to_s
end

#read_file(path) ⇒ Object



91
92
93
94
95
96
# File 'lib/chef/provisioning/transport/ssh.rb', line 91

def read_file(path)
  Chef::Log.debug("Reading file #{path} from #{username}@#{host}")
  result = StringIO.new
  download(path, result)
  result.string
end

#upload_file(local_path, path) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/chef/provisioning/transport/ssh.rb', line 117

def upload_file(local_path, path)
  execute("mkdir -p #{File.dirname(path)}").error!
  if options[:prefix]
    # Make a tempfile on the other side, upload to that, and sudo mv / chown / etc.
    remote_tempfile = "/tmp/#{File.basename(path)}.#{Random.rand(2**32)}"
    Chef::Log.debug("Uploading #{local_path} to #{remote_tempfile} on #{username}@#{host}")
    Net::SCP.new(session).upload!(local_path, remote_tempfile)
    begin
      execute("mv #{remote_tempfile} #{path}").error!
    rescue
      # Clean up if we were unable to move
      execute("rm #{remote_tempfile}").error!
    end
  else
    Chef::Log.debug("Uploading #{local_path} to #{path} on #{username}@#{host}")
    Net::SCP.new(session).upload!(local_path, path)
  end
end

#write_file(path, content) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/chef/provisioning/transport/ssh.rb', line 103

def write_file(path, content)
  execute("mkdir -p #{File.dirname(path)}").error!
  if options[:prefix]
    # Make a tempfile on the other side, upload to that, and sudo mv / chown / etc.
    remote_tempfile = "/tmp/#{File.basename(path)}.#{Random.rand(2**32)}"
    Chef::Log.debug("Writing #{content.length} bytes to #{remote_tempfile} on #{username}@#{host}")
    Net::SCP.new(session).upload!(StringIO.new(content), remote_tempfile)
    execute("mv #{remote_tempfile} #{path}").error!
  else
    Chef::Log.debug("Writing #{content.length} bytes to #{path} on #{username}@#{host}")
    Net::SCP.new(session).upload!(StringIO.new(content), path)
  end
end