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) {
52 modTime := c.ModifiedAt
56 fs := &collectionFileSystem{
58 fileSystem: fileSystem{
59 fsBackend: keepBackend{apiClient: client, keepClient: kc},
60 thr: newThrottle(concurrentWriters),
68 mode: os.ModeDir | 0755,
71 inodes: make(map[string]inode),
74 root.SetParent(root, ".")
75 if err := root.loadManifest(c.ManifestText); err != nil {
78 backdateTree(root, modTime)
83 func backdateTree(n inode, modTime time.Time) {
84 switch n := n.(type) {
86 n.fileinfo.modTime = modTime
88 n.fileinfo.modTime = modTime
89 for _, n := range n.inodes {
90 backdateTree(n, modTime)
95 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
96 if name == "" || name == "." || name == ".." {
97 return nil, ErrInvalidArgument
105 mode: perm | os.ModeDir,
108 inodes: make(map[string]inode),
116 mode: perm & ^os.ModeDir,
123 func (fs *collectionFileSystem) Sync() error {
127 txt, err := fs.MarshalManifest(".")
129 return fmt.Errorf("sync failed: %s", err)
135 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
136 "collection": map[string]string{
137 "manifest_text": coll.ManifestText,
139 "select": []string{"uuid"},
142 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
147 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
148 node, err := rlookup(fs.fileSystem.root, path)
152 dn, ok := node.(*dirnode)
154 return ErrNotADirectory
158 names := dn.sortedNames()
160 // Caller only wants to flush the specified dir,
161 // non-recursively. Drop subdirs from the list of
163 var filenames []string
164 for _, name := range names {
165 if _, ok := dn.inodes[name].(*filenode); ok {
166 filenames = append(filenames, name)
171 for _, name := range names {
172 child := dn.inodes[name]
176 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
179 func (fs *collectionFileSystem) memorySize() int64 {
180 fs.fileSystem.root.Lock()
181 defer fs.fileSystem.root.Unlock()
182 return fs.fileSystem.root.(*dirnode).memorySize()
185 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
186 fs.fileSystem.root.Lock()
187 defer fs.fileSystem.root.Unlock()
188 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
191 func (fs *collectionFileSystem) Size() int64 {
192 return fs.fileSystem.root.(*dirnode).TreeSize()
195 // filenodePtr is an offset into a file that is (usually) efficient to
196 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
198 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
199 // corresponds to file offset filenodePtr.off. Otherwise, it is
200 // necessary to reexamine len(filenode.segments[0]) etc. to find the
201 // correct segment and offset.
202 type filenodePtr struct {
209 // seek returns a ptr that is consistent with both startPtr.off and
210 // the current state of fn. The caller must already hold fn.RLock() or
213 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
218 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
220 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
221 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
224 // meaningless anyway
226 } else if ptr.off >= fn.fileinfo.size {
227 ptr.segmentIdx = len(fn.segments)
229 ptr.repacked = fn.repacked
231 } else if ptr.repacked == fn.repacked {
232 // segmentIdx and segmentOff accurately reflect
233 // ptr.off, but might have fallen off the end of a
235 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
242 ptr.repacked = fn.repacked
244 if ptr.off >= fn.fileinfo.size {
245 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
248 // Recompute segmentIdx and segmentOff. We have already
249 // established fn.fileinfo.size > ptr.off >= 0, so we don't
250 // have to deal with edge cases here.
252 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
253 // This would panic (index out of range) if
254 // fn.fileinfo.size were larger than
255 // sum(fn.segments[i].Len()) -- but that can't happen
256 // because we have ensured fn.fileinfo.size is always
258 segLen := int64(fn.segments[ptr.segmentIdx].Len())
259 if off+segLen > ptr.off {
260 ptr.segmentOff = int(ptr.off - off)
268 // filenode implements inode.
269 type filenode struct {
274 // number of times `segments` has changed in a
275 // way that might invalidate a filenodePtr
277 memsize int64 // bytes in memSegments
282 // caller must have lock
283 func (fn *filenode) appendSegment(e segment) {
284 fn.segments = append(fn.segments, e)
285 fn.fileinfo.size += int64(e.Len())
288 func (fn *filenode) SetParent(p inode, name string) {
292 fn.fileinfo.name = name
295 func (fn *filenode) Parent() inode {
301 func (fn *filenode) FS() FileSystem {
305 // Read reads file data from a single segment, starting at startPtr,
306 // into p. startPtr is assumed not to be up-to-date. Caller must have
308 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
309 ptr = fn.seek(startPtr)
311 err = ErrNegativeOffset
314 if ptr.segmentIdx >= len(fn.segments) {
318 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
322 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
325 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
333 func (fn *filenode) Size() int64 {
336 return fn.fileinfo.Size()
339 func (fn *filenode) FileInfo() os.FileInfo {
345 func (fn *filenode) Truncate(size int64) error {
348 return fn.truncate(size)
351 func (fn *filenode) truncate(size int64) error {
352 if size == fn.fileinfo.size {
356 if size < fn.fileinfo.size {
357 ptr := fn.seek(filenodePtr{off: size})
358 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
359 if seg, ok := fn.segments[i].(*memSegment); ok {
360 fn.memsize -= int64(seg.Len())
363 if ptr.segmentOff == 0 {
364 fn.segments = fn.segments[:ptr.segmentIdx]
366 fn.segments = fn.segments[:ptr.segmentIdx+1]
367 switch seg := fn.segments[ptr.segmentIdx].(type) {
369 seg.Truncate(ptr.segmentOff)
370 fn.memsize += int64(seg.Len())
372 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
375 fn.fileinfo.size = size
378 for size > fn.fileinfo.size {
379 grow := size - fn.fileinfo.size
382 if len(fn.segments) == 0 {
384 fn.segments = append(fn.segments, seg)
385 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
387 fn.segments = append(fn.segments, seg)
389 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
392 seg.Truncate(seg.Len() + int(grow))
393 fn.fileinfo.size += grow
399 // Write writes data from p to the file, starting at startPtr,
400 // extending the file size if necessary. Caller must have Lock.
401 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
402 if startPtr.off > fn.fileinfo.size {
403 if err = fn.truncate(startPtr.off); err != nil {
404 return 0, startPtr, err
407 ptr = fn.seek(startPtr)
409 err = ErrNegativeOffset
412 for len(p) > 0 && err == nil {
414 if len(cando) > maxBlockSize {
415 cando = cando[:maxBlockSize]
417 // Rearrange/grow fn.segments (and shrink cando if
418 // needed) such that cando can be copied to
419 // fn.segments[ptr.segmentIdx] at offset
421 cur := ptr.segmentIdx
422 prev := ptr.segmentIdx - 1
424 if cur < len(fn.segments) {
425 _, curWritable = fn.segments[cur].(*memSegment)
427 var prevAppendable bool
428 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
429 _, prevAppendable = fn.segments[prev].(*memSegment)
431 if ptr.segmentOff > 0 && !curWritable {
432 // Split a non-writable block.
433 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
434 // Truncate cur, and insert a new
437 fn.segments = append(fn.segments, nil)
438 copy(fn.segments[cur+1:], fn.segments[cur:])
440 // Split cur into two copies, truncate
441 // the one on the left, shift the one
442 // on the right, and insert a new
443 // segment between them.
444 fn.segments = append(fn.segments, nil, nil)
445 copy(fn.segments[cur+2:], fn.segments[cur:])
446 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
451 seg.Truncate(len(cando))
452 fn.memsize += int64(len(cando))
453 fn.segments[cur] = seg
454 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
459 } else if curWritable {
460 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
465 // Shrink cando if needed to fit in
467 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
468 cando = cando[:cangrow]
472 if cur == len(fn.segments) {
473 // ptr is at EOF, filesize is changing.
474 fn.fileinfo.size += int64(len(cando))
475 } else if el := fn.segments[cur].Len(); el <= len(cando) {
476 // cando is long enough that we won't
477 // need cur any more. shrink cando to
478 // be exactly as long as cur
479 // (otherwise we'd accidentally shift
480 // the effective position of all
481 // segments after cur).
483 copy(fn.segments[cur:], fn.segments[cur+1:])
484 fn.segments = fn.segments[:len(fn.segments)-1]
486 // shrink cur by the same #bytes we're growing prev
487 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
493 ptr.segmentOff = fn.segments[prev].Len()
494 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
495 fn.memsize += int64(len(cando))
499 // Insert a segment between prev and
500 // cur, and advance prev/cur.
501 fn.segments = append(fn.segments, nil)
502 if cur < len(fn.segments) {
503 copy(fn.segments[cur+1:], fn.segments[cur:])
507 // appending a new segment does
508 // not invalidate any ptrs
511 seg.Truncate(len(cando))
512 fn.memsize += int64(len(cando))
513 fn.segments[cur] = seg
519 // Finally we can copy bytes from cando to the current segment.
520 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
524 ptr.off += int64(len(cando))
525 ptr.segmentOff += len(cando)
526 if ptr.segmentOff >= maxBlockSize {
527 fn.pruneMemSegments()
529 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
534 fn.fileinfo.modTime = time.Now()
539 // Write some data out to disk to reduce memory use. Caller must have
541 func (fn *filenode) pruneMemSegments() {
542 // TODO: share code with (*dirnode)flush()
543 // TODO: pack/flush small blocks too, when fragmented
544 for idx, seg := range fn.segments {
545 seg, ok := seg.(*memSegment)
546 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
549 // Setting seg.flushing guarantees seg.buf will not be
550 // modified in place: WriteAt and Truncate will
551 // allocate a new buf instead, if necessary.
552 idx, buf := idx, seg.buf
553 done := make(chan struct{})
555 // If lots of background writes are already in
556 // progress, block here until one finishes, rather
557 // than pile up an unlimited number of buffered writes
558 // and network flush operations.
559 fn.fs.throttle().Acquire()
562 locator, _, err := fn.FS().PutB(buf)
563 fn.fs.throttle().Release()
566 if seg.flushing != done {
567 // A new seg.buf has been allocated.
572 // TODO: stall (or return errors from)
573 // subsequent writes until flushing
574 // starts to succeed.
577 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
578 // Segment has been dropped/moved/resized.
581 fn.memsize -= int64(len(buf))
582 fn.segments[idx] = storedSegment{
593 // Block until all pending pruneMemSegments/flush work is
594 // finished. Caller must NOT have lock.
595 func (fn *filenode) waitPrune() {
596 var pending []<-chan struct{}
598 for _, seg := range fn.segments {
599 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
600 pending = append(pending, seg.flushing)
604 for _, p := range pending {
609 type dirnode struct {
610 fs *collectionFileSystem
614 func (dn *dirnode) FS() FileSystem {
618 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
619 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
620 gn := &getternode{Getter: func() ([]byte, error) {
623 coll.ManifestText, err = dn.fs.MarshalManifest(".")
627 data, err := json.Marshal(&coll)
629 data = append(data, '\n')
633 gn.SetParent(dn, name)
636 return dn.treenode.Child(name, replace)
639 type fnSegmentRef struct {
644 // commitBlock concatenates the data from the given filenode segments
645 // (which must be *memSegments), writes the data out to Keep as a
646 // single block, and replaces the filenodes' *memSegments with
647 // storedSegments that reference the relevant portions of the new
650 // bufsize is the total data size in refs. It is used to preallocate
651 // the correct amount of memory when len(refs)>1.
653 // If sync is false, commitBlock returns right away, after starting a
654 // goroutine to do the writes, reacquire the filenodes' locks, and
655 // swap out the *memSegments. Some filenodes' segments might get
656 // modified/rearranged in the meantime, in which case commitBlock
657 // won't replace them.
659 // Caller must have write lock.
660 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
664 if err := ctx.Err(); err != nil {
667 done := make(chan struct{})
669 segs := make([]*memSegment, 0, len(refs))
670 offsets := make([]int, 0, len(refs)) // location of segment's data within block
671 for _, ref := range refs {
672 seg := ref.fn.segments[ref.idx].(*memSegment)
673 if seg.flushing != nil && !sync {
674 // Let the other flushing goroutine finish. If
675 // it fails, we'll try again next time.
678 // In sync mode, we proceed regardless of
679 // whether another flush is in progress: It
680 // can't finish before we do, because we hold
681 // fn's lock until we finish our own writes.
684 offsets = append(offsets, len(block))
687 } else if block == nil {
688 block = append(make([]byte, 0, bufsize), seg.buf...)
690 block = append(block, seg.buf...)
692 segs = append(segs, seg)
694 dn.fs.throttle().Acquire()
695 errs := make(chan error, 1)
699 locked := map[*filenode]bool{}
700 locator, _, err := dn.fs.PutB(block)
701 dn.fs.throttle().Release()
704 for _, name := range dn.sortedNames() {
705 if fn, ok := dn.inodes[name].(*filenode); ok {
713 for _, seg := range segs {
714 if seg.flushing == done {
724 for idx, ref := range refs {
726 // In async mode, fn's lock was
727 // released while we were waiting for
728 // PutB(); lots of things might have
730 if len(ref.fn.segments) <= ref.idx {
731 // file segments have
732 // rearranged or changed in
735 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
736 // segment has been replaced
738 } else if seg.flushing != done {
739 // seg.buf has been replaced
741 } else if !locked[ref.fn] {
742 // file was renamed, moved, or
743 // deleted since we called
748 data := ref.fn.segments[ref.idx].(*memSegment).buf
749 ref.fn.segments[ref.idx] = storedSegment{
753 offset: offsets[idx],
756 ref.fn.memsize -= int64(len(data))
766 type flushOpts struct {
771 // flush in-memory data and remote-cluster block references (for the
772 // children with the given names, which must be children of dn) to
773 // local-cluster persistent storage.
775 // Caller must have write lock on dn and the named children.
777 // If any children are dirs, they will be flushed recursively.
778 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
779 cg := newContextGroup(ctx)
782 goCommit := func(refs []fnSegmentRef, bufsize int) {
784 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
788 var pending []fnSegmentRef
789 var pendingLen int = 0
790 localLocator := map[string]string{}
791 for _, name := range names {
792 switch node := dn.inodes[name].(type) {
794 grandchildNames := node.sortedNames()
795 for _, grandchildName := range grandchildNames {
796 grandchild := node.inodes[grandchildName]
798 defer grandchild.Unlock()
800 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
802 for idx, seg := range node.segments {
803 switch seg := seg.(type) {
805 loc, ok := localLocator[seg.locator]
808 loc, err = dn.fs.LocalLocator(seg.locator)
812 localLocator[seg.locator] = loc
815 node.segments[idx] = seg
817 if seg.Len() > maxBlockSize/2 {
818 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
821 if pendingLen+seg.Len() > maxBlockSize {
822 goCommit(pending, pendingLen)
826 pending = append(pending, fnSegmentRef{node, idx})
827 pendingLen += seg.Len()
829 panic(fmt.Sprintf("can't sync segment type %T", seg))
834 if opts.shortBlocks {
835 goCommit(pending, pendingLen)
840 // caller must have write lock.
841 func (dn *dirnode) memorySize() (size int64) {
842 for _, name := range dn.sortedNames() {
843 node := dn.inodes[name]
846 switch node := node.(type) {
848 size += node.memorySize()
850 for _, seg := range node.segments {
851 switch seg := seg.(type) {
853 size += int64(seg.Len())
861 // caller must have write lock.
862 func (dn *dirnode) sortedNames() []string {
863 names := make([]string, 0, len(dn.inodes))
864 for name := range dn.inodes {
865 names = append(names, name)
871 // caller must have write lock.
872 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
873 cg := newContextGroup(ctx)
876 if len(dn.inodes) == 0 {
880 // Express the existence of an empty directory by
881 // adding an empty file named `\056`, which (unlike
882 // the more obvious spelling `.`) is accepted by the
883 // API's manifest validator.
884 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
887 names := dn.sortedNames()
889 // Wait for children to finish any pending write operations
890 // before locking them.
891 for _, name := range names {
892 node := dn.inodes[name]
893 if fn, ok := node.(*filenode); ok {
898 var dirnames []string
899 var filenames []string
900 for _, name := range names {
901 node := dn.inodes[name]
904 switch node := node.(type) {
906 dirnames = append(dirnames, name)
908 filenames = append(filenames, name)
910 panic(fmt.Sprintf("can't marshal inode type %T", node))
914 subdirs := make([]string, len(dirnames))
916 for i, name := range dirnames {
919 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
927 type filepart struct {
933 var fileparts []filepart
935 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
938 for _, name := range filenames {
939 node := dn.inodes[name].(*filenode)
940 if len(node.segments) == 0 {
941 fileparts = append(fileparts, filepart{name: name})
944 for _, seg := range node.segments {
945 switch seg := seg.(type) {
947 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
948 streamLen -= int64(seg.size)
950 blocks = append(blocks, seg.locator)
954 offset: streamLen + int64(seg.offset),
955 length: int64(seg.length),
957 if prev := len(fileparts) - 1; prev >= 0 &&
958 fileparts[prev].name == name &&
959 fileparts[prev].offset+fileparts[prev].length == next.offset {
960 fileparts[prev].length += next.length
962 fileparts = append(fileparts, next)
964 streamLen += int64(seg.size)
966 // This can't happen: we
967 // haven't unlocked since
968 // calling flush(sync=true).
969 panic(fmt.Sprintf("can't marshal segment type %T", seg))
973 var filetokens []string
974 for _, s := range fileparts {
975 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
977 if len(filetokens) == 0 {
979 } else if len(blocks) == 0 {
980 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
982 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
986 return rootdir + strings.Join(subdirs, ""), err
989 func (dn *dirnode) loadManifest(txt string) error {
991 streams := strings.Split(txt, "\n")
992 if streams[len(streams)-1] != "" {
993 return fmt.Errorf("line %d: no trailing newline", len(streams))
995 streams = streams[:len(streams)-1]
996 segments := []storedSegment{}
997 for i, stream := range streams {
999 var anyFileTokens bool
1002 segments = segments[:0]
1003 for i, token := range strings.Split(stream, " ") {
1005 dirname = manifestUnescape(token)
1008 if !strings.Contains(token, ":") {
1010 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1012 toks := strings.SplitN(token, "+", 3)
1014 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1016 length, err := strconv.ParseInt(toks[1], 10, 32)
1017 if err != nil || length < 0 {
1018 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1020 segments = append(segments, storedSegment{
1024 length: int(length),
1027 } else if len(segments) == 0 {
1028 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1031 toks := strings.SplitN(token, ":", 3)
1033 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1035 anyFileTokens = true
1037 offset, err := strconv.ParseInt(toks[0], 10, 64)
1038 if err != nil || offset < 0 {
1039 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1041 length, err := strconv.ParseInt(toks[1], 10, 64)
1042 if err != nil || length < 0 {
1043 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1045 name := dirname + "/" + manifestUnescape(toks[2])
1046 fnode, err := dn.createFileAndParents(name)
1047 if fnode == nil && err == nil && length == 0 {
1048 // Special case: an empty file used as
1049 // a marker to preserve an otherwise
1050 // empty directory in a manifest.
1053 if err != nil || (fnode == nil && length != 0) {
1054 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1056 // Map the stream offset/range coordinates to
1057 // block/offset/range coordinates and add
1058 // corresponding storedSegments to the filenode
1060 // Can't continue where we left off.
1061 // TODO: binary search instead of
1062 // rewinding all the way (but this
1063 // situation might be rare anyway)
1066 for next := int64(0); segIdx < len(segments); segIdx++ {
1067 seg := segments[segIdx]
1068 next = pos + int64(seg.Len())
1069 if next <= offset || seg.Len() == 0 {
1073 if pos >= offset+length {
1078 blkOff = int(offset - pos)
1080 blkLen := seg.Len() - blkOff
1081 if pos+int64(blkOff+blkLen) > offset+length {
1082 blkLen = int(offset + length - pos - int64(blkOff))
1084 fnode.appendSegment(storedSegment{
1086 locator: seg.locator,
1091 if next > offset+length {
1097 if segIdx == len(segments) && pos < offset+length {
1098 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1102 return fmt.Errorf("line %d: no file segments", lineno)
1103 } else if len(segments) == 0 {
1104 return fmt.Errorf("line %d: no locators", lineno)
1105 } else if dirname == "" {
1106 return fmt.Errorf("line %d: no stream name", lineno)
1112 // only safe to call from loadManifest -- no locking.
1114 // If path is a "parent directory exists" marker (the last path
1115 // component is "."), the returned values are both nil.
1116 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1118 names := strings.Split(path, "/")
1119 basename := names[len(names)-1]
1120 for _, name := range names[:len(names)-1] {
1126 // can't be sure parent will be a *dirnode
1127 return nil, ErrInvalidArgument
1129 node = node.Parent()
1132 node, err = node.Child(name, func(child inode) (inode, error) {
1134 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1138 child.SetParent(node, name)
1140 } else if !child.IsDir() {
1141 return child, ErrFileExists
1150 if basename == "." {
1152 } else if !permittedName(basename) {
1153 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1156 _, err = node.Child(basename, func(child inode) (inode, error) {
1157 switch child := child.(type) {
1159 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1163 child.SetParent(node, basename)
1164 fn = child.(*filenode)
1170 return child, ErrIsDirectory
1172 return child, ErrInvalidArgument
1178 func (dn *dirnode) TreeSize() (bytes int64) {
1181 for _, i := range dn.inodes {
1182 switch i := i.(type) {
1186 bytes += i.TreeSize()
1192 type segment interface {
1195 // Return a new segment with a subsection of the data from this
1196 // one. length<0 means length=Len()-off.
1197 Slice(off int, length int) segment
1200 type memSegment struct {
1202 // If flushing is not nil, then a) buf is being shared by a
1203 // pruneMemSegments goroutine, and must be copied on write;
1204 // and b) the flushing channel will close when the goroutine
1205 // finishes, whether it succeeds or not.
1206 flushing <-chan struct{}
1209 func (me *memSegment) Len() int {
1213 func (me *memSegment) Slice(off, length int) segment {
1215 length = len(me.buf) - off
1217 buf := make([]byte, length)
1218 copy(buf, me.buf[off:])
1219 return &memSegment{buf: buf}
1222 func (me *memSegment) Truncate(n int) {
1223 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1226 newsize = newsize << 2
1228 newbuf := make([]byte, n, newsize)
1229 copy(newbuf, me.buf)
1230 me.buf, me.flushing = newbuf, nil
1232 // reclaim existing capacity, and zero reclaimed part
1233 oldlen := len(me.buf)
1235 for i := oldlen; i < n; i++ {
1241 func (me *memSegment) WriteAt(p []byte, off int) {
1242 if off+len(p) > len(me.buf) {
1243 panic("overflowed segment")
1245 if me.flushing != nil {
1246 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1248 copy(me.buf[off:], p)
1251 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1252 if off > int64(me.Len()) {
1256 n = copy(p, me.buf[int(off):])
1263 type storedSegment struct {
1266 size int // size of stored block (also encoded in locator)
1267 offset int // position of segment within the stored block
1268 length int // bytes in this segment (offset + length <= size)
1271 func (se storedSegment) Len() int {
1275 func (se storedSegment) Slice(n, size int) segment {
1278 if size >= 0 && se.length > size {
1284 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1285 if off > int64(se.length) {
1288 maxlen := se.length - int(off)
1289 if len(p) > maxlen {
1291 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1297 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1300 func canonicalName(name string) string {
1301 name = path.Clean("/" + name)
1302 if name == "/" || name == "./" {
1304 } else if strings.HasPrefix(name, "/") {
1310 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1312 func manifestUnescapeFunc(seq string) string {
1316 i, err := strconv.ParseUint(seq[1:], 8, 8)
1318 // Invalid escape sequence: can't unescape.
1321 return string([]byte{byte(i)})
1324 func manifestUnescape(s string) string {
1325 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1328 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1330 func manifestEscapeFunc(seq string) string {
1331 return fmt.Sprintf("\\%03o", byte(seq[0]))
1334 func manifestEscape(s string) string {
1335 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)