summaryrefslogtreecommitdiff
path: root/app/models/container_repository.rb
blob: e5076f30c8ea2410c3d940da23e6c2ac2b155205 (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
69
70
71
class ContainerRepository < ActiveRecord::Base
  belongs_to :project

  validates :manifest, presence: true
  validates :name, length: { minimum: 0, allow_nil: false }

  delegate :client, to: :registry
  before_destroy :delete_tags

  def registry
    @registry ||= begin
      token = Auth::ContainerRegistryAuthenticationService.full_access_token(path)

      url = Gitlab.config.registry.api_url
      host_port = Gitlab.config.registry.host_port

      ContainerRegistry::Registry.new(url, token: token, path: host_port)
    end
  end

  def path
    @path ||= [project.full_path, name].select(&:present?).join('/')
  end

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

  def manifest
    @manifest ||= client.repository_tags(self.path)
  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(self.path, digest)
    end
  end

  def self.project_from_path(repository_path)
    return unless repository_path.include?('/')

    ##
    # Projects are always located inside a namespace, so we can remove
    # the last node, and see if project with that path exists.
    #
    truncated_path = repository_path.slice(0...repository_path.rindex('/'))

    ##
    # We still make it possible to search projects by a full image path
    # in order to maintain backwards compatibility.
    #
    Project.find_by_full_path(truncated_path) ||
      Project.find_by_full_path(repository_path)
  end
end