Class: GitlabJanitor::ImageCleaner::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab_janitor/image_cleaner/store.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger:, filename: './images.txt') ⇒ Store

Returns a new instance of Store.



7
8
9
10
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 7

def initialize(logger:, filename: './images.txt')
  @filename = filename
  @logger = logger
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



5
6
7
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 5

def filename
  @filename
end

#imagesObject (readonly)

Returns the value of attribute images.



5
6
7
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 5

def images
  @images
end

#loggerObject (readonly)

Returns the value of attribute logger.



5
6
7
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 5

def logger
  @logger
end

Instance Method Details

#image(img) ⇒ Object



45
46
47
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 45

def image(img)
  @images[img.name] ||= { id: img.id, loaded_at: Time.now }
end

#loadObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 24

def load
  containers = Docker::Container.all(all: true).each_with_object({}) do |c, res|
    res[c.info['ImageID']] = true
    res[c.info['Image']] = true
  end

  File.open(@filename, 'a+') do |file|
    i = 0
    @images = file.readlines.select(&:present?).each_with_object({}) do |line, imgs|
      i += 1
      name, image_id, loaded_at = line.strip.split(' ')
      loaded_at = Time.now.to_i if containers[name] || containers[image_id]

      imgs[name] = { id: image_id, loaded_at: Time.at(loaded_at.to_i) }
    rescue StandardError => e
      logger.error "Unable to load from line #{i} '#{line}': #{e}"
    end
  end
  @images
end

#parse_imagesObject



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 12

def parse_images
  Docker::Image.all.map do |m|
    tags = m.info.fetch('RepoTags', []) || []
    tags = [m.info['id']] if tags.empty? || tags.first == '<none>:<none>'
    m.info['RepoTags'] = tags

    tags.map do |name|
      Model.new(m, name, self)
    end
  end.flatten
end

#save(imgs = parse_images, skip_older: Time.at(0)) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/gitlab_janitor/image_cleaner/store.rb', line 49

def save(imgs = parse_images, skip_older: Time.at(0))
  @images = @images.delete_if do |_k, img|
    img[:loaded_at] < skip_older
  end

  imgs.each {|m| image(m) }

  File.open(@filename, 'w+') do |file|
    @images.each do |name, data|
      file.puts("#{name} #{data[:id]} #{data[:loaded_at].to_i}")
    end
  end
end