1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.arvados.org/arvados.git/sdk/go/arvados"
19 "git.arvados.org/arvados.git/sdk/go/keepclient"
20 "github.com/bmatcuk/doublestar/v4"
23 type printfer interface {
24 Printf(string, ...interface{})
27 var errTooManySymlinks = errors.New("too many symlinks, or symlink cycle")
29 const limitFollowSymlinks = 10
31 type filetodo struct {
37 // copier copies data from a finished container's output path to a new
38 // Arvados collection.
40 // Regular files (and symlinks to regular files) in hostOutputDir are
41 // copied from the local filesystem.
43 // Symlinks to mounted collections, and any collections mounted under
44 // ctrOutputDir, are copied by transforming the relevant parts of the
45 // existing manifests, without moving any data around.
47 // Symlinks to other parts of the container's filesystem result in
52 // manifest, err := (&copier{...}).Copy()
54 client *arvados.Client
55 keepClient IKeepClient
59 bindmounts map[string]bindmount
60 mounts map[string]arvados.Mount
61 secretMounts map[string]arvados.Mount
68 manifestCache map[string]string
71 // Copy copies data as needed, and returns a new manifest.
72 func (cp *copier) Copy() (string, error) {
73 err := cp.walkMount("", cp.ctrOutputDir, limitFollowSymlinks, true)
75 return "", fmt.Errorf("error scanning files to copy to output: %v", err)
77 collfs, err := (&arvados.Collection{ManifestText: cp.manifest}).FileSystem(cp.client, cp.keepClient)
79 return "", fmt.Errorf("error creating Collection.FileSystem: %v", err)
82 // Remove files/dirs that don't match globs (the ones that
83 // were added during cp.walkMount() by copying subtree
84 // manifests into cp.manifest).
85 err = cp.applyGlobsToCollectionFS(collfs)
87 return "", fmt.Errorf("error while removing non-matching files from output collection: %w", err)
89 // Remove files/dirs that don't match globs (the ones that are
90 // stored on the local filesystem and would need to be copied
91 // in copyFile() below).
92 cp.applyGlobsToFilesAndDirs()
93 for _, d := range cp.dirs {
94 err = collfs.Mkdir(d, 0777)
95 if err != nil && err != os.ErrExist {
96 return "", fmt.Errorf("error making directory %q in output collection: %v", d, err)
101 var lastparentdir string
102 for _, f := range cp.files {
103 // If a dir has just had its last file added, do a
104 // full Flush. Otherwise, do a partial Flush (write
105 // full-size blocks, but leave the last short block
106 // open so f's data can be packed with it).
107 dir, _ := filepath.Split(f.dst)
108 if dir != lastparentdir || unflushed > keepclient.BLOCKSIZE {
109 if err := collfs.Flush("/"+lastparentdir, dir != lastparentdir); err != nil {
110 return "", fmt.Errorf("error flushing output collection file data: %v", err)
116 n, err := cp.copyFile(collfs, f)
118 return "", fmt.Errorf("error copying file %q into output collection: %v", f, err)
122 return collfs.MarshalManifest(".")
125 func (cp *copier) matchGlobs(path string, isDir bool) bool {
126 // An entry in the top level of the output directory looks
127 // like "/foo", but globs look like "foo", so we strip the
128 // leading "/" before matching.
129 path = strings.TrimLeft(path, "/")
130 for _, glob := range cp.globs {
131 if !isDir && strings.HasSuffix(glob, "/**") {
132 // doublestar.Match("f*/**", "ff") and
133 // doublestar.Match("f*/**", "ff/gg") both
134 // return true, but (to be compatible with
135 // bash shopt) "ff" should match only if it is
138 // To avoid errant matches, we add the file's
139 // basename to the end of the pattern:
141 // Match("f*/**/ff", "ff") => false
142 // Match("f*/**/gg", "ff/gg") => true
144 // Of course, we need to escape basename in
145 // case it contains *, ?, \, etc.
146 _, name := filepath.Split(path)
147 escapedName := strings.TrimSuffix(strings.Replace(name, "", "\\", -1), "\\")
148 if match, _ := doublestar.Match(glob+"/"+escapedName, path); match {
151 } else if match, _ := doublestar.Match(glob, path); match {
154 // Workaround doublestar bug (v4.6.1).
155 // "foo*/**" should match "foo", but does not,
156 // because isZeroLengthPattern does not accept
157 // "*/**" as a zero length pattern.
158 if trunc := strings.TrimSuffix(glob, "*/**"); trunc != glob {
159 if match, _ := doublestar.Match(trunc, path); match {
168 // Delete entries from cp.files that do not match cp.globs.
170 // Delete entries from cp.dirs that do not match cp.globs.
172 // Ensure parent/ancestor directories of remaining cp.files and
173 // cp.dirs entries are still present in cp.dirs, even if they do not
174 // match cp.globs themselves.
175 func (cp *copier) applyGlobsToFilesAndDirs() {
176 if len(cp.globs) == 0 {
179 keepdirs := make(map[string]bool)
180 for _, path := range cp.dirs {
181 if cp.matchGlobs(path, true) {
182 keepdirs[path] = true
185 for path := range keepdirs {
186 for i, c := range path {
187 if i > 0 && c == '/' {
188 keepdirs[path[:i]] = true
192 var keepfiles []filetodo
193 for _, file := range cp.files {
194 if cp.matchGlobs(file.dst, false) {
195 keepfiles = append(keepfiles, file)
198 for _, file := range keepfiles {
199 for i, c := range file.dst {
200 if i > 0 && c == '/' {
201 keepdirs[file.dst[:i]] = true
206 for path := range keepdirs {
207 cp.dirs = append(cp.dirs, path)
209 sort.Strings(cp.dirs)
213 // Delete files in collfs that do not match cp.globs. Also delete
214 // directories that are empty (after deleting non-matching files) and
215 // do not match cp.globs themselves.
216 func (cp *copier) applyGlobsToCollectionFS(collfs arvados.CollectionFileSystem) error {
217 if len(cp.globs) == 0 {
220 include := make(map[string]bool)
221 err := fs.WalkDir(arvados.FS(collfs), "", func(path string, ent fs.DirEntry, err error) error {
222 if cp.matchGlobs(path, ent.IsDir()) {
223 for i, c := range path {
224 if i > 0 && c == '/' {
225 include[path[:i]] = true
235 err = fs.WalkDir(arvados.FS(collfs), "", func(path string, ent fs.DirEntry, err error) error {
236 if err != nil || path == "" {
240 err := collfs.RemoveAll(path)
253 // Return true if it's possible for any descendant of the given path
254 // to match anything in cp.globs. Used by walkMount to avoid loading
255 // collections that are mounted underneath ctrOutputPath but excluded
257 func (cp *copier) subtreeCouldMatch(path string) bool {
258 if len(cp.globs) == 0 {
261 pathdepth := 1 + strings.Count(path, "/")
262 for _, glob := range cp.globs {
265 for i, c := range glob {
266 if c != '/' || !doublestar.ValidatePattern(glob[:i]) {
267 // Escaped "/", or "/" in a character
268 // class, is not a path separator.
271 if glob[lastsep:i] == "**" {
275 if globdepth++; globdepth == pathdepth {
276 if match, _ := doublestar.Match(glob[:i]+"/*", path+"/z"); match {
282 if globdepth < pathdepth && glob[lastsep:] == "**" {
289 func (cp *copier) copyFile(fs arvados.CollectionFileSystem, f filetodo) (int64, error) {
290 cp.logger.Printf("copying %q (%d bytes)", strings.TrimLeft(f.dst, "/"), f.size)
291 dst, err := fs.OpenFile(f.dst, os.O_CREATE|os.O_WRONLY, 0666)
295 src, err := os.Open(f.src)
301 n, err := io.Copy(dst, src)
306 return n, dst.Close()
309 // Append to cp.manifest, cp.files, and cp.dirs so as to copy src (an
310 // absolute path in the container's filesystem) to dest (an absolute
311 // path in the output collection, or "" for output root).
313 // src must be (or be a descendant of) a readonly "collection" mount,
314 // a writable collection mounted at ctrOutputPath, or a "tmp" mount.
316 // If walkMountsBelow is true, include contents of any collection
317 // mounted below src as well.
318 func (cp *copier) walkMount(dest, src string, maxSymlinks int, walkMountsBelow bool) error {
319 // srcRoot, srcMount indicate the innermost mount that
322 var srcMount arvados.Mount
323 for root, mnt := range cp.mounts {
324 if len(root) > len(srcRoot) && strings.HasPrefix(src+"/", root+"/") {
325 srcRoot, srcMount = root, mnt
328 for root := range cp.secretMounts {
329 if len(root) > len(srcRoot) && strings.HasPrefix(src+"/", root+"/") {
330 // Silently omit secrets, and symlinks to
336 return fmt.Errorf("cannot output file %q: not in any mount", src)
339 // srcRelPath is the path to the file/dir we are trying to
340 // copy, relative to its mount point -- ".", "./foo.txt", ...
341 srcRelPath := filepath.Join(".", srcMount.Path, src[len(srcRoot):])
343 // outputRelPath is the destination path relative to the
344 // output directory. Used for logging and glob matching.
345 var outputRelPath = ""
346 if strings.HasPrefix(src, cp.ctrOutputDir) {
347 outputRelPath = strings.TrimPrefix(src[len(cp.ctrOutputDir):], "/")
349 if outputRelPath == "" {
350 // blank means copy a whole directory, so replace it
351 // with a wildcard to make it a little clearer what's
352 // going on since outputRelPath is only used for logging
357 case srcMount.ExcludeFromOutput:
358 case outputRelPath != "*" && !cp.subtreeCouldMatch(outputRelPath):
359 cp.logger.Printf("not copying %q because contents cannot match output globs", outputRelPath)
361 case srcMount.Kind == "tmp":
362 // Handle by walking the host filesystem.
363 return cp.walkHostFS(dest, src, maxSymlinks, walkMountsBelow)
364 case srcMount.Kind != "collection":
365 return fmt.Errorf("%q: unsupported mount %q in output (kind is %q)", src, srcRoot, srcMount.Kind)
366 case !srcMount.Writable:
367 cp.logger.Printf("copying %q from %v/%v", outputRelPath, srcMount.PortableDataHash, strings.TrimPrefix(srcRelPath, "./"))
368 mft, err := cp.getManifest(srcMount.PortableDataHash)
372 err = cp.copyFromCollection(dest, &arvados.Collection{ManifestText: mft}, srcRelPath)
377 cp.logger.Printf("copying %q", outputRelPath)
378 hostRoot, err := cp.hostRoot(srcRoot)
382 f, err := os.Open(filepath.Join(hostRoot, ".arvados#collection"))
387 var coll arvados.Collection
388 err = json.NewDecoder(f).Decode(&coll)
392 err = cp.copyFromCollection(dest, &coll, srcRelPath)
398 return cp.walkMountsBelow(dest, src)
403 func (cp *copier) copyFromCollection(dest string, coll *arvados.Collection, srcRelPath string) error {
404 tmpfs, err := coll.FileSystem(cp.client, cp.keepClient)
408 snap, err := arvados.Snapshot(tmpfs, srcRelPath)
412 tmpfs, err = (&arvados.Collection{}).FileSystem(cp.client, cp.keepClient)
416 // Create ancestors of dest, if necessary.
417 for i, c := range dest {
418 if i > 0 && c == '/' {
419 err = tmpfs.Mkdir(dest[:i], 0777)
420 if err != nil && !os.IsExist(err) {
425 err = arvados.Splice(tmpfs, dest, snap)
429 mtxt, err := tmpfs.MarshalManifest(".")
437 func (cp *copier) walkMountsBelow(dest, src string) error {
438 for mnt, mntinfo := range cp.mounts {
439 if !strings.HasPrefix(mnt, src+"/") {
442 if cp.copyRegularFiles(mntinfo) {
443 // These got copied into the nearest parent
444 // mount as regular files during setup, so
445 // they get copied as regular files when we
446 // process the parent. Output will reflect any
447 // changes and deletions done by the
451 // Example: we are processing dest=/foo src=/mnt1/dir1
452 // (perhaps we followed a symlink /outdir/foo ->
453 // /mnt1/dir1). Caller has already processed the
454 // collection mounted at /mnt1, but now we find that
455 // /mnt1/dir1/mnt2 is also a mount, so we need to copy
456 // src=/mnt1/dir1/mnt2 to dest=/foo/mnt2.
458 // We handle all descendants of /mnt1/dir1 in this
459 // loop instead of using recursion:
460 // /mnt1/dir1/mnt2/mnt3 is a child of both /mnt1 and
461 // /mnt1/dir1/mnt2, but we only want to walk it
462 // once. (This simplification is safe because mounted
463 // collections cannot contain symlinks.)
464 err := cp.walkMount(dest+mnt[len(src):], mnt, 0, false)
472 // Add entries to cp.dirs and cp.files so as to copy src (an absolute
473 // path in the container's filesystem which corresponds to a real file
474 // or directory in cp.hostOutputDir) to dest (an absolute path in the
475 // output collection, or "" for output root).
477 // Always follow symlinks.
479 // If includeMounts is true, include mounts at and below src.
480 // Otherwise, skip them.
481 func (cp *copier) walkHostFS(dest, src string, maxSymlinks int, includeMounts bool) error {
483 err := cp.walkMountsBelow(dest, src)
489 hostsrc := cp.hostOutputDir + src[len(cp.ctrOutputDir):]
491 // If src is a symlink, walk its target.
492 fi, err := os.Lstat(hostsrc)
494 return fmt.Errorf("lstat %q: %s", src, err)
496 if fi.Mode()&os.ModeSymlink != 0 {
498 return errTooManySymlinks
500 target, err := os.Readlink(hostsrc)
502 return fmt.Errorf("readlink %q: %s", src, err)
504 if !strings.HasPrefix(target, "/") {
505 target = filepath.Join(filepath.Dir(src), target)
507 return cp.walkMount(dest, target, maxSymlinks-1, true)
510 // If src is a regular directory, append it to cp.dirs and
511 // walk each of its children. (If there are no children,
512 // create an empty file "dest/.keep".)
513 if fi.Mode().IsDir() {
515 cp.dirs = append(cp.dirs, dest)
517 dir, err := os.Open(hostsrc)
519 return fmt.Errorf("open %q: %s", src, err)
521 names, err := dir.Readdirnames(-1)
524 return fmt.Errorf("readdirnames %q: %s", src, err)
528 cp.files = append(cp.files, filetodo{
530 dst: dest + "/.keep",
536 for _, name := range names {
537 dest, src := dest+"/"+name, src+"/"+name
538 if _, isSecret := cp.secretMounts[src]; isSecret {
541 if mntinfo, isMount := cp.mounts[src]; isMount && !cp.copyRegularFiles(mntinfo) {
542 // If a regular file/dir somehow
543 // exists at a path that's also a
544 // mount target, ignore the file --
545 // the mount has already been included
546 // with walkMountsBelow().
548 // (...except mount types that are
549 // handled as regular files.)
551 } else if isMount && !cp.subtreeCouldMatch(src[len(cp.ctrOutputDir)+1:]) {
554 err = cp.walkHostFS(dest, src, maxSymlinks, false)
562 // If src is a regular file, append it to cp.files.
563 if fi.Mode().IsRegular() {
564 cp.files = append(cp.files, filetodo{
571 cp.logger.Printf("Skipping unsupported file type (mode %o) in output dir: %q", fi.Mode(), src)
575 // Return the host path that was mounted at the given path in the
577 func (cp *copier) hostRoot(ctrRoot string) (string, error) {
578 if ctrRoot == cp.ctrOutputDir {
579 return cp.hostOutputDir, nil
581 if mnt, ok := cp.bindmounts[ctrRoot]; ok {
582 return mnt.HostPath, nil
584 return "", fmt.Errorf("not bind-mounted: %q", ctrRoot)
587 func (cp *copier) copyRegularFiles(m arvados.Mount) bool {
588 return m.Kind == "text" || m.Kind == "json" || (m.Kind == "collection" && m.Writable)
591 func (cp *copier) getManifest(pdh string) (string, error) {
592 if mft, ok := cp.manifestCache[pdh]; ok {
595 var coll arvados.Collection
596 err := cp.client.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+pdh, nil, nil)
598 return "", fmt.Errorf("error retrieving collection record for %q: %s", pdh, err)
600 if cp.manifestCache == nil {
601 cp.manifestCache = make(map[string]string)
603 cp.manifestCache[pdh] = coll.ManifestText
604 return coll.ManifestText, nil