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 during flush()
25 writeAheadBlocks = 1 // max background jobs flushing to Keep before blocking writes
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) {
54 if c.ModifiedAt == nil {
57 modTime = *c.ModifiedAt
59 fs := &collectionFileSystem{
61 fileSystem: fileSystem{
62 fsBackend: keepBackend{apiClient: client, keepClient: kc},
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(shortBlocks bool) error {
150 fs.fileSystem.root.Lock()
151 defer fs.fileSystem.root.Unlock()
152 dn := fs.fileSystem.root.(*dirnode)
153 return dn.flush(context.TODO(), newThrottle(concurrentWriters), dn.sortedNames(), flushOpts{sync: false, shortBlocks: shortBlocks})
156 func (fs *collectionFileSystem) memorySize() int64 {
157 fs.fileSystem.root.Lock()
158 defer fs.fileSystem.root.Unlock()
159 return fs.fileSystem.root.(*dirnode).memorySize()
162 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
163 fs.fileSystem.root.Lock()
164 defer fs.fileSystem.root.Unlock()
165 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix, newThrottle(concurrentWriters))
168 func (fs *collectionFileSystem) Size() int64 {
169 return fs.fileSystem.root.(*dirnode).TreeSize()
172 // filenodePtr is an offset into a file that is (usually) efficient to
173 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
175 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
176 // corresponds to file offset filenodePtr.off. Otherwise, it is
177 // necessary to reexamine len(filenode.segments[0]) etc. to find the
178 // correct segment and offset.
179 type filenodePtr struct {
186 // seek returns a ptr that is consistent with both startPtr.off and
187 // the current state of fn. The caller must already hold fn.RLock() or
190 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
195 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
197 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
198 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
201 // meaningless anyway
203 } else if ptr.off >= fn.fileinfo.size {
204 ptr.segmentIdx = len(fn.segments)
206 ptr.repacked = fn.repacked
208 } else if ptr.repacked == fn.repacked {
209 // segmentIdx and segmentOff accurately reflect
210 // ptr.off, but might have fallen off the end of a
212 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
219 ptr.repacked = fn.repacked
221 if ptr.off >= fn.fileinfo.size {
222 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
225 // Recompute segmentIdx and segmentOff. We have already
226 // established fn.fileinfo.size > ptr.off >= 0, so we don't
227 // have to deal with edge cases here.
229 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
230 // This would panic (index out of range) if
231 // fn.fileinfo.size were larger than
232 // sum(fn.segments[i].Len()) -- but that can't happen
233 // because we have ensured fn.fileinfo.size is always
235 segLen := int64(fn.segments[ptr.segmentIdx].Len())
236 if off+segLen > ptr.off {
237 ptr.segmentOff = int(ptr.off - off)
245 // filenode implements inode.
246 type filenode struct {
251 // number of times `segments` has changed in a
252 // way that might invalidate a filenodePtr
254 memsize int64 // bytes in memSegments
260 // caller must have lock
261 func (fn *filenode) appendSegment(e segment) {
262 fn.segments = append(fn.segments, e)
263 fn.fileinfo.size += int64(e.Len())
266 func (fn *filenode) SetParent(p inode, name string) {
270 fn.fileinfo.name = name
273 func (fn *filenode) Parent() inode {
279 func (fn *filenode) FS() FileSystem {
283 // Read reads file data from a single segment, starting at startPtr,
284 // into p. startPtr is assumed not to be up-to-date. Caller must have
286 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
287 ptr = fn.seek(startPtr)
289 err = ErrNegativeOffset
292 if ptr.segmentIdx >= len(fn.segments) {
296 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
300 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
303 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
311 func (fn *filenode) Size() int64 {
314 return fn.fileinfo.Size()
317 func (fn *filenode) FileInfo() os.FileInfo {
323 func (fn *filenode) Truncate(size int64) error {
326 return fn.truncate(size)
329 func (fn *filenode) truncate(size int64) error {
330 if size == fn.fileinfo.size {
334 if size < fn.fileinfo.size {
335 ptr := fn.seek(filenodePtr{off: size})
336 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
337 if seg, ok := fn.segments[i].(*memSegment); ok {
338 fn.memsize -= int64(seg.Len())
341 if ptr.segmentOff == 0 {
342 fn.segments = fn.segments[:ptr.segmentIdx]
344 fn.segments = fn.segments[:ptr.segmentIdx+1]
345 switch seg := fn.segments[ptr.segmentIdx].(type) {
347 seg.Truncate(ptr.segmentOff)
348 fn.memsize += int64(seg.Len())
350 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
353 fn.fileinfo.size = size
356 for size > fn.fileinfo.size {
357 grow := size - fn.fileinfo.size
360 if len(fn.segments) == 0 {
362 fn.segments = append(fn.segments, seg)
363 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
365 fn.segments = append(fn.segments, seg)
367 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
370 seg.Truncate(seg.Len() + int(grow))
371 fn.fileinfo.size += grow
377 // Write writes data from p to the file, starting at startPtr,
378 // extending the file size if necessary. Caller must have Lock.
379 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
380 if startPtr.off > fn.fileinfo.size {
381 if err = fn.truncate(startPtr.off); err != nil {
382 return 0, startPtr, err
385 ptr = fn.seek(startPtr)
387 err = ErrNegativeOffset
390 for len(p) > 0 && err == nil {
392 if len(cando) > maxBlockSize {
393 cando = cando[:maxBlockSize]
395 // Rearrange/grow fn.segments (and shrink cando if
396 // needed) such that cando can be copied to
397 // fn.segments[ptr.segmentIdx] at offset
399 cur := ptr.segmentIdx
400 prev := ptr.segmentIdx - 1
402 if cur < len(fn.segments) {
403 _, curWritable = fn.segments[cur].(*memSegment)
405 var prevAppendable bool
406 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
407 _, prevAppendable = fn.segments[prev].(*memSegment)
409 if ptr.segmentOff > 0 && !curWritable {
410 // Split a non-writable block.
411 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
412 // Truncate cur, and insert a new
415 fn.segments = append(fn.segments, nil)
416 copy(fn.segments[cur+1:], fn.segments[cur:])
418 // Split cur into two copies, truncate
419 // the one on the left, shift the one
420 // on the right, and insert a new
421 // segment between them.
422 fn.segments = append(fn.segments, nil, nil)
423 copy(fn.segments[cur+2:], fn.segments[cur:])
424 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
429 seg.Truncate(len(cando))
430 fn.memsize += int64(len(cando))
431 fn.segments[cur] = seg
432 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
437 } else if curWritable {
438 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
443 // Shrink cando if needed to fit in
445 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
446 cando = cando[:cangrow]
450 if cur == len(fn.segments) {
451 // ptr is at EOF, filesize is changing.
452 fn.fileinfo.size += int64(len(cando))
453 } else if el := fn.segments[cur].Len(); el <= len(cando) {
454 // cando is long enough that we won't
455 // need cur any more. shrink cando to
456 // be exactly as long as cur
457 // (otherwise we'd accidentally shift
458 // the effective position of all
459 // segments after cur).
461 copy(fn.segments[cur:], fn.segments[cur+1:])
462 fn.segments = fn.segments[:len(fn.segments)-1]
464 // shrink cur by the same #bytes we're growing prev
465 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
471 ptr.segmentOff = fn.segments[prev].Len()
472 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
473 fn.memsize += int64(len(cando))
477 // Insert a segment between prev and
478 // cur, and advance prev/cur.
479 fn.segments = append(fn.segments, nil)
480 if cur < len(fn.segments) {
481 copy(fn.segments[cur+1:], fn.segments[cur:])
485 // appending a new segment does
486 // not invalidate any ptrs
489 seg.Truncate(len(cando))
490 fn.memsize += int64(len(cando))
491 fn.segments[cur] = seg
497 // Finally we can copy bytes from cando to the current segment.
498 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
502 ptr.off += int64(len(cando))
503 ptr.segmentOff += len(cando)
504 if ptr.segmentOff >= maxBlockSize {
505 fn.pruneMemSegments()
507 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
512 fn.fileinfo.modTime = time.Now()
517 // Write some data out to disk to reduce memory use. Caller must have
519 func (fn *filenode) pruneMemSegments() {
520 // TODO: share code with (*dirnode)flush()
521 // TODO: pack/flush small blocks too, when fragmented
522 if fn.throttle == nil {
523 // TODO: share a throttle with filesystem
524 fn.throttle = newThrottle(writeAheadBlocks)
526 for idx, seg := range fn.segments {
527 seg, ok := seg.(*memSegment)
528 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
531 // Setting seg.flushing guarantees seg.buf will not be
532 // modified in place: WriteAt and Truncate will
533 // allocate a new buf instead, if necessary.
534 idx, buf := idx, seg.buf
535 done := make(chan struct{})
537 // If lots of background writes are already in
538 // progress, block here until one finishes, rather
539 // than pile up an unlimited number of buffered writes
540 // and network flush operations.
541 fn.throttle.Acquire()
544 locator, _, err := fn.FS().PutB(buf)
545 fn.throttle.Release()
548 if seg.flushing != done {
549 // A new seg.buf has been allocated.
554 // TODO: stall (or return errors from)
555 // subsequent writes until flushing
556 // starts to succeed.
559 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
560 // Segment has been dropped/moved/resized.
563 fn.memsize -= int64(len(buf))
564 fn.segments[idx] = storedSegment{
575 // Block until all pending pruneMemSegments/flush work is
576 // finished. Caller must NOT have lock.
577 func (fn *filenode) waitPrune() {
578 var pending []<-chan struct{}
580 for _, seg := range fn.segments {
581 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
582 pending = append(pending, seg.flushing)
586 for _, p := range pending {
591 type dirnode struct {
592 fs *collectionFileSystem
596 func (dn *dirnode) FS() FileSystem {
600 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
601 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
602 gn := &getternode{Getter: func() ([]byte, error) {
605 coll.ManifestText, err = dn.fs.MarshalManifest(".")
609 data, err := json.Marshal(&coll)
611 data = append(data, '\n')
615 gn.SetParent(dn, name)
618 return dn.treenode.Child(name, replace)
621 type fnSegmentRef struct {
626 // commitBlock concatenates the data from the given filenode segments
627 // (which must be *memSegments), writes the data out to Keep as a
628 // single block, and replaces the filenodes' *memSegments with
629 // storedSegments that reference the relevant portions of the new
632 // If sync is false, commitBlock returns right away, after starting a
633 // goroutine to do the writes, reacquire the filenodes' locks, and
634 // swap out the *memSegments. Some filenodes' segments might get
635 // modified/rearranged in the meantime, in which case commitBlock
636 // won't replace them.
638 // Caller must have write lock.
639 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, sync bool) error {
640 if err := ctx.Err(); err != nil {
643 done := make(chan struct{})
644 block := make([]byte, 0, maxBlockSize)
645 segs := make([]*memSegment, 0, len(refs))
646 offsets := make([]int, 0, len(refs)) // location of segment's data within block
647 for _, ref := range refs {
648 seg := ref.fn.segments[ref.idx].(*memSegment)
649 if seg.flushing != nil && !sync {
650 // Let the other flushing goroutine finish. If
651 // it fails, we'll try again next time.
654 // In sync mode, we proceed regardless of
655 // whether another flush is in progress: It
656 // can't finish before we do, because we hold
657 // fn's lock until we finish our own writes.
660 offsets = append(offsets, len(block))
661 block = append(block, seg.buf...)
662 segs = append(segs, seg)
664 errs := make(chan error, 1)
668 locked := map[*filenode]bool{}
669 locator, _, err := dn.fs.PutB(block)
672 for _, name := range dn.sortedNames() {
673 if fn, ok := dn.inodes[name].(*filenode); ok {
681 for _, seg := range segs {
682 if seg.flushing == done {
692 for idx, ref := range refs {
694 // In async mode, fn's lock was
695 // released while we were waiting for
696 // PutB(); lots of things might have
698 if len(ref.fn.segments) <= ref.idx {
699 // file segments have
700 // rearranged or changed in
703 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
704 // segment has been replaced
706 } else if seg.flushing != done {
707 // seg.buf has been replaced
709 } else if !locked[ref.fn] {
710 // file was renamed, moved, or
711 // deleted since we called
716 data := ref.fn.segments[ref.idx].(*memSegment).buf
717 ref.fn.segments[ref.idx] = storedSegment{
721 offset: offsets[idx],
724 ref.fn.memsize -= int64(len(data))
734 type flushOpts struct {
739 // flush in-memory data and remote-cluster block references (for the
740 // children with the given names, which must be children of dn) to
741 // local-cluster persistent storage.
743 // Caller must have write lock on dn and the named children.
745 // If any children are dirs, they will be flushed recursively.
746 func (dn *dirnode) flush(ctx context.Context, throttle *throttle, names []string, opts flushOpts) error {
747 cg := newContextGroup(ctx)
750 goCommit := func(refs []fnSegmentRef) {
756 defer throttle.Release()
757 return dn.commitBlock(cg.Context(), refs, opts.sync)
761 var pending []fnSegmentRef
762 var pendingLen int = 0
763 localLocator := map[string]string{}
764 for _, name := range names {
765 switch node := dn.inodes[name].(type) {
767 grandchildNames := node.sortedNames()
768 for _, grandchildName := range grandchildNames {
769 grandchild := node.inodes[grandchildName]
771 defer grandchild.Unlock()
773 cg.Go(func() error { return node.flush(cg.Context(), throttle, grandchildNames, opts) })
775 for idx, seg := range node.segments {
776 switch seg := seg.(type) {
778 loc, ok := localLocator[seg.locator]
781 loc, err = dn.fs.LocalLocator(seg.locator)
785 localLocator[seg.locator] = loc
788 node.segments[idx] = seg
790 if seg.Len() > maxBlockSize/2 {
791 goCommit([]fnSegmentRef{{node, idx}})
794 if pendingLen+seg.Len() > maxBlockSize {
799 pending = append(pending, fnSegmentRef{node, idx})
800 pendingLen += seg.Len()
802 panic(fmt.Sprintf("can't sync segment type %T", seg))
807 if opts.shortBlocks {
813 // caller must have write lock.
814 func (dn *dirnode) memorySize() (size int64) {
815 for _, name := range dn.sortedNames() {
816 node := dn.inodes[name]
819 switch node := node.(type) {
821 size += node.memorySize()
823 for _, seg := range node.segments {
824 switch seg := seg.(type) {
826 size += int64(seg.Len())
834 // caller must have write lock.
835 func (dn *dirnode) sortedNames() []string {
836 names := make([]string, 0, len(dn.inodes))
837 for name := range dn.inodes {
838 names = append(names, name)
844 // caller must have write lock.
845 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string, throttle *throttle) (string, error) {
846 cg := newContextGroup(ctx)
849 if len(dn.inodes) == 0 {
853 // Express the existence of an empty directory by
854 // adding an empty file named `\056`, which (unlike
855 // the more obvious spelling `.`) is accepted by the
856 // API's manifest validator.
857 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
860 names := dn.sortedNames()
862 // Wait for children to finish any pending write operations
863 // before locking them.
864 for _, name := range names {
865 node := dn.inodes[name]
866 if fn, ok := node.(*filenode); ok {
871 var dirnames []string
872 var filenames []string
873 for _, name := range names {
874 node := dn.inodes[name]
877 switch node := node.(type) {
879 dirnames = append(dirnames, name)
881 filenames = append(filenames, name)
883 panic(fmt.Sprintf("can't marshal inode type %T", node))
887 subdirs := make([]string, len(dirnames))
889 for i, name := range dirnames {
892 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name, throttle)
900 type filepart struct {
906 var fileparts []filepart
908 if err := dn.flush(cg.Context(), throttle, filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
911 for _, name := range filenames {
912 node := dn.inodes[name].(*filenode)
913 if len(node.segments) == 0 {
914 fileparts = append(fileparts, filepart{name: name})
917 for _, seg := range node.segments {
918 switch seg := seg.(type) {
920 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
921 streamLen -= int64(seg.size)
923 blocks = append(blocks, seg.locator)
927 offset: streamLen + int64(seg.offset),
928 length: int64(seg.length),
930 if prev := len(fileparts) - 1; prev >= 0 &&
931 fileparts[prev].name == name &&
932 fileparts[prev].offset+fileparts[prev].length == next.offset {
933 fileparts[prev].length += next.length
935 fileparts = append(fileparts, next)
937 streamLen += int64(seg.size)
939 // This can't happen: we
940 // haven't unlocked since
941 // calling flush(sync=true).
942 panic(fmt.Sprintf("can't marshal segment type %T", seg))
946 var filetokens []string
947 for _, s := range fileparts {
948 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
950 if len(filetokens) == 0 {
952 } else if len(blocks) == 0 {
953 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
955 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
959 return rootdir + strings.Join(subdirs, ""), err
962 func (dn *dirnode) loadManifest(txt string) error {
964 streams := strings.Split(txt, "\n")
965 if streams[len(streams)-1] != "" {
966 return fmt.Errorf("line %d: no trailing newline", len(streams))
968 streams = streams[:len(streams)-1]
969 segments := []storedSegment{}
970 for i, stream := range streams {
972 var anyFileTokens bool
975 segments = segments[:0]
976 for i, token := range strings.Split(stream, " ") {
978 dirname = manifestUnescape(token)
981 if !strings.Contains(token, ":") {
983 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
985 toks := strings.SplitN(token, "+", 3)
987 return fmt.Errorf("line %d: bad locator %q", lineno, token)
989 length, err := strconv.ParseInt(toks[1], 10, 32)
990 if err != nil || length < 0 {
991 return fmt.Errorf("line %d: bad locator %q", lineno, token)
993 segments = append(segments, storedSegment{
1000 } else if len(segments) == 0 {
1001 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1004 toks := strings.SplitN(token, ":", 3)
1006 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1008 anyFileTokens = true
1010 offset, err := strconv.ParseInt(toks[0], 10, 64)
1011 if err != nil || offset < 0 {
1012 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1014 length, err := strconv.ParseInt(toks[1], 10, 64)
1015 if err != nil || length < 0 {
1016 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1018 name := dirname + "/" + manifestUnescape(toks[2])
1019 fnode, err := dn.createFileAndParents(name)
1020 if fnode == nil && err == nil && length == 0 {
1021 // Special case: an empty file used as
1022 // a marker to preserve an otherwise
1023 // empty directory in a manifest.
1026 if err != nil || (fnode == nil && length != 0) {
1027 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1029 // Map the stream offset/range coordinates to
1030 // block/offset/range coordinates and add
1031 // corresponding storedSegments to the filenode
1033 // Can't continue where we left off.
1034 // TODO: binary search instead of
1035 // rewinding all the way (but this
1036 // situation might be rare anyway)
1039 for next := int64(0); segIdx < len(segments); segIdx++ {
1040 seg := segments[segIdx]
1041 next = pos + int64(seg.Len())
1042 if next <= offset || seg.Len() == 0 {
1046 if pos >= offset+length {
1051 blkOff = int(offset - pos)
1053 blkLen := seg.Len() - blkOff
1054 if pos+int64(blkOff+blkLen) > offset+length {
1055 blkLen = int(offset + length - pos - int64(blkOff))
1057 fnode.appendSegment(storedSegment{
1059 locator: seg.locator,
1064 if next > offset+length {
1070 if segIdx == len(segments) && pos < offset+length {
1071 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1075 return fmt.Errorf("line %d: no file segments", lineno)
1076 } else if len(segments) == 0 {
1077 return fmt.Errorf("line %d: no locators", lineno)
1078 } else if dirname == "" {
1079 return fmt.Errorf("line %d: no stream name", lineno)
1085 // only safe to call from loadManifest -- no locking.
1087 // If path is a "parent directory exists" marker (the last path
1088 // component is "."), the returned values are both nil.
1089 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1091 names := strings.Split(path, "/")
1092 basename := names[len(names)-1]
1093 for _, name := range names[:len(names)-1] {
1099 // can't be sure parent will be a *dirnode
1100 return nil, ErrInvalidArgument
1102 node = node.Parent()
1105 node, err = node.Child(name, func(child inode) (inode, error) {
1107 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1111 child.SetParent(node, name)
1113 } else if !child.IsDir() {
1114 return child, ErrFileExists
1123 if basename == "." {
1125 } else if !permittedName(basename) {
1126 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1129 _, err = node.Child(basename, func(child inode) (inode, error) {
1130 switch child := child.(type) {
1132 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1136 child.SetParent(node, basename)
1137 fn = child.(*filenode)
1143 return child, ErrIsDirectory
1145 return child, ErrInvalidArgument
1151 func (dn *dirnode) TreeSize() (bytes int64) {
1154 for _, i := range dn.inodes {
1155 switch i := i.(type) {
1159 bytes += i.TreeSize()
1165 type segment interface {
1168 // Return a new segment with a subsection of the data from this
1169 // one. length<0 means length=Len()-off.
1170 Slice(off int, length int) segment
1173 type memSegment struct {
1175 // If flushing is not nil, then a) buf is being shared by a
1176 // pruneMemSegments goroutine, and must be copied on write;
1177 // and b) the flushing channel will close when the goroutine
1178 // finishes, whether it succeeds or not.
1179 flushing <-chan struct{}
1182 func (me *memSegment) Len() int {
1186 func (me *memSegment) Slice(off, length int) segment {
1188 length = len(me.buf) - off
1190 buf := make([]byte, length)
1191 copy(buf, me.buf[off:])
1192 return &memSegment{buf: buf}
1195 func (me *memSegment) Truncate(n int) {
1196 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1199 newsize = newsize << 2
1201 newbuf := make([]byte, n, newsize)
1202 copy(newbuf, me.buf)
1203 me.buf, me.flushing = newbuf, nil
1205 // reclaim existing capacity, and zero reclaimed part
1206 oldlen := len(me.buf)
1208 for i := oldlen; i < n; i++ {
1214 func (me *memSegment) WriteAt(p []byte, off int) {
1215 if off+len(p) > len(me.buf) {
1216 panic("overflowed segment")
1218 if me.flushing != nil {
1219 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1221 copy(me.buf[off:], p)
1224 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1225 if off > int64(me.Len()) {
1229 n = copy(p, me.buf[int(off):])
1236 type storedSegment struct {
1239 size int // size of stored block (also encoded in locator)
1240 offset int // position of segment within the stored block
1241 length int // bytes in this segment (offset + length <= size)
1244 func (se storedSegment) Len() int {
1248 func (se storedSegment) Slice(n, size int) segment {
1251 if size >= 0 && se.length > size {
1257 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1258 if off > int64(se.length) {
1261 maxlen := se.length - int(off)
1262 if len(p) > maxlen {
1264 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1270 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1273 func canonicalName(name string) string {
1274 name = path.Clean("/" + name)
1275 if name == "/" || name == "./" {
1277 } else if strings.HasPrefix(name, "/") {
1283 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1285 func manifestUnescapeFunc(seq string) string {
1289 i, err := strconv.ParseUint(seq[1:], 8, 8)
1291 // Invalid escape sequence: can't unescape.
1294 return string([]byte{byte(i)})
1297 func manifestUnescape(s string) string {
1298 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1301 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1303 func manifestEscapeFunc(seq string) string {
1304 return fmt.Sprintf("\\%03o", byte(seq[0]))
1307 func manifestEscape(s string) string {
1308 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)