Class: DockerCleaner::Containers

Inherits:
Object
  • Object
show all
Defined in:
lib/docker_cleaner/containers.rb

Instance Method Summary collapse

Constructor Details

#initialize(logger, opts = {}) ⇒ Containers

Returns a new instance of Containers.



3
4
5
6
# File 'lib/docker_cleaner/containers.rb', line 3

def initialize(logger, opts = {})
  @logger = logger
  @delay = opts.fetch(:delay, 0)
end

Instance Method Details

#remove(container) ⇒ Object



8
9
10
11
12
# File 'lib/docker_cleaner/containers.rb', line 8

def remove(container)
  @logger.info "Remove #{container.id[0...10]} - #{container.info["Image"]} - #{container.info["Names"][0]}"
  container.remove v: true
  @logger.info "Remove #{container.id[0...10]} - #{container.info["Image"]} - #{container.info["Names"][0]}... OK"
end

#runObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/docker_cleaner/containers.rb', line 14

def run
  # Remove stopped container which stopped with code '0'
  two_hours_ago = Time.now.to_i - 2 * 3600
  Docker::Container.all(all: true).select{ |container|
    status = container.info["Status"]
    (status == "Created" && container.info["Created"].to_i < two_hours_ago) ||
      (status.include?("Exited (") && container.info["Created"].to_i < two_hours_ago)
  }.each do |container|
    remove(container)
    sleep(@delay)
  end

  containers_per_app = {}
  Docker::Container.all(all: true).select{ |container|
    container.info["Status"].include?("Exited")
  }.each{ |container|
    app = container.info["Image"].split(":", 2)[0]
    if containers_per_app[app].nil?
      containers_per_app[app] = [container]
    else
      containers_per_app[app] << container
    end
  }
  containers_per_app.each do |app, containers|
    containers.shift
    containers.each do |container|
      remove(container)
      sleep(@delay)
    end
  end
end