Class: ContainedMr::Cleaner

Inherits:
Object
  • Object
show all
Defined in:
lib/contained_mr/cleaner.rb

Overview

Cleans up left over Docker images and containers.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name_prefix) ⇒ Cleaner

Sets up a cleaner.

Parameters:

  • name_prefix (String)

    should match the value given to Template instances



11
12
13
14
# File 'lib/contained_mr/cleaner.rb', line 11

def initialize(name_prefix)
  @name_prefix = name_prefix
  @label_value = name_prefix
end

Instance Attribute Details

#name_prefixObject (readonly)

Returns the value of attribute name_prefix.



5
6
7
# File 'lib/contained_mr/cleaner.rb', line 5

def name_prefix
  @name_prefix
end

Instance Method Details

#container_filtersHash<Symbol, Array<String>>

Returns filters used to identify Docker containers started by this controller.

Returns:

  • (Hash<Symbol, Array<String>>)

    filters used to identify Docker containers started by this controller



58
59
60
# File 'lib/contained_mr/cleaner.rb', line 58

def container_filters
  { label: [ "contained_mr.ctl=#{@label_value}" ] }
end

#destroy_all!Array<Docker::Container, Docker::Image>

Removes all images and containers matching this cleaner’s name prefix.

Returns:

  • (Array<Docker::Container, Docker::Image>)

    the removed objects



19
20
21
22
23
# File 'lib/contained_mr/cleaner.rb', line 19

def destroy_all!
  containers = destroy_all_containers!
  images = destroy_all_images!
  containers + images
end

#destroy_all_containers!Array<Docker::Container>

Returns the removed containers.

Returns:

  • (Array<Docker::Container>)

    the removed containers



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/contained_mr/cleaner.rb', line 26

def destroy_all_containers!
  containers = Docker::Container.all all: true,
                                     filters: container_filters.to_json
  containers.each do |container|
    begin
      container.delete force: false, volumes: true
    rescue Docker::Error::NotFoundError
      # Workaround for https://github.com/docker/docker/issues/14474
    end
  end
end

#destroy_all_images!Array<Docker::Image>

Returns the removed images.

Returns:

  • (Array<Docker::Image>)

    the removed images



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/contained_mr/cleaner.rb', line 39

def destroy_all_images!
  tag_prefix = "#{@name_prefix}/"
  images = Docker::Image.all
  deleted_images = []
  images.each do |image|
    next unless image_tags = image.info['RepoTags']
    image_tags.each do |image_tag|
      next unless image_tag.start_with? tag_prefix
      # HACK(pwnall): Trick docker-api into issuing a DELETE request by tag.
      tag_image = Docker::Image.new Docker.connection, 'id' => image_tag
      tag_image.delete
      deleted_images << image
    end
  end
  deleted_images
end