1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
22 var maxBlockSize = 1 << 26
24 // A CollectionFileSystem is a FileSystem that can be serialized as a
25 // manifest and stored as a collection.
26 type CollectionFileSystem interface {
29 // Flush all file data to Keep and return a snapshot of the
30 // filesystem suitable for saving as (Collection)ManifestText.
31 // Prefix (normally ".") is a top level directory, effectively
32 // prepended to all paths in the returned manifest.
33 MarshalManifest(prefix string) (string, error)
36 type collectionFileSystem struct {
41 // FileSystem returns a CollectionFileSystem for the collection.
42 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
44 if c.ModifiedAt == nil {
47 modTime = *c.ModifiedAt
49 fs := &collectionFileSystem{
51 fileSystem: fileSystem{
52 fsBackend: keepBackend{apiClient: client, keepClient: kc},
60 mode: os.ModeDir | 0755,
63 inodes: make(map[string]inode),
66 root.SetParent(root, ".")
67 if err := root.loadManifest(c.ManifestText); err != nil {
70 backdateTree(root, modTime)
75 func backdateTree(n inode, modTime time.Time) {
76 switch n := n.(type) {
78 n.fileinfo.modTime = modTime
80 n.fileinfo.modTime = modTime
81 for _, n := range n.inodes {
82 backdateTree(n, modTime)
87 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
88 if name == "" || name == "." || name == ".." {
89 return nil, ErrInvalidArgument
97 mode: perm | os.ModeDir,
100 inodes: make(map[string]inode),
108 mode: perm & ^os.ModeDir,
115 func (fs *collectionFileSystem) Sync() error {
116 log.Printf("cfs.Sync()")
120 txt, err := fs.MarshalManifest(".")
122 log.Printf("WARNING: (collectionFileSystem)Sync() failed: %s", err)
129 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, fs.UpdateBody(coll), map[string]interface{}{"select": []string{"uuid"}})
131 log.Printf("WARNING: (collectionFileSystem)Sync() failed: %s", err)
136 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
137 fs.fileSystem.root.Lock()
138 defer fs.fileSystem.root.Unlock()
139 return fs.fileSystem.root.(*dirnode).marshalManifest(prefix)
142 // filenodePtr is an offset into a file that is (usually) efficient to
143 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
145 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
146 // corresponds to file offset filenodePtr.off. Otherwise, it is
147 // necessary to reexamine len(filenode.segments[0]) etc. to find the
148 // correct segment 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 is beyond EOF, ptr.segment* will indicate precisely
165 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
167 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
168 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
171 // meaningless anyway
173 } else if ptr.off >= fn.fileinfo.size {
174 ptr.segmentIdx = len(fn.segments)
176 ptr.repacked = fn.repacked
178 } else if ptr.repacked == fn.repacked {
179 // segmentIdx and segmentOff accurately reflect
180 // ptr.off, but might have fallen off the end of a
182 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
189 ptr.repacked = fn.repacked
191 if ptr.off >= fn.fileinfo.size {
192 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
195 // Recompute segmentIdx and segmentOff. 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.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
200 // This would panic (index out of range) if
201 // fn.fileinfo.size were larger than
202 // sum(fn.segments[i].Len()) -- but that can't happen
203 // because we have ensured fn.fileinfo.size is always
205 segLen := int64(fn.segments[ptr.segmentIdx].Len())
206 if off+segLen > ptr.off {
207 ptr.segmentOff = int(ptr.off - off)
215 // filenode implements inode.
216 type filenode struct {
221 // number of times `segments` has changed in a
222 // way that might invalidate a filenodePtr
224 memsize int64 // bytes in memSegments
229 // caller must have lock
230 func (fn *filenode) appendSegment(e segment) {
231 fn.segments = append(fn.segments, e)
232 fn.fileinfo.size += int64(e.Len())
235 func (fn *filenode) SetParent(p inode, name string) {
239 fn.fileinfo.name = name
242 func (fn *filenode) Parent() inode {
248 func (fn *filenode) FS() FileSystem {
252 // Read reads file data from a single segment, starting at startPtr,
253 // into p. startPtr is assumed not to be up-to-date. Caller must have
255 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
256 ptr = fn.seek(startPtr)
258 err = ErrNegativeOffset
261 if ptr.segmentIdx >= len(fn.segments) {
265 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
269 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
272 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
280 func (fn *filenode) Size() int64 {
283 return fn.fileinfo.Size()
286 func (fn *filenode) FileInfo() os.FileInfo {
292 func (fn *filenode) Truncate(size int64) error {
295 return fn.truncate(size)
298 func (fn *filenode) truncate(size int64) error {
299 if size == fn.fileinfo.size {
303 if size < fn.fileinfo.size {
304 ptr := fn.seek(filenodePtr{off: size})
305 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
306 if seg, ok := fn.segments[i].(*memSegment); ok {
307 fn.memsize -= int64(seg.Len())
310 if ptr.segmentOff == 0 {
311 fn.segments = fn.segments[:ptr.segmentIdx]
313 fn.segments = fn.segments[:ptr.segmentIdx+1]
314 switch seg := fn.segments[ptr.segmentIdx].(type) {
316 seg.Truncate(ptr.segmentOff)
317 fn.memsize += int64(seg.Len())
319 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
322 fn.fileinfo.size = size
325 for size > fn.fileinfo.size {
326 grow := size - fn.fileinfo.size
329 if len(fn.segments) == 0 {
331 fn.segments = append(fn.segments, seg)
332 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
334 fn.segments = append(fn.segments, seg)
336 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
339 seg.Truncate(seg.Len() + int(grow))
340 fn.fileinfo.size += grow
346 // Write writes data from p to the file, starting at startPtr,
347 // extending the file size if necessary. Caller must have Lock.
348 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
349 if startPtr.off > fn.fileinfo.size {
350 if err = fn.truncate(startPtr.off); err != nil {
351 return 0, startPtr, err
354 ptr = fn.seek(startPtr)
356 err = ErrNegativeOffset
359 for len(p) > 0 && err == nil {
361 if len(cando) > maxBlockSize {
362 cando = cando[:maxBlockSize]
364 // Rearrange/grow fn.segments (and shrink cando if
365 // needed) such that cando can be copied to
366 // fn.segments[ptr.segmentIdx] at offset
368 cur := ptr.segmentIdx
369 prev := ptr.segmentIdx - 1
371 if cur < len(fn.segments) {
372 _, curWritable = fn.segments[cur].(*memSegment)
374 var prevAppendable bool
375 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
376 _, prevAppendable = fn.segments[prev].(*memSegment)
378 if ptr.segmentOff > 0 && !curWritable {
379 // Split a non-writable block.
380 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
381 // Truncate cur, and insert a new
384 fn.segments = append(fn.segments, nil)
385 copy(fn.segments[cur+1:], fn.segments[cur:])
387 // Split cur into two copies, truncate
388 // the one on the left, shift the one
389 // on the right, and insert a new
390 // segment between them.
391 fn.segments = append(fn.segments, nil, nil)
392 copy(fn.segments[cur+2:], fn.segments[cur:])
393 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
398 seg.Truncate(len(cando))
399 fn.memsize += int64(len(cando))
400 fn.segments[cur] = seg
401 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
406 } else if curWritable {
407 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
412 // Shrink cando if needed to fit in
414 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
415 cando = cando[:cangrow]
419 if cur == len(fn.segments) {
420 // ptr is at EOF, filesize is changing.
421 fn.fileinfo.size += int64(len(cando))
422 } else if el := fn.segments[cur].Len(); el <= len(cando) {
423 // cando is long enough that we won't
424 // need cur any more. shrink cando to
425 // be exactly as long as cur
426 // (otherwise we'd accidentally shift
427 // the effective position of all
428 // segments after cur).
430 copy(fn.segments[cur:], fn.segments[cur+1:])
431 fn.segments = fn.segments[:len(fn.segments)-1]
433 // shrink cur by the same #bytes we're growing prev
434 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
440 ptr.segmentOff = fn.segments[prev].Len()
441 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
442 fn.memsize += int64(len(cando))
446 // Insert a segment between prev and
447 // cur, and advance prev/cur.
448 fn.segments = append(fn.segments, nil)
449 if cur < len(fn.segments) {
450 copy(fn.segments[cur+1:], fn.segments[cur:])
454 // appending a new segment does
455 // not invalidate any ptrs
458 seg.Truncate(len(cando))
459 fn.memsize += int64(len(cando))
460 fn.segments[cur] = seg
466 // Finally we can copy bytes from cando to the current segment.
467 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
471 ptr.off += int64(len(cando))
472 ptr.segmentOff += len(cando)
473 if ptr.segmentOff >= maxBlockSize {
474 fn.pruneMemSegments()
476 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
481 fn.fileinfo.modTime = time.Now()
486 // Write some data out to disk to reduce memory use. Caller must have
488 func (fn *filenode) pruneMemSegments() {
489 // TODO: async (don't hold Lock() while waiting for Keep)
490 // TODO: share code with (*dirnode)sync()
491 // TODO: pack/flush small blocks too, when fragmented
492 for idx, seg := range fn.segments {
493 seg, ok := seg.(*memSegment)
494 if !ok || seg.Len() < maxBlockSize {
497 locator, _, err := fn.FS().PutB(seg.buf)
499 // TODO: stall (or return errors from)
500 // subsequent writes until flushing
504 fn.memsize -= int64(seg.Len())
505 fn.segments[idx] = storedSegment{
515 type dirnode struct {
516 fs *collectionFileSystem
520 func (dn *dirnode) FS() FileSystem {
524 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
525 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
526 gn := &getternode{Getter: func() ([]byte, error) {
529 coll.ManifestText, err = dn.fs.MarshalManifest(".")
533 data, err := json.Marshal(&coll)
535 data = append(data, '\n')
539 gn.SetParent(dn, name)
542 return dn.treenode.Child(name, replace)
545 // sync flushes in-memory data (for all files in the tree rooted at
546 // dn) to persistent storage. Caller must hold dn.Lock().
547 func (dn *dirnode) sync() error {
548 type shortBlock struct {
552 var pending []shortBlock
555 flush := func(sbs []shortBlock) error {
559 block := make([]byte, 0, maxBlockSize)
560 for _, sb := range sbs {
561 block = append(block, sb.fn.segments[sb.idx].(*memSegment).buf...)
563 locator, _, err := dn.fs.PutB(block)
568 for _, sb := range sbs {
569 data := sb.fn.segments[sb.idx].(*memSegment).buf
570 sb.fn.segments[sb.idx] = storedSegment{
578 sb.fn.memsize -= int64(len(data))
583 names := make([]string, 0, len(dn.inodes))
584 for name := range dn.inodes {
585 names = append(names, name)
589 for _, name := range names {
590 fn, ok := dn.inodes[name].(*filenode)
596 for idx, seg := range fn.segments {
597 seg, ok := seg.(*memSegment)
601 if seg.Len() > maxBlockSize/2 {
602 if err := flush([]shortBlock{{fn, idx}}); err != nil {
607 if pendingLen+seg.Len() > maxBlockSize {
608 if err := flush(pending); err != nil {
614 pending = append(pending, shortBlock{fn, idx})
615 pendingLen += seg.Len()
618 return flush(pending)
621 // caller must have read lock.
622 func (dn *dirnode) marshalManifest(prefix string) (string, error) {
624 type filepart struct {
629 var fileparts []filepart
633 if err := dn.sync(); err != nil {
637 names := make([]string, 0, len(dn.inodes))
638 for name, node := range dn.inodes {
639 names = append(names, name)
645 for _, name := range names {
646 switch node := dn.inodes[name].(type) {
648 subdir, err := node.marshalManifest(prefix + "/" + name)
652 subdirs = subdirs + subdir
654 if len(node.segments) == 0 {
655 fileparts = append(fileparts, filepart{name: name})
658 for _, seg := range node.segments {
659 switch seg := seg.(type) {
661 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
662 streamLen -= int64(seg.size)
664 blocks = append(blocks, seg.locator)
668 offset: streamLen + int64(seg.offset),
669 length: int64(seg.length),
671 if prev := len(fileparts) - 1; prev >= 0 &&
672 fileparts[prev].name == name &&
673 fileparts[prev].offset+fileparts[prev].length == next.offset {
674 fileparts[prev].length += next.length
676 fileparts = append(fileparts, next)
678 streamLen += int64(seg.size)
680 // This can't happen: we
681 // haven't unlocked since
683 panic(fmt.Sprintf("can't marshal segment type %T", seg))
687 panic(fmt.Sprintf("can't marshal inode type %T", node))
690 var filetokens []string
691 for _, s := range fileparts {
692 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
694 if len(filetokens) == 0 {
696 } else if len(blocks) == 0 {
697 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
699 return manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n" + subdirs, nil
702 func (dn *dirnode) loadManifest(txt string) error {
704 streams := strings.Split(txt, "\n")
705 if streams[len(streams)-1] != "" {
706 return fmt.Errorf("line %d: no trailing newline", len(streams))
708 streams = streams[:len(streams)-1]
709 segments := []storedSegment{}
710 for i, stream := range streams {
712 var anyFileTokens bool
715 segments = segments[:0]
716 for i, token := range strings.Split(stream, " ") {
718 dirname = manifestUnescape(token)
721 if !strings.Contains(token, ":") {
723 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
725 toks := strings.SplitN(token, "+", 3)
727 return fmt.Errorf("line %d: bad locator %q", lineno, token)
729 length, err := strconv.ParseInt(toks[1], 10, 32)
730 if err != nil || length < 0 {
731 return fmt.Errorf("line %d: bad locator %q", lineno, token)
733 segments = append(segments, storedSegment{
740 } else if len(segments) == 0 {
741 return fmt.Errorf("line %d: bad locator %q", lineno, token)
744 toks := strings.SplitN(token, ":", 3)
746 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
750 offset, err := strconv.ParseInt(toks[0], 10, 64)
751 if err != nil || offset < 0 {
752 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
754 length, err := strconv.ParseInt(toks[1], 10, 64)
755 if err != nil || length < 0 {
756 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
758 name := dirname + "/" + manifestUnescape(toks[2])
759 fnode, err := dn.createFileAndParents(name)
761 return fmt.Errorf("line %d: cannot use path %q: %s", lineno, name, err)
763 // Map the stream offset/range coordinates to
764 // block/offset/range coordinates and add
765 // corresponding storedSegments to the filenode
767 // Can't continue where we left off.
768 // TODO: binary search instead of
769 // rewinding all the way (but this
770 // situation might be rare anyway)
773 for next := int64(0); segIdx < len(segments); segIdx++ {
774 seg := segments[segIdx]
775 next = pos + int64(seg.Len())
776 if next <= offset || seg.Len() == 0 {
780 if pos >= offset+length {
785 blkOff = int(offset - pos)
787 blkLen := seg.Len() - blkOff
788 if pos+int64(blkOff+blkLen) > offset+length {
789 blkLen = int(offset + length - pos - int64(blkOff))
791 fnode.appendSegment(storedSegment{
793 locator: seg.locator,
798 if next > offset+length {
804 if segIdx == len(segments) && pos < offset+length {
805 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
809 return fmt.Errorf("line %d: no file segments", lineno)
810 } else if len(segments) == 0 {
811 return fmt.Errorf("line %d: no locators", lineno)
812 } else if dirname == "" {
813 return fmt.Errorf("line %d: no stream name", lineno)
819 // only safe to call from loadManifest -- no locking
820 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
822 names := strings.Split(path, "/")
823 basename := names[len(names)-1]
824 if !permittedName(basename) {
825 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
828 for _, name := range names[:len(names)-1] {
834 // can't be sure parent will be a *dirnode
835 return nil, ErrInvalidArgument
840 node, err = node.Child(name, func(child inode) (inode, error) {
842 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
846 child.SetParent(node, name)
848 } else if !child.IsDir() {
849 return child, ErrFileExists
858 _, err = node.Child(basename, func(child inode) (inode, error) {
859 switch child := child.(type) {
861 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
865 child.SetParent(node, basename)
866 fn = child.(*filenode)
872 return child, ErrIsDirectory
874 return child, ErrInvalidArgument
880 type segment interface {
883 // Return a new segment with a subsection of the data from this
884 // one. length<0 means length=Len()-off.
885 Slice(off int, length int) segment
888 type memSegment struct {
892 func (me *memSegment) Len() int {
896 func (me *memSegment) Slice(off, length int) segment {
898 length = len(me.buf) - off
900 buf := make([]byte, length)
901 copy(buf, me.buf[off:])
902 return &memSegment{buf: buf}
905 func (me *memSegment) Truncate(n int) {
909 newsize = newsize << 2
911 newbuf := make([]byte, n, newsize)
915 // Zero unused part when shrinking, in case we grow
916 // and start using it again later.
917 for i := n; i < len(me.buf); i++ {
924 func (me *memSegment) WriteAt(p []byte, off int) {
925 if off+len(p) > len(me.buf) {
926 panic("overflowed segment")
928 copy(me.buf[off:], p)
931 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
932 if off > int64(me.Len()) {
936 n = copy(p, me.buf[int(off):])
943 type storedSegment struct {
946 size int // size of stored block (also encoded in locator)
947 offset int // position of segment within the stored block
948 length int // bytes in this segment (offset + length <= size)
951 func (se storedSegment) Len() int {
955 func (se storedSegment) Slice(n, size int) segment {
958 if size >= 0 && se.length > size {
964 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
965 if off > int64(se.length) {
968 maxlen := se.length - int(off)
971 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
977 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
980 func canonicalName(name string) string {
981 name = path.Clean("/" + name)
982 if name == "/" || name == "./" {
984 } else if strings.HasPrefix(name, "/") {
990 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
992 func manifestUnescapeFunc(seq string) string {
996 i, err := strconv.ParseUint(seq[1:], 8, 8)
998 // Invalid escape sequence: can't unescape.
1001 return string([]byte{byte(i)})
1004 func manifestUnescape(s string) string {
1005 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1008 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1010 func manifestEscapeFunc(seq string) string {
1011 return fmt.Sprintf("\\%03o", byte(seq[0]))
1014 func manifestEscape(s string) string {
1015 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)