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.
42 // Memory consumed by buffered file data.
46 type collectionFileSystem struct {
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 fileSystem: fileSystem{
60 fsBackend: keepBackend{apiClient: client, keepClient: kc},
61 thr: newThrottle(concurrentWriters),
69 mode: os.ModeDir | 0755,
72 inodes: make(map[string]inode),
75 root.SetParent(root, ".")
76 if err := root.loadManifest(c.ManifestText); err != nil {
79 backdateTree(root, modTime)
84 func backdateTree(n inode, modTime time.Time) {
85 switch n := n.(type) {
87 n.fileinfo.modTime = modTime
89 n.fileinfo.modTime = modTime
90 for _, n := range n.inodes {
91 backdateTree(n, modTime)
96 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
97 if name == "" || name == "." || name == ".." {
98 return nil, ErrInvalidArgument
106 mode: perm | os.ModeDir,
109 inodes: make(map[string]inode),
117 mode: perm & ^os.ModeDir,
124 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
125 return fs.rootnode().Child(name, replace)
128 func (fs *collectionFileSystem) FS() FileSystem {
132 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
133 return fs.rootnode().FileInfo()
136 func (fs *collectionFileSystem) IsDir() bool {
140 func (fs *collectionFileSystem) Lock() {
144 func (fs *collectionFileSystem) Unlock() {
145 fs.rootnode().Unlock()
148 func (fs *collectionFileSystem) RLock() {
149 fs.rootnode().RLock()
152 func (fs *collectionFileSystem) RUnlock() {
153 fs.rootnode().RUnlock()
156 func (fs *collectionFileSystem) Parent() inode {
157 return fs.rootnode().Parent()
160 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
161 return 0, ptr, ErrInvalidOperation
164 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
165 return 0, ptr, ErrInvalidOperation
168 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
169 return fs.rootnode().Readdir()
172 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
173 fs.rootnode().SetParent(parent, name)
176 func (fs *collectionFileSystem) Truncate(int64) error {
177 return ErrInvalidOperation
180 func (fs *collectionFileSystem) Sync() error {
184 txt, err := fs.MarshalManifest(".")
186 return fmt.Errorf("sync failed: %s", err)
192 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
193 "collection": map[string]string{
194 "manifest_text": coll.ManifestText,
196 "select": []string{"uuid"},
199 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
204 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
205 node, err := rlookup(fs.fileSystem.root, path)
209 dn, ok := node.(*dirnode)
211 return ErrNotADirectory
215 names := dn.sortedNames()
217 // Caller only wants to flush the specified dir,
218 // non-recursively. Drop subdirs from the list of
220 var filenames []string
221 for _, name := range names {
222 if _, ok := dn.inodes[name].(*filenode); ok {
223 filenames = append(filenames, name)
228 for _, name := range names {
229 child := dn.inodes[name]
233 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
236 func (fs *collectionFileSystem) memorySize() int64 {
237 fs.fileSystem.root.Lock()
238 defer fs.fileSystem.root.Unlock()
239 return fs.fileSystem.root.(*dirnode).memorySize()
242 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
243 fs.fileSystem.root.Lock()
244 defer fs.fileSystem.root.Unlock()
245 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
248 func (fs *collectionFileSystem) Size() int64 {
249 return fs.fileSystem.root.(*dirnode).TreeSize()
252 // filenodePtr is an offset into a file that is (usually) efficient to
253 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
255 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
256 // corresponds to file offset filenodePtr.off. Otherwise, it is
257 // necessary to reexamine len(filenode.segments[0]) etc. to find the
258 // correct segment and offset.
259 type filenodePtr struct {
266 // seek returns a ptr that is consistent with both startPtr.off and
267 // the current state of fn. The caller must already hold fn.RLock() or
270 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
275 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
277 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
278 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
281 // meaningless anyway
283 } else if ptr.off >= fn.fileinfo.size {
284 ptr.segmentIdx = len(fn.segments)
286 ptr.repacked = fn.repacked
288 } else if ptr.repacked == fn.repacked {
289 // segmentIdx and segmentOff accurately reflect
290 // ptr.off, but might have fallen off the end of a
292 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
299 ptr.repacked = fn.repacked
301 if ptr.off >= fn.fileinfo.size {
302 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
305 // Recompute segmentIdx and segmentOff. We have already
306 // established fn.fileinfo.size > ptr.off >= 0, so we don't
307 // have to deal with edge cases here.
309 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
310 // This would panic (index out of range) if
311 // fn.fileinfo.size were larger than
312 // sum(fn.segments[i].Len()) -- but that can't happen
313 // because we have ensured fn.fileinfo.size is always
315 segLen := int64(fn.segments[ptr.segmentIdx].Len())
316 if off+segLen > ptr.off {
317 ptr.segmentOff = int(ptr.off - off)
325 // filenode implements inode.
326 type filenode struct {
331 // number of times `segments` has changed in a
332 // way that might invalidate a filenodePtr
334 memsize int64 // bytes in memSegments
339 // caller must have lock
340 func (fn *filenode) appendSegment(e segment) {
341 fn.segments = append(fn.segments, e)
342 fn.fileinfo.size += int64(e.Len())
345 func (fn *filenode) SetParent(p inode, name string) {
349 fn.fileinfo.name = name
352 func (fn *filenode) Parent() inode {
358 func (fn *filenode) FS() FileSystem {
362 // Read reads file data from a single segment, starting at startPtr,
363 // into p. startPtr is assumed not to be up-to-date. Caller must have
365 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
366 ptr = fn.seek(startPtr)
368 err = ErrNegativeOffset
371 if ptr.segmentIdx >= len(fn.segments) {
375 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
379 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
382 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
390 func (fn *filenode) Size() int64 {
393 return fn.fileinfo.Size()
396 func (fn *filenode) FileInfo() os.FileInfo {
402 func (fn *filenode) Truncate(size int64) error {
405 return fn.truncate(size)
408 func (fn *filenode) truncate(size int64) error {
409 if size == fn.fileinfo.size {
413 if size < fn.fileinfo.size {
414 ptr := fn.seek(filenodePtr{off: size})
415 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
416 if seg, ok := fn.segments[i].(*memSegment); ok {
417 fn.memsize -= int64(seg.Len())
420 if ptr.segmentOff == 0 {
421 fn.segments = fn.segments[:ptr.segmentIdx]
423 fn.segments = fn.segments[:ptr.segmentIdx+1]
424 switch seg := fn.segments[ptr.segmentIdx].(type) {
426 seg.Truncate(ptr.segmentOff)
427 fn.memsize += int64(seg.Len())
429 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
432 fn.fileinfo.size = size
435 for size > fn.fileinfo.size {
436 grow := size - fn.fileinfo.size
439 if len(fn.segments) == 0 {
441 fn.segments = append(fn.segments, seg)
442 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
444 fn.segments = append(fn.segments, seg)
446 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
449 seg.Truncate(seg.Len() + int(grow))
450 fn.fileinfo.size += grow
456 // Write writes data from p to the file, starting at startPtr,
457 // extending the file size if necessary. Caller must have Lock.
458 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
459 if startPtr.off > fn.fileinfo.size {
460 if err = fn.truncate(startPtr.off); err != nil {
461 return 0, startPtr, err
464 ptr = fn.seek(startPtr)
466 err = ErrNegativeOffset
469 for len(p) > 0 && err == nil {
471 if len(cando) > maxBlockSize {
472 cando = cando[:maxBlockSize]
474 // Rearrange/grow fn.segments (and shrink cando if
475 // needed) such that cando can be copied to
476 // fn.segments[ptr.segmentIdx] at offset
478 cur := ptr.segmentIdx
479 prev := ptr.segmentIdx - 1
481 if cur < len(fn.segments) {
482 _, curWritable = fn.segments[cur].(*memSegment)
484 var prevAppendable bool
485 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
486 _, prevAppendable = fn.segments[prev].(*memSegment)
488 if ptr.segmentOff > 0 && !curWritable {
489 // Split a non-writable block.
490 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
491 // Truncate cur, and insert a new
494 fn.segments = append(fn.segments, nil)
495 copy(fn.segments[cur+1:], fn.segments[cur:])
497 // Split cur into two copies, truncate
498 // the one on the left, shift the one
499 // on the right, and insert a new
500 // segment between them.
501 fn.segments = append(fn.segments, nil, nil)
502 copy(fn.segments[cur+2:], fn.segments[cur:])
503 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
508 seg.Truncate(len(cando))
509 fn.memsize += int64(len(cando))
510 fn.segments[cur] = seg
511 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
516 } else if curWritable {
517 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
522 // Shrink cando if needed to fit in
524 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
525 cando = cando[:cangrow]
529 if cur == len(fn.segments) {
530 // ptr is at EOF, filesize is changing.
531 fn.fileinfo.size += int64(len(cando))
532 } else if el := fn.segments[cur].Len(); el <= len(cando) {
533 // cando is long enough that we won't
534 // need cur any more. shrink cando to
535 // be exactly as long as cur
536 // (otherwise we'd accidentally shift
537 // the effective position of all
538 // segments after cur).
540 copy(fn.segments[cur:], fn.segments[cur+1:])
541 fn.segments = fn.segments[:len(fn.segments)-1]
543 // shrink cur by the same #bytes we're growing prev
544 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
550 ptr.segmentOff = fn.segments[prev].Len()
551 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
552 fn.memsize += int64(len(cando))
556 // Insert a segment between prev and
557 // cur, and advance prev/cur.
558 fn.segments = append(fn.segments, nil)
559 if cur < len(fn.segments) {
560 copy(fn.segments[cur+1:], fn.segments[cur:])
564 // appending a new segment does
565 // not invalidate any ptrs
568 seg.Truncate(len(cando))
569 fn.memsize += int64(len(cando))
570 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 locator, _, err := fn.FS().PutB(buf)
620 fn.fs.throttle().Release()
623 if seg.flushing != done {
624 // A new seg.buf has been allocated.
628 // TODO: stall (or return errors from)
629 // subsequent writes until flushing
630 // starts to succeed.
633 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
634 // Segment has been dropped/moved/resized.
637 fn.memsize -= int64(len(buf))
638 fn.segments[idx] = storedSegment{
649 // Block until all pending pruneMemSegments/flush work is
650 // finished. Caller must NOT have lock.
651 func (fn *filenode) waitPrune() {
652 var pending []<-chan struct{}
654 for _, seg := range fn.segments {
655 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
656 pending = append(pending, seg.flushing)
660 for _, p := range pending {
665 type dirnode struct {
666 fs *collectionFileSystem
670 func (dn *dirnode) FS() FileSystem {
674 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
675 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
676 gn := &getternode{Getter: func() ([]byte, error) {
679 coll.ManifestText, err = dn.fs.MarshalManifest(".")
683 data, err := json.Marshal(&coll)
685 data = append(data, '\n')
689 gn.SetParent(dn, name)
692 return dn.treenode.Child(name, replace)
695 type fnSegmentRef struct {
700 // commitBlock concatenates the data from the given filenode segments
701 // (which must be *memSegments), writes the data out to Keep as a
702 // single block, and replaces the filenodes' *memSegments with
703 // storedSegments that reference the relevant portions of the new
706 // bufsize is the total data size in refs. It is used to preallocate
707 // the correct amount of memory when len(refs)>1.
709 // If sync is false, commitBlock returns right away, after starting a
710 // goroutine to do the writes, reacquire the filenodes' locks, and
711 // swap out the *memSegments. Some filenodes' segments might get
712 // modified/rearranged in the meantime, in which case commitBlock
713 // won't replace them.
715 // Caller must have write lock.
716 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
720 if err := ctx.Err(); err != nil {
723 done := make(chan struct{})
725 segs := make([]*memSegment, 0, len(refs))
726 offsets := make([]int, 0, len(refs)) // location of segment's data within block
727 for _, ref := range refs {
728 seg := ref.fn.segments[ref.idx].(*memSegment)
729 if !sync && seg.flushingUnfinished() {
730 // Let the other flushing goroutine finish. If
731 // it fails, we'll try again next time.
735 // In sync mode, we proceed regardless of
736 // whether another flush is in progress: It
737 // can't finish before we do, because we hold
738 // fn's lock until we finish our own writes.
741 offsets = append(offsets, len(block))
744 } else if block == nil {
745 block = append(make([]byte, 0, bufsize), seg.buf...)
747 block = append(block, seg.buf...)
749 segs = append(segs, seg)
751 blocksize := len(block)
752 dn.fs.throttle().Acquire()
753 errs := make(chan error, 1)
757 locator, _, err := dn.fs.PutB(block)
758 dn.fs.throttle().Release()
763 for idx, ref := range refs {
766 // In async mode, fn's lock was
767 // released while we were waiting for
768 // PutB(); lots of things might have
770 if len(ref.fn.segments) <= ref.idx {
771 // file segments have
772 // rearranged or changed in
776 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
777 // segment has been replaced
780 } else if seg.flushing != done {
781 // seg.buf has been replaced
786 data := ref.fn.segments[ref.idx].(*memSegment).buf
787 ref.fn.segments[ref.idx] = storedSegment{
791 offset: offsets[idx],
794 // atomic is needed here despite caller having
795 // lock: caller might be running concurrent
796 // commitBlock() goroutines using the same
797 // lock, writing different segments from the
799 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
812 type flushOpts struct {
817 // flush in-memory data and remote-cluster block references (for the
818 // children with the given names, which must be children of dn) to
819 // local-cluster persistent storage.
821 // Caller must have write lock on dn and the named children.
823 // If any children are dirs, they will be flushed recursively.
824 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
825 cg := newContextGroup(ctx)
828 goCommit := func(refs []fnSegmentRef, bufsize int) {
830 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
834 var pending []fnSegmentRef
835 var pendingLen int = 0
836 localLocator := map[string]string{}
837 for _, name := range names {
838 switch node := dn.inodes[name].(type) {
840 grandchildNames := node.sortedNames()
841 for _, grandchildName := range grandchildNames {
842 grandchild := node.inodes[grandchildName]
844 defer grandchild.Unlock()
846 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
848 for idx, seg := range node.segments {
849 switch seg := seg.(type) {
851 loc, ok := localLocator[seg.locator]
854 loc, err = dn.fs.LocalLocator(seg.locator)
858 localLocator[seg.locator] = loc
861 node.segments[idx] = seg
863 if seg.Len() > maxBlockSize/2 {
864 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
867 if pendingLen+seg.Len() > maxBlockSize {
868 goCommit(pending, pendingLen)
872 pending = append(pending, fnSegmentRef{node, idx})
873 pendingLen += seg.Len()
875 panic(fmt.Sprintf("can't sync segment type %T", seg))
880 if opts.shortBlocks {
881 goCommit(pending, pendingLen)
886 // caller must have write lock.
887 func (dn *dirnode) memorySize() (size int64) {
888 for _, name := range dn.sortedNames() {
889 node := dn.inodes[name]
892 switch node := node.(type) {
894 size += node.memorySize()
896 for _, seg := range node.segments {
897 switch seg := seg.(type) {
899 size += int64(seg.Len())
907 // caller must have write lock.
908 func (dn *dirnode) sortedNames() []string {
909 names := make([]string, 0, len(dn.inodes))
910 for name := range dn.inodes {
911 names = append(names, name)
917 // caller must have write lock.
918 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
919 cg := newContextGroup(ctx)
922 if len(dn.inodes) == 0 {
926 // Express the existence of an empty directory by
927 // adding an empty file named `\056`, which (unlike
928 // the more obvious spelling `.`) is accepted by the
929 // API's manifest validator.
930 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
933 names := dn.sortedNames()
935 // Wait for children to finish any pending write operations
936 // before locking them.
937 for _, name := range names {
938 node := dn.inodes[name]
939 if fn, ok := node.(*filenode); ok {
944 var dirnames []string
945 var filenames []string
946 for _, name := range names {
947 node := dn.inodes[name]
950 switch node := node.(type) {
952 dirnames = append(dirnames, name)
954 filenames = append(filenames, name)
956 panic(fmt.Sprintf("can't marshal inode type %T", node))
960 subdirs := make([]string, len(dirnames))
962 for i, name := range dirnames {
965 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
973 type filepart struct {
979 var fileparts []filepart
981 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
984 for _, name := range filenames {
985 node := dn.inodes[name].(*filenode)
986 if len(node.segments) == 0 {
987 fileparts = append(fileparts, filepart{name: name})
990 for _, seg := range node.segments {
991 switch seg := seg.(type) {
993 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
994 streamLen -= int64(seg.size)
996 blocks = append(blocks, seg.locator)
1000 offset: streamLen + int64(seg.offset),
1001 length: int64(seg.length),
1003 if prev := len(fileparts) - 1; prev >= 0 &&
1004 fileparts[prev].name == name &&
1005 fileparts[prev].offset+fileparts[prev].length == next.offset {
1006 fileparts[prev].length += next.length
1008 fileparts = append(fileparts, next)
1010 streamLen += int64(seg.size)
1012 // This can't happen: we
1013 // haven't unlocked since
1014 // calling flush(sync=true).
1015 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1019 var filetokens []string
1020 for _, s := range fileparts {
1021 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1023 if len(filetokens) == 0 {
1025 } else if len(blocks) == 0 {
1026 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1028 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1032 return rootdir + strings.Join(subdirs, ""), err
1035 func (dn *dirnode) loadManifest(txt string) error {
1037 streams := strings.Split(txt, "\n")
1038 if streams[len(streams)-1] != "" {
1039 return fmt.Errorf("line %d: no trailing newline", len(streams))
1041 streams = streams[:len(streams)-1]
1042 segments := []storedSegment{}
1043 for i, stream := range streams {
1045 var anyFileTokens bool
1048 segments = segments[:0]
1049 for i, token := range strings.Split(stream, " ") {
1051 dirname = manifestUnescape(token)
1054 if !strings.Contains(token, ":") {
1056 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1058 toks := strings.SplitN(token, "+", 3)
1060 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1062 length, err := strconv.ParseInt(toks[1], 10, 32)
1063 if err != nil || length < 0 {
1064 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1066 segments = append(segments, storedSegment{
1070 length: int(length),
1073 } else if len(segments) == 0 {
1074 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1077 toks := strings.SplitN(token, ":", 3)
1079 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1081 anyFileTokens = true
1083 offset, err := strconv.ParseInt(toks[0], 10, 64)
1084 if err != nil || offset < 0 {
1085 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1087 length, err := strconv.ParseInt(toks[1], 10, 64)
1088 if err != nil || length < 0 {
1089 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1091 name := dirname + "/" + manifestUnescape(toks[2])
1092 fnode, err := dn.createFileAndParents(name)
1093 if fnode == nil && err == nil && length == 0 {
1094 // Special case: an empty file used as
1095 // a marker to preserve an otherwise
1096 // empty directory in a manifest.
1099 if err != nil || (fnode == nil && length != 0) {
1100 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1102 // Map the stream offset/range coordinates to
1103 // block/offset/range coordinates and add
1104 // corresponding storedSegments to the filenode
1106 // Can't continue where we left off.
1107 // TODO: binary search instead of
1108 // rewinding all the way (but this
1109 // situation might be rare anyway)
1112 for next := int64(0); segIdx < len(segments); segIdx++ {
1113 seg := segments[segIdx]
1114 next = pos + int64(seg.Len())
1115 if next <= offset || seg.Len() == 0 {
1119 if pos >= offset+length {
1124 blkOff = int(offset - pos)
1126 blkLen := seg.Len() - blkOff
1127 if pos+int64(blkOff+blkLen) > offset+length {
1128 blkLen = int(offset + length - pos - int64(blkOff))
1130 fnode.appendSegment(storedSegment{
1132 locator: seg.locator,
1137 if next > offset+length {
1143 if segIdx == len(segments) && pos < offset+length {
1144 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1148 return fmt.Errorf("line %d: no file segments", lineno)
1149 } else if len(segments) == 0 {
1150 return fmt.Errorf("line %d: no locators", lineno)
1151 } else if dirname == "" {
1152 return fmt.Errorf("line %d: no stream name", lineno)
1158 // only safe to call from loadManifest -- no locking.
1160 // If path is a "parent directory exists" marker (the last path
1161 // component is "."), the returned values are both nil.
1162 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1164 names := strings.Split(path, "/")
1165 basename := names[len(names)-1]
1166 for _, name := range names[:len(names)-1] {
1172 // can't be sure parent will be a *dirnode
1173 return nil, ErrInvalidArgument
1175 node = node.Parent()
1178 node, err = node.Child(name, func(child inode) (inode, error) {
1180 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1184 child.SetParent(node, name)
1186 } else if !child.IsDir() {
1187 return child, ErrFileExists
1196 if basename == "." {
1198 } else if !permittedName(basename) {
1199 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1202 _, err = node.Child(basename, func(child inode) (inode, error) {
1203 switch child := child.(type) {
1205 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1209 child.SetParent(node, basename)
1210 fn = child.(*filenode)
1216 return child, ErrIsDirectory
1218 return child, ErrInvalidArgument
1224 func (dn *dirnode) TreeSize() (bytes int64) {
1227 for _, i := range dn.inodes {
1228 switch i := i.(type) {
1232 bytes += i.TreeSize()
1238 type segment interface {
1241 // Return a new segment with a subsection of the data from this
1242 // one. length<0 means length=Len()-off.
1243 Slice(off int, length int) segment
1246 type memSegment struct {
1248 // If flushing is not nil and not ready/closed, then a) buf is
1249 // being shared by a pruneMemSegments goroutine, and must be
1250 // copied on write; and b) the flushing channel will close
1251 // when the goroutine finishes, whether it succeeds or not.
1252 flushing <-chan struct{}
1255 func (me *memSegment) flushingUnfinished() bool {
1256 if me.flushing == nil {
1268 func (me *memSegment) Len() int {
1272 func (me *memSegment) Slice(off, length int) segment {
1274 length = len(me.buf) - off
1276 buf := make([]byte, length)
1277 copy(buf, me.buf[off:])
1278 return &memSegment{buf: buf}
1281 func (me *memSegment) Truncate(n int) {
1282 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1285 newsize = newsize << 2
1287 newbuf := make([]byte, n, newsize)
1288 copy(newbuf, me.buf)
1289 me.buf, me.flushing = newbuf, nil
1291 // reclaim existing capacity, and zero reclaimed part
1292 oldlen := len(me.buf)
1294 for i := oldlen; i < n; i++ {
1300 func (me *memSegment) WriteAt(p []byte, off int) {
1301 if off+len(p) > len(me.buf) {
1302 panic("overflowed segment")
1304 if me.flushing != nil {
1305 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1307 copy(me.buf[off:], p)
1310 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1311 if off > int64(me.Len()) {
1315 n = copy(p, me.buf[int(off):])
1322 type storedSegment struct {
1325 size int // size of stored block (also encoded in locator)
1326 offset int // position of segment within the stored block
1327 length int // bytes in this segment (offset + length <= size)
1330 func (se storedSegment) Len() int {
1334 func (se storedSegment) Slice(n, size int) segment {
1337 if size >= 0 && se.length > size {
1343 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1344 if off > int64(se.length) {
1347 maxlen := se.length - int(off)
1348 if len(p) > maxlen {
1350 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1356 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1359 func canonicalName(name string) string {
1360 name = path.Clean("/" + name)
1361 if name == "/" || name == "./" {
1363 } else if strings.HasPrefix(name, "/") {
1369 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1371 func manifestUnescapeFunc(seq string) string {
1375 i, err := strconv.ParseUint(seq[1:], 8, 8)
1377 // Invalid escape sequence: can't unescape.
1380 return string([]byte{byte(i)})
1383 func manifestUnescape(s string) string {
1384 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1387 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1389 func manifestEscapeFunc(seq string) string {
1390 return fmt.Sprintf("\\%03o", byte(seq[0]))
1393 func manifestEscape(s string) string {
1394 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)