1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
24 maxBlockSize = 1 << 26
25 concurrentWriters = 4 // max goroutines writing to Keep in background and during flush()
28 // A CollectionFileSystem is a FileSystem that can be serialized as a
29 // manifest and stored as a collection.
30 type CollectionFileSystem interface {
33 // Flush all file data to Keep and return a snapshot of the
34 // filesystem suitable for saving as (Collection)ManifestText.
35 // Prefix (normally ".") is a top level directory, effectively
36 // prepended to all paths in the returned manifest.
37 MarshalManifest(prefix string) (string, error)
39 // Total data bytes in all files.
43 type collectionFileSystem struct {
47 storageClasses []string
50 // FileSystem returns a CollectionFileSystem for the collection.
51 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
52 modTime := c.ModifiedAt
56 fs := &collectionFileSystem{
58 storageClasses: c.StorageClassesDesired,
59 fileSystem: fileSystem{
60 fsBackend: keepBackend{apiClient: client, keepClient: kc},
61 thr: newThrottle(concurrentWriters),
64 if r := c.ReplicationDesired; r != nil {
72 mode: os.ModeDir | 0755,
75 inodes: make(map[string]inode),
78 root.SetParent(root, ".")
79 if err := root.loadManifest(c.ManifestText); err != nil {
82 backdateTree(root, modTime)
87 func backdateTree(n inode, modTime time.Time) {
88 switch n := n.(type) {
90 n.fileinfo.modTime = modTime
92 n.fileinfo.modTime = modTime
93 for _, n := range n.inodes {
94 backdateTree(n, modTime)
99 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
100 if name == "" || name == "." || name == ".." {
101 return nil, ErrInvalidArgument
109 mode: perm | os.ModeDir,
112 inodes: make(map[string]inode),
120 mode: perm & ^os.ModeDir,
126 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
127 return fs.rootnode().Child(name, replace)
130 func (fs *collectionFileSystem) FS() FileSystem {
134 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
135 return fs.rootnode().FileInfo()
138 func (fs *collectionFileSystem) IsDir() bool {
142 func (fs *collectionFileSystem) Lock() {
146 func (fs *collectionFileSystem) Unlock() {
147 fs.rootnode().Unlock()
150 func (fs *collectionFileSystem) RLock() {
151 fs.rootnode().RLock()
154 func (fs *collectionFileSystem) RUnlock() {
155 fs.rootnode().RUnlock()
158 func (fs *collectionFileSystem) Parent() inode {
159 return fs.rootnode().Parent()
162 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
163 return 0, ptr, ErrInvalidOperation
166 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
167 return 0, ptr, ErrInvalidOperation
170 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
171 return fs.rootnode().Readdir()
174 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
175 fs.rootnode().SetParent(parent, name)
178 func (fs *collectionFileSystem) Truncate(int64) error {
179 return ErrInvalidOperation
182 func (fs *collectionFileSystem) Sync() error {
186 txt, err := fs.MarshalManifest(".")
188 return fmt.Errorf("sync failed: %s", err)
194 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
195 "collection": map[string]string{
196 "manifest_text": coll.ManifestText,
198 "select": []string{"uuid"},
201 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
206 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
207 node, err := rlookup(fs.fileSystem.root, path)
211 dn, ok := node.(*dirnode)
213 return ErrNotADirectory
217 names := dn.sortedNames()
219 // Caller only wants to flush the specified dir,
220 // non-recursively. Drop subdirs from the list of
222 var filenames []string
223 for _, name := range names {
224 if _, ok := dn.inodes[name].(*filenode); ok {
225 filenames = append(filenames, name)
230 for _, name := range names {
231 child := dn.inodes[name]
235 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
238 func (fs *collectionFileSystem) MemorySize() int64 {
239 fs.fileSystem.root.Lock()
240 defer fs.fileSystem.root.Unlock()
241 return fs.fileSystem.root.(*dirnode).MemorySize()
244 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
245 fs.fileSystem.root.Lock()
246 defer fs.fileSystem.root.Unlock()
247 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
250 func (fs *collectionFileSystem) Size() int64 {
251 return fs.fileSystem.root.(*dirnode).TreeSize()
254 // filenodePtr is an offset into a file that is (usually) efficient to
255 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
257 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
258 // corresponds to file offset filenodePtr.off. Otherwise, it is
259 // necessary to reexamine len(filenode.segments[0]) etc. to find the
260 // correct segment and offset.
261 type filenodePtr struct {
268 // seek returns a ptr that is consistent with both startPtr.off and
269 // the current state of fn. The caller must already hold fn.RLock() or
272 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
277 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
279 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
280 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
283 // meaningless anyway
285 } else if ptr.off >= fn.fileinfo.size {
286 ptr.segmentIdx = len(fn.segments)
288 ptr.repacked = fn.repacked
290 } else if ptr.repacked == fn.repacked {
291 // segmentIdx and segmentOff accurately reflect
292 // ptr.off, but might have fallen off the end of a
294 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
301 ptr.repacked = fn.repacked
303 if ptr.off >= fn.fileinfo.size {
304 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
307 // Recompute segmentIdx and segmentOff. We have already
308 // established fn.fileinfo.size > ptr.off >= 0, so we don't
309 // have to deal with edge cases here.
311 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
312 // This would panic (index out of range) if
313 // fn.fileinfo.size were larger than
314 // sum(fn.segments[i].Len()) -- but that can't happen
315 // because we have ensured fn.fileinfo.size is always
317 segLen := int64(fn.segments[ptr.segmentIdx].Len())
318 if off+segLen > ptr.off {
319 ptr.segmentOff = int(ptr.off - off)
327 // filenode implements inode.
328 type filenode struct {
330 fs *collectionFileSystem
333 // number of times `segments` has changed in a
334 // way that might invalidate a filenodePtr
336 memsize int64 // bytes in memSegments
341 // caller must have lock
342 func (fn *filenode) appendSegment(e segment) {
343 fn.segments = append(fn.segments, e)
344 fn.fileinfo.size += int64(e.Len())
347 func (fn *filenode) SetParent(p inode, name string) {
351 fn.fileinfo.name = name
354 func (fn *filenode) Parent() inode {
360 func (fn *filenode) FS() FileSystem {
364 // Read reads file data from a single segment, starting at startPtr,
365 // into p. startPtr is assumed not to be up-to-date. Caller must have
367 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
368 ptr = fn.seek(startPtr)
370 err = ErrNegativeOffset
373 if ptr.segmentIdx >= len(fn.segments) {
377 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
381 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
384 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
392 func (fn *filenode) Size() int64 {
395 return fn.fileinfo.Size()
398 func (fn *filenode) FileInfo() os.FileInfo {
404 func (fn *filenode) Truncate(size int64) error {
407 return fn.truncate(size)
410 func (fn *filenode) truncate(size int64) error {
411 if size == fn.fileinfo.size {
415 if size < fn.fileinfo.size {
416 ptr := fn.seek(filenodePtr{off: size})
417 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
418 if seg, ok := fn.segments[i].(*memSegment); ok {
419 fn.memsize -= int64(seg.Len())
422 if ptr.segmentOff == 0 {
423 fn.segments = fn.segments[:ptr.segmentIdx]
425 fn.segments = fn.segments[:ptr.segmentIdx+1]
426 switch seg := fn.segments[ptr.segmentIdx].(type) {
428 seg.Truncate(ptr.segmentOff)
429 fn.memsize += int64(seg.Len())
431 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
434 fn.fileinfo.size = size
437 for size > fn.fileinfo.size {
438 grow := size - fn.fileinfo.size
441 if len(fn.segments) == 0 {
443 fn.segments = append(fn.segments, seg)
444 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
446 fn.segments = append(fn.segments, seg)
448 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
451 seg.Truncate(seg.Len() + int(grow))
452 fn.fileinfo.size += grow
458 // Write writes data from p to the file, starting at startPtr,
459 // extending the file size if necessary. Caller must have Lock.
460 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
461 if startPtr.off > fn.fileinfo.size {
462 if err = fn.truncate(startPtr.off); err != nil {
463 return 0, startPtr, err
466 ptr = fn.seek(startPtr)
468 err = ErrNegativeOffset
471 for len(p) > 0 && err == nil {
473 if len(cando) > maxBlockSize {
474 cando = cando[:maxBlockSize]
476 // Rearrange/grow fn.segments (and shrink cando if
477 // needed) such that cando can be copied to
478 // fn.segments[ptr.segmentIdx] at offset
480 cur := ptr.segmentIdx
481 prev := ptr.segmentIdx - 1
483 if cur < len(fn.segments) {
484 _, curWritable = fn.segments[cur].(*memSegment)
486 var prevAppendable bool
487 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
488 _, prevAppendable = fn.segments[prev].(*memSegment)
490 if ptr.segmentOff > 0 && !curWritable {
491 // Split a non-writable block.
492 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
493 // Truncate cur, and insert a new
496 fn.segments = append(fn.segments, nil)
497 copy(fn.segments[cur+1:], fn.segments[cur:])
499 // Split cur into two copies, truncate
500 // the one on the left, shift the one
501 // on the right, and insert a new
502 // segment between them.
503 fn.segments = append(fn.segments, nil, nil)
504 copy(fn.segments[cur+2:], fn.segments[cur:])
505 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
510 seg.Truncate(len(cando))
511 fn.memsize += int64(len(cando))
512 fn.segments[cur] = seg
513 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
518 } else if curWritable {
519 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
524 // Shrink cando if needed to fit in
526 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
527 cando = cando[:cangrow]
531 if cur == len(fn.segments) {
532 // ptr is at EOF, filesize is changing.
533 fn.fileinfo.size += int64(len(cando))
534 } else if el := fn.segments[cur].Len(); el <= len(cando) {
535 // cando is long enough that we won't
536 // need cur any more. shrink cando to
537 // be exactly as long as cur
538 // (otherwise we'd accidentally shift
539 // the effective position of all
540 // segments after cur).
542 copy(fn.segments[cur:], fn.segments[cur+1:])
543 fn.segments = fn.segments[:len(fn.segments)-1]
545 // shrink cur by the same #bytes we're growing prev
546 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
552 ptr.segmentOff = fn.segments[prev].Len()
553 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
554 fn.memsize += int64(len(cando))
558 // Insert a segment between prev and
559 // cur, and advance prev/cur.
560 fn.segments = append(fn.segments, nil)
561 if cur < len(fn.segments) {
562 copy(fn.segments[cur+1:], fn.segments[cur:])
566 // appending a new segment does
567 // not invalidate any ptrs
570 seg.Truncate(len(cando))
571 fn.memsize += int64(len(cando))
572 fn.segments[cur] = seg
576 // Finally we can copy bytes from cando to the current segment.
577 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
581 ptr.off += int64(len(cando))
582 ptr.segmentOff += len(cando)
583 if ptr.segmentOff >= maxBlockSize {
584 fn.pruneMemSegments()
586 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
591 fn.fileinfo.modTime = time.Now()
596 // Write some data out to disk to reduce memory use. Caller must have
598 func (fn *filenode) pruneMemSegments() {
599 // TODO: share code with (*dirnode)flush()
600 // TODO: pack/flush small blocks too, when fragmented
601 for idx, seg := range fn.segments {
602 seg, ok := seg.(*memSegment)
603 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
606 // Setting seg.flushing guarantees seg.buf will not be
607 // modified in place: WriteAt and Truncate will
608 // allocate a new buf instead, if necessary.
609 idx, buf := idx, seg.buf
610 done := make(chan struct{})
612 // If lots of background writes are already in
613 // progress, block here until one finishes, rather
614 // than pile up an unlimited number of buffered writes
615 // and network flush operations.
616 fn.fs.throttle().Acquire()
619 resp, err := fn.FS().BlockWrite(context.Background(), BlockWriteOptions{
621 Replicas: fn.fs.replicas,
622 StorageClasses: fn.fs.storageClasses,
624 fn.fs.throttle().Release()
627 if seg.flushing != done {
628 // A new seg.buf has been allocated.
632 // TODO: stall (or return errors from)
633 // subsequent writes until flushing
634 // starts to succeed.
637 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
638 // Segment has been dropped/moved/resized.
641 fn.memsize -= int64(len(buf))
642 fn.segments[idx] = storedSegment{
644 locator: resp.Locator,
653 // Block until all pending pruneMemSegments/flush work is
654 // finished. Caller must NOT have lock.
655 func (fn *filenode) waitPrune() {
656 var pending []<-chan struct{}
658 for _, seg := range fn.segments {
659 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
660 pending = append(pending, seg.flushing)
664 for _, p := range pending {
669 type dirnode struct {
670 fs *collectionFileSystem
674 func (dn *dirnode) FS() FileSystem {
678 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
679 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
680 gn := &getternode{Getter: func() ([]byte, error) {
683 coll.ManifestText, err = dn.fs.MarshalManifest(".")
687 coll.UUID = dn.fs.uuid
688 data, err := json.Marshal(&coll)
690 data = append(data, '\n')
694 gn.SetParent(dn, name)
697 return dn.treenode.Child(name, replace)
700 type fnSegmentRef struct {
705 // commitBlock concatenates the data from the given filenode segments
706 // (which must be *memSegments), writes the data out to Keep as a
707 // single block, and replaces the filenodes' *memSegments with
708 // storedSegments that reference the relevant portions of the new
711 // bufsize is the total data size in refs. It is used to preallocate
712 // the correct amount of memory when len(refs)>1.
714 // If sync is false, commitBlock returns right away, after starting a
715 // goroutine to do the writes, reacquire the filenodes' locks, and
716 // swap out the *memSegments. Some filenodes' segments might get
717 // modified/rearranged in the meantime, in which case commitBlock
718 // won't replace them.
720 // Caller must have write lock.
721 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
725 if err := ctx.Err(); err != nil {
728 done := make(chan struct{})
730 segs := make([]*memSegment, 0, len(refs))
731 offsets := make([]int, 0, len(refs)) // location of segment's data within block
732 for _, ref := range refs {
733 seg := ref.fn.segments[ref.idx].(*memSegment)
734 if !sync && seg.flushingUnfinished() {
735 // Let the other flushing goroutine finish. If
736 // it fails, we'll try again next time.
740 // In sync mode, we proceed regardless of
741 // whether another flush is in progress: It
742 // can't finish before we do, because we hold
743 // fn's lock until we finish our own writes.
745 offsets = append(offsets, len(block))
748 } else if block == nil {
749 block = append(make([]byte, 0, bufsize), seg.buf...)
751 block = append(block, seg.buf...)
753 segs = append(segs, seg)
755 blocksize := len(block)
756 dn.fs.throttle().Acquire()
757 errs := make(chan error, 1)
761 resp, err := dn.fs.BlockWrite(context.Background(), BlockWriteOptions{
763 Replicas: dn.fs.replicas,
764 StorageClasses: dn.fs.storageClasses,
766 dn.fs.throttle().Release()
771 for idx, ref := range refs {
774 // In async mode, fn's lock was
775 // released while we were waiting for
776 // PutB(); lots of things might have
778 if len(ref.fn.segments) <= ref.idx {
779 // file segments have
780 // rearranged or changed in
784 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
785 // segment has been replaced
788 } else if seg.flushing != done {
789 // seg.buf has been replaced
794 data := ref.fn.segments[ref.idx].(*memSegment).buf
795 ref.fn.segments[ref.idx] = storedSegment{
797 locator: resp.Locator,
799 offset: offsets[idx],
802 // atomic is needed here despite caller having
803 // lock: caller might be running concurrent
804 // commitBlock() goroutines using the same
805 // lock, writing different segments from the
807 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
819 type flushOpts struct {
824 // flush in-memory data and remote-cluster block references (for the
825 // children with the given names, which must be children of dn) to
826 // local-cluster persistent storage.
828 // Caller must have write lock on dn and the named children.
830 // If any children are dirs, they will be flushed recursively.
831 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
832 cg := newContextGroup(ctx)
835 goCommit := func(refs []fnSegmentRef, bufsize int) {
837 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
841 var pending []fnSegmentRef
842 var pendingLen int = 0
843 localLocator := map[string]string{}
844 for _, name := range names {
845 switch node := dn.inodes[name].(type) {
847 grandchildNames := node.sortedNames()
848 for _, grandchildName := range grandchildNames {
849 grandchild := node.inodes[grandchildName]
851 defer grandchild.Unlock()
853 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
855 for idx, seg := range node.segments {
856 switch seg := seg.(type) {
858 loc, ok := localLocator[seg.locator]
861 loc, err = dn.fs.LocalLocator(seg.locator)
865 localLocator[seg.locator] = loc
868 node.segments[idx] = seg
870 if seg.Len() > maxBlockSize/2 {
871 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
874 if pendingLen+seg.Len() > maxBlockSize {
875 goCommit(pending, pendingLen)
879 pending = append(pending, fnSegmentRef{node, idx})
880 pendingLen += seg.Len()
882 panic(fmt.Sprintf("can't sync segment type %T", seg))
887 if opts.shortBlocks {
888 goCommit(pending, pendingLen)
893 // caller must have write lock.
894 func (dn *dirnode) MemorySize() (size int64) {
895 for _, name := range dn.sortedNames() {
896 node := dn.inodes[name]
899 switch node := node.(type) {
901 size += node.MemorySize()
903 for _, seg := range node.segments {
904 switch seg := seg.(type) {
906 size += int64(seg.Len())
914 // caller must have write lock.
915 func (dn *dirnode) sortedNames() []string {
916 names := make([]string, 0, len(dn.inodes))
917 for name := range dn.inodes {
918 names = append(names, name)
924 // caller must have write lock.
925 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
926 cg := newContextGroup(ctx)
929 if len(dn.inodes) == 0 {
933 // Express the existence of an empty directory by
934 // adding an empty file named `\056`, which (unlike
935 // the more obvious spelling `.`) is accepted by the
936 // API's manifest validator.
937 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
940 names := dn.sortedNames()
942 // Wait for children to finish any pending write operations
943 // before locking them.
944 for _, name := range names {
945 node := dn.inodes[name]
946 if fn, ok := node.(*filenode); ok {
951 var dirnames []string
952 var filenames []string
953 for _, name := range names {
954 node := dn.inodes[name]
957 switch node := node.(type) {
959 dirnames = append(dirnames, name)
961 filenames = append(filenames, name)
963 panic(fmt.Sprintf("can't marshal inode type %T", node))
967 subdirs := make([]string, len(dirnames))
969 for i, name := range dirnames {
972 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
980 type filepart struct {
986 var fileparts []filepart
988 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
991 for _, name := range filenames {
992 node := dn.inodes[name].(*filenode)
993 if len(node.segments) == 0 {
994 fileparts = append(fileparts, filepart{name: name})
997 for _, seg := range node.segments {
998 switch seg := seg.(type) {
1000 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1001 streamLen -= int64(seg.size)
1003 blocks = append(blocks, seg.locator)
1007 offset: streamLen + int64(seg.offset),
1008 length: int64(seg.length),
1010 if prev := len(fileparts) - 1; prev >= 0 &&
1011 fileparts[prev].name == name &&
1012 fileparts[prev].offset+fileparts[prev].length == next.offset {
1013 fileparts[prev].length += next.length
1015 fileparts = append(fileparts, next)
1017 streamLen += int64(seg.size)
1019 // This can't happen: we
1020 // haven't unlocked since
1021 // calling flush(sync=true).
1022 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1026 var filetokens []string
1027 for _, s := range fileparts {
1028 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1030 if len(filetokens) == 0 {
1032 } else if len(blocks) == 0 {
1033 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1035 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1039 return rootdir + strings.Join(subdirs, ""), err
1042 func (dn *dirnode) loadManifest(txt string) error {
1044 streams := strings.Split(txt, "\n")
1045 if streams[len(streams)-1] != "" {
1046 return fmt.Errorf("line %d: no trailing newline", len(streams))
1048 streams = streams[:len(streams)-1]
1049 segments := []storedSegment{}
1050 for i, stream := range streams {
1052 var anyFileTokens bool
1055 segments = segments[:0]
1056 for i, token := range strings.Split(stream, " ") {
1058 dirname = manifestUnescape(token)
1061 if !strings.Contains(token, ":") {
1063 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1065 toks := strings.SplitN(token, "+", 3)
1067 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1069 length, err := strconv.ParseInt(toks[1], 10, 32)
1070 if err != nil || length < 0 {
1071 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1073 segments = append(segments, storedSegment{
1077 length: int(length),
1080 } else if len(segments) == 0 {
1081 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1084 toks := strings.SplitN(token, ":", 3)
1086 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1088 anyFileTokens = true
1090 offset, err := strconv.ParseInt(toks[0], 10, 64)
1091 if err != nil || offset < 0 {
1092 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1094 length, err := strconv.ParseInt(toks[1], 10, 64)
1095 if err != nil || length < 0 {
1096 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1098 name := dirname + "/" + manifestUnescape(toks[2])
1099 fnode, err := dn.createFileAndParents(name)
1100 if fnode == nil && err == nil && length == 0 {
1101 // Special case: an empty file used as
1102 // a marker to preserve an otherwise
1103 // empty directory in a manifest.
1106 if err != nil || (fnode == nil && length != 0) {
1107 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1109 // Map the stream offset/range coordinates to
1110 // block/offset/range coordinates and add
1111 // corresponding storedSegments to the filenode
1113 // Can't continue where we left off.
1114 // TODO: binary search instead of
1115 // rewinding all the way (but this
1116 // situation might be rare anyway)
1119 for ; segIdx < len(segments); segIdx++ {
1120 seg := segments[segIdx]
1121 next := pos + int64(seg.Len())
1122 if next <= offset || seg.Len() == 0 {
1126 if pos >= offset+length {
1131 blkOff = int(offset - pos)
1133 blkLen := seg.Len() - blkOff
1134 if pos+int64(blkOff+blkLen) > offset+length {
1135 blkLen = int(offset + length - pos - int64(blkOff))
1137 fnode.appendSegment(storedSegment{
1139 locator: seg.locator,
1144 if next > offset+length {
1150 if segIdx == len(segments) && pos < offset+length {
1151 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1155 return fmt.Errorf("line %d: no file segments", lineno)
1156 } else if len(segments) == 0 {
1157 return fmt.Errorf("line %d: no locators", lineno)
1158 } else if dirname == "" {
1159 return fmt.Errorf("line %d: no stream name", lineno)
1165 // only safe to call from loadManifest -- no locking.
1167 // If path is a "parent directory exists" marker (the last path
1168 // component is "."), the returned values are both nil.
1169 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1171 names := strings.Split(path, "/")
1172 basename := names[len(names)-1]
1173 for _, name := range names[:len(names)-1] {
1179 // can't be sure parent will be a *dirnode
1180 return nil, ErrInvalidArgument
1182 node = node.Parent()
1185 modtime := node.Parent().FileInfo().ModTime()
1188 node, err = node.Child(name, func(child inode) (inode, error) {
1190 child, err := node.FS().newNode(name, 0755|os.ModeDir, modtime)
1194 child.SetParent(node, name)
1196 } else if !child.IsDir() {
1197 return child, ErrFileExists
1207 if basename == "." {
1209 } else if !permittedName(basename) {
1210 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1213 modtime := node.FileInfo().ModTime()
1216 _, err = node.Child(basename, func(child inode) (inode, error) {
1217 switch child := child.(type) {
1219 child, err = node.FS().newNode(basename, 0755, modtime)
1223 child.SetParent(node, basename)
1224 fn = child.(*filenode)
1230 return child, ErrIsDirectory
1232 return child, ErrInvalidArgument
1238 func (dn *dirnode) TreeSize() (bytes int64) {
1241 for _, i := range dn.inodes {
1242 switch i := i.(type) {
1246 bytes += i.TreeSize()
1252 type segment interface {
1255 // Return a new segment with a subsection of the data from this
1256 // one. length<0 means length=Len()-off.
1257 Slice(off int, length int) segment
1260 type memSegment struct {
1262 // If flushing is not nil and not ready/closed, then a) buf is
1263 // being shared by a pruneMemSegments goroutine, and must be
1264 // copied on write; and b) the flushing channel will close
1265 // when the goroutine finishes, whether it succeeds or not.
1266 flushing <-chan struct{}
1269 func (me *memSegment) flushingUnfinished() bool {
1270 if me.flushing == nil {
1282 func (me *memSegment) Len() int {
1286 func (me *memSegment) Slice(off, length int) segment {
1288 length = len(me.buf) - off
1290 buf := make([]byte, length)
1291 copy(buf, me.buf[off:])
1292 return &memSegment{buf: buf}
1295 func (me *memSegment) Truncate(n int) {
1296 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1299 newsize = newsize << 2
1301 newbuf := make([]byte, n, newsize)
1302 copy(newbuf, me.buf)
1303 me.buf, me.flushing = newbuf, nil
1305 // reclaim existing capacity, and zero reclaimed part
1306 oldlen := len(me.buf)
1308 for i := oldlen; i < n; i++ {
1314 func (me *memSegment) WriteAt(p []byte, off int) {
1315 if off+len(p) > len(me.buf) {
1316 panic("overflowed segment")
1318 if me.flushing != nil {
1319 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1321 copy(me.buf[off:], p)
1324 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1325 if off > int64(me.Len()) {
1329 n = copy(p, me.buf[int(off):])
1336 type storedSegment struct {
1339 size int // size of stored block (also encoded in locator)
1340 offset int // position of segment within the stored block
1341 length int // bytes in this segment (offset + length <= size)
1344 func (se storedSegment) Len() int {
1348 func (se storedSegment) Slice(n, size int) segment {
1351 if size >= 0 && se.length > size {
1357 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1358 if off > int64(se.length) {
1361 maxlen := se.length - int(off)
1362 if len(p) > maxlen {
1364 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1370 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1373 func canonicalName(name string) string {
1374 name = path.Clean("/" + name)
1375 if name == "/" || name == "./" {
1377 } else if strings.HasPrefix(name, "/") {
1383 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1385 func manifestUnescapeFunc(seq string) string {
1389 i, err := strconv.ParseUint(seq[1:], 8, 8)
1391 // Invalid escape sequence: can't unescape.
1394 return string([]byte{byte(i)})
1397 func manifestUnescape(s string) string {
1398 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1401 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1403 func manifestEscapeFunc(seq string) string {
1404 return fmt.Sprintf("\\%03o", byte(seq[0]))
1407 func manifestEscape(s string) string {
1408 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)