1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
21 ErrReadOnlyFile = errors.New("read-only file")
22 ErrNegativeOffset = errors.New("cannot seek to negative offset")
23 ErrFileExists = errors.New("file exists")
24 ErrInvalidOperation = errors.New("invalid operation")
25 ErrInvalidArgument = errors.New("invalid argument")
26 ErrDirectoryNotEmpty = errors.New("directory not empty")
27 ErrWriteOnlyMode = errors.New("file is O_WRONLY")
28 ErrSyncNotSupported = errors.New("O_SYNC flag is not supported")
29 ErrIsDirectory = errors.New("cannot rename file to overwrite existing directory")
30 ErrNotADirectory = errors.New("not a directory")
31 ErrPermission = os.ErrPermission
32 DebugLocksPanicMode = false
35 type syncer interface {
39 func debugPanicIfNotLocked(l sync.Locker, writing bool) {
40 if !DebugLocksPanicMode {
44 if rl, ok := l.(interface {
49 // Fail if we can grab the read lock during an
50 // operation that purportedly has write lock.
64 panic("bug: caller-must-have-lock func called, but nobody has lock")
68 // A File is an *os.File-like interface for reading and writing files
76 Readdir(int) ([]os.FileInfo, error)
77 Stat() (os.FileInfo, error)
82 // A FileSystem is an http.Filesystem plus Stat() and support for
83 // opening writable files. All methods are safe to call from multiple
85 type FileSystem interface {
91 // filesystem-wide lock: used by Rename() to prevent deadlock
92 // while locking multiple inodes.
95 // throttle for limiting concurrent background writers
98 // create a new node with nil parent.
99 newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error)
101 // analogous to os.Stat()
102 Stat(name string) (os.FileInfo, error)
104 // analogous to os.Create(): create/truncate a file and open it O_RDWR.
105 Create(name string) (File, error)
107 // Like os.OpenFile(): create or open a file or directory.
109 // If flag&os.O_EXCL==0, it opens an existing file or
110 // directory if one exists. If flag&os.O_CREATE!=0, it creates
111 // a new empty file or directory if one does not already
114 // When creating a new item, perm&os.ModeDir determines
115 // whether it is a file or a directory.
117 // A file can be opened multiple times and used concurrently
118 // from multiple goroutines. However, each File object should
119 // be used by only one goroutine at a time.
120 OpenFile(name string, flag int, perm os.FileMode) (File, error)
122 Mkdir(name string, perm os.FileMode) error
123 Remove(name string) error
124 RemoveAll(name string) error
125 Rename(oldname, newname string) error
127 // Write buffered data from memory to storage, returning when
128 // all updates have been saved to persistent storage.
131 // Write buffered data from memory to storage, but don't wait
132 // for all writes to finish before returning. If shortBlocks
133 // is true, flush everything; otherwise, if there's less than
134 // a full block of buffered data at the end of a stream, leave
135 // it buffered in memory in case more data can be appended. If
136 // path is "", flush all dirs/streams; otherwise, flush only
137 // the specified dir/stream.
138 Flush(path string, shortBlocks bool) error
140 // Estimate current memory usage.
144 type inode interface {
145 SetParent(parent inode, name string)
148 Read([]byte, filenodePtr) (int, filenodePtr, error)
149 Write([]byte, filenodePtr) (int, filenodePtr, error)
150 Truncate(int64) error
152 Readdir() ([]os.FileInfo, error)
154 FileInfo() os.FileInfo
156 // Child() performs lookups and updates of named child nodes.
158 // (The term "child" here is used strictly. This means name is
159 // not "." or "..", and name does not contain "/".)
161 // If replace is non-nil, Child calls replace(x) where x is
162 // the current child inode with the given name. If possible,
163 // the child inode is replaced with the one returned by
166 // If replace(x) returns an inode (besides x or nil) that is
167 // subsequently returned by Child(), then Child()'s caller
168 // must ensure the new child's name and parent are set/updated
169 // to Child()'s name argument and its receiver respectively.
170 // This is not necessarily done before replace(x) returns, but
171 // it must be done before Child()'s caller releases the
174 // Nil represents "no child". replace(nil) signifies that no
175 // child with this name exists yet. If replace() returns nil,
176 // the existing child should be deleted if possible.
178 // An implementation of Child() is permitted to ignore
179 // replace() or its return value. For example, a regular file
180 // inode does not have children, so Child() always returns
183 // Child() returns the child, if any, with the given name: if
184 // a child was added or changed, the new child is returned.
186 // Caller must have lock (or rlock if replace is nil).
187 Child(name string, replace func(inode) (inode, error)) (inode, error)
195 type fileinfo struct {
202 // Name implements os.FileInfo.
203 func (fi fileinfo) Name() string {
207 // ModTime implements os.FileInfo.
208 func (fi fileinfo) ModTime() time.Time {
212 // Mode implements os.FileInfo.
213 func (fi fileinfo) Mode() os.FileMode {
217 // IsDir implements os.FileInfo.
218 func (fi fileinfo) IsDir() bool {
219 return fi.mode&os.ModeDir != 0
222 // Size implements os.FileInfo.
223 func (fi fileinfo) Size() int64 {
227 // Sys implements os.FileInfo.
228 func (fi fileinfo) Sys() interface{} {
232 type nullnode struct{}
234 func (*nullnode) Mkdir(string, os.FileMode) error {
235 return ErrInvalidOperation
238 func (*nullnode) Read([]byte, filenodePtr) (int, filenodePtr, error) {
239 return 0, filenodePtr{}, ErrInvalidOperation
242 func (*nullnode) Write([]byte, filenodePtr) (int, filenodePtr, error) {
243 return 0, filenodePtr{}, ErrInvalidOperation
246 func (*nullnode) Truncate(int64) error {
247 return ErrInvalidOperation
250 func (*nullnode) FileInfo() os.FileInfo {
254 func (*nullnode) IsDir() bool {
258 func (*nullnode) Readdir() ([]os.FileInfo, error) {
259 return nil, ErrInvalidOperation
262 func (*nullnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
263 return nil, ErrNotADirectory
266 func (*nullnode) MemorySize() int64 {
267 // Types that embed nullnode should report their own size, but
268 // if they don't, we at least report a non-zero size to ensure
269 // a large tree doesn't get reported as 0 bytes.
273 type treenode struct {
276 inodes map[string]inode
282 func (n *treenode) FS() FileSystem {
286 func (n *treenode) SetParent(p inode, name string) {
290 n.fileinfo.name = name
293 func (n *treenode) Parent() inode {
299 func (n *treenode) IsDir() bool {
303 func (n *treenode) Child(name string, replace func(inode) (inode, error)) (child inode, err error) {
304 debugPanicIfNotLocked(n, false)
305 child = n.inodes[name]
306 if name == "" || name == "." || name == ".." {
307 err = ErrInvalidArgument
313 newchild, err := replace(child)
318 debugPanicIfNotLocked(n, true)
319 delete(n.inodes, name)
320 } else if newchild != child {
321 debugPanicIfNotLocked(n, true)
322 n.inodes[name] = newchild
323 n.fileinfo.modTime = time.Now()
329 func (n *treenode) Size() int64 {
330 return n.FileInfo().Size()
333 func (n *treenode) FileInfo() os.FileInfo {
336 n.fileinfo.size = int64(len(n.inodes))
340 func (n *treenode) Readdir() (fi []os.FileInfo, err error) {
343 fi = make([]os.FileInfo, 0, len(n.inodes))
344 for _, inode := range n.inodes {
345 fi = append(fi, inode.FileInfo())
350 func (n *treenode) Sync() error {
353 for _, inode := range n.inodes {
354 syncer, ok := inode.(syncer)
356 return ErrInvalidOperation
366 func (n *treenode) MemorySize() (size int64) {
369 debugPanicIfNotLocked(n, false)
370 for _, inode := range n.inodes {
371 size += inode.MemorySize()
376 type fileSystem struct {
383 func (fs *fileSystem) rootnode() inode {
387 func (fs *fileSystem) throttle() *throttle {
391 func (fs *fileSystem) locker() sync.Locker {
395 // OpenFile is analogous to os.OpenFile().
396 func (fs *fileSystem) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
397 return fs.openFile(name, flag, perm)
400 func (fs *fileSystem) openFile(name string, flag int, perm os.FileMode) (*filehandle, error) {
401 if flag&os.O_SYNC != 0 {
402 return nil, ErrSyncNotSupported
404 dirname, name := path.Split(name)
405 parent, err := rlookup(fs.root, dirname)
409 var readable, writable bool
410 switch flag & (os.O_RDWR | os.O_RDONLY | os.O_WRONLY) {
419 return nil, fmt.Errorf("invalid flags 0x%x", flag)
421 if !writable && parent.IsDir() {
422 // A directory can be opened via "foo/", "foo/.", or
426 return &filehandle{inode: parent}, nil
428 return &filehandle{inode: parent.Parent()}, nil
431 createMode := flag&os.O_CREATE != 0
432 // We always need to take Lock() here, not just RLock(). Even
433 // if we know we won't be creating a file, parent might be a
434 // lookupnode, which sometimes populates its inodes map during
437 defer parent.Unlock()
438 n, err := parent.Child(name, nil)
443 return nil, os.ErrNotExist
445 n, err = parent.Child(name, func(inode) (repl inode, err error) {
446 repl, err = parent.FS().newNode(name, perm|0755, time.Now())
450 repl.SetParent(parent, name)
456 // Parent rejected new child, but returned no error
457 return nil, ErrInvalidArgument
459 } else if flag&os.O_EXCL != 0 {
460 return nil, ErrFileExists
461 } else if flag&os.O_TRUNC != 0 {
463 return nil, fmt.Errorf("invalid flag O_TRUNC in read-only mode")
464 } else if n.IsDir() {
465 return nil, fmt.Errorf("invalid flag O_TRUNC when opening directory")
466 } else if err := n.Truncate(0); err != nil {
472 append: flag&os.O_APPEND != 0,
478 func (fs *fileSystem) Open(name string) (http.File, error) {
479 return fs.OpenFile(name, os.O_RDONLY, 0)
482 func (fs *fileSystem) Create(name string) (File, error) {
483 return fs.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0)
486 func (fs *fileSystem) Mkdir(name string, perm os.FileMode) error {
487 dirname, name := path.Split(name)
488 n, err := rlookup(fs.root, dirname)
494 if child, err := n.Child(name, nil); err != nil {
496 } else if child != nil {
500 _, err = n.Child(name, func(inode) (repl inode, err error) {
501 repl, err = n.FS().newNode(name, perm|os.ModeDir, time.Now())
505 repl.SetParent(n, name)
511 func (fs *fileSystem) Stat(name string) (os.FileInfo, error) {
512 node, err := rlookup(fs.root, name)
516 return node.FileInfo(), nil
519 func (fs *fileSystem) Rename(oldname, newname string) error {
520 olddir, oldname := path.Split(oldname)
521 if oldname == "" || oldname == "." || oldname == ".." {
522 return ErrInvalidArgument
524 olddirf, err := fs.openFile(olddir+".", os.O_RDONLY, 0)
526 return fmt.Errorf("%q: %s", olddir, err)
528 defer olddirf.Close()
530 newdir, newname := path.Split(newname)
531 if newname == "." || newname == ".." {
532 return ErrInvalidArgument
533 } else if newname == "" {
534 // Rename("a/b", "c/") means Rename("a/b", "c/b")
537 newdirf, err := fs.openFile(newdir+".", os.O_RDONLY, 0)
539 return fmt.Errorf("%q: %s", newdir, err)
541 defer newdirf.Close()
543 // TODO: If the nearest common ancestor ("nca") of olddirf and
544 // newdirf is on a different filesystem than fs, we should
545 // call nca.FS().Rename() instead of proceeding. Until then
546 // it's awkward for filesystems to implement their own Rename
547 // methods effectively: the only one that runs is the one on
548 // the root FileSystem exposed to the caller (webdav, fuse,
551 // When acquiring locks on multiple inodes, avoid deadlock by
552 // locking the entire containing filesystem first.
553 cfs := olddirf.inode.FS()
555 defer cfs.locker().Unlock()
557 if cfs != newdirf.inode.FS() {
558 // Moving inodes across filesystems is not (yet)
559 // supported. Locking inodes from different
560 // filesystems could deadlock, so we must error out
562 return ErrInvalidArgument
565 // To ensure we can test reliably whether we're about to move
566 // a directory into itself, lock all potential common
567 // ancestors of olddir and newdir.
568 needLock := []sync.Locker{}
569 for _, node := range []inode{olddirf.inode, newdirf.inode} {
570 needLock = append(needLock, node)
571 for node.Parent() != node && node.Parent().FS() == node.FS() {
573 needLock = append(needLock, node)
576 locked := map[sync.Locker]bool{}
577 for i := len(needLock) - 1; i >= 0; i-- {
578 if n := needLock[i]; !locked[n] {
585 _, err = olddirf.inode.Child(oldname, func(oldinode inode) (inode, error) {
587 return oldinode, os.ErrNotExist
589 if locked[oldinode] {
590 // oldinode cannot become a descendant of itself.
591 return oldinode, ErrInvalidArgument
593 if oldinode.FS() != cfs && newdirf.inode != olddirf.inode {
594 // moving a mount point to a different parent
595 // is not (yet) supported.
596 return oldinode, ErrInvalidArgument
598 accepted, err := newdirf.inode.Child(newname, func(existing inode) (inode, error) {
599 if existing != nil && existing.IsDir() {
600 return existing, ErrIsDirectory
605 // Leave oldinode in olddir.
608 accepted.SetParent(newdirf.inode, newname)
614 func (fs *fileSystem) Remove(name string) error {
615 return fs.remove(strings.TrimRight(name, "/"), false)
618 func (fs *fileSystem) RemoveAll(name string) error {
619 err := fs.remove(strings.TrimRight(name, "/"), true)
620 if os.IsNotExist(err) {
621 // "If the path does not exist, RemoveAll returns
622 // nil." (see "os" pkg)
628 func (fs *fileSystem) remove(name string, recursive bool) error {
629 dirname, name := path.Split(name)
630 if name == "" || name == "." || name == ".." {
631 return ErrInvalidArgument
633 dir, err := rlookup(fs.root, dirname)
639 _, err = dir.Child(name, func(node inode) (inode, error) {
641 return nil, os.ErrNotExist
643 if !recursive && node.IsDir() && node.Size() > 0 {
644 return node, ErrDirectoryNotEmpty
651 func (fs *fileSystem) Sync() error {
652 if syncer, ok := fs.root.(syncer); ok {
655 return ErrInvalidOperation
658 func (fs *fileSystem) Flush(string, bool) error {
659 log.Printf("TODO: flush fileSystem")
660 return ErrInvalidOperation
663 func (fs *fileSystem) MemorySize() int64 {
664 return fs.root.MemorySize()
667 // rlookup (recursive lookup) returns the inode for the file/directory
668 // with the given name (which may contain "/" separators). If no such
669 // file/directory exists, the returned node is nil.
670 func rlookup(start inode, path string) (node inode, err error) {
672 for _, name := range strings.Split(path, "/") {
674 if name == "." || name == "" {
682 node, err = func() (inode, error) {
685 return node.Child(name, nil)
687 if node == nil || err != nil {
691 if node == nil && err == nil {
697 func permittedName(name string) bool {
698 return name != "" && name != "." && name != ".." && !strings.Contains(name, "/")