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 = Logging.logger[target.safe_name]
  @docker_host = @target.options['service-url']
  @logger.debug("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.debug { "Opened session" }
  true
rescue StandardError => e
  raise Bolt::Node::ConnectError.new(
    "Failed to connect to #{@target.safe_name}: #{e.message}",
    'CONNECT_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.debug { "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.debug { "Command returned successfully" }
  else
    @logger.info { "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.debug { "Command aborted" }
  raise
end

#make_executable(path) ⇒ Object



141
142
143
144
145
146
147
# File 'lib/bolt/transport/docker/connection.rb', line 141

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



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

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



98
99
100
101
102
103
104
# File 'lib/bolt/transport/docker/connection.rb', line 98

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



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/bolt/transport/docker/connection.rb', line 117

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
        @logger.warn("Failed to clean up tmpdir '#{dir}': #{stderr}")
      end
    else
      @logger.warn("Skipping cleanup of tmpdir '#{dir}'")
    end
  end
end

#write_remote_directory(source, destination) ⇒ Object



90
91
92
93
94
95
96
# File 'lib/bolt/transport/docker/connection.rb', line 90

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

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



133
134
135
136
137
138
139
# File 'lib/bolt/transport/docker/connection.rb', line 133

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

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