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) Sync() error {
128 txt, err := fs.MarshalManifest(".")
130 return fmt.Errorf("sync failed: %s", err)
136 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
137 "collection": map[string]string{
138 "manifest_text": coll.ManifestText,
140 "select": []string{"uuid"},
143 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
148 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
149 node, err := rlookup(fs.fileSystem.root, path)
153 dn, ok := node.(*dirnode)
155 return ErrNotADirectory
159 names := dn.sortedNames()
161 // Caller only wants to flush the specified dir,
162 // non-recursively. Drop subdirs from the list of
164 var filenames []string
165 for _, name := range names {
166 if _, ok := dn.inodes[name].(*filenode); ok {
167 filenames = append(filenames, name)
172 for _, name := range names {
173 child := dn.inodes[name]
177 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
180 func (fs *collectionFileSystem) memorySize() int64 {
181 fs.fileSystem.root.Lock()
182 defer fs.fileSystem.root.Unlock()
183 return fs.fileSystem.root.(*dirnode).memorySize()
186 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
187 fs.fileSystem.root.Lock()
188 defer fs.fileSystem.root.Unlock()
189 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
192 func (fs *collectionFileSystem) Size() int64 {
193 return fs.fileSystem.root.(*dirnode).TreeSize()
196 // asChildNode() repackages fs as an inode that can be used as a child
197 // node in a different fs. Not goroutine-safe.
199 // After calling asChildNode(), the caller should not use fs directly.
200 func (fs *collectionFileSystem) asChildNode(parent inode, name string) *collectionfsnode {
201 root := fs.rootnode().(*dirnode)
202 root.SetParent(parent, name)
203 return &collectionfsnode{dirnode: root, fs: fs}
206 type collectionfsnode struct {
208 fs *collectionFileSystem
211 func (cn *collectionfsnode) Sync() error {
215 // filenodePtr is an offset into a file that is (usually) efficient to
216 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
218 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
219 // corresponds to file offset filenodePtr.off. Otherwise, it is
220 // necessary to reexamine len(filenode.segments[0]) etc. to find the
221 // correct segment and offset.
222 type filenodePtr struct {
229 // seek returns a ptr that is consistent with both startPtr.off and
230 // the current state of fn. The caller must already hold fn.RLock() or
233 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
238 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
240 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
241 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
244 // meaningless anyway
246 } else if ptr.off >= fn.fileinfo.size {
247 ptr.segmentIdx = len(fn.segments)
249 ptr.repacked = fn.repacked
251 } else if ptr.repacked == fn.repacked {
252 // segmentIdx and segmentOff accurately reflect
253 // ptr.off, but might have fallen off the end of a
255 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
262 ptr.repacked = fn.repacked
264 if ptr.off >= fn.fileinfo.size {
265 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
268 // Recompute segmentIdx and segmentOff. We have already
269 // established fn.fileinfo.size > ptr.off >= 0, so we don't
270 // have to deal with edge cases here.
272 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
273 // This would panic (index out of range) if
274 // fn.fileinfo.size were larger than
275 // sum(fn.segments[i].Len()) -- but that can't happen
276 // because we have ensured fn.fileinfo.size is always
278 segLen := int64(fn.segments[ptr.segmentIdx].Len())
279 if off+segLen > ptr.off {
280 ptr.segmentOff = int(ptr.off - off)
288 // filenode implements inode.
289 type filenode struct {
294 // number of times `segments` has changed in a
295 // way that might invalidate a filenodePtr
297 memsize int64 // bytes in memSegments
302 // caller must have lock
303 func (fn *filenode) appendSegment(e segment) {
304 fn.segments = append(fn.segments, e)
305 fn.fileinfo.size += int64(e.Len())
308 func (fn *filenode) SetParent(p inode, name string) {
312 fn.fileinfo.name = name
315 func (fn *filenode) Parent() inode {
321 func (fn *filenode) FS() FileSystem {
325 // Read reads file data from a single segment, starting at startPtr,
326 // into p. startPtr is assumed not to be up-to-date. Caller must have
328 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
329 ptr = fn.seek(startPtr)
331 err = ErrNegativeOffset
334 if ptr.segmentIdx >= len(fn.segments) {
338 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
342 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
345 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
353 func (fn *filenode) Size() int64 {
356 return fn.fileinfo.Size()
359 func (fn *filenode) FileInfo() os.FileInfo {
365 func (fn *filenode) Truncate(size int64) error {
368 return fn.truncate(size)
371 func (fn *filenode) truncate(size int64) error {
372 if size == fn.fileinfo.size {
376 if size < fn.fileinfo.size {
377 ptr := fn.seek(filenodePtr{off: size})
378 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
379 if seg, ok := fn.segments[i].(*memSegment); ok {
380 fn.memsize -= int64(seg.Len())
383 if ptr.segmentOff == 0 {
384 fn.segments = fn.segments[:ptr.segmentIdx]
386 fn.segments = fn.segments[:ptr.segmentIdx+1]
387 switch seg := fn.segments[ptr.segmentIdx].(type) {
389 seg.Truncate(ptr.segmentOff)
390 fn.memsize += int64(seg.Len())
392 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
395 fn.fileinfo.size = size
398 for size > fn.fileinfo.size {
399 grow := size - fn.fileinfo.size
402 if len(fn.segments) == 0 {
404 fn.segments = append(fn.segments, seg)
405 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
407 fn.segments = append(fn.segments, seg)
409 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
412 seg.Truncate(seg.Len() + int(grow))
413 fn.fileinfo.size += grow
419 // Write writes data from p to the file, starting at startPtr,
420 // extending the file size if necessary. Caller must have Lock.
421 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
422 if startPtr.off > fn.fileinfo.size {
423 if err = fn.truncate(startPtr.off); err != nil {
424 return 0, startPtr, err
427 ptr = fn.seek(startPtr)
429 err = ErrNegativeOffset
432 for len(p) > 0 && err == nil {
434 if len(cando) > maxBlockSize {
435 cando = cando[:maxBlockSize]
437 // Rearrange/grow fn.segments (and shrink cando if
438 // needed) such that cando can be copied to
439 // fn.segments[ptr.segmentIdx] at offset
441 cur := ptr.segmentIdx
442 prev := ptr.segmentIdx - 1
444 if cur < len(fn.segments) {
445 _, curWritable = fn.segments[cur].(*memSegment)
447 var prevAppendable bool
448 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
449 _, prevAppendable = fn.segments[prev].(*memSegment)
451 if ptr.segmentOff > 0 && !curWritable {
452 // Split a non-writable block.
453 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
454 // Truncate cur, and insert a new
457 fn.segments = append(fn.segments, nil)
458 copy(fn.segments[cur+1:], fn.segments[cur:])
460 // Split cur into two copies, truncate
461 // the one on the left, shift the one
462 // on the right, and insert a new
463 // segment between them.
464 fn.segments = append(fn.segments, nil, nil)
465 copy(fn.segments[cur+2:], fn.segments[cur:])
466 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
471 seg.Truncate(len(cando))
472 fn.memsize += int64(len(cando))
473 fn.segments[cur] = seg
474 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
479 } else if curWritable {
480 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
485 // Shrink cando if needed to fit in
487 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
488 cando = cando[:cangrow]
492 if cur == len(fn.segments) {
493 // ptr is at EOF, filesize is changing.
494 fn.fileinfo.size += int64(len(cando))
495 } else if el := fn.segments[cur].Len(); el <= len(cando) {
496 // cando is long enough that we won't
497 // need cur any more. shrink cando to
498 // be exactly as long as cur
499 // (otherwise we'd accidentally shift
500 // the effective position of all
501 // segments after cur).
503 copy(fn.segments[cur:], fn.segments[cur+1:])
504 fn.segments = fn.segments[:len(fn.segments)-1]
506 // shrink cur by the same #bytes we're growing prev
507 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
513 ptr.segmentOff = fn.segments[prev].Len()
514 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
515 fn.memsize += int64(len(cando))
519 // Insert a segment between prev and
520 // cur, and advance prev/cur.
521 fn.segments = append(fn.segments, nil)
522 if cur < len(fn.segments) {
523 copy(fn.segments[cur+1:], fn.segments[cur:])
527 // appending a new segment does
528 // not invalidate any ptrs
531 seg.Truncate(len(cando))
532 fn.memsize += int64(len(cando))
533 fn.segments[cur] = seg
539 // Finally we can copy bytes from cando to the current segment.
540 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
544 ptr.off += int64(len(cando))
545 ptr.segmentOff += len(cando)
546 if ptr.segmentOff >= maxBlockSize {
547 fn.pruneMemSegments()
549 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
554 fn.fileinfo.modTime = time.Now()
559 // Write some data out to disk to reduce memory use. Caller must have
561 func (fn *filenode) pruneMemSegments() {
562 // TODO: share code with (*dirnode)flush()
563 // TODO: pack/flush small blocks too, when fragmented
564 for idx, seg := range fn.segments {
565 seg, ok := seg.(*memSegment)
566 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
569 // Setting seg.flushing guarantees seg.buf will not be
570 // modified in place: WriteAt and Truncate will
571 // allocate a new buf instead, if necessary.
572 idx, buf := idx, seg.buf
573 done := make(chan struct{})
575 // If lots of background writes are already in
576 // progress, block here until one finishes, rather
577 // than pile up an unlimited number of buffered writes
578 // and network flush operations.
579 fn.fs.throttle().Acquire()
582 locator, _, err := fn.FS().PutB(buf)
583 fn.fs.throttle().Release()
586 if seg.flushing != done {
587 // A new seg.buf has been allocated.
591 // TODO: stall (or return errors from)
592 // subsequent writes until flushing
593 // starts to succeed.
596 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
597 // Segment has been dropped/moved/resized.
600 fn.memsize -= int64(len(buf))
601 fn.segments[idx] = storedSegment{
612 // Block until all pending pruneMemSegments/flush work is
613 // finished. Caller must NOT have lock.
614 func (fn *filenode) waitPrune() {
615 var pending []<-chan struct{}
617 for _, seg := range fn.segments {
618 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
619 pending = append(pending, seg.flushing)
623 for _, p := range pending {
628 type dirnode struct {
629 fs *collectionFileSystem
633 func (dn *dirnode) FS() FileSystem {
637 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
638 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
639 gn := &getternode{Getter: func() ([]byte, error) {
642 coll.ManifestText, err = dn.fs.MarshalManifest(".")
646 data, err := json.Marshal(&coll)
648 data = append(data, '\n')
652 gn.SetParent(dn, name)
655 return dn.treenode.Child(name, replace)
658 type fnSegmentRef struct {
663 // commitBlock concatenates the data from the given filenode segments
664 // (which must be *memSegments), writes the data out to Keep as a
665 // single block, and replaces the filenodes' *memSegments with
666 // storedSegments that reference the relevant portions of the new
669 // bufsize is the total data size in refs. It is used to preallocate
670 // the correct amount of memory when len(refs)>1.
672 // If sync is false, commitBlock returns right away, after starting a
673 // goroutine to do the writes, reacquire the filenodes' locks, and
674 // swap out the *memSegments. Some filenodes' segments might get
675 // modified/rearranged in the meantime, in which case commitBlock
676 // won't replace them.
678 // Caller must have write lock.
679 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
683 if err := ctx.Err(); err != nil {
686 done := make(chan struct{})
688 segs := make([]*memSegment, 0, len(refs))
689 offsets := make([]int, 0, len(refs)) // location of segment's data within block
690 for _, ref := range refs {
691 seg := ref.fn.segments[ref.idx].(*memSegment)
692 if !sync && seg.flushingUnfinished() {
693 // Let the other flushing goroutine finish. If
694 // it fails, we'll try again next time.
698 // In sync mode, we proceed regardless of
699 // whether another flush is in progress: It
700 // can't finish before we do, because we hold
701 // fn's lock until we finish our own writes.
704 offsets = append(offsets, len(block))
707 } else if block == nil {
708 block = append(make([]byte, 0, bufsize), seg.buf...)
710 block = append(block, seg.buf...)
712 segs = append(segs, seg)
714 blocksize := len(block)
715 dn.fs.throttle().Acquire()
716 errs := make(chan error, 1)
720 locator, _, err := dn.fs.PutB(block)
721 dn.fs.throttle().Release()
726 for idx, ref := range refs {
729 // In async mode, fn's lock was
730 // released while we were waiting for
731 // PutB(); lots of things might have
733 if len(ref.fn.segments) <= ref.idx {
734 // file segments have
735 // rearranged or changed in
739 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
740 // segment has been replaced
743 } else if seg.flushing != done {
744 // seg.buf has been replaced
749 data := ref.fn.segments[ref.idx].(*memSegment).buf
750 ref.fn.segments[ref.idx] = storedSegment{
754 offset: offsets[idx],
757 // atomic is needed here despite caller having
758 // lock: caller might be running concurrent
759 // commitBlock() goroutines using the same
760 // lock, writing different segments from the
762 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
775 type flushOpts struct {
780 // flush in-memory data and remote-cluster block references (for the
781 // children with the given names, which must be children of dn) to
782 // local-cluster persistent storage.
784 // Caller must have write lock on dn and the named children.
786 // If any children are dirs, they will be flushed recursively.
787 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
788 cg := newContextGroup(ctx)
791 goCommit := func(refs []fnSegmentRef, bufsize int) {
793 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
797 var pending []fnSegmentRef
798 var pendingLen int = 0
799 localLocator := map[string]string{}
800 for _, name := range names {
801 switch node := dn.inodes[name].(type) {
803 grandchildNames := node.sortedNames()
804 for _, grandchildName := range grandchildNames {
805 grandchild := node.inodes[grandchildName]
807 defer grandchild.Unlock()
809 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
811 for idx, seg := range node.segments {
812 switch seg := seg.(type) {
814 loc, ok := localLocator[seg.locator]
817 loc, err = dn.fs.LocalLocator(seg.locator)
821 localLocator[seg.locator] = loc
824 node.segments[idx] = seg
826 if seg.Len() > maxBlockSize/2 {
827 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
830 if pendingLen+seg.Len() > maxBlockSize {
831 goCommit(pending, pendingLen)
835 pending = append(pending, fnSegmentRef{node, idx})
836 pendingLen += seg.Len()
838 panic(fmt.Sprintf("can't sync segment type %T", seg))
843 if opts.shortBlocks {
844 goCommit(pending, pendingLen)
849 // caller must have write lock.
850 func (dn *dirnode) memorySize() (size int64) {
851 for _, name := range dn.sortedNames() {
852 node := dn.inodes[name]
855 switch node := node.(type) {
857 size += node.memorySize()
859 for _, seg := range node.segments {
860 switch seg := seg.(type) {
862 size += int64(seg.Len())
870 // caller must have write lock.
871 func (dn *dirnode) sortedNames() []string {
872 names := make([]string, 0, len(dn.inodes))
873 for name := range dn.inodes {
874 names = append(names, name)
880 // caller must have write lock.
881 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
882 cg := newContextGroup(ctx)
885 if len(dn.inodes) == 0 {
889 // Express the existence of an empty directory by
890 // adding an empty file named `\056`, which (unlike
891 // the more obvious spelling `.`) is accepted by the
892 // API's manifest validator.
893 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
896 names := dn.sortedNames()
898 // Wait for children to finish any pending write operations
899 // before locking them.
900 for _, name := range names {
901 node := dn.inodes[name]
902 if fn, ok := node.(*filenode); ok {
907 var dirnames []string
908 var filenames []string
909 for _, name := range names {
910 node := dn.inodes[name]
913 switch node := node.(type) {
915 dirnames = append(dirnames, name)
917 filenames = append(filenames, name)
919 panic(fmt.Sprintf("can't marshal inode type %T", node))
923 subdirs := make([]string, len(dirnames))
925 for i, name := range dirnames {
928 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
936 type filepart struct {
942 var fileparts []filepart
944 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
947 for _, name := range filenames {
948 node := dn.inodes[name].(*filenode)
949 if len(node.segments) == 0 {
950 fileparts = append(fileparts, filepart{name: name})
953 for _, seg := range node.segments {
954 switch seg := seg.(type) {
956 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
957 streamLen -= int64(seg.size)
959 blocks = append(blocks, seg.locator)
963 offset: streamLen + int64(seg.offset),
964 length: int64(seg.length),
966 if prev := len(fileparts) - 1; prev >= 0 &&
967 fileparts[prev].name == name &&
968 fileparts[prev].offset+fileparts[prev].length == next.offset {
969 fileparts[prev].length += next.length
971 fileparts = append(fileparts, next)
973 streamLen += int64(seg.size)
975 // This can't happen: we
976 // haven't unlocked since
977 // calling flush(sync=true).
978 panic(fmt.Sprintf("can't marshal segment type %T", seg))
982 var filetokens []string
983 for _, s := range fileparts {
984 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
986 if len(filetokens) == 0 {
988 } else if len(blocks) == 0 {
989 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
991 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
995 return rootdir + strings.Join(subdirs, ""), err
998 func (dn *dirnode) loadManifest(txt string) error {
1000 streams := strings.Split(txt, "\n")
1001 if streams[len(streams)-1] != "" {
1002 return fmt.Errorf("line %d: no trailing newline", len(streams))
1004 streams = streams[:len(streams)-1]
1005 segments := []storedSegment{}
1006 for i, stream := range streams {
1008 var anyFileTokens bool
1011 segments = segments[:0]
1012 for i, token := range strings.Split(stream, " ") {
1014 dirname = manifestUnescape(token)
1017 if !strings.Contains(token, ":") {
1019 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1021 toks := strings.SplitN(token, "+", 3)
1023 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1025 length, err := strconv.ParseInt(toks[1], 10, 32)
1026 if err != nil || length < 0 {
1027 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1029 segments = append(segments, storedSegment{
1033 length: int(length),
1036 } else if len(segments) == 0 {
1037 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1040 toks := strings.SplitN(token, ":", 3)
1042 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1044 anyFileTokens = true
1046 offset, err := strconv.ParseInt(toks[0], 10, 64)
1047 if err != nil || offset < 0 {
1048 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1050 length, err := strconv.ParseInt(toks[1], 10, 64)
1051 if err != nil || length < 0 {
1052 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1054 name := dirname + "/" + manifestUnescape(toks[2])
1055 fnode, err := dn.createFileAndParents(name)
1056 if fnode == nil && err == nil && length == 0 {
1057 // Special case: an empty file used as
1058 // a marker to preserve an otherwise
1059 // empty directory in a manifest.
1062 if err != nil || (fnode == nil && length != 0) {
1063 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1065 // Map the stream offset/range coordinates to
1066 // block/offset/range coordinates and add
1067 // corresponding storedSegments to the filenode
1069 // Can't continue where we left off.
1070 // TODO: binary search instead of
1071 // rewinding all the way (but this
1072 // situation might be rare anyway)
1075 for next := int64(0); segIdx < len(segments); segIdx++ {
1076 seg := segments[segIdx]
1077 next = pos + int64(seg.Len())
1078 if next <= offset || seg.Len() == 0 {
1082 if pos >= offset+length {
1087 blkOff = int(offset - pos)
1089 blkLen := seg.Len() - blkOff
1090 if pos+int64(blkOff+blkLen) > offset+length {
1091 blkLen = int(offset + length - pos - int64(blkOff))
1093 fnode.appendSegment(storedSegment{
1095 locator: seg.locator,
1100 if next > offset+length {
1106 if segIdx == len(segments) && pos < offset+length {
1107 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1111 return fmt.Errorf("line %d: no file segments", lineno)
1112 } else if len(segments) == 0 {
1113 return fmt.Errorf("line %d: no locators", lineno)
1114 } else if dirname == "" {
1115 return fmt.Errorf("line %d: no stream name", lineno)
1121 // only safe to call from loadManifest -- no locking.
1123 // If path is a "parent directory exists" marker (the last path
1124 // component is "."), the returned values are both nil.
1125 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1127 names := strings.Split(path, "/")
1128 basename := names[len(names)-1]
1129 for _, name := range names[:len(names)-1] {
1135 // can't be sure parent will be a *dirnode
1136 return nil, ErrInvalidArgument
1138 node = node.Parent()
1141 node, err = node.Child(name, func(child inode) (inode, error) {
1143 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1147 child.SetParent(node, name)
1149 } else if !child.IsDir() {
1150 return child, ErrFileExists
1159 if basename == "." {
1161 } else if !permittedName(basename) {
1162 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1165 _, err = node.Child(basename, func(child inode) (inode, error) {
1166 switch child := child.(type) {
1168 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1172 child.SetParent(node, basename)
1173 fn = child.(*filenode)
1179 return child, ErrIsDirectory
1181 return child, ErrInvalidArgument
1187 func (dn *dirnode) TreeSize() (bytes int64) {
1190 for _, i := range dn.inodes {
1191 switch i := i.(type) {
1195 bytes += i.TreeSize()
1201 type segment interface {
1204 // Return a new segment with a subsection of the data from this
1205 // one. length<0 means length=Len()-off.
1206 Slice(off int, length int) segment
1209 type memSegment struct {
1211 // If flushing is not nil and not ready/closed, then a) buf is
1212 // being shared by a pruneMemSegments goroutine, and must be
1213 // copied on write; and b) the flushing channel will close
1214 // when the goroutine finishes, whether it succeeds or not.
1215 flushing <-chan struct{}
1218 func (me *memSegment) flushingUnfinished() bool {
1219 if me.flushing == nil {
1231 func (me *memSegment) Len() int {
1235 func (me *memSegment) Slice(off, length int) segment {
1237 length = len(me.buf) - off
1239 buf := make([]byte, length)
1240 copy(buf, me.buf[off:])
1241 return &memSegment{buf: buf}
1244 func (me *memSegment) Truncate(n int) {
1245 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1248 newsize = newsize << 2
1250 newbuf := make([]byte, n, newsize)
1251 copy(newbuf, me.buf)
1252 me.buf, me.flushing = newbuf, nil
1254 // reclaim existing capacity, and zero reclaimed part
1255 oldlen := len(me.buf)
1257 for i := oldlen; i < n; i++ {
1263 func (me *memSegment) WriteAt(p []byte, off int) {
1264 if off+len(p) > len(me.buf) {
1265 panic("overflowed segment")
1267 if me.flushing != nil {
1268 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1270 copy(me.buf[off:], p)
1273 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1274 if off > int64(me.Len()) {
1278 n = copy(p, me.buf[int(off):])
1285 type storedSegment struct {
1288 size int // size of stored block (also encoded in locator)
1289 offset int // position of segment within the stored block
1290 length int // bytes in this segment (offset + length <= size)
1293 func (se storedSegment) Len() int {
1297 func (se storedSegment) Slice(n, size int) segment {
1300 if size >= 0 && se.length > size {
1306 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1307 if off > int64(se.length) {
1310 maxlen := se.length - int(off)
1311 if len(p) > maxlen {
1313 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1319 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1322 func canonicalName(name string) string {
1323 name = path.Clean("/" + name)
1324 if name == "/" || name == "./" {
1326 } else if strings.HasPrefix(name, "/") {
1332 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1334 func manifestUnescapeFunc(seq string) string {
1338 i, err := strconv.ParseUint(seq[1:], 8, 8)
1340 // Invalid escape sequence: can't unescape.
1343 return string([]byte{byte(i)})
1346 func manifestUnescape(s string) string {
1347 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1350 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1352 func manifestEscapeFunc(seq string) string {
1353 return fmt.Sprintf("\\%03o", byte(seq[0]))
1356 func manifestEscape(s string) string {
1357 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)