container_image.rb 1.66 KB
Newer Older
1
class ContainerImage < ActiveRecord::Base
2
  belongs_to :project
3

4 5 6 7
  delegate :container_registry, :container_registry_allowed_paths,
    :container_registry_path_with_namespace, to: :project

  delegate :client, to: :container_registry
8 9 10

  validates :manifest, presence: true

11 12
  before_destroy :delete_tags

13 14
  before_validation :update_token, on: :create
  def update_token
15
    paths = container_registry_allowed_paths << name_with_namespace
16 17 18 19 20
    token = Auth::ContainerRegistryAuthenticationService.full_access_token(paths)
    client.update_token(token)
  end

  def path
21
    [container_registry.path, name_with_namespace].compact.join('/')
22 23 24
  end

  def name_with_namespace
25
    [container_registry_path_with_namespace, name].reject(&:blank?).join('/')
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
  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

52 53 54 55
    digests = tags.map {|tag| tag.digest }.to_set
    digests.all? do |digest|
      client.delete_repository_tag(name_with_namespace, digest)
    end
56 57
  end

58 59
  # rubocop:disable RedundantReturn

60 61 62 63 64 65 66 67 68
  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