Class: Squared::Workspace::Project::Docker

Inherits:
Base
  • Object
show all
Includes:
Prompt
Defined in:
lib/squared/workspace/project/docker.rb

Constant Summary collapse

DIR_DOCKER =
(COMPOSEFILE + BAKEFILE).freeze

Constants included from Common

Common::ARG, Common::PATH

Instance Attribute Summary collapse

Attributes inherited from Base

#dependfile, #exception, #group, #name, #parent, #path, #pipe, #project, #theme, #verbose, #workspace

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#add, aliasargs, #allref, #archive, #archive?, #as, as_path, bannerargs, #basepath, batchargs, #build, #copy, #copy?, #depend, #depend?, #dependtype, #dev?, #doc, #doc?, #enabled?, #error, #event, #exclude?, #first, #generate, #graph, #graph?, #has?, #initialize_build, #initialize_env, #initialize_events, #initialize_logger, #initialize_ref, #inject, #inspect, #last, #lint, #lint?, #localname, #log, populate, #prod?, ref, #ref?, #rootpath, #script?, #series, #task_include?, #test, #test?, to_s, #to_s, #to_sym, #unpack, #variable_set, #version, #with

Methods included from Common::Format

#enable_aixterm

Constructor Details

#initialize(file: nil, context: nil, tag: nil, secrets: nil, mounts: [], registry: nil, **kwargs) ⇒ Docker

Returns a new instance of Docker.



99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/squared/workspace/project/docker.rb', line 99

def initialize(*, file: nil, context: nil, tag: nil, secrets: nil, mounts: [], registry: nil, **kwargs)
  super
  return unless dockerfile(file).exist?

  @context = context
  @tag = tag || "#{@project}:latest"
  @mounts = mounts
  @secrets = secrets
  @registry = [registry, kwargs[:username]].compact.join('/')
  initialize_ref Docker.ref
  initialize_logger(**kwargs)
  initialize_env(**kwargs)
  @output[4] = merge_opts(kwargs[:args], @output[4]) if kwargs[:args]
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



96
97
98
# File 'lib/squared/workspace/project/docker.rb', line 96

def context
  @context
end

#tagObject

Returns the value of attribute tag.



97
98
99
# File 'lib/squared/workspace/project/docker.rb', line 97

def tag
  @tag
end

Class Method Details

.config?(val) ⇒ Boolean

Returns:

  • (Boolean)


81
82
83
84
85
# File 'lib/squared/workspace/project/docker.rb', line 81

def config?(val)
  return false unless (val = as_path(val))

  val.join('Dockerfile').exist? || DIR_DOCKER.any? { |file| val.join(file).exist? }
end

.tasksObject



77
78
79
# File 'lib/squared/workspace/project/docker.rb', line 77

def tasks
  [].freeze
end

Instance Method Details

#build?Boolean

Returns:

  • (Boolean)


470
471
472
# File 'lib/squared/workspace/project/docker.rb', line 470

def build?
  @output[0] != false && dockerfile.exist?
end

#buildx(flag, opts = [], tag: nil, context: nil) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/squared/workspace/project/docker.rb', line 267

def buildx(flag, opts = [], tag: nil, context: nil)
  cmd, opts = docker_session('buildx', opts: opts)
  opts = option_sanitize(opts, OPT_DOCKER[:buildx][:common]).first
  cmd << flag
  out = option_sanitize(opts, OPT_DOCKER[:buildx][flag] + OPT_DOCKER[:buildx][:shared]).first
  case flag
  when :build
    cmd.merge(as_a(tag).map { |val| quote_option('tag', val) })
    append_context context
  when :bake
    unless out.empty?
      args = out.dup
      out.clear
      if Dir.exist?(args.last)
        if projectpath?(val = args.pop)
          context = val
        else
          out << val
        end
      end
      append_value(args, escape: true)
      contextdir(context) if context
    end
  end
  option_clear out
  run(from: :"buildx:#{flag}")
end

#clean(sync: invoked_sync?('clean')) ⇒ Object



199
200
201
202
203
# File 'lib/squared/workspace/project/docker.rb', line 199

def clean(*, sync: invoked_sync?('clean'), **)
  return super unless @clean.nil?

  image(:rm, sync: sync)
end

#clean?Boolean

Returns:

  • (Boolean)


474
475
476
# File 'lib/squared/workspace/project/docker.rb', line 474

def clean?
  super || dockerfile.exist?
end

#compose(opts, flags = nil, script: false, args: nil, from: :build) ⇒ Object



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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/squared/workspace/project/docker.rb', line 205

def compose(opts, flags = nil, script: false, args: nil, from: :build, **)
  return opts if script == false

  ret = docker_session
  if from == :build
    case (n = filetype)
    when 1, 2
      ret << 'buildx' << 'bake'
      append_file n
      from = :bake
    when 3, 4
      ret << 'compose' << 'build'
      append_file n
      from = :compose
    else
      ret << 'build'
    end
  else
    ret << from
  end
  case opts
  when String
    ret << opts
  when Hash
    ret.merge(append_hash(opts, build: true))
  when Enumerable
    ret.merge(opts.to_a)
  end
  [args, flags].each_with_index do |target, index|
    next unless target

    target = append_any(target, target: []) unless target.is_a?(Array)
    ret.merge(target.map { |arg| index == 0 ? fill_option(arg) : quote_option('build-arg', arg) })
  end
  case from
  when :build
    case @secrets
    when String
      quote_option('secret', @secrets, double: true)
    when Hash
      append = lambda do |type|
        as_a(@secrets[type]).each { |arg| ret << quote_option('secret', "type=#{type},#{arg}", double: true) }
      end
      append.(:file)
      append.(:env)
    else
      as_a(@secrets).each { |arg| ret << quote_option('secret', arg) }
    end
    if (val = option('tag', ignore: false))
      ret << quote_option('tag', val)
    elsif !session_arg?('t', 'tag')
      ret << quote_option('tag', tag)
    end
    append_context
  when :bake, :compose
    if (val = option(from == :bake ? 'target' : 'service', ignore: false))
      ret.merge(split_escape(val).map { |s| shell_escape(s) })
    end
  end
  ret
end

#composex(flag, opts = [], service: nil) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/squared/workspace/project/docker.rb', line 295

def composex(flag, opts = [], service: nil)
  cmd, opts = docker_session('compose', opts: opts)
  opts = option_sanitize(opts, OPT_DOCKER[:compose][:common]).first
  append_file filetype unless session_arg?('f', 'file')
  cmd << flag
  out = option_sanitize(opts, OPT_DOCKER[:compose][flag] + OPT_DOCKER[:common]).first
  from = :"compose:#{flag}"
  case flag
  when :build, :up
    append_value(out, escape: true)
  when :exec, :run
    append_command(flag, service, out, from: from)
  end
  run(from: from)
end

#container(flag, opts = [], id: nil) ⇒ Object



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/squared/workspace/project/docker.rb', line 311

def container(flag, opts = [], id: nil)
  cmd, opts = docker_session('container', flag, opts: opts)
  list = OPT_DOCKER[:container].fetch(flag, [])
  list += OPT_DOCKER[:container][:update] if flag == :run
  out = option_sanitize(opts, list, first: flag == :exec).first
  from = :"container:#{flag}"
  case flag
  when :run, :exec
    if flag == :run && !session_arg?('mount')
      run = VAL_DOCKER[:run]
      both = run[:bind] + run[:tmpfs]
      diff = run[:bind].reject { |val| run[:tmpfs].include?(val) }
      delim = Regexp.new(",\\s*(?=#{both.join('|')})")
      as_a(@mounts).each do |val|
        args = []
        tmpfs = true
        val.split(delim).each do |opt|
          k, v, q = split_option(opt)
          next unless both.include?(k)

          if k == 'type'
            tmpfs = false if v == 'bind'
            next
          elsif diff.include?(k)
            tmpfs = false
          end
          case k
          when 'readonly', 'ro'
            args << k
            next
          when 'source', 'src', 'destination', 'dst', 'target'
            v = basepath(v)
            v = shell_quote(v, option: false, force: false) if q == ''
            tmpfs = false if k[0] == 's'
          end
          args << "#{k}=#{q + v + q}"
        end
        cmd << "--mount type=#{tmpfs ? 'tmpfs' : 'bind'},#{args.join(',')}"
      end
    end
    append_command(flag, id.to_s.empty? ? tag : id, out, target: cmd, from: from)
  when :update
    raise_error('missing container', hint: from) if out.empty?
    append_value(out, escape: true)
  when :commit
    latest = out.shift || tag
    cmd << id << latest
    raise_error("unknown args: #{out.join(', ')}", hint: from) unless out.empty?
    return unless confirm_command(cmd.to_s, title: from, target: id, as: latest)

    registry = option('registry') || @registry
    run(from: from, exception: registry.nil? ? exception : true)
    return unless registry

    opts = []
    append_option('platform', target: opts, equals: true)
    case option('disable-content-trust', ignore: false)
    when 'true', '1'
      opts << 'disable-content-trust'
    when 'false', '0'
      opts << 'disable-content-trust=false'
    end
    opts << '--quiet' unless verbose
    return image(:push, opts, id: latest, registry: registry)
  else
    if out.empty?
      ps = docker_output 'ps', '-a'
      status = []
      no = true
      case flag
      when :inspect, :diff
        no = false
      when :start
        status = %w[created exited]
        no = false
      when :stop, :pause
        status = %w[running restarting]
      when :restart
        status = %w[running paused exited]
      when :unpause
        status << 'paused'
        no = false
      when :top, :stats
        status << 'running'
        cmd << '--no-stream' if flag == :stats
        no = false
      when :kill
        status = %w[running restarting paused]
      when :rm
        status = %w[created exited dead]
      end
      ps.merge(status.map { |s| "--filter=\"status=#{s}\"" })
      list_image(flag, ps, no: no, hint: "status: #{status.join(', ')}", from: from) do |id|
        run(cmd.temp(id), from: from)
      end
      return
    else
      append_value(out, escape: true)
    end
  end
  run(from: from)
end

#dockerfile(val = nil) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/squared/workspace/project/docker.rb', line 478

def dockerfile(val = nil)
  if val == 'Dockerfile'
    @file = false
  elsif val
    @file = if val.is_a?(Array)
              val = val.select { |file| basepath(file).exist? }
              val.size > 1 ? val : val.first
            else
              val || DIR_DOCKER.find { |file| basepath(file).exist? }
            end
    @file ||= false
  end
  basepath((@file.is_a?(Array) ? @file.first : @file) || 'Dockerfile')
end

#image(flag, opts = [], sync: true, id: nil, registry: nil) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/squared/workspace/project/docker.rb', line 414

def image(flag, opts = [], sync: true, id: nil, registry: nil)
  cmd, opts = docker_session('image', flag == :exec ? :list : flag, opts: opts)
  out = option_sanitize(opts, OPT_DOCKER[:image][flag]).first
  from = :"image:#{flag}"
  case flag
  when :list
    if opts.size == out.size
      index = 0
      name = nil
      opts.each do |opt|
        if (name = opt[/^name=["']?(.+)["']?$/, 1])
          opts.delete(opt)
          break
        end
      end
      flag = :run if flag == :list
      list_image(flag, cmd << '-a', from: from) do |val|
        container(flag, if name
                          opts.dup << "name=#{index == 0 ? name : "#{name}-#{index}"}"
                        else
                          opts
                        end, id: val)
        index += 1
      end
      return
    else
      option_clear out
    end
  when :rm
    if id
      cmd << id
    elsif !out.empty?
      out.each { |val| run(cmd.temp(val), sync: sync, from: from) }
      return
    else
      list_image(flag, docker_output('image', 'ls -a'), from: from) do |val|
        image(:rm, opts, sync: sync, id: val)
      end
      return
    end
  when :push
    id ||= tag
    registry ||= out.shift || @registry
    raise_error(id ? "unknown args: #{out.join(', ')}" : 'no id/tag given', hint: from) unless id && out.empty?
    raise_error('username/registry not provided', hint: from) unless registry
    registry.chomp!('/')
    uri = shell_quote("#{registry}/#{id}")
    cmd << uri
    img = docker_output 'image', 'tag', id, uri
    return unless confirm_command(img.to_s, cmd.to_s, target: id, as: registry, title: from)

    run(img, exception: true, sync: false, banner: false)
  end
  run(sync: sync, from: from)
end

#populateObject



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
# File 'lib/squared/workspace/project/docker.rb', line 118

def populate(*, **)
  super
  return unless ref?(Docker.ref)

  namespace name do
    @@tasks[Docker.ref].each do |action, flags|
      next if @pass.include?(action)

      namespace action do
        flags.each do |flag|
          case action
          when 'build'
            case flag
            when :tag, :context
              format_desc(action, flag, 'opts*', before: flag == :tag ? 'name' : 'dir')
              task flag, [flag] do |_, args|
                param = param_guard(action, flag, args: args, key: flag)
                buildx(:build, args.to_a.drop(1), "#{flag}": param)
              end
            when :bake
              format_desc action, flag, 'opts*,target*,context?'
              task flag do |_, args|
                args = param_guard(action, flag, args: args.to_a)
                buildx flag, args
              end
            end
          when 'compose'
            case flag
            when :build, :up
              format_desc action, flag, 'opts*,service*'
              task flag do |_, args|
                composex flag, args.to_a
              end
            when :exec, :run
              format_desc action, flag, "service,command#{flag == :exec ? '' : '?'},args*,opts*"
              task flag, [:service] do |_, args|
                service = param_guard(action, flag, args: args, key: :service)
                composex(flag, args.to_a.drop(1), service: service)
              end
            end
          when 'container'
            case flag
            when :exec, :commit
              format_desc(action, flag, 'id/name,opts*', after: flag == :exec ? 'args+' : 'tag?')
              task flag, [:id] do |_, args|
                id = param_guard(action, flag, args: args, key: :id)
                container(flag, args.to_a.drop(1), id: id)
              end
            when :run
              format_desc action, flag, 'image,opts*,args*'
              task flag, [:image] do |_, args|
                image = param_guard(action, flag, args: args, key: :image)
                container(flag, args.to_a.drop(1), id: image)
              end
            else
              format_desc(action, flag, 'opts*', after: "id/name#{flag == :update ? '+' : '*'}")
              task flag do |_, args|
                container flag, args.to_a
              end
            end
          when 'image'
            case flag
            when :push
              format_desc action, flag, 'tag,registry/username?,opts*'
              task flag, [:tag] do |_, args|
                tag = param_guard(action, flag, args: args, key: :tag)
                image(flag, args.to_a.drop(1), id: tag)
              end
            else
              format_desc(action, flag, flag == :rm ? 'id*,opts*' : 'opts*,args*')
              task flag do |_, args|
                image flag, args.to_a
              end
            end
          end
        end
      end
    end
  end
end

#refObject



114
115
116
# File 'lib/squared/workspace/project/docker.rb', line 114

def ref
  Docker.ref
end