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
34 // A File is an *os.File-like interface for reading and writing files
42 Readdir(int) ([]os.FileInfo, error)
43 Stat() (os.FileInfo, error)
48 // A FileSystem is an http.Filesystem plus Stat() and support for
49 // opening writable files. All methods are safe to call from multiple
51 type FileSystem interface {
57 // filesystem-wide lock: used by Rename() to prevent deadlock
58 // while locking multiple inodes.
61 // throttle for limiting concurrent background writers
64 // create a new node with nil parent.
65 newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error)
67 // analogous to os.Stat()
68 Stat(name string) (os.FileInfo, error)
70 // analogous to os.Create(): create/truncate a file and open it O_RDWR.
71 Create(name string) (File, error)
73 // Like os.OpenFile(): create or open a file or directory.
75 // If flag&os.O_EXCL==0, it opens an existing file or
76 // directory if one exists. If flag&os.O_CREATE!=0, it creates
77 // a new empty file or directory if one does not already
80 // When creating a new item, perm&os.ModeDir determines
81 // whether it is a file or a directory.
83 // A file can be opened multiple times and used concurrently
84 // from multiple goroutines. However, each File object should
85 // be used by only one goroutine at a time.
86 OpenFile(name string, flag int, perm os.FileMode) (File, error)
88 Mkdir(name string, perm os.FileMode) error
89 Remove(name string) error
90 RemoveAll(name string) error
91 Rename(oldname, newname string) error
93 // Write buffered data from memory to storage, returning when
94 // all updates have been saved to persistent storage.
97 // Write buffered data from memory to storage, but don't wait
98 // for all writes to finish before returning. If shortBlocks
99 // is true, flush everything; otherwise, if there's less than
100 // a full block of buffered data at the end of a stream, leave
101 // it buffered in memory in case more data can be appended. If
102 // path is "", flush all dirs/streams; otherwise, flush only
103 // the specified dir/stream.
104 Flush(path string, shortBlocks bool) error
107 type inode interface {
108 SetParent(parent inode, name string)
111 Read([]byte, filenodePtr) (int, filenodePtr, error)
112 Write([]byte, filenodePtr) (int, filenodePtr, error)
113 Truncate(int64) error
115 Readdir() ([]os.FileInfo, error)
117 FileInfo() os.FileInfo
119 // Child() performs lookups and updates of named child nodes.
121 // (The term "child" here is used strictly. This means name is
122 // not "." or "..", and name does not contain "/".)
124 // If replace is non-nil, Child calls replace(x) where x is
125 // the current child inode with the given name. If possible,
126 // the child inode is replaced with the one returned by
129 // If replace(x) returns an inode (besides x or nil) that is
130 // subsequently returned by Child(), then Child()'s caller
131 // must ensure the new child's name and parent are set/updated
132 // to Child()'s name argument and its receiver respectively.
133 // This is not necessarily done before replace(x) returns, but
134 // it must be done before Child()'s caller releases the
137 // Nil represents "no child". replace(nil) signifies that no
138 // child with this name exists yet. If replace() returns nil,
139 // the existing child should be deleted if possible.
141 // An implementation of Child() is permitted to ignore
142 // replace() or its return value. For example, a regular file
143 // inode does not have children, so Child() always returns
146 // Child() returns the child, if any, with the given name: if
147 // a child was added or changed, the new child is returned.
149 // Caller must have lock (or rlock if replace is nil).
150 Child(name string, replace func(inode) (inode, error)) (inode, error)
157 type fileinfo struct {
164 // Name implements os.FileInfo.
165 func (fi fileinfo) Name() string {
169 // ModTime implements os.FileInfo.
170 func (fi fileinfo) ModTime() time.Time {
174 // Mode implements os.FileInfo.
175 func (fi fileinfo) Mode() os.FileMode {
179 // IsDir implements os.FileInfo.
180 func (fi fileinfo) IsDir() bool {
181 return fi.mode&os.ModeDir != 0
184 // Size implements os.FileInfo.
185 func (fi fileinfo) Size() int64 {
189 // Sys implements os.FileInfo.
190 func (fi fileinfo) Sys() interface{} {
194 type nullnode struct{}
196 func (*nullnode) Mkdir(string, os.FileMode) error {
197 return ErrInvalidOperation
200 func (*nullnode) Read([]byte, filenodePtr) (int, filenodePtr, error) {
201 return 0, filenodePtr{}, ErrInvalidOperation
204 func (*nullnode) Write([]byte, filenodePtr) (int, filenodePtr, error) {
205 return 0, filenodePtr{}, ErrInvalidOperation
208 func (*nullnode) Truncate(int64) error {
209 return ErrInvalidOperation
212 func (*nullnode) FileInfo() os.FileInfo {
216 func (*nullnode) IsDir() bool {
220 func (*nullnode) Readdir() ([]os.FileInfo, error) {
221 return nil, ErrInvalidOperation
224 func (*nullnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
225 return nil, ErrNotADirectory
228 type treenode struct {
231 inodes map[string]inode
237 func (n *treenode) FS() FileSystem {
241 func (n *treenode) SetParent(p inode, name string) {
245 n.fileinfo.name = name
248 func (n *treenode) Parent() inode {
254 func (n *treenode) IsDir() bool {
258 func (n *treenode) Child(name string, replace func(inode) (inode, error)) (child inode, err error) {
259 child = n.inodes[name]
260 if name == "" || name == "." || name == ".." {
261 err = ErrInvalidArgument
267 newchild, err := replace(child)
272 delete(n.inodes, name)
273 } else if newchild != child {
274 n.inodes[name] = newchild
275 n.fileinfo.modTime = time.Now()
281 func (n *treenode) Size() int64 {
282 return n.FileInfo().Size()
285 func (n *treenode) FileInfo() os.FileInfo {
288 n.fileinfo.size = int64(len(n.inodes))
292 func (n *treenode) Readdir() (fi []os.FileInfo, err error) {
295 fi = make([]os.FileInfo, 0, len(n.inodes))
296 for _, inode := range n.inodes {
297 fi = append(fi, inode.FileInfo())
302 type fileSystem struct {
309 func (fs *fileSystem) rootnode() inode {
313 func (fs *fileSystem) throttle() *throttle {
317 func (fs *fileSystem) locker() sync.Locker {
321 // OpenFile is analogous to os.OpenFile().
322 func (fs *fileSystem) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
323 return fs.openFile(name, flag, perm)
326 func (fs *fileSystem) openFile(name string, flag int, perm os.FileMode) (*filehandle, error) {
327 if flag&os.O_SYNC != 0 {
328 return nil, ErrSyncNotSupported
330 dirname, name := path.Split(name)
331 parent, err := rlookup(fs.root, dirname)
335 var readable, writable bool
336 switch flag & (os.O_RDWR | os.O_RDONLY | os.O_WRONLY) {
345 return nil, fmt.Errorf("invalid flags 0x%x", flag)
347 if !writable && parent.IsDir() {
348 // A directory can be opened via "foo/", "foo/.", or
352 return &filehandle{inode: parent}, nil
354 return &filehandle{inode: parent.Parent()}, nil
357 createMode := flag&os.O_CREATE != 0
360 defer parent.Unlock()
363 defer parent.RUnlock()
365 n, err := parent.Child(name, nil)
370 return nil, os.ErrNotExist
372 n, err = parent.Child(name, func(inode) (repl inode, err error) {
373 repl, err = parent.FS().newNode(name, perm|0755, time.Now())
377 repl.SetParent(parent, name)
383 // Parent rejected new child, but returned no error
384 return nil, ErrInvalidArgument
386 } else if flag&os.O_EXCL != 0 {
387 return nil, ErrFileExists
388 } else if flag&os.O_TRUNC != 0 {
390 return nil, fmt.Errorf("invalid flag O_TRUNC in read-only mode")
391 } else if n.IsDir() {
392 return nil, fmt.Errorf("invalid flag O_TRUNC when opening directory")
393 } else if err := n.Truncate(0); err != nil {
399 append: flag&os.O_APPEND != 0,
405 func (fs *fileSystem) Open(name string) (http.File, error) {
406 return fs.OpenFile(name, os.O_RDONLY, 0)
409 func (fs *fileSystem) Create(name string) (File, error) {
410 return fs.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0)
413 func (fs *fileSystem) Mkdir(name string, perm os.FileMode) error {
414 dirname, name := path.Split(name)
415 n, err := rlookup(fs.root, dirname)
421 if child, err := n.Child(name, nil); err != nil {
423 } else if child != nil {
427 _, err = n.Child(name, func(inode) (repl inode, err error) {
428 repl, err = n.FS().newNode(name, perm|os.ModeDir, time.Now())
432 repl.SetParent(n, name)
438 func (fs *fileSystem) Stat(name string) (os.FileInfo, error) {
439 node, err := rlookup(fs.root, name)
443 return node.FileInfo(), nil
446 func (fs *fileSystem) Rename(oldname, newname string) error {
447 olddir, oldname := path.Split(oldname)
448 if oldname == "" || oldname == "." || oldname == ".." {
449 return ErrInvalidArgument
451 olddirf, err := fs.openFile(olddir+".", os.O_RDONLY, 0)
453 return fmt.Errorf("%q: %s", olddir, err)
455 defer olddirf.Close()
457 newdir, newname := path.Split(newname)
458 if newname == "." || newname == ".." {
459 return ErrInvalidArgument
460 } else if newname == "" {
461 // Rename("a/b", "c/") means Rename("a/b", "c/b")
464 newdirf, err := fs.openFile(newdir+".", os.O_RDONLY, 0)
466 return fmt.Errorf("%q: %s", newdir, err)
468 defer newdirf.Close()
470 // TODO: If the nearest common ancestor ("nca") of olddirf and
471 // newdirf is on a different filesystem than fs, we should
472 // call nca.FS().Rename() instead of proceeding. Until then
473 // it's awkward for filesystems to implement their own Rename
474 // methods effectively: the only one that runs is the one on
475 // the root FileSystem exposed to the caller (webdav, fuse,
478 // When acquiring locks on multiple inodes, avoid deadlock by
479 // locking the entire containing filesystem first.
480 cfs := olddirf.inode.FS()
482 defer cfs.locker().Unlock()
484 if cfs != newdirf.inode.FS() {
485 // Moving inodes across filesystems is not (yet)
486 // supported. Locking inodes from different
487 // filesystems could deadlock, so we must error out
489 return ErrInvalidArgument
492 // To ensure we can test reliably whether we're about to move
493 // a directory into itself, lock all potential common
494 // ancestors of olddir and newdir.
495 needLock := []sync.Locker{}
496 for _, node := range []inode{olddirf.inode, newdirf.inode} {
497 needLock = append(needLock, node)
498 for node.Parent() != node && node.Parent().FS() == node.FS() {
500 needLock = append(needLock, node)
503 locked := map[sync.Locker]bool{}
504 for i := len(needLock) - 1; i >= 0; i-- {
505 if n := needLock[i]; !locked[n] {
512 _, err = olddirf.inode.Child(oldname, func(oldinode inode) (inode, error) {
514 return oldinode, os.ErrNotExist
516 if locked[oldinode] {
517 // oldinode cannot become a descendant of itself.
518 return oldinode, ErrInvalidArgument
520 if oldinode.FS() != cfs && newdirf.inode != olddirf.inode {
521 // moving a mount point to a different parent
522 // is not (yet) supported.
523 return oldinode, ErrInvalidArgument
525 accepted, err := newdirf.inode.Child(newname, func(existing inode) (inode, error) {
526 if existing != nil && existing.IsDir() {
527 return existing, ErrIsDirectory
532 // Leave oldinode in olddir.
535 accepted.SetParent(newdirf.inode, newname)
541 func (fs *fileSystem) Remove(name string) error {
542 return fs.remove(strings.TrimRight(name, "/"), false)
545 func (fs *fileSystem) RemoveAll(name string) error {
546 err := fs.remove(strings.TrimRight(name, "/"), true)
547 if os.IsNotExist(err) {
548 // "If the path does not exist, RemoveAll returns
549 // nil." (see "os" pkg)
555 func (fs *fileSystem) remove(name string, recursive bool) error {
556 dirname, name := path.Split(name)
557 if name == "" || name == "." || name == ".." {
558 return ErrInvalidArgument
560 dir, err := rlookup(fs.root, dirname)
566 _, err = dir.Child(name, func(node inode) (inode, error) {
568 return nil, os.ErrNotExist
570 if !recursive && node.IsDir() && node.Size() > 0 {
571 return node, ErrDirectoryNotEmpty
578 func (fs *fileSystem) Sync() error {
579 log.Printf("TODO: sync fileSystem")
580 return ErrInvalidOperation
583 func (fs *fileSystem) Flush(string, bool) error {
584 log.Printf("TODO: flush fileSystem")
585 return ErrInvalidOperation
588 // rlookup (recursive lookup) returns the inode for the file/directory
589 // with the given name (which may contain "/" separators). If no such
590 // file/directory exists, the returned node is nil.
591 func rlookup(start inode, path string) (node inode, err error) {
593 for _, name := range strings.Split(path, "/") {
595 if name == "." || name == "" {
603 node, err = func() (inode, error) {
606 return node.Child(name, nil)
608 if node == nil || err != nil {
612 if node == nil && err == nil {
618 func permittedName(name string) bool {
619 return name != "" && name != "." && name != ".." && !strings.Contains(name, "/")