1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
23 maxBlockSize = 1 << 26
24 concurrentWriters = 4 // max goroutines writing to Keep in background and during flush()
27 // A CollectionFileSystem is a FileSystem that can be serialized as a
28 // manifest and stored as a collection.
29 type CollectionFileSystem interface {
32 // Flush all file data to Keep and return a snapshot of the
33 // filesystem suitable for saving as (Collection)ManifestText.
34 // Prefix (normally ".") is a top level directory, effectively
35 // prepended to all paths in the returned manifest.
36 MarshalManifest(prefix string) (string, error)
38 // Total data bytes in all files.
41 // Memory consumed by buffered file data.
45 type collectionFileSystem struct {
50 // FileSystem returns a CollectionFileSystem for the collection.
51 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
53 if c.ModifiedAt == nil {
56 modTime = *c.ModifiedAt
58 fs := &collectionFileSystem{
60 fileSystem: fileSystem{
61 fsBackend: keepBackend{apiClient: client, keepClient: kc},
62 thr: newThrottle(concurrentWriters),
70 mode: os.ModeDir | 0755,
73 inodes: make(map[string]inode),
76 root.SetParent(root, ".")
77 if err := root.loadManifest(c.ManifestText); err != nil {
80 backdateTree(root, modTime)
85 func backdateTree(n inode, modTime time.Time) {
86 switch n := n.(type) {
88 n.fileinfo.modTime = modTime
90 n.fileinfo.modTime = modTime
91 for _, n := range n.inodes {
92 backdateTree(n, modTime)
97 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
98 if name == "" || name == "." || name == ".." {
99 return nil, ErrInvalidArgument
107 mode: perm | os.ModeDir,
110 inodes: make(map[string]inode),
118 mode: perm & ^os.ModeDir,
125 func (fs *collectionFileSystem) Sync() error {
129 txt, err := fs.MarshalManifest(".")
131 return fmt.Errorf("sync failed: %s", err)
137 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
138 "collection": map[string]string{
139 "manifest_text": coll.ManifestText,
141 "select": []string{"uuid"},
144 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
149 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
150 node, err := rlookup(fs.fileSystem.root, path)
154 dn, ok := node.(*dirnode)
156 return ErrNotADirectory
160 names := dn.sortedNames()
162 // Caller only wants to flush the specified dir,
163 // non-recursively. Drop subdirs from the list of
165 var filenames []string
166 for _, name := range names {
167 if _, ok := dn.inodes[name].(*filenode); ok {
168 filenames = append(filenames, name)
173 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
176 func (fs *collectionFileSystem) memorySize() int64 {
177 fs.fileSystem.root.Lock()
178 defer fs.fileSystem.root.Unlock()
179 return fs.fileSystem.root.(*dirnode).memorySize()
182 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
183 fs.fileSystem.root.Lock()
184 defer fs.fileSystem.root.Unlock()
185 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
188 func (fs *collectionFileSystem) Size() int64 {
189 return fs.fileSystem.root.(*dirnode).TreeSize()
192 // filenodePtr is an offset into a file that is (usually) efficient to
193 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
195 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
196 // corresponds to file offset filenodePtr.off. Otherwise, it is
197 // necessary to reexamine len(filenode.segments[0]) etc. to find the
198 // correct segment and offset.
199 type filenodePtr struct {
206 // seek returns a ptr that is consistent with both startPtr.off and
207 // the current state of fn. The caller must already hold fn.RLock() or
210 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
215 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
217 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
218 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
221 // meaningless anyway
223 } else if ptr.off >= fn.fileinfo.size {
224 ptr.segmentIdx = len(fn.segments)
226 ptr.repacked = fn.repacked
228 } else if ptr.repacked == fn.repacked {
229 // segmentIdx and segmentOff accurately reflect
230 // ptr.off, but might have fallen off the end of a
232 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
239 ptr.repacked = fn.repacked
241 if ptr.off >= fn.fileinfo.size {
242 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
245 // Recompute segmentIdx and segmentOff. We have already
246 // established fn.fileinfo.size > ptr.off >= 0, so we don't
247 // have to deal with edge cases here.
249 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
250 // This would panic (index out of range) if
251 // fn.fileinfo.size were larger than
252 // sum(fn.segments[i].Len()) -- but that can't happen
253 // because we have ensured fn.fileinfo.size is always
255 segLen := int64(fn.segments[ptr.segmentIdx].Len())
256 if off+segLen > ptr.off {
257 ptr.segmentOff = int(ptr.off - off)
265 // filenode implements inode.
266 type filenode struct {
271 // number of times `segments` has changed in a
272 // way that might invalidate a filenodePtr
274 memsize int64 // bytes in memSegments
279 // caller must have lock
280 func (fn *filenode) appendSegment(e segment) {
281 fn.segments = append(fn.segments, e)
282 fn.fileinfo.size += int64(e.Len())
285 func (fn *filenode) SetParent(p inode, name string) {
289 fn.fileinfo.name = name
292 func (fn *filenode) Parent() inode {
298 func (fn *filenode) FS() FileSystem {
302 // Read reads file data from a single segment, starting at startPtr,
303 // into p. startPtr is assumed not to be up-to-date. Caller must have
305 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
306 ptr = fn.seek(startPtr)
308 err = ErrNegativeOffset
311 if ptr.segmentIdx >= len(fn.segments) {
315 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
319 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
322 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
330 func (fn *filenode) Size() int64 {
333 return fn.fileinfo.Size()
336 func (fn *filenode) FileInfo() os.FileInfo {
342 func (fn *filenode) Truncate(size int64) error {
345 return fn.truncate(size)
348 func (fn *filenode) truncate(size int64) error {
349 if size == fn.fileinfo.size {
353 if size < fn.fileinfo.size {
354 ptr := fn.seek(filenodePtr{off: size})
355 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
356 if seg, ok := fn.segments[i].(*memSegment); ok {
357 fn.memsize -= int64(seg.Len())
360 if ptr.segmentOff == 0 {
361 fn.segments = fn.segments[:ptr.segmentIdx]
363 fn.segments = fn.segments[:ptr.segmentIdx+1]
364 switch seg := fn.segments[ptr.segmentIdx].(type) {
366 seg.Truncate(ptr.segmentOff)
367 fn.memsize += int64(seg.Len())
369 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
372 fn.fileinfo.size = size
375 for size > fn.fileinfo.size {
376 grow := size - fn.fileinfo.size
379 if len(fn.segments) == 0 {
381 fn.segments = append(fn.segments, seg)
382 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
384 fn.segments = append(fn.segments, seg)
386 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
389 seg.Truncate(seg.Len() + int(grow))
390 fn.fileinfo.size += grow
396 // Write writes data from p to the file, starting at startPtr,
397 // extending the file size if necessary. Caller must have Lock.
398 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
399 if startPtr.off > fn.fileinfo.size {
400 if err = fn.truncate(startPtr.off); err != nil {
401 return 0, startPtr, err
404 ptr = fn.seek(startPtr)
406 err = ErrNegativeOffset
409 for len(p) > 0 && err == nil {
411 if len(cando) > maxBlockSize {
412 cando = cando[:maxBlockSize]
414 // Rearrange/grow fn.segments (and shrink cando if
415 // needed) such that cando can be copied to
416 // fn.segments[ptr.segmentIdx] at offset
418 cur := ptr.segmentIdx
419 prev := ptr.segmentIdx - 1
421 if cur < len(fn.segments) {
422 _, curWritable = fn.segments[cur].(*memSegment)
424 var prevAppendable bool
425 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
426 _, prevAppendable = fn.segments[prev].(*memSegment)
428 if ptr.segmentOff > 0 && !curWritable {
429 // Split a non-writable block.
430 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
431 // Truncate cur, and insert a new
434 fn.segments = append(fn.segments, nil)
435 copy(fn.segments[cur+1:], fn.segments[cur:])
437 // Split cur into two copies, truncate
438 // the one on the left, shift the one
439 // on the right, and insert a new
440 // segment between them.
441 fn.segments = append(fn.segments, nil, nil)
442 copy(fn.segments[cur+2:], fn.segments[cur:])
443 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
448 seg.Truncate(len(cando))
449 fn.memsize += int64(len(cando))
450 fn.segments[cur] = seg
451 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
456 } else if curWritable {
457 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
462 // Shrink cando if needed to fit in
464 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
465 cando = cando[:cangrow]
469 if cur == len(fn.segments) {
470 // ptr is at EOF, filesize is changing.
471 fn.fileinfo.size += int64(len(cando))
472 } else if el := fn.segments[cur].Len(); el <= len(cando) {
473 // cando is long enough that we won't
474 // need cur any more. shrink cando to
475 // be exactly as long as cur
476 // (otherwise we'd accidentally shift
477 // the effective position of all
478 // segments after cur).
480 copy(fn.segments[cur:], fn.segments[cur+1:])
481 fn.segments = fn.segments[:len(fn.segments)-1]
483 // shrink cur by the same #bytes we're growing prev
484 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
490 ptr.segmentOff = fn.segments[prev].Len()
491 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
492 fn.memsize += int64(len(cando))
496 // Insert a segment between prev and
497 // cur, and advance prev/cur.
498 fn.segments = append(fn.segments, nil)
499 if cur < len(fn.segments) {
500 copy(fn.segments[cur+1:], fn.segments[cur:])
504 // appending a new segment does
505 // not invalidate any ptrs
508 seg.Truncate(len(cando))
509 fn.memsize += int64(len(cando))
510 fn.segments[cur] = seg
516 // Finally we can copy bytes from cando to the current segment.
517 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
521 ptr.off += int64(len(cando))
522 ptr.segmentOff += len(cando)
523 if ptr.segmentOff >= maxBlockSize {
524 fn.pruneMemSegments()
526 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
531 fn.fileinfo.modTime = time.Now()
536 // Write some data out to disk to reduce memory use. Caller must have
538 func (fn *filenode) pruneMemSegments() {
539 // TODO: share code with (*dirnode)flush()
540 // TODO: pack/flush small blocks too, when fragmented
541 for idx, seg := range fn.segments {
542 seg, ok := seg.(*memSegment)
543 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
546 // Setting seg.flushing guarantees seg.buf will not be
547 // modified in place: WriteAt and Truncate will
548 // allocate a new buf instead, if necessary.
549 idx, buf := idx, seg.buf
550 done := make(chan struct{})
552 // If lots of background writes are already in
553 // progress, block here until one finishes, rather
554 // than pile up an unlimited number of buffered writes
555 // and network flush operations.
556 fn.fs.throttle().Acquire()
559 locator, _, err := fn.FS().PutB(buf)
560 fn.fs.throttle().Release()
563 if seg.flushing != done {
564 // A new seg.buf has been allocated.
569 // TODO: stall (or return errors from)
570 // subsequent writes until flushing
571 // starts to succeed.
574 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
575 // Segment has been dropped/moved/resized.
578 fn.memsize -= int64(len(buf))
579 fn.segments[idx] = storedSegment{
590 // Block until all pending pruneMemSegments/flush work is
591 // finished. Caller must NOT have lock.
592 func (fn *filenode) waitPrune() {
593 var pending []<-chan struct{}
595 for _, seg := range fn.segments {
596 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
597 pending = append(pending, seg.flushing)
601 for _, p := range pending {
606 type dirnode struct {
607 fs *collectionFileSystem
611 func (dn *dirnode) FS() FileSystem {
615 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
616 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
617 gn := &getternode{Getter: func() ([]byte, error) {
620 coll.ManifestText, err = dn.fs.MarshalManifest(".")
624 data, err := json.Marshal(&coll)
626 data = append(data, '\n')
630 gn.SetParent(dn, name)
633 return dn.treenode.Child(name, replace)
636 type fnSegmentRef struct {
641 // commitBlock concatenates the data from the given filenode segments
642 // (which must be *memSegments), writes the data out to Keep as a
643 // single block, and replaces the filenodes' *memSegments with
644 // storedSegments that reference the relevant portions of the new
647 // If sync is false, commitBlock returns right away, after starting a
648 // goroutine to do the writes, reacquire the filenodes' locks, and
649 // swap out the *memSegments. Some filenodes' segments might get
650 // modified/rearranged in the meantime, in which case commitBlock
651 // won't replace them.
653 // Caller must have write lock.
654 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, sync bool) error {
655 if err := ctx.Err(); err != nil {
658 done := make(chan struct{})
659 block := make([]byte, 0, maxBlockSize)
660 segs := make([]*memSegment, 0, len(refs))
661 offsets := make([]int, 0, len(refs)) // location of segment's data within block
662 for _, ref := range refs {
663 seg := ref.fn.segments[ref.idx].(*memSegment)
664 if seg.flushing != nil && !sync {
665 // Let the other flushing goroutine finish. If
666 // it fails, we'll try again next time.
669 // In sync mode, we proceed regardless of
670 // whether another flush is in progress: It
671 // can't finish before we do, because we hold
672 // fn's lock until we finish our own writes.
675 offsets = append(offsets, len(block))
676 block = append(block, seg.buf...)
677 segs = append(segs, seg)
679 dn.fs.throttle().Acquire()
680 errs := make(chan error, 1)
684 locked := map[*filenode]bool{}
685 locator, _, err := dn.fs.PutB(block)
686 dn.fs.throttle().Release()
689 for _, name := range dn.sortedNames() {
690 if fn, ok := dn.inodes[name].(*filenode); ok {
698 for _, seg := range segs {
699 if seg.flushing == done {
709 for idx, ref := range refs {
711 // In async mode, fn's lock was
712 // released while we were waiting for
713 // PutB(); lots of things might have
715 if len(ref.fn.segments) <= ref.idx {
716 // file segments have
717 // rearranged or changed in
720 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
721 // segment has been replaced
723 } else if seg.flushing != done {
724 // seg.buf has been replaced
726 } else if !locked[ref.fn] {
727 // file was renamed, moved, or
728 // deleted since we called
733 data := ref.fn.segments[ref.idx].(*memSegment).buf
734 ref.fn.segments[ref.idx] = storedSegment{
738 offset: offsets[idx],
741 ref.fn.memsize -= int64(len(data))
751 type flushOpts struct {
756 // flush in-memory data and remote-cluster block references (for the
757 // children with the given names, which must be children of dn) to
758 // local-cluster persistent storage.
760 // Caller must have write lock on dn and the named children.
762 // If any children are dirs, they will be flushed recursively.
763 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
764 cg := newContextGroup(ctx)
767 goCommit := func(refs []fnSegmentRef) {
772 return dn.commitBlock(cg.Context(), refs, opts.sync)
776 var pending []fnSegmentRef
777 var pendingLen int = 0
778 localLocator := map[string]string{}
779 for _, name := range names {
780 switch node := dn.inodes[name].(type) {
782 grandchildNames := node.sortedNames()
783 for _, grandchildName := range grandchildNames {
784 grandchild := node.inodes[grandchildName]
786 defer grandchild.Unlock()
788 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
790 for idx, seg := range node.segments {
791 switch seg := seg.(type) {
793 loc, ok := localLocator[seg.locator]
796 loc, err = dn.fs.LocalLocator(seg.locator)
800 localLocator[seg.locator] = loc
803 node.segments[idx] = seg
805 if seg.Len() > maxBlockSize/2 {
806 goCommit([]fnSegmentRef{{node, idx}})
809 if pendingLen+seg.Len() > maxBlockSize {
814 pending = append(pending, fnSegmentRef{node, idx})
815 pendingLen += seg.Len()
817 panic(fmt.Sprintf("can't sync segment type %T", seg))
822 if opts.shortBlocks {
828 // caller must have write lock.
829 func (dn *dirnode) memorySize() (size int64) {
830 for _, name := range dn.sortedNames() {
831 node := dn.inodes[name]
834 switch node := node.(type) {
836 size += node.memorySize()
838 for _, seg := range node.segments {
839 switch seg := seg.(type) {
841 size += int64(seg.Len())
849 // caller must have write lock.
850 func (dn *dirnode) sortedNames() []string {
851 names := make([]string, 0, len(dn.inodes))
852 for name := range dn.inodes {
853 names = append(names, name)
859 // caller must have write lock.
860 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
861 cg := newContextGroup(ctx)
864 if len(dn.inodes) == 0 {
868 // Express the existence of an empty directory by
869 // adding an empty file named `\056`, which (unlike
870 // the more obvious spelling `.`) is accepted by the
871 // API's manifest validator.
872 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
875 names := dn.sortedNames()
877 // Wait for children to finish any pending write operations
878 // before locking them.
879 for _, name := range names {
880 node := dn.inodes[name]
881 if fn, ok := node.(*filenode); ok {
886 var dirnames []string
887 var filenames []string
888 for _, name := range names {
889 node := dn.inodes[name]
892 switch node := node.(type) {
894 dirnames = append(dirnames, name)
896 filenames = append(filenames, name)
898 panic(fmt.Sprintf("can't marshal inode type %T", node))
902 subdirs := make([]string, len(dirnames))
904 for i, name := range dirnames {
907 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
915 type filepart struct {
921 var fileparts []filepart
923 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
926 for _, name := range filenames {
927 node := dn.inodes[name].(*filenode)
928 if len(node.segments) == 0 {
929 fileparts = append(fileparts, filepart{name: name})
932 for _, seg := range node.segments {
933 switch seg := seg.(type) {
935 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
936 streamLen -= int64(seg.size)
938 blocks = append(blocks, seg.locator)
942 offset: streamLen + int64(seg.offset),
943 length: int64(seg.length),
945 if prev := len(fileparts) - 1; prev >= 0 &&
946 fileparts[prev].name == name &&
947 fileparts[prev].offset+fileparts[prev].length == next.offset {
948 fileparts[prev].length += next.length
950 fileparts = append(fileparts, next)
952 streamLen += int64(seg.size)
954 // This can't happen: we
955 // haven't unlocked since
956 // calling flush(sync=true).
957 panic(fmt.Sprintf("can't marshal segment type %T", seg))
961 var filetokens []string
962 for _, s := range fileparts {
963 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
965 if len(filetokens) == 0 {
967 } else if len(blocks) == 0 {
968 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
970 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
974 return rootdir + strings.Join(subdirs, ""), err
977 func (dn *dirnode) loadManifest(txt string) error {
979 streams := strings.Split(txt, "\n")
980 if streams[len(streams)-1] != "" {
981 return fmt.Errorf("line %d: no trailing newline", len(streams))
983 streams = streams[:len(streams)-1]
984 segments := []storedSegment{}
985 for i, stream := range streams {
987 var anyFileTokens bool
990 segments = segments[:0]
991 for i, token := range strings.Split(stream, " ") {
993 dirname = manifestUnescape(token)
996 if !strings.Contains(token, ":") {
998 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1000 toks := strings.SplitN(token, "+", 3)
1002 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1004 length, err := strconv.ParseInt(toks[1], 10, 32)
1005 if err != nil || length < 0 {
1006 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1008 segments = append(segments, storedSegment{
1012 length: int(length),
1015 } else if len(segments) == 0 {
1016 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1019 toks := strings.SplitN(token, ":", 3)
1021 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1023 anyFileTokens = true
1025 offset, err := strconv.ParseInt(toks[0], 10, 64)
1026 if err != nil || offset < 0 {
1027 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1029 length, err := strconv.ParseInt(toks[1], 10, 64)
1030 if err != nil || length < 0 {
1031 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1033 name := dirname + "/" + manifestUnescape(toks[2])
1034 fnode, err := dn.createFileAndParents(name)
1035 if fnode == nil && err == nil && length == 0 {
1036 // Special case: an empty file used as
1037 // a marker to preserve an otherwise
1038 // empty directory in a manifest.
1041 if err != nil || (fnode == nil && length != 0) {
1042 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1044 // Map the stream offset/range coordinates to
1045 // block/offset/range coordinates and add
1046 // corresponding storedSegments to the filenode
1048 // Can't continue where we left off.
1049 // TODO: binary search instead of
1050 // rewinding all the way (but this
1051 // situation might be rare anyway)
1054 for next := int64(0); segIdx < len(segments); segIdx++ {
1055 seg := segments[segIdx]
1056 next = pos + int64(seg.Len())
1057 if next <= offset || seg.Len() == 0 {
1061 if pos >= offset+length {
1066 blkOff = int(offset - pos)
1068 blkLen := seg.Len() - blkOff
1069 if pos+int64(blkOff+blkLen) > offset+length {
1070 blkLen = int(offset + length - pos - int64(blkOff))
1072 fnode.appendSegment(storedSegment{
1074 locator: seg.locator,
1079 if next > offset+length {
1085 if segIdx == len(segments) && pos < offset+length {
1086 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1090 return fmt.Errorf("line %d: no file segments", lineno)
1091 } else if len(segments) == 0 {
1092 return fmt.Errorf("line %d: no locators", lineno)
1093 } else if dirname == "" {
1094 return fmt.Errorf("line %d: no stream name", lineno)
1100 // only safe to call from loadManifest -- no locking.
1102 // If path is a "parent directory exists" marker (the last path
1103 // component is "."), the returned values are both nil.
1104 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1106 names := strings.Split(path, "/")
1107 basename := names[len(names)-1]
1108 for _, name := range names[:len(names)-1] {
1114 // can't be sure parent will be a *dirnode
1115 return nil, ErrInvalidArgument
1117 node = node.Parent()
1120 node, err = node.Child(name, func(child inode) (inode, error) {
1122 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1126 child.SetParent(node, name)
1128 } else if !child.IsDir() {
1129 return child, ErrFileExists
1138 if basename == "." {
1140 } else if !permittedName(basename) {
1141 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1144 _, err = node.Child(basename, func(child inode) (inode, error) {
1145 switch child := child.(type) {
1147 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1151 child.SetParent(node, basename)
1152 fn = child.(*filenode)
1158 return child, ErrIsDirectory
1160 return child, ErrInvalidArgument
1166 func (dn *dirnode) TreeSize() (bytes int64) {
1169 for _, i := range dn.inodes {
1170 switch i := i.(type) {
1174 bytes += i.TreeSize()
1180 type segment interface {
1183 // Return a new segment with a subsection of the data from this
1184 // one. length<0 means length=Len()-off.
1185 Slice(off int, length int) segment
1188 type memSegment struct {
1190 // If flushing is not nil, then a) buf is being shared by a
1191 // pruneMemSegments goroutine, and must be copied on write;
1192 // and b) the flushing channel will close when the goroutine
1193 // finishes, whether it succeeds or not.
1194 flushing <-chan struct{}
1197 func (me *memSegment) Len() int {
1201 func (me *memSegment) Slice(off, length int) segment {
1203 length = len(me.buf) - off
1205 buf := make([]byte, length)
1206 copy(buf, me.buf[off:])
1207 return &memSegment{buf: buf}
1210 func (me *memSegment) Truncate(n int) {
1211 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1214 newsize = newsize << 2
1216 newbuf := make([]byte, n, newsize)
1217 copy(newbuf, me.buf)
1218 me.buf, me.flushing = newbuf, nil
1220 // reclaim existing capacity, and zero reclaimed part
1221 oldlen := len(me.buf)
1223 for i := oldlen; i < n; i++ {
1229 func (me *memSegment) WriteAt(p []byte, off int) {
1230 if off+len(p) > len(me.buf) {
1231 panic("overflowed segment")
1233 if me.flushing != nil {
1234 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1236 copy(me.buf[off:], p)
1239 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1240 if off > int64(me.Len()) {
1244 n = copy(p, me.buf[int(off):])
1251 type storedSegment struct {
1254 size int // size of stored block (also encoded in locator)
1255 offset int // position of segment within the stored block
1256 length int // bytes in this segment (offset + length <= size)
1259 func (se storedSegment) Len() int {
1263 func (se storedSegment) Slice(n, size int) segment {
1266 if size >= 0 && se.length > size {
1272 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1273 if off > int64(se.length) {
1276 maxlen := se.length - int(off)
1277 if len(p) > maxlen {
1279 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1285 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1288 func canonicalName(name string) string {
1289 name = path.Clean("/" + name)
1290 if name == "/" || name == "./" {
1292 } else if strings.HasPrefix(name, "/") {
1298 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1300 func manifestUnescapeFunc(seq string) string {
1304 i, err := strconv.ParseUint(seq[1:], 8, 8)
1306 // Invalid escape sequence: can't unescape.
1309 return string([]byte{byte(i)})
1312 func manifestUnescape(s string) string {
1313 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1316 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1318 func manifestEscapeFunc(seq string) string {
1319 return fmt.Sprintf("\\%03o", byte(seq[0]))
1322 func manifestEscape(s string) string {
1323 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)