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 {
48 // FileSystem returns a CollectionFileSystem for the collection.
49 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
50 modTime := c.ModifiedAt
54 fs := &collectionFileSystem{
56 fileSystem: fileSystem{
57 fsBackend: keepBackend{apiClient: client, keepClient: kc},
58 thr: newThrottle(concurrentWriters),
66 mode: os.ModeDir | 0755,
69 inodes: make(map[string]inode),
72 root.SetParent(root, ".")
73 if err := root.loadManifest(c.ManifestText); err != nil {
76 backdateTree(root, modTime)
81 func backdateTree(n inode, modTime time.Time) {
82 switch n := n.(type) {
84 n.fileinfo.modTime = modTime
86 n.fileinfo.modTime = modTime
87 for _, n := range n.inodes {
88 backdateTree(n, modTime)
93 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
94 if name == "" || name == "." || name == ".." {
95 return nil, ErrInvalidArgument
103 mode: perm | os.ModeDir,
106 inodes: make(map[string]inode),
114 mode: perm & ^os.ModeDir,
120 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
121 return fs.rootnode().Child(name, replace)
124 func (fs *collectionFileSystem) FS() FileSystem {
128 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
129 return fs.rootnode().FileInfo()
132 func (fs *collectionFileSystem) IsDir() bool {
136 func (fs *collectionFileSystem) Lock() {
140 func (fs *collectionFileSystem) Unlock() {
141 fs.rootnode().Unlock()
144 func (fs *collectionFileSystem) RLock() {
145 fs.rootnode().RLock()
148 func (fs *collectionFileSystem) RUnlock() {
149 fs.rootnode().RUnlock()
152 func (fs *collectionFileSystem) Parent() inode {
153 return fs.rootnode().Parent()
156 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
157 return 0, ptr, ErrInvalidOperation
160 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
161 return 0, ptr, ErrInvalidOperation
164 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
165 return fs.rootnode().Readdir()
168 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
169 fs.rootnode().SetParent(parent, name)
172 func (fs *collectionFileSystem) Truncate(int64) error {
173 return ErrInvalidOperation
176 func (fs *collectionFileSystem) Sync() error {
180 txt, err := fs.MarshalManifest(".")
182 return fmt.Errorf("sync failed: %s", err)
188 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
189 "collection": map[string]string{
190 "manifest_text": coll.ManifestText,
192 "select": []string{"uuid"},
195 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
200 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
201 node, err := rlookup(fs.fileSystem.root, path)
205 dn, ok := node.(*dirnode)
207 return ErrNotADirectory
211 names := dn.sortedNames()
213 // Caller only wants to flush the specified dir,
214 // non-recursively. Drop subdirs from the list of
216 var filenames []string
217 for _, name := range names {
218 if _, ok := dn.inodes[name].(*filenode); ok {
219 filenames = append(filenames, name)
224 for _, name := range names {
225 child := dn.inodes[name]
229 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
232 func (fs *collectionFileSystem) MemorySize() int64 {
233 fs.fileSystem.root.Lock()
234 defer fs.fileSystem.root.Unlock()
235 return fs.fileSystem.root.(*dirnode).MemorySize()
238 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
239 fs.fileSystem.root.Lock()
240 defer fs.fileSystem.root.Unlock()
241 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
244 func (fs *collectionFileSystem) Size() int64 {
245 return fs.fileSystem.root.(*dirnode).TreeSize()
248 // filenodePtr is an offset into a file that is (usually) efficient to
249 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
251 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
252 // corresponds to file offset filenodePtr.off. Otherwise, it is
253 // necessary to reexamine len(filenode.segments[0]) etc. to find the
254 // correct segment and offset.
255 type filenodePtr struct {
262 // seek returns a ptr that is consistent with both startPtr.off and
263 // the current state of fn. The caller must already hold fn.RLock() or
266 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
271 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
273 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
274 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
277 // meaningless anyway
279 } else if ptr.off >= fn.fileinfo.size {
280 ptr.segmentIdx = len(fn.segments)
282 ptr.repacked = fn.repacked
284 } else if ptr.repacked == fn.repacked {
285 // segmentIdx and segmentOff accurately reflect
286 // ptr.off, but might have fallen off the end of a
288 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
295 ptr.repacked = fn.repacked
297 if ptr.off >= fn.fileinfo.size {
298 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
301 // Recompute segmentIdx and segmentOff. We have already
302 // established fn.fileinfo.size > ptr.off >= 0, so we don't
303 // have to deal with edge cases here.
305 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
306 // This would panic (index out of range) if
307 // fn.fileinfo.size were larger than
308 // sum(fn.segments[i].Len()) -- but that can't happen
309 // because we have ensured fn.fileinfo.size is always
311 segLen := int64(fn.segments[ptr.segmentIdx].Len())
312 if off+segLen > ptr.off {
313 ptr.segmentOff = int(ptr.off - off)
321 // filenode implements inode.
322 type filenode struct {
327 // number of times `segments` has changed in a
328 // way that might invalidate a filenodePtr
330 memsize int64 // bytes in memSegments
335 // caller must have lock
336 func (fn *filenode) appendSegment(e segment) {
337 fn.segments = append(fn.segments, e)
338 fn.fileinfo.size += int64(e.Len())
341 func (fn *filenode) SetParent(p inode, name string) {
345 fn.fileinfo.name = name
348 func (fn *filenode) Parent() inode {
354 func (fn *filenode) FS() FileSystem {
358 // Read reads file data from a single segment, starting at startPtr,
359 // into p. startPtr is assumed not to be up-to-date. Caller must have
361 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
362 ptr = fn.seek(startPtr)
364 err = ErrNegativeOffset
367 if ptr.segmentIdx >= len(fn.segments) {
371 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
375 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
378 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
386 func (fn *filenode) Size() int64 {
389 return fn.fileinfo.Size()
392 func (fn *filenode) FileInfo() os.FileInfo {
398 func (fn *filenode) Truncate(size int64) error {
401 return fn.truncate(size)
404 func (fn *filenode) truncate(size int64) error {
405 if size == fn.fileinfo.size {
409 if size < fn.fileinfo.size {
410 ptr := fn.seek(filenodePtr{off: size})
411 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
412 if seg, ok := fn.segments[i].(*memSegment); ok {
413 fn.memsize -= int64(seg.Len())
416 if ptr.segmentOff == 0 {
417 fn.segments = fn.segments[:ptr.segmentIdx]
419 fn.segments = fn.segments[:ptr.segmentIdx+1]
420 switch seg := fn.segments[ptr.segmentIdx].(type) {
422 seg.Truncate(ptr.segmentOff)
423 fn.memsize += int64(seg.Len())
425 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
428 fn.fileinfo.size = size
431 for size > fn.fileinfo.size {
432 grow := size - fn.fileinfo.size
435 if len(fn.segments) == 0 {
437 fn.segments = append(fn.segments, seg)
438 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
440 fn.segments = append(fn.segments, seg)
442 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
445 seg.Truncate(seg.Len() + int(grow))
446 fn.fileinfo.size += grow
452 // Write writes data from p to the file, starting at startPtr,
453 // extending the file size if necessary. Caller must have Lock.
454 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
455 if startPtr.off > fn.fileinfo.size {
456 if err = fn.truncate(startPtr.off); err != nil {
457 return 0, startPtr, err
460 ptr = fn.seek(startPtr)
462 err = ErrNegativeOffset
465 for len(p) > 0 && err == nil {
467 if len(cando) > maxBlockSize {
468 cando = cando[:maxBlockSize]
470 // Rearrange/grow fn.segments (and shrink cando if
471 // needed) such that cando can be copied to
472 // fn.segments[ptr.segmentIdx] at offset
474 cur := ptr.segmentIdx
475 prev := ptr.segmentIdx - 1
477 if cur < len(fn.segments) {
478 _, curWritable = fn.segments[cur].(*memSegment)
480 var prevAppendable bool
481 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
482 _, prevAppendable = fn.segments[prev].(*memSegment)
484 if ptr.segmentOff > 0 && !curWritable {
485 // Split a non-writable block.
486 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
487 // Truncate cur, and insert a new
490 fn.segments = append(fn.segments, nil)
491 copy(fn.segments[cur+1:], fn.segments[cur:])
493 // Split cur into two copies, truncate
494 // the one on the left, shift the one
495 // on the right, and insert a new
496 // segment between them.
497 fn.segments = append(fn.segments, nil, nil)
498 copy(fn.segments[cur+2:], fn.segments[cur:])
499 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
504 seg.Truncate(len(cando))
505 fn.memsize += int64(len(cando))
506 fn.segments[cur] = seg
507 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
512 } else if curWritable {
513 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
518 // Shrink cando if needed to fit in
520 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
521 cando = cando[:cangrow]
525 if cur == len(fn.segments) {
526 // ptr is at EOF, filesize is changing.
527 fn.fileinfo.size += int64(len(cando))
528 } else if el := fn.segments[cur].Len(); el <= len(cando) {
529 // cando is long enough that we won't
530 // need cur any more. shrink cando to
531 // be exactly as long as cur
532 // (otherwise we'd accidentally shift
533 // the effective position of all
534 // segments after cur).
536 copy(fn.segments[cur:], fn.segments[cur+1:])
537 fn.segments = fn.segments[:len(fn.segments)-1]
539 // shrink cur by the same #bytes we're growing prev
540 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
546 ptr.segmentOff = fn.segments[prev].Len()
547 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
548 fn.memsize += int64(len(cando))
552 // Insert a segment between prev and
553 // cur, and advance prev/cur.
554 fn.segments = append(fn.segments, nil)
555 if cur < len(fn.segments) {
556 copy(fn.segments[cur+1:], fn.segments[cur:])
560 // appending a new segment does
561 // not invalidate any ptrs
564 seg.Truncate(len(cando))
565 fn.memsize += int64(len(cando))
566 fn.segments[cur] = seg
570 // Finally we can copy bytes from cando to the current segment.
571 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
575 ptr.off += int64(len(cando))
576 ptr.segmentOff += len(cando)
577 if ptr.segmentOff >= maxBlockSize {
578 fn.pruneMemSegments()
580 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
585 fn.fileinfo.modTime = time.Now()
590 // Write some data out to disk to reduce memory use. Caller must have
592 func (fn *filenode) pruneMemSegments() {
593 // TODO: share code with (*dirnode)flush()
594 // TODO: pack/flush small blocks too, when fragmented
595 for idx, seg := range fn.segments {
596 seg, ok := seg.(*memSegment)
597 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
600 // Setting seg.flushing guarantees seg.buf will not be
601 // modified in place: WriteAt and Truncate will
602 // allocate a new buf instead, if necessary.
603 idx, buf := idx, seg.buf
604 done := make(chan struct{})
606 // If lots of background writes are already in
607 // progress, block here until one finishes, rather
608 // than pile up an unlimited number of buffered writes
609 // and network flush operations.
610 fn.fs.throttle().Acquire()
613 locator, _, err := fn.FS().PutB(buf)
614 fn.fs.throttle().Release()
617 if seg.flushing != done {
618 // A new seg.buf has been allocated.
622 // TODO: stall (or return errors from)
623 // subsequent writes until flushing
624 // starts to succeed.
627 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
628 // Segment has been dropped/moved/resized.
631 fn.memsize -= int64(len(buf))
632 fn.segments[idx] = storedSegment{
643 // Block until all pending pruneMemSegments/flush work is
644 // finished. Caller must NOT have lock.
645 func (fn *filenode) waitPrune() {
646 var pending []<-chan struct{}
648 for _, seg := range fn.segments {
649 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
650 pending = append(pending, seg.flushing)
654 for _, p := range pending {
659 type dirnode struct {
660 fs *collectionFileSystem
664 func (dn *dirnode) FS() FileSystem {
668 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
669 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
670 gn := &getternode{Getter: func() ([]byte, error) {
673 coll.ManifestText, err = dn.fs.MarshalManifest(".")
677 data, err := json.Marshal(&coll)
679 data = append(data, '\n')
683 gn.SetParent(dn, name)
686 return dn.treenode.Child(name, replace)
689 type fnSegmentRef struct {
694 // commitBlock concatenates the data from the given filenode segments
695 // (which must be *memSegments), writes the data out to Keep as a
696 // single block, and replaces the filenodes' *memSegments with
697 // storedSegments that reference the relevant portions of the new
700 // bufsize is the total data size in refs. It is used to preallocate
701 // the correct amount of memory when len(refs)>1.
703 // If sync is false, commitBlock returns right away, after starting a
704 // goroutine to do the writes, reacquire the filenodes' locks, and
705 // swap out the *memSegments. Some filenodes' segments might get
706 // modified/rearranged in the meantime, in which case commitBlock
707 // won't replace them.
709 // Caller must have write lock.
710 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
714 if err := ctx.Err(); err != nil {
717 done := make(chan struct{})
719 segs := make([]*memSegment, 0, len(refs))
720 offsets := make([]int, 0, len(refs)) // location of segment's data within block
721 for _, ref := range refs {
722 seg := ref.fn.segments[ref.idx].(*memSegment)
723 if !sync && seg.flushingUnfinished() {
724 // Let the other flushing goroutine finish. If
725 // it fails, we'll try again next time.
729 // In sync mode, we proceed regardless of
730 // whether another flush is in progress: It
731 // can't finish before we do, because we hold
732 // fn's lock until we finish our own writes.
734 offsets = append(offsets, len(block))
737 } else if block == nil {
738 block = append(make([]byte, 0, bufsize), seg.buf...)
740 block = append(block, seg.buf...)
742 segs = append(segs, seg)
744 blocksize := len(block)
745 dn.fs.throttle().Acquire()
746 errs := make(chan error, 1)
750 locator, _, err := dn.fs.PutB(block)
751 dn.fs.throttle().Release()
756 for idx, ref := range refs {
759 // In async mode, fn's lock was
760 // released while we were waiting for
761 // PutB(); lots of things might have
763 if len(ref.fn.segments) <= ref.idx {
764 // file segments have
765 // rearranged or changed in
769 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
770 // segment has been replaced
773 } else if seg.flushing != done {
774 // seg.buf has been replaced
779 data := ref.fn.segments[ref.idx].(*memSegment).buf
780 ref.fn.segments[ref.idx] = storedSegment{
784 offset: offsets[idx],
787 // atomic is needed here despite caller having
788 // lock: caller might be running concurrent
789 // commitBlock() goroutines using the same
790 // lock, writing different segments from the
792 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
804 type flushOpts struct {
809 // flush in-memory data and remote-cluster block references (for the
810 // children with the given names, which must be children of dn) to
811 // local-cluster persistent storage.
813 // Caller must have write lock on dn and the named children.
815 // If any children are dirs, they will be flushed recursively.
816 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
817 cg := newContextGroup(ctx)
820 goCommit := func(refs []fnSegmentRef, bufsize int) {
822 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
826 var pending []fnSegmentRef
827 var pendingLen int = 0
828 localLocator := map[string]string{}
829 for _, name := range names {
830 switch node := dn.inodes[name].(type) {
832 grandchildNames := node.sortedNames()
833 for _, grandchildName := range grandchildNames {
834 grandchild := node.inodes[grandchildName]
836 defer grandchild.Unlock()
838 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
840 for idx, seg := range node.segments {
841 switch seg := seg.(type) {
843 loc, ok := localLocator[seg.locator]
846 loc, err = dn.fs.LocalLocator(seg.locator)
850 localLocator[seg.locator] = loc
853 node.segments[idx] = seg
855 if seg.Len() > maxBlockSize/2 {
856 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
859 if pendingLen+seg.Len() > maxBlockSize {
860 goCommit(pending, pendingLen)
864 pending = append(pending, fnSegmentRef{node, idx})
865 pendingLen += seg.Len()
867 panic(fmt.Sprintf("can't sync segment type %T", seg))
872 if opts.shortBlocks {
873 goCommit(pending, pendingLen)
878 // caller must have write lock.
879 func (dn *dirnode) MemorySize() (size int64) {
880 for _, name := range dn.sortedNames() {
881 node := dn.inodes[name]
884 switch node := node.(type) {
886 size += node.MemorySize()
888 for _, seg := range node.segments {
889 switch seg := seg.(type) {
891 size += int64(seg.Len())
899 // caller must have write lock.
900 func (dn *dirnode) sortedNames() []string {
901 names := make([]string, 0, len(dn.inodes))
902 for name := range dn.inodes {
903 names = append(names, name)
909 // caller must have write lock.
910 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
911 cg := newContextGroup(ctx)
914 if len(dn.inodes) == 0 {
918 // Express the existence of an empty directory by
919 // adding an empty file named `\056`, which (unlike
920 // the more obvious spelling `.`) is accepted by the
921 // API's manifest validator.
922 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
925 names := dn.sortedNames()
927 // Wait for children to finish any pending write operations
928 // before locking them.
929 for _, name := range names {
930 node := dn.inodes[name]
931 if fn, ok := node.(*filenode); ok {
936 var dirnames []string
937 var filenames []string
938 for _, name := range names {
939 node := dn.inodes[name]
942 switch node := node.(type) {
944 dirnames = append(dirnames, name)
946 filenames = append(filenames, name)
948 panic(fmt.Sprintf("can't marshal inode type %T", node))
952 subdirs := make([]string, len(dirnames))
954 for i, name := range dirnames {
957 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
965 type filepart struct {
971 var fileparts []filepart
973 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
976 for _, name := range filenames {
977 node := dn.inodes[name].(*filenode)
978 if len(node.segments) == 0 {
979 fileparts = append(fileparts, filepart{name: name})
982 for _, seg := range node.segments {
983 switch seg := seg.(type) {
985 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
986 streamLen -= int64(seg.size)
988 blocks = append(blocks, seg.locator)
992 offset: streamLen + int64(seg.offset),
993 length: int64(seg.length),
995 if prev := len(fileparts) - 1; prev >= 0 &&
996 fileparts[prev].name == name &&
997 fileparts[prev].offset+fileparts[prev].length == next.offset {
998 fileparts[prev].length += next.length
1000 fileparts = append(fileparts, next)
1002 streamLen += int64(seg.size)
1004 // This can't happen: we
1005 // haven't unlocked since
1006 // calling flush(sync=true).
1007 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1011 var filetokens []string
1012 for _, s := range fileparts {
1013 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1015 if len(filetokens) == 0 {
1017 } else if len(blocks) == 0 {
1018 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1020 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1024 return rootdir + strings.Join(subdirs, ""), err
1027 func (dn *dirnode) loadManifest(txt string) error {
1029 streams := strings.Split(txt, "\n")
1030 if streams[len(streams)-1] != "" {
1031 return fmt.Errorf("line %d: no trailing newline", len(streams))
1033 streams = streams[:len(streams)-1]
1034 segments := []storedSegment{}
1035 for i, stream := range streams {
1037 var anyFileTokens bool
1040 segments = segments[:0]
1041 for i, token := range strings.Split(stream, " ") {
1043 dirname = manifestUnescape(token)
1046 if !strings.Contains(token, ":") {
1048 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1050 toks := strings.SplitN(token, "+", 3)
1052 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1054 length, err := strconv.ParseInt(toks[1], 10, 32)
1055 if err != nil || length < 0 {
1056 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1058 segments = append(segments, storedSegment{
1062 length: int(length),
1065 } else if len(segments) == 0 {
1066 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1069 toks := strings.SplitN(token, ":", 3)
1071 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1073 anyFileTokens = true
1075 offset, err := strconv.ParseInt(toks[0], 10, 64)
1076 if err != nil || offset < 0 {
1077 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1079 length, err := strconv.ParseInt(toks[1], 10, 64)
1080 if err != nil || length < 0 {
1081 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1083 name := dirname + "/" + manifestUnescape(toks[2])
1084 fnode, err := dn.createFileAndParents(name)
1085 if fnode == nil && err == nil && length == 0 {
1086 // Special case: an empty file used as
1087 // a marker to preserve an otherwise
1088 // empty directory in a manifest.
1091 if err != nil || (fnode == nil && length != 0) {
1092 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1094 // Map the stream offset/range coordinates to
1095 // block/offset/range coordinates and add
1096 // corresponding storedSegments to the filenode
1098 // Can't continue where we left off.
1099 // TODO: binary search instead of
1100 // rewinding all the way (but this
1101 // situation might be rare anyway)
1104 for ; segIdx < len(segments); segIdx++ {
1105 seg := segments[segIdx]
1106 next := pos + int64(seg.Len())
1107 if next <= offset || seg.Len() == 0 {
1111 if pos >= offset+length {
1116 blkOff = int(offset - pos)
1118 blkLen := seg.Len() - blkOff
1119 if pos+int64(blkOff+blkLen) > offset+length {
1120 blkLen = int(offset + length - pos - int64(blkOff))
1122 fnode.appendSegment(storedSegment{
1124 locator: seg.locator,
1129 if next > offset+length {
1135 if segIdx == len(segments) && pos < offset+length {
1136 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1140 return fmt.Errorf("line %d: no file segments", lineno)
1141 } else if len(segments) == 0 {
1142 return fmt.Errorf("line %d: no locators", lineno)
1143 } else if dirname == "" {
1144 return fmt.Errorf("line %d: no stream name", lineno)
1150 // only safe to call from loadManifest -- no locking.
1152 // If path is a "parent directory exists" marker (the last path
1153 // component is "."), the returned values are both nil.
1154 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1156 names := strings.Split(path, "/")
1157 basename := names[len(names)-1]
1158 for _, name := range names[:len(names)-1] {
1164 // can't be sure parent will be a *dirnode
1165 return nil, ErrInvalidArgument
1167 node = node.Parent()
1170 node, err = node.Child(name, func(child inode) (inode, error) {
1172 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1176 child.SetParent(node, name)
1178 } else if !child.IsDir() {
1179 return child, ErrFileExists
1188 if basename == "." {
1190 } else if !permittedName(basename) {
1191 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1194 _, err = node.Child(basename, func(child inode) (inode, error) {
1195 switch child := child.(type) {
1197 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1201 child.SetParent(node, basename)
1202 fn = child.(*filenode)
1208 return child, ErrIsDirectory
1210 return child, ErrInvalidArgument
1216 func (dn *dirnode) TreeSize() (bytes int64) {
1219 for _, i := range dn.inodes {
1220 switch i := i.(type) {
1224 bytes += i.TreeSize()
1230 type segment interface {
1233 // Return a new segment with a subsection of the data from this
1234 // one. length<0 means length=Len()-off.
1235 Slice(off int, length int) segment
1238 type memSegment struct {
1240 // If flushing is not nil and not ready/closed, then a) buf is
1241 // being shared by a pruneMemSegments goroutine, and must be
1242 // copied on write; and b) the flushing channel will close
1243 // when the goroutine finishes, whether it succeeds or not.
1244 flushing <-chan struct{}
1247 func (me *memSegment) flushingUnfinished() bool {
1248 if me.flushing == nil {
1260 func (me *memSegment) Len() int {
1264 func (me *memSegment) Slice(off, length int) segment {
1266 length = len(me.buf) - off
1268 buf := make([]byte, length)
1269 copy(buf, me.buf[off:])
1270 return &memSegment{buf: buf}
1273 func (me *memSegment) Truncate(n int) {
1274 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1277 newsize = newsize << 2
1279 newbuf := make([]byte, n, newsize)
1280 copy(newbuf, me.buf)
1281 me.buf, me.flushing = newbuf, nil
1283 // reclaim existing capacity, and zero reclaimed part
1284 oldlen := len(me.buf)
1286 for i := oldlen; i < n; i++ {
1292 func (me *memSegment) WriteAt(p []byte, off int) {
1293 if off+len(p) > len(me.buf) {
1294 panic("overflowed segment")
1296 if me.flushing != nil {
1297 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1299 copy(me.buf[off:], p)
1302 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1303 if off > int64(me.Len()) {
1307 n = copy(p, me.buf[int(off):])
1314 type storedSegment struct {
1317 size int // size of stored block (also encoded in locator)
1318 offset int // position of segment within the stored block
1319 length int // bytes in this segment (offset + length <= size)
1322 func (se storedSegment) Len() int {
1326 func (se storedSegment) Slice(n, size int) segment {
1329 if size >= 0 && se.length > size {
1335 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1336 if off > int64(se.length) {
1339 maxlen := se.length - int(off)
1340 if len(p) > maxlen {
1342 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1348 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1351 func canonicalName(name string) string {
1352 name = path.Clean("/" + name)
1353 if name == "/" || name == "./" {
1355 } else if strings.HasPrefix(name, "/") {
1361 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1363 func manifestUnescapeFunc(seq string) string {
1367 i, err := strconv.ParseUint(seq[1:], 8, 8)
1369 // Invalid escape sequence: can't unescape.
1372 return string([]byte{byte(i)})
1375 func manifestUnescape(s string) string {
1376 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1379 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1381 func manifestEscapeFunc(seq string) string {
1382 return fmt.Sprintf("\\%03o", byte(seq[0]))
1385 func manifestEscape(s string) string {
1386 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)