1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
25 maxBlockSize = 1 << 26
26 concurrentWriters = 4 // max goroutines writing to Keep in background and during flush()
29 // A CollectionFileSystem is a FileSystem that can be serialized as a
30 // manifest and stored as a collection.
31 type CollectionFileSystem interface {
34 // Flush all file data to Keep and return a snapshot of the
35 // filesystem suitable for saving as (Collection)ManifestText.
36 // Prefix (normally ".") is a top level directory, effectively
37 // prepended to all paths in the returned manifest.
38 MarshalManifest(prefix string) (string, error)
40 // Total data bytes in all files.
44 type collectionFileSystem struct {
48 storageClasses []string
51 // FileSystem returns a CollectionFileSystem for the collection.
52 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
53 modTime := c.ModifiedAt
57 fs := &collectionFileSystem{
59 storageClasses: c.StorageClassesDesired,
60 fileSystem: fileSystem{
61 fsBackend: keepBackend{apiClient: client, keepClient: kc},
62 thr: newThrottle(concurrentWriters),
65 if r := c.ReplicationDesired; r != nil {
73 mode: os.ModeDir | 0755,
76 inodes: make(map[string]inode),
79 root.SetParent(root, ".")
80 if err := root.loadManifest(c.ManifestText); err != nil {
83 backdateTree(root, modTime)
88 func backdateTree(n inode, modTime time.Time) {
89 switch n := n.(type) {
91 n.fileinfo.modTime = modTime
93 n.fileinfo.modTime = modTime
94 for _, n := range n.inodes {
95 backdateTree(n, modTime)
100 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
101 if name == "" || name == "." || name == ".." {
102 return nil, ErrInvalidArgument
110 mode: perm | os.ModeDir,
113 inodes: make(map[string]inode),
121 mode: perm & ^os.ModeDir,
127 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
128 return fs.rootnode().Child(name, replace)
131 func (fs *collectionFileSystem) FS() FileSystem {
135 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
136 return fs.rootnode().FileInfo()
139 func (fs *collectionFileSystem) IsDir() bool {
143 func (fs *collectionFileSystem) Lock() {
147 func (fs *collectionFileSystem) Unlock() {
148 fs.rootnode().Unlock()
151 func (fs *collectionFileSystem) RLock() {
152 fs.rootnode().RLock()
155 func (fs *collectionFileSystem) RUnlock() {
156 fs.rootnode().RUnlock()
159 func (fs *collectionFileSystem) Parent() inode {
160 return fs.rootnode().Parent()
163 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
164 return 0, ptr, ErrInvalidOperation
167 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
168 return 0, ptr, ErrInvalidOperation
171 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
172 return fs.rootnode().Readdir()
175 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
176 fs.rootnode().SetParent(parent, name)
179 func (fs *collectionFileSystem) Truncate(int64) error {
180 return ErrInvalidOperation
183 func (fs *collectionFileSystem) Sync() error {
187 txt, err := fs.MarshalManifest(".")
189 return fmt.Errorf("sync failed: %s", err)
195 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
196 "collection": map[string]string{
197 "manifest_text": coll.ManifestText,
199 "select": []string{"uuid"},
202 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
207 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
208 node, err := rlookup(fs.fileSystem.root, path)
212 dn, ok := node.(*dirnode)
214 return ErrNotADirectory
218 names := dn.sortedNames()
220 // Caller only wants to flush the specified dir,
221 // non-recursively. Drop subdirs from the list of
223 var filenames []string
224 for _, name := range names {
225 if _, ok := dn.inodes[name].(*filenode); ok {
226 filenames = append(filenames, name)
231 for _, name := range names {
232 child := dn.inodes[name]
236 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
239 func (fs *collectionFileSystem) MemorySize() int64 {
240 fs.fileSystem.root.Lock()
241 defer fs.fileSystem.root.Unlock()
242 return fs.fileSystem.root.(*dirnode).MemorySize()
245 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
246 fs.fileSystem.root.Lock()
247 defer fs.fileSystem.root.Unlock()
248 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
251 func (fs *collectionFileSystem) Size() int64 {
252 return fs.fileSystem.root.(*dirnode).TreeSize()
255 // filenodePtr is an offset into a file that is (usually) efficient to
256 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
258 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
259 // corresponds to file offset filenodePtr.off. Otherwise, it is
260 // necessary to reexamine len(filenode.segments[0]) etc. to find the
261 // correct segment and offset.
262 type filenodePtr struct {
269 // seek returns a ptr that is consistent with both startPtr.off and
270 // the current state of fn. The caller must already hold fn.RLock() or
273 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
278 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
280 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
281 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
284 // meaningless anyway
286 } else if ptr.off >= fn.fileinfo.size {
287 ptr.segmentIdx = len(fn.segments)
289 ptr.repacked = fn.repacked
291 } else if ptr.repacked == fn.repacked {
292 // segmentIdx and segmentOff accurately reflect
293 // ptr.off, but might have fallen off the end of a
295 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
302 ptr.repacked = fn.repacked
304 if ptr.off >= fn.fileinfo.size {
305 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
308 // Recompute segmentIdx and segmentOff. We have already
309 // established fn.fileinfo.size > ptr.off >= 0, so we don't
310 // have to deal with edge cases here.
312 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
313 // This would panic (index out of range) if
314 // fn.fileinfo.size were larger than
315 // sum(fn.segments[i].Len()) -- but that can't happen
316 // because we have ensured fn.fileinfo.size is always
318 segLen := int64(fn.segments[ptr.segmentIdx].Len())
319 if off+segLen > ptr.off {
320 ptr.segmentOff = int(ptr.off - off)
328 // filenode implements inode.
329 type filenode struct {
331 fs *collectionFileSystem
334 // number of times `segments` has changed in a
335 // way that might invalidate a filenodePtr
337 memsize int64 // bytes in memSegments
342 // caller must have lock
343 func (fn *filenode) appendSegment(e segment) {
344 fn.segments = append(fn.segments, e)
345 fn.fileinfo.size += int64(e.Len())
348 func (fn *filenode) SetParent(p inode, name string) {
352 fn.fileinfo.name = name
355 func (fn *filenode) Parent() inode {
361 func (fn *filenode) FS() FileSystem {
365 // Read reads file data from a single segment, starting at startPtr,
366 // into p. startPtr is assumed not to be up-to-date. Caller must have
368 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
369 ptr = fn.seek(startPtr)
371 err = ErrNegativeOffset
374 if ptr.segmentIdx >= len(fn.segments) {
378 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
382 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
385 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
393 func (fn *filenode) Size() int64 {
396 return fn.fileinfo.Size()
399 func (fn *filenode) FileInfo() os.FileInfo {
405 func (fn *filenode) Truncate(size int64) error {
408 return fn.truncate(size)
411 func (fn *filenode) truncate(size int64) error {
412 if size == fn.fileinfo.size {
416 if size < fn.fileinfo.size {
417 ptr := fn.seek(filenodePtr{off: size})
418 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
419 if seg, ok := fn.segments[i].(*memSegment); ok {
420 fn.memsize -= int64(seg.Len())
423 if ptr.segmentOff == 0 {
424 fn.segments = fn.segments[:ptr.segmentIdx]
426 fn.segments = fn.segments[:ptr.segmentIdx+1]
427 switch seg := fn.segments[ptr.segmentIdx].(type) {
429 seg.Truncate(ptr.segmentOff)
430 fn.memsize += int64(seg.Len())
432 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
435 fn.fileinfo.size = size
438 for size > fn.fileinfo.size {
439 grow := size - fn.fileinfo.size
442 if len(fn.segments) == 0 {
444 fn.segments = append(fn.segments, seg)
445 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
447 fn.segments = append(fn.segments, seg)
449 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
452 seg.Truncate(seg.Len() + int(grow))
453 fn.fileinfo.size += grow
459 // Write writes data from p to the file, starting at startPtr,
460 // extending the file size if necessary. Caller must have Lock.
461 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
462 if startPtr.off > fn.fileinfo.size {
463 if err = fn.truncate(startPtr.off); err != nil {
464 return 0, startPtr, err
467 ptr = fn.seek(startPtr)
469 err = ErrNegativeOffset
472 for len(p) > 0 && err == nil {
474 if len(cando) > maxBlockSize {
475 cando = cando[:maxBlockSize]
477 // Rearrange/grow fn.segments (and shrink cando if
478 // needed) such that cando can be copied to
479 // fn.segments[ptr.segmentIdx] at offset
481 cur := ptr.segmentIdx
482 prev := ptr.segmentIdx - 1
484 if cur < len(fn.segments) {
485 _, curWritable = fn.segments[cur].(*memSegment)
487 var prevAppendable bool
488 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
489 _, prevAppendable = fn.segments[prev].(*memSegment)
491 if ptr.segmentOff > 0 && !curWritable {
492 // Split a non-writable block.
493 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
494 // Truncate cur, and insert a new
497 fn.segments = append(fn.segments, nil)
498 copy(fn.segments[cur+1:], fn.segments[cur:])
500 // Split cur into two copies, truncate
501 // the one on the left, shift the one
502 // on the right, and insert a new
503 // segment between them.
504 fn.segments = append(fn.segments, nil, nil)
505 copy(fn.segments[cur+2:], fn.segments[cur:])
506 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
511 seg.Truncate(len(cando))
512 fn.memsize += int64(len(cando))
513 fn.segments[cur] = seg
514 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
519 } else if curWritable {
520 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
525 // Shrink cando if needed to fit in
527 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
528 cando = cando[:cangrow]
532 if cur == len(fn.segments) {
533 // ptr is at EOF, filesize is changing.
534 fn.fileinfo.size += int64(len(cando))
535 } else if el := fn.segments[cur].Len(); el <= len(cando) {
536 // cando is long enough that we won't
537 // need cur any more. shrink cando to
538 // be exactly as long as cur
539 // (otherwise we'd accidentally shift
540 // the effective position of all
541 // segments after cur).
543 copy(fn.segments[cur:], fn.segments[cur+1:])
544 fn.segments = fn.segments[:len(fn.segments)-1]
546 // shrink cur by the same #bytes we're growing prev
547 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
553 ptr.segmentOff = fn.segments[prev].Len()
554 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
555 fn.memsize += int64(len(cando))
559 // Insert a segment between prev and
560 // cur, and advance prev/cur.
561 fn.segments = append(fn.segments, nil)
562 if cur < len(fn.segments) {
563 copy(fn.segments[cur+1:], fn.segments[cur:])
567 // appending a new segment does
568 // not invalidate any ptrs
571 seg.Truncate(len(cando))
572 fn.memsize += int64(len(cando))
573 fn.segments[cur] = seg
577 // Finally we can copy bytes from cando to the current segment.
578 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
582 ptr.off += int64(len(cando))
583 ptr.segmentOff += len(cando)
584 if ptr.segmentOff >= maxBlockSize {
585 fn.pruneMemSegments()
587 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
592 fn.fileinfo.modTime = time.Now()
597 // Write some data out to disk to reduce memory use. Caller must have
599 func (fn *filenode) pruneMemSegments() {
600 // TODO: share code with (*dirnode)flush()
601 // TODO: pack/flush small blocks too, when fragmented
602 for idx, seg := range fn.segments {
603 seg, ok := seg.(*memSegment)
604 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
607 // Setting seg.flushing guarantees seg.buf will not be
608 // modified in place: WriteAt and Truncate will
609 // allocate a new buf instead, if necessary.
610 idx, buf := idx, seg.buf
611 done := make(chan struct{})
613 // If lots of background writes are already in
614 // progress, block here until one finishes, rather
615 // than pile up an unlimited number of buffered writes
616 // and network flush operations.
617 fn.fs.throttle().Acquire()
620 resp, err := fn.FS().BlockWrite(context.Background(), BlockWriteOptions{
622 Replicas: fn.fs.replicas,
623 StorageClasses: fn.fs.storageClasses,
625 fn.fs.throttle().Release()
628 if seg.flushing != done {
629 // A new seg.buf has been allocated.
633 // TODO: stall (or return errors from)
634 // subsequent writes until flushing
635 // starts to succeed.
638 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
639 // Segment has been dropped/moved/resized.
642 fn.memsize -= int64(len(buf))
643 fn.segments[idx] = storedSegment{
645 locator: resp.Locator,
654 // Block until all pending pruneMemSegments/flush work is
655 // finished. Caller must NOT have lock.
656 func (fn *filenode) waitPrune() {
657 var pending []<-chan struct{}
659 for _, seg := range fn.segments {
660 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
661 pending = append(pending, seg.flushing)
665 for _, p := range pending {
670 type dirnode struct {
671 fs *collectionFileSystem
675 func (dn *dirnode) FS() FileSystem {
679 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
680 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
681 gn := &getternode{Getter: func() ([]byte, error) {
684 coll.ManifestText, err = dn.fs.MarshalManifest(".")
688 coll.UUID = dn.fs.uuid
689 data, err := json.Marshal(&coll)
691 data = append(data, '\n')
695 gn.SetParent(dn, name)
698 return dn.treenode.Child(name, replace)
701 type fnSegmentRef struct {
706 // commitBlock concatenates the data from the given filenode segments
707 // (which must be *memSegments), writes the data out to Keep as a
708 // single block, and replaces the filenodes' *memSegments with
709 // storedSegments that reference the relevant portions of the new
712 // bufsize is the total data size in refs. It is used to preallocate
713 // the correct amount of memory when len(refs)>1.
715 // If sync is false, commitBlock returns right away, after starting a
716 // goroutine to do the writes, reacquire the filenodes' locks, and
717 // swap out the *memSegments. Some filenodes' segments might get
718 // modified/rearranged in the meantime, in which case commitBlock
719 // won't replace them.
721 // Caller must have write lock.
722 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
726 if err := ctx.Err(); err != nil {
729 done := make(chan struct{})
731 segs := make([]*memSegment, 0, len(refs))
732 offsets := make([]int, 0, len(refs)) // location of segment's data within block
733 for _, ref := range refs {
734 seg := ref.fn.segments[ref.idx].(*memSegment)
735 if !sync && seg.flushingUnfinished() {
736 // Let the other flushing goroutine finish. If
737 // it fails, we'll try again next time.
741 // In sync mode, we proceed regardless of
742 // whether another flush is in progress: It
743 // can't finish before we do, because we hold
744 // fn's lock until we finish our own writes.
746 offsets = append(offsets, len(block))
749 } else if block == nil {
750 block = append(make([]byte, 0, bufsize), seg.buf...)
752 block = append(block, seg.buf...)
754 segs = append(segs, seg)
756 blocksize := len(block)
757 dn.fs.throttle().Acquire()
758 errs := make(chan error, 1)
762 resp, err := dn.fs.BlockWrite(context.Background(), BlockWriteOptions{
764 Replicas: dn.fs.replicas,
765 StorageClasses: dn.fs.storageClasses,
767 dn.fs.throttle().Release()
772 for idx, ref := range refs {
775 // In async mode, fn's lock was
776 // released while we were waiting for
777 // PutB(); lots of things might have
779 if len(ref.fn.segments) <= ref.idx {
780 // file segments have
781 // rearranged or changed in
785 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
786 // segment has been replaced
789 } else if seg.flushing != done {
790 // seg.buf has been replaced
795 data := ref.fn.segments[ref.idx].(*memSegment).buf
796 ref.fn.segments[ref.idx] = storedSegment{
798 locator: resp.Locator,
800 offset: offsets[idx],
803 // atomic is needed here despite caller having
804 // lock: caller might be running concurrent
805 // commitBlock() goroutines using the same
806 // lock, writing different segments from the
808 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
820 type flushOpts struct {
825 // flush in-memory data and remote-cluster block references (for the
826 // children with the given names, which must be children of dn) to
827 // local-cluster persistent storage.
829 // Caller must have write lock on dn and the named children.
831 // If any children are dirs, they will be flushed recursively.
832 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
833 cg := newContextGroup(ctx)
836 goCommit := func(refs []fnSegmentRef, bufsize int) {
838 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
842 var pending []fnSegmentRef
843 var pendingLen int = 0
844 localLocator := map[string]string{}
845 for _, name := range names {
846 switch node := dn.inodes[name].(type) {
848 grandchildNames := node.sortedNames()
849 for _, grandchildName := range grandchildNames {
850 grandchild := node.inodes[grandchildName]
852 defer grandchild.Unlock()
854 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
856 for idx, seg := range node.segments {
857 switch seg := seg.(type) {
859 loc, ok := localLocator[seg.locator]
862 loc, err = dn.fs.LocalLocator(seg.locator)
866 localLocator[seg.locator] = loc
869 node.segments[idx] = seg
871 if seg.Len() > maxBlockSize/2 {
872 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
875 if pendingLen+seg.Len() > maxBlockSize {
876 goCommit(pending, pendingLen)
880 pending = append(pending, fnSegmentRef{node, idx})
881 pendingLen += seg.Len()
883 panic(fmt.Sprintf("can't sync segment type %T", seg))
888 if opts.shortBlocks {
889 goCommit(pending, pendingLen)
894 // caller must have write lock.
895 func (dn *dirnode) MemorySize() (size int64) {
896 for _, name := range dn.sortedNames() {
897 node := dn.inodes[name]
900 switch node := node.(type) {
902 size += node.MemorySize()
904 for _, seg := range node.segments {
905 switch seg := seg.(type) {
907 size += int64(seg.Len())
915 // caller must have write lock.
916 func (dn *dirnode) sortedNames() []string {
917 names := make([]string, 0, len(dn.inodes))
918 for name := range dn.inodes {
919 names = append(names, name)
925 // caller must have write lock.
926 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
927 cg := newContextGroup(ctx)
930 if len(dn.inodes) == 0 {
934 // Express the existence of an empty directory by
935 // adding an empty file named `\056`, which (unlike
936 // the more obvious spelling `.`) is accepted by the
937 // API's manifest validator.
938 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
941 names := dn.sortedNames()
943 // Wait for children to finish any pending write operations
944 // before locking them.
945 for _, name := range names {
946 node := dn.inodes[name]
947 if fn, ok := node.(*filenode); ok {
952 var dirnames []string
953 var filenames []string
954 for _, name := range names {
955 node := dn.inodes[name]
958 switch node := node.(type) {
960 dirnames = append(dirnames, name)
962 filenames = append(filenames, name)
964 panic(fmt.Sprintf("can't marshal inode type %T", node))
968 subdirs := make([]string, len(dirnames))
970 for i, name := range dirnames {
973 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
981 type filepart struct {
987 var fileparts []filepart
989 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
992 for _, name := range filenames {
993 node := dn.inodes[name].(*filenode)
994 if len(node.segments) == 0 {
995 fileparts = append(fileparts, filepart{name: name})
998 for _, seg := range node.segments {
999 switch seg := seg.(type) {
1001 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1002 streamLen -= int64(seg.size)
1004 blocks = append(blocks, seg.locator)
1008 offset: streamLen + int64(seg.offset),
1009 length: int64(seg.length),
1011 if prev := len(fileparts) - 1; prev >= 0 &&
1012 fileparts[prev].name == name &&
1013 fileparts[prev].offset+fileparts[prev].length == next.offset {
1014 fileparts[prev].length += next.length
1016 fileparts = append(fileparts, next)
1018 streamLen += int64(seg.size)
1020 // This can't happen: we
1021 // haven't unlocked since
1022 // calling flush(sync=true).
1023 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1027 var filetokens []string
1028 for _, s := range fileparts {
1029 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1031 if len(filetokens) == 0 {
1033 } else if len(blocks) == 0 {
1034 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1036 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1040 return rootdir + strings.Join(subdirs, ""), err
1043 func (dn *dirnode) loadManifest(txt string) error {
1044 streams := bytes.Split([]byte(txt), []byte{'\n'})
1045 if len(streams[len(streams)-1]) != 0 {
1046 return fmt.Errorf("line %d: no trailing newline", len(streams))
1048 streams = streams[:len(streams)-1]
1049 segments := []storedSegment{}
1050 // To reduce allocs, we reuse a single "pathparts" slice
1051 // (pre-split on "/" separators) for the duration of this
1053 var pathparts []string
1054 // To reduce allocs, we reuse a single "toks" slice of 3 byte
1056 var toks = make([][]byte, 3)
1057 // Similar to bytes.SplitN(token, []byte{c}, 3), but splits
1058 // into the toks slice rather than allocating a new one, and
1059 // returns the number of toks (1, 2, or 3).
1060 splitToToks := func(src []byte, c rune) int {
1061 c1 := bytes.IndexRune(src, c)
1066 toks[0], src = src[:c1], src[c1+1:]
1067 c2 := bytes.IndexRune(src, c)
1072 toks[1], toks[2] = src[:c2], src[c2+1:]
1075 for i, stream := range streams {
1077 var anyFileTokens bool
1080 segments = segments[:0]
1083 for i, token := range bytes.Split(stream, []byte{' '}) {
1085 pathparts = strings.Split(manifestUnescape(string(token)), "/")
1086 streamparts = len(pathparts)
1089 if !bytes.ContainsRune(token, ':') {
1091 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1093 if splitToToks(token, '+') < 2 {
1094 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1096 length, err := strconv.ParseInt(string(toks[1]), 10, 32)
1097 if err != nil || length < 0 {
1098 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1100 segments = append(segments, storedSegment{
1101 locator: string(token),
1104 length: int(length),
1107 } else if len(segments) == 0 {
1108 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1110 if splitToToks(token, ':') != 3 {
1111 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1113 anyFileTokens = true
1115 offset, err := strconv.ParseInt(string(toks[0]), 10, 64)
1116 if err != nil || offset < 0 {
1117 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1119 length, err := strconv.ParseInt(string(toks[1]), 10, 64)
1120 if err != nil || length < 0 {
1121 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1123 if !bytes.ContainsAny(toks[2], `\/`) {
1124 // optimization for a common case
1125 pathparts = append(pathparts[:streamparts], string(toks[2]))
1127 pathparts = append(pathparts[:streamparts], strings.Split(manifestUnescape(string(toks[2])), "/")...)
1129 fnode, err := dn.createFileAndParents(pathparts)
1130 if fnode == nil && err == nil && length == 0 {
1131 // Special case: an empty file used as
1132 // a marker to preserve an otherwise
1133 // empty directory in a manifest.
1136 if err != nil || (fnode == nil && length != 0) {
1137 return fmt.Errorf("line %d: cannot use name %q with length %d: %s", lineno, toks[2], length, err)
1139 // Map the stream offset/range coordinates to
1140 // block/offset/range coordinates and add
1141 // corresponding storedSegments to the filenode
1143 // Can't continue where we left off.
1144 // TODO: binary search instead of
1145 // rewinding all the way (but this
1146 // situation might be rare anyway)
1149 for ; segIdx < len(segments); segIdx++ {
1150 seg := segments[segIdx]
1151 next := pos + int64(seg.Len())
1152 if next <= offset || seg.Len() == 0 {
1156 if pos >= offset+length {
1161 blkOff = int(offset - pos)
1163 blkLen := seg.Len() - blkOff
1164 if pos+int64(blkOff+blkLen) > offset+length {
1165 blkLen = int(offset + length - pos - int64(blkOff))
1167 fnode.appendSegment(storedSegment{
1169 locator: seg.locator,
1174 if next > offset+length {
1180 if segIdx == len(segments) && pos < offset+length {
1181 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1185 return fmt.Errorf("line %d: no file segments", lineno)
1186 } else if len(segments) == 0 {
1187 return fmt.Errorf("line %d: no locators", lineno)
1188 } else if streamparts == 0 {
1189 return fmt.Errorf("line %d: no stream name", lineno)
1195 // only safe to call from loadManifest -- no locking.
1197 // If path is a "parent directory exists" marker (the last path
1198 // component is "."), the returned values are both nil.
1200 // Newly added nodes have modtime==0. Caller is responsible for fixing
1201 // them with backdateTree.
1202 func (dn *dirnode) createFileAndParents(names []string) (fn *filenode, err error) {
1204 basename := names[len(names)-1]
1205 for _, name := range names[:len(names)-1] {
1211 // can't be sure parent will be a *dirnode
1212 return nil, ErrInvalidArgument
1214 node = node.Parent()
1218 unlock := node.Unlock
1219 node, err = node.Child(name, func(child inode) (inode, error) {
1221 // note modtime will be fixed later in backdateTree()
1222 child, err := node.FS().newNode(name, 0755|os.ModeDir, time.Time{})
1226 child.SetParent(node, name)
1228 } else if !child.IsDir() {
1229 return child, ErrFileExists
1239 if basename == "." {
1241 } else if !permittedName(basename) {
1242 err = fmt.Errorf("invalid file part %q in path %q", basename, names)
1247 _, err = node.Child(basename, func(child inode) (inode, error) {
1248 switch child := child.(type) {
1250 child, err = node.FS().newNode(basename, 0755, time.Time{})
1254 child.SetParent(node, basename)
1255 fn = child.(*filenode)
1261 return child, ErrIsDirectory
1263 return child, ErrInvalidArgument
1269 func (dn *dirnode) TreeSize() (bytes int64) {
1272 for _, i := range dn.inodes {
1273 switch i := i.(type) {
1277 bytes += i.TreeSize()
1283 type segment interface {
1286 // Return a new segment with a subsection of the data from this
1287 // one. length<0 means length=Len()-off.
1288 Slice(off int, length int) segment
1291 type memSegment struct {
1293 // If flushing is not nil and not ready/closed, then a) buf is
1294 // being shared by a pruneMemSegments goroutine, and must be
1295 // copied on write; and b) the flushing channel will close
1296 // when the goroutine finishes, whether it succeeds or not.
1297 flushing <-chan struct{}
1300 func (me *memSegment) flushingUnfinished() bool {
1301 if me.flushing == nil {
1313 func (me *memSegment) Len() int {
1317 func (me *memSegment) Slice(off, length int) segment {
1319 length = len(me.buf) - off
1321 buf := make([]byte, length)
1322 copy(buf, me.buf[off:])
1323 return &memSegment{buf: buf}
1326 func (me *memSegment) Truncate(n int) {
1327 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1330 newsize = newsize << 2
1332 newbuf := make([]byte, n, newsize)
1333 copy(newbuf, me.buf)
1334 me.buf, me.flushing = newbuf, nil
1336 // reclaim existing capacity, and zero reclaimed part
1337 oldlen := len(me.buf)
1339 for i := oldlen; i < n; i++ {
1345 func (me *memSegment) WriteAt(p []byte, off int) {
1346 if off+len(p) > len(me.buf) {
1347 panic("overflowed segment")
1349 if me.flushing != nil {
1350 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1352 copy(me.buf[off:], p)
1355 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1356 if off > int64(me.Len()) {
1360 n = copy(p, me.buf[int(off):])
1367 type storedSegment struct {
1370 size int // size of stored block (also encoded in locator)
1371 offset int // position of segment within the stored block
1372 length int // bytes in this segment (offset + length <= size)
1375 func (se storedSegment) Len() int {
1379 func (se storedSegment) Slice(n, size int) segment {
1382 if size >= 0 && se.length > size {
1388 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1389 if off > int64(se.length) {
1392 maxlen := se.length - int(off)
1393 if len(p) > maxlen {
1395 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1401 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1404 func canonicalName(name string) string {
1405 name = path.Clean("/" + name)
1406 if name == "/" || name == "./" {
1408 } else if strings.HasPrefix(name, "/") {
1414 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1416 func manifestUnescapeFunc(seq string) string {
1420 i, err := strconv.ParseUint(seq[1:], 8, 8)
1422 // Invalid escape sequence: can't unescape.
1425 return string([]byte{byte(i)})
1428 func manifestUnescape(s string) string {
1429 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1432 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1434 func manifestEscapeFunc(seq string) string {
1435 return fmt.Sprintf("\\%03o", byte(seq[0]))
1438 func manifestEscape(s string) string {
1439 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)