forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
452 lines (395 loc) · 13 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package dockerregistry
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"path"
"strings"
"time"
"github.com/fsouza/go-dockerclient"
"github.com/golang/glog"
imageapi "github.com/openshift/origin/pkg/image/api"
)
// 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, allowInsecure bool) (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.
// TODO: accept a docker auth config
func NewClient() Client {
return &client{
connections: make(map[string]*connection),
}
}
// client implements the Client interface
type client struct {
connections map[string]*connection
}
// Connect accepts the name of a registry in the common form Docker provides and will
// create a connection to the registry. Callers may provide a host, a host:port, or
// a fully qualified URL. When not providing a URL, the default scheme will be "https"
func (c *client) Connect(name string, allowInsecure bool) (Connection, error) {
target, err := normalizeRegistryName(name)
if err != nil {
return nil, err
}
prefix := target.String()
if conn, ok := c.connections[prefix]; ok && conn.allowInsecure == allowInsecure {
return conn, nil
}
conn := newConnection(*target, allowInsecure)
c.connections[prefix] = conn
return conn, nil
}
func normalizeRegistryName(name string) (*url.URL, error) {
prefix := name
if len(prefix) == 0 {
prefix = "index.docker.io"
}
hadPrefix := false
switch {
case strings.HasPrefix(prefix, "http://"), strings.HasPrefix(prefix, "https://"):
hadPrefix = true
default:
prefix = "https://" + prefix
}
target, err := url.Parse(prefix)
if err != nil {
return nil, fmt.Errorf("the registry name cannot be made into a valid url: %v", err)
}
if host, port, err := net.SplitHostPort(target.Host); err == nil {
if host == "docker.io" {
host = "index.docker.io"
}
if hadPrefix {
switch {
case port == "443" && target.Scheme == "https":
target.Host = host
case port == "80" && target.Scheme == "http":
target.Host = host
}
}
} else {
if target.Host == "docker.io" {
target.Host = "index.docker.io"
}
}
return target, 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
url url.URL
cached map[string]*repository
allowInsecure bool
}
func newConnection(url url.URL, allowInsecure bool) *connection {
jar, _ := cookiejar.New(nil)
client := &http.Client{Jar: jar}
if allowInsecure {
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
}
return &connection{
url: url,
client: client,
cached: make(map[string]*repository),
allowInsecure: allowInsecure,
}
}
type repository struct {
name string
endpoint url.URL
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 = imageapi.DefaultImageTag
}
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) {
glog.V(4).Infof("Getting repository %s from %s", name, c.url)
base := c.url
base.Path = path.Join(base.Path, fmt.Sprintf("/v1/repositories/%s/images", name))
req, err := http.NewRequest("GET", base.String(), 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 {
// if we tried https and were rejected, try http
if c.url.Scheme == "https" && c.allowInsecure {
glog.V(4).Infof("Failed to get https, trying http: %v", err)
c.url.Scheme = "http"
return c.getRepository(name)
}
return nil, convertConnectionError(c.url.String(), fmt.Errorf("error getting X-Docker-Token from %s: %v", name, err))
}
defer resp.Body.Close()
// if we were redirected, update the base urls
c.url.Scheme = resp.Request.URL.Scheme
c.url.Host = resp.Request.URL.Host
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)
}
// TODO: select a random endpoint
return &repository{
name: name,
endpoint: url.URL{Scheme: c.url.Scheme, Host: resp.Header.Get("X-Docker-Endpoints")},
token: resp.Header.Get("X-Docker-Token"),
}, nil
}
func (c *connection) getTags(repo *repository) (map[string]string, error) {
endpoint := repo.endpoint
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("/v1/repositories/%s/tags", repo.name))
req, err := http.NewRequest("GET", endpoint.String(), 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.url.String(), fmt.Errorf("error getting image tags for %s: %v", repo.name, err))
}
defer resp.Body.Close()
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return nil, errRepositoryNotFound{repo.name}
case code >= 300 || resp.StatusCode < 200:
// token might have expired - evict repo from cache so we can get a new one on retry
delete(c.cached, repo.name)
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) {
endpoint := repo.endpoint
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("/v1/repositories/%s/tags/%s", repo.name, tag))
req, err := http.NewRequest("GET", endpoint.String(), 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.url.String(), fmt.Errorf("error getting image id for %s:%s: %v", repo.name, tag, err))
}
defer resp.Body.Close()
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return "", errTagNotFound{len(userTag) == 0, tag, repo.name}
case code >= 300 || resp.StatusCode < 200:
// token might have expired - evict repo from cache so we can get a new one on retry
delete(c.cached, repo.name)
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) {
endpoint := repo.endpoint
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("/v1/images/%s/json", image))
req, err := http.NewRequest("GET", endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
if len(repo.token) > 0 {
req.Header.Add("Authorization", "Token "+repo.token)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, convertConnectionError(c.url.String(), fmt.Errorf("error getting json for image %q: %v", image, err))
}
defer resp.Body.Close()
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return nil, NewImageNotFoundError(repo.name, image, userTag)
case code >= 300 || resp.StatusCode < 200:
// token might have expired - evict repo from cache so we can get a new one on retry
delete(c.cached, repo.name)
if body, err := ioutil.ReadAll(resp.Body); err == nil {
glog.V(6).Infof("unable to fetch image %s: %#v\n%s", req.URL, resp, string(body))
}
return nil, fmt.Errorf("error retrieving image %s: server returned %d", req.URL, resp.StatusCode)
}
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
}