Class: Beaker::Docker

Inherits:
Hypervisor
  • Object
show all
Defined in:
lib/beaker/hypervisor/docker.rb

Instance Method Summary collapse

Constructor Details

#initialize(hosts, options) ⇒ Docker

Docker hypvervisor initializtion Env variables supported: DOCKER_REGISTRY: Docker registry URL DOCKER_HOST: Remote docker host DOCKER_BUILDARGS: Docker buildargs map

Parameters:

  • hosts (Host, Array<Host>, String, Symbol)

    One or more hosts to act upon, or a role (String or Symbol) that identifies one or more hosts.

  • options (Hash{Symbol=>String})

    Options to pass on to the hypervisor



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/beaker/hypervisor/docker.rb', line 12

def initialize(hosts, options)
  require 'docker'
  @options = options
  @logger = options[:logger] || Beaker::Logger.new
  @hosts = hosts

  # increase the http timeouts as provisioning images can be slow
  default_docker_options = { :write_timeout => 300, :read_timeout => 300 }.merge(::Docker.options || {})
  # Merge docker options from the entry in hosts file
  ::Docker.options = default_docker_options.merge(@options[:docker_options] || {})
  # assert that the docker-api gem can talk to your docker
  # enpoint.  Will raise if there is a version mismatch
  begin
    ::Docker.validate_version!
  rescue Excon::Errors::SocketError => e
    raise "Docker instance not connectable.\nError was: #{e}\nCheck your DOCKER_HOST variable has been set\nIf you are on OSX or Windows, you might not have Docker Machine setup correctly: https://docs.docker.com/machine/\n"
  end

  # Pass on all the logging from docker-api to the beaker logger instance
  ::Docker.logger = @logger

  # Find out what kind of remote instance we are talking against
  if ::Docker.version['Version'] =~ /swarm/
    @docker_type = 'swarm'
    unless ENV['DOCKER_REGISTRY']
      raise "Using Swarm with beaker requires a private registry. Please setup the private registry and set the 'DOCKER_REGISTRY' env var"
    else
      @registry = ENV['DOCKER_REGISTRY']
    end
  else
    @docker_type = 'docker'
  end

end

Instance Method Details

#cleanupObject



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/beaker/hypervisor/docker.rb', line 285

def cleanup
  @logger.notify "Cleaning up docker"
  @hosts.each do |host|
    # leave the container running if docker_preserve_container is set
    # setting docker_preserve_container also implies docker_preserve_image
    # is set, since you can't delete an image that's the base of a running
    # container
    unless host['docker_preserve_container']
      container = find_container(host)
      if container
        @logger.debug("stop container #{container.id}")
        begin
          container.kill
          sleep 2 # avoid a race condition where the root FS can't unmount
        rescue Excon::Errors::ClientError => e
          @logger.warn("stop of container #{container.id} failed: #{e.response.body}")
        end
        @logger.debug("delete container #{container.id}")
        begin
          container.delete
        rescue Excon::Errors::ClientError => e
          @logger.warn("deletion of container #{container.id} failed: #{e.response.body}")
        end
      end

      # Do not remove the image if docker_preserve_image is set to true, otherwise remove it
      unless host['docker_preserve_image']
        image_id = host['docker_image_id']

        if image_id
          @logger.debug("deleting image #{image_id}")
          begin
            ::Docker::Image.remove(image_id)
          rescue Excon::Errors::ClientError => e
            @logger.warn("deletion of image #{image_id} failed: #{e.response.body}")
          rescue ::Docker::Error::DockerError => e
            @logger.warn("deletion of image #{image_id} caused internal Docker error: #{e.message}")
          end
        else
          @logger.warn("Intended to delete the host's docker image, but host['docker_image_id'] was not set")
        end
      end
    end
  end
end

#get_container_image(host) ⇒ 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
109
110
# File 'lib/beaker/hypervisor/docker.rb', line 73

def get_container_image(host)
  @logger.debug("Creating image")

  if host['use_image_as_is']
    return ::Docker::Image.create('fromImage' => host['image'])
  end

  dockerfile = host['dockerfile']
  if dockerfile
    # assume that the dockerfile is in the repo and tests are running
    # from the root of the repo; maybe add support for external Dockerfiles
    # with external build dependencies later.
    if File.exist?(dockerfile)
      dir = File.expand_path(dockerfile).chomp(dockerfile)
      return ::Docker::Image.build_from_dir(
        dir,
        { 'dockerfile' => dockerfile,
          :rm => true,
          :buildargs => buildargs_for(host)
        }
      )
    else
      raise "Unable to find dockerfile at #{dockerfile}"
    end
  elsif host['use_image_entry_point']
    df = <<-DF
      FROM #{host['image']}
      EXPOSE 22
    DF

    cmd = host['docker_cmd']
    df += cmd if cmd
    return ::Docker::Image.build(df, { rm: true, buildargs: buildargs_for(host) })
  end

  return ::Docker::Image.build(dockerfile_for(host),
              { rm: true, buildargs: buildargs_for(host) })
end

#get_container_opts(host, image_name) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/beaker/hypervisor/docker.rb', line 51

def get_container_opts(host, image_name)
  container_opts = {}
  if host['dockerfile']
    container_opts['ExposedPorts'] = {'22/tcp' => {} }
  end

  container_opts.merge! ( {
    'Image' => image_name,
    'Hostname' => host.name,
    'HostConfig' => {
      'PortBindings' => {
        '22/tcp' => [{ 'HostPort' => rand.to_s[2..5], 'HostIp' => '0.0.0.0'}]
      },
      'PublishAllPorts' => true,
      'Privileged' => true,
      'RestartPolicy' => {
        'Name' => 'always'
      }
    }
  } )
end

#install_and_run_ssh(host) ⇒ Object



47
48
49
# File 'lib/beaker/hypervisor/docker.rb', line 47

def install_and_run_ssh(host)
  host['dockerfile'] || host['use_image_entry_point']
end

#install_ssh_components(container, host) ⇒ Object

This sideloads sshd after a container starts



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/beaker/hypervisor/docker.rb', line 242

def install_ssh_components(container, host)
  case host['platform']
  when /ubuntu/, /debian/
    container.exec(%w(apt-get update))
    container.exec(%w(apt-get install -y openssh-server openssh-client))
  when /cumulus/
    container.exec(%w(apt-get update))
    container.exec(%w(apt-get install -y openssh-server openssh-client))
  when /fedora-(2[2-9])/
    container.exec(%w(dnf clean all))
    container.exec(%w(dnf install -y sudo openssh-server openssh-clients))
    container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key))
    container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key))
  when /^el-/, /centos/, /fedora/, /redhat/, /eos/
    container.exec(%w(yum clean all))
    container.exec(%w(yum install -y sudo openssh-server openssh-clients))
    container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key))
    container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key))
  when /opensuse/, /sles/
    container.exec(%w(zypper -n in openssh))
    container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key))
    container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key))
    container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config))
  when /archlinux/
    container.exec(%w(pacman --noconfirm -Sy archlinux-keyring))
    container.exec(%w(pacman --noconfirm -Syu))
    container.exec(%w(pacman -S --noconfirm openssh))
    container.exec(%w(ssh-keygen -A))
    container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config))
    container.exec(%w(systemctl enable sshd))
  when /alpine/
    container.exec(%w(apk add --update openssh))
    container.exec(%w(ssh-keygen -A))
  else
    # TODO add more platform steps here
    raise "platform #{host['platform']} not yet supported on docker"
  end

  # Make sshd directory, set root password
  container.exec(%w(mkdir -p /var/run/sshd))
  container.exec(['/bin/sh', '-c', "echo root:#{root_password} | chpasswd"])
end

#provisionObject



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/beaker/hypervisor/docker.rb', line 112

def provision
  @logger.notify "Provisioning docker"

  @hosts.each do |host|
    @logger.notify "provisioning #{host.name}"


    image = get_container_image(host)

    if host['tag']
      image.tag({:repo => host['tag']})
    end

    if @docker_type == 'swarm'
      image_name = "#{@registry}/beaker/#{image.id}"
      ret = ::Docker::Image.search(:term => image_name)
      if ret.first.nil?
        @logger.debug("Image does not exist on registry. Pushing.")
        image.tag({:repo => image_name, :force => true})
        image.push
      end
    else
      image_name = image.id
    end

    container_opts = get_container_opts(host, image_name)
    if host['dockeropts'] || @options[:dockeropts]
      dockeropts = host['dockeropts'] ? host['dockeropts'] : @options[:dockeropts]
      dockeropts.each do |k,v|
        container_opts[k] = v
      end
    end

    container = find_container(host)

    # Provisioning - Only provision if the host's container can't be found
    # via its name or ID
    if container.nil?
      unless host['mount_folders'].nil?
        container_opts['HostConfig'] ||= {}
        container_opts['HostConfig']['Binds'] = host['mount_folders'].values.map do |mount|
          host_path = File.expand_path(mount['host_path'])
          # When using docker_toolbox and getting a "(Driveletter):/" path, convert windows path to VM mount
          if ENV['DOCKER_TOOLBOX_INSTALL_PATH'] && host_path =~ /^.\:\//
            host_path = "/" + host_path.gsub(/^.\:/, host_path[/^(.)/].downcase)
          end
          a = [ host_path, mount['container_path'] ]
          a << mount['opts'] if mount.has_key?('opts')
          a.join(':')
        end
      end

      if host['docker_env']
        container_opts['Env'] = host['docker_env']
      end

      if host['docker_cap_add']
        container_opts['HostConfig']['CapAdd'] = host['docker_cap_add']
      end

      if host['docker_container_name']
        container_opts['name'] = host['docker_container_name']
      end

      @logger.debug("Creating container from image #{image_name}")
      container = ::Docker::Container.create(container_opts)
    else
      host['use_existing_container'] = true
    end

    if container.nil?
      raise RuntimeError, 'Cannot continue because no existing container ' +
                          'could be found and provisioning is disabled.'
    end

    fix_ssh(container) if @options[:provision] == false

    @logger.debug("Starting container #{container.id}")
    container.start

    if install_and_run_ssh(host)
      @logger.notify("Installing ssh components and starting ssh daemon in #{host} container")
      install_ssh_components(container, host)
      # run fixssh to configure and start the ssh service
      fix_ssh(container, host)
    end
    # Find out where the ssh port is from the container
    # When running on swarm DOCKER_HOST points to the swarm manager so we have to get the
    # IP of the swarm slave via the container data
    # When we are talking to a normal docker instance DOCKER_HOST can point to a remote docker instance.

    # Talking against a remote docker host which is a normal docker host
    if @docker_type == 'docker' && ENV['DOCKER_HOST']
      ip = URI.parse(ENV['DOCKER_HOST']).host
    else
      # Swarm or local docker host
      if in_container?
        ip = container.json["NetworkSettings"]["Gateway"]
      else
        ip = container.json["NetworkSettings"]["Ports"]["22/tcp"][0]["HostIp"]
      end
    end

    @logger.info("Using docker server at #{ip}")
    port = container.json["NetworkSettings"]["Ports"]["22/tcp"][0]["HostPort"]

    forward_ssh_agent = @options[:forward_ssh_agent] || false

    # Update host metadata
    host['ip']  = ip
    host['port'] = port
    host['ssh']  = {
      :password => root_password,
      :port => port,
      :forward_agent => forward_ssh_agent,
      :auth_methods => ['password', 'publickey', 'hostbased', 'keyboard-interactive']
    }

    @logger.debug("node available as  ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@#{ip} -p #{port}")
    host['docker_container_id'] = container.id
    host['docker_image_id'] = image.id
    host['vm_ip'] = container.json["NetworkSettings"]["IPAddress"].to_s

  end

  hack_etc_hosts @hosts, @options

end