Class: SSHKit::Backend::Docker

Inherits:
Abstract
  • Object
show all
Defined in:
lib/sshkit/backend/docker.rb

Defined Under Namespace

Classes: Configuration

Constant Summary collapse

CONTAINER_MAP =
{}
CONTAINER_WAIT_IO =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, &block) ⇒ Docker

Returns a new instance of Docker.



23
24
25
26
# File 'lib/sshkit/backend/docker.rb', line 23

def initialize(host, &block)
  super
  @container = nil
end

Instance Attribute Details

#docker_open_stdinObject

Returns the value of attribute docker_open_stdin.



17
18
19
# File 'lib/sshkit/backend/docker.rb', line 17

def docker_open_stdin
  @docker_open_stdin
end

Class Method Details

.find_container_by_host(host) ⇒ Object



19
20
21
# File 'lib/sshkit/backend/docker.rb', line 19

def self.find_container_by_host(host)
  host.docker_options[:container] || CONTAINER_MAP[host.docker_host_id]
end

Instance Method Details

#containerObject



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/sshkit/backend/docker.rb', line 28

def container
  @container and return @container
  if host.docker_options[:container]
    @container = host.docker_options[:container]
  else
    @container = docker_run_image
    host.hostname.chop! << ", container: #{@container})"
  end
  if host.respond_to? :roles_array
    host.hostname.chop! << ", roles: #{host.roles_array.inspect})"
  end
  @container
end

#docker_commit(host = nil) ⇒ Object



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
# File 'lib/sshkit/backend/docker.rb', line 151

def docker_commit(host = nil)
  host ||= self.host

  if host.is_a?(String)
    commit_id = host
    host = _deep_dup(self.host)
    host.docker_options[:commit] = commit_id
  elsif host.is_a?(Hash)
    commit_info = host
    host = _deep_dup(self.host)
    host.docker_options[:commit] ||= {}
    host.docker_options[:commit].update commit_info.symbolize_keys
  end

  host.docker_options[:commit] or return

  container = self.class.find_container_by_host(host) or
    raise "Cannot find container for host #{host.inspect}"

  cmd = %w(docker commit)

  if host.docker_options[:image]
    # if container is delivered from image, recover USER and CMD.
    image_config = {}
    IO.popen ['docker', 'inspect', '-f', '{{json .Config}}', host.docker_options[:image]], 'rb' do |f|
      image_config = JSON.parse(f.read.chomp)
    end

    if image_config["User"].to_s.length > 1
      cmd << '-c' << "USER #{image_config["User"]}"
    end

    c = image_config["Cmd"]
    if c[0] == "/bin/sh" && c[1] == "-c"
      c.shift; c.shift;
    end
    unless c.empty?
      cmd << '-c' << "CMD #{c.join(' ')}"
    end
  end

  image_name = host.docker_options[:commit]
  if image_name.is_a?(Hash)
    image_name.symbolize_keys.each do |key, val|
      if key == :name
        image_name = val
      else
        [*val].each do |v|
          cmd << "--#{key.to_s.tr('_', '-')}" << v
        end
      end
    end
  end
  cmd << container
  image_name == true or
    cmd << image_name

  image_hash = nil
  pid = nil
  IO.popen cmd, 'rb' do |f|
    pid = f.pid
    image_hash = f.gets
  end
  image_hash.nil? and
    output.error "Docker: Failed to get image hash. Commit may be failed!"
  image_hash.chomp!
  ret = image_name == true ? image_hash : image_name
  output.info "Docker: commit #{container} as #{ret}"
  ret
end

#docker_run_image(host = nil) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
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
# File 'lib/sshkit/backend/docker.rb', line 101

def docker_run_image(host = nil)
  host ||= self.host

  if host.is_a?(String)
    image_name = host
    host_id = host.__id__
    host = _deep_dup(self.host)
    host.docker_options[:image] = image_name
    host.docker_host_id = host_id
  elsif host.is_a?(Hash)
    d_opts = host
    host = _deep_dup(self.host)
    host.docker_options = d_opts.symbolize_keys
    host.docker_host_id = d_opts.__id__
  end

  map_key = host.docker_host_id
  CONTAINER_MAP[map_key] and
    return CONTAINER_MAP[map_key]

  image_name = host.docker_options[:image]
  cmd = %w(docker run -i)
  host.docker_options.each do |key, val|
    %w(container image env env_file commit).member?(key.to_s) and next
    if %w(t tty h hostname attach d detach entrypoint rm).member?(key.to_s)
      output.warn "Docker: run option '#{key}' is filtered."
      next
    end
    [*val].each do |v|
      cmd << "--#{key.to_s.tr('_', '-')}" << v
    end
  end
  merged_env.each do |key, val|
    cmd << "-e" << "#{key}=#{val}"
  end
  cmd += [image_name, 'sh', '-c', "# SSHkit \n hostname; read _"]
  cmd.unshift('sudo') if Docker.config.use_sudo
  io = IO.popen cmd, 'r+b'
  cid = io.gets
  if cid.nil?
    output.fatal "Docker: Failed to run image #{image_name}"
    raise "Failed to get container ID! (cmd: #{cmd.inspect})"
  end
  at_exit { io.close }
  CONTAINER_WAIT_IO[map_key] = io
  CONTAINER_MAP[map_key] = cid.strip
  output.info "Docker: run new container #{CONTAINER_MAP[map_key]} from image #{image_name}"
  CONTAINER_MAP[map_key]
end

#download!(remote, local = nil, _options = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/sshkit/backend/docker.rb', line 59

def download!(remote, local=nil, _options = {})
  local_io = local
  local_io.nil? and
    local_io = File.basename(remote)
  local_io.is_a?(String) and
    local_io = File.open(local_io, 'wb')

  with_pty(false) do
    IO.popen(to_docker_cmd('cat', remote), 'rb') do |f|
      IO.copy_stream(f, local_io)
    end
  end

  local.nil? || local.is_a?(String) and
    local_io.close
end

#merged_envObject



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/sshkit/backend/docker.rb', line 76

def merged_env
  menv = (SSHKit.config.default_env || {}).dup.symbolize_keys
  [*host.docker_options[:env_file]].each do |ef|
    File.foreach(ef) do |line|
      line.include? "=" or next
      key, val = line.chomp.split('=', 2)
      menv[key.strip.to_sym] = val.strip
    end
  end
  if host.docker_options[:env].is_a?(Hash)
    host.docker_options[:env].each do |key, val|
      menv[key.to_sym] = val
    end
  else
    [*host.docker_options[:env]].each do |e|
      key, val = e.split('=', 2)
      menv[key.strip.to_sym] = val.strip
    end
  end
  if menv[:rails_env]
    menv[:RAILS_ENV] = menv.delete(:rails_env)
  end
  menv
end

#to_docker_cmd(*args) ⇒ Object



222
223
224
225
226
227
228
229
230
231
# File 'lib/sshkit/backend/docker.rb', line 222

def to_docker_cmd(*args)
  cmd = %w(docker exec)
  cmd << '-it' if Docker.config.pty
  cmd << '-i' if docker_open_stdin
  cmd << '-u' << host.username
  cmd << container
  cmd += args
  cmd.unshift('sudo') if Docker.config.use_sudo
  cmd
end

#upload!(local, remote, _options = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/sshkit/backend/docker.rb', line 42

def upload!(local, remote, _options = {})
  local_io = local
  local_io.is_a?(String) and
    local_io = File.open(local_io, 'rb')
  @docker_open_stdin = true

  with_pty(false) do
    IO.popen(to_docker_cmd('sh', '-c', "cat > '#{remote}'"), 'wb') do |f|
      IO.copy_stream(local_io, f)
    end
  end

  @docker_open_stdin = false
  local.is_a?(String) and
    local_io.close
end