Class: FPM::Fry::Client

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/fpm/fry/client.rb

Defined Under Namespace

Classes: ContainerCreationFailed, ContainerDeletionFailed, ContainerNotFound, FileNotFound, NotAFile

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/fpm/fry/client.rb', line 40

def initialize(options = {})
  @docker_url = options.fetch(:docker_url){ self.class.docker_url }
  @logger = options[:logger]
  if @logger.nil?
    @logger = Cabin::Channel.get
  end
  if options[:tls].nil? ? docker_url =~ %r!(\Ahttps://|:2376\z)! : options[:tls]
    # enable tls
    @tls = {
      client_cert: File.join(self.class.docker_cert_path,'cert.pem'),
      client_key: File.join(self.class.docker_cert_path, 'key.pem'),
      ssl_ca_file: File.join(self.class.docker_cert_path, 'ca.pem'),
      ssl_verify_peer: options.fetch(:tlsverify){ false }
    }
    [:client_cert, :client_key, :ssl_ca_file].each do |k|
      if !File.exist?(@tls[k])
        raise ArgumentError.new("#{k} #{@tls[k]} doesn't exist. Did you set DOCKER_CERT_PATH correctly?")
      end
    end
  else
    @tls = {}
  end
end

Instance Attribute Details

#docker_urlObject (readonly)

Returns the value of attribute docker_url.



38
39
40
# File 'lib/fpm/fry/client.rb', line 38

def docker_url
  @docker_url
end

#loggerObject (readonly)

Returns the value of attribute logger.



38
39
40
# File 'lib/fpm/fry/client.rb', line 38

def logger
  @logger
end

#tlsObject (readonly)

Returns the value of attribute tls.



38
39
40
# File 'lib/fpm/fry/client.rb', line 38

def tls
  @tls
end

Class Method Details

.docker_cert_pathString

Returns docker cert path from environment.

Returns:

  • (String)

    docker cert path from environment



80
81
82
# File 'lib/fpm/fry/client.rb', line 80

def self.docker_cert_path
  ENV.fetch('DOCKER_CERT_PATH',File.join(Dir.home, '.docker'))
end

.docker_urlObject



84
85
86
# File 'lib/fpm/fry/client.rb', line 84

def self.docker_url
  ENV.fetch('DOCKER_HOST'.freeze, 'unix:///var/run/docker.sock')
end

Instance Method Details

#agentObject



261
262
263
# File 'lib/fpm/fry/client.rb', line 261

def agent
  @agent ||= agent_for(docker_url, tls)
end

#agent_for(uri, tls) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/fpm/fry/client.rb', line 269

def agent_for( uri, tls )
  proto, address = uri.split('://',2)
  options = {
    read_timeout: 10000
  }.merge( tls )
  case(proto)
  when 'unix'
    uri = "unix:///"
    options[:socket] = address
    options[:host] = ""
    options[:hostname] = ""
  when 'tcp'
    if tls.any?
      return agent_for("https://#{address}", tls)
    else
      return agent_for("http://#{address}", tls)
    end
  when 'http', 'https'
  end
  logger.debug("Creating Agent", options.merge(uri: uri))
  return Excon.new(uri, options)
end

#broken_symlinks?Boolean

Returns:

  • (Boolean)


265
266
267
# File 'lib/fpm/fry/client.rb', line 265

def broken_symlinks?
  return true
end

#changes(name) ⇒ Object



184
185
186
187
188
189
190
191
# File 'lib/fpm/fry/client.rb', line 184

def changes(name)
  url = url('containers',name,'changes')
  res = agent.get(path: url, expects: [200, 204])
  return JSON.parse(res.body)
rescue Excon::Error => e
  logger.error("could not retrieve changes for: #{name}, url: #{url}, error: #{e}")
  raise
end

#copy(name, resource, map, options = {}) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/fpm/fry/client.rb', line 171

def copy(name, resource, map, options = {})
  ex = FPM::Fry::Tar::Extractor.new(logger: logger)
  base = File.dirname(resource)
  read(name, resource) do | entry |
    file = File.join(base, entry.full_name).chomp('/')
    file = file.sub(%r"\A\./",'')
    to = map[file]
    next unless to
    logger.debug("Copy",name: file, to: to)
    ex.extract_entry(to, entry, options)
  end
end

#create(image) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/fpm/fry/client.rb', line 220

def create(image)
  url = url('containers','create')
  res = agent.post(
    headers: { 'Content-Type' => 'application/json' },
    path: url,
    body: JSON.generate('Image' => image),
  )
  data = JSON.parse(res.body)
  if res.status != 201
    logger.error(data["message"])
    if res.status == 404
      logger.info("execute docker pull #{image} first or specify --pull argument for fpm-fry")
    end
    raise ContainerCreationFailed.new("could not create container from #{image}", message: data["message"])
  end
  data['Id']
rescue Excon::Error => e
  logger.error("could not create container from #{image}, url: #{url}, error: #{e}")
  raise
end

#delete(image) ⇒ Object



216
217
218
# File 'lib/fpm/fry/client.rb', line 216

def delete(image)
  agent.delete(path: url('images',image), expects: [200, 404])
end

#destroy(container) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/fpm/fry/client.rb', line 241

def destroy(container)
  return unless container

  url = self.url('containers', container)
  res = agent.delete(
    path: url,
    expects: [204, 409]
  )
  return unless res.status == 409
  data = JSON.parse(res.body) rescue ({"message" => "could not parse response body: '#{res.body}'"})
  if data["message"] =~ /removal of container .* is already in progress/
    logger.info(data["message"])
  else
    raise ContainerDeletionFailed.new("could not destroy container #{container}", data)
  end
rescue Excon::Error => e
  logger.error("could not destroy container: #{container}, url: #{url}, error: #{e}")
  raise
end

Gets the target of a symlink

Parameters:

  • name (String)

    the container name

  • resource (String)

    the file name

Returns:

  • (String)

    target

  • (nil)

    if resource is not a symlink



161
162
163
164
165
166
167
168
169
# File 'lib/fpm/fry/client.rb', line 161

def link_target(name, resource)
  read(name, resource) do |file|
    if file.header.typeflag == "2"
      return File.absolute_path(file.header.linkname,File.dirname(resource))
    end
    return nil
  end
  return nil
end

#pull(image, platform: nil) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/fpm/fry/client.rb', line 193

def pull(image, platform: nil)
  last_status = ""
  streamer = lambda do |chunk, remaining_bytes, total_bytes|
    chunk.each_line do |line|
      begin
        msg = JSON.parse(line)
        status, progress, id = *msg.values_at("status", "progress", "id")
        id += ": " if id
        status += " " if progress
        move_up_one_line = $stdout.tty? && status =~ /Downloading|Extracting/ && last_status =~ /Downloading|Extracting/
        last_status = status
        cursor_move = move_up_one_line ? "\e[1A" : ""
        puts [cursor_move, id, status, progress].join("")
      rescue JSON::ParserError => e
        $stderr.puts "Could not parse JSON response from docker: #{e}"
      end
    end
  end
  query = {'fromImage' => image}
  query['platform'] = platform if platform
  agent.post(path: url('images','create'), query: query, :response_block => streamer)
end

#read(name, resource) ⇒ Object



96
97
98
99
100
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
# File 'lib/fpm/fry/client.rb', line 96

def read(name, resource)
  return to_enum(:read, name, resource) unless block_given?
  url = nil
  res = begin
          if (server_version['ApiVersion'] < "1.20")
            url = self.url('containers', name, 'copy')
            agent.post(
              path: url,
              headers: { 'Content-Type' => 'application/json' },
              body: JSON.generate({'Resource' => resource}),
              expects: [200,404,500]
            )
          else
            url = self.url('containers', name, 'archive')
            agent.get(
              path: url,
              headers: { 'Content-Type' => 'application/json' },
              query: {:path => resource},
              expects: [200,404,500]
            )
          end
        rescue Excon::Error => e
          logger.error("unexpected response when reading resource: url: #{url}, error: #{e}")
          raise
        end
  if [404,500].include? res.status
    body_message = Hash[JSON.load(res.body).map{|k,v| ["docker.#{k}",v] }] rescue {'docker.message' => res.body}
    body_message['docker.container'] = name
    if body_message['docker.message'] =~ /\ANo such container:/
      raise ContainerNotFound.new("container not found", body_message)
    end
    raise FileNotFound.new("file not found", {'path' => resource}.merge(body_message))
  end
  sio = StringIO.new(res.body)
  tar = FPM::Fry::Tar::Reader.new( sio )
  tar.each do |entry|
    yield entry
  end
end

#read_content(name, resource) ⇒ String

Gets the file contents while following symlinks

Parameters:

  • name (String)

    the container name

  • resource (String)

    the file name

Returns:

  • (String)

    content

Raises:

  • (NotAFile)

    when the file has no readable content

  • (FileNotFound)

    when the file does not exist



143
144
145
146
147
148
149
150
151
152
153
# File 'lib/fpm/fry/client.rb', line 143

def read_content(name, resource)
  read(name, resource) do |file|
    if file.header.typeflag == "2"
      return read_content(name, File.absolute_path(file.header.linkname,File.dirname(resource)))
    end
    if file.header.typeflag != "0"
      raise NotAFile.new("not a file", {'path' => resource})
    end
    return file.read
  end
end

#server_versionString

Returns docker server api version.

Returns:

  • (String)

    docker server api version



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/fpm/fry/client.rb', line 65

def server_version
  @server_version ||=
    begin
      res = agent.get(
        expects: [200],
        path: '/version'
      )
      JSON.parse(res.body)
    rescue Excon::Error => e
      @logger.error("could not read server version: url: /version, errorr #{e}")
      raise
    end
end

#tls?Boolean

Returns:

  • (Boolean)


88
89
90
# File 'lib/fpm/fry/client.rb', line 88

def tls?
  tls.any?
end

#url(*path) ⇒ Object



92
93
94
# File 'lib/fpm/fry/client.rb', line 92

def url(*path)
  ['', "v"+server_version['ApiVersion'], *path.compact].join('/')
end