1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
23 ErrReadOnlyFile = errors.New("read-only file")
24 ErrNegativeOffset = errors.New("cannot seek to negative offset")
25 ErrInvalidOperation = errors.New("invalid operation")
26 ErrInvalidArgument = errors.New("invalid argument")
27 ErrDirectoryNotEmpty = errors.New("directory not empty")
28 ErrWriteOnlyMode = errors.New("file is O_WRONLY")
29 ErrSyncNotSupported = errors.New("O_SYNC flag is not supported")
30 ErrIsDirectory = errors.New("cannot rename file to overwrite existing directory")
31 ErrNotADirectory = errors.New("not a directory")
32 ErrPermission = os.ErrPermission
33 DebugLocksPanicMode = false
36 type syncer interface {
40 func debugPanicIfNotLocked(l sync.Locker, writing bool) {
41 if !DebugLocksPanicMode {
45 if rl, ok := l.(interface {
50 // Fail if we can grab the read lock during an
51 // operation that purportedly has write lock.
65 panic("bug: caller-must-have-lock func called, but nobody has lock")
69 // A File is an *os.File-like interface for reading and writing files
77 Readdir(int) ([]os.FileInfo, error)
78 Stat() (os.FileInfo, error)
81 // Create a snapshot of a file or directory tree, which can
82 // then be spliced onto a different path or a different
84 Snapshot() (*Subtree, error)
85 // Replace this file or directory with the given snapshot.
86 // The target must be inside a collection: Splice returns an
87 // error if the File is a virtual file or directory like
88 // by_id, a project directory, .arvados#collection,
89 // etc. Splice can replace directories with regular files and
90 // vice versa, except it cannot replace the root directory of
91 // a collection with a regular file.
92 Splice(snapshot *Subtree) error
95 // A Subtree is a detached part of a filesystem tree that can be
96 // spliced into a filesystem via (File)Splice().
101 // A FileSystem is an http.Filesystem plus Stat() and support for
102 // opening writable files. All methods are safe to call from multiple
104 type FileSystem interface {
110 // filesystem-wide lock: used by Rename() to prevent deadlock
111 // while locking multiple inodes.
114 // throttle for limiting concurrent background writers
117 // create a new node with nil parent.
118 newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error)
120 // analogous to os.Stat()
121 Stat(name string) (os.FileInfo, error)
123 // analogous to os.Create(): create/truncate a file and open it O_RDWR.
124 Create(name string) (File, error)
126 // Like os.OpenFile(): create or open a file or directory.
128 // If flag&os.O_EXCL==0, it opens an existing file or
129 // directory if one exists. If flag&os.O_CREATE!=0, it creates
130 // a new empty file or directory if one does not already
133 // When creating a new item, perm&os.ModeDir determines
134 // whether it is a file or a directory.
136 // A file can be opened multiple times and used concurrently
137 // from multiple goroutines. However, each File object should
138 // be used by only one goroutine at a time.
139 OpenFile(name string, flag int, perm os.FileMode) (File, error)
141 Mkdir(name string, perm os.FileMode) error
142 Remove(name string) error
143 RemoveAll(name string) error
144 Rename(oldname, newname string) error
146 // Write buffered data from memory to storage, returning when
147 // all updates have been saved to persistent storage.
150 // Write buffered data from memory to storage, but don't wait
151 // for all writes to finish before returning. If shortBlocks
152 // is true, flush everything; otherwise, if there's less than
153 // a full block of buffered data at the end of a stream, leave
154 // it buffered in memory in case more data can be appended. If
155 // path is "", flush all dirs/streams; otherwise, flush only
156 // the specified dir/stream.
157 Flush(path string, shortBlocks bool) error
159 // Estimate current memory usage.
167 // FS returns an fs.FS interface to the given FileSystem, to enable
168 // the use of fs.WalkDir, etc.
169 func FS(fs FileSystem) fs.FS { return fsFS{fs} }
170 func (fs fsFS) Open(path string) (fs.File, error) {
171 f, err := fs.FileSystem.Open(path)
175 type inode interface {
176 SetParent(parent inode, name string)
179 Read([]byte, filenodePtr) (int, filenodePtr, error)
180 Write([]byte, filenodePtr) (int, filenodePtr, error)
181 Truncate(int64) error
183 Readdir() ([]os.FileInfo, error)
185 FileInfo() os.FileInfo
186 // Create a snapshot of this node and its descendants.
187 Snapshot() (inode, error)
188 // Replace this node with a copy of the provided snapshot.
189 // Caller may provide the same snapshot to multiple Splice
190 // calls, but must not modify the snapshot concurrently.
193 // Child() performs lookups and updates of named child nodes.
195 // (The term "child" here is used strictly. This means name is
196 // not "." or "..", and name does not contain "/".)
198 // If replace is non-nil, Child calls replace(x) where x is
199 // the current child inode with the given name. If possible,
200 // the child inode is replaced with the one returned by
203 // If replace(x) returns an inode (besides x or nil) that is
204 // subsequently returned by Child(), then Child()'s caller
205 // must ensure the new child's name and parent are set/updated
206 // to Child()'s name argument and its receiver respectively.
207 // This is not necessarily done before replace(x) returns, but
208 // it must be done before Child()'s caller releases the
211 // Nil represents "no child". replace(nil) signifies that no
212 // child with this name exists yet. If replace() returns nil,
213 // the existing child should be deleted if possible.
215 // An implementation of Child() is permitted to ignore
216 // replace() or its return value. For example, a regular file
217 // inode does not have children, so Child() always returns
220 // Child() returns the child, if any, with the given name: if
221 // a child was added or changed, the new child is returned.
223 // Caller must have lock (or rlock if replace is nil).
224 Child(name string, replace func(inode) (inode, error)) (inode, error)
232 type fileinfo struct {
237 // If not nil, sys() returns the source data structure, which
238 // can be a *Collection, *Group, or nil. Currently populated
239 // only for project dirs and top-level collection dirs. Does
240 // not stay up to date with upstream changes.
242 // Intended to support keep-web's properties-as-s3-metadata
243 // feature (https://dev.arvados.org/issues/19088).
244 sys func() interface{}
247 // Name implements os.FileInfo.
248 func (fi fileinfo) Name() string {
252 // ModTime implements os.FileInfo.
253 func (fi fileinfo) ModTime() time.Time {
257 // Mode implements os.FileInfo.
258 func (fi fileinfo) Mode() os.FileMode {
262 // IsDir implements os.FileInfo.
263 func (fi fileinfo) IsDir() bool {
264 return fi.mode&os.ModeDir != 0
267 // Size implements os.FileInfo.
268 func (fi fileinfo) Size() int64 {
272 // Sys implements os.FileInfo. See comment in fileinfo struct.
273 func (fi fileinfo) Sys() interface{} {
280 type nullnode struct{}
282 func (*nullnode) Mkdir(string, os.FileMode) error {
283 return ErrInvalidOperation
286 func (*nullnode) Read([]byte, filenodePtr) (int, filenodePtr, error) {
287 return 0, filenodePtr{}, ErrInvalidOperation
290 func (*nullnode) Write([]byte, filenodePtr) (int, filenodePtr, error) {
291 return 0, filenodePtr{}, ErrInvalidOperation
294 func (*nullnode) Truncate(int64) error {
295 return ErrInvalidOperation
298 func (*nullnode) FileInfo() os.FileInfo {
302 func (*nullnode) IsDir() bool {
306 func (*nullnode) Readdir() ([]os.FileInfo, error) {
307 return nil, ErrInvalidOperation
310 func (*nullnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
311 return nil, ErrNotADirectory
314 func (*nullnode) MemorySize() int64 {
315 // Types that embed nullnode should report their own size, but
316 // if they don't, we at least report a non-zero size to ensure
317 // a large tree doesn't get reported as 0 bytes.
321 func (*nullnode) Snapshot() (inode, error) {
322 return nil, ErrInvalidOperation
325 func (*nullnode) Splice(inode) error {
326 return ErrInvalidOperation
329 type treenode struct {
332 inodes map[string]inode
338 func (n *treenode) FS() FileSystem {
342 func (n *treenode) SetParent(p inode, name string) {
346 n.fileinfo.name = name
349 func (n *treenode) Parent() inode {
355 func (n *treenode) IsDir() bool {
359 func (n *treenode) Child(name string, replace func(inode) (inode, error)) (child inode, err error) {
360 debugPanicIfNotLocked(n, false)
361 child = n.inodes[name]
362 if name == "" || name == "." || name == ".." {
363 err = ErrInvalidArgument
369 newchild, err := replace(child)
374 debugPanicIfNotLocked(n, true)
375 delete(n.inodes, name)
376 } else if newchild != child {
377 debugPanicIfNotLocked(n, true)
378 n.inodes[name] = newchild
379 n.fileinfo.modTime = time.Now()
385 func (n *treenode) Size() int64 {
386 return n.FileInfo().Size()
389 func (n *treenode) FileInfo() os.FileInfo {
393 fi.size = int64(len(n.inodes))
397 func (n *treenode) Readdir() (fi []os.FileInfo, err error) {
398 // We need RLock to safely read n.inodes, but we must release
399 // it before calling FileInfo() on the child nodes. Otherwise,
400 // we risk deadlock when filter groups A and B match each
401 // other, concurrent Readdir() calls try to RLock them in
402 // opposite orders, and one cannot be RLocked a second time
403 // because a third caller is waiting for a write lock.
405 inodes := make([]inode, 0, len(n.inodes))
406 for _, inode := range n.inodes {
407 inodes = append(inodes, inode)
410 fi = make([]os.FileInfo, 0, len(inodes))
411 for _, inode := range inodes {
412 fi = append(fi, inode.FileInfo())
417 func (n *treenode) Sync() error {
420 for _, inode := range n.inodes {
421 syncer, ok := inode.(syncer)
423 return ErrInvalidOperation
433 func (n *treenode) MemorySize() (size int64) {
434 // To avoid making other callers wait while we count the
435 // entire filesystem size, we lock the node only long enough
436 // to copy the list of children. We accept that the resulting
437 // size will sometimes be misleading (e.g., we will
438 // double-count an item that moves from A to B after we check
439 // A's size but before we check B's size).
441 debugPanicIfNotLocked(n, false)
442 todo := make([]inode, 0, len(n.inodes))
443 for _, inode := range n.inodes {
444 todo = append(todo, inode)
447 for _, inode := range todo {
448 size += inode.MemorySize()
453 type fileSystem struct {
460 func (fs *fileSystem) rootnode() inode {
464 func (fs *fileSystem) throttle() *throttle {
468 func (fs *fileSystem) locker() sync.Locker {
472 // OpenFile is analogous to os.OpenFile().
473 func (fs *fileSystem) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
474 return fs.openFile(name, flag, perm)
477 func (fs *fileSystem) openFile(name string, flag int, perm os.FileMode) (*filehandle, error) {
478 if flag&os.O_SYNC != 0 {
479 return nil, ErrSyncNotSupported
481 dirname, name := path.Split(name)
482 ancestors := map[inode]bool{}
483 parent, err := rlookup(fs.root, dirname, ancestors)
487 var readable, writable bool
488 switch flag & (os.O_RDWR | os.O_RDONLY | os.O_WRONLY) {
497 return nil, fmt.Errorf("invalid flags 0x%x", flag)
500 // A directory can be opened via "foo/", "foo/.", or
504 return &filehandle{inode: parent, readable: readable, writable: writable}, nil
506 return &filehandle{inode: parent.Parent(), readable: readable, writable: writable}, nil
509 createMode := flag&os.O_CREATE != 0
510 // We always need to take Lock() here, not just RLock(). Even
511 // if we know we won't be creating a file, parent might be a
512 // lookupnode, which sometimes populates its inodes map during
515 defer parent.Unlock()
516 n, err := parent.Child(name, nil)
521 return nil, os.ErrNotExist
523 n, err = parent.Child(name, func(inode) (repl inode, err error) {
524 repl, err = parent.FS().newNode(name, perm|0755, time.Now())
528 repl.SetParent(parent, name)
534 // Parent rejected new child, but returned no error
535 return nil, ErrInvalidArgument
537 } else if flag&os.O_EXCL != 0 {
538 return nil, os.ErrExist
539 } else if flag&os.O_TRUNC != 0 {
541 return nil, fmt.Errorf("invalid flag O_TRUNC in read-only mode")
542 } else if n.IsDir() {
543 return nil, fmt.Errorf("invalid flag O_TRUNC when opening directory")
544 } else if err := n.Truncate(0); err != nil {
548 // If n and one of its parents/ancestors are [hardlinks to]
549 // the same node (e.g., a filter group that matches itself),
550 // open an "empty directory" node instead, so the inner
551 // hardlink appears empty. This is needed to ensure
552 // Open("a/b/c/x/x").Readdir() appears empty, matching the
553 // behavior of rlookup("a/b/c/x/x/z") => ErrNotExist.
554 if hl, ok := n.(*hardlink); (ok && ancestors[hl.inode]) || ancestors[n] {
562 mode: 0555 | os.ModeDir,
568 append: flag&os.O_APPEND != 0,
574 func (fs *fileSystem) Open(name string) (http.File, error) {
575 return fs.OpenFile(name, os.O_RDONLY, 0)
578 func (fs *fileSystem) Create(name string) (File, error) {
579 return fs.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0)
582 func (fs *fileSystem) Mkdir(name string, perm os.FileMode) error {
583 dirname, name := path.Split(name)
584 n, err := rlookup(fs.root, dirname, nil)
590 if child, err := n.Child(name, nil); err != nil {
592 } else if child != nil {
596 _, err = n.Child(name, func(inode) (repl inode, err error) {
597 repl, err = n.FS().newNode(name, perm|os.ModeDir, time.Now())
601 repl.SetParent(n, name)
607 func (fs *fileSystem) Stat(name string) (os.FileInfo, error) {
608 node, err := rlookup(fs.root, name, nil)
612 return node.FileInfo(), nil
615 func (fs *fileSystem) Rename(oldname, newname string) error {
616 olddir, oldname := path.Split(oldname)
617 if oldname == "" || oldname == "." || oldname == ".." {
618 return ErrInvalidArgument
620 olddirf, err := fs.openFile(olddir+".", os.O_RDONLY, 0)
622 return fmt.Errorf("%q: %s", olddir, err)
624 defer olddirf.Close()
626 newdir, newname := path.Split(newname)
627 if newname == "." || newname == ".." {
628 return ErrInvalidArgument
629 } else if newname == "" {
630 // Rename("a/b", "c/") means Rename("a/b", "c/b")
633 newdirf, err := fs.openFile(newdir+".", os.O_RDONLY, 0)
635 return fmt.Errorf("%q: %s", newdir, err)
637 defer newdirf.Close()
639 // TODO: If the nearest common ancestor ("nca") of olddirf and
640 // newdirf is on a different filesystem than fs, we should
641 // call nca.FS().Rename() instead of proceeding. Until then
642 // it's awkward for filesystems to implement their own Rename
643 // methods effectively: the only one that runs is the one on
644 // the root FileSystem exposed to the caller (webdav, fuse,
647 // When acquiring locks on multiple inodes, avoid deadlock by
648 // locking the entire containing filesystem first.
649 cfs := olddirf.inode.FS()
651 defer cfs.locker().Unlock()
653 if cfs != newdirf.inode.FS() {
654 // Moving inodes across filesystems is not (yet)
655 // supported. Locking inodes from different
656 // filesystems could deadlock, so we must error out
658 return ErrInvalidOperation
661 // To ensure we can test reliably whether we're about to move
662 // a directory into itself, lock all potential common
663 // ancestors of olddir and newdir.
664 needLock := []sync.Locker{}
665 for _, node := range []inode{olddirf.inode, newdirf.inode} {
666 needLock = append(needLock, node)
667 for node.Parent() != node && node.Parent().FS() == node.FS() {
669 needLock = append(needLock, node)
672 locked := map[sync.Locker]bool{}
673 for i := len(needLock) - 1; i >= 0; i-- {
675 if fs, ok := n.(interface{ rootnode() inode }); ok {
676 // Lock the fs's root dir directly, not
677 // through the fs. Otherwise our "locked" map
678 // would not reliably prevent double-locking
679 // the fs's root dir.
689 _, err = olddirf.inode.Child(oldname, func(oldinode inode) (inode, error) {
691 return oldinode, os.ErrNotExist
693 if locked[oldinode] {
694 // oldinode cannot become a descendant of itself.
695 return oldinode, ErrInvalidArgument
697 if oldinode.FS() != cfs && newdirf.inode != olddirf.inode {
698 // moving a mount point to a different parent
699 // is not (yet) supported.
700 return oldinode, ErrInvalidArgument
702 accepted, err := newdirf.inode.Child(newname, func(existing inode) (inode, error) {
703 if existing != nil && existing.IsDir() {
704 return existing, ErrIsDirectory
709 // Leave oldinode in olddir.
712 accepted.SetParent(newdirf.inode, newname)
718 func (fs *fileSystem) Remove(name string) error {
719 return fs.remove(strings.TrimRight(name, "/"), false)
722 func (fs *fileSystem) RemoveAll(name string) error {
723 err := fs.remove(strings.TrimRight(name, "/"), true)
724 if os.IsNotExist(err) {
725 // "If the path does not exist, RemoveAll returns
726 // nil." (see "os" pkg)
732 func (fs *fileSystem) remove(name string, recursive bool) error {
733 dirname, name := path.Split(name)
734 if name == "" || name == "." || name == ".." {
735 return ErrInvalidArgument
737 dir, err := rlookup(fs.root, dirname, nil)
743 _, err = dir.Child(name, func(node inode) (inode, error) {
745 return nil, os.ErrNotExist
747 if !recursive && node.IsDir() && node.Size() > 0 {
748 return node, ErrDirectoryNotEmpty
755 func (fs *fileSystem) Sync() error {
756 if syncer, ok := fs.root.(syncer); ok {
759 return ErrInvalidOperation
762 func (fs *fileSystem) Flush(string, bool) error {
763 log.Printf("TODO: flush fileSystem")
764 return ErrInvalidOperation
767 func (fs *fileSystem) MemorySize() int64 {
768 return fs.root.MemorySize()
771 // rlookup (recursive lookup) returns the inode for the file/directory
772 // with the given name (which may contain "/" separators). If no such
773 // file/directory exists, the returned node is nil.
775 // The visited map should be either nil or empty. If non-nil, all
776 // nodes and hardlink targets visited by the given path will be added
779 // If a cycle is detected, the second occurrence of the offending node
780 // will be replaced by an empty directory. For example, if "x" is a
781 // filter group that matches itself, then rlookup("a/b/c/x") will
782 // return the filter group, and rlookup("a/b/c/x/x") will return an
784 func rlookup(start inode, path string, visited map[inode]bool) (node inode, err error) {
786 visited = map[inode]bool{}
789 // Clean up ./ and ../ and double-slashes, but (unlike
790 // filepath.Clean) retain a trailing slash, because looking up
791 // ".../regularfile/" should fail.
792 trailingSlash := strings.HasSuffix(path, "/")
793 path = filepath.Clean(path)
794 if trailingSlash && path != "/" {
797 for _, name := range strings.Split(path, "/") {
800 if name == "." || name == "" {
808 node, err = func() (inode, error) {
811 return node.Child(name, nil)
813 if node == nil || err != nil {
817 if hardlinked, ok := checknode.(*hardlink); ok {
818 checknode = hardlinked.inode
820 if visited[checknode] {
823 parent: node.Parent(),
828 mode: 0555 | os.ModeDir,
832 visited[checknode] = true
835 if node == nil && err == nil {
841 func permittedName(name string) bool {
842 return name != "" && name != "." && name != ".." && !strings.Contains(name, "/")
845 // Snapshot returns a Subtree that's a copy of the given path. It
846 // returns an error if the path is not inside a collection.
847 func Snapshot(fs FileSystem, path string) (*Subtree, error) {
848 f, err := fs.OpenFile(path, os.O_RDONLY, 0)
856 // Splice inserts newsubtree at the indicated target path.
858 // Splice returns an error if target is not inside a collection.
860 // Splice returns an error if target is the root of a collection and
861 // newsubtree is a snapshot of a file.
862 func Splice(fs FileSystem, target string, newsubtree *Subtree) error {
863 f, err := fs.OpenFile(target, os.O_WRONLY, 0)
864 if os.IsNotExist(err) {
865 f, err = fs.OpenFile(target, os.O_CREATE|os.O_WRONLY, 0700)
868 return fmt.Errorf("open %s: %w", target, err)
871 return f.Splice(newsubtree)