Method: CIDE::CLI#clean

Defined in:
lib/cide/cli.rb

#cleanObject



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
# File 'lib/cide/cli.rb', line 285

def clean
  days_to_keep = options[:days]
  max_images = options[:count]

  # Delete failed images
  failed_filter = 'label=cide.build.complete=false'
  cide_failed_image_ids = docker_image_ids(filter_by: failed_filter)
  if cide_failed_image_ids.any?
    docker('rmi', '--force', *cide_failed_image_ids)
  end

  # Retrieve all other cide images
  cide_image_ids = docker_image_ids(filter_by: 'label=cide')

  if cide_image_ids.empty?
    puts 'No images found to be cleaned'
    return
  end

  x = docker('inspect', *cide_image_ids, capture: true)
  cide_images =
    JSON
    .parse(x.strip)
    .each { |image| image['Created'] = Time.iso8601(image['Created']) }
    .sort { |a, b| a['Created'] <=> b['Created'] }

  to_destroy = cide_images[max_images..-1]
  leftover_images = cide_images[0..(max_images - 1)]

  expire_from = Time.now - (days_to_keep * 24 * 60 * 60)
  to_destroy <<
    leftover_images.select { |image| image['Created'] < expire_from }

  to_destroy_ids = to_destroy.map { |image| image['Id'] }

  if to_destroy_ids.empty?
    puts 'No images found to be cleaned'
    return
  end

  docker('rmi', '--force', *to_destroy_ids)
end