This repository has been archived by the owner on Jan 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
docker_tag_pusher.rb
76 lines (62 loc) · 2.21 KB
/
docker_tag_pusher.rb
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
72
73
74
75
76
require "json"
require "net/http"
require "uri"
class DockerTagPusher
REGISTRY = "https://registry-1.docker.io".freeze
MEDIA_TYPE = "application/vnd.docker.distribution.manifest.v2+json".freeze
attr_reader :username, :password
private :username, :password
def initialize(username, password)
@username = username
@password = password
end
def has_repo?(repo)
request = Net::HTTP::Get.new(
"#{REGISTRY}/v2/#{repo}/tags/list?n=1",
"Authorization" => "Bearer #{token(repo)}",
)
response = registry_client.request(request)
raise "Error (#{response.code}) checking repo exists: #{response.body}" unless %w[200 404].include?(response.code)
response.code == "200"
end
def get_manifest(repo, tag)
request = Net::HTTP::Get.new(
"#{REGISTRY}/v2/#{repo}/manifests/#{tag}",
"Authorization" => "Bearer #{token(repo)}",
"Accept" => MEDIA_TYPE,
)
response = registry_client.request(request)
raise "Image or tag not found" if response.code == "404"
raise "Error (#{response.code}) while fetching manifest: #{response.body}" if response.code != "200"
raise "Remote image not in correct format (must be #{MEDIA_TYPE})" if response["Content-Type"] != MEDIA_TYPE
response.body
end
def put_manifest(repo, manifest, tag)
request = Net::HTTP::Put.new(
"#{REGISTRY}/v2/#{repo}/manifests/#{tag}",
"Authorization" => "Bearer #{token(repo)}",
"Content-Type" => MEDIA_TYPE,
)
request.body = manifest
response = registry_client.request(request)
raise "Server error while putting manifest: #{response.body}" if response.code != "201"
end
private
def token(repo)
uri = URI.parse("https://auth.docker.io/token?service=registry.docker.io&scope=repository:#{repo}:pull,push")
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
request = Net::HTTP::Get.new uri
request.basic_auth username, password
response = http.request request
JSON.parse(response.body)["token"]
end
end
def registry_client
@registry_client ||= begin
uri = URI.parse(REGISTRY)
Net::HTTP.new(uri.host, uri.port).tap do |client|
client.use_ssl = uri.scheme == "https"
end
end
end
end