-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
107 lines (87 loc) · 2.41 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
package imageconfig
import (
"encoding/json"
"fmt"
"github.com/buger/jsonparser"
"github.com/containers/image/docker/reference"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
)
type Client struct {
Client *http.Client
Auth Authenticator
}
func (c *Client) GetConfig(imageName string) (*Config, error) {
r, err := reference.ParseNormalizedNamed(imageName)
if err != nil {
return nil, errors.Wrap(err, "parsing name")
}
digest, err := c.digest(r)
if err != nil {
return nil, errors.Wrap(err, "getting digest")
}
url := fmt.Sprintf("https://%s/v2/%s/blobs/%s", domain(r), reference.Path(r), digest)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json")
resp, err := c.authenticatedRequest(req, r)
if err != nil {
return nil, errors.Wrap(err, "performing http req")
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "reading resp bytes")
}
conf := configWrapper{}
err = json.Unmarshal(bytes, &conf)
if err != nil {
return nil, errors.Wrap(err, "unmarshalling json")
}
return &conf.Config, nil
}
func (c *Client) authenticatedRequest(req *http.Request, r reference.Named) (*http.Response, error) {
auth := DefaultAuthenticator
if c != nil && c.Auth != nil {
auth = c.Auth
}
err := auth.Authenticate(req, r)
if err != nil {
return nil, errors.Wrap(err, "authenticating digest request")
}
client := http.DefaultClient
if c != nil && c.Client != nil {
client = c.Client
}
return client.Do(req)
}
func domain(r reference.Named) string {
d := reference.Domain(r)
if d == "docker.io" {
return "registry-1.docker.io"
} else {
return d
}
}
func (c *Client) digest(r reference.Named) (string, error) {
tag := "latest"
if tagged, ok := r.(reference.Tagged); ok {
tag = tagged.Tag()
}
url := fmt.Sprintf("https://%s/v2/%s/manifests/%s", domain(r), reference.Path(r), tag)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json")
resp, err := c.authenticatedRequest(req, r)
if err != nil {
return "", errors.Wrap(err, "performing digest request")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "reading digest response")
}
// TODO: make some structs
digest, err := jsonparser.GetString(body, "config", "digest")
if err != nil {
return "", err
}
return digest, nil
}