This repository has been archived by the owner on Feb 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 887
/
repository.go
352 lines (288 loc) · 8.99 KB
/
repository.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
package repository
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/common"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/types"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/util"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/schema"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/coreos/ioprogress"
)
type RepoData struct {
Tokens []string
Endpoints []string
Cookie []string
}
type RepositoryBackend struct {
repoData *RepoData
username string
password string
}
func NewRepositoryBackend(username string, password string) *RepositoryBackend {
return &RepositoryBackend{
username: username,
password: password,
}
}
func (rb *RepositoryBackend) GetImageInfo(url string) ([]string, *types.ParsedDockerURL, error) {
dockerURL := common.ParseDockerURL(url)
repoData, err := rb.getRepoData(dockerURL.IndexURL, dockerURL.ImageName)
if err != nil {
return nil, nil, fmt.Errorf("error getting repository data: %v", err)
}
// TODO(iaguis) check more endpoints
appImageID, err := getImageIDFromTag(repoData.Endpoints[0], dockerURL.ImageName, dockerURL.Tag, repoData)
if err != nil {
return nil, nil, fmt.Errorf("error getting ImageID from tag %s: %v", dockerURL.Tag, err)
}
ancestry, err := getAncestry(appImageID, repoData.Endpoints[0], repoData)
if err != nil {
return nil, nil, err
}
rb.repoData = repoData
return ancestry, dockerURL, nil
}
func (rb *RepositoryBackend) BuildACI(layerID string, dockerURL *types.ParsedDockerURL, outputDir string, tmpBaseDir string, curPwl []string, compress bool) (string, *schema.ImageManifest, error) {
tmpDir, err := ioutil.TempDir(tmpBaseDir, "docker2aci-")
if err != nil {
return "", nil, fmt.Errorf("error creating dir: %v", err)
}
defer os.RemoveAll(tmpDir)
j, size, err := getJson(layerID, rb.repoData.Endpoints[0], rb.repoData)
if err != nil {
return "", nil, fmt.Errorf("error getting image json: %v", err)
}
layerData := types.DockerImageData{}
if err := json.Unmarshal(j, &layerData); err != nil {
return "", nil, fmt.Errorf("error unmarshaling layer data: %v", err)
}
layerFile, err := getLayer(layerID, rb.repoData.Endpoints[0], rb.repoData, size, tmpDir)
if err != nil {
return "", nil, fmt.Errorf("error getting the remote layer: %v", err)
}
defer layerFile.Close()
util.Debug("Generating layer ACI...")
aciPath, manifest, err := common.GenerateACI(layerData, dockerURL, outputDir, layerFile, curPwl, compress)
if err != nil {
return "", nil, fmt.Errorf("error generating ACI: %v", err)
}
return aciPath, manifest, nil
}
func (rb *RepositoryBackend) getRepoData(indexURL string, remote string) (*RepoData, error) {
client := &http.Client{}
repositoryURL := "https://" + path.Join(indexURL, "v1", "repositories", remote, "images")
req, err := http.NewRequest("GET", repositoryURL, nil)
if err != nil {
return nil, err
}
if rb.username != "" && rb.password != "" {
req.SetBasicAuth(rb.username, rb.password)
}
req.Header.Set("X-Docker-Token", "true")
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, fmt.Errorf("HTTP code: %d, URL: %s", res.StatusCode, req.URL)
}
var tokens []string
if res.Header.Get("X-Docker-Token") != "" {
tokens = res.Header["X-Docker-Token"]
}
var cookies []string
if res.Header.Get("Set-Cookie") != "" {
cookies = res.Header["Set-Cookie"]
}
var endpoints []string
if res.Header.Get("X-Docker-Endpoints") != "" {
endpoints = makeEndpointsList(res.Header["X-Docker-Endpoints"])
} else {
// Assume same endpoint
endpoints = append(endpoints, indexURL)
}
return &RepoData{
Endpoints: endpoints,
Tokens: tokens,
Cookie: cookies,
}, nil
}
func getImageIDFromTag(registry string, appName string, tag string, repoData *RepoData) (string, error) {
client := &http.Client{}
// we get all the tags instead of directly getting the imageID of the
// requested one (.../tags/TAG) because even though it's specified in the
// Docker API, some registries (e.g. Google Container Registry) don't
// implement it.
req, err := http.NewRequest("GET", "https://"+path.Join(registry, "repositories", appName, "tags"), nil)
if err != nil {
return "", fmt.Errorf("failed to get Image ID: %s, URL: %s", err, req.URL)
}
setAuthToken(req, repoData.Tokens)
setCookie(req, repoData.Cookie)
res, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to get Image ID: %s, URL: %s", err, req.URL)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return "", fmt.Errorf("HTTP code: %d. URL: %s", res.StatusCode, req.URL)
}
j, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
var tags map[string]string
if err := json.Unmarshal(j, &tags); err != nil {
return "", fmt.Errorf("error unmarshaling: %v", err)
}
imageID, ok := tags[tag]
if !ok {
return "", fmt.Errorf("tag %s not found", tag)
}
return imageID, nil
}
func getAncestry(imgID, registry string, repoData *RepoData) ([]string, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://"+path.Join(registry, "images", imgID, "ancestry"), nil)
if err != nil {
return nil, err
}
setAuthToken(req, repoData.Tokens)
setCookie(req, repoData.Cookie)
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, fmt.Errorf("HTTP code: %d. URL: %s", res.StatusCode, req.URL)
}
var ancestry []string
j, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Failed to read downloaded json: %s (%s)", err, j)
}
if err := json.Unmarshal(j, &ancestry); err != nil {
return nil, fmt.Errorf("error unmarshaling: %v", err)
}
return ancestry, nil
}
func getJson(imgID, registry string, repoData *RepoData) ([]byte, int64, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://"+path.Join(registry, "images", imgID, "json"), nil)
if err != nil {
return nil, -1, err
}
setAuthToken(req, repoData.Tokens)
setCookie(req, repoData.Cookie)
res, err := client.Do(req)
if err != nil {
return nil, -1, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, -1, fmt.Errorf("HTTP code: %d, URL: %s", res.StatusCode, req.URL)
}
imageSize := int64(-1)
if hdr := res.Header.Get("X-Docker-Size"); hdr != "" {
imageSize, err = strconv.ParseInt(hdr, 10, 64)
if err != nil {
return nil, -1, err
}
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, -1, fmt.Errorf("failed to read downloaded json: %v (%s)", err, b)
}
return b, imageSize, nil
}
func getLayer(imgID, registry string, repoData *RepoData, imgSize int64, tmpDir string) (*os.File, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://"+path.Join(registry, "images", imgID, "layer"), nil)
if err != nil {
return nil, err
}
setAuthToken(req, repoData.Tokens)
setCookie(req, repoData.Cookie)
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
res.Body.Close()
return nil, fmt.Errorf("HTTP code: %d. URL: %s", res.StatusCode, req.URL)
}
// if we didn't receive the size via X-Docker-Size when we retrieved the
// layer's json, try Content-Length
if imgSize == -1 {
if hdr := res.Header.Get("Content-Length"); hdr != "" {
imgSize, err = strconv.ParseInt(hdr, 10, 64)
if err != nil {
return nil, err
}
}
}
prefix := "Downloading " + imgID[:12]
fmtBytesSize := 18
barSize := int64(80 - len(prefix) - fmtBytesSize)
bar := ioprogress.DrawTextFormatBarForW(barSize, os.Stderr)
fmtfunc := func(progress, total int64) string {
return fmt.Sprintf(
"%s: %s %s",
prefix,
bar(progress, total),
ioprogress.DrawTextFormatBytes(progress, total),
)
}
progressReader := &ioprogress.Reader{
Reader: res.Body,
Size: imgSize,
DrawFunc: ioprogress.DrawTerminalf(os.Stderr, fmtfunc),
DrawInterval: 500 * time.Millisecond,
}
layerFile, err := ioutil.TempFile(tmpDir, "dockerlayer-")
if err != nil {
return nil, err
}
_, err = io.Copy(layerFile, progressReader)
if err != nil {
return nil, err
}
if err := layerFile.Sync(); err != nil {
return nil, err
}
return layerFile, nil
}
func setAuthToken(req *http.Request, token []string) {
if req.Header.Get("Authorization") == "" {
req.Header.Set("Authorization", "Token "+strings.Join(token, ","))
}
}
func setCookie(req *http.Request, cookie []string) {
if req.Header.Get("Cookie") == "" {
req.Header.Set("Cookie", strings.Join(cookie, ""))
}
}
func makeEndpointsList(headers []string) []string {
var endpoints []string
for _, ep := range headers {
endpointsList := strings.Split(ep, ",")
for _, endpointEl := range endpointsList {
endpoints = append(
endpoints,
// TODO(iaguis) discover if httpsOrHTTP
path.Join(strings.TrimSpace(endpointEl), "v1"))
}
}
return endpoints
}