1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
22 ErrReadOnlyFile = errors.New("read-only file")
23 ErrNegativeOffset = errors.New("cannot seek to negative offset")
24 ErrFileExists = errors.New("file exists")
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 {
239 // Name implements os.FileInfo.
240 func (fi fileinfo) Name() string {
244 // ModTime implements os.FileInfo.
245 func (fi fileinfo) ModTime() time.Time {
249 // Mode implements os.FileInfo.
250 func (fi fileinfo) Mode() os.FileMode {
254 // IsDir implements os.FileInfo.
255 func (fi fileinfo) IsDir() bool {
256 return fi.mode&os.ModeDir != 0
259 // Size implements os.FileInfo.
260 func (fi fileinfo) Size() int64 {
264 // Sys implements os.FileInfo.
265 func (fi fileinfo) Sys() interface{} {
269 type nullnode struct{}
271 func (*nullnode) Mkdir(string, os.FileMode) error {
272 return ErrInvalidOperation
275 func (*nullnode) Read([]byte, filenodePtr) (int, filenodePtr, error) {
276 return 0, filenodePtr{}, ErrInvalidOperation
279 func (*nullnode) Write([]byte, filenodePtr) (int, filenodePtr, error) {
280 return 0, filenodePtr{}, ErrInvalidOperation
283 func (*nullnode) Truncate(int64) error {
284 return ErrInvalidOperation
287 func (*nullnode) FileInfo() os.FileInfo {
291 func (*nullnode) IsDir() bool {
295 func (*nullnode) Readdir() ([]os.FileInfo, error) {
296 return nil, ErrInvalidOperation
299 func (*nullnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
300 return nil, ErrNotADirectory
303 func (*nullnode) MemorySize() int64 {
304 // Types that embed nullnode should report their own size, but
305 // if they don't, we at least report a non-zero size to ensure
306 // a large tree doesn't get reported as 0 bytes.
310 func (*nullnode) Snapshot() (inode, error) {
311 return nil, ErrInvalidOperation
314 func (*nullnode) Splice(inode) error {
315 return ErrInvalidOperation
318 type treenode struct {
321 inodes map[string]inode
327 func (n *treenode) FS() FileSystem {
331 func (n *treenode) SetParent(p inode, name string) {
335 n.fileinfo.name = name
338 func (n *treenode) Parent() inode {
344 func (n *treenode) IsDir() bool {
348 func (n *treenode) Child(name string, replace func(inode) (inode, error)) (child inode, err error) {
349 debugPanicIfNotLocked(n, false)
350 child = n.inodes[name]
351 if name == "" || name == "." || name == ".." {
352 err = ErrInvalidArgument
358 newchild, err := replace(child)
363 debugPanicIfNotLocked(n, true)
364 delete(n.inodes, name)
365 } else if newchild != child {
366 debugPanicIfNotLocked(n, true)
367 n.inodes[name] = newchild
368 n.fileinfo.modTime = time.Now()
374 func (n *treenode) Size() int64 {
375 return n.FileInfo().Size()
378 func (n *treenode) FileInfo() os.FileInfo {
381 n.fileinfo.size = int64(len(n.inodes))
385 func (n *treenode) Readdir() (fi []os.FileInfo, err error) {
388 fi = make([]os.FileInfo, 0, len(n.inodes))
389 for _, inode := range n.inodes {
390 fi = append(fi, inode.FileInfo())
395 func (n *treenode) Sync() error {
398 for _, inode := range n.inodes {
399 syncer, ok := inode.(syncer)
401 return ErrInvalidOperation
411 func (n *treenode) MemorySize() (size int64) {
414 debugPanicIfNotLocked(n, false)
415 for _, inode := range n.inodes {
416 size += inode.MemorySize()
421 type fileSystem struct {
428 func (fs *fileSystem) rootnode() inode {
432 func (fs *fileSystem) throttle() *throttle {
436 func (fs *fileSystem) locker() sync.Locker {
440 // OpenFile is analogous to os.OpenFile().
441 func (fs *fileSystem) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
442 return fs.openFile(name, flag, perm)
445 func (fs *fileSystem) openFile(name string, flag int, perm os.FileMode) (*filehandle, error) {
446 if flag&os.O_SYNC != 0 {
447 return nil, ErrSyncNotSupported
449 dirname, name := path.Split(name)
450 parent, err := rlookup(fs.root, dirname)
454 var readable, writable bool
455 switch flag & (os.O_RDWR | os.O_RDONLY | os.O_WRONLY) {
464 return nil, fmt.Errorf("invalid flags 0x%x", flag)
467 // A directory can be opened via "foo/", "foo/.", or
471 return &filehandle{inode: parent, readable: readable, writable: writable}, nil
473 return &filehandle{inode: parent.Parent(), readable: readable, writable: writable}, nil
476 createMode := flag&os.O_CREATE != 0
477 // We always need to take Lock() here, not just RLock(). Even
478 // if we know we won't be creating a file, parent might be a
479 // lookupnode, which sometimes populates its inodes map during
482 defer parent.Unlock()
483 n, err := parent.Child(name, nil)
488 return nil, os.ErrNotExist
490 n, err = parent.Child(name, func(inode) (repl inode, err error) {
491 repl, err = parent.FS().newNode(name, perm|0755, time.Now())
495 repl.SetParent(parent, name)
501 // Parent rejected new child, but returned no error
502 return nil, ErrInvalidArgument
504 } else if flag&os.O_EXCL != 0 {
505 return nil, ErrFileExists
506 } else if flag&os.O_TRUNC != 0 {
508 return nil, fmt.Errorf("invalid flag O_TRUNC in read-only mode")
509 } else if n.IsDir() {
510 return nil, fmt.Errorf("invalid flag O_TRUNC when opening directory")
511 } else if err := n.Truncate(0); err != nil {
517 append: flag&os.O_APPEND != 0,
523 func (fs *fileSystem) Open(name string) (http.File, error) {
524 return fs.OpenFile(name, os.O_RDONLY, 0)
527 func (fs *fileSystem) Create(name string) (File, error) {
528 return fs.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0)
531 func (fs *fileSystem) Mkdir(name string, perm os.FileMode) error {
532 dirname, name := path.Split(name)
533 n, err := rlookup(fs.root, dirname)
539 if child, err := n.Child(name, nil); err != nil {
541 } else if child != nil {
545 _, err = n.Child(name, func(inode) (repl inode, err error) {
546 repl, err = n.FS().newNode(name, perm|os.ModeDir, time.Now())
550 repl.SetParent(n, name)
556 func (fs *fileSystem) Stat(name string) (os.FileInfo, error) {
557 node, err := rlookup(fs.root, name)
561 return node.FileInfo(), nil
564 func (fs *fileSystem) Rename(oldname, newname string) error {
565 olddir, oldname := path.Split(oldname)
566 if oldname == "" || oldname == "." || oldname == ".." {
567 return ErrInvalidArgument
569 olddirf, err := fs.openFile(olddir+".", os.O_RDONLY, 0)
571 return fmt.Errorf("%q: %s", olddir, err)
573 defer olddirf.Close()
575 newdir, newname := path.Split(newname)
576 if newname == "." || newname == ".." {
577 return ErrInvalidArgument
578 } else if newname == "" {
579 // Rename("a/b", "c/") means Rename("a/b", "c/b")
582 newdirf, err := fs.openFile(newdir+".", os.O_RDONLY, 0)
584 return fmt.Errorf("%q: %s", newdir, err)
586 defer newdirf.Close()
588 // TODO: If the nearest common ancestor ("nca") of olddirf and
589 // newdirf is on a different filesystem than fs, we should
590 // call nca.FS().Rename() instead of proceeding. Until then
591 // it's awkward for filesystems to implement their own Rename
592 // methods effectively: the only one that runs is the one on
593 // the root FileSystem exposed to the caller (webdav, fuse,
596 // When acquiring locks on multiple inodes, avoid deadlock by
597 // locking the entire containing filesystem first.
598 cfs := olddirf.inode.FS()
600 defer cfs.locker().Unlock()
602 if cfs != newdirf.inode.FS() {
603 // Moving inodes across filesystems is not (yet)
604 // supported. Locking inodes from different
605 // filesystems could deadlock, so we must error out
607 return ErrInvalidOperation
610 // To ensure we can test reliably whether we're about to move
611 // a directory into itself, lock all potential common
612 // ancestors of olddir and newdir.
613 needLock := []sync.Locker{}
614 for _, node := range []inode{olddirf.inode, newdirf.inode} {
615 needLock = append(needLock, node)
616 for node.Parent() != node && node.Parent().FS() == node.FS() {
618 needLock = append(needLock, node)
621 locked := map[sync.Locker]bool{}
622 for i := len(needLock) - 1; i >= 0; i-- {
623 if n := needLock[i]; !locked[n] {
630 _, err = olddirf.inode.Child(oldname, func(oldinode inode) (inode, error) {
632 return oldinode, os.ErrNotExist
634 if locked[oldinode] {
635 // oldinode cannot become a descendant of itself.
636 return oldinode, ErrInvalidArgument
638 if oldinode.FS() != cfs && newdirf.inode != olddirf.inode {
639 // moving a mount point to a different parent
640 // is not (yet) supported.
641 return oldinode, ErrInvalidArgument
643 accepted, err := newdirf.inode.Child(newname, func(existing inode) (inode, error) {
644 if existing != nil && existing.IsDir() {
645 return existing, ErrIsDirectory
650 // Leave oldinode in olddir.
653 accepted.SetParent(newdirf.inode, newname)
659 func (fs *fileSystem) Remove(name string) error {
660 return fs.remove(strings.TrimRight(name, "/"), false)
663 func (fs *fileSystem) RemoveAll(name string) error {
664 err := fs.remove(strings.TrimRight(name, "/"), true)
665 if os.IsNotExist(err) {
666 // "If the path does not exist, RemoveAll returns
667 // nil." (see "os" pkg)
673 func (fs *fileSystem) remove(name string, recursive bool) error {
674 dirname, name := path.Split(name)
675 if name == "" || name == "." || name == ".." {
676 return ErrInvalidArgument
678 dir, err := rlookup(fs.root, dirname)
684 _, err = dir.Child(name, func(node inode) (inode, error) {
686 return nil, os.ErrNotExist
688 if !recursive && node.IsDir() && node.Size() > 0 {
689 return node, ErrDirectoryNotEmpty
696 func (fs *fileSystem) Sync() error {
697 if syncer, ok := fs.root.(syncer); ok {
700 return ErrInvalidOperation
703 func (fs *fileSystem) Flush(string, bool) error {
704 log.Printf("TODO: flush fileSystem")
705 return ErrInvalidOperation
708 func (fs *fileSystem) MemorySize() int64 {
709 return fs.root.MemorySize()
712 // rlookup (recursive lookup) returns the inode for the file/directory
713 // with the given name (which may contain "/" separators). If no such
714 // file/directory exists, the returned node is nil.
715 func rlookup(start inode, path string) (node inode, err error) {
717 for _, name := range strings.Split(path, "/") {
719 if name == "." || name == "" {
727 node, err = func() (inode, error) {
730 return node.Child(name, nil)
732 if node == nil || err != nil {
736 if node == nil && err == nil {
742 func permittedName(name string) bool {
743 return name != "" && name != "." && name != ".." && !strings.Contains(name, "/")
746 // Snapshot returns a Subtree that's a copy of the given path. It
747 // returns an error if the path is not inside a collection.
748 func Snapshot(fs FileSystem, path string) (*Subtree, error) {
749 f, err := fs.OpenFile(path, os.O_RDONLY, 0)
757 // Splice inserts newsubtree at the indicated target path.
759 // Splice returns an error if target is not inside a collection.
761 // Splice returns an error if target is the root of a collection and
762 // newsubtree is a snapshot of a file.
763 func Splice(fs FileSystem, target string, newsubtree *Subtree) error {
764 f, err := fs.OpenFile(target, os.O_WRONLY, 0)
765 if os.IsNotExist(err) {
766 f, err = fs.OpenFile(target, os.O_CREATE|os.O_WRONLY, 0700)
769 return fmt.Errorf("open %s: %w", target, err)
772 return f.Splice(newsubtree)