2020-12-11 00:09:41 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DependencyProxy
|
|
|
|
class FindOrCreateManifestService < DependencyProxy::BaseService
|
|
|
|
def initialize(group, image, tag, token)
|
|
|
|
@group = group
|
|
|
|
@image = image
|
|
|
|
@tag = tag
|
|
|
|
@token = token
|
|
|
|
@file_name = "#{@image}:#{@tag}.json"
|
|
|
|
@manifest = nil
|
|
|
|
end
|
|
|
|
|
|
|
|
def execute
|
|
|
|
@manifest = @group.dependency_proxy_manifests
|
2021-02-22 18:10:55 +00:00
|
|
|
.find_or_initialize_by_file_name_or_digest(file_name: @file_name, digest: @tag)
|
2020-12-11 00:09:41 +00:00
|
|
|
|
|
|
|
head_result = DependencyProxy::HeadManifestService.new(@image, @tag, @token).execute
|
|
|
|
|
2021-07-23 12:09:05 +00:00
|
|
|
return success(manifest: @manifest, from_cache: true) if cached_manifest_matches?(head_result)
|
2020-12-11 00:09:41 +00:00
|
|
|
|
|
|
|
pull_new_manifest
|
2021-07-23 12:09:05 +00:00
|
|
|
respond(from_cache: false)
|
2020-12-11 00:09:41 +00:00
|
|
|
rescue Timeout::Error, *Gitlab::HTTP::HTTP_ERRORS
|
|
|
|
respond
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def pull_new_manifest
|
|
|
|
DependencyProxy::PullManifestService.new(@image, @tag, @token).execute_with_manifest do |new_manifest|
|
|
|
|
@manifest.update!(
|
2021-02-22 18:10:55 +00:00
|
|
|
content_type: new_manifest[:content_type],
|
2020-12-11 00:09:41 +00:00
|
|
|
digest: new_manifest[:digest],
|
|
|
|
file: new_manifest[:file],
|
|
|
|
size: new_manifest[:file].size
|
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def cached_manifest_matches?(head_result)
|
2021-02-22 18:10:55 +00:00
|
|
|
return false if head_result[:status] == :error
|
|
|
|
|
|
|
|
@manifest && @manifest.digest == head_result[:digest] && @manifest.content_type == head_result[:content_type]
|
2020-12-11 00:09:41 +00:00
|
|
|
end
|
|
|
|
|
2021-07-23 12:09:05 +00:00
|
|
|
def respond(from_cache: true)
|
2020-12-11 00:09:41 +00:00
|
|
|
if @manifest.persisted?
|
2021-07-23 12:09:05 +00:00
|
|
|
success(manifest: @manifest, from_cache: from_cache)
|
2020-12-11 00:09:41 +00:00
|
|
|
else
|
|
|
|
error('Failed to download the manifest from the external registry', 503)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|