container_repository.rb 1.75 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
class ContainerRepository < ActiveRecord::Base
  belongs_to :project
5
6

  validates :name, length: { minimum: 0, allow_nil: false }
7
  validates :name, uniqueness: { scope: :project_id }
8
9

  delegate :client, to: :registry
10

11
  # rubocop: disable CodeReuse/ServiceClass
12
  def registry
13
14
15
16
17
18
19
20
21
    @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
22
  # rubocop: enable CodeReuse/ServiceClass
23
24

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

29
30
31
32
  def location
    File.join(registry.path, path)
  end

33
34
35
36
37
  def tag(tag)
    ContainerRegistry::Tag.new(self, tag)
  end

  def manifest
38
    @manifest ||= client.repository_tags(path)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  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

54
  def has_tags?
55
    tags.any?
56
57
  end

58
59
60
61
  def root_repository?
    name.empty?
  end

62
63
  def delete_tags!
    return unless has_tags?
64

65
66
    digests = tags.map { |tag| tag.digest }.to_set

67
68
69
70
    digests.all? do |digest|
      client.delete_repository_tag(self.path, digest)
    end
  end
71

72
73
74
75
76
  def self.build_from_path(path)
    self.new(project: path.repository_project,
             name: path.repository_name)
  end

77
  def self.create_from_path!(path)
78
    build_from_path(path).tap(&:save!)
79
  end
80
81
82
83

  def self.build_root_repository(project)
    self.new(project: project, name: '')
  end
84
end