summaryrefslogtreecommitdiff
path: root/app/models/container_image.rb
blob: 583cb97791041807e28d7344755d4273e6900e19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class ContainerImage < ActiveRecord::Base
  belongs_to :project

  delegate :container_registry, :container_registry_allowed_paths,
    :container_registry_path_with_namespace, to: :project

  delegate :client, to: :container_registry

  validates :manifest, presence: true

  before_destroy :delete_tags

  before_validation :update_token, on: :create
  def update_token
    paths = container_registry_allowed_paths << name_with_namespace
    token = Auth::ContainerRegistryAuthenticationService.full_access_token(paths)
    client.update_token(token)
  end

  def path
    [container_registry.path, name_with_namespace].compact.join('/')
  end

  def name_with_namespace
    [container_registry_path_with_namespace, name].reject(&:blank?).join('/')
  end

  def tag(tag)
    ContainerRegistry::Tag.new(self, tag)
  end

  def manifest
    @manifest ||= client.repository_tags(name_with_namespace)
  end

  def tags
    return @tags if defined?(@tags)
    return [] unless manifest && manifest['tags']

    @tags = manifest['tags'].map do |tag|
      ContainerRegistry::Tag.new(self, tag)
    end
  end

  def blob(config)
    ContainerRegistry::Blob.new(self, config)
  end

  def delete_tags
    return unless tags

    digests = tags.map {|tag| tag.digest }.to_set
    digests.all? do |digest|
      client.delete_repository_tag(name_with_namespace, digest)
    end
  end

  # rubocop:disable RedundantReturn

  def self.split_namespace(full_path)
    image_name = full_path.split('/').last
    namespace = full_path.gsub(/(.*)(#{Regexp.escape('/' + image_name)})/, '\1')
    if namespace.count('/') < 1
      namespace, image_name = full_path, ""
    end
    return namespace, image_name
  end
end