forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
340 lines (298 loc) · 9.74 KB
/
client.go
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package dockerregistry
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/fsouza/go-dockerclient"
)
// Client includes methods for accessing a Docker registry by name.
type Client interface {
// Connect to a Docker registry by name. Pass "" for the Docker Hub
Connect(registry string) (Connection, error)
}
// Connection allows you to retrieve data from a Docker V1 registry.
type Connection interface {
// ImageTags will return a map of the tags for the image by namespace (if not
// specified, will be "library") and name.
ImageTags(namespace, name string) (map[string]string, error)
// ImageByID will return the requested image by namespace (if not specified,
// will be "library"), name, and ID.
ImageByID(namespace, name, id string) (*docker.Image, error)
// ImageByTag will return the requested image by namespace (if not specified,
// will be "library"), name, and tag (if not specified, "latest").
ImageByTag(namespace, name, tag string) (*docker.Image, error)
}
// NewClient returns a client object which allows public access to
// a Docker registry.
func NewClient() Client {
return &client{
connections: make(map[string]connection),
}
}
// client implements the Client interface
type client struct {
connections map[string]connection
}
func (c *client) Connect(name string) (Connection, error) {
if len(name) == 0 {
name = "index.docker.io"
}
if conn, ok := c.connections[name]; ok {
return conn, nil
}
conn := newConnection(name)
c.connections[name] = conn
return conn, nil
}
func convertConnectionError(registry string, err error) error {
switch {
case strings.Contains(err.Error(), "connection refused"):
return errRegistryNotFound{registry}
default:
return err
}
}
type connection struct {
client *http.Client
host string
cached map[string]*repository
}
func newConnection(name string) connection {
return connection{
host: name,
client: http.DefaultClient,
cached: make(map[string]*repository),
}
}
type repository struct {
name string
endpoint string
token string
}
// ImageTags returns the tags for the named Docker image repository.
func (c connection) ImageTags(namespace, name string) (map[string]string, error) {
if len(namespace) == 0 {
namespace = "library"
}
if len(name) == 0 {
return nil, fmt.Errorf("image name must be specified")
}
repo, err := c.getCachedRepository(fmt.Sprintf("%s/%s", namespace, name))
if err != nil {
return nil, err
}
return c.getTags(repo)
}
// ImageByID returns the specified image within the named Docker image repository
func (c connection) ImageByID(namespace, name, imageID string) (*docker.Image, error) {
if len(namespace) == 0 {
namespace = "library"
}
if len(name) == 0 {
return nil, fmt.Errorf("image name must be specified")
}
repo, err := c.getCachedRepository(fmt.Sprintf("%s/%s", namespace, name))
if err != nil {
return nil, err
}
return c.getImage(repo, imageID, "")
}
// ImageByTag returns the specified image within the named Docker image repository
func (c connection) ImageByTag(namespace, name, tag string) (*docker.Image, error) {
if len(namespace) == 0 {
namespace = "library"
}
if len(name) == 0 {
return nil, fmt.Errorf("image name must be specified")
}
searchTag := tag
if len(searchTag) == 0 {
searchTag = "latest"
}
repo, err := c.getCachedRepository(fmt.Sprintf("%s/%s", namespace, name))
if err != nil {
return nil, err
}
imageID, err := c.getTag(repo, searchTag, tag)
if err != nil {
return nil, err
}
return c.getImage(repo, imageID, tag)
}
func (c connection) getCachedRepository(name string) (*repository, error) {
if cached, ok := c.cached[name]; ok {
return cached, nil
}
repo, err := c.getRepository(name)
if err != nil {
return nil, err
}
c.cached[name] = repo
return repo, nil
}
func (c connection) getRepository(name string) (*repository, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/repositories/%s/images", c.host, name), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("X-Docker-Token", "true")
resp, err := c.client.Do(req)
if err != nil {
return nil, convertConnectionError(c.host, fmt.Errorf("error getting X-Docker-Token from index.docker.io: %v", err))
}
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return nil, errRepositoryNotFound{name}
case code >= 300 || resp.StatusCode < 200:
return nil, fmt.Errorf("error retrieving repository: server returned %d", resp.StatusCode)
}
return &repository{
name: name,
endpoint: resp.Header.Get("X-Docker-Endpoints"),
token: resp.Header.Get("X-Docker-Token"),
}, nil
}
func (c connection) getTags(repo *repository) (map[string]string, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/repositories/%s/tags", repo.endpoint, repo.name), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("Authorization", "Token "+repo.token)
resp, err := c.client.Do(req)
if err != nil {
return nil, convertConnectionError(c.host, fmt.Errorf("error getting image tags for %s: %v", repo.name, err))
}
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return nil, errRepositoryNotFound{repo.name}
case code >= 300 || resp.StatusCode < 200:
return nil, fmt.Errorf("error retrieving tags: server returned %d", resp.StatusCode)
}
tags := make(map[string]string)
if err := json.NewDecoder(resp.Body).Decode(&tags); err != nil {
return nil, fmt.Errorf("error decoding image %s tags: %v", repo.name, err)
}
return tags, nil
}
func (c connection) getTag(repo *repository, tag, userTag string) (string, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/repositories/%s/tags/%s", repo.endpoint, repo.name, tag), nil)
if err != nil {
return "", fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("Authorization", "Token "+repo.token)
resp, err := c.client.Do(req)
if err != nil {
return "", convertConnectionError(c.host, fmt.Errorf("error getting image id for %s:%s: %v", repo.name, tag, err))
}
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return "", errTagNotFound{len(userTag) == 0, tag, repo.name}
case code >= 300 || resp.StatusCode < 200:
return "", fmt.Errorf("error retrieving tag: server returned %d", resp.StatusCode)
}
var imageID string
if err := json.NewDecoder(resp.Body).Decode(&imageID); err != nil {
return "", fmt.Errorf("error decoding image id: %v", err)
}
return imageID, nil
}
func (c connection) getImage(repo *repository, image, userTag string) (*docker.Image, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/images/%s/json", repo.endpoint, image), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("Authorization", "Token "+repo.token)
resp, err := c.client.Do(req)
if err != nil {
return nil, convertConnectionError(c.host, fmt.Errorf("error getting json for image %q: %v", image, err))
}
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return nil, NewImageNotFoundError(repo.name, image, userTag)
case code >= 300 || resp.StatusCode < 200:
return nil, fmt.Errorf("error retrieving image %s: server returned %d", req.URL, resp.StatusCode)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("can't read image body from %s: %v", req.URL, err)
}
return unmarshalDockerImage(body)
}
type errTagNotFound struct {
wasDefault bool
tag string
repository string
}
func (e errTagNotFound) Error() string {
if e.wasDefault {
return fmt.Sprintf("the default tag %q has not been set on repository %q", e.tag, e.repository)
}
return fmt.Sprintf("tag %q has not been set on repository %q", e.tag, e.repository)
}
type errRepositoryNotFound struct {
repository string
}
func (e errRepositoryNotFound) Error() string {
return fmt.Sprintf("the repository %q was not found", e.repository)
}
type errImageNotFound struct {
tag string
image string
repository string
}
func NewImageNotFoundError(repository, image, tag string) error {
return errImageNotFound{tag, image, repository}
}
func (e errImageNotFound) Error() string {
if len(e.tag) == 0 {
return fmt.Sprintf("the image %q in repository %q was not found and may have been deleted", e.image, e.repository)
}
return fmt.Sprintf("the image %q in repository %q with tag %q was not found and may have been deleted", e.image, e.repository, e.tag)
}
type errRegistryNotFound struct {
registry string
}
func (e errRegistryNotFound) Error() string {
return fmt.Sprintf("the registry %q could not be reached", e.registry)
}
func IsRegistryNotFound(err error) bool {
_, ok := err.(errRegistryNotFound)
return ok
}
func IsRepositoryNotFound(err error) bool {
_, ok := err.(errRepositoryNotFound)
return ok
}
func IsImageNotFound(err error) bool {
_, ok := err.(errImageNotFound)
return ok
}
func IsTagNotFound(err error) bool {
_, ok := err.(errTagNotFound)
return ok
}
func IsNotFound(err error) bool {
return IsRegistryNotFound(err) || IsRepositoryNotFound(err) || IsImageNotFound(err) || IsTagNotFound(err)
}
func unmarshalDockerImage(body []byte) (*docker.Image, error) {
var imagePre012 docker.ImagePre012
if err := json.Unmarshal(body, &imagePre012); err != nil {
return nil, err
}
return &docker.Image{
ID: imagePre012.ID,
Parent: imagePre012.Parent,
Comment: imagePre012.Comment,
Created: imagePre012.Created,
Container: imagePre012.Container,
ContainerConfig: imagePre012.ContainerConfig,
DockerVersion: imagePre012.DockerVersion,
Author: imagePre012.Author,
Config: imagePre012.Config,
Architecture: imagePre012.Architecture,
Size: imagePre012.Size,
}, nil
}