Debian Codegraph @

dockerclient/archive.go

raw
1 package dockerclient
2
3 import (
4 "archive/tar"
5 "bytes"
6 "errors"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "os"
12 "path"
13 "path/filepath"
14 "strings"
15
16 "github.com/moby/patternmatcher"
17 "go.podman.io/storage/pkg/archive"
18 "go.podman.io/storage/pkg/fileutils"
19 "go.podman.io/storage/pkg/idtools"
20 "go.podman.io/storage/pkg/ioutils"
21 "k8s.io/klog"
22 )
23
24 var isArchivePath = archive.IsArchivePath
25 var dstNeedsToBeDirectoryError = errors.New("copying would overwrite content that was already copied; destination needs to be a directory")
26
27 // TransformFileFunc is given a chance to transform an arbitrary input file.
28 type TransformFileFunc func(h *tar.Header, r io.Reader) (data []byte, update bool, skip bool, err error)
29
30 // FetchArchiveFunc retrieves an entire second copy of the archive we're
31 // processing, so that we can fetch something from it that we discarded
32 // earlier. This is expensive, so it is only called when it's needed.
33 type FetchArchiveFunc func(pw *io.PipeWriter)
34
35 // FilterArchive transforms the provided input archive to a new archive,
36 // giving the fn a chance to transform arbitrary files.
37 func FilterArchive(r io.Reader, w io.Writer, fn TransformFileFunc) error {
38 tr := tar.NewReader(r)
39 tw := tar.NewWriter(w)
40
41 for {
42 h, err := tr.Next()
43 if err == io.EOF {
44 return tw.Close()
45 }
46 if err != nil {
47 return err
48 }
49
50 var body io.Reader = tr
51 name := h.Name
52 data, ok, skip, err := fn(h, tr)
53 klog.V(6).Infof("Transform %s(0%o) -> %s: data=%t ok=%t skip=%t err=%v", name, h.Mode, h.Name, data != nil, ok, skip, err)
54 if err != nil {
55 return err
56 }
57 if skip {
58 continue
59 }
60 if ok {
61 h.Size = int64(len(data))
62 body = bytes.NewBuffer(data)
63 }
64 if err := tw.WriteHeader(h); err != nil {
65 return err
66 }
67 if _, err := io.Copy(tw, body); err != nil {
68 return err
69 }
70 }
71 }
72
73 type CreateFileFunc func() (*tar.Header, io.ReadCloser, bool, error)
74
75 func NewLazyArchive(fn CreateFileFunc) io.ReadCloser {
76 pr, pw := io.Pipe()
77 tw := tar.NewWriter(pw)
78 go func() {
79 for {
80 h, r, more, err := fn()
81 if err != nil {
82 pw.CloseWithError(err)
83 return
84 }
85 if h == nil {
86 tw.Flush()
87 pw.Close()
88 return
89 }
90 if err := tw.WriteHeader(h); err != nil {
91 r.Close()
92 pw.CloseWithError(err)
93 return
94 }
95 n, err := io.Copy(tw, &io.LimitedReader{R: r, N: h.Size})
96 r.Close()
97 if err != nil {
98 pw.CloseWithError(err)
99 return
100 }
101 if n != h.Size {
102 pw.CloseWithError(fmt.Errorf("short read for %s", h.Name))
103 return
104 }
105 if !more {
106 tw.Flush()
107 pw.Close()
108 return
109 }
110 }
111 }()
112 return pr
113 }
114
115 func archiveFromURL(src, dst, tempDir string, check DirectoryCheck) (io.Reader, io.Closer, error) {
116 // get filename from URL
117 u, err := url.Parse(src)
118 if err != nil {
119 return nil, nil, err
120 }
121 base := path.Base(u.Path)
122 if base == "." {
123 return nil, nil, fmt.Errorf("cannot determine filename from url: %s", u)
124 }
125 resp, err := http.Get(src)
126 if err != nil {
127 return nil, nil, err
128 }
129 archive := NewLazyArchive(func() (*tar.Header, io.ReadCloser, bool, error) {
130 if resp.StatusCode >= 400 {
131 return nil, nil, false, fmt.Errorf("server returned a status code >= 400: %s", resp.Status)
132 }
133
134 header := &tar.Header{
135 Name: sourceToDestinationName(path.Base(u.Path), dst, false),
136 Mode: 0600,
137 }
138 r := resp.Body
139 if resp.ContentLength == -1 {
140 f, err := os.CreateTemp(tempDir, "url")
141 if err != nil {
142 return nil, nil, false, fmt.Errorf("unable to create temporary file for source URL: %v", err)
143 }
144 n, err := io.Copy(f, resp.Body)
145 if err != nil {
146 f.Close()
147 return nil, nil, false, fmt.Errorf("unable to download source URL: %v", err)
148 }
149 if err := f.Close(); err != nil {
150 return nil, nil, false, fmt.Errorf("unable to write source URL: %v", err)
151 }
152 f, err = os.Open(f.Name())
153 if err != nil {
154 return nil, nil, false, fmt.Errorf("unable to open downloaded source URL: %v", err)
155 }
156 r = f
157 header.Size = n
158 } else {
159 header.Size = resp.ContentLength
160 }
161 return header, r, false, nil
162 })
163 return archive, closers{resp.Body.Close, archive.Close}, nil
164 }
165
166 func archiveFromDisk(directory string, src, dst string, allowDownload bool, excludes []string, check DirectoryCheck) (io.Reader, io.Closer, error) {
167 var err error
168 if filepath.IsAbs(src) {
169 src, err = filepath.Rel(directory, filepath.Join(directory, src))
170 if err != nil {
171 return nil, nil, err
172 }
173 }
174
175 infos, err := CalcCopyInfo(src, directory, true)
176 if err != nil {
177 return nil, nil, err
178 }
179
180 // special case when we are archiving a single file at the root
181 if len(infos) == 1 && !infos[0].FileInfo.IsDir() && (infos[0].Path == "." || infos[0].Path == "/") {
182 klog.V(5).Infof("Archiving a file instead of a directory from %s", directory)
183 infos[0].Path = filepath.Base(directory)
184 infos[0].FromDir = false
185 directory = filepath.Dir(directory)
186 }
187
188 options, err := archiveOptionsFor(directory, infos, dst, excludes, allowDownload, check)
189 if err != nil {
190 return nil, nil, err
191 }
192
193 pipeReader, pipeWriter := io.Pipe() // the archive we're creating
194
195 includeFiles := options.IncludeFiles
196 var returnedError error
197 go func() {
198 defer pipeWriter.Close()
199 tw := tar.NewWriter(pipeWriter)
200 defer tw.Close()
201 var nonArchives []string
202 for _, includeFile := range includeFiles {
203 if allowDownload && src != "." && src != "/" && isArchivePath(filepath.Join(directory, includeFile)) {
204 // it's an archive -> copy each item to the
205 // archive being written to the pipe writer
206 klog.V(4).Infof("Extracting %s", includeFile)
207 if err := func() error {
208 f, err := os.Open(filepath.Join(directory, includeFile))
209 if err != nil {
210 return err
211 }
212 defer f.Close()
213 dc, err := archive.DecompressStream(f)
214 if err != nil {
215 return err
216 }
217 defer dc.Close()
218 tr := tar.NewReader(dc)
219 hdr, err := tr.Next()
220 for err == nil {
221 if renamed, ok := options.RebaseNames[includeFile]; ok {
222 hdr.Name = strings.TrimSuffix(renamed, includeFile) + hdr.Name
223 if hdr.Typeflag == tar.TypeLink {
224 hdr.Linkname = strings.TrimSuffix(renamed, includeFile) + hdr.Linkname
225 }
226 }
227 tw.WriteHeader(hdr)
228 _, err = io.Copy(tw, tr)
229 if err != nil {
230 break
231 }
232 hdr, err = tr.Next()
233 }
234 if err != nil && err != io.EOF {
235 return err
236 }
237 return nil
238 }(); err != nil {
239 returnedError = err
240 break
241 }
242 continue
243 }
244 nonArchives = append(nonArchives, includeFile)
245 }
246 if len(nonArchives) > 0 && returnedError == nil {
247 // the not-archive items -> add them all to the archive as-is
248 options.IncludeFiles = nonArchives
249 klog.V(4).Infof("Tar of %s %#v", directory, options)
250 rc, err := archive.TarWithOptions(directory, options)
251 if err != nil {
252 returnedError = err
253 return
254 }
255 defer rc.Close()
256 tr := tar.NewReader(rc)
257 hdr, err := tr.Next()
258 for err == nil {
259 tw.WriteHeader(hdr)
260 _, err = io.Copy(tw, tr)
261 if err != nil {
262 break
263 }
264 hdr, err = tr.Next()
265 }
266 if err != nil && err != io.EOF {
267 returnedError = err
268 return
269 }
270 }
271 }()
272
273 // the reader should close the pipe, and also get any error we need to report
274 readWrapper := ioutils.NewReadCloserWrapper(pipeReader, func() error {
275 if err := pipeReader.Close(); err != nil {
276 return err
277 }
278 return returnedError
279 })
280
281 return readWrapper, readWrapper, err
282 }
283
284 func archiveFromFile(file string, src, dst string, excludes []string, check DirectoryCheck) (io.Reader, io.Closer, error) {
285 var err error
286 if filepath.IsAbs(src) {
287 src, err = filepath.Rel(filepath.Dir(src), src)
288 if err != nil {
289 return nil, nil, err
290 }
291 }
292
293 refetch := func(pw *io.PipeWriter) {
294 f, err := os.Open(file)
295 if err != nil {
296 pw.CloseWithError(err)
297 return
298 }
299 defer f.Close()
300 dc, err := archive.DecompressStream(f)
301 if err != nil {
302 pw.CloseWithError(err)
303 return
304 }
305 defer dc.Close()
306 _, err = io.Copy(pw, dc)
307 pw.CloseWithError(err)
308 }
309
310 mapper, _, err := newArchiveMapper(src, dst, excludes, false, true, check, refetch, true)
311 if err != nil {
312 return nil, nil, err
313 }
314
315 f, err := os.Open(file)
316 if err != nil {
317 return nil, nil, err
318 }
319
320 r, err := transformArchive(f, true, mapper.Filter)
321 cc := newCloser(func() error {
322 err := f.Close()
323 if mapper.foundItems == 0 {
324 return fmt.Errorf("%s: %w", src, os.ErrNotExist)
325 }
326 return err
327 })
328 return r, cc, err
329 }
330
331 func archiveFromContainer(in io.Reader, src, dst string, excludes []string, check DirectoryCheck, refetch FetchArchiveFunc, assumeDstIsDirectory bool) (io.ReadCloser, string, error) {
332 mapper, archiveRoot, err := newArchiveMapper(src, dst, excludes, true, false, check, refetch, assumeDstIsDirectory)
333 if err != nil {
334 return nil, "", err
335 }
336
337 r, err := transformArchive(in, false, mapper.Filter)
338 rc := readCloser{Reader: r, Closer: newCloser(func() error {
339 if mapper.foundItems == 0 {
340 return fmt.Errorf("%s: %w", src, os.ErrNotExist)
341 }
342 return nil
343 })}
344 return rc, archiveRoot, err
345 }
346
347 func transformArchive(r io.Reader, compressed bool, fn TransformFileFunc) (io.Reader, error) {
348 pr, pw := io.Pipe()
349 go func() {
350 if compressed {
351 in, err := archive.DecompressStream(r)
352 if err != nil {
353 pw.CloseWithError(err)
354 return
355 }
356 r = in
357 }
358 err := FilterArchive(r, pw, fn)
359 pw.CloseWithError(err)
360 }()
361 return pr, nil
362 }
363
364 // * -> test
365 // a (dir) -> test
366 // a (file) -> test
367 // a (dir) -> test/
368 // a (file) -> test/
369 func archivePathMapper(src, dst string, isDestDir bool) (fn func(itemCount *int, name string, isDir bool) (string, bool, error)) {
370 srcPattern := filepath.Clean(src)
371 if srcPattern == "." {
372 srcPattern = "*"
373 }
374 pattern := filepath.Base(srcPattern)
375
376 klog.V(6).Infof("creating mapper for srcPattern=%s pattern=%s dst=%s isDestDir=%t", srcPattern, pattern, dst, isDestDir)
377
378 // no wildcards
379 if !containsWildcards(pattern) {
380 return func(itemCount *int, name string, isDir bool) (string, bool, error) {
381 // when extracting from the working directory, Docker prefaces with ./
382 if strings.HasPrefix(name, "."+string(filepath.Separator)) {
383 name = name[2:]
384 }
385 if name == srcPattern {
386 if isDir { // the source is a directory: this directory; skip it
387 return "", false, nil
388 }
389 if isDestDir { // the destination is a directory, put this under it
390 return filepath.Join(dst, filepath.Base(name)), true, nil
391 }
392 // the source is a non-directory: copy to the destination's name
393 if itemCount != nil && *itemCount != 0 { // but we've already written something there
394 return "", false, dstNeedsToBeDirectoryError // tell the caller to start over
395 }
396 return dst, true, nil
397 }
398
399 // source is a directory, this is under it; put this under the destination directory
400 remainder := strings.TrimPrefix(name, srcPattern+string(filepath.Separator))
401 if remainder == name {
402 return "", false, nil
403 }
404 return filepath.Join(dst, remainder), true, nil
405 }
406 }
407
408 // root with pattern
409 prefix := filepath.Dir(srcPattern)
410 if prefix == "." {
411 return func(itemCount *int, name string, isDir bool) (string, bool, error) {
412 // match only on the first segment under the prefix
413 var firstSegment = name
414 if i := strings.Index(name, string(filepath.Separator)); i != -1 {
415 firstSegment = name[:i]
416 }
417 ok, _ := filepath.Match(pattern, firstSegment)
418 if !ok {
419 return "", false, nil
420 }
421 if !isDestDir && !isDir { // the destination is not a directory, put this right there
422 if itemCount != nil && *itemCount != 0 { // but we've already written something there
423 return "", false, dstNeedsToBeDirectoryError // tell the caller to start over
424 }
425 return dst, true, nil
426 }
427 return filepath.Join(dst, name), true, nil
428 }
429 }
430 prefix += string(filepath.Separator)
431
432 // nested with pattern
433 return func(_ *int, name string, isDir bool) (string, bool, error) {
434 remainder := strings.TrimPrefix(name, prefix)
435 if remainder == name {
436 return "", false, nil
437 }
438 // match only on the first segment under the prefix
439 var firstSegment = remainder
440 if i := strings.Index(remainder, string(filepath.Separator)); i != -1 {
441 firstSegment = remainder[:i]
442 }
443 ok, _ := filepath.Match(pattern, firstSegment)
444 if !ok {
445 return "", false, nil
446 }
447 return filepath.Join(dst, remainder), true, nil
448 }
449 }
450
451 type archiveMapper struct {
452 exclude *fileutils.PatternMatcher
453 rename func(itemCount *int, name string, isDir bool) (string, bool, error)
454 prefix string
455 dst string
456 resetDstMode bool
457 resetOwners bool
458 foundItems int
459 refetch FetchArchiveFunc
460 renameLinks map[string]string
461 }
462
463 func newArchiveMapper(src, dst string, excludes []string, resetDstMode, resetOwners bool, check DirectoryCheck, refetch FetchArchiveFunc, assumeDstIsDirectory bool) (*archiveMapper, string, error) {
464 ex, err := fileutils.NewPatternMatcher(excludes)
465 if err != nil {
466 return nil, "", err
467 }
468
469 isDestDir := strings.HasSuffix(dst, "/") || path.Base(dst) == "." || strings.HasSuffix(src, "/") || path.Base(src) == "." || assumeDstIsDirectory
470 dst = path.Clean(dst)
471 if !isDestDir && check != nil {
472 isDir, err := check.IsDirectory(dst)
473 if err != nil {
474 return nil, "", err
475 }
476 isDestDir = isDir
477 }
478
479 var prefix string
480 archiveRoot := src
481 srcPattern := "*"
482 switch {
483 case src == "":
484 return nil, "", fmt.Errorf("source may not be empty")
485 case src == ".", src == "/":
486 // no transformation necessary
487 case strings.HasSuffix(src, "/"), strings.HasSuffix(src, "/."):
488 src = path.Clean(src)
489 archiveRoot = src
490 if archiveRoot != "/" && archiveRoot != "." {
491 prefix = path.Base(archiveRoot)
492 }
493 default:
494 src = path.Clean(src)
495 srcPattern = path.Base(src)
496 archiveRoot = path.Dir(src)
497 if archiveRoot != "/" && archiveRoot != "." {
498 prefix = path.Base(archiveRoot)
499 }
500 }
501 if !strings.HasSuffix(archiveRoot, "/") {
502 archiveRoot += "/"
503 }
504
505 mapperFn := archivePathMapper(srcPattern, dst, isDestDir)
506
507 return &archiveMapper{
508 exclude: ex,
509 rename: mapperFn,
510 prefix: prefix,
511 dst: dst,
512 resetDstMode: resetDstMode,
513 resetOwners: resetOwners,
514 refetch: refetch,
515 renameLinks: make(map[string]string),
516 }, archiveRoot, nil
517 }
518
519 func (m *archiveMapper) Filter(h *tar.Header, r io.Reader) ([]byte, bool, bool, error) {
520 if m.resetOwners {
521 h.Uid, h.Gid = 0, 0
522 }
523 // Trim a leading path, the prefix segment (which has no leading or trailing slashes), and
524 // the final leader segment. Depending on the segment, Docker could return /prefix/ or prefix/.
525 h.Name = strings.TrimPrefix(h.Name, "/")
526 if !strings.HasPrefix(h.Name, m.prefix) {
527 return nil, false, true, nil
528 }
529 h.Name = strings.TrimPrefix(strings.TrimPrefix(h.Name, m.prefix), "/")
530
531 // skip a file if it doesn't match the src
532 isDir := h.Typeflag == tar.TypeDir
533 newName, ok, err := m.rename(&m.foundItems, h.Name, isDir)
534 if err != nil {
535 return nil, false, true, err
536 }
537 if !ok {
538 return nil, false, true, nil
539 }
540 if newName == "." {
541 return nil, false, true, nil
542 }
543 // skip based on excludes
544 if ok, _ := m.exclude.Matches(h.Name); ok {
545 return nil, false, true, nil
546 }
547
548 m.foundItems++
549
550 h.Name = newName
551
552 if m.resetDstMode && isDir && path.Clean(h.Name) == path.Clean(m.dst) {
553 h.Mode = (h.Mode & ^0o777) | 0o755
554 }
555
556 if h.Typeflag == tar.TypeLink {
557 if newTarget, ok := m.renameLinks[h.Linkname]; ok {
558 // we already replaced the original link target, so make this a link to the file we copied
559 klog.V(6).Infof("Replaced link target %s -> %s: ok=%t", h.Linkname, newTarget, ok)
560 h.Linkname = newTarget
561 } else {
562 needReplacement := false
563 // run the link target name through the same mapping the Name
564 // in the target's entry would have gotten
565 linkName := strings.TrimPrefix(h.Linkname, "/")
566 if !strings.HasPrefix(linkName, m.prefix) {
567 // the link target didn't start with the prefix, so it wasn't passed along
568 needReplacement = true
569 }
570 var newTarget string
571 if !needReplacement {
572 linkName = strings.TrimPrefix(strings.TrimPrefix(linkName, m.prefix), "/")
573 var ok bool
574 if newTarget, ok, err = m.rename(nil, linkName, false); err != nil {
575 return nil, false, true, err
576 }
577 if !ok || newTarget == "." {
578 // the link target wasn't passed along
579 needReplacement = true
580 }
581 }
582 if !needReplacement {
583 if ok, _ := m.exclude.Matches(linkName); ok {
584 // link target was skipped based on excludes
585 needReplacement = true
586 }
587 }
588 if !needReplacement {
589 // the link target was passed along, everything's fine
590 klog.V(6).Infof("Transform link target %s -> %s: ok=%t skip=%t", h.Linkname, newTarget, ok, true)
591 h.Linkname = newTarget
592 } else {
593 // the link target wasn't passed along, splice it back in as this file
594 if m.refetch == nil {
595 return nil, false, true, fmt.Errorf("need to create %q as a hard link to %q, but did not copy %q", h.Name, h.Linkname, h.Linkname)
596 }
597 pr, pw := io.Pipe()
598 go m.refetch(pw)
599 tr2 := tar.NewReader(pr)
600 rehdr, err := tr2.Next()
601 for err == nil && rehdr.Name != h.Linkname {
602 rehdr, err = tr2.Next()
603 }
604 if err != nil {
605 pr.Close()
606 return nil, false, true, fmt.Errorf("needed to create %q as a hard link to %q, but got error refetching %q: %v", h.Name, h.Linkname, h.Linkname, err)
607 }
608 buf, err := io.ReadAll(pr)
609 pr.Close()
610 if err != nil {
611 return nil, false, true, fmt.Errorf("needed to create %q as a hard link to %q, but got error refetching contents of %q: %v", h.Name, h.Linkname, h.Linkname, err)
612 }
613 m.renameLinks[h.Linkname] = h.Name
614 h.Typeflag = tar.TypeReg
615 h.Size, h.Mode = rehdr.Size, rehdr.Mode
616 h.Uid, h.Gid = rehdr.Uid, rehdr.Gid
617 h.Uname, h.Gname = rehdr.Uname, rehdr.Gname
618 h.ModTime, h.AccessTime, h.ChangeTime = rehdr.ModTime, rehdr.AccessTime, rehdr.ChangeTime
619 h.Xattrs = nil
620 for k, v := range rehdr.Xattrs {
621 if h.Xattrs != nil {
622 h.Xattrs = make(map[string]string)
623 }
624 h.Xattrs[k] = v
625 }
626 klog.V(6).Infof("Transform link %s -> reg %s", h.Linkname, h.Name)
627 h.Linkname = ""
628 return buf, true, false, nil
629 }
630 }
631 }
632
633 // include all files
634 return nil, false, false, nil
635 }
636
637 func archiveOptionsFor(directory string, infos []CopyInfo, dst string, excludes []string, allowDownload bool, check DirectoryCheck) (*archive.TarOptions, error) {
638 dst = trimLeadingPath(dst)
639 dstIsDir := strings.HasSuffix(dst, "/") || dst == "." || dst == "/" || strings.HasSuffix(dst, "/.")
640 dst = trimTrailingSlash(dst)
641 dstIsRoot := dst == "." || dst == "/"
642
643 if !dstIsDir && check != nil {
644 isDir, err := check.IsDirectory(dst)
645 if err != nil {
646 return nil, fmt.Errorf("unable to check whether %s is a directory: %v", dst, err)
647 }
648 dstIsDir = isDir
649 }
650
651 options := &archive.TarOptions{
652 ChownOpts: &idtools.IDPair{UID: 0, GID: 0},
653 }
654
655 pm, err := patternmatcher.New(excludes)
656 if err != nil {
657 return options, nil
658 }
659
660 if !dstIsDir {
661 for _, info := range infos {
662 if ok, _ := pm.MatchesOrParentMatches(info.Path); ok {
663 continue
664 }
665 infoPath := info.Path
666 if directory != "" {
667 infoPath = filepath.Join(directory, infoPath)
668 }
669 if allowDownload && isArchivePath(infoPath) {
670 dstIsDir = true
671 break
672 }
673 }
674 }
675
676 for _, info := range infos {
677 if ok, _ := pm.MatchesOrParentMatches(info.Path); ok {
678 continue
679 }
680
681 srcIsDir := strings.HasSuffix(info.Path, "/") || info.Path == "." || info.Path == "/" || strings.HasSuffix(info.Path, "/.")
682 infoPath := trimTrailingSlash(info.Path)
683
684 options.IncludeFiles = append(options.IncludeFiles, infoPath)
685 if len(dst) == 0 {
686 continue
687 }
688 if options.RebaseNames == nil {
689 options.RebaseNames = make(map[string]string)
690 }
691
692 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)
693 switch {
694 case len(infos) > 1 && dstIsRoot:
695 // copying multiple things into root, no rename necessary ([Dockerfile, dir] -> [Dockerfile, dir])
696 case len(infos) > 1:
697 // put each input into the target, which is assumed to be a directory ([Dockerfile, dir] -> [a/Dockerfile, a/dir])
698 options.RebaseNames[infoPath] = path.Join(dst, path.Base(infoPath))
699 case info.FileInfo.IsDir():
700 // mapping a directory to a destination, explicit or not ([dir] -> [a])
701 options.RebaseNames[infoPath] = dst
702 case info.FromDir:
703 // this is a file that was part of an explicit directory request, no transformation
704 options.RebaseNames[infoPath] = path.Join(dst, path.Base(infoPath))
705 case dstIsDir:
706 // mapping what is probably a file to a non-root directory ([Dockerfile] -> [dir/Dockerfile])
707 options.RebaseNames[infoPath] = path.Join(dst, path.Base(infoPath))
708 default:
709 // a single file mapped to another single file ([Dockerfile] -> [Dockerfile.2])
710 options.RebaseNames[infoPath] = dst
711 }
712 }
713
714 options.ExcludePatterns = excludes
715 return options, nil
716 }
717
718 func sourceToDestinationName(src, dst string, forceDir bool) string {
719 switch {
720 case forceDir, strings.HasSuffix(dst, "/"), path.Base(dst) == ".":
721 return path.Join(dst, src)
722 default:
723 return dst
724 }
725 }
726
727 // logArchiveOutput prints log info about the provided tar file as it is streamed. If an
728 // error occurs the remainder of the pipe is read to prevent blocking.
729 func logArchiveOutput(r io.Reader, prefix string) {
730 pr, pw := io.Pipe()
731 r = io.NopCloser(io.TeeReader(r, pw))
732 go func() {
733 err := func() error {
734 tr := tar.NewReader(pr)
735 for {
736 h, err := tr.Next()
737 if err != nil {
738 return err
739 }
740 klog.Infof("%s %s (%d %s)", prefix, h.Name, h.Size, h.FileInfo().Mode())
741 if _, err := io.Copy(io.Discard, tr); err != nil {
742 return err
743 }
744 }
745 }()
746 if err != io.EOF {
747 klog.Infof("%s: unable to log archive output: %v", prefix, err)
748 io.Copy(io.Discard, pr)
749 }
750 }()
751 }
752
753 type closer struct {
754 closefn func() error
755 }
756
757 func newCloser(closeFunction func() error) *closer {
758 return &closer{closefn: closeFunction}
759 }
760
761 func (r *closer) Close() error {
762 return r.closefn()
763 }
764
765 type readCloser struct {
766 io.Reader
767 io.Closer
768 }