forked from openshift/imagebuilder
/
archive.go
502 lines (455 loc) · 13.2 KB
/
archive.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package dockerclient
import (
"archive/tar"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"github.com/containers/storage/pkg/archive"
"github.com/containers/storage/pkg/fileutils"
"github.com/containers/storage/pkg/idtools"
"k8s.io/klog"
)
// TransformFileFunc is given a chance to transform an arbitrary input file.
type TransformFileFunc func(h *tar.Header, r io.Reader) (data []byte, update bool, skip bool, err error)
// FilterArchive transforms the provided input archive to a new archive,
// giving the fn a chance to transform arbitrary files.
func FilterArchive(r io.Reader, w io.Writer, fn TransformFileFunc) error {
tr := tar.NewReader(r)
tw := tar.NewWriter(w)
for {
h, err := tr.Next()
if err == io.EOF {
return tw.Close()
}
if err != nil {
return err
}
var body io.Reader = tr
name := h.Name
data, ok, skip, err := fn(h, tr)
klog.V(6).Infof("Transform %s -> %s: data=%t ok=%t skip=%t err=%v", name, h.Name, data != nil, ok, skip, err)
if err != nil {
return err
}
if skip {
continue
}
if ok {
h.Size = int64(len(data))
body = bytes.NewBuffer(data)
}
if err := tw.WriteHeader(h); err != nil {
return err
}
if _, err := io.Copy(tw, body); err != nil {
return err
}
}
}
type CreateFileFunc func() (*tar.Header, io.ReadCloser, bool, error)
func NewLazyArchive(fn CreateFileFunc) io.ReadCloser {
pr, pw := io.Pipe()
tw := tar.NewWriter(pw)
go func() {
for {
h, r, more, err := fn()
if err != nil {
pw.CloseWithError(err)
return
}
if h == nil {
tw.Flush()
pw.Close()
return
}
if err := tw.WriteHeader(h); err != nil {
r.Close()
pw.CloseWithError(err)
return
}
n, err := io.Copy(tw, &io.LimitedReader{R: r, N: h.Size})
r.Close()
if err != nil {
pw.CloseWithError(err)
return
}
if n != h.Size {
pw.CloseWithError(fmt.Errorf("short read for %s", h.Name))
return
}
if !more {
tw.Flush()
pw.Close()
return
}
}
}()
return pr
}
func archiveFromURL(src, dst, tempDir string, check DirectoryCheck) (io.Reader, io.Closer, error) {
// get filename from URL
u, err := url.Parse(src)
if err != nil {
return nil, nil, err
}
base := path.Base(u.Path)
if base == "." {
return nil, nil, fmt.Errorf("cannot determine filename from url: %s", u)
}
resp, err := http.Get(src)
if err != nil {
return nil, nil, err
}
archive := NewLazyArchive(func() (*tar.Header, io.ReadCloser, bool, error) {
if resp.StatusCode >= 400 {
return nil, nil, false, fmt.Errorf("server returned a status code >= 400: %s", resp.Status)
}
header := &tar.Header{
Name: sourceToDestinationName(path.Base(u.Path), dst, false),
Mode: 0600,
}
r := resp.Body
if resp.ContentLength == -1 {
f, err := ioutil.TempFile(tempDir, "url")
if err != nil {
return nil, nil, false, fmt.Errorf("unable to create temporary file for source URL: %v", err)
}
n, err := io.Copy(f, resp.Body)
if err != nil {
f.Close()
return nil, nil, false, fmt.Errorf("unable to download source URL: %v", err)
}
if err := f.Close(); err != nil {
return nil, nil, false, fmt.Errorf("unable to write source URL: %v", err)
}
f, err = os.Open(f.Name())
if err != nil {
return nil, nil, false, fmt.Errorf("unable to open downloaded source URL: %v", err)
}
r = f
header.Size = n
} else {
header.Size = resp.ContentLength
}
return header, r, false, nil
})
return archive, closers{resp.Body.Close, archive.Close}, nil
}
func archiveFromDisk(directory string, src, dst string, allowDownload bool, excludes []string, check DirectoryCheck) (io.Reader, io.Closer, error) {
var err error
if filepath.IsAbs(src) {
src, err = filepath.Rel(filepath.Dir(src), src)
if err != nil {
return nil, nil, err
}
}
infos, err := CalcCopyInfo(src, directory, true)
if err != nil {
return nil, nil, err
}
// special case when we are archiving a single file at the root
if len(infos) == 1 && !infos[0].FileInfo.IsDir() && (infos[0].Path == "." || infos[0].Path == "/") {
klog.V(5).Infof("Archiving a file instead of a directory from %s", directory)
infos[0].Path = filepath.Base(directory)
infos[0].FromDir = false
directory = filepath.Dir(directory)
}
options, err := archiveOptionsFor(infos, dst, excludes, check)
if err != nil {
return nil, nil, err
}
klog.V(4).Infof("Tar of %s %#v", directory, options)
rc, err := archive.TarWithOptions(directory, options)
return rc, rc, err
}
func archiveFromFile(file string, src, dst string, excludes []string, check DirectoryCheck) (io.Reader, io.Closer, error) {
var err error
if filepath.IsAbs(src) {
src, err = filepath.Rel(filepath.Dir(src), src)
if err != nil {
return nil, nil, err
}
}
mapper, _, err := newArchiveMapper(src, dst, excludes, true, check)
if err != nil {
return nil, nil, err
}
f, err := os.Open(file)
if err != nil {
return nil, nil, err
}
r, err := transformArchive(f, true, mapper.Filter)
return r, f, err
}
func archiveFromContainer(in io.Reader, src, dst string, excludes []string, check DirectoryCheck) (io.Reader, string, error) {
mapper, archiveRoot, err := newArchiveMapper(src, dst, excludes, false, check)
if err != nil {
return nil, "", err
}
r, err := transformArchive(in, false, mapper.Filter)
return r, archiveRoot, err
}
func transformArchive(r io.Reader, compressed bool, fn TransformFileFunc) (io.Reader, error) {
pr, pw := io.Pipe()
go func() {
if compressed {
in, err := archive.DecompressStream(r)
if err != nil {
pw.CloseWithError(err)
return
}
r = in
}
err := FilterArchive(r, pw, fn)
pw.CloseWithError(err)
}()
return pr, nil
}
// * -> test
// a (dir) -> test
// a (file) -> test
// a (dir) -> test/
// a (file) -> test/
//
func archivePathMapper(src, dst string, isDestDir bool) (fn func(name string, isDir bool) (string, bool)) {
srcPattern := filepath.Clean(src)
if srcPattern == "." {
srcPattern = "*"
}
pattern := filepath.Base(srcPattern)
klog.V(6).Infof("creating mapper for srcPattern=%s pattern=%s dst=%s isDestDir=%t", srcPattern, pattern, dst, isDestDir)
// no wildcards
if !containsWildcards(pattern) {
return func(name string, isDir bool) (string, bool) {
// when extracting from the working directory, Docker prefaces with ./
if strings.HasPrefix(name, "."+string(filepath.Separator)) {
name = name[2:]
}
if name == srcPattern {
if isDir {
return "", false
}
if isDestDir {
return filepath.Join(dst, filepath.Base(name)), true
}
return dst, true
}
remainder := strings.TrimPrefix(name, srcPattern+string(filepath.Separator))
if remainder == name {
return "", false
}
return filepath.Join(dst, remainder), true
}
}
// root with pattern
prefix := filepath.Dir(srcPattern)
if prefix == "." {
return func(name string, isDir bool) (string, bool) {
// match only on the first segment under the prefix
var firstSegment = name
if i := strings.Index(name, string(filepath.Separator)); i != -1 {
firstSegment = name[:i]
}
ok, _ := filepath.Match(pattern, firstSegment)
if !ok {
return "", false
}
return filepath.Join(dst, name), true
}
}
prefix += string(filepath.Separator)
// nested with pattern
return func(name string, isDir bool) (string, bool) {
remainder := strings.TrimPrefix(name, prefix)
if remainder == name {
return "", false
}
// match only on the first segment under the prefix
var firstSegment = remainder
if i := strings.Index(remainder, string(filepath.Separator)); i != -1 {
firstSegment = remainder[:i]
}
ok, _ := filepath.Match(pattern, firstSegment)
if !ok {
return "", false
}
return filepath.Join(dst, remainder), true
}
}
type archiveMapper struct {
exclude *fileutils.PatternMatcher
rename func(name string, isDir bool) (string, bool)
prefix string
resetOwners bool
}
func newArchiveMapper(src, dst string, excludes []string, resetOwners bool, check DirectoryCheck) (*archiveMapper, string, error) {
ex, err := fileutils.NewPatternMatcher(excludes)
if err != nil {
return nil, "", err
}
isDestDir := strings.HasSuffix(dst, "/") || path.Base(dst) == "."
dst = path.Clean(dst)
if !isDestDir && check != nil {
isDir, err := check.IsDirectory(dst)
if err != nil {
return nil, "", err
}
isDestDir = isDir
}
var prefix string
archiveRoot := src
srcPattern := "*"
switch {
case src == "":
return nil, "", fmt.Errorf("source may not be empty")
case src == ".", src == "/":
// no transformation necessary
case strings.HasSuffix(src, "/"), strings.HasSuffix(src, "/."):
src = path.Clean(src)
archiveRoot = src
if archiveRoot != "/" && archiveRoot != "." {
prefix = path.Base(archiveRoot)
}
default:
src = path.Clean(src)
srcPattern = path.Base(src)
archiveRoot = path.Dir(src)
if archiveRoot != "/" && archiveRoot != "." {
prefix = path.Base(archiveRoot)
}
}
if !strings.HasSuffix(archiveRoot, "/") {
archiveRoot += "/"
}
mapperFn := archivePathMapper(srcPattern, dst, isDestDir)
return &archiveMapper{
exclude: ex,
rename: mapperFn,
prefix: prefix,
resetOwners: resetOwners,
}, archiveRoot, nil
}
func (m *archiveMapper) Filter(h *tar.Header, r io.Reader) ([]byte, bool, bool, error) {
if m.resetOwners {
h.Uid, h.Gid = 0, 0
}
// Trim a leading path, the prefix segment (which has no leading or trailing slashes), and
// the final leader segment. Depending on the segment, Docker could return /prefix/ or prefix/.
h.Name = strings.TrimPrefix(h.Name, "/")
if !strings.HasPrefix(h.Name, m.prefix) {
return nil, false, true, nil
}
h.Name = strings.TrimPrefix(strings.TrimPrefix(h.Name, m.prefix), "/")
// skip a file if it doesn't match the src
isDir := h.Typeflag == tar.TypeDir
newName, ok := m.rename(h.Name, isDir)
if !ok {
return nil, false, true, nil
}
if newName == "." {
return nil, false, true, nil
}
// skip based on excludes
if ok, _ := m.exclude.Matches(h.Name); ok {
return nil, false, true, nil
}
h.Name = newName
// include all files
return nil, false, false, nil
}
func archiveOptionsFor(infos []CopyInfo, dst string, excludes []string, check DirectoryCheck) (*archive.TarOptions, error) {
dst = trimLeadingPath(dst)
dstIsDir := strings.HasSuffix(dst, "/") || dst == "." || dst == "/" || strings.HasSuffix(dst, "/.")
dst = trimTrailingSlash(dst)
dstIsRoot := dst == "." || dst == "/"
if !dstIsDir && check != nil {
isDir, err := check.IsDirectory(dst)
if err != nil {
return nil, fmt.Errorf("unable to check whether %s is a directory: %v", dst, err)
}
dstIsDir = isDir
}
options := &archive.TarOptions{
ChownOpts: &idtools.IDPair{UID: 0, GID: 0},
}
pm, err := fileutils.NewPatternMatcher(excludes)
if err != nil {
return options, nil
}
for _, info := range infos {
if ok, _ := pm.Matches(info.Path); ok {
continue
}
srcIsDir := strings.HasSuffix(info.Path, "/") || info.Path == "." || info.Path == "/" || strings.HasSuffix(info.Path, "/.")
infoPath := trimTrailingSlash(info.Path)
options.IncludeFiles = append(options.IncludeFiles, infoPath)
if len(dst) == 0 {
continue
}
if options.RebaseNames == nil {
options.RebaseNames = make(map[string]string)
}
klog.V(6).Infof("len=%d info.FromDir=%t info.IsDir=%t dstIsRoot=%t dstIsDir=%t srcIsDir=%t", len(infos), info.FromDir, info.IsDir(), dstIsRoot, dstIsDir, srcIsDir)
switch {
case len(infos) > 1 && dstIsRoot:
// copying multiple things into root, no rename necessary ([Dockerfile, dir] -> [Dockerfile, dir])
case len(infos) > 1:
// put each input into the target, which is assumed to be a directory ([Dockerfile, dir] -> [a/Dockerfile, a/dir])
options.RebaseNames[infoPath] = path.Join(dst, path.Base(infoPath))
case info.FileInfo.IsDir():
// mapping a directory to a destination, explicit or not ([dir] -> [a])
options.RebaseNames[infoPath] = dst
case info.FromDir:
// this is a file that was part of an explicit directory request, no transformation
options.RebaseNames[infoPath] = path.Join(dst, path.Base(infoPath))
case dstIsDir:
// mapping what is probably a file to a non-root directory ([Dockerfile] -> [dir/Dockerfile])
options.RebaseNames[infoPath] = path.Join(dst, path.Base(infoPath))
default:
// a single file mapped to another single file ([Dockerfile] -> [Dockerfile.2])
options.RebaseNames[infoPath] = dst
}
}
options.ExcludePatterns = excludes
return options, nil
}
func sourceToDestinationName(src, dst string, forceDir bool) string {
switch {
case forceDir, strings.HasSuffix(dst, "/"), path.Base(dst) == ".":
return path.Join(dst, src)
default:
return dst
}
}
// logArchiveOutput prints log info about the provided tar file as it is streamed. If an
// error occurs the remainder of the pipe is read to prevent blocking.
func logArchiveOutput(r io.Reader, prefix string) {
pr, pw := io.Pipe()
r = ioutil.NopCloser(io.TeeReader(r, pw))
go func() {
err := func() error {
tr := tar.NewReader(pr)
for {
h, err := tr.Next()
if err != nil {
return err
}
klog.Infof("%s %s (%d %s)", prefix, h.Name, h.Size, h.FileInfo().Mode())
if _, err := io.Copy(ioutil.Discard, tr); err != nil {
return err
}
}
}()
if err != io.EOF {
klog.Infof("%s: unable to log archive output: %v", prefix, err)
io.Copy(ioutil.Discard, pr)
}
}()
}