-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
96 lines (93 loc) · 2.5 KB
/
docker.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
package nktest
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
// DockerImageTags gets the docker registry tags for a image id.
func DockerImageTags(ctx context.Context, id string) ([]string, error) {
tok, err := DockerToken(ctx, id)
if err != nil {
return nil, err
}
switch {
case strings.HasPrefix(id, "localhost/"):
return nil, nil
case !strings.HasPrefix(id, "docker.io/"):
return nil, fmt.Errorf("%s is not fully qualified", id)
case strings.HasPrefix(id, "docker.io/library/"):
id = strings.TrimPrefix(id, "docker.io/library/")
default:
id = strings.TrimPrefix(id, "docker.io/")
}
req, err := http.NewRequestWithContext(ctx, "GET", DockerRegistryURL(ctx)+"/v2/"+id+"/tags/list", nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+tok)
res, err := HttpClient(ctx).Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status %d != 200", res.StatusCode)
}
var v struct {
Name string `json:"name"`
Tags []string `json:"tags"`
}
dec := json.NewDecoder(res.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return nil, err
}
return v.Tags, nil
}
// DockerToken generates a docker auth token for the repo id.
func DockerToken(ctx context.Context, id string) (string, error) {
switch {
case strings.HasPrefix(id, "localhost/"):
return "", nil
case !strings.HasPrefix(id, "docker.io/"):
return "", fmt.Errorf("%s is not fully qualified", id)
case strings.HasPrefix(id, "docker.io/library/"):
id = strings.TrimPrefix(id, "docker.io/library/")
default:
id = strings.TrimPrefix(id, "docker.io/")
}
q := url.Values{
"service": []string{DockerAuthName(ctx)},
"scope": []string{DockerAuthScope(ctx, id)},
}
req, err := http.NewRequestWithContext(ctx, "GET", DockerTokenURL(ctx)+"?"+q.Encode(), nil)
if err != nil {
return "", err
}
res, err := HttpClient(ctx).Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
var v struct {
Token string `json:"token"`
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
IssuedAt string `json:"issued_at"`
}
dec := json.NewDecoder(res.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return "", err
}
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("status %d != 200", res.StatusCode)
}
if v.Token == "" {
return "", fmt.Errorf("empty token for %s", id)
}
return v.Token, nil
}