Class: Bolt::Transport::Docker::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt/transport/docker/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(target) ⇒ Connection

Returns a new instance of Connection.



10
11
12
13
14
15
16
# File 'lib/bolt/transport/docker/connection.rb', line 10

def initialize(target)
  raise Bolt::ValidationError, "Target #{target.safe_name} does not have a host" unless target.host
  @target = target
  @logger = Bolt::Logger.logger(target.safe_name)
  @docker_host = @target.options['service-url']
  @logger.trace("Initializing docker connection to #{@target.safe_name}")
end

Instance Method Details

#connectObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/bolt/transport/docker/connection.rb', line 18

def connect
  # We don't actually have a connection, but we do need to
  # check that the container exists and is running.
  output = execute_local_docker_json_command('ps')
  index = output.find_index { |item| item["ID"] == @target.host || item["Names"] == @target.host }
  raise "Could not find a container with name or ID matching '#{@target.host}'" if index.nil?
  # Now find the indepth container information
  output = execute_local_docker_json_command('inspect', [output[index]["ID"]])
  # Store the container information for later
  @container_info = output[0]
  @logger.trace { "Opened session" }
  true
rescue StandardError => e
  raise Bolt::Node::ConnectError.new(
    "Failed to connect to #{@target.safe_name}: #{e.message}",
    'CONNECT_ERROR'
  )
end

#download_remote_content(source, destination) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/bolt/transport/docker/connection.rb', line 102

def download_remote_content(source, destination)
  @logger.trace { "Downloading #{source} to #{destination}" }
  # Create the destination directory, otherwise copying a source directory with Docker will
  # copy the *contents* of the directory.
  # https://docs.docker.com/engine/reference/commandline/cp/
  FileUtils.mkdir_p(destination)
  _, stdout_str, status = execute_local_docker_command('cp', ["#{container_id}:#{source}", destination])
  unless status.exitstatus.zero?
    raise "Error downloading content from container #{@container_id}: #{stdout_str}"
  end
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end

#execute(*command, options) ⇒ Object

Executes a command inside the target container

Parameters:

  • command (Array)

    The command to run, expressed as an array of strings

  • options (Hash)

    command specific options

  • opts (Hash)

    a customizable set of options



44
45
46
47
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
# File 'lib/bolt/transport/docker/connection.rb', line 44

def execute(*command, options)
  command.unshift(options[:interpreter]) if options[:interpreter]
  # Build the `--env` parameters
  envs = []
  if options[:environment]
    options[:environment].each { |env, val| envs.concat(['--env', "#{env}=#{val}"]) }
  end

  command_options = []
  # Need to be interactive if redirecting STDIN
  command_options << '--interactive' unless options[:stdin].nil?
  command_options << '--tty' if options[:tty]
  command_options.concat(envs) unless envs.empty?
  command_options << container_id
  command_options.concat(command)

  @logger.trace { "Executing: exec #{command_options}" }

  stdout_str, stderr_str, status = execute_local_docker_command('exec', command_options, options[:stdin])

  # The actual result is the exitstatus not the process object
  status = status.nil? ? -32768 : status.exitstatus
  if status == 0
    @logger.trace { "Command returned successfully" }
  else
    @logger.trace { "Command failed with exit code #{status}" }
  end
  stdout_str.force_encoding(Encoding::UTF_8)
  stderr_str.force_encoding(Encoding::UTF_8)
  # Normalise line endings
  stdout_str.gsub!("\r\n", "\n")
  stderr_str.gsub!("\r\n", "\n")
  [stdout_str, stderr_str, status]
rescue StandardError
  @logger.trace { "Command aborted" }
  raise
end

#make_executable(path) ⇒ Object



159
160
161
162
163
164
165
# File 'lib/bolt/transport/docker/connection.rb', line 159

def make_executable(path)
  _, stderr, exitcode = execute('chmod', 'u+x', path, {})
  if exitcode != 0
    message = "Could not make file '#{path}' executable: #{stderr}"
    raise Bolt::Node::FileError.new(message, 'CHMOD_ERROR')
  end
end

#make_tmpdirObject



124
125
126
127
128
129
130
131
132
133
# File 'lib/bolt/transport/docker/connection.rb', line 124

def make_tmpdir
  tmpdir = @target.options.fetch('tmpdir', container_tmpdir)
  tmppath = "#{tmpdir}/#{SecureRandom.uuid}"

  stdout, stderr, exitcode = execute('mkdir', '-m', '700', tmppath, {})
  if exitcode != 0
    raise Bolt::Node::FileError.new("Could not make tmpdir: #{stderr}", 'TMPDIR_ERROR')
  end
  tmppath || stdout.first
end

#mkdirs(dirs) ⇒ Object



116
117
118
119
120
121
122
# File 'lib/bolt/transport/docker/connection.rb', line 116

def mkdirs(dirs)
  _, stderr, exitcode = execute('mkdir', '-p', *dirs, {})
  if exitcode != 0
    message = "Could not create directories: #{stderr}"
    raise Bolt::Node::FileError.new(message, 'MKDIR_ERROR')
  end
end

#with_remote_tmpdirObject



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/bolt/transport/docker/connection.rb', line 135

def with_remote_tmpdir
  dir = make_tmpdir
  yield dir
ensure
  if dir
    if @target.options['cleanup']
      _, stderr, exitcode = execute('rm', '-rf', dir, {})
      if exitcode != 0
        Bolt::Logger.warn("fail_cleanup", "Failed to clean up tmpdir '#{dir}': #{stderr}")
      end
    else
      Bolt::Logger.warn("skip_cleanup", "Skipping cleanup of tmpdir '#{dir}'")
    end
  end
end

#write_remote_directory(source, destination) ⇒ Object



92
93
94
95
96
97
98
99
100
# File 'lib/bolt/transport/docker/connection.rb', line 92

def write_remote_directory(source, destination)
  @logger.trace { "Uploading #{source} to #{destination}" }
  _, stdout_str, status = execute_local_docker_command('cp', [source, "#{container_id}:#{destination}"])
  unless status.exitstatus.zero?
    raise "Error writing directory to container #{@container_id}: #{stdout_str}"
  end
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end

#write_remote_executable(dir, file, filename = nil) ⇒ Object



151
152
153
154
155
156
157
# File 'lib/bolt/transport/docker/connection.rb', line 151

def write_remote_executable(dir, file, filename = nil)
  filename ||= File.basename(file)
  remote_path = File.join(dir.to_s, filename)
  write_remote_file(file, remote_path)
  make_executable(remote_path)
  remote_path
end

#write_remote_file(source, destination) ⇒ Object



82
83
84
85
86
87
88
89
90
# File 'lib/bolt/transport/docker/connection.rb', line 82

def write_remote_file(source, destination)
  @logger.trace { "Uploading #{source} to #{destination}" }
  _, stdout_str, status = execute_local_docker_command('cp', [source, "#{container_id}:#{destination}"])
  unless status.exitstatus.zero?
    raise "Error writing file to container #{@container_id}: #{stdout_str}"
  end
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end