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 ErrPermission = os.ErrPermission
27 maxBlockSize = 1 << 26
36 Readdir(int) ([]os.FileInfo, error)
37 Stat() (os.FileInfo, error)
41 type keepClient interface {
42 ReadAt(locator string, p []byte, off int) (int, error)
45 type fileinfo struct {
52 // Name implements os.FileInfo.
53 func (fi fileinfo) Name() string {
57 // ModTime implements os.FileInfo.
58 func (fi fileinfo) ModTime() time.Time {
62 // Mode implements os.FileInfo.
63 func (fi fileinfo) Mode() os.FileMode {
67 // IsDir implements os.FileInfo.
68 func (fi fileinfo) IsDir() bool {
69 return fi.mode&os.ModeDir != 0
72 // Size implements os.FileInfo.
73 func (fi fileinfo) Size() int64 {
77 // Sys implements os.FileInfo.
78 func (fi fileinfo) Sys() interface{} {
82 func (fi fileinfo) Stat() os.FileInfo {
86 // A CollectionFileSystem is an http.Filesystem plus Stat() and
87 // support for opening writable files.
88 type CollectionFileSystem interface {
90 Stat(name string) (os.FileInfo, error)
91 Create(name string) (File, error)
92 OpenFile(name string, flag int, perm os.FileMode) (File, error)
95 type fileSystem struct {
99 func (fs *fileSystem) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
100 return fs.dirnode.OpenFile(path.Clean(name), flag, perm)
103 func (fs *fileSystem) Open(name string) (http.File, error) {
104 return fs.dirnode.OpenFile(path.Clean(name), os.O_RDONLY, 0)
107 func (fs *fileSystem) Create(name string) (File, error) {
108 return fs.dirnode.OpenFile(path.Clean(name), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0)
111 func (fs *fileSystem) Stat(name string) (os.FileInfo, error) {
112 f, err := fs.OpenFile(name, os.O_RDONLY, 0)
120 type inode interface {
122 OpenFile(string, int, os.FileMode) (*file, error)
124 Read([]byte, filenodePtr) (int, filenodePtr, error)
125 Write([]byte, filenodePtr) (int, filenodePtr, error)
126 Truncate(int64) error
127 Readdir() []os.FileInfo
134 // filenode implements inode.
135 type filenode struct {
139 repacked int64 // number of times anything in []extents has changed len
143 // filenodePtr is an offset into a file that is (usually) efficient to
144 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
145 // then filenode.extents[filenodePtr.extentIdx][filenodePtr.extentOff]
146 // corresponds to file offset filenodePtr.off. Otherwise, it is
147 // necessary to reexamine len(filenode.extents[0]) etc. to find the
148 // correct extent and offset.
149 type filenodePtr struct {
156 // seek returns a ptr that is consistent with both startPtr.off and
157 // the current state of fn. The caller must already hold fn.RLock() or
160 // If startPtr points beyond the end of the file, ptr will point to
161 // exactly the end of the file.
165 // ptr.extentIdx == len(filenode.extents) // i.e., at EOF
167 // filenode.extents[ptr.extentIdx].Len() >= ptr.extentOff
168 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
171 // meaningless anyway
173 } else if ptr.off >= fn.fileinfo.size {
174 ptr.off = fn.fileinfo.size
175 ptr.extentIdx = len(fn.extents)
177 ptr.repacked = fn.repacked
179 } else if ptr.repacked == fn.repacked {
180 // extentIdx and extentOff accurately reflect ptr.off,
181 // but might have fallen off the end of an extent
182 if ptr.extentOff >= fn.extents[ptr.extentIdx].Len() {
189 ptr.repacked = fn.repacked
191 if ptr.off >= fn.fileinfo.size {
192 ptr.extentIdx, ptr.extentOff = len(fn.extents), 0
195 // Recompute extentIdx and extentOff. We have already
196 // established fn.fileinfo.size > ptr.off >= 0, so we don't
197 // have to deal with edge cases here.
199 for ptr.extentIdx, ptr.extentOff = 0, 0; off < ptr.off; ptr.extentIdx++ {
200 // This would panic (index out of range) if
201 // fn.fileinfo.size were larger than
202 // sum(fn.extents[i].Len()) -- but that can't happen
203 // because we have ensured fn.fileinfo.size is always
205 extLen := int64(fn.extents[ptr.extentIdx].Len())
206 if off+extLen > ptr.off {
207 ptr.extentOff = int(ptr.off - off)
215 func (fn *filenode) appendExtent(e extent) {
218 fn.extents = append(fn.extents, e)
219 fn.fileinfo.size += int64(e.Len())
222 func (fn *filenode) OpenFile(string, int, os.FileMode) (*file, error) {
223 return nil, os.ErrNotExist
226 func (fn *filenode) Parent() inode {
230 func (fn *filenode) Readdir() []os.FileInfo {
234 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
237 ptr = fn.seek(startPtr)
239 err = ErrNegativeOffset
242 if ptr.extentIdx >= len(fn.extents) {
246 n, err = fn.extents[ptr.extentIdx].ReadAt(p, int64(ptr.extentOff))
250 if ptr.extentOff == fn.extents[ptr.extentIdx].Len() {
253 if ptr.extentIdx < len(fn.extents) && err == io.EOF {
261 func (fn *filenode) Truncate(size int64) error {
264 if size < fn.fileinfo.size {
265 ptr := fn.seek(filenodePtr{off: size, repacked: fn.repacked - 1})
266 if ptr.extentOff == 0 {
267 fn.extents = fn.extents[:ptr.extentIdx]
269 fn.extents = fn.extents[:ptr.extentIdx+1]
270 e := fn.extents[ptr.extentIdx]
271 if e, ok := e.(writableExtent); ok {
272 e.Truncate(ptr.extentOff)
274 fn.extents[ptr.extentIdx] = e.Slice(0, ptr.extentOff)
277 fn.fileinfo.size = size
281 for size > fn.fileinfo.size {
282 grow := size - fn.fileinfo.size
285 if len(fn.extents) == 0 {
287 fn.extents = append(fn.extents, e)
288 } else if e, ok = fn.extents[len(fn.extents)-1].(writableExtent); !ok || e.Len() >= maxBlockSize {
290 fn.extents = append(fn.extents, e)
294 if maxgrow := int64(maxBlockSize - e.Len()); maxgrow < grow {
297 e.Truncate(e.Len() + int(grow))
298 fn.fileinfo.size += grow
303 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
306 ptr = fn.seek(startPtr)
308 err = ErrNegativeOffset
311 for len(p) > 0 && err == nil {
313 if len(cando) > maxBlockSize {
314 cando = cando[:maxBlockSize]
316 // Rearrange/grow fn.extents (and shrink cando if
317 // needed) such that cando can be copied to
318 // fn.extents[ptr.extentIdx] at offset ptr.extentOff.
320 prev := ptr.extentIdx - 1
322 if cur < len(fn.extents) {
323 _, curWritable = fn.extents[cur].(writableExtent)
325 var prevAppendable bool
326 if prev >= 0 && fn.extents[prev].Len() < maxBlockSize {
327 _, prevAppendable = fn.extents[prev].(writableExtent)
329 if ptr.extentOff > 0 && !curWritable {
330 // Split a non-writable block.
331 if max := fn.extents[cur].Len() - ptr.extentOff; max <= len(cando) {
332 // Truncate cur, and insert a new
335 fn.extents = append(fn.extents, nil)
336 copy(fn.extents[cur+1:], fn.extents[cur:])
338 // Split cur into two copies, truncate
339 // the one on the left, shift the one
340 // on the right, and insert a new
341 // extent between them.
342 fn.extents = append(fn.extents, nil, nil)
343 copy(fn.extents[cur+2:], fn.extents[cur:])
344 fn.extents[cur+2] = fn.extents[cur+2].Slice(ptr.extentOff+len(cando), -1)
349 e.Truncate(len(cando))
351 fn.extents[prev] = fn.extents[prev].Slice(0, ptr.extentOff)
356 } else if curWritable {
357 if fit := int(fn.extents[cur].Len()) - ptr.extentOff; fit < len(cando) {
362 // Shrink cando if needed to fit in prev extent.
363 if cangrow := maxBlockSize - fn.extents[prev].Len(); cangrow < len(cando) {
364 cando = cando[:cangrow]
368 if cur == len(fn.extents) {
369 // ptr is at EOF, filesize is changing.
370 fn.fileinfo.size += int64(len(cando))
371 } else if el := fn.extents[cur].Len(); el <= len(cando) {
372 // cando is long enough that we won't
373 // need cur any more. shrink cando to
374 // be exactly as long as cur
375 // (otherwise we'd accidentally shift
376 // the effective position of all
377 // extents after cur).
379 copy(fn.extents[cur:], fn.extents[cur+1:])
380 fn.extents = fn.extents[:len(fn.extents)-1]
382 // shrink cur by the same #bytes we're growing prev
383 fn.extents[cur] = fn.extents[cur].Slice(len(cando), -1)
389 ptr.extentOff = fn.extents[prev].Len()
390 fn.extents[prev].(writableExtent).Truncate(ptr.extentOff + len(cando))
394 // Insert an extent between prev and cur, and advance prev/cur.
395 fn.extents = append(fn.extents, nil)
396 if cur < len(fn.extents) {
397 copy(fn.extents[cur+1:], fn.extents[cur:])
401 // appending a new extent does
402 // not invalidate any ptrs
405 e.Truncate(len(cando))
412 // Finally we can copy bytes from cando to the current extent.
413 fn.extents[ptr.extentIdx].(writableExtent).WriteAt(cando, ptr.extentOff)
417 ptr.off += int64(len(cando))
418 ptr.extentOff += len(cando)
419 if fn.extents[ptr.extentIdx].Len() == ptr.extentOff {
427 // FileSystem returns a CollectionFileSystem for the collection.
428 func (c *Collection) FileSystem(client *Client, kc keepClient) CollectionFileSystem {
429 fs := &fileSystem{dirnode: dirnode{
430 cache: &keepBlockCache{kc: kc},
433 fileinfo: fileinfo{name: ".", mode: os.ModeDir | 0755},
435 inodes: make(map[string]inode),
437 fs.dirnode.parent = &fs.dirnode
438 fs.dirnode.loadManifest(c.ManifestText)
447 unreaddirs []os.FileInfo
450 func (f *file) Read(p []byte) (n int, err error) {
451 n, f.ptr, err = f.inode.Read(p, f.ptr)
455 func (f *file) Seek(off int64, whence int) (pos int64, err error) {
456 size := f.inode.Size()
467 return f.ptr.off, ErrNegativeOffset
472 if ptr.off != f.ptr.off {
474 // force filenode to recompute f.ptr fields on next
478 return f.ptr.off, nil
481 func (f *file) Truncate(size int64) error {
482 return f.inode.Truncate(size)
485 func (f *file) Write(p []byte) (n int, err error) {
487 return 0, ErrReadOnlyFile
489 n, f.ptr, err = f.inode.Write(p, f.ptr)
493 func (f *file) Readdir(count int) ([]os.FileInfo, error) {
494 if !f.inode.IsDir() {
495 return nil, ErrInvalidOperation
498 return f.inode.Readdir(), nil
500 if f.unreaddirs == nil {
501 f.unreaddirs = f.inode.Readdir()
503 if len(f.unreaddirs) == 0 {
506 if count > len(f.unreaddirs) {
507 count = len(f.unreaddirs)
509 ret := f.unreaddirs[:count]
510 f.unreaddirs = f.unreaddirs[count:]
514 func (f *file) Stat() (os.FileInfo, error) {
518 func (f *file) Close() error {
523 func (f *file) OpenFile(name string, flag int, perm os.FileMode) (*file, error) {
524 return f.inode.OpenFile(name, flag, perm)
527 type dirnode struct {
533 inodes map[string]inode
537 func (dn *dirnode) loadManifest(txt string) {
540 for _, stream := range strings.Split(txt, "\n") {
541 var extents []storedExtent
542 for i, token := range strings.Split(stream, " ") {
544 dirname = manifestUnescape(token)
547 if !strings.Contains(token, ":") {
548 toks := strings.SplitN(token, "+", 3)
553 length, err := strconv.ParseInt(toks[1], 10, 32)
554 if err != nil || length < 0 {
558 extents = append(extents, storedExtent{
565 toks := strings.Split(token, ":")
567 // FIXME: broken manifest
570 offset, err := strconv.ParseInt(toks[0], 10, 64)
571 if err != nil || offset < 0 {
572 // FIXME: broken manifest
575 length, err := strconv.ParseInt(toks[1], 10, 64)
576 if err != nil || length < 0 {
577 // FIXME: broken manifest
580 name := path.Clean(dirname + "/" + manifestUnescape(toks[2]))
581 dn.makeParentDirs(name)
582 f, err := dn.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0700)
587 if f.inode.Stat().IsDir() {
589 // FIXME: broken manifest
592 // Map the stream offset/range coordinates to
593 // block/offset/range coordinates and add
594 // corresponding storedExtents to the filenode
596 for _, e := range extents {
597 next := pos + int64(e.Len())
602 if pos > offset+length {
607 blkOff = int(offset - pos)
609 blkLen := e.Len() - blkOff
610 if pos+int64(blkOff+blkLen) > offset+length {
611 blkLen = int(offset + length - pos - int64(blkOff))
613 f.inode.(*filenode).appendExtent(storedExtent{
626 func (dn *dirnode) makeParentDirs(name string) {
627 names := strings.Split(name, "/")
628 for _, name := range names[:len(names)-1] {
631 if n, ok := dn.inodes[name]; !ok {
638 mode: os.ModeDir | 0755,
641 if dn.inodes == nil {
642 dn.inodes = make(map[string]inode)
647 } else if n, ok := n.(*dirnode); ok {
656 func (dn *dirnode) Parent() inode {
660 func (dn *dirnode) Readdir() (fi []os.FileInfo) {
663 fi = make([]os.FileInfo, 0, len(dn.inodes))
664 for _, inode := range dn.inodes {
665 fi = append(fi, inode.Stat())
670 func (dn *dirnode) Read(p []byte, ptr filenodePtr) (int, filenodePtr, error) {
671 return 0, ptr, ErrInvalidOperation
674 func (dn *dirnode) Write(p []byte, ptr filenodePtr) (int, filenodePtr, error) {
675 return 0, ptr, ErrInvalidOperation
678 func (dn *dirnode) Truncate(int64) error {
679 return ErrInvalidOperation
682 func (dn *dirnode) OpenFile(name string, flag int, perm os.FileMode) (*file, error) {
683 name = strings.TrimSuffix(name, "/")
684 if name == "." || name == "" {
685 return &file{inode: dn}, nil
687 if dirname, name := path.Split(name); dirname != "" {
688 // OpenFile("foo/bar/baz") =>
689 // OpenFile("foo/bar").OpenFile("baz") (or
690 // ErrNotExist, if foo/bar is a file)
691 f, err := dn.OpenFile(dirname, os.O_RDONLY, 0)
696 if dn, ok := f.inode.(*dirnode); ok {
697 return dn.OpenFile(name, flag, perm)
699 return nil, os.ErrNotExist
705 return &file{inode: dn.parent}, nil
707 n, ok := dn.inodes[name]
709 if flag&os.O_CREATE == 0 {
710 return nil, os.ErrNotExist
719 if dn.inodes == nil {
720 dn.inodes = make(map[string]inode)
724 } else if flag&os.O_EXCL != 0 {
725 return nil, ErrFileExists
729 append: flag&os.O_APPEND != 0,
730 writable: flag&(os.O_WRONLY|os.O_RDWR) != 0,
734 type extent interface {
737 // Return a new extent with a subsection of the data from this
738 // one. length<0 means length=Len()-off.
739 Slice(off int, length int) extent
742 type writableExtent interface {
744 WriteAt(p []byte, off int)
748 type memExtent struct {
752 func (me *memExtent) Len() int {
756 func (me *memExtent) Slice(off, length int) extent {
758 length = len(me.buf) - off
760 buf := make([]byte, length)
761 copy(buf, me.buf[off:])
762 return &memExtent{buf: buf}
765 func (me *memExtent) Truncate(n int) {
769 newsize = newsize << 2
771 newbuf := make([]byte, n, newsize)
775 // Zero unused part when shrinking, in case we grow
776 // and start using it again later.
777 for i := n; i < len(me.buf); i++ {
784 func (me *memExtent) WriteAt(p []byte, off int) {
785 if off+len(p) > len(me.buf) {
786 panic("overflowed extent")
788 copy(me.buf[off:], p)
791 func (me *memExtent) ReadAt(p []byte, off int64) (n int, err error) {
792 if off > int64(me.Len()) {
796 n = copy(p, me.buf[int(off):])
803 type storedExtent struct {
810 func (se storedExtent) Len() int {
814 func (se storedExtent) Slice(n, size int) extent {
817 if size >= 0 && se.length > size {
823 func (se storedExtent) ReadAt(p []byte, off int64) (n int, err error) {
824 if off > int64(se.length) {
827 maxlen := se.length - int(off)
830 n, err = se.cache.ReadAt(se.locator, p, int(off)+se.offset)
836 return se.cache.ReadAt(se.locator, p, int(off)+se.offset)
839 type blockCache interface {
840 ReadAt(locator string, p []byte, off int) (n int, err error)
843 type keepBlockCache struct {
847 var scratch = make([]byte, 2<<26)
849 func (kbc *keepBlockCache) ReadAt(locator string, p []byte, off int) (int, error) {
850 return kbc.kc.ReadAt(locator, p, off)
853 func canonicalName(name string) string {
854 name = path.Clean("/" + name)
855 if name == "/" || name == "./" {
857 } else if strings.HasPrefix(name, "/") {
863 var manifestEscapeSeq = regexp.MustCompile(`\\([0-9]{3}|\\)`)
865 func manifestUnescapeSeq(seq string) string {
869 i, err := strconv.ParseUint(seq[1:], 8, 8)
871 // Invalid escape sequence: can't unescape.
874 return string([]byte{byte(i)})
877 func manifestUnescape(s string) string {
878 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeSeq)