-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdocker_src.go
305 lines (251 loc) · 8.93 KB
/
docker_src.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
package remote
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"strings"
"code.cloudfoundry.org/lager"
"github.com/Sirupsen/logrus"
"github.com/containers/image/docker"
manifestpkg "github.com/containers/image/manifest"
"github.com/containers/image/types"
specsv1 "github.com/opencontainers/image-spec/specs-go/v1"
errorspkg "github.com/pkg/errors"
)
type DockerSource struct {
trustedRegistries []string
}
func NewDockerSource(trustedRegistries []string) *DockerSource {
return &DockerSource{
trustedRegistries: trustedRegistries,
}
}
func (s *DockerSource) Manifest(logger lager.Logger, imageURL *url.URL) (Manifest, error) {
logger = logger.Session("fetching-image-manifest", lager.Data{"imageURL": imageURL})
logger.Info("start")
defer logger.Info("end")
img, err := s.preSteamedImage(logger, imageURL)
if err != nil {
return Manifest{}, err
}
contents, mimeType, err := img.Manifest()
if err != nil {
logger.Error("fetching-manifest-failed", err)
return Manifest{}, errorspkg.Wrap(err, "fetching manifest")
}
var manifest Manifest
switch mimeType {
case manifestpkg.DockerV2Schema1MediaType, manifestpkg.DockerV2Schema1SignedMediaType:
logger.Debug("docker-image-version-2-schema-1")
manifest, err = s.parseSchemaV1Manifest(logger, contents)
case specsv1.MediaTypeImageManifest, manifestpkg.DockerV2Schema2MediaType:
logger.Debug("docker-image-version-2-schema-2")
manifest, err = s.parseSchemaV2Manifest(logger, contents)
default:
return Manifest{}, errors.New(fmt.Sprintf("unknown media type '%s'", mimeType))
}
return manifest, nil
}
func (s *DockerSource) Config(logger lager.Logger, imageURL *url.URL, manifest Manifest) (specsv1.Image, error) {
logger = logger.Session("fetching-image-config", lager.Data{
"imageURL": imageURL,
"configDigest": manifest.ConfigCacheKey,
})
logger.Info("start")
defer logger.Info("end")
var (
config specsv1.Image
err error
)
switch manifest.SchemaVersion {
case 1:
logger.Debug("docker-image-version-2-schema-1")
config, err = s.parseSchemaV1Config(logger, manifest)
if err != nil {
return specsv1.Image{}, err
}
case 2:
logger.Debug("docker-image-version-2-schema-2")
config, err = s.parseSchemaV2Config(logger, imageURL, manifest.ConfigCacheKey)
if err != nil {
return specsv1.Image{}, err
}
default:
return specsv1.Image{}, fmt.Errorf("schema version not supported (%d)", manifest.SchemaVersion)
}
return config, nil
}
func (s *DockerSource) Blob(logger lager.Logger, imageURL *url.URL, digest string) ([]byte, int64, error) {
logrus.SetOutput(os.Stderr)
logger = logger.Session("streaming-blob", lager.Data{
"imageURL": imageURL,
"digest": digest,
})
logger.Info("start")
defer logger.Info("end")
imgSrc, err := s.preSteamedImageSource(logger, imageURL)
if err != nil {
return nil, 0, err
}
blob, size, err := imgSrc.GetBlob(digest)
if err != nil {
return nil, 0, err
}
logger.Debug("got-blob-stream", lager.Data{"digest": digest, "size": size})
blobContents, err := ioutil.ReadAll(blob)
if err != nil {
return nil, 0, err
}
logger.Debug("got-blob", lager.Data{"actualSize": blobContents})
if !s.checkCheckSum(logger, blobContents, digest) {
return nil, 0, fmt.Errorf("invalid checksum: layer is corrupted `%s`", digest)
}
return blobContents, size, nil
}
func (s *DockerSource) checkCheckSum(logger lager.Logger, blobContents []byte, digest string) bool {
hash := sha256.New()
if _, err := hash.Write(blobContents); err != nil {
logger.Error("writing-blob-contents", err)
return false
}
digestID := strings.Split(digest, ":")[1]
blobContentsSha := hex.EncodeToString(hash.Sum(nil))
logger.Debug("checking-checksum", lager.Data{
"digestIDChecksum": digestID,
"downloadedChecksum": blobContentsSha,
})
if digestID != blobContentsSha {
return false
}
return true
}
func (s *DockerSource) skipTLSValidation(imageURL *url.URL) bool {
for _, trustedRegistry := range s.trustedRegistries {
if imageURL.Host == trustedRegistry {
return true
}
}
return false
}
func (s *DockerSource) parseSchemaV1Manifest(logger lager.Logger, rawManifest []byte) (Manifest, error) {
var dockerManifest SchemaV1Manifest
if err := json.Unmarshal(rawManifest, &dockerManifest); err != nil {
logger.Error("parsing-manifest-failed", err, lager.Data{"manifest": string(rawManifest)})
return Manifest{}, fmt.Errorf("parsing manifest: %s", err)
}
manifest := Manifest{}
for _, layer := range dockerManifest.FSLayers {
manifest.Layers = append([]Layer{Layer{BlobID: layer["blobSum"]}}, manifest.Layers...)
}
for _, history := range dockerManifest.History {
manifest.V1Compatibility = append([]string{history.V1Compatibility}, manifest.V1Compatibility...)
}
v1Config := manifest.V1Compatibility[len(manifest.V1Compatibility)-1]
configSha := sha256.Sum256([]byte(v1Config))
manifest.ConfigCacheKey = fmt.Sprintf("sha256:%s", hex.EncodeToString(configSha[:32]))
manifest.SchemaVersion = 1
return manifest, nil
}
func (s *DockerSource) parseSchemaV2Manifest(logger lager.Logger, rawManifest []byte) (Manifest, error) {
var ociManifest specsv1.Manifest
if err := json.Unmarshal(rawManifest, &ociManifest); err != nil {
logger.Error("parsing-manifest-failed", err, lager.Data{"manifest": string(rawManifest)})
return Manifest{}, fmt.Errorf("parsing manifest: %s", err)
}
manifest := Manifest{
ConfigCacheKey: ociManifest.Config.Digest,
}
for _, layer := range ociManifest.Layers {
manifest.Layers = append(manifest.Layers, Layer{BlobID: layer.Digest, Size: layer.Size})
}
manifest.SchemaVersion = 2
return manifest, nil
}
func (s *DockerSource) parseSchemaV2Config(logger lager.Logger, imageURL *url.URL, configDigest string) (specsv1.Image, error) {
imgSrc, err := s.preSteamedImageSource(logger, imageURL)
if err != nil {
return specsv1.Image{}, err
}
stream, _, err := imgSrc.GetBlob(configDigest)
if err != nil {
logger.Error("fetching-config-failed", err)
return specsv1.Image{}, errorspkg.Wrap(err, "fetching config blob")
}
var config specsv1.Image
if err := json.NewDecoder(stream).Decode(&config); err != nil {
logger.Error("parsing-config-failed", err)
return specsv1.Image{}, fmt.Errorf("parsing image config: %s", err)
}
return config, nil
}
func (s *DockerSource) parseSchemaV1Config(logger lager.Logger, manifest Manifest) (specsv1.Image, error) {
if len(manifest.V1Compatibility) == 0 {
logger.Error("v1-manifest-validation-failed", errors.New("v1compatibility has no layers"), lager.Data{"manifest": manifest})
return specsv1.Image{}, errors.New("V1Compatibility is empty for the manifest")
}
var config specsv1.Image
v1Config := manifest.V1Compatibility[len(manifest.V1Compatibility)-1]
if err := json.Unmarshal([]byte(v1Config), &config); err != nil {
logger.Error("parsing-manifest-v1-compatibility-failed", err)
return specsv1.Image{}, fmt.Errorf("parsing manifest V1Compatibility: %s", err)
}
for _, rawHistory := range manifest.V1Compatibility {
var v1Compatibility V1Compatibility
if err := json.Unmarshal([]byte(rawHistory), &v1Compatibility); err != nil {
logger.Error("parsing-manifest-v1-compatibility-failed", err)
return specsv1.Image{}, fmt.Errorf("parsing manifest V1Compatibility: %s", err)
}
config.RootFS.DiffIDs = append(config.RootFS.DiffIDs, "sha256:"+v1Compatibility.ID)
}
return config, nil
}
func (s *DockerSource) preSteamedReference(logger lager.Logger, imageURL *url.URL) (types.ImageReference, error) {
refString := "/"
if imageURL.Host != "" {
refString += "/" + imageURL.Host
}
refString += imageURL.Path
logger.Debug("parsing-reference", lager.Data{"refString": refString})
ref, err := docker.ParseReference(refString)
if err != nil {
return nil, fmt.Errorf("parsing url failed: %s", err)
}
return ref, nil
}
func (s *DockerSource) preSteamedImage(logger lager.Logger, imageURL *url.URL) (types.Image, error) {
ref, err := s.preSteamedReference(logger, imageURL)
if err != nil {
return nil, err
}
skipTLSValidation := s.skipTLSValidation(imageURL)
logger.Debug("new-image", lager.Data{"skipTLSValidation": skipTLSValidation})
img, err := ref.NewImage(&types.SystemContext{DockerInsecureSkipTLSVerify: skipTLSValidation})
if err != nil {
return nil, fmt.Errorf("creating reference: %s", err)
}
return img, nil
}
func (s *DockerSource) preSteamedImageSource(logger lager.Logger, imageURL *url.URL) (types.ImageSource, error) {
ref, err := s.preSteamedReference(logger, imageURL)
if err != nil {
return nil, err
}
skipTLSValidation := s.skipTLSValidation(imageURL)
imgSrc, _ := ref.NewImageSource(&types.SystemContext{DockerInsecureSkipTLSVerify: skipTLSValidation}, preferedMediaTypes())
if err != nil {
return nil, fmt.Errorf("creating reference: %s", err)
}
logger.Debug("new-image", lager.Data{"skipTLSValidation": skipTLSValidation})
return imgSrc, nil
}
func preferedMediaTypes() []string {
return []string{
specsv1.MediaTypeImageManifest,
manifestpkg.DockerV2Schema2MediaType,
}
}